Files
Compose-Files/Backups/Miker/.obsidian/plugins/mcp-tools-istefox/main.js
T
2026-07-20 09:23:17 -04:00

4988 lines
2.4 MiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY BUN
if you want to view the source, please visit https://github.com/istefox/obsidian-mcp-connector
*/
var qk0=Object.create;var{getPrototypeOf:Uk0,defineProperty:Gq,getOwnPropertyNames:hJ0,getOwnPropertyDescriptor:$k0}=Object,_J0=Object.prototype.hasOwnProperty;function fJ0(Q){return this[Q]}var Zk0,Fk0,K7=(Q,J,G)=>{var H=Q!=null&&typeof Q==="object";if(H){var K=J?Zk0??=new WeakMap:Fk0??=new WeakMap,z=K.get(Q);if(z)return z}G=Q!=null?qk0(Uk0(Q)):{};let q=J||!Q||!Q.__esModule?Gq(G,"default",{value:Q,enumerable:!0}):G;for(let F of hJ0(Q))if(!_J0.call(q,F))Gq(q,F,{get:fJ0.bind(Q,F),enumerable:!0});if(H)K.set(Q,q);return q},Dk0=(Q)=>{var J=(gJ0??=new WeakMap).get(Q),G;if(J)return J;if(J=Gq({},"__esModule",{value:!0}),Q&&typeof Q==="object"||typeof Q==="function"){for(var H of hJ0(Q))if(!_J0.call(J,H))Gq(J,H,{get:fJ0.bind(Q,H),enumerable:!(G=$k0(Q,H))||G.enumerable})}return gJ0.set(Q,J),J},gJ0,i=(Q,J)=>()=>(J||Q((J={exports:{}}).exports,J),J.exports);var Mk0=(Q)=>Q;function Lk0(Q,J){this[Q]=Mk0.bind(null,J)}var UD=(Q,J)=>{for(var G in J)Gq(Q,G,{get:J[G],enumerable:!0,configurable:!0,set:Lk0.bind(J,G)})};var e6=i(($D)=>{Object.defineProperty($D,"__esModule",{value:!0});$D.isFunction=void 0;function Ok0(Q){return typeof Q==="function"}$D.isFunction=Ok0});var d5=i((ZD)=>{Object.defineProperty(ZD,"__esModule",{value:!0});ZD.createErrorClass=void 0;function Pk0(Q){var J=function(H){Error.call(H),H.stack=Error().stack},G=Q(J);return G.prototype=Object.create(Error.prototype),G.prototype.constructor=G,G}ZD.createErrorClass=Pk0});var gw=i((FD)=>{Object.defineProperty(FD,"__esModule",{value:!0});FD.UnsubscriptionError=void 0;var Nk0=d5();FD.UnsubscriptionError=Nk0.createErrorClass(function(Q){return function(G){Q(this),this.message=G?G.length+` errors occurred during unsubscription:
`+G.map(function(H,K){return K+1+") "+H.toString()}).join(`
`):"",this.name="UnsubscriptionError",this.errors=G}})});var dW=i((DD)=>{Object.defineProperty(DD,"__esModule",{value:!0});DD.arrRemove=void 0;function jk0(Q,J){if(Q){var G=Q.indexOf(J);0<=G&&Q.splice(G,1)}}DD.arrRemove=jk0});var rJ=i((CJ)=>{var mJ0=CJ&&CJ.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")},uJ0=CJ&&CJ.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},pJ0=CJ&&CJ.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(CJ,"__esModule",{value:!0});CJ.isSubscription=CJ.EMPTY_SUBSCRIPTION=CJ.Subscription=void 0;var Wq=e6(),hw=gw(),lJ0=dW(),_w=function(){function Q(J){this.initialTeardown=J,this.closed=!1,this._parentage=null,this._finalizers=null}return Q.prototype.unsubscribe=function(){var J,G,H,K,z;if(!this.closed){this.closed=!0;var q=this._parentage;if(q)if(this._parentage=null,Array.isArray(q))try{for(var F=mJ0(q),D=F.next();!D.done;D=F.next()){var V=D.value;V.remove(this)}}catch(w){J={error:w}}finally{try{if(D&&!D.done&&(G=F.return))G.call(F)}finally{if(J)throw J.error}}else q.remove(this);var O=this.initialTeardown;if(Wq.isFunction(O))try{O()}catch(w){z=w instanceof hw.UnsubscriptionError?w.errors:[w]}var P=this._finalizers;if(P){this._finalizers=null;try{for(var N=mJ0(P),I=N.next();!I.done;I=N.next()){var R=I.value;try{dJ0(R)}catch(w){if(z=z!==null&&z!==void 0?z:[],w instanceof hw.UnsubscriptionError)z=pJ0(pJ0([],uJ0(z)),uJ0(w.errors));else z.push(w)}}}catch(w){H={error:w}}finally{try{if(I&&!I.done&&(K=N.return))K.call(N)}finally{if(H)throw H.error}}}if(z)throw new hw.UnsubscriptionError(z)}},Q.prototype.add=function(J){var G;if(J&&J!==this)if(this.closed)dJ0(J);else{if(J instanceof Q){if(J.closed||J._hasParent(this))return;J._addParent(this)}(this._finalizers=(G=this._finalizers)!==null&&G!==void 0?G:[]).push(J)}},Q.prototype._hasParent=function(J){var G=this._parentage;return G===J||Array.isArray(G)&&G.includes(J)},Q.prototype._addParent=function(J){var G=this._parentage;this._parentage=Array.isArray(G)?(G.push(J),G):G?[G,J]:J},Q.prototype._removeParent=function(J){var G=this._parentage;if(G===J)this._parentage=null;else if(Array.isArray(G))lJ0.arrRemove(G,J)},Q.prototype.remove=function(J){var G=this._finalizers;if(G&&lJ0.arrRemove(G,J),J instanceof Q)J._removeParent(this)},Q.EMPTY=function(){var J=new Q;return J.closed=!0,J}(),Q}();CJ.Subscription=_w;CJ.EMPTY_SUBSCRIPTION=_w.EMPTY;function Ck0(Q){return Q instanceof _w||Q&&"closed"in Q&&Wq.isFunction(Q.remove)&&Wq.isFunction(Q.add)&&Wq.isFunction(Q.unsubscribe)}CJ.isSubscription=Ck0;function dJ0(Q){if(Wq.isFunction(Q))Q();else Q.unsubscribe()}});var yB=i((MD)=>{Object.defineProperty(MD,"__esModule",{value:!0});MD.config=void 0;MD.config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1}});var fw=i((nG)=>{var cJ0=nG&&nG.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},iJ0=nG&&nG.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(nG,"__esModule",{value:!0});nG.timeoutProvider=void 0;nG.timeoutProvider={setTimeout:function(Q,J){var G=[];for(var H=2;H<arguments.length;H++)G[H-2]=arguments[H];var K=nG.timeoutProvider.delegate;if(K===null||K===void 0?void 0:K.setTimeout)return K.setTimeout.apply(K,iJ0([Q,J],cJ0(G)));return setTimeout.apply(void 0,iJ0([Q,J],cJ0(G)))},clearTimeout:function(Q){var J=nG.timeoutProvider.delegate;return((J===null||J===void 0?void 0:J.clearTimeout)||clearTimeout)(Q)},delegate:void 0}});var mw=i((LD)=>{Object.defineProperty(LD,"__esModule",{value:!0});LD.reportUnhandledError=void 0;var Ik0=yB(),Rk0=fw();function wk0(Q){Rk0.timeoutProvider.setTimeout(function(){var J=Ik0.config.onUnhandledError;if(J)J(Q);else throw Q})}LD.reportUnhandledError=wk0});var GX=i((OD)=>{Object.defineProperty(OD,"__esModule",{value:!0});OD.noop=void 0;function Ek0(){}OD.noop=Ek0});var oJ0=i((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});aG.createNotification=aG.nextNotification=aG.errorNotification=aG.COMPLETE_NOTIFICATION=void 0;aG.COMPLETE_NOTIFICATION=function(){return PD("C",void 0,void 0)}();function Sk0(Q){return PD("E",void 0,Q)}aG.errorNotification=Sk0;function Tk0(Q){return PD("N",Q,void 0)}aG.nextNotification=Tk0;function PD(Q,J,G){return{kind:Q,value:J,error:G}}aG.createNotification=PD});var ND=i((vB)=>{Object.defineProperty(vB,"__esModule",{value:!0});vB.captureError=vB.errorContext=void 0;var nJ0=yB(),EH=null;function kk0(Q){if(nJ0.config.useDeprecatedSynchronousErrorHandling){var J=!EH;if(J)EH={errorThrown:!1,error:null};if(Q(),J){var G=EH,H=G.errorThrown,K=G.error;if(EH=null,H)throw K}}else Q()}vB.errorContext=kk0;function yk0(Q){if(nJ0.config.useDeprecatedSynchronousErrorHandling&&EH)EH.errorThrown=!0,EH.error=Q}vB.captureError=yk0});var xB=i((XG)=>{var rJ0=XG&&XG.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(XG,"__esModule",{value:!0});XG.EMPTY_OBSERVER=XG.SafeSubscriber=XG.Subscriber=void 0;var vk0=e6(),aJ0=rJ(),dw=yB(),xk0=mw(),sJ0=GX(),uw=oJ0(),bk0=fw(),gk0=ND(),tJ0=function(Q){rJ0(J,Q);function J(G){var H=Q.call(this)||this;if(H.isStopped=!1,G){if(H.destination=G,aJ0.isSubscription(G))G.add(H)}else H.destination=XG.EMPTY_OBSERVER;return H}return J.create=function(G,H,K){return new eJ0(G,H,K)},J.prototype.next=function(G){if(this.isStopped)lw(uw.nextNotification(G),this);else this._next(G)},J.prototype.error=function(G){if(this.isStopped)lw(uw.errorNotification(G),this);else this.isStopped=!0,this._error(G)},J.prototype.complete=function(){if(this.isStopped)lw(uw.COMPLETE_NOTIFICATION,this);else this.isStopped=!0,this._complete()},J.prototype.unsubscribe=function(){if(!this.closed)this.isStopped=!0,Q.prototype.unsubscribe.call(this),this.destination=null},J.prototype._next=function(G){this.destination.next(G)},J.prototype._error=function(G){try{this.destination.error(G)}finally{this.unsubscribe()}},J.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},J}(aJ0.Subscription);XG.Subscriber=tJ0;var hk0=Function.prototype.bind;function pw(Q,J){return hk0.call(Q,J)}var _k0=function(){function Q(J){this.partialObserver=J}return Q.prototype.next=function(J){var G=this.partialObserver;if(G.next)try{G.next(J)}catch(H){jD(H)}},Q.prototype.error=function(J){var G=this.partialObserver;if(G.error)try{G.error(J)}catch(H){jD(H)}else jD(J)},Q.prototype.complete=function(){var J=this.partialObserver;if(J.complete)try{J.complete()}catch(G){jD(G)}},Q}(),eJ0=function(Q){rJ0(J,Q);function J(G,H,K){var z=Q.call(this)||this,q;if(vk0.isFunction(G)||!G)q={next:G!==null&&G!==void 0?G:void 0,error:H!==null&&H!==void 0?H:void 0,complete:K!==null&&K!==void 0?K:void 0};else{var F;if(z&&dw.config.useDeprecatedNextContext)F=Object.create(G),F.unsubscribe=function(){return z.unsubscribe()},q={next:G.next&&pw(G.next,F),error:G.error&&pw(G.error,F),complete:G.complete&&pw(G.complete,F)};else q=G}return z.destination=new _k0(q),z}return J}(tJ0);XG.SafeSubscriber=eJ0;function jD(Q){if(dw.config.useDeprecatedSynchronousErrorHandling)gk0.captureError(Q);else xk0.reportUnhandledError(Q)}function fk0(Q){throw Q}function lw(Q,J){var G=dw.config.onStoppedNotification;G&&bk0.timeoutProvider.setTimeout(function(){return G(Q,J)})}XG.EMPTY_OBSERVER={closed:!0,next:sJ0.noop,error:fk0,complete:sJ0.noop}});var Hq=i((CD)=>{Object.defineProperty(CD,"__esModule",{value:!0});CD.observable=void 0;CD.observable=function(){return typeof Symbol==="function"&&Symbol.observable||"@@observable"}()});var WX=i((ID)=>{Object.defineProperty(ID,"__esModule",{value:!0});ID.identity=void 0;function mk0(Q){return Q}ID.identity=mk0});var Bq=i((bB)=>{Object.defineProperty(bB,"__esModule",{value:!0});bB.pipeFromArray=bB.pipe=void 0;var uk0=WX();function pk0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return QY0(Q)}bB.pipe=pk0;function QY0(Q){if(Q.length===0)return uk0.identity;if(Q.length===1)return Q[0];return function(G){return Q.reduce(function(H,K){return K(H)},G)}}bB.pipeFromArray=QY0});var H9=i((RD)=>{Object.defineProperty(RD,"__esModule",{value:!0});RD.Observable=void 0;var iw=xB(),lk0=rJ(),dk0=Hq(),ck0=Bq(),ik0=yB(),cw=e6(),ok0=ND(),nk0=function(){function Q(J){if(J)this._subscribe=J}return Q.prototype.lift=function(J){var G=new Q;return G.source=this,G.operator=J,G},Q.prototype.subscribe=function(J,G,H){var K=this,z=sk0(J)?J:new iw.SafeSubscriber(J,G,H);return ok0.errorContext(function(){var q=K,F=q.operator,D=q.source;z.add(F?F.call(z,D):D?K._subscribe(z):K._trySubscribe(z))}),z},Q.prototype._trySubscribe=function(J){try{return this._subscribe(J)}catch(G){J.error(G)}},Q.prototype.forEach=function(J,G){var H=this;return G=XY0(G),new G(function(K,z){var q=new iw.SafeSubscriber({next:function(F){try{J(F)}catch(D){z(D),q.unsubscribe()}},error:z,complete:K});H.subscribe(q)})},Q.prototype._subscribe=function(J){var G;return(G=this.source)===null||G===void 0?void 0:G.subscribe(J)},Q.prototype[dk0.observable]=function(){return this},Q.prototype.pipe=function(){var J=[];for(var G=0;G<arguments.length;G++)J[G]=arguments[G];return ck0.pipeFromArray(J)(this)},Q.prototype.toPromise=function(J){var G=this;return J=XY0(J),new J(function(H,K){var z;G.subscribe(function(q){return z=q},function(q){return K(q)},function(){return H(z)})})},Q.create=function(J){return new Q(J)},Q}();RD.Observable=nk0;function XY0(Q){var J;return(J=Q!==null&&Q!==void 0?Q:ik0.config.Promise)!==null&&J!==void 0?J:Promise}function ak0(Q){return Q&&cw.isFunction(Q.next)&&cw.isFunction(Q.error)&&cw.isFunction(Q.complete)}function sk0(Q){return Q&&Q instanceof iw.Subscriber||ak0(Q)&&lk0.isSubscription(Q)}});var uQ=i((gB)=>{Object.defineProperty(gB,"__esModule",{value:!0});gB.operate=gB.hasLift=void 0;var rk0=e6();function JY0(Q){return rk0.isFunction(Q===null||Q===void 0?void 0:Q.lift)}gB.hasLift=JY0;function tk0(Q){return function(J){if(JY0(J))return J.lift(function(G){try{return Q(G,this)}catch(H){this.error(H)}});throw TypeError("Unable to lift unknown Observable type")}}gB.operate=tk0});var Y8=i((c5)=>{var ek0=c5&&c5.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(c5,"__esModule",{value:!0});c5.OperatorSubscriber=c5.createOperatorSubscriber=void 0;var Qy0=xB();function Xy0(Q,J,G,H,K){return new YY0(Q,J,G,H,K)}c5.createOperatorSubscriber=Xy0;var YY0=function(Q){ek0(J,Q);function J(G,H,K,z,q,F){var D=Q.call(this,G)||this;return D.onFinalize=q,D.shouldUnsubscribe=F,D._next=H?function(V){try{H(V)}catch(O){G.error(O)}}:Q.prototype._next,D._error=z?function(V){try{z(V)}catch(O){G.error(O)}finally{this.unsubscribe()}}:Q.prototype._error,D._complete=K?function(){try{K()}catch(V){G.error(V)}finally{this.unsubscribe()}}:Q.prototype._complete,D}return J.prototype.unsubscribe=function(){var G;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var H=this.closed;Q.prototype.unsubscribe.call(this),!H&&((G=this.onFinalize)===null||G===void 0||G.call(this))}},J}(Qy0.Subscriber);c5.OperatorSubscriber=YY0});var ow=i((wD)=>{Object.defineProperty(wD,"__esModule",{value:!0});wD.refCount=void 0;var Jy0=uQ(),Yy0=Y8();function Gy0(){return Jy0.operate(function(Q,J){var G=null;Q._refCount++;var H=Yy0.createOperatorSubscriber(J,void 0,void 0,void 0,function(){if(!Q||Q._refCount<=0||0<--Q._refCount){G=null;return}var K=Q._connection,z=G;if(G=null,K&&(!z||K===z))K.unsubscribe();J.unsubscribe()});if(Q.subscribe(H),!H.closed)G=Q.connect()})}wD.refCount=Gy0});var Aq=i((hB)=>{var Wy0=hB&&hB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(hB,"__esModule",{value:!0});hB.ConnectableObservable=void 0;var Hy0=H9(),GY0=rJ(),By0=ow(),Ay0=Y8(),Ky0=uQ(),zy0=function(Q){Wy0(J,Q);function J(G,H){var K=Q.call(this)||this;if(K.source=G,K.subjectFactory=H,K._subject=null,K._refCount=0,K._connection=null,Ky0.hasLift(G))K.lift=G.lift;return K}return J.prototype._subscribe=function(G){return this.getSubject().subscribe(G)},J.prototype.getSubject=function(){var G=this._subject;if(!G||G.isStopped)this._subject=this.subjectFactory();return this._subject},J.prototype._teardown=function(){this._refCount=0;var G=this._connection;this._subject=this._connection=null,G===null||G===void 0||G.unsubscribe()},J.prototype.connect=function(){var G=this,H=this._connection;if(!H){H=this._connection=new GY0.Subscription;var K=this.getSubject();if(H.add(this.source.subscribe(Ay0.createOperatorSubscriber(K,void 0,function(){G._teardown(),K.complete()},function(z){G._teardown(),K.error(z)},function(){return G._teardown()}))),H.closed)this._connection=null,H=GY0.Subscription.EMPTY}return H},J.prototype.refCount=function(){return By0.refCount()(this)},J}(Hy0.Observable);hB.ConnectableObservable=zy0});var WY0=i((Kq)=>{Object.defineProperty(Kq,"__esModule",{value:!0});Kq.performanceTimestampProvider=void 0;Kq.performanceTimestampProvider={now:function(){return(Kq.performanceTimestampProvider.delegate||performance).now()},delegate:void 0}});var nw=i((JG)=>{var HY0=JG&&JG.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},BY0=JG&&JG.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(JG,"__esModule",{value:!0});JG.animationFrameProvider=void 0;var Vy0=rJ();JG.animationFrameProvider={schedule:function(Q){var J=requestAnimationFrame,G=cancelAnimationFrame,H=JG.animationFrameProvider.delegate;if(H)J=H.requestAnimationFrame,G=H.cancelAnimationFrame;var K=J(function(z){G=void 0,Q(z)});return new Vy0.Subscription(function(){return G===null||G===void 0?void 0:G(K)})},requestAnimationFrame:function(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=JG.animationFrameProvider.delegate;return((G===null||G===void 0?void 0:G.requestAnimationFrame)||requestAnimationFrame).apply(void 0,BY0([],HY0(Q)))},cancelAnimationFrame:function(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=JG.animationFrameProvider.delegate;return((G===null||G===void 0?void 0:G.cancelAnimationFrame)||cancelAnimationFrame).apply(void 0,BY0([],HY0(Q)))},delegate:void 0}});var zY0=i((ED)=>{Object.defineProperty(ED,"__esModule",{value:!0});ED.animationFrames=void 0;var qy0=H9(),Uy0=WY0(),AY0=nw();function $y0(Q){return Q?KY0(Q):Zy0}ED.animationFrames=$y0;function KY0(Q){return new qy0.Observable(function(J){var G=Q||Uy0.performanceTimestampProvider,H=G.now(),K=0,z=function(){if(!J.closed)K=AY0.animationFrameProvider.requestAnimationFrame(function(q){K=0;var F=G.now();J.next({timestamp:Q?F:q,elapsed:F-H}),z()})};return z(),function(){if(K)AY0.animationFrameProvider.cancelAnimationFrame(K)}})}var Zy0=KY0()});var aw=i((SD)=>{Object.defineProperty(SD,"__esModule",{value:!0});SD.ObjectUnsubscribedError=void 0;var Fy0=d5();SD.ObjectUnsubscribedError=Fy0.createErrorClass(function(Q){return function(){Q(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})});var HX=i((sG)=>{var qY0=sG&&sG.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}(),Dy0=sG&&sG.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(sG,"__esModule",{value:!0});sG.AnonymousSubject=sG.Subject=void 0;var VY0=H9(),rw=rJ(),My0=aw(),Ly0=dW(),sw=ND(),UY0=function(Q){qY0(J,Q);function J(){var G=Q.call(this)||this;return G.closed=!1,G.currentObservers=null,G.observers=[],G.isStopped=!1,G.hasError=!1,G.thrownError=null,G}return J.prototype.lift=function(G){var H=new tw(this,this);return H.operator=G,H},J.prototype._throwIfClosed=function(){if(this.closed)throw new My0.ObjectUnsubscribedError},J.prototype.next=function(G){var H=this;sw.errorContext(function(){var K,z;if(H._throwIfClosed(),!H.isStopped){if(!H.currentObservers)H.currentObservers=Array.from(H.observers);try{for(var q=Dy0(H.currentObservers),F=q.next();!F.done;F=q.next()){var D=F.value;D.next(G)}}catch(V){K={error:V}}finally{try{if(F&&!F.done&&(z=q.return))z.call(q)}finally{if(K)throw K.error}}}})},J.prototype.error=function(G){var H=this;sw.errorContext(function(){if(H._throwIfClosed(),!H.isStopped){H.hasError=H.isStopped=!0,H.thrownError=G;var K=H.observers;while(K.length)K.shift().error(G)}})},J.prototype.complete=function(){var G=this;sw.errorContext(function(){if(G._throwIfClosed(),!G.isStopped){G.isStopped=!0;var H=G.observers;while(H.length)H.shift().complete()}})},J.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(J.prototype,"observed",{get:function(){var G;return((G=this.observers)===null||G===void 0?void 0:G.length)>0},enumerable:!1,configurable:!0}),J.prototype._trySubscribe=function(G){return this._throwIfClosed(),Q.prototype._trySubscribe.call(this,G)},J.prototype._subscribe=function(G){return this._throwIfClosed(),this._checkFinalizedStatuses(G),this._innerSubscribe(G)},J.prototype._innerSubscribe=function(G){var H=this,K=this,z=K.hasError,q=K.isStopped,F=K.observers;if(z||q)return rw.EMPTY_SUBSCRIPTION;return this.currentObservers=null,F.push(G),new rw.Subscription(function(){H.currentObservers=null,Ly0.arrRemove(F,G)})},J.prototype._checkFinalizedStatuses=function(G){var H=this,K=H.hasError,z=H.thrownError,q=H.isStopped;if(K)G.error(z);else if(q)G.complete()},J.prototype.asObservable=function(){var G=new VY0.Observable;return G.source=this,G},J.create=function(G,H){return new tw(G,H)},J}(VY0.Observable);sG.Subject=UY0;var tw=function(Q){qY0(J,Q);function J(G,H){var K=Q.call(this)||this;return K.destination=G,K.source=H,K}return J.prototype.next=function(G){var H,K;(K=(H=this.destination)===null||H===void 0?void 0:H.next)===null||K===void 0||K.call(H,G)},J.prototype.error=function(G){var H,K;(K=(H=this.destination)===null||H===void 0?void 0:H.error)===null||K===void 0||K.call(H,G)},J.prototype.complete=function(){var G,H;(H=(G=this.destination)===null||G===void 0?void 0:G.complete)===null||H===void 0||H.call(G)},J.prototype._subscribe=function(G){var H,K;return(K=(H=this.source)===null||H===void 0?void 0:H.subscribe(G))!==null&&K!==void 0?K:rw.EMPTY_SUBSCRIPTION},J}(UY0);sG.AnonymousSubject=tw});var ew=i((_B)=>{var Oy0=_B&&_B.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(_B,"__esModule",{value:!0});_B.BehaviorSubject=void 0;var Py0=HX(),Ny0=function(Q){Oy0(J,Q);function J(G){var H=Q.call(this)||this;return H._value=G,H}return Object.defineProperty(J.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),J.prototype._subscribe=function(G){var H=Q.prototype._subscribe.call(this,G);return!H.closed&&G.next(this._value),H},J.prototype.getValue=function(){var G=this,H=G.hasError,K=G.thrownError,z=G._value;if(H)throw K;return this._throwIfClosed(),z},J.prototype.next=function(G){Q.prototype.next.call(this,this._value=G)},J}(Py0.Subject);_B.BehaviorSubject=Ny0});var TD=i((zq)=>{Object.defineProperty(zq,"__esModule",{value:!0});zq.dateTimestampProvider=void 0;zq.dateTimestampProvider={now:function(){return(zq.dateTimestampProvider.delegate||Date).now()},delegate:void 0}});var kD=i((fB)=>{var jy0=fB&&fB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(fB,"__esModule",{value:!0});fB.ReplaySubject=void 0;var Cy0=HX(),Iy0=TD(),Ry0=function(Q){jy0(J,Q);function J(G,H,K){if(G===void 0)G=1/0;if(H===void 0)H=1/0;if(K===void 0)K=Iy0.dateTimestampProvider;var z=Q.call(this)||this;return z._bufferSize=G,z._windowTime=H,z._timestampProvider=K,z._buffer=[],z._infiniteTimeWindow=!0,z._infiniteTimeWindow=H===1/0,z._bufferSize=Math.max(1,G),z._windowTime=Math.max(1,H),z}return J.prototype.next=function(G){var H=this,K=H.isStopped,z=H._buffer,q=H._infiniteTimeWindow,F=H._timestampProvider,D=H._windowTime;if(!K)z.push(G),!q&&z.push(F.now()+D);this._trimBuffer(),Q.prototype.next.call(this,G)},J.prototype._subscribe=function(G){this._throwIfClosed(),this._trimBuffer();var H=this._innerSubscribe(G),K=this,z=K._infiniteTimeWindow,q=K._buffer,F=q.slice();for(var D=0;D<F.length&&!G.closed;D+=z?1:2)G.next(F[D]);return this._checkFinalizedStatuses(G),H},J.prototype._trimBuffer=function(){var G=this,H=G._bufferSize,K=G._timestampProvider,z=G._buffer,q=G._infiniteTimeWindow,F=(q?1:2)*H;if(H<1/0&&F<z.length&&z.splice(0,z.length-F),!q){var D=K.now(),V=0;for(var O=1;O<z.length&&z[O]<=D;O+=2)V=O;V&&z.splice(0,V+1)}},J}(Cy0.Subject);fB.ReplaySubject=Ry0});var yD=i((mB)=>{var wy0=mB&&mB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(mB,"__esModule",{value:!0});mB.AsyncSubject=void 0;var Ey0=HX(),Sy0=function(Q){wy0(J,Q);function J(){var G=Q!==null&&Q.apply(this,arguments)||this;return G._value=null,G._hasValue=!1,G._isComplete=!1,G}return J.prototype._checkFinalizedStatuses=function(G){var H=this,K=H.hasError,z=H._hasValue,q=H._value,F=H.thrownError,D=H.isStopped,V=H._isComplete;if(K)G.error(F);else if(D||V)z&&G.next(q),G.complete()},J.prototype.next=function(G){if(!this.isStopped)this._value=G,this._hasValue=!0},J.prototype.complete=function(){var G=this,H=G._hasValue,K=G._value,z=G._isComplete;if(!z)this._isComplete=!0,H&&Q.prototype.next.call(this,K),Q.prototype.complete.call(this)},J}(Ey0.Subject);mB.AsyncSubject=Sy0});var $Y0=i((uB)=>{var Ty0=uB&&uB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(uB,"__esModule",{value:!0});uB.Action=void 0;var ky0=rJ(),yy0=function(Q){Ty0(J,Q);function J(G,H){return Q.call(this)||this}return J.prototype.schedule=function(G,H){if(H===void 0)H=0;return this},J}(ky0.Subscription);uB.Action=yy0});var DY0=i((rG)=>{var ZY0=rG&&rG.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},FY0=rG&&rG.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(rG,"__esModule",{value:!0});rG.intervalProvider=void 0;rG.intervalProvider={setInterval:function(Q,J){var G=[];for(var H=2;H<arguments.length;H++)G[H-2]=arguments[H];var K=rG.intervalProvider.delegate;if(K===null||K===void 0?void 0:K.setInterval)return K.setInterval.apply(K,FY0([Q,J],ZY0(G)));return setInterval.apply(void 0,FY0([Q,J],ZY0(G)))},clearInterval:function(Q){var J=rG.intervalProvider.delegate;return((J===null||J===void 0?void 0:J.clearInterval)||clearInterval)(Q)},delegate:void 0}});var lB=i((pB)=>{var vy0=pB&&pB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(pB,"__esModule",{value:!0});pB.AsyncAction=void 0;var xy0=$Y0(),MY0=DY0(),by0=dW(),gy0=function(Q){vy0(J,Q);function J(G,H){var K=Q.call(this,G,H)||this;return K.scheduler=G,K.work=H,K.pending=!1,K}return J.prototype.schedule=function(G,H){var K;if(H===void 0)H=0;if(this.closed)return this;this.state=G;var z=this.id,q=this.scheduler;if(z!=null)this.id=this.recycleAsyncId(q,z,H);return this.pending=!0,this.delay=H,this.id=(K=this.id)!==null&&K!==void 0?K:this.requestAsyncId(q,this.id,H),this},J.prototype.requestAsyncId=function(G,H,K){if(K===void 0)K=0;return MY0.intervalProvider.setInterval(G.flush.bind(G,this),K)},J.prototype.recycleAsyncId=function(G,H,K){if(K===void 0)K=0;if(K!=null&&this.delay===K&&this.pending===!1)return H;if(H!=null)MY0.intervalProvider.clearInterval(H);return},J.prototype.execute=function(G,H){if(this.closed)return Error("executing a cancelled action");this.pending=!1;var K=this._execute(G,H);if(K)return K;else if(this.pending===!1&&this.id!=null)this.id=this.recycleAsyncId(this.scheduler,this.id,null)},J.prototype._execute=function(G,H){var K=!1,z;try{this.work(G)}catch(q){K=!0,z=q?q:Error("Scheduled action threw falsy error")}if(K)return this.unsubscribe(),z},J.prototype.unsubscribe=function(){if(!this.closed){var G=this,H=G.id,K=G.scheduler,z=K.actions;if(this.work=this.state=this.scheduler=null,this.pending=!1,by0.arrRemove(z,this),H!=null)this.id=this.recycleAsyncId(K,H,null);this.delay=null,Q.prototype.unsubscribe.call(this)}},J}(xy0.Action);pB.AsyncAction=gy0});var OY0=i((dB)=>{Object.defineProperty(dB,"__esModule",{value:!0});dB.TestTools=dB.Immediate=void 0;var hy0=1,QE,vD={};function LY0(Q){if(Q in vD)return delete vD[Q],!0;return!1}dB.Immediate={setImmediate:function(Q){var J=hy0++;if(vD[J]=!0,!QE)QE=Promise.resolve();return QE.then(function(){return LY0(J)&&Q()}),J},clearImmediate:function(Q){LY0(Q)}};dB.TestTools={pending:function(){return Object.keys(vD).length}}});var NY0=i((tG)=>{var _y0=tG&&tG.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},fy0=tG&&tG.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(tG,"__esModule",{value:!0});tG.immediateProvider=void 0;var PY0=OY0(),my0=PY0.Immediate.setImmediate,uy0=PY0.Immediate.clearImmediate;tG.immediateProvider={setImmediate:function(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=tG.immediateProvider.delegate;return((G===null||G===void 0?void 0:G.setImmediate)||my0).apply(void 0,fy0([],_y0(Q)))},clearImmediate:function(Q){var J=tG.immediateProvider.delegate;return((J===null||J===void 0?void 0:J.clearImmediate)||uy0)(Q)},delegate:void 0}});var CY0=i((cB)=>{var py0=cB&&cB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(cB,"__esModule",{value:!0});cB.AsapAction=void 0;var ly0=lB(),jY0=NY0(),dy0=function(Q){py0(J,Q);function J(G,H){var K=Q.call(this,G,H)||this;return K.scheduler=G,K.work=H,K}return J.prototype.requestAsyncId=function(G,H,K){if(K===void 0)K=0;if(K!==null&&K>0)return Q.prototype.requestAsyncId.call(this,G,H,K);return G.actions.push(this),G._scheduled||(G._scheduled=jY0.immediateProvider.setImmediate(G.flush.bind(G,void 0)))},J.prototype.recycleAsyncId=function(G,H,K){var z;if(K===void 0)K=0;if(K!=null?K>0:this.delay>0)return Q.prototype.recycleAsyncId.call(this,G,H,K);var q=G.actions;if(H!=null&&((z=q[q.length-1])===null||z===void 0?void 0:z.id)!==H){if(jY0.immediateProvider.clearImmediate(H),G._scheduled===H)G._scheduled=void 0}return},J}(ly0.AsyncAction);cB.AsapAction=dy0});var XE=i((xD)=>{Object.defineProperty(xD,"__esModule",{value:!0});xD.Scheduler=void 0;var cy0=TD(),iy0=function(){function Q(J,G){if(G===void 0)G=Q.now;this.schedulerActionCtor=J,this.now=G}return Q.prototype.schedule=function(J,G,H){if(G===void 0)G=0;return new this.schedulerActionCtor(this,J).schedule(H,G)},Q.now=cy0.dateTimestampProvider.now,Q}();xD.Scheduler=iy0});var oB=i((iB)=>{var oy0=iB&&iB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(iB,"__esModule",{value:!0});iB.AsyncScheduler=void 0;var IY0=XE(),ny0=function(Q){oy0(J,Q);function J(G,H){if(H===void 0)H=IY0.Scheduler.now;var K=Q.call(this,G,H)||this;return K.actions=[],K._active=!1,K}return J.prototype.flush=function(G){var H=this.actions;if(this._active){H.push(G);return}var K;this._active=!0;do if(K=G.execute(G.state,G.delay))break;while(G=H.shift());if(this._active=!1,K){while(G=H.shift())G.unsubscribe();throw K}},J}(IY0.Scheduler);iB.AsyncScheduler=ny0});var RY0=i((nB)=>{var ay0=nB&&nB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(nB,"__esModule",{value:!0});nB.AsapScheduler=void 0;var sy0=oB(),ry0=function(Q){ay0(J,Q);function J(){return Q!==null&&Q.apply(this,arguments)||this}return J.prototype.flush=function(G){this._active=!0;var H=this._scheduled;this._scheduled=void 0;var K=this.actions,z;G=G||K.shift();do if(z=G.execute(G.state,G.delay))break;while((G=K[0])&&G.id===H&&K.shift());if(this._active=!1,z){while((G=K[0])&&G.id===H&&K.shift())G.unsubscribe();throw z}},J}(sy0.AsyncScheduler);nB.AsapScheduler=ry0});var wY0=i((SH)=>{Object.defineProperty(SH,"__esModule",{value:!0});SH.asap=SH.asapScheduler=void 0;var ty0=CY0(),ey0=RY0();SH.asapScheduler=new ey0.AsapScheduler(ty0.AsapAction);SH.asap=SH.asapScheduler});var IJ=i((TH)=>{Object.defineProperty(TH,"__esModule",{value:!0});TH.async=TH.asyncScheduler=void 0;var Qv0=lB(),Xv0=oB();TH.asyncScheduler=new Xv0.AsyncScheduler(Qv0.AsyncAction);TH.async=TH.asyncScheduler});var EY0=i((aB)=>{var Jv0=aB&&aB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(aB,"__esModule",{value:!0});aB.QueueAction=void 0;var Yv0=lB(),Gv0=function(Q){Jv0(J,Q);function J(G,H){var K=Q.call(this,G,H)||this;return K.scheduler=G,K.work=H,K}return J.prototype.schedule=function(G,H){if(H===void 0)H=0;if(H>0)return Q.prototype.schedule.call(this,G,H);return this.delay=H,this.state=G,this.scheduler.flush(this),this},J.prototype.execute=function(G,H){return H>0||this.closed?Q.prototype.execute.call(this,G,H):this._execute(G,H)},J.prototype.requestAsyncId=function(G,H,K){if(K===void 0)K=0;if(K!=null&&K>0||K==null&&this.delay>0)return Q.prototype.requestAsyncId.call(this,G,H,K);return G.flush(this),0},J}(Yv0.AsyncAction);aB.QueueAction=Gv0});var SY0=i((sB)=>{var Wv0=sB&&sB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(sB,"__esModule",{value:!0});sB.QueueScheduler=void 0;var Hv0=oB(),Bv0=function(Q){Wv0(J,Q);function J(){return Q!==null&&Q.apply(this,arguments)||this}return J}(Hv0.AsyncScheduler);sB.QueueScheduler=Bv0});var TY0=i((kH)=>{Object.defineProperty(kH,"__esModule",{value:!0});kH.queue=kH.queueScheduler=void 0;var Av0=EY0(),Kv0=SY0();kH.queueScheduler=new Kv0.QueueScheduler(Av0.QueueAction);kH.queue=kH.queueScheduler});var yY0=i((rB)=>{var zv0=rB&&rB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(rB,"__esModule",{value:!0});rB.AnimationFrameAction=void 0;var Vv0=lB(),kY0=nw(),qv0=function(Q){zv0(J,Q);function J(G,H){var K=Q.call(this,G,H)||this;return K.scheduler=G,K.work=H,K}return J.prototype.requestAsyncId=function(G,H,K){if(K===void 0)K=0;if(K!==null&&K>0)return Q.prototype.requestAsyncId.call(this,G,H,K);return G.actions.push(this),G._scheduled||(G._scheduled=kY0.animationFrameProvider.requestAnimationFrame(function(){return G.flush(void 0)}))},J.prototype.recycleAsyncId=function(G,H,K){var z;if(K===void 0)K=0;if(K!=null?K>0:this.delay>0)return Q.prototype.recycleAsyncId.call(this,G,H,K);var q=G.actions;if(H!=null&&((z=q[q.length-1])===null||z===void 0?void 0:z.id)!==H)kY0.animationFrameProvider.cancelAnimationFrame(H),G._scheduled=void 0;return},J}(Vv0.AsyncAction);rB.AnimationFrameAction=qv0});var vY0=i((tB)=>{var Uv0=tB&&tB.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(tB,"__esModule",{value:!0});tB.AnimationFrameScheduler=void 0;var $v0=oB(),Zv0=function(Q){Uv0(J,Q);function J(){return Q!==null&&Q.apply(this,arguments)||this}return J.prototype.flush=function(G){this._active=!0;var H=this._scheduled;this._scheduled=void 0;var K=this.actions,z;G=G||K.shift();do if(z=G.execute(G.state,G.delay))break;while((G=K[0])&&G.id===H&&K.shift());if(this._active=!1,z){while((G=K[0])&&G.id===H&&K.shift())G.unsubscribe();throw z}},J}($v0.AsyncScheduler);tB.AnimationFrameScheduler=Zv0});var xY0=i((yH)=>{Object.defineProperty(yH,"__esModule",{value:!0});yH.animationFrame=yH.animationFrameScheduler=void 0;var Fv0=yY0(),Dv0=vY0();yH.animationFrameScheduler=new Dv0.AnimationFrameScheduler(Fv0.AnimationFrameAction);yH.animationFrame=yH.animationFrameScheduler});var hY0=i((i5)=>{var bY0=i5&&i5.__extends||function(){var Q=function(J,G){return Q=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(H,K){H.__proto__=K}||function(H,K){for(var z in K)if(Object.prototype.hasOwnProperty.call(K,z))H[z]=K[z]},Q(J,G)};return function(J,G){if(typeof G!=="function"&&G!==null)throw TypeError("Class extends value "+String(G)+" is not a constructor or null");Q(J,G);function H(){this.constructor=J}J.prototype=G===null?Object.create(G):(H.prototype=G.prototype,new H)}}();Object.defineProperty(i5,"__esModule",{value:!0});i5.VirtualAction=i5.VirtualTimeScheduler=void 0;var Mv0=lB(),Lv0=rJ(),Ov0=oB(),Pv0=function(Q){bY0(J,Q);function J(G,H){if(G===void 0)G=gY0;if(H===void 0)H=1/0;var K=Q.call(this,G,function(){return K.frame})||this;return K.maxFrames=H,K.frame=0,K.index=-1,K}return J.prototype.flush=function(){var G=this,H=G.actions,K=G.maxFrames,z,q;while((q=H[0])&&q.delay<=K)if(H.shift(),this.frame=q.delay,z=q.execute(q.state,q.delay))break;if(z){while(q=H.shift())q.unsubscribe();throw z}},J.frameTimeFactor=10,J}(Ov0.AsyncScheduler);i5.VirtualTimeScheduler=Pv0;var gY0=function(Q){bY0(J,Q);function J(G,H,K){if(K===void 0)K=G.index+=1;var z=Q.call(this,G,H)||this;return z.scheduler=G,z.work=H,z.index=K,z.active=!0,z.index=G.index=K,z}return J.prototype.schedule=function(G,H){if(H===void 0)H=0;if(Number.isFinite(H)){if(!this.id)return Q.prototype.schedule.call(this,G,H);this.active=!1;var K=new J(this.scheduler,this.work);return this.add(K),K.schedule(G,H)}else return Lv0.Subscription.EMPTY},J.prototype.requestAsyncId=function(G,H,K){if(K===void 0)K=0;this.delay=G.frame+K;var z=G.actions;return z.push(this),z.sort(J.sortActions),1},J.prototype.recycleAsyncId=function(G,H,K){if(K===void 0)K=0;return},J.prototype._execute=function(G,H){if(this.active===!0)return Q.prototype._execute.call(this,G,H)},J.sortActions=function(G,H){if(G.delay===H.delay)if(G.index===H.index)return 0;else if(G.index>H.index)return 1;else return-1;else if(G.delay>H.delay)return 1;else return-1},J}(Mv0.AsyncAction);i5.VirtualAction=gY0});var YG=i((vH)=>{Object.defineProperty(vH,"__esModule",{value:!0});vH.empty=vH.EMPTY=void 0;var _Y0=H9();vH.EMPTY=new _Y0.Observable(function(Q){return Q.complete()});function Nv0(Q){return Q?jv0(Q):vH.EMPTY}vH.empty=Nv0;function jv0(Q){return new _Y0.Observable(function(J){return Q.schedule(function(){return J.complete()})})}});var Vq=i((bD)=>{Object.defineProperty(bD,"__esModule",{value:!0});bD.isScheduler=void 0;var Cv0=e6();function Iv0(Q){return Q&&Cv0.isFunction(Q.schedule)}bD.isScheduler=Iv0});var RJ=i((o5)=>{Object.defineProperty(o5,"__esModule",{value:!0});o5.popNumber=o5.popScheduler=o5.popResultSelector=void 0;var Rv0=e6(),wv0=Vq();function JE(Q){return Q[Q.length-1]}function Ev0(Q){return Rv0.isFunction(JE(Q))?Q.pop():void 0}o5.popResultSelector=Ev0;function Sv0(Q){return wv0.isScheduler(JE(Q))?Q.pop():void 0}o5.popScheduler=Sv0;function Tv0(Q,J){return typeof JE(Q)==="number"?Q.pop():J}o5.popNumber=Tv0});var hD=i((gD)=>{Object.defineProperty(gD,"__esModule",{value:!0});gD.isArrayLike=void 0;gD.isArrayLike=function(Q){return Q&&typeof Q.length==="number"&&typeof Q!=="function"}});var YE=i((_D)=>{Object.defineProperty(_D,"__esModule",{value:!0});_D.isPromise=void 0;var kv0=e6();function yv0(Q){return kv0.isFunction(Q===null||Q===void 0?void 0:Q.then)}_D.isPromise=yv0});var GE=i((fD)=>{Object.defineProperty(fD,"__esModule",{value:!0});fD.isInteropObservable=void 0;var vv0=Hq(),xv0=e6();function bv0(Q){return xv0.isFunction(Q[vv0.observable])}fD.isInteropObservable=bv0});var WE=i((mD)=>{Object.defineProperty(mD,"__esModule",{value:!0});mD.isAsyncIterable=void 0;var gv0=e6();function hv0(Q){return Symbol.asyncIterator&&gv0.isFunction(Q===null||Q===void 0?void 0:Q[Symbol.asyncIterator])}mD.isAsyncIterable=hv0});var HE=i((uD)=>{Object.defineProperty(uD,"__esModule",{value:!0});uD.createInvalidObservableTypeError=void 0;function _v0(Q){return TypeError("You provided "+(Q!==null&&typeof Q==="object"?"an invalid object":"'"+Q+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}uD.createInvalidObservableTypeError=_v0});var BE=i((eB)=>{Object.defineProperty(eB,"__esModule",{value:!0});eB.iterator=eB.getSymbolIterator=void 0;function fY0(){if(typeof Symbol!=="function"||!Symbol.iterator)return"@@iterator";return Symbol.iterator}eB.getSymbolIterator=fY0;eB.iterator=fY0()});var AE=i((pD)=>{Object.defineProperty(pD,"__esModule",{value:!0});pD.isIterable=void 0;var fv0=BE(),mv0=e6();function uv0(Q){return mv0.isFunction(Q===null||Q===void 0?void 0:Q[fv0.iterator])}pD.isIterable=uv0});var lD=i((CY)=>{var pv0=CY&&CY.__generator||function(Q,J){var G={label:0,sent:function(){if(z[0]&1)throw z[1];return z[1]},trys:[],ops:[]},H,K,z,q;return q={next:F(0),throw:F(1),return:F(2)},typeof Symbol==="function"&&(q[Symbol.iterator]=function(){return this}),q;function F(V){return function(O){return D([V,O])}}function D(V){if(H)throw TypeError("Generator is already executing.");while(G)try{if(H=1,K&&(z=V[0]&2?K.return:V[0]?K.throw||((z=K.return)&&z.call(K),0):K.next)&&!(z=z.call(K,V[1])).done)return z;if(K=0,z)V=[V[0]&2,z.value];switch(V[0]){case 0:case 1:z=V;break;case 4:return G.label++,{value:V[1],done:!1};case 5:G.label++,K=V[1],V=[0];continue;case 7:V=G.ops.pop(),G.trys.pop();continue;default:if((z=G.trys,!(z=z.length>0&&z[z.length-1]))&&(V[0]===6||V[0]===2)){G=0;continue}if(V[0]===3&&(!z||V[1]>z[0]&&V[1]<z[3])){G.label=V[1];break}if(V[0]===6&&G.label<z[1]){G.label=z[1],z=V;break}if(z&&G.label<z[2]){G.label=z[2],G.ops.push(V);break}if(z[2])G.ops.pop();G.trys.pop();continue}V=J.call(Q,G)}catch(O){V=[6,O],K=0}finally{H=z=0}if(V[0]&5)throw V[1];return{value:V[0]?V[1]:void 0,done:!0}}},XA=CY&&CY.__await||function(Q){return this instanceof XA?(this.v=Q,this):new XA(Q)},lv0=CY&&CY.__asyncGenerator||function(Q,J,G){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var H=G.apply(Q,J||[]),K,z=[];return K={},q("next"),q("throw"),q("return"),K[Symbol.asyncIterator]=function(){return this},K;function q(N){if(H[N])K[N]=function(I){return new Promise(function(R,w){z.push([N,I,R,w])>1||F(N,I)})}}function F(N,I){try{D(H[N](I))}catch(R){P(z[0][3],R)}}function D(N){N.value instanceof XA?Promise.resolve(N.value.v).then(V,O):P(z[0][2],N)}function V(N){F("next",N)}function O(N){F("throw",N)}function P(N,I){if(N(I),z.shift(),z.length)F(z[0][0],z[0][1])}};Object.defineProperty(CY,"__esModule",{value:!0});CY.isReadableStreamLike=CY.readableStreamLikeToAsyncGenerator=void 0;var dv0=e6();function cv0(Q){return lv0(this,arguments,function(){var G,H,K,z;return pv0(this,function(q){switch(q.label){case 0:G=Q.getReader(),q.label=1;case 1:q.trys.push([1,,9,10]),q.label=2;case 2:return[4,XA(G.read())];case 3:if(H=q.sent(),K=H.value,z=H.done,!z)return[3,5];return[4,XA(void 0)];case 4:return[2,q.sent()];case 5:return[4,XA(K)];case 6:return[4,q.sent()];case 7:return q.sent(),[3,2];case 8:return[3,10];case 9:return G.releaseLock(),[7];case 10:return[2]}})})}CY.readableStreamLikeToAsyncGenerator=cv0;function iv0(Q){return dv0.isFunction(Q===null||Q===void 0?void 0:Q.getReader)}CY.isReadableStreamLike=iv0});var i8=i((y9)=>{var ov0=y9&&y9.__awaiter||function(Q,J,G,H){function K(z){return z instanceof G?z:new G(function(q){q(z)})}return new(G||(G=Promise))(function(z,q){function F(O){try{V(H.next(O))}catch(P){q(P)}}function D(O){try{V(H.throw(O))}catch(P){q(P)}}function V(O){O.done?z(O.value):K(O.value).then(F,D)}V((H=H.apply(Q,J||[])).next())})},nv0=y9&&y9.__generator||function(Q,J){var G={label:0,sent:function(){if(z[0]&1)throw z[1];return z[1]},trys:[],ops:[]},H,K,z,q;return q={next:F(0),throw:F(1),return:F(2)},typeof Symbol==="function"&&(q[Symbol.iterator]=function(){return this}),q;function F(V){return function(O){return D([V,O])}}function D(V){if(H)throw TypeError("Generator is already executing.");while(G)try{if(H=1,K&&(z=V[0]&2?K.return:V[0]?K.throw||((z=K.return)&&z.call(K),0):K.next)&&!(z=z.call(K,V[1])).done)return z;if(K=0,z)V=[V[0]&2,z.value];switch(V[0]){case 0:case 1:z=V;break;case 4:return G.label++,{value:V[1],done:!1};case 5:G.label++,K=V[1],V=[0];continue;case 7:V=G.ops.pop(),G.trys.pop();continue;default:if((z=G.trys,!(z=z.length>0&&z[z.length-1]))&&(V[0]===6||V[0]===2)){G=0;continue}if(V[0]===3&&(!z||V[1]>z[0]&&V[1]<z[3])){G.label=V[1];break}if(V[0]===6&&G.label<z[1]){G.label=z[1],z=V;break}if(z&&G.label<z[2]){G.label=z[2],G.ops.push(V);break}if(z[2])G.ops.pop();G.trys.pop();continue}V=J.call(Q,G)}catch(O){V=[6,O],K=0}finally{H=z=0}if(V[0]&5)throw V[1];return{value:V[0]?V[1]:void 0,done:!0}}},av0=y9&&y9.__asyncValues||function(Q){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var J=Q[Symbol.asyncIterator],G;return J?J.call(Q):(Q=typeof KE==="function"?KE(Q):Q[Symbol.iterator](),G={},H("next"),H("throw"),H("return"),G[Symbol.asyncIterator]=function(){return this},G);function H(z){G[z]=Q[z]&&function(q){return new Promise(function(F,D){q=Q[z](q),K(F,D,q.done,q.value)})}}function K(z,q,F,D){Promise.resolve(D).then(function(V){z({value:V,done:F})},q)}},KE=y9&&y9.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(y9,"__esModule",{value:!0});y9.fromReadableStreamLike=y9.fromAsyncIterable=y9.fromIterable=y9.fromPromise=y9.fromArrayLike=y9.fromInteropObservable=y9.innerFrom=void 0;var sv0=hD(),rv0=YE(),uA=H9(),tv0=GE(),ev0=WE(),Qx0=HE(),Xx0=AE(),mY0=lD(),Jx0=e6(),Yx0=mw(),Gx0=Hq();function Wx0(Q){if(Q instanceof uA.Observable)return Q;if(Q!=null){if(tv0.isInteropObservable(Q))return uY0(Q);if(sv0.isArrayLike(Q))return pY0(Q);if(rv0.isPromise(Q))return lY0(Q);if(ev0.isAsyncIterable(Q))return zE(Q);if(Xx0.isIterable(Q))return dY0(Q);if(mY0.isReadableStreamLike(Q))return cY0(Q)}throw Qx0.createInvalidObservableTypeError(Q)}y9.innerFrom=Wx0;function uY0(Q){return new uA.Observable(function(J){var G=Q[Gx0.observable]();if(Jx0.isFunction(G.subscribe))return G.subscribe(J);throw TypeError("Provided object does not correctly implement Symbol.observable")})}y9.fromInteropObservable=uY0;function pY0(Q){return new uA.Observable(function(J){for(var G=0;G<Q.length&&!J.closed;G++)J.next(Q[G]);J.complete()})}y9.fromArrayLike=pY0;function lY0(Q){return new uA.Observable(function(J){Q.then(function(G){if(!J.closed)J.next(G),J.complete()},function(G){return J.error(G)}).then(null,Yx0.reportUnhandledError)})}y9.fromPromise=lY0;function dY0(Q){return new uA.Observable(function(J){var G,H;try{for(var K=KE(Q),z=K.next();!z.done;z=K.next()){var q=z.value;if(J.next(q),J.closed)return}}catch(F){G={error:F}}finally{try{if(z&&!z.done&&(H=K.return))H.call(K)}finally{if(G)throw G.error}}J.complete()})}y9.fromIterable=dY0;function zE(Q){return new uA.Observable(function(J){Hx0(Q,J).catch(function(G){return J.error(G)})})}y9.fromAsyncIterable=zE;function cY0(Q){return zE(mY0.readableStreamLikeToAsyncGenerator(Q))}y9.fromReadableStreamLike=cY0;function Hx0(Q,J){var G,H,K,z;return ov0(this,void 0,void 0,function(){var q,F;return nv0(this,function(D){switch(D.label){case 0:D.trys.push([0,5,6,11]),G=av0(Q),D.label=1;case 1:return[4,G.next()];case 2:if(H=D.sent(),!!H.done)return[3,4];if(q=H.value,J.next(q),J.closed)return[2];D.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return F=D.sent(),K={error:F},[3,11];case 6:if(D.trys.push([6,,9,10]),!(H&&!H.done&&(z=G.return)))return[3,8];return[4,z.call(G)];case 7:D.sent(),D.label=8;case 8:return[3,10];case 9:if(K)throw K.error;return[7];case 10:return[7];case 11:return J.complete(),[2]}})})}});var cW=i((dD)=>{Object.defineProperty(dD,"__esModule",{value:!0});dD.executeSchedule=void 0;function Bx0(Q,J,G,H,K){if(H===void 0)H=0;if(K===void 0)K=!1;var z=J.schedule(function(){if(G(),K)Q.add(this.schedule(null,H));else this.unsubscribe()},H);if(Q.add(z),!K)return z}dD.executeSchedule=Bx0});var qq=i((cD)=>{Object.defineProperty(cD,"__esModule",{value:!0});cD.observeOn=void 0;var VE=cW(),Ax0=uQ(),Kx0=Y8();function zx0(Q,J){if(J===void 0)J=0;return Ax0.operate(function(G,H){G.subscribe(Kx0.createOperatorSubscriber(H,function(K){return VE.executeSchedule(H,Q,function(){return H.next(K)},J)},function(){return VE.executeSchedule(H,Q,function(){return H.complete()},J)},function(K){return VE.executeSchedule(H,Q,function(){return H.error(K)},J)}))})}cD.observeOn=zx0});var Uq=i((iD)=>{Object.defineProperty(iD,"__esModule",{value:!0});iD.subscribeOn=void 0;var Vx0=uQ();function qx0(Q,J){if(J===void 0)J=0;return Vx0.operate(function(G,H){H.add(Q.schedule(function(){return G.subscribe(H)},J))})}iD.subscribeOn=qx0});var iY0=i((oD)=>{Object.defineProperty(oD,"__esModule",{value:!0});oD.scheduleObservable=void 0;var Ux0=i8(),$x0=qq(),Zx0=Uq();function Fx0(Q,J){return Ux0.innerFrom(Q).pipe(Zx0.subscribeOn(J),$x0.observeOn(J))}oD.scheduleObservable=Fx0});var oY0=i((nD)=>{Object.defineProperty(nD,"__esModule",{value:!0});nD.schedulePromise=void 0;var Dx0=i8(),Mx0=qq(),Lx0=Uq();function Ox0(Q,J){return Dx0.innerFrom(Q).pipe(Lx0.subscribeOn(J),Mx0.observeOn(J))}nD.schedulePromise=Ox0});var nY0=i((aD)=>{Object.defineProperty(aD,"__esModule",{value:!0});aD.scheduleArray=void 0;var Px0=H9();function Nx0(Q,J){return new Px0.Observable(function(G){var H=0;return J.schedule(function(){if(H===Q.length)G.complete();else if(G.next(Q[H++]),!G.closed)this.schedule()})})}aD.scheduleArray=Nx0});var qE=i((sD)=>{Object.defineProperty(sD,"__esModule",{value:!0});sD.scheduleIterable=void 0;var jx0=H9(),Cx0=BE(),Ix0=e6(),aY0=cW();function Rx0(Q,J){return new jx0.Observable(function(G){var H;return aY0.executeSchedule(G,J,function(){H=Q[Cx0.iterator](),aY0.executeSchedule(G,J,function(){var K,z,q;try{K=H.next(),z=K.value,q=K.done}catch(F){G.error(F);return}if(q)G.complete();else G.next(z)},0,!0)}),function(){return Ix0.isFunction(H===null||H===void 0?void 0:H.return)&&H.return()}})}sD.scheduleIterable=Rx0});var UE=i((rD)=>{Object.defineProperty(rD,"__esModule",{value:!0});rD.scheduleAsyncIterable=void 0;var wx0=H9(),sY0=cW();function Ex0(Q,J){if(!Q)throw Error("Iterable cannot be null");return new wx0.Observable(function(G){sY0.executeSchedule(G,J,function(){var H=Q[Symbol.asyncIterator]();sY0.executeSchedule(G,J,function(){H.next().then(function(K){if(K.done)G.complete();else G.next(K.value)})},0,!0)})})}rD.scheduleAsyncIterable=Ex0});var rY0=i((tD)=>{Object.defineProperty(tD,"__esModule",{value:!0});tD.scheduleReadableStreamLike=void 0;var Sx0=UE(),Tx0=lD();function kx0(Q,J){return Sx0.scheduleAsyncIterable(Tx0.readableStreamLikeToAsyncGenerator(Q),J)}tD.scheduleReadableStreamLike=kx0});var $E=i((eD)=>{Object.defineProperty(eD,"__esModule",{value:!0});eD.scheduled=void 0;var yx0=iY0(),vx0=oY0(),xx0=nY0(),bx0=qE(),gx0=UE(),hx0=GE(),_x0=YE(),fx0=hD(),mx0=AE(),ux0=WE(),px0=HE(),lx0=lD(),dx0=rY0();function cx0(Q,J){if(Q!=null){if(hx0.isInteropObservable(Q))return yx0.scheduleObservable(Q,J);if(fx0.isArrayLike(Q))return xx0.scheduleArray(Q,J);if(_x0.isPromise(Q))return vx0.schedulePromise(Q,J);if(ux0.isAsyncIterable(Q))return gx0.scheduleAsyncIterable(Q,J);if(mx0.isIterable(Q))return bx0.scheduleIterable(Q,J);if(lx0.isReadableStreamLike(Q))return dx0.scheduleReadableStreamLike(Q,J)}throw px0.createInvalidObservableTypeError(Q)}eD.scheduled=cx0});var iW=i((QM)=>{Object.defineProperty(QM,"__esModule",{value:!0});QM.from=void 0;var ix0=$E(),ox0=i8();function nx0(Q,J){return J?ix0.scheduled(Q,J):ox0.innerFrom(Q)}QM.from=nx0});var JM=i((XM)=>{Object.defineProperty(XM,"__esModule",{value:!0});XM.of=void 0;var ax0=RJ(),sx0=iW();function rx0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=ax0.popScheduler(Q);return sx0.from(Q,G)}XM.of=rx0});var ZE=i((YM)=>{Object.defineProperty(YM,"__esModule",{value:!0});YM.throwError=void 0;var tx0=H9(),ex0=e6();function Qb0(Q,J){var G=ex0.isFunction(Q)?Q:function(){return Q},H=function(K){return K.error(G())};return new tx0.Observable(J?function(K){return J.schedule(H,0,K)}:H)}YM.throwError=Qb0});var GM=i((oW)=>{Object.defineProperty(oW,"__esModule",{value:!0});oW.observeNotification=oW.Notification=oW.NotificationKind=void 0;var Xb0=YG(),Jb0=JM(),Yb0=ZE(),Gb0=e6(),Wb0;(function(Q){Q.NEXT="N",Q.ERROR="E",Q.COMPLETE="C"})(Wb0=oW.NotificationKind||(oW.NotificationKind={}));var Hb0=function(){function Q(J,G,H){this.kind=J,this.value=G,this.error=H,this.hasValue=J==="N"}return Q.prototype.observe=function(J){return tY0(this,J)},Q.prototype.do=function(J,G,H){var K=this,z=K.kind,q=K.value,F=K.error;return z==="N"?J===null||J===void 0?void 0:J(q):z==="E"?G===null||G===void 0?void 0:G(F):H===null||H===void 0?void 0:H()},Q.prototype.accept=function(J,G,H){var K;return Gb0.isFunction((K=J)===null||K===void 0?void 0:K.next)?this.observe(J):this.do(J,G,H)},Q.prototype.toObservable=function(){var J=this,G=J.kind,H=J.value,K=J.error,z=G==="N"?Jb0.of(H):G==="E"?Yb0.throwError(function(){return K}):G==="C"?Xb0.EMPTY:0;if(!z)throw TypeError("Unexpected notification kind "+G);return z},Q.createNext=function(J){return new Q("N",J)},Q.createError=function(J){return new Q("E",void 0,J)},Q.createComplete=function(){return Q.completeNotification},Q.completeNotification=new Q("C"),Q}();oW.Notification=Hb0;function tY0(Q,J){var G,H,K,z=Q,q=z.kind,F=z.value,D=z.error;if(typeof q!=="string")throw TypeError('Invalid notification, missing "kind"');q==="N"?(G=J.next)===null||G===void 0||G.call(J,F):q==="E"?(H=J.error)===null||H===void 0||H.call(J,D):(K=J.complete)===null||K===void 0||K.call(J)}oW.observeNotification=tY0});var QG0=i((WM)=>{Object.defineProperty(WM,"__esModule",{value:!0});WM.isObservable=void 0;var Bb0=H9(),eY0=e6();function Ab0(Q){return!!Q&&(Q instanceof Bb0.Observable||eY0.isFunction(Q.lift)&&eY0.isFunction(Q.subscribe))}WM.isObservable=Ab0});var n5=i((HM)=>{Object.defineProperty(HM,"__esModule",{value:!0});HM.EmptyError=void 0;var Kb0=d5();HM.EmptyError=Kb0.createErrorClass(function(Q){return function(){Q(this),this.name="EmptyError",this.message="no elements in sequence"}})});var XG0=i((BM)=>{Object.defineProperty(BM,"__esModule",{value:!0});BM.lastValueFrom=void 0;var zb0=n5();function Vb0(Q,J){var G=typeof J==="object";return new Promise(function(H,K){var z=!1,q;Q.subscribe({next:function(F){q=F,z=!0},error:K,complete:function(){if(z)H(q);else if(G)H(J.defaultValue);else K(new zb0.EmptyError)}})})}BM.lastValueFrom=Vb0});var JG0=i((AM)=>{Object.defineProperty(AM,"__esModule",{value:!0});AM.firstValueFrom=void 0;var qb0=n5(),Ub0=xB();function $b0(Q,J){var G=typeof J==="object";return new Promise(function(H,K){var z=new Ub0.SafeSubscriber({next:function(q){H(q),z.unsubscribe()},error:K,complete:function(){if(G)H(J.defaultValue);else K(new qb0.EmptyError)}});Q.subscribe(z)})}AM.firstValueFrom=$b0});var FE=i((KM)=>{Object.defineProperty(KM,"__esModule",{value:!0});KM.ArgumentOutOfRangeError=void 0;var Zb0=d5();KM.ArgumentOutOfRangeError=Zb0.createErrorClass(function(Q){return function(){Q(this),this.name="ArgumentOutOfRangeError",this.message="argument out of range"}})});var DE=i((zM)=>{Object.defineProperty(zM,"__esModule",{value:!0});zM.NotFoundError=void 0;var Fb0=d5();zM.NotFoundError=Fb0.createErrorClass(function(Q){return function(G){Q(this),this.name="NotFoundError",this.message=G}})});var ME=i((VM)=>{Object.defineProperty(VM,"__esModule",{value:!0});VM.SequenceError=void 0;var Db0=d5();VM.SequenceError=Db0.createErrorClass(function(Q){return function(G){Q(this),this.name="SequenceError",this.message=G}})});var UM=i((qM)=>{Object.defineProperty(qM,"__esModule",{value:!0});qM.isValidDate=void 0;function Mb0(Q){return Q instanceof Date&&!isNaN(Q)}qM.isValidDate=Mb0});var $M=i((xH)=>{Object.defineProperty(xH,"__esModule",{value:!0});xH.timeout=xH.TimeoutError=void 0;var Lb0=IJ(),Ob0=UM(),Pb0=uQ(),Nb0=i8(),jb0=d5(),Cb0=Y8(),Ib0=cW();xH.TimeoutError=jb0.createErrorClass(function(Q){return function(G){if(G===void 0)G=null;Q(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=G}});function Rb0(Q,J){var G=Ob0.isValidDate(Q)?{first:Q}:typeof Q==="number"?{each:Q}:Q,H=G.first,K=G.each,z=G.with,q=z===void 0?wb0:z,F=G.scheduler,D=F===void 0?J!==null&&J!==void 0?J:Lb0.asyncScheduler:F,V=G.meta,O=V===void 0?null:V;if(H==null&&K==null)throw TypeError("No timeout provided.");return Pb0.operate(function(P,N){var I,R,w=null,E=0,T=function(y){R=Ib0.executeSchedule(N,D,function(){try{I.unsubscribe(),Nb0.innerFrom(q({meta:O,lastValue:w,seen:E})).subscribe(N)}catch(x){N.error(x)}},y)};I=P.subscribe(Cb0.createOperatorSubscriber(N,function(y){R===null||R===void 0||R.unsubscribe(),E++,N.next(w=y),K>0&&T(K)},void 0,void 0,function(){if(!(R===null||R===void 0?void 0:R.closed))R===null||R===void 0||R.unsubscribe();w=null})),!E&&T(H!=null?typeof H==="number"?H:+H-D.now():K)})}xH.timeout=Rb0;function wb0(Q){throw new xH.TimeoutError(Q)}});var a5=i((ZM)=>{Object.defineProperty(ZM,"__esModule",{value:!0});ZM.map=void 0;var Eb0=uQ(),Sb0=Y8();function Tb0(Q,J){return Eb0.operate(function(G,H){var K=0;G.subscribe(Sb0.createOperatorSubscriber(H,function(z){H.next(Q.call(J,z,K++))}))})}ZM.map=Tb0});var r5=i((s5)=>{var kb0=s5&&s5.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},yb0=s5&&s5.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(s5,"__esModule",{value:!0});s5.mapOneOrManyArgs=void 0;var vb0=a5(),xb0=Array.isArray;function bb0(Q,J){return xb0(J)?Q.apply(void 0,yb0([],kb0(J))):Q(J)}function gb0(Q){return vb0.map(function(J){return bb0(Q,J)})}s5.mapOneOrManyArgs=gb0});var OE=i((t5)=>{var hb0=t5&&t5.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},YG0=t5&&t5.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(t5,"__esModule",{value:!0});t5.bindCallbackInternals=void 0;var _b0=Vq(),fb0=H9(),mb0=Uq(),ub0=r5(),pb0=qq(),lb0=yD();function LE(Q,J,G,H){if(G)if(_b0.isScheduler(G))H=G;else return function(){var K=[];for(var z=0;z<arguments.length;z++)K[z]=arguments[z];return LE(Q,J,H).apply(this,K).pipe(ub0.mapOneOrManyArgs(G))};if(H)return function(){var K=[];for(var z=0;z<arguments.length;z++)K[z]=arguments[z];return LE(Q,J).apply(this,K).pipe(mb0.subscribeOn(H),pb0.observeOn(H))};return function(){var K=this,z=[];for(var q=0;q<arguments.length;q++)z[q]=arguments[q];var F=new lb0.AsyncSubject,D=!0;return new fb0.Observable(function(V){var O=F.subscribe(V);if(D){D=!1;var P=!1,N=!1;if(J.apply(K,YG0(YG0([],hb0(z)),[function(){var I=[];for(var R=0;R<arguments.length;R++)I[R]=arguments[R];if(Q){var w=I.shift();if(w!=null){F.error(w);return}}if(F.next(1<I.length?I:I[0]),N=!0,P)F.complete()}])),N)F.complete();P=!0}return O})}}t5.bindCallbackInternals=LE});var GG0=i((FM)=>{Object.defineProperty(FM,"__esModule",{value:!0});FM.bindCallback=void 0;var db0=OE();function cb0(Q,J,G){return db0.bindCallbackInternals(!1,Q,J,G)}FM.bindCallback=cb0});var WG0=i((DM)=>{Object.defineProperty(DM,"__esModule",{value:!0});DM.bindNodeCallback=void 0;var ib0=OE();function ob0(Q,J,G){return ib0.bindCallbackInternals(!0,Q,J,G)}DM.bindNodeCallback=ob0});var PE=i((MM)=>{Object.defineProperty(MM,"__esModule",{value:!0});MM.argsArgArrayOrObject=void 0;var nb0=Array.isArray,ab0=Object.getPrototypeOf,sb0=Object.prototype,rb0=Object.keys;function tb0(Q){if(Q.length===1){var J=Q[0];if(nb0(J))return{args:J,keys:null};if(eb0(J)){var G=rb0(J);return{args:G.map(function(H){return J[H]}),keys:G}}}return{args:Q,keys:null}}MM.argsArgArrayOrObject=tb0;function eb0(Q){return Q&&typeof Q==="object"&&ab0(Q)===sb0}});var NE=i((LM)=>{Object.defineProperty(LM,"__esModule",{value:!0});LM.createObject=void 0;function Qg0(Q,J){return Q.reduce(function(G,H,K){return G[H]=J[K],G},{})}LM.createObject=Qg0});var OM=i((QK)=>{Object.defineProperty(QK,"__esModule",{value:!0});QK.combineLatestInit=QK.combineLatest=void 0;var Xg0=H9(),Jg0=PE(),AG0=iW(),KG0=WX(),Yg0=r5(),HG0=RJ(),Gg0=NE(),Wg0=Y8(),Hg0=cW();function Bg0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=HG0.popScheduler(Q),H=HG0.popResultSelector(Q),K=Jg0.argsArgArrayOrObject(Q),z=K.args,q=K.keys;if(z.length===0)return AG0.from([],G);var F=new Xg0.Observable(zG0(z,G,q?function(D){return Gg0.createObject(q,D)}:KG0.identity));return H?F.pipe(Yg0.mapOneOrManyArgs(H)):F}QK.combineLatest=Bg0;function zG0(Q,J,G){if(G===void 0)G=KG0.identity;return function(H){BG0(J,function(){var K=Q.length,z=Array(K),q=K,F=K,D=function(O){BG0(J,function(){var P=AG0.from(Q[O],J),N=!1;P.subscribe(Wg0.createOperatorSubscriber(H,function(I){if(z[O]=I,!N)N=!0,F--;if(!F)H.next(G(z.slice()))},function(){if(!--q)H.complete()}))},H)};for(var V=0;V<K;V++)D(V)},H)}}QK.combineLatestInit=zG0;function BG0(Q,J,G){if(Q)Hg0.executeSchedule(G,Q,J);else J()}});var NM=i((PM)=>{Object.defineProperty(PM,"__esModule",{value:!0});PM.mergeInternals=void 0;var Ag0=i8(),Kg0=cW(),VG0=Y8();function zg0(Q,J,G,H,K,z,q,F){var D=[],V=0,O=0,P=!1,N=function(){if(P&&!D.length&&!V)J.complete()},I=function(w){return V<H?R(w):D.push(w)},R=function(w){z&&J.next(w),V++;var E=!1;Ag0.innerFrom(G(w,O++)).subscribe(VG0.createOperatorSubscriber(J,function(T){if(K===null||K===void 0||K(T),z)I(T);else J.next(T)},function(){E=!0},void 0,function(){if(E)try{V--;var T=function(){var y=D.shift();if(q)Kg0.executeSchedule(J,q,function(){return R(y)});else R(y)};while(D.length&&V<H)T();N()}catch(y){J.error(y)}}))};return Q.subscribe(VG0.createOperatorSubscriber(J,I,function(){P=!0,N()})),function(){F===null||F===void 0||F()}}PM.mergeInternals=zg0});var nW=i((jM)=>{Object.defineProperty(jM,"__esModule",{value:!0});jM.mergeMap=void 0;var Vg0=a5(),qg0=i8(),Ug0=uQ(),$g0=NM(),Zg0=e6();function qG0(Q,J,G){if(G===void 0)G=1/0;if(Zg0.isFunction(J))return qG0(function(H,K){return Vg0.map(function(z,q){return J(H,z,K,q)})(qg0.innerFrom(Q(H,K)))},G);else if(typeof J==="number")G=J;return Ug0.operate(function(H,K){return $g0.mergeInternals(H,K,Q,G)})}jM.mergeMap=qG0});var $q=i((CM)=>{Object.defineProperty(CM,"__esModule",{value:!0});CM.mergeAll=void 0;var Fg0=nW(),Dg0=WX();function Mg0(Q){if(Q===void 0)Q=1/0;return Fg0.mergeMap(Dg0.identity,Q)}CM.mergeAll=Mg0});var RM=i((IM)=>{Object.defineProperty(IM,"__esModule",{value:!0});IM.concatAll=void 0;var Lg0=$q();function Og0(){return Lg0.mergeAll(1)}IM.concatAll=Og0});var Zq=i((wM)=>{Object.defineProperty(wM,"__esModule",{value:!0});wM.concat=void 0;var Pg0=RM(),Ng0=RJ(),jg0=iW();function Cg0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return Pg0.concatAll()(jg0.from(Q,Ng0.popScheduler(Q)))}wM.concat=Cg0});var Fq=i((EM)=>{Object.defineProperty(EM,"__esModule",{value:!0});EM.defer=void 0;var Ig0=H9(),Rg0=i8();function wg0(Q){return new Ig0.Observable(function(J){Rg0.innerFrom(Q()).subscribe(J)})}EM.defer=wg0});var UG0=i((SM)=>{Object.defineProperty(SM,"__esModule",{value:!0});SM.connectable=void 0;var Eg0=HX(),Sg0=H9(),Tg0=Fq(),kg0={connector:function(){return new Eg0.Subject},resetOnDisconnect:!0};function yg0(Q,J){if(J===void 0)J=kg0;var G=null,H=J.connector,K=J.resetOnDisconnect,z=K===void 0?!0:K,q=H(),F=new Sg0.Observable(function(D){return q.subscribe(D)});return F.connect=function(){if(!G||G.closed){if(G=Tg0.defer(function(){return Q}).subscribe(q),z)G.add(function(){return q=H()})}return G},F}SM.connectable=yg0});var $G0=i((TM)=>{Object.defineProperty(TM,"__esModule",{value:!0});TM.forkJoin=void 0;var vg0=H9(),xg0=PE(),bg0=i8(),gg0=RJ(),hg0=Y8(),_g0=r5(),fg0=NE();function mg0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=gg0.popResultSelector(Q),H=xg0.argsArgArrayOrObject(Q),K=H.args,z=H.keys,q=new vg0.Observable(function(F){var D=K.length;if(!D){F.complete();return}var V=Array(D),O=D,P=D,N=function(R){var w=!1;bg0.innerFrom(K[R]).subscribe(hg0.createOperatorSubscriber(F,function(E){if(!w)w=!0,P--;V[R]=E},function(){return O--},void 0,function(){if(!O||!w){if(!P)F.next(z?fg0.createObject(z,V):V);F.complete()}}))};for(var I=0;I<D;I++)N(I)});return G?q.pipe(_g0.mapOneOrManyArgs(G)):q}TM.forkJoin=mg0});var FG0=i((XK)=>{var ug0=XK&&XK.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z};Object.defineProperty(XK,"__esModule",{value:!0});XK.fromEvent=void 0;var pg0=i8(),lg0=H9(),dg0=nW(),cg0=hD(),bH=e6(),ig0=r5(),og0=["addListener","removeListener"],ng0=["addEventListener","removeEventListener"],ag0=["on","off"];function jE(Q,J,G,H){if(bH.isFunction(G))H=G,G=void 0;if(H)return jE(Q,J,G).pipe(ig0.mapOneOrManyArgs(H));var K=ug0(tg0(Q)?ng0.map(function(F){return function(D){return Q[F](J,D,G)}}):sg0(Q)?og0.map(ZG0(Q,J)):rg0(Q)?ag0.map(ZG0(Q,J)):[],2),z=K[0],q=K[1];if(!z){if(cg0.isArrayLike(Q))return dg0.mergeMap(function(F){return jE(F,J,G)})(pg0.innerFrom(Q))}if(!z)throw TypeError("Invalid event target");return new lg0.Observable(function(F){var D=function(){var V=[];for(var O=0;O<arguments.length;O++)V[O]=arguments[O];return F.next(1<V.length?V:V[0])};return z(D),function(){return q(D)}})}XK.fromEvent=jE;function ZG0(Q,J){return function(G){return function(H){return Q[G](J,H)}}}function sg0(Q){return bH.isFunction(Q.addListener)&&bH.isFunction(Q.removeListener)}function rg0(Q){return bH.isFunction(Q.on)&&bH.isFunction(Q.off)}function tg0(Q){return bH.isFunction(Q.addEventListener)&&bH.isFunction(Q.removeEventListener)}});var MG0=i((kM)=>{Object.defineProperty(kM,"__esModule",{value:!0});kM.fromEventPattern=void 0;var eg0=H9(),Qh0=e6(),Xh0=r5();function DG0(Q,J,G){if(G)return DG0(Q,J).pipe(Xh0.mapOneOrManyArgs(G));return new eg0.Observable(function(H){var K=function(){var q=[];for(var F=0;F<arguments.length;F++)q[F]=arguments[F];return H.next(q.length===1?q[0]:q)},z=Q(K);return Qh0.isFunction(J)?function(){return J(K,z)}:void 0})}kM.fromEventPattern=DG0});var OG0=i((JK)=>{var Jh0=JK&&JK.__generator||function(Q,J){var G={label:0,sent:function(){if(z[0]&1)throw z[1];return z[1]},trys:[],ops:[]},H,K,z,q;return q={next:F(0),throw:F(1),return:F(2)},typeof Symbol==="function"&&(q[Symbol.iterator]=function(){return this}),q;function F(V){return function(O){return D([V,O])}}function D(V){if(H)throw TypeError("Generator is already executing.");while(G)try{if(H=1,K&&(z=V[0]&2?K.return:V[0]?K.throw||((z=K.return)&&z.call(K),0):K.next)&&!(z=z.call(K,V[1])).done)return z;if(K=0,z)V=[V[0]&2,z.value];switch(V[0]){case 0:case 1:z=V;break;case 4:return G.label++,{value:V[1],done:!1};case 5:G.label++,K=V[1],V=[0];continue;case 7:V=G.ops.pop(),G.trys.pop();continue;default:if((z=G.trys,!(z=z.length>0&&z[z.length-1]))&&(V[0]===6||V[0]===2)){G=0;continue}if(V[0]===3&&(!z||V[1]>z[0]&&V[1]<z[3])){G.label=V[1];break}if(V[0]===6&&G.label<z[1]){G.label=z[1],z=V;break}if(z&&G.label<z[2]){G.label=z[2],G.ops.push(V);break}if(z[2])G.ops.pop();G.trys.pop();continue}V=J.call(Q,G)}catch(O){V=[6,O],K=0}finally{H=z=0}if(V[0]&5)throw V[1];return{value:V[0]?V[1]:void 0,done:!0}}};Object.defineProperty(JK,"__esModule",{value:!0});JK.generate=void 0;var LG0=WX(),Yh0=Vq(),Gh0=Fq(),Wh0=qE();function Hh0(Q,J,G,H,K){var z,q,F,D;if(arguments.length===1)z=Q,D=z.initialState,J=z.condition,G=z.iterate,q=z.resultSelector,F=q===void 0?LG0.identity:q,K=z.scheduler;else if(D=Q,!H||Yh0.isScheduler(H))F=LG0.identity,K=H;else F=H;function V(){var O;return Jh0(this,function(P){switch(P.label){case 0:O=D,P.label=1;case 1:if(!(!J||J(O)))return[3,4];return[4,F(O)];case 2:P.sent(),P.label=3;case 3:return O=G(O),[3,1];case 4:return[2]}})}return Gh0.defer(K?function(){return Wh0.scheduleIterable(V(),K)}:V)}JK.generate=Hh0});var PG0=i((yM)=>{Object.defineProperty(yM,"__esModule",{value:!0});yM.iif=void 0;var Bh0=Fq();function Ah0(Q,J,G){return Bh0.defer(function(){return Q()?J:G})}yM.iif=Ah0});var e5=i((vM)=>{Object.defineProperty(vM,"__esModule",{value:!0});vM.timer=void 0;var Kh0=H9(),zh0=IJ(),Vh0=Vq(),qh0=UM();function Uh0(Q,J,G){if(Q===void 0)Q=0;if(G===void 0)G=zh0.async;var H=-1;if(J!=null)if(Vh0.isScheduler(J))G=J;else H=J;return new Kh0.Observable(function(K){var z=qh0.isValidDate(Q)?+Q-G.now():Q;if(z<0)z=0;var q=0;return G.schedule(function(){if(!K.closed)if(K.next(q++),0<=H)this.schedule(void 0,H);else K.complete()},z)})}vM.timer=Uh0});var CE=i((xM)=>{Object.defineProperty(xM,"__esModule",{value:!0});xM.interval=void 0;var $h0=IJ(),Zh0=e5();function Fh0(Q,J){if(Q===void 0)Q=0;if(J===void 0)J=$h0.asyncScheduler;if(Q<0)Q=0;return Zh0.timer(Q,Q,J)}xM.interval=Fh0});var jG0=i((bM)=>{Object.defineProperty(bM,"__esModule",{value:!0});bM.merge=void 0;var Dh0=$q(),Mh0=i8(),Lh0=YG(),NG0=RJ(),Oh0=iW();function Ph0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=NG0.popScheduler(Q),H=NG0.popNumber(Q,1/0),K=Q;return!K.length?Lh0.EMPTY:K.length===1?Mh0.innerFrom(K[0]):Dh0.mergeAll(H)(Oh0.from(K,G))}bM.merge=Ph0});var IE=i((gH)=>{Object.defineProperty(gH,"__esModule",{value:!0});gH.never=gH.NEVER=void 0;var Nh0=H9(),jh0=GX();gH.NEVER=new Nh0.Observable(jh0.noop);function Ch0(){return gH.NEVER}gH.never=Ch0});var hH=i((gM)=>{Object.defineProperty(gM,"__esModule",{value:!0});gM.argsOrArgArray=void 0;var Ih0=Array.isArray;function Rh0(Q){return Q.length===1&&Ih0(Q[0])?Q[0]:Q}gM.argsOrArgArray=Rh0});var RE=i((hM)=>{Object.defineProperty(hM,"__esModule",{value:!0});hM.onErrorResumeNext=void 0;var wh0=H9(),Eh0=hH(),Sh0=Y8(),CG0=GX(),Th0=i8();function kh0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=Eh0.argsOrArgArray(Q);return new wh0.Observable(function(H){var K=0,z=function(){if(K<G.length){var q=void 0;try{q=Th0.innerFrom(G[K++])}catch(D){z();return}var F=new Sh0.OperatorSubscriber(H,void 0,CG0.noop,CG0.noop);q.subscribe(F),F.add(z)}else H.complete()};z()})}hM.onErrorResumeNext=kh0});var IG0=i((_M)=>{Object.defineProperty(_M,"__esModule",{value:!0});_M.pairs=void 0;var yh0=iW();function vh0(Q,J){return yh0.from(Object.entries(Q),J)}_M.pairs=vh0});var RG0=i((fM)=>{Object.defineProperty(fM,"__esModule",{value:!0});fM.not=void 0;function xh0(Q,J){return function(G,H){return!Q.call(J,G,H)}}fM.not=xh0});var _H=i((mM)=>{Object.defineProperty(mM,"__esModule",{value:!0});mM.filter=void 0;var bh0=uQ(),gh0=Y8();function hh0(Q,J){return bh0.operate(function(G,H){var K=0;G.subscribe(gh0.createOperatorSubscriber(H,function(z){return Q.call(J,z,K++)&&H.next(z)}))})}mM.filter=hh0});var SG0=i((uM)=>{Object.defineProperty(uM,"__esModule",{value:!0});uM.partition=void 0;var _h0=RG0(),wG0=_H(),EG0=i8();function fh0(Q,J,G){return[wG0.filter(J,G)(EG0.innerFrom(Q)),wG0.filter(_h0.not(J,G))(EG0.innerFrom(Q))]}uM.partition=fh0});var wE=i((YK)=>{Object.defineProperty(YK,"__esModule",{value:!0});YK.raceInit=YK.race=void 0;var mh0=H9(),TG0=i8(),uh0=hH(),ph0=Y8();function lh0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return Q=uh0.argsOrArgArray(Q),Q.length===1?TG0.innerFrom(Q[0]):new mh0.Observable(kG0(Q))}YK.race=lh0;function kG0(Q){return function(J){var G=[],H=function(z){G.push(TG0.innerFrom(Q[z]).subscribe(ph0.createOperatorSubscriber(J,function(q){if(G){for(var F=0;F<G.length;F++)F!==z&&G[F].unsubscribe();G=null}J.next(q)})))};for(var K=0;G&&!J.closed&&K<Q.length;K++)H(K)}}YK.raceInit=kG0});var yG0=i((pM)=>{Object.defineProperty(pM,"__esModule",{value:!0});pM.range=void 0;var dh0=H9(),ch0=YG();function ih0(Q,J,G){if(J==null)J=Q,Q=0;if(J<=0)return ch0.EMPTY;var H=J+Q;return new dh0.Observable(G?function(K){var z=Q;return G.schedule(function(){if(z<H)K.next(z++),this.schedule();else K.complete()})}:function(K){var z=Q;while(z<H&&!K.closed)K.next(z++);K.complete()})}pM.range=ih0});var vG0=i((lM)=>{Object.defineProperty(lM,"__esModule",{value:!0});lM.using=void 0;var oh0=H9(),nh0=i8(),ah0=YG();function sh0(Q,J){return new oh0.Observable(function(G){var H=Q(),K=J(H),z=K?nh0.innerFrom(K):ah0.EMPTY;return z.subscribe(G),function(){if(H)H.unsubscribe()}})}lM.using=sh0});var dM=i((Q4)=>{var rh0=Q4&&Q4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},th0=Q4&&Q4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(Q4,"__esModule",{value:!0});Q4.zip=void 0;var eh0=H9(),Q_0=i8(),X_0=hH(),J_0=YG(),Y_0=Y8(),G_0=RJ();function W_0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=G_0.popResultSelector(Q),H=X_0.argsOrArgArray(Q);return H.length?new eh0.Observable(function(K){var z=H.map(function(){return[]}),q=H.map(function(){return!1});K.add(function(){z=q=null});var F=function(V){Q_0.innerFrom(H[V]).subscribe(Y_0.createOperatorSubscriber(K,function(O){if(z[V].push(O),z.every(function(N){return N.length})){var P=z.map(function(N){return N.shift()});if(K.next(G?G.apply(void 0,th0([],rh0(P))):P),z.some(function(N,I){return!N.length&&q[I]}))K.complete()}},function(){q[V]=!0,!z[V].length&&K.complete()}))};for(var D=0;!K.closed&&D<H.length;D++)F(D);return function(){z=q=null}}):J_0.EMPTY}Q4.zip=W_0});var bG0=i((xG0)=>{Object.defineProperty(xG0,"__esModule",{value:!0})});var EE=i((cM)=>{Object.defineProperty(cM,"__esModule",{value:!0});cM.audit=void 0;var H_0=uQ(),B_0=i8(),gG0=Y8();function A_0(Q){return H_0.operate(function(J,G){var H=!1,K=null,z=null,q=!1,F=function(){if(z===null||z===void 0||z.unsubscribe(),z=null,H){H=!1;var V=K;K=null,G.next(V)}q&&G.complete()},D=function(){z=null,q&&G.complete()};J.subscribe(gG0.createOperatorSubscriber(G,function(V){if(H=!0,K=V,!z)B_0.innerFrom(Q(V)).subscribe(z=gG0.createOperatorSubscriber(G,F,D))},function(){q=!0,(!H||!z||z.closed)&&G.complete()}))})}cM.audit=A_0});var hG0=i((iM)=>{Object.defineProperty(iM,"__esModule",{value:!0});iM.auditTime=void 0;var K_0=IJ(),z_0=EE(),V_0=e5();function q_0(Q,J){if(J===void 0)J=K_0.asyncScheduler;return z_0.audit(function(){return V_0.timer(Q,J)})}iM.auditTime=q_0});var fG0=i((oM)=>{Object.defineProperty(oM,"__esModule",{value:!0});oM.buffer=void 0;var U_0=uQ(),$_0=GX(),_G0=Y8(),Z_0=i8();function F_0(Q){return U_0.operate(function(J,G){var H=[];return J.subscribe(_G0.createOperatorSubscriber(G,function(K){return H.push(K)},function(){G.next(H),G.complete()})),Z_0.innerFrom(Q).subscribe(_G0.createOperatorSubscriber(G,function(){var K=H;H=[],G.next(K)},$_0.noop)),function(){H=null}})}oM.buffer=F_0});var mG0=i((GK)=>{var SE=GK&&GK.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(GK,"__esModule",{value:!0});GK.bufferCount=void 0;var D_0=uQ(),M_0=Y8(),L_0=dW();function O_0(Q,J){if(J===void 0)J=null;return J=J!==null&&J!==void 0?J:Q,D_0.operate(function(G,H){var K=[],z=0;G.subscribe(M_0.createOperatorSubscriber(H,function(q){var F,D,V,O,P=null;if(z++%J===0)K.push([]);try{for(var N=SE(K),I=N.next();!I.done;I=N.next()){var R=I.value;if(R.push(q),Q<=R.length)P=P!==null&&P!==void 0?P:[],P.push(R)}}catch(T){F={error:T}}finally{try{if(I&&!I.done&&(D=N.return))D.call(N)}finally{if(F)throw F.error}}if(P)try{for(var w=SE(P),E=w.next();!E.done;E=w.next()){var R=E.value;L_0.arrRemove(K,R),H.next(R)}}catch(T){V={error:T}}finally{try{if(E&&!E.done&&(O=w.return))O.call(w)}finally{if(V)throw V.error}}},function(){var q,F;try{for(var D=SE(K),V=D.next();!V.done;V=D.next()){var O=V.value;H.next(O)}}catch(P){q={error:P}}finally{try{if(V&&!V.done&&(F=D.return))F.call(D)}finally{if(q)throw q.error}}H.complete()},void 0,function(){K=null}))})}GK.bufferCount=O_0});var pG0=i((WK)=>{var P_0=WK&&WK.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(WK,"__esModule",{value:!0});WK.bufferTime=void 0;var N_0=rJ(),j_0=uQ(),C_0=Y8(),I_0=dW(),R_0=IJ(),w_0=RJ(),uG0=cW();function E_0(Q){var J,G,H=[];for(var K=1;K<arguments.length;K++)H[K-1]=arguments[K];var z=(J=w_0.popScheduler(H))!==null&&J!==void 0?J:R_0.asyncScheduler,q=(G=H[0])!==null&&G!==void 0?G:null,F=H[1]||1/0;return j_0.operate(function(D,V){var O=[],P=!1,N=function(w){var{buffer:E,subs:T}=w;T.unsubscribe(),I_0.arrRemove(O,w),V.next(E),P&&I()},I=function(){if(O){var w=new N_0.Subscription;V.add(w);var E=[],T={buffer:E,subs:w};O.push(T),uG0.executeSchedule(w,z,function(){return N(T)},Q)}};if(q!==null&&q>=0)uG0.executeSchedule(V,z,I,q,!0);else P=!0;I();var R=C_0.createOperatorSubscriber(V,function(w){var E,T,y=O.slice();try{for(var x=P_0(y),b=x.next();!b.done;b=x.next()){var g=b.value,l=g.buffer;l.push(w),F<=l.length&&N(g)}}catch(_){E={error:_}}finally{try{if(b&&!b.done&&(T=x.return))T.call(x)}finally{if(E)throw E.error}}},function(){while(O===null||O===void 0?void 0:O.length)V.next(O.shift().buffer);R===null||R===void 0||R.unsubscribe(),V.complete(),V.unsubscribe()},void 0,function(){return O=null});D.subscribe(R)})}WK.bufferTime=E_0});var cG0=i((HK)=>{var S_0=HK&&HK.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(HK,"__esModule",{value:!0});HK.bufferToggle=void 0;var T_0=rJ(),k_0=uQ(),lG0=i8(),TE=Y8(),dG0=GX(),y_0=dW();function v_0(Q,J){return k_0.operate(function(G,H){var K=[];lG0.innerFrom(Q).subscribe(TE.createOperatorSubscriber(H,function(z){var q=[];K.push(q);var F=new T_0.Subscription,D=function(){y_0.arrRemove(K,q),H.next(q),F.unsubscribe()};F.add(lG0.innerFrom(J(z)).subscribe(TE.createOperatorSubscriber(H,D,dG0.noop)))},dG0.noop)),G.subscribe(TE.createOperatorSubscriber(H,function(z){var q,F;try{for(var D=S_0(K),V=D.next();!V.done;V=D.next()){var O=V.value;O.push(z)}}catch(P){q={error:P}}finally{try{if(V&&!V.done&&(F=D.return))F.call(D)}finally{if(q)throw q.error}}},function(){while(K.length>0)H.next(K.shift());H.complete()}))})}HK.bufferToggle=v_0});var oG0=i((nM)=>{Object.defineProperty(nM,"__esModule",{value:!0});nM.bufferWhen=void 0;var x_0=uQ(),b_0=GX(),iG0=Y8(),g_0=i8();function h_0(Q){return x_0.operate(function(J,G){var H=null,K=null,z=function(){K===null||K===void 0||K.unsubscribe();var q=H;H=[],q&&G.next(q),g_0.innerFrom(Q()).subscribe(K=iG0.createOperatorSubscriber(G,z,b_0.noop))};z(),J.subscribe(iG0.createOperatorSubscriber(G,function(q){return H===null||H===void 0?void 0:H.push(q)},function(){H&&G.next(H),G.complete()},void 0,function(){return H=K=null}))})}nM.bufferWhen=h_0});var aG0=i((aM)=>{Object.defineProperty(aM,"__esModule",{value:!0});aM.catchError=void 0;var __0=i8(),f_0=Y8(),m_0=uQ();function nG0(Q){return m_0.operate(function(J,G){var H=null,K=!1,z;if(H=J.subscribe(f_0.createOperatorSubscriber(G,void 0,void 0,function(q){if(z=__0.innerFrom(Q(q,nG0(Q)(J))),H)H.unsubscribe(),H=null,z.subscribe(G);else K=!0})),K)H.unsubscribe(),H=null,z.subscribe(G)})}aM.catchError=nG0});var kE=i((sM)=>{Object.defineProperty(sM,"__esModule",{value:!0});sM.scanInternals=void 0;var u_0=Y8();function p_0(Q,J,G,H,K){return function(z,q){var F=G,D=J,V=0;z.subscribe(u_0.createOperatorSubscriber(q,function(O){var P=V++;D=F?Q(D,O,P):(F=!0,O),H&&q.next(D)},K&&function(){F&&q.next(D),q.complete()}))}}sM.scanInternals=p_0});var BK=i((rM)=>{Object.defineProperty(rM,"__esModule",{value:!0});rM.reduce=void 0;var l_0=kE(),d_0=uQ();function c_0(Q,J){return d_0.operate(l_0.scanInternals(Q,J,arguments.length>=2,!1,!0))}rM.reduce=c_0});var yE=i((tM)=>{Object.defineProperty(tM,"__esModule",{value:!0});tM.toArray=void 0;var i_0=BK(),o_0=uQ(),n_0=function(Q,J){return Q.push(J),Q};function a_0(){return o_0.operate(function(Q,J){i_0.reduce(n_0,[])(Q).subscribe(J)})}tM.toArray=a_0});var vE=i((eM)=>{Object.defineProperty(eM,"__esModule",{value:!0});eM.joinAllInternals=void 0;var s_0=WX(),r_0=r5(),t_0=Bq(),e_0=nW(),Qf0=yE();function Xf0(Q,J){return t_0.pipe(Qf0.toArray(),e_0.mergeMap(function(G){return Q(G)}),J?r_0.mapOneOrManyArgs(J):s_0.identity)}eM.joinAllInternals=Xf0});var xE=i((QL)=>{Object.defineProperty(QL,"__esModule",{value:!0});QL.combineLatestAll=void 0;var Jf0=OM(),Yf0=vE();function Gf0(Q){return Yf0.joinAllInternals(Jf0.combineLatest,Q)}QL.combineLatestAll=Gf0});var sG0=i((XL)=>{Object.defineProperty(XL,"__esModule",{value:!0});XL.combineAll=void 0;var Wf0=xE();XL.combineAll=Wf0.combineLatestAll});var QW0=i((X4)=>{var rG0=X4&&X4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},tG0=X4&&X4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(X4,"__esModule",{value:!0});X4.combineLatest=void 0;var Hf0=OM(),Bf0=uQ(),Af0=hH(),Kf0=r5(),zf0=Bq(),Vf0=RJ();function eG0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=Vf0.popResultSelector(Q);return G?zf0.pipe(eG0.apply(void 0,tG0([],rG0(Q))),Kf0.mapOneOrManyArgs(G)):Bf0.operate(function(H,K){Hf0.combineLatestInit(tG0([H],rG0(Af0.argsOrArgArray(Q))))(K)})}X4.combineLatest=eG0});var XW0=i((J4)=>{var qf0=J4&&J4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Uf0=J4&&J4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(J4,"__esModule",{value:!0});J4.combineLatestWith=void 0;var $f0=QW0();function Zf0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return $f0.combineLatest.apply(void 0,Uf0([],qf0(Q)))}J4.combineLatestWith=Zf0});var bE=i((JL)=>{Object.defineProperty(JL,"__esModule",{value:!0});JL.concatMap=void 0;var JW0=nW(),Ff0=e6();function Df0(Q,J){return Ff0.isFunction(J)?JW0.mergeMap(Q,J,1):JW0.mergeMap(Q,1)}JL.concatMap=Df0});var GW0=i((YL)=>{Object.defineProperty(YL,"__esModule",{value:!0});YL.concatMapTo=void 0;var YW0=bE(),Mf0=e6();function Lf0(Q,J){return Mf0.isFunction(J)?YW0.concatMap(function(){return Q},J):YW0.concatMap(function(){return Q})}YL.concatMapTo=Lf0});var WW0=i((Y4)=>{var Of0=Y4&&Y4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Pf0=Y4&&Y4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(Y4,"__esModule",{value:!0});Y4.concat=void 0;var Nf0=uQ(),jf0=RM(),Cf0=RJ(),If0=iW();function Rf0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=Cf0.popScheduler(Q);return Nf0.operate(function(H,K){jf0.concatAll()(If0.from(Pf0([H],Of0(Q)),G)).subscribe(K)})}Y4.concat=Rf0});var HW0=i((G4)=>{var wf0=G4&&G4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Ef0=G4&&G4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(G4,"__esModule",{value:!0});G4.concatWith=void 0;var Sf0=WW0();function Tf0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return Sf0.concat.apply(void 0,Ef0([],wf0(Q)))}G4.concatWith=Tf0});var BW0=i((GL)=>{Object.defineProperty(GL,"__esModule",{value:!0});GL.fromSubscribable=void 0;var kf0=H9();function yf0(Q){return new kf0.Observable(function(J){return Q.subscribe(J)})}GL.fromSubscribable=yf0});var HL=i((WL)=>{Object.defineProperty(WL,"__esModule",{value:!0});WL.connect=void 0;var vf0=HX(),xf0=i8(),bf0=uQ(),gf0=BW0(),hf0={connector:function(){return new vf0.Subject}};function _f0(Q,J){if(J===void 0)J=hf0;var G=J.connector;return bf0.operate(function(H,K){var z=G();xf0.innerFrom(Q(gf0.fromSubscribable(z))).subscribe(K),K.add(H.subscribe(z))})}WL.connect=_f0});var AW0=i((BL)=>{Object.defineProperty(BL,"__esModule",{value:!0});BL.count=void 0;var ff0=BK();function mf0(Q){return ff0.reduce(function(J,G,H){return!Q||Q(G,H)?J+1:J},0)}BL.count=mf0});var zW0=i((AL)=>{Object.defineProperty(AL,"__esModule",{value:!0});AL.debounce=void 0;var uf0=uQ(),pf0=GX(),KW0=Y8(),lf0=i8();function df0(Q){return uf0.operate(function(J,G){var H=!1,K=null,z=null,q=function(){if(z===null||z===void 0||z.unsubscribe(),z=null,H){H=!1;var F=K;K=null,G.next(F)}};J.subscribe(KW0.createOperatorSubscriber(G,function(F){z===null||z===void 0||z.unsubscribe(),H=!0,K=F,z=KW0.createOperatorSubscriber(G,q,pf0.noop),lf0.innerFrom(Q(F)).subscribe(z)},function(){q(),G.complete()},void 0,function(){K=z=null}))})}AL.debounce=df0});var VW0=i((KL)=>{Object.defineProperty(KL,"__esModule",{value:!0});KL.debounceTime=void 0;var cf0=IJ(),if0=uQ(),of0=Y8();function nf0(Q,J){if(J===void 0)J=cf0.asyncScheduler;return if0.operate(function(G,H){var K=null,z=null,q=null,F=function(){if(K){K.unsubscribe(),K=null;var V=z;z=null,H.next(V)}};function D(){var V=q+Q,O=J.now();if(O<V){K=this.schedule(void 0,V-O),H.add(K);return}F()}G.subscribe(of0.createOperatorSubscriber(H,function(V){if(z=V,q=J.now(),!K)K=J.schedule(D,Q),H.add(K)},function(){F(),H.complete()},void 0,function(){z=K=null}))})}KL.debounceTime=nf0});var Dq=i((zL)=>{Object.defineProperty(zL,"__esModule",{value:!0});zL.defaultIfEmpty=void 0;var af0=uQ(),sf0=Y8();function rf0(Q){return af0.operate(function(J,G){var H=!1;J.subscribe(sf0.createOperatorSubscriber(G,function(K){H=!0,G.next(K)},function(){if(!H)G.next(Q);G.complete()}))})}zL.defaultIfEmpty=rf0});var Mq=i((VL)=>{Object.defineProperty(VL,"__esModule",{value:!0});VL.take=void 0;var tf0=YG(),ef0=uQ(),Qm0=Y8();function Xm0(Q){return Q<=0?function(){return tf0.EMPTY}:ef0.operate(function(J,G){var H=0;J.subscribe(Qm0.createOperatorSubscriber(G,function(K){if(++H<=Q){if(G.next(K),Q<=H)G.complete()}}))})}VL.take=Xm0});var gE=i((qL)=>{Object.defineProperty(qL,"__esModule",{value:!0});qL.ignoreElements=void 0;var Jm0=uQ(),Ym0=Y8(),Gm0=GX();function Wm0(){return Jm0.operate(function(Q,J){Q.subscribe(Ym0.createOperatorSubscriber(J,Gm0.noop))})}qL.ignoreElements=Wm0});var hE=i((UL)=>{Object.defineProperty(UL,"__esModule",{value:!0});UL.mapTo=void 0;var Hm0=a5();function Bm0(Q){return Hm0.map(function(){return Q})}UL.mapTo=Bm0});var _E=i(($L)=>{Object.defineProperty($L,"__esModule",{value:!0});$L.delayWhen=void 0;var Am0=Zq(),qW0=Mq(),Km0=gE(),zm0=hE(),Vm0=nW(),qm0=i8();function UW0(Q,J){if(J)return function(G){return Am0.concat(J.pipe(qW0.take(1),Km0.ignoreElements()),G.pipe(UW0(Q)))};return Vm0.mergeMap(function(G,H){return qm0.innerFrom(Q(G,H)).pipe(qW0.take(1),zm0.mapTo(G))})}$L.delayWhen=UW0});var $W0=i((ZL)=>{Object.defineProperty(ZL,"__esModule",{value:!0});ZL.delay=void 0;var Um0=IJ(),$m0=_E(),Zm0=e5();function Fm0(Q,J){if(J===void 0)J=Um0.asyncScheduler;var G=Zm0.timer(Q,J);return $m0.delayWhen(function(){return G})}ZL.delay=Fm0});var ZW0=i((FL)=>{Object.defineProperty(FL,"__esModule",{value:!0});FL.dematerialize=void 0;var Dm0=GM(),Mm0=uQ(),Lm0=Y8();function Om0(){return Mm0.operate(function(Q,J){Q.subscribe(Lm0.createOperatorSubscriber(J,function(G){return Dm0.observeNotification(G,J)}))})}FL.dematerialize=Om0});var DW0=i((DL)=>{Object.defineProperty(DL,"__esModule",{value:!0});DL.distinct=void 0;var Pm0=uQ(),FW0=Y8(),Nm0=GX(),jm0=i8();function Cm0(Q,J){return Pm0.operate(function(G,H){var K=new Set;G.subscribe(FW0.createOperatorSubscriber(H,function(z){var q=Q?Q(z):z;if(!K.has(q))K.add(q),H.next(z)})),J&&jm0.innerFrom(J).subscribe(FW0.createOperatorSubscriber(H,function(){return K.clear()},Nm0.noop))})}DL.distinct=Cm0});var fE=i((ML)=>{Object.defineProperty(ML,"__esModule",{value:!0});ML.distinctUntilChanged=void 0;var Im0=WX(),Rm0=uQ(),wm0=Y8();function Em0(Q,J){if(J===void 0)J=Im0.identity;return Q=Q!==null&&Q!==void 0?Q:Sm0,Rm0.operate(function(G,H){var K,z=!0;G.subscribe(wm0.createOperatorSubscriber(H,function(q){var F=J(q);if(z||!Q(K,F))z=!1,K=F,H.next(q)}))})}ML.distinctUntilChanged=Em0;function Sm0(Q,J){return Q===J}});var MW0=i((LL)=>{Object.defineProperty(LL,"__esModule",{value:!0});LL.distinctUntilKeyChanged=void 0;var Tm0=fE();function km0(Q,J){return Tm0.distinctUntilChanged(function(G,H){return J?J(G[Q],H[Q]):G[Q]===H[Q]})}LL.distinctUntilKeyChanged=km0});var Lq=i((OL)=>{Object.defineProperty(OL,"__esModule",{value:!0});OL.throwIfEmpty=void 0;var ym0=n5(),vm0=uQ(),xm0=Y8();function bm0(Q){if(Q===void 0)Q=gm0;return vm0.operate(function(J,G){var H=!1;J.subscribe(xm0.createOperatorSubscriber(G,function(K){H=!0,G.next(K)},function(){return H?G.complete():G.error(Q())}))})}OL.throwIfEmpty=bm0;function gm0(){return new ym0.EmptyError}});var OW0=i((PL)=>{Object.defineProperty(PL,"__esModule",{value:!0});PL.elementAt=void 0;var LW0=FE(),hm0=_H(),_m0=Lq(),fm0=Dq(),mm0=Mq();function um0(Q,J){if(Q<0)throw new LW0.ArgumentOutOfRangeError;var G=arguments.length>=2;return function(H){return H.pipe(hm0.filter(function(K,z){return z===Q}),mm0.take(1),G?fm0.defaultIfEmpty(J):_m0.throwIfEmpty(function(){return new LW0.ArgumentOutOfRangeError}))}}PL.elementAt=um0});var PW0=i((W4)=>{var pm0=W4&&W4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},lm0=W4&&W4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(W4,"__esModule",{value:!0});W4.endWith=void 0;var dm0=Zq(),cm0=JM();function im0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return function(G){return dm0.concat(G,cm0.of.apply(void 0,lm0([],pm0(Q))))}}W4.endWith=im0});var NW0=i((NL)=>{Object.defineProperty(NL,"__esModule",{value:!0});NL.every=void 0;var om0=uQ(),nm0=Y8();function am0(Q,J){return om0.operate(function(G,H){var K=0;G.subscribe(nm0.createOperatorSubscriber(H,function(z){if(!Q.call(J,z,K++,G))H.next(!1),H.complete()},function(){H.next(!0),H.complete()}))})}NL.every=am0});var mE=i((jL)=>{Object.defineProperty(jL,"__esModule",{value:!0});jL.exhaustMap=void 0;var sm0=a5(),jW0=i8(),rm0=uQ(),CW0=Y8();function IW0(Q,J){if(J)return function(G){return G.pipe(IW0(function(H,K){return jW0.innerFrom(Q(H,K)).pipe(sm0.map(function(z,q){return J(H,z,K,q)}))}))};return rm0.operate(function(G,H){var K=0,z=null,q=!1;G.subscribe(CW0.createOperatorSubscriber(H,function(F){if(!z)z=CW0.createOperatorSubscriber(H,void 0,function(){z=null,q&&H.complete()}),jW0.innerFrom(Q(F,K++)).subscribe(z)},function(){q=!0,!z&&H.complete()}))})}jL.exhaustMap=IW0});var uE=i((CL)=>{Object.defineProperty(CL,"__esModule",{value:!0});CL.exhaustAll=void 0;var tm0=mE(),em0=WX();function Qu0(){return tm0.exhaustMap(em0.identity)}CL.exhaustAll=Qu0});var RW0=i((IL)=>{Object.defineProperty(IL,"__esModule",{value:!0});IL.exhaust=void 0;var Xu0=uE();IL.exhaust=Xu0.exhaustAll});var wW0=i((RL)=>{Object.defineProperty(RL,"__esModule",{value:!0});RL.expand=void 0;var Ju0=uQ(),Yu0=NM();function Gu0(Q,J,G){if(J===void 0)J=1/0;return J=(J||0)<1?1/0:J,Ju0.operate(function(H,K){return Yu0.mergeInternals(H,K,Q,J,void 0,!0,G)})}RL.expand=Gu0});var EW0=i((wL)=>{Object.defineProperty(wL,"__esModule",{value:!0});wL.finalize=void 0;var Wu0=uQ();function Hu0(Q){return Wu0.operate(function(J,G){try{J.subscribe(G)}finally{G.add(Q)}})}wL.finalize=Hu0});var pE=i((AK)=>{Object.defineProperty(AK,"__esModule",{value:!0});AK.createFind=AK.find=void 0;var Bu0=uQ(),Au0=Y8();function Ku0(Q,J){return Bu0.operate(SW0(Q,J,"value"))}AK.find=Ku0;function SW0(Q,J,G){var H=G==="index";return function(K,z){var q=0;K.subscribe(Au0.createOperatorSubscriber(z,function(F){var D=q++;if(Q.call(J,F,D,K))z.next(H?D:F),z.complete()},function(){z.next(H?-1:void 0),z.complete()}))}}AK.createFind=SW0});var TW0=i((EL)=>{Object.defineProperty(EL,"__esModule",{value:!0});EL.findIndex=void 0;var zu0=uQ(),Vu0=pE();function qu0(Q,J){return zu0.operate(Vu0.createFind(Q,J,"index"))}EL.findIndex=qu0});var kW0=i((SL)=>{Object.defineProperty(SL,"__esModule",{value:!0});SL.first=void 0;var Uu0=n5(),$u0=_H(),Zu0=Mq(),Fu0=Dq(),Du0=Lq(),Mu0=WX();function Lu0(Q,J){var G=arguments.length>=2;return function(H){return H.pipe(Q?$u0.filter(function(K,z){return Q(K,z,H)}):Mu0.identity,Zu0.take(1),G?Fu0.defaultIfEmpty(J):Du0.throwIfEmpty(function(){return new Uu0.EmptyError}))}}SL.first=Lu0});var vW0=i((TL)=>{Object.defineProperty(TL,"__esModule",{value:!0});TL.groupBy=void 0;var Ou0=H9(),Pu0=i8(),Nu0=HX(),ju0=uQ(),yW0=Y8();function Cu0(Q,J,G,H){return ju0.operate(function(K,z){var q;if(!J||typeof J==="function")q=J;else G=J.duration,q=J.element,H=J.connector;var F=new Map,D=function(R){F.forEach(R),R(z)},V=function(R){return D(function(w){return w.error(R)})},O=0,P=!1,N=new yW0.OperatorSubscriber(z,function(R){try{var w=Q(R),E=F.get(w);if(!E){F.set(w,E=H?H():new Nu0.Subject);var T=I(w,E);if(z.next(T),G){var y=yW0.createOperatorSubscriber(E,function(){E.complete(),y===null||y===void 0||y.unsubscribe()},void 0,void 0,function(){return F.delete(w)});N.add(Pu0.innerFrom(G(T)).subscribe(y))}}E.next(q?q(R):R)}catch(x){V(x)}},function(){return D(function(R){return R.complete()})},V,function(){return F.clear()},function(){return P=!0,O===0});K.subscribe(N);function I(R,w){var E=new Ou0.Observable(function(T){O++;var y=w.subscribe(T);return function(){y.unsubscribe(),--O===0&&P&&N.unsubscribe()}});return E.key=R,E}})}TL.groupBy=Cu0});var xW0=i((kL)=>{Object.defineProperty(kL,"__esModule",{value:!0});kL.isEmpty=void 0;var Iu0=uQ(),Ru0=Y8();function wu0(){return Iu0.operate(function(Q,J){Q.subscribe(Ru0.createOperatorSubscriber(J,function(){J.next(!1),J.complete()},function(){J.next(!0),J.complete()}))})}kL.isEmpty=wu0});var lE=i((KK)=>{var Eu0=KK&&KK.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(KK,"__esModule",{value:!0});KK.takeLast=void 0;var Su0=YG(),Tu0=uQ(),ku0=Y8();function yu0(Q){return Q<=0?function(){return Su0.EMPTY}:Tu0.operate(function(J,G){var H=[];J.subscribe(ku0.createOperatorSubscriber(G,function(K){H.push(K),Q<H.length&&H.shift()},function(){var K,z;try{for(var q=Eu0(H),F=q.next();!F.done;F=q.next()){var D=F.value;G.next(D)}}catch(V){K={error:V}}finally{try{if(F&&!F.done&&(z=q.return))z.call(q)}finally{if(K)throw K.error}}G.complete()},void 0,function(){H=null}))})}KK.takeLast=yu0});var bW0=i((yL)=>{Object.defineProperty(yL,"__esModule",{value:!0});yL.last=void 0;var vu0=n5(),xu0=_H(),bu0=lE(),gu0=Lq(),hu0=Dq(),_u0=WX();function fu0(Q,J){var G=arguments.length>=2;return function(H){return H.pipe(Q?xu0.filter(function(K,z){return Q(K,z,H)}):_u0.identity,bu0.takeLast(1),G?hu0.defaultIfEmpty(J):gu0.throwIfEmpty(function(){return new vu0.EmptyError}))}}yL.last=fu0});var gW0=i((vL)=>{Object.defineProperty(vL,"__esModule",{value:!0});vL.materialize=void 0;var dE=GM(),mu0=uQ(),uu0=Y8();function pu0(){return mu0.operate(function(Q,J){Q.subscribe(uu0.createOperatorSubscriber(J,function(G){J.next(dE.Notification.createNext(G))},function(){J.next(dE.Notification.createComplete()),J.complete()},function(G){J.next(dE.Notification.createError(G)),J.complete()}))})}vL.materialize=pu0});var hW0=i((xL)=>{Object.defineProperty(xL,"__esModule",{value:!0});xL.max=void 0;var lu0=BK(),du0=e6();function cu0(Q){return lu0.reduce(du0.isFunction(Q)?function(J,G){return Q(J,G)>0?J:G}:function(J,G){return J>G?J:G})}xL.max=cu0});var _W0=i((bL)=>{Object.defineProperty(bL,"__esModule",{value:!0});bL.flatMap=void 0;var iu0=nW();bL.flatMap=iu0.mergeMap});var mW0=i((gL)=>{Object.defineProperty(gL,"__esModule",{value:!0});gL.mergeMapTo=void 0;var fW0=nW(),ou0=e6();function nu0(Q,J,G){if(G===void 0)G=1/0;if(ou0.isFunction(J))return fW0.mergeMap(function(){return Q},J,G);if(typeof J==="number")G=J;return fW0.mergeMap(function(){return Q},G)}gL.mergeMapTo=nu0});var uW0=i((hL)=>{Object.defineProperty(hL,"__esModule",{value:!0});hL.mergeScan=void 0;var au0=uQ(),su0=NM();function ru0(Q,J,G){if(G===void 0)G=1/0;return au0.operate(function(H,K){var z=J;return su0.mergeInternals(H,K,function(q,F){return Q(z,q,F)},G,function(q){z=q},!1,void 0,function(){return z=null})})}hL.mergeScan=ru0});var lW0=i((H4)=>{var tu0=H4&&H4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},eu0=H4&&H4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(H4,"__esModule",{value:!0});H4.merge=void 0;var Qp0=uQ(),Xp0=hH(),Jp0=$q(),pW0=RJ(),Yp0=iW();function Gp0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=pW0.popScheduler(Q),H=pW0.popNumber(Q,1/0);return Q=Xp0.argsOrArgArray(Q),Qp0.operate(function(K,z){Jp0.mergeAll(H)(Yp0.from(eu0([K],tu0(Q)),G)).subscribe(z)})}H4.merge=Gp0});var dW0=i((B4)=>{var Wp0=B4&&B4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Hp0=B4&&B4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(B4,"__esModule",{value:!0});B4.mergeWith=void 0;var Bp0=lW0();function Ap0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return Bp0.merge.apply(void 0,Hp0([],Wp0(Q)))}B4.mergeWith=Ap0});var cW0=i((_L)=>{Object.defineProperty(_L,"__esModule",{value:!0});_L.min=void 0;var Kp0=BK(),zp0=e6();function Vp0(Q){return Kp0.reduce(zp0.isFunction(Q)?function(J,G){return Q(J,G)<0?J:G}:function(J,G){return J<G?J:G})}_L.min=Vp0});var mL=i((fL)=>{Object.defineProperty(fL,"__esModule",{value:!0});fL.multicast=void 0;var qp0=Aq(),iW0=e6(),Up0=HL();function $p0(Q,J){var G=iW0.isFunction(Q)?Q:function(){return Q};if(iW0.isFunction(J))return Up0.connect(J,{connector:G});return function(H){return new qp0.ConnectableObservable(H,G)}}fL.multicast=$p0});var nW0=i((eG)=>{var Zp0=eG&&eG.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Fp0=eG&&eG.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(eG,"__esModule",{value:!0});eG.onErrorResumeNext=eG.onErrorResumeNextWith=void 0;var Dp0=hH(),Mp0=RE();function oW0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=Dp0.argsOrArgArray(Q);return function(H){return Mp0.onErrorResumeNext.apply(void 0,Fp0([H],Zp0(G)))}}eG.onErrorResumeNextWith=oW0;eG.onErrorResumeNext=oW0});var aW0=i((uL)=>{Object.defineProperty(uL,"__esModule",{value:!0});uL.pairwise=void 0;var Lp0=uQ(),Op0=Y8();function Pp0(){return Lp0.operate(function(Q,J){var G,H=!1;Q.subscribe(Op0.createOperatorSubscriber(J,function(K){var z=G;G=K,H&&J.next([z,K]),H=!0}))})}uL.pairwise=Pp0});var sW0=i((pL)=>{Object.defineProperty(pL,"__esModule",{value:!0});pL.pluck=void 0;var Np0=a5();function jp0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=Q.length;if(G===0)throw Error("list of properties cannot be empty.");return Np0.map(function(H){var K=H;for(var z=0;z<G;z++){var q=K===null||K===void 0?void 0:K[Q[z]];if(typeof q<"u")K=q;else return}return K})}pL.pluck=jp0});var rW0=i((lL)=>{Object.defineProperty(lL,"__esModule",{value:!0});lL.publish=void 0;var Cp0=HX(),Ip0=mL(),Rp0=HL();function wp0(Q){return Q?function(J){return Rp0.connect(Q)(J)}:function(J){return Ip0.multicast(new Cp0.Subject)(J)}}lL.publish=wp0});var tW0=i((dL)=>{Object.defineProperty(dL,"__esModule",{value:!0});dL.publishBehavior=void 0;var Ep0=ew(),Sp0=Aq();function Tp0(Q){return function(J){var G=new Ep0.BehaviorSubject(Q);return new Sp0.ConnectableObservable(J,function(){return G})}}dL.publishBehavior=Tp0});var eW0=i((cL)=>{Object.defineProperty(cL,"__esModule",{value:!0});cL.publishLast=void 0;var kp0=yD(),yp0=Aq();function vp0(){return function(Q){var J=new kp0.AsyncSubject;return new yp0.ConnectableObservable(Q,function(){return J})}}cL.publishLast=vp0});var X50=i((iL)=>{Object.defineProperty(iL,"__esModule",{value:!0});iL.publishReplay=void 0;var xp0=kD(),bp0=mL(),Q50=e6();function gp0(Q,J,G,H){if(G&&!Q50.isFunction(G))H=G;var K=Q50.isFunction(G)?G:void 0;return function(z){return bp0.multicast(new xp0.ReplaySubject(Q,J,H),K)(z)}}iL.publishReplay=gp0});var J50=i((A4)=>{var hp0=A4&&A4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},_p0=A4&&A4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(A4,"__esModule",{value:!0});A4.raceWith=void 0;var fp0=wE(),mp0=uQ(),up0=WX();function pp0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return!Q.length?up0.identity:mp0.operate(function(G,H){fp0.raceInit(_p0([G],hp0(Q)))(H)})}A4.raceWith=pp0});var G50=i((oL)=>{Object.defineProperty(oL,"__esModule",{value:!0});oL.repeat=void 0;var lp0=YG(),dp0=uQ(),Y50=Y8(),cp0=i8(),ip0=e5();function op0(Q){var J,G=1/0,H;if(Q!=null)if(typeof Q==="object")J=Q.count,G=J===void 0?1/0:J,H=Q.delay;else G=Q;return G<=0?function(){return lp0.EMPTY}:dp0.operate(function(K,z){var q=0,F,D=function(){if(F===null||F===void 0||F.unsubscribe(),F=null,H!=null){var O=typeof H==="number"?ip0.timer(H):cp0.innerFrom(H(q)),P=Y50.createOperatorSubscriber(z,function(){P.unsubscribe(),V()});O.subscribe(P)}else V()},V=function(){var O=!1;if(F=K.subscribe(Y50.createOperatorSubscriber(z,void 0,function(){if(++q<G)if(F)D();else O=!0;else z.complete()})),O)D()};V()})}oL.repeat=op0});var H50=i((nL)=>{Object.defineProperty(nL,"__esModule",{value:!0});nL.repeatWhen=void 0;var np0=i8(),ap0=HX(),sp0=uQ(),W50=Y8();function rp0(Q){return sp0.operate(function(J,G){var H,K=!1,z,q=!1,F=!1,D=function(){return F&&q&&(G.complete(),!0)},V=function(){if(!z)z=new ap0.Subject,np0.innerFrom(Q(z)).subscribe(W50.createOperatorSubscriber(G,function(){if(H)O();else K=!0},function(){q=!0,D()}));return z},O=function(){if(F=!1,H=J.subscribe(W50.createOperatorSubscriber(G,void 0,function(){F=!0,!D()&&V().next()})),K)H.unsubscribe(),H=null,K=!1,O()};O()})}nL.repeatWhen=rp0});var A50=i((aL)=>{Object.defineProperty(aL,"__esModule",{value:!0});aL.retry=void 0;var tp0=uQ(),B50=Y8(),ep0=WX(),Ql0=e5(),Xl0=i8();function Jl0(Q){if(Q===void 0)Q=1/0;var J;if(Q&&typeof Q==="object")J=Q;else J={count:Q};var G=J.count,H=G===void 0?1/0:G,K=J.delay,z=J.resetOnSuccess,q=z===void 0?!1:z;return H<=0?ep0.identity:tp0.operate(function(F,D){var V=0,O,P=function(){var N=!1;if(O=F.subscribe(B50.createOperatorSubscriber(D,function(I){if(q)V=0;D.next(I)},void 0,function(I){if(V++<H){var R=function(){if(O)O.unsubscribe(),O=null,P();else N=!0};if(K!=null){var w=typeof K==="number"?Ql0.timer(K):Xl0.innerFrom(K(I,V)),E=B50.createOperatorSubscriber(D,function(){E.unsubscribe(),R()},function(){D.complete()});w.subscribe(E)}else R()}else D.error(I)})),N)O.unsubscribe(),O=null,P()};P()})}aL.retry=Jl0});var z50=i((sL)=>{Object.defineProperty(sL,"__esModule",{value:!0});sL.retryWhen=void 0;var Yl0=i8(),Gl0=HX(),Wl0=uQ(),K50=Y8();function Hl0(Q){return Wl0.operate(function(J,G){var H,K=!1,z,q=function(){if(H=J.subscribe(K50.createOperatorSubscriber(G,void 0,void 0,function(F){if(!z)z=new Gl0.Subject,Yl0.innerFrom(Q(z)).subscribe(K50.createOperatorSubscriber(G,function(){return H?q():K=!0}));if(z)z.next(F)})),K)H.unsubscribe(),H=null,K=!1,q()};q()})}sL.retryWhen=Hl0});var cE=i((rL)=>{Object.defineProperty(rL,"__esModule",{value:!0});rL.sample=void 0;var Bl0=i8(),Al0=uQ(),Kl0=GX(),V50=Y8();function zl0(Q){return Al0.operate(function(J,G){var H=!1,K=null;J.subscribe(V50.createOperatorSubscriber(G,function(z){H=!0,K=z})),Bl0.innerFrom(Q).subscribe(V50.createOperatorSubscriber(G,function(){if(H){H=!1;var z=K;K=null,G.next(z)}},Kl0.noop))})}rL.sample=zl0});var q50=i((tL)=>{Object.defineProperty(tL,"__esModule",{value:!0});tL.sampleTime=void 0;var Vl0=IJ(),ql0=cE(),Ul0=CE();function $l0(Q,J){if(J===void 0)J=Vl0.asyncScheduler;return ql0.sample(Ul0.interval(Q,J))}tL.sampleTime=$l0});var U50=i((eL)=>{Object.defineProperty(eL,"__esModule",{value:!0});eL.scan=void 0;var Zl0=uQ(),Fl0=kE();function Dl0(Q,J){return Zl0.operate(Fl0.scanInternals(Q,J,arguments.length>=2,!0))}eL.scan=Dl0});var Z50=i((QO)=>{Object.defineProperty(QO,"__esModule",{value:!0});QO.sequenceEqual=void 0;var Ml0=uQ(),Ll0=Y8(),Ol0=i8();function Pl0(Q,J){if(J===void 0)J=function(G,H){return G===H};return Ml0.operate(function(G,H){var K=$50(),z=$50(),q=function(D){H.next(D),H.complete()},F=function(D,V){var O=Ll0.createOperatorSubscriber(H,function(P){var{buffer:N,complete:I}=V;if(N.length===0)I?q(!1):D.buffer.push(P);else!J(P,N.shift())&&q(!1)},function(){D.complete=!0;var{complete:P,buffer:N}=V;P&&q(N.length===0),O===null||O===void 0||O.unsubscribe()});return O};G.subscribe(F(K,z)),Ol0.innerFrom(Q).subscribe(F(z,K))})}QO.sequenceEqual=Pl0;function $50(){return{buffer:[],complete:!1}}});var oE=i((K4)=>{var Nl0=K4&&K4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},jl0=K4&&K4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(K4,"__esModule",{value:!0});K4.share=void 0;var F50=i8(),Cl0=HX(),D50=xB(),Il0=uQ();function Rl0(Q){if(Q===void 0)Q={};var J=Q.connector,G=J===void 0?function(){return new Cl0.Subject}:J,H=Q.resetOnError,K=H===void 0?!0:H,z=Q.resetOnComplete,q=z===void 0?!0:z,F=Q.resetOnRefCountZero,D=F===void 0?!0:F;return function(V){var O,P,N,I=0,R=!1,w=!1,E=function(){P===null||P===void 0||P.unsubscribe(),P=void 0},T=function(){E(),O=N=void 0,R=w=!1},y=function(){var x=O;T(),x===null||x===void 0||x.unsubscribe()};return Il0.operate(function(x,b){if(I++,!w&&!R)E();var g=N=N!==null&&N!==void 0?N:G();if(b.add(function(){if(I--,I===0&&!w&&!R)P=iE(y,D)}),g.subscribe(b),!O&&I>0)O=new D50.SafeSubscriber({next:function(l){return g.next(l)},error:function(l){w=!0,E(),P=iE(T,K,l),g.error(l)},complete:function(){R=!0,E(),P=iE(T,q),g.complete()}}),F50.innerFrom(x).subscribe(O)})(V)}}K4.share=Rl0;function iE(Q,J){var G=[];for(var H=2;H<arguments.length;H++)G[H-2]=arguments[H];if(J===!0){Q();return}if(J===!1)return;var K=new D50.SafeSubscriber({next:function(){K.unsubscribe(),Q()}});return F50.innerFrom(J.apply(void 0,jl0([],Nl0(G)))).subscribe(K)}});var M50=i((XO)=>{Object.defineProperty(XO,"__esModule",{value:!0});XO.shareReplay=void 0;var wl0=kD(),El0=oE();function Sl0(Q,J,G){var H,K,z,q,F=!1;if(Q&&typeof Q==="object")H=Q.bufferSize,q=H===void 0?1/0:H,K=Q.windowTime,J=K===void 0?1/0:K,z=Q.refCount,F=z===void 0?!1:z,G=Q.scheduler;else q=Q!==null&&Q!==void 0?Q:1/0;return El0.share({connector:function(){return new wl0.ReplaySubject(q,J,G)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:F})}XO.shareReplay=Sl0});var L50=i((JO)=>{Object.defineProperty(JO,"__esModule",{value:!0});JO.single=void 0;var Tl0=n5(),kl0=ME(),yl0=DE(),vl0=uQ(),xl0=Y8();function bl0(Q){return vl0.operate(function(J,G){var H=!1,K,z=!1,q=0;J.subscribe(xl0.createOperatorSubscriber(G,function(F){if(z=!0,!Q||Q(F,q++,J))H&&G.error(new kl0.SequenceError("Too many matching values")),H=!0,K=F},function(){if(H)G.next(K),G.complete();else G.error(z?new yl0.NotFoundError("No matching values"):new Tl0.EmptyError)}))})}JO.single=bl0});var O50=i((YO)=>{Object.defineProperty(YO,"__esModule",{value:!0});YO.skip=void 0;var gl0=_H();function hl0(Q){return gl0.filter(function(J,G){return Q<=G})}YO.skip=hl0});var P50=i((GO)=>{Object.defineProperty(GO,"__esModule",{value:!0});GO.skipLast=void 0;var _l0=WX(),fl0=uQ(),ml0=Y8();function ul0(Q){return Q<=0?_l0.identity:fl0.operate(function(J,G){var H=Array(Q),K=0;return J.subscribe(ml0.createOperatorSubscriber(G,function(z){var q=K++;if(q<Q)H[q]=z;else{var F=q%Q,D=H[F];H[F]=z,G.next(D)}})),function(){H=null}})}GO.skipLast=ul0});var j50=i((WO)=>{Object.defineProperty(WO,"__esModule",{value:!0});WO.skipUntil=void 0;var pl0=uQ(),N50=Y8(),ll0=i8(),dl0=GX();function cl0(Q){return pl0.operate(function(J,G){var H=!1,K=N50.createOperatorSubscriber(G,function(){K===null||K===void 0||K.unsubscribe(),H=!0},dl0.noop);ll0.innerFrom(Q).subscribe(K),J.subscribe(N50.createOperatorSubscriber(G,function(z){return H&&G.next(z)}))})}WO.skipUntil=cl0});var C50=i((HO)=>{Object.defineProperty(HO,"__esModule",{value:!0});HO.skipWhile=void 0;var il0=uQ(),ol0=Y8();function nl0(Q){return il0.operate(function(J,G){var H=!1,K=0;J.subscribe(ol0.createOperatorSubscriber(G,function(z){return(H||(H=!Q(z,K++)))&&G.next(z)}))})}HO.skipWhile=nl0});var R50=i((BO)=>{Object.defineProperty(BO,"__esModule",{value:!0});BO.startWith=void 0;var I50=Zq(),al0=RJ(),sl0=uQ();function rl0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=al0.popScheduler(Q);return sl0.operate(function(H,K){(G?I50.concat(Q,H,G):I50.concat(Q,H)).subscribe(K)})}BO.startWith=rl0});var Oq=i((AO)=>{Object.defineProperty(AO,"__esModule",{value:!0});AO.switchMap=void 0;var tl0=i8(),el0=uQ(),w50=Y8();function Qd0(Q,J){return el0.operate(function(G,H){var K=null,z=0,q=!1,F=function(){return q&&!K&&H.complete()};G.subscribe(w50.createOperatorSubscriber(H,function(D){K===null||K===void 0||K.unsubscribe();var V=0,O=z++;tl0.innerFrom(Q(D,O)).subscribe(K=w50.createOperatorSubscriber(H,function(P){return H.next(J?J(D,P,O,V++):P)},function(){K=null,F()}))},function(){q=!0,F()}))})}AO.switchMap=Qd0});var E50=i((KO)=>{Object.defineProperty(KO,"__esModule",{value:!0});KO.switchAll=void 0;var Xd0=Oq(),Jd0=WX();function Yd0(){return Xd0.switchMap(Jd0.identity)}KO.switchAll=Yd0});var T50=i((zO)=>{Object.defineProperty(zO,"__esModule",{value:!0});zO.switchMapTo=void 0;var S50=Oq(),Gd0=e6();function Wd0(Q,J){return Gd0.isFunction(J)?S50.switchMap(function(){return Q},J):S50.switchMap(function(){return Q})}zO.switchMapTo=Wd0});var k50=i((VO)=>{Object.defineProperty(VO,"__esModule",{value:!0});VO.switchScan=void 0;var Hd0=Oq(),Bd0=uQ();function Ad0(Q,J){return Bd0.operate(function(G,H){var K=J;return Hd0.switchMap(function(z,q){return Q(K,z,q)},function(z,q){return K=q,q})(G).subscribe(H),function(){K=null}})}VO.switchScan=Ad0});var y50=i((qO)=>{Object.defineProperty(qO,"__esModule",{value:!0});qO.takeUntil=void 0;var Kd0=uQ(),zd0=Y8(),Vd0=i8(),qd0=GX();function Ud0(Q){return Kd0.operate(function(J,G){Vd0.innerFrom(Q).subscribe(zd0.createOperatorSubscriber(G,function(){return G.complete()},qd0.noop)),!G.closed&&J.subscribe(G)})}qO.takeUntil=Ud0});var v50=i((UO)=>{Object.defineProperty(UO,"__esModule",{value:!0});UO.takeWhile=void 0;var $d0=uQ(),Zd0=Y8();function Fd0(Q,J){if(J===void 0)J=!1;return $d0.operate(function(G,H){var K=0;G.subscribe(Zd0.createOperatorSubscriber(H,function(z){var q=Q(z,K++);(q||J)&&H.next(z),!q&&H.complete()}))})}UO.takeWhile=Fd0});var x50=i(($O)=>{Object.defineProperty($O,"__esModule",{value:!0});$O.tap=void 0;var Dd0=e6(),Md0=uQ(),Ld0=Y8(),Od0=WX();function Pd0(Q,J,G){var H=Dd0.isFunction(Q)||J||G?{next:Q,error:J,complete:G}:Q;return H?Md0.operate(function(K,z){var q;(q=H.subscribe)===null||q===void 0||q.call(H);var F=!0;K.subscribe(Ld0.createOperatorSubscriber(z,function(D){var V;(V=H.next)===null||V===void 0||V.call(H,D),z.next(D)},function(){var D;F=!1,(D=H.complete)===null||D===void 0||D.call(H),z.complete()},function(D){var V;F=!1,(V=H.error)===null||V===void 0||V.call(H,D),z.error(D)},function(){var D,V;if(F)(D=H.unsubscribe)===null||D===void 0||D.call(H);(V=H.finalize)===null||V===void 0||V.call(H)}))}):Od0.identity}$O.tap=Pd0});var nE=i((ZO)=>{Object.defineProperty(ZO,"__esModule",{value:!0});ZO.throttle=void 0;var Nd0=uQ(),b50=Y8(),jd0=i8();function Cd0(Q,J){return Nd0.operate(function(G,H){var K=J!==null&&J!==void 0?J:{},z=K.leading,q=z===void 0?!0:z,F=K.trailing,D=F===void 0?!1:F,V=!1,O=null,P=null,N=!1,I=function(){if(P===null||P===void 0||P.unsubscribe(),P=null,D)E(),N&&H.complete()},R=function(){P=null,N&&H.complete()},w=function(T){return P=jd0.innerFrom(Q(T)).subscribe(b50.createOperatorSubscriber(H,I,R))},E=function(){if(V){V=!1;var T=O;O=null,H.next(T),!N&&w(T)}};G.subscribe(b50.createOperatorSubscriber(H,function(T){V=!0,O=T,!(P&&!P.closed)&&(q?E():w(T))},function(){N=!0,!(D&&V&&P&&!P.closed)&&H.complete()}))})}ZO.throttle=Cd0});var g50=i((FO)=>{Object.defineProperty(FO,"__esModule",{value:!0});FO.throttleTime=void 0;var Id0=IJ(),Rd0=nE(),wd0=e5();function Ed0(Q,J,G){if(J===void 0)J=Id0.asyncScheduler;var H=wd0.timer(Q,J);return Rd0.throttle(function(){return H},G)}FO.throttleTime=Ed0});var _50=i((zK)=>{Object.defineProperty(zK,"__esModule",{value:!0});zK.TimeInterval=zK.timeInterval=void 0;var Sd0=IJ(),Td0=uQ(),kd0=Y8();function yd0(Q){if(Q===void 0)Q=Sd0.asyncScheduler;return Td0.operate(function(J,G){var H=Q.now();J.subscribe(kd0.createOperatorSubscriber(G,function(K){var z=Q.now(),q=z-H;H=z,G.next(new h50(K,q))}))})}zK.timeInterval=yd0;var h50=function(){function Q(J,G){this.value=J,this.interval=G}return Q}();zK.TimeInterval=h50});var f50=i((DO)=>{Object.defineProperty(DO,"__esModule",{value:!0});DO.timeoutWith=void 0;var vd0=IJ(),xd0=UM(),bd0=$M();function gd0(Q,J,G){var H,K,z;if(G=G!==null&&G!==void 0?G:vd0.async,xd0.isValidDate(Q))H=Q;else if(typeof Q==="number")K=Q;if(J)z=function(){return J};else throw TypeError("No observable provided to switch to");if(H==null&&K==null)throw TypeError("No timeout provided.");return bd0.timeout({first:H,each:K,scheduler:G,with:z})}DO.timeoutWith=gd0});var m50=i((MO)=>{Object.defineProperty(MO,"__esModule",{value:!0});MO.timestamp=void 0;var hd0=TD(),_d0=a5();function fd0(Q){if(Q===void 0)Q=hd0.dateTimestampProvider;return _d0.map(function(J){return{value:J,timestamp:Q.now()}})}MO.timestamp=fd0});var l50=i((LO)=>{Object.defineProperty(LO,"__esModule",{value:!0});LO.window=void 0;var u50=HX(),md0=uQ(),p50=Y8(),ud0=GX(),pd0=i8();function ld0(Q){return md0.operate(function(J,G){var H=new u50.Subject;G.next(H.asObservable());var K=function(z){H.error(z),G.error(z)};return J.subscribe(p50.createOperatorSubscriber(G,function(z){return H===null||H===void 0?void 0:H.next(z)},function(){H.complete(),G.complete()},K)),pd0.innerFrom(Q).subscribe(p50.createOperatorSubscriber(G,function(){H.complete(),G.next(H=new u50.Subject)},ud0.noop,K)),function(){H===null||H===void 0||H.unsubscribe(),H=null}})}LO.window=ld0});var c50=i((VK)=>{var dd0=VK&&VK.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(VK,"__esModule",{value:!0});VK.windowCount=void 0;var d50=HX(),cd0=uQ(),id0=Y8();function od0(Q,J){if(J===void 0)J=0;var G=J>0?J:Q;return cd0.operate(function(H,K){var z=[new d50.Subject],q=[],F=0;K.next(z[0].asObservable()),H.subscribe(id0.createOperatorSubscriber(K,function(D){var V,O;try{for(var P=dd0(z),N=P.next();!N.done;N=P.next()){var I=N.value;I.next(D)}}catch(E){V={error:E}}finally{try{if(N&&!N.done&&(O=P.return))O.call(P)}finally{if(V)throw V.error}}var R=F-Q+1;if(R>=0&&R%G===0)z.shift().complete();if(++F%G===0){var w=new d50.Subject;z.push(w),K.next(w.asObservable())}},function(){while(z.length>0)z.shift().complete();K.complete()},function(D){while(z.length>0)z.shift().error(D);K.error(D)},function(){q=null,z=null}))})}VK.windowCount=od0});var o50=i((OO)=>{Object.defineProperty(OO,"__esModule",{value:!0});OO.windowTime=void 0;var nd0=HX(),ad0=IJ(),sd0=rJ(),rd0=uQ(),td0=Y8(),ed0=dW(),Qc0=RJ(),i50=cW();function Xc0(Q){var J,G,H=[];for(var K=1;K<arguments.length;K++)H[K-1]=arguments[K];var z=(J=Qc0.popScheduler(H))!==null&&J!==void 0?J:ad0.asyncScheduler,q=(G=H[0])!==null&&G!==void 0?G:null,F=H[1]||1/0;return rd0.operate(function(D,V){var O=[],P=!1,N=function(E){var{window:T,subs:y}=E;T.complete(),y.unsubscribe(),ed0.arrRemove(O,E),P&&I()},I=function(){if(O){var E=new sd0.Subscription;V.add(E);var T=new nd0.Subject,y={window:T,subs:E,seen:0};O.push(y),V.next(T.asObservable()),i50.executeSchedule(E,z,function(){return N(y)},Q)}};if(q!==null&&q>=0)i50.executeSchedule(V,z,I,q,!0);else P=!0;I();var R=function(E){return O.slice().forEach(E)},w=function(E){R(function(T){var y=T.window;return E(y)}),E(V),V.unsubscribe()};return D.subscribe(td0.createOperatorSubscriber(V,function(E){R(function(T){T.window.next(E),F<=++T.seen&&N(T)})},function(){return w(function(E){return E.complete()})},function(E){return w(function(T){return T.error(E)})})),function(){O=null}})}OO.windowTime=Xc0});var s50=i((qK)=>{var Jc0=qK&&qK.__values||function(Q){var J=typeof Symbol==="function"&&Symbol.iterator,G=J&&Q[J],H=0;if(G)return G.call(Q);if(Q&&typeof Q.length==="number")return{next:function(){if(Q&&H>=Q.length)Q=void 0;return{value:Q&&Q[H++],done:!Q}}};throw TypeError(J?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(qK,"__esModule",{value:!0});qK.windowToggle=void 0;var Yc0=HX(),Gc0=rJ(),Wc0=uQ(),n50=i8(),aE=Y8(),a50=GX(),Hc0=dW();function Bc0(Q,J){return Wc0.operate(function(G,H){var K=[],z=function(q){while(0<K.length)K.shift().error(q);H.error(q)};n50.innerFrom(Q).subscribe(aE.createOperatorSubscriber(H,function(q){var F=new Yc0.Subject;K.push(F);var D=new Gc0.Subscription,V=function(){Hc0.arrRemove(K,F),F.complete(),D.unsubscribe()},O;try{O=n50.innerFrom(J(q))}catch(P){z(P);return}H.next(F.asObservable()),D.add(O.subscribe(aE.createOperatorSubscriber(H,V,a50.noop,z)))},a50.noop)),G.subscribe(aE.createOperatorSubscriber(H,function(q){var F,D,V=K.slice();try{for(var O=Jc0(V),P=O.next();!P.done;P=O.next()){var N=P.value;N.next(q)}}catch(I){F={error:I}}finally{try{if(P&&!P.done&&(D=O.return))D.call(O)}finally{if(F)throw F.error}}},function(){while(0<K.length)K.shift().complete();H.complete()},z,function(){while(0<K.length)K.shift().unsubscribe()}))})}qK.windowToggle=Bc0});var t50=i((PO)=>{Object.defineProperty(PO,"__esModule",{value:!0});PO.windowWhen=void 0;var Ac0=HX(),Kc0=uQ(),r50=Y8(),zc0=i8();function Vc0(Q){return Kc0.operate(function(J,G){var H,K,z=function(F){H.error(F),G.error(F)},q=function(){K===null||K===void 0||K.unsubscribe(),H===null||H===void 0||H.complete(),H=new Ac0.Subject,G.next(H.asObservable());var F;try{F=zc0.innerFrom(Q())}catch(D){z(D);return}F.subscribe(K=r50.createOperatorSubscriber(G,q,q,z))};q(),J.subscribe(r50.createOperatorSubscriber(G,function(F){return H.next(F)},function(){H.complete(),G.complete()},z,function(){K===null||K===void 0||K.unsubscribe(),H=null}))})}PO.windowWhen=Vc0});var J40=i((z4)=>{var e50=z4&&z4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Q40=z4&&z4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(z4,"__esModule",{value:!0});z4.withLatestFrom=void 0;var qc0=uQ(),X40=Y8(),Uc0=i8(),$c0=WX(),Zc0=GX(),Fc0=RJ();function Dc0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];var G=Fc0.popResultSelector(Q);return qc0.operate(function(H,K){var z=Q.length,q=Array(z),F=Q.map(function(){return!1}),D=!1,V=function(P){Uc0.innerFrom(Q[P]).subscribe(X40.createOperatorSubscriber(K,function(N){if(q[P]=N,!D&&!F[P])F[P]=!0,(D=F.every($c0.identity))&&(F=null)},Zc0.noop))};for(var O=0;O<z;O++)V(O);H.subscribe(X40.createOperatorSubscriber(K,function(P){if(D){var N=Q40([P],e50(q));K.next(G?G.apply(void 0,Q40([],e50(N))):N)}}))})}z4.withLatestFrom=Dc0});var Y40=i((NO)=>{Object.defineProperty(NO,"__esModule",{value:!0});NO.zipAll=void 0;var Mc0=dM(),Lc0=vE();function Oc0(Q){return Lc0.joinAllInternals(Mc0.zip,Q)}NO.zipAll=Oc0});var G40=i((V4)=>{var Pc0=V4&&V4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},Nc0=V4&&V4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(V4,"__esModule",{value:!0});V4.zip=void 0;var jc0=dM(),Cc0=uQ();function Ic0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return Cc0.operate(function(G,H){jc0.zip.apply(void 0,Nc0([G],Pc0(Q))).subscribe(H)})}V4.zip=Ic0});var W40=i((q4)=>{var Rc0=q4&&q4.__read||function(Q,J){var G=typeof Symbol==="function"&&Q[Symbol.iterator];if(!G)return Q;var H=G.call(Q),K,z=[],q;try{while((J===void 0||J-- >0)&&!(K=H.next()).done)z.push(K.value)}catch(F){q={error:F}}finally{try{if(K&&!K.done&&(G=H.return))G.call(H)}finally{if(q)throw q.error}}return z},wc0=q4&&q4.__spreadArray||function(Q,J){for(var G=0,H=J.length,K=Q.length;G<H;G++,K++)Q[K]=J[G];return Q};Object.defineProperty(q4,"__esModule",{value:!0});q4.zipWith=void 0;var Ec0=G40();function Sc0(){var Q=[];for(var J=0;J<arguments.length;J++)Q[J]=arguments[J];return Ec0.zip.apply(void 0,wc0([],Rc0(Q)))}q4.zipWith=Sc0});var sE=i((o)=>{var Tc0=o&&o.__createBinding||(Object.create?function(Q,J,G,H){if(H===void 0)H=G;Object.defineProperty(Q,H,{enumerable:!0,get:function(){return J[G]}})}:function(Q,J,G,H){if(H===void 0)H=G;Q[H]=J[G]}),kc0=o&&o.__exportStar||function(Q,J){for(var G in Q)if(G!=="default"&&!Object.prototype.hasOwnProperty.call(J,G))Tc0(J,Q,G)};Object.defineProperty(o,"__esModule",{value:!0});o.interval=o.iif=o.generate=o.fromEventPattern=o.fromEvent=o.from=o.forkJoin=o.empty=o.defer=o.connectable=o.concat=o.combineLatest=o.bindNodeCallback=o.bindCallback=o.UnsubscriptionError=o.TimeoutError=o.SequenceError=o.ObjectUnsubscribedError=o.NotFoundError=o.EmptyError=o.ArgumentOutOfRangeError=o.firstValueFrom=o.lastValueFrom=o.isObservable=o.identity=o.noop=o.pipe=o.NotificationKind=o.Notification=o.Subscriber=o.Subscription=o.Scheduler=o.VirtualAction=o.VirtualTimeScheduler=o.animationFrameScheduler=o.animationFrame=o.queueScheduler=o.queue=o.asyncScheduler=o.async=o.asapScheduler=o.asap=o.AsyncSubject=o.ReplaySubject=o.BehaviorSubject=o.Subject=o.animationFrames=o.observable=o.ConnectableObservable=o.Observable=void 0;o.filter=o.expand=o.exhaustMap=o.exhaustAll=o.exhaust=o.every=o.endWith=o.elementAt=o.distinctUntilKeyChanged=o.distinctUntilChanged=o.distinct=o.dematerialize=o.delayWhen=o.delay=o.defaultIfEmpty=o.debounceTime=o.debounce=o.count=o.connect=o.concatWith=o.concatMapTo=o.concatMap=o.concatAll=o.combineLatestWith=o.combineLatestAll=o.combineAll=o.catchError=o.bufferWhen=o.bufferToggle=o.bufferTime=o.bufferCount=o.buffer=o.auditTime=o.audit=o.config=o.NEVER=o.EMPTY=o.scheduled=o.zip=o.using=o.timer=o.throwError=o.range=o.race=o.partition=o.pairs=o.onErrorResumeNext=o.of=o.never=o.merge=void 0;o.switchMap=o.switchAll=o.subscribeOn=o.startWith=o.skipWhile=o.skipUntil=o.skipLast=o.skip=o.single=o.shareReplay=o.share=o.sequenceEqual=o.scan=o.sampleTime=o.sample=o.refCount=o.retryWhen=o.retry=o.repeatWhen=o.repeat=o.reduce=o.raceWith=o.publishReplay=o.publishLast=o.publishBehavior=o.publish=o.pluck=o.pairwise=o.onErrorResumeNextWith=o.observeOn=o.multicast=o.min=o.mergeWith=o.mergeScan=o.mergeMapTo=o.mergeMap=o.flatMap=o.mergeAll=o.max=o.materialize=o.mapTo=o.map=o.last=o.isEmpty=o.ignoreElements=o.groupBy=o.first=o.findIndex=o.find=o.finalize=void 0;o.zipWith=o.zipAll=o.withLatestFrom=o.windowWhen=o.windowToggle=o.windowTime=o.windowCount=o.window=o.toArray=o.timestamp=o.timeoutWith=o.timeout=o.timeInterval=o.throwIfEmpty=o.throttleTime=o.throttle=o.tap=o.takeWhile=o.takeUntil=o.takeLast=o.take=o.switchScan=o.switchMapTo=void 0;var yc0=H9();Object.defineProperty(o,"Observable",{enumerable:!0,get:function(){return yc0.Observable}});var vc0=Aq();Object.defineProperty(o,"ConnectableObservable",{enumerable:!0,get:function(){return vc0.ConnectableObservable}});var xc0=Hq();Object.defineProperty(o,"observable",{enumerable:!0,get:function(){return xc0.observable}});var bc0=zY0();Object.defineProperty(o,"animationFrames",{enumerable:!0,get:function(){return bc0.animationFrames}});var gc0=HX();Object.defineProperty(o,"Subject",{enumerable:!0,get:function(){return gc0.Subject}});var hc0=ew();Object.defineProperty(o,"BehaviorSubject",{enumerable:!0,get:function(){return hc0.BehaviorSubject}});var _c0=kD();Object.defineProperty(o,"ReplaySubject",{enumerable:!0,get:function(){return _c0.ReplaySubject}});var fc0=yD();Object.defineProperty(o,"AsyncSubject",{enumerable:!0,get:function(){return fc0.AsyncSubject}});var H40=wY0();Object.defineProperty(o,"asap",{enumerable:!0,get:function(){return H40.asap}});Object.defineProperty(o,"asapScheduler",{enumerable:!0,get:function(){return H40.asapScheduler}});var B40=IJ();Object.defineProperty(o,"async",{enumerable:!0,get:function(){return B40.async}});Object.defineProperty(o,"asyncScheduler",{enumerable:!0,get:function(){return B40.asyncScheduler}});var A40=TY0();Object.defineProperty(o,"queue",{enumerable:!0,get:function(){return A40.queue}});Object.defineProperty(o,"queueScheduler",{enumerable:!0,get:function(){return A40.queueScheduler}});var K40=xY0();Object.defineProperty(o,"animationFrame",{enumerable:!0,get:function(){return K40.animationFrame}});Object.defineProperty(o,"animationFrameScheduler",{enumerable:!0,get:function(){return K40.animationFrameScheduler}});var z40=hY0();Object.defineProperty(o,"VirtualTimeScheduler",{enumerable:!0,get:function(){return z40.VirtualTimeScheduler}});Object.defineProperty(o,"VirtualAction",{enumerable:!0,get:function(){return z40.VirtualAction}});var mc0=XE();Object.defineProperty(o,"Scheduler",{enumerable:!0,get:function(){return mc0.Scheduler}});var uc0=rJ();Object.defineProperty(o,"Subscription",{enumerable:!0,get:function(){return uc0.Subscription}});var pc0=xB();Object.defineProperty(o,"Subscriber",{enumerable:!0,get:function(){return pc0.Subscriber}});var V40=GM();Object.defineProperty(o,"Notification",{enumerable:!0,get:function(){return V40.Notification}});Object.defineProperty(o,"NotificationKind",{enumerable:!0,get:function(){return V40.NotificationKind}});var lc0=Bq();Object.defineProperty(o,"pipe",{enumerable:!0,get:function(){return lc0.pipe}});var dc0=GX();Object.defineProperty(o,"noop",{enumerable:!0,get:function(){return dc0.noop}});var cc0=WX();Object.defineProperty(o,"identity",{enumerable:!0,get:function(){return cc0.identity}});var ic0=QG0();Object.defineProperty(o,"isObservable",{enumerable:!0,get:function(){return ic0.isObservable}});var oc0=XG0();Object.defineProperty(o,"lastValueFrom",{enumerable:!0,get:function(){return oc0.lastValueFrom}});var nc0=JG0();Object.defineProperty(o,"firstValueFrom",{enumerable:!0,get:function(){return nc0.firstValueFrom}});var ac0=FE();Object.defineProperty(o,"ArgumentOutOfRangeError",{enumerable:!0,get:function(){return ac0.ArgumentOutOfRangeError}});var sc0=n5();Object.defineProperty(o,"EmptyError",{enumerable:!0,get:function(){return sc0.EmptyError}});var rc0=DE();Object.defineProperty(o,"NotFoundError",{enumerable:!0,get:function(){return rc0.NotFoundError}});var tc0=aw();Object.defineProperty(o,"ObjectUnsubscribedError",{enumerable:!0,get:function(){return tc0.ObjectUnsubscribedError}});var ec0=ME();Object.defineProperty(o,"SequenceError",{enumerable:!0,get:function(){return ec0.SequenceError}});var Qi0=$M();Object.defineProperty(o,"TimeoutError",{enumerable:!0,get:function(){return Qi0.TimeoutError}});var Xi0=gw();Object.defineProperty(o,"UnsubscriptionError",{enumerable:!0,get:function(){return Xi0.UnsubscriptionError}});var Ji0=GG0();Object.defineProperty(o,"bindCallback",{enumerable:!0,get:function(){return Ji0.bindCallback}});var Yi0=WG0();Object.defineProperty(o,"bindNodeCallback",{enumerable:!0,get:function(){return Yi0.bindNodeCallback}});var Gi0=OM();Object.defineProperty(o,"combineLatest",{enumerable:!0,get:function(){return Gi0.combineLatest}});var Wi0=Zq();Object.defineProperty(o,"concat",{enumerable:!0,get:function(){return Wi0.concat}});var Hi0=UG0();Object.defineProperty(o,"connectable",{enumerable:!0,get:function(){return Hi0.connectable}});var Bi0=Fq();Object.defineProperty(o,"defer",{enumerable:!0,get:function(){return Bi0.defer}});var Ai0=YG();Object.defineProperty(o,"empty",{enumerable:!0,get:function(){return Ai0.empty}});var Ki0=$G0();Object.defineProperty(o,"forkJoin",{enumerable:!0,get:function(){return Ki0.forkJoin}});var zi0=iW();Object.defineProperty(o,"from",{enumerable:!0,get:function(){return zi0.from}});var Vi0=FG0();Object.defineProperty(o,"fromEvent",{enumerable:!0,get:function(){return Vi0.fromEvent}});var qi0=MG0();Object.defineProperty(o,"fromEventPattern",{enumerable:!0,get:function(){return qi0.fromEventPattern}});var Ui0=OG0();Object.defineProperty(o,"generate",{enumerable:!0,get:function(){return Ui0.generate}});var $i0=PG0();Object.defineProperty(o,"iif",{enumerable:!0,get:function(){return $i0.iif}});var Zi0=CE();Object.defineProperty(o,"interval",{enumerable:!0,get:function(){return Zi0.interval}});var Fi0=jG0();Object.defineProperty(o,"merge",{enumerable:!0,get:function(){return Fi0.merge}});var Di0=IE();Object.defineProperty(o,"never",{enumerable:!0,get:function(){return Di0.never}});var Mi0=JM();Object.defineProperty(o,"of",{enumerable:!0,get:function(){return Mi0.of}});var Li0=RE();Object.defineProperty(o,"onErrorResumeNext",{enumerable:!0,get:function(){return Li0.onErrorResumeNext}});var Oi0=IG0();Object.defineProperty(o,"pairs",{enumerable:!0,get:function(){return Oi0.pairs}});var Pi0=SG0();Object.defineProperty(o,"partition",{enumerable:!0,get:function(){return Pi0.partition}});var Ni0=wE();Object.defineProperty(o,"race",{enumerable:!0,get:function(){return Ni0.race}});var ji0=yG0();Object.defineProperty(o,"range",{enumerable:!0,get:function(){return ji0.range}});var Ci0=ZE();Object.defineProperty(o,"throwError",{enumerable:!0,get:function(){return Ci0.throwError}});var Ii0=e5();Object.defineProperty(o,"timer",{enumerable:!0,get:function(){return Ii0.timer}});var Ri0=vG0();Object.defineProperty(o,"using",{enumerable:!0,get:function(){return Ri0.using}});var wi0=dM();Object.defineProperty(o,"zip",{enumerable:!0,get:function(){return wi0.zip}});var Ei0=$E();Object.defineProperty(o,"scheduled",{enumerable:!0,get:function(){return Ei0.scheduled}});var Si0=YG();Object.defineProperty(o,"EMPTY",{enumerable:!0,get:function(){return Si0.EMPTY}});var Ti0=IE();Object.defineProperty(o,"NEVER",{enumerable:!0,get:function(){return Ti0.NEVER}});kc0(bG0(),o);var ki0=yB();Object.defineProperty(o,"config",{enumerable:!0,get:function(){return ki0.config}});var yi0=EE();Object.defineProperty(o,"audit",{enumerable:!0,get:function(){return yi0.audit}});var vi0=hG0();Object.defineProperty(o,"auditTime",{enumerable:!0,get:function(){return vi0.auditTime}});var xi0=fG0();Object.defineProperty(o,"buffer",{enumerable:!0,get:function(){return xi0.buffer}});var bi0=mG0();Object.defineProperty(o,"bufferCount",{enumerable:!0,get:function(){return bi0.bufferCount}});var gi0=pG0();Object.defineProperty(o,"bufferTime",{enumerable:!0,get:function(){return gi0.bufferTime}});var hi0=cG0();Object.defineProperty(o,"bufferToggle",{enumerable:!0,get:function(){return hi0.bufferToggle}});var _i0=oG0();Object.defineProperty(o,"bufferWhen",{enumerable:!0,get:function(){return _i0.bufferWhen}});var fi0=aG0();Object.defineProperty(o,"catchError",{enumerable:!0,get:function(){return fi0.catchError}});var mi0=sG0();Object.defineProperty(o,"combineAll",{enumerable:!0,get:function(){return mi0.combineAll}});var ui0=xE();Object.defineProperty(o,"combineLatestAll",{enumerable:!0,get:function(){return ui0.combineLatestAll}});var pi0=XW0();Object.defineProperty(o,"combineLatestWith",{enumerable:!0,get:function(){return pi0.combineLatestWith}});var li0=RM();Object.defineProperty(o,"concatAll",{enumerable:!0,get:function(){return li0.concatAll}});var di0=bE();Object.defineProperty(o,"concatMap",{enumerable:!0,get:function(){return di0.concatMap}});var ci0=GW0();Object.defineProperty(o,"concatMapTo",{enumerable:!0,get:function(){return ci0.concatMapTo}});var ii0=HW0();Object.defineProperty(o,"concatWith",{enumerable:!0,get:function(){return ii0.concatWith}});var oi0=HL();Object.defineProperty(o,"connect",{enumerable:!0,get:function(){return oi0.connect}});var ni0=AW0();Object.defineProperty(o,"count",{enumerable:!0,get:function(){return ni0.count}});var ai0=zW0();Object.defineProperty(o,"debounce",{enumerable:!0,get:function(){return ai0.debounce}});var si0=VW0();Object.defineProperty(o,"debounceTime",{enumerable:!0,get:function(){return si0.debounceTime}});var ri0=Dq();Object.defineProperty(o,"defaultIfEmpty",{enumerable:!0,get:function(){return ri0.defaultIfEmpty}});var ti0=$W0();Object.defineProperty(o,"delay",{enumerable:!0,get:function(){return ti0.delay}});var ei0=_E();Object.defineProperty(o,"delayWhen",{enumerable:!0,get:function(){return ei0.delayWhen}});var Qo0=ZW0();Object.defineProperty(o,"dematerialize",{enumerable:!0,get:function(){return Qo0.dematerialize}});var Xo0=DW0();Object.defineProperty(o,"distinct",{enumerable:!0,get:function(){return Xo0.distinct}});var Jo0=fE();Object.defineProperty(o,"distinctUntilChanged",{enumerable:!0,get:function(){return Jo0.distinctUntilChanged}});var Yo0=MW0();Object.defineProperty(o,"distinctUntilKeyChanged",{enumerable:!0,get:function(){return Yo0.distinctUntilKeyChanged}});var Go0=OW0();Object.defineProperty(o,"elementAt",{enumerable:!0,get:function(){return Go0.elementAt}});var Wo0=PW0();Object.defineProperty(o,"endWith",{enumerable:!0,get:function(){return Wo0.endWith}});var Ho0=NW0();Object.defineProperty(o,"every",{enumerable:!0,get:function(){return Ho0.every}});var Bo0=RW0();Object.defineProperty(o,"exhaust",{enumerable:!0,get:function(){return Bo0.exhaust}});var Ao0=uE();Object.defineProperty(o,"exhaustAll",{enumerable:!0,get:function(){return Ao0.exhaustAll}});var Ko0=mE();Object.defineProperty(o,"exhaustMap",{enumerable:!0,get:function(){return Ko0.exhaustMap}});var zo0=wW0();Object.defineProperty(o,"expand",{enumerable:!0,get:function(){return zo0.expand}});var Vo0=_H();Object.defineProperty(o,"filter",{enumerable:!0,get:function(){return Vo0.filter}});var qo0=EW0();Object.defineProperty(o,"finalize",{enumerable:!0,get:function(){return qo0.finalize}});var Uo0=pE();Object.defineProperty(o,"find",{enumerable:!0,get:function(){return Uo0.find}});var $o0=TW0();Object.defineProperty(o,"findIndex",{enumerable:!0,get:function(){return $o0.findIndex}});var Zo0=kW0();Object.defineProperty(o,"first",{enumerable:!0,get:function(){return Zo0.first}});var Fo0=vW0();Object.defineProperty(o,"groupBy",{enumerable:!0,get:function(){return Fo0.groupBy}});var Do0=gE();Object.defineProperty(o,"ignoreElements",{enumerable:!0,get:function(){return Do0.ignoreElements}});var Mo0=xW0();Object.defineProperty(o,"isEmpty",{enumerable:!0,get:function(){return Mo0.isEmpty}});var Lo0=bW0();Object.defineProperty(o,"last",{enumerable:!0,get:function(){return Lo0.last}});var Oo0=a5();Object.defineProperty(o,"map",{enumerable:!0,get:function(){return Oo0.map}});var Po0=hE();Object.defineProperty(o,"mapTo",{enumerable:!0,get:function(){return Po0.mapTo}});var No0=gW0();Object.defineProperty(o,"materialize",{enumerable:!0,get:function(){return No0.materialize}});var jo0=hW0();Object.defineProperty(o,"max",{enumerable:!0,get:function(){return jo0.max}});var Co0=$q();Object.defineProperty(o,"mergeAll",{enumerable:!0,get:function(){return Co0.mergeAll}});var Io0=_W0();Object.defineProperty(o,"flatMap",{enumerable:!0,get:function(){return Io0.flatMap}});var Ro0=nW();Object.defineProperty(o,"mergeMap",{enumerable:!0,get:function(){return Ro0.mergeMap}});var wo0=mW0();Object.defineProperty(o,"mergeMapTo",{enumerable:!0,get:function(){return wo0.mergeMapTo}});var Eo0=uW0();Object.defineProperty(o,"mergeScan",{enumerable:!0,get:function(){return Eo0.mergeScan}});var So0=dW0();Object.defineProperty(o,"mergeWith",{enumerable:!0,get:function(){return So0.mergeWith}});var To0=cW0();Object.defineProperty(o,"min",{enumerable:!0,get:function(){return To0.min}});var ko0=mL();Object.defineProperty(o,"multicast",{enumerable:!0,get:function(){return ko0.multicast}});var yo0=qq();Object.defineProperty(o,"observeOn",{enumerable:!0,get:function(){return yo0.observeOn}});var vo0=nW0();Object.defineProperty(o,"onErrorResumeNextWith",{enumerable:!0,get:function(){return vo0.onErrorResumeNextWith}});var xo0=aW0();Object.defineProperty(o,"pairwise",{enumerable:!0,get:function(){return xo0.pairwise}});var bo0=sW0();Object.defineProperty(o,"pluck",{enumerable:!0,get:function(){return bo0.pluck}});var go0=rW0();Object.defineProperty(o,"publish",{enumerable:!0,get:function(){return go0.publish}});var ho0=tW0();Object.defineProperty(o,"publishBehavior",{enumerable:!0,get:function(){return ho0.publishBehavior}});var _o0=eW0();Object.defineProperty(o,"publishLast",{enumerable:!0,get:function(){return _o0.publishLast}});var fo0=X50();Object.defineProperty(o,"publishReplay",{enumerable:!0,get:function(){return fo0.publishReplay}});var mo0=J50();Object.defineProperty(o,"raceWith",{enumerable:!0,get:function(){return mo0.raceWith}});var uo0=BK();Object.defineProperty(o,"reduce",{enumerable:!0,get:function(){return uo0.reduce}});var po0=G50();Object.defineProperty(o,"repeat",{enumerable:!0,get:function(){return po0.repeat}});var lo0=H50();Object.defineProperty(o,"repeatWhen",{enumerable:!0,get:function(){return lo0.repeatWhen}});var do0=A50();Object.defineProperty(o,"retry",{enumerable:!0,get:function(){return do0.retry}});var co0=z50();Object.defineProperty(o,"retryWhen",{enumerable:!0,get:function(){return co0.retryWhen}});var io0=ow();Object.defineProperty(o,"refCount",{enumerable:!0,get:function(){return io0.refCount}});var oo0=cE();Object.defineProperty(o,"sample",{enumerable:!0,get:function(){return oo0.sample}});var no0=q50();Object.defineProperty(o,"sampleTime",{enumerable:!0,get:function(){return no0.sampleTime}});var ao0=U50();Object.defineProperty(o,"scan",{enumerable:!0,get:function(){return ao0.scan}});var so0=Z50();Object.defineProperty(o,"sequenceEqual",{enumerable:!0,get:function(){return so0.sequenceEqual}});var ro0=oE();Object.defineProperty(o,"share",{enumerable:!0,get:function(){return ro0.share}});var to0=M50();Object.defineProperty(o,"shareReplay",{enumerable:!0,get:function(){return to0.shareReplay}});var eo0=L50();Object.defineProperty(o,"single",{enumerable:!0,get:function(){return eo0.single}});var Qn0=O50();Object.defineProperty(o,"skip",{enumerable:!0,get:function(){return Qn0.skip}});var Xn0=P50();Object.defineProperty(o,"skipLast",{enumerable:!0,get:function(){return Xn0.skipLast}});var Jn0=j50();Object.defineProperty(o,"skipUntil",{enumerable:!0,get:function(){return Jn0.skipUntil}});var Yn0=C50();Object.defineProperty(o,"skipWhile",{enumerable:!0,get:function(){return Yn0.skipWhile}});var Gn0=R50();Object.defineProperty(o,"startWith",{enumerable:!0,get:function(){return Gn0.startWith}});var Wn0=Uq();Object.defineProperty(o,"subscribeOn",{enumerable:!0,get:function(){return Wn0.subscribeOn}});var Hn0=E50();Object.defineProperty(o,"switchAll",{enumerable:!0,get:function(){return Hn0.switchAll}});var Bn0=Oq();Object.defineProperty(o,"switchMap",{enumerable:!0,get:function(){return Bn0.switchMap}});var An0=T50();Object.defineProperty(o,"switchMapTo",{enumerable:!0,get:function(){return An0.switchMapTo}});var Kn0=k50();Object.defineProperty(o,"switchScan",{enumerable:!0,get:function(){return Kn0.switchScan}});var zn0=Mq();Object.defineProperty(o,"take",{enumerable:!0,get:function(){return zn0.take}});var Vn0=lE();Object.defineProperty(o,"takeLast",{enumerable:!0,get:function(){return Vn0.takeLast}});var qn0=y50();Object.defineProperty(o,"takeUntil",{enumerable:!0,get:function(){return qn0.takeUntil}});var Un0=v50();Object.defineProperty(o,"takeWhile",{enumerable:!0,get:function(){return Un0.takeWhile}});var $n0=x50();Object.defineProperty(o,"tap",{enumerable:!0,get:function(){return $n0.tap}});var Zn0=nE();Object.defineProperty(o,"throttle",{enumerable:!0,get:function(){return Zn0.throttle}});var Fn0=g50();Object.defineProperty(o,"throttleTime",{enumerable:!0,get:function(){return Fn0.throttleTime}});var Dn0=Lq();Object.defineProperty(o,"throwIfEmpty",{enumerable:!0,get:function(){return Dn0.throwIfEmpty}});var Mn0=_50();Object.defineProperty(o,"timeInterval",{enumerable:!0,get:function(){return Mn0.timeInterval}});var Ln0=$M();Object.defineProperty(o,"timeout",{enumerable:!0,get:function(){return Ln0.timeout}});var On0=f50();Object.defineProperty(o,"timeoutWith",{enumerable:!0,get:function(){return On0.timeoutWith}});var Pn0=m50();Object.defineProperty(o,"timestamp",{enumerable:!0,get:function(){return Pn0.timestamp}});var Nn0=yE();Object.defineProperty(o,"toArray",{enumerable:!0,get:function(){return Nn0.toArray}});var jn0=l50();Object.defineProperty(o,"window",{enumerable:!0,get:function(){return jn0.window}});var Cn0=c50();Object.defineProperty(o,"windowCount",{enumerable:!0,get:function(){return Cn0.windowCount}});var In0=o50();Object.defineProperty(o,"windowTime",{enumerable:!0,get:function(){return In0.windowTime}});var Rn0=s50();Object.defineProperty(o,"windowToggle",{enumerable:!0,get:function(){return Rn0.windowToggle}});var wn0=t50();Object.defineProperty(o,"windowWhen",{enumerable:!0,get:function(){return wn0.windowWhen}});var En0=J40();Object.defineProperty(o,"withLatestFrom",{enumerable:!0,get:function(){return En0.withLatestFrom}});var Sn0=Y40();Object.defineProperty(o,"zipAll",{enumerable:!0,get:function(){return Sn0.zipAll}});var Tn0=W40();Object.defineProperty(o,"zipWith",{enumerable:!0,get:function(){return Tn0.zipWith}})});var YZ=i((y6)=>{Object.defineProperty(y6,"__esModule",{value:!0});y6.regexpCode=y6.getEsmExportName=y6.getProperty=y6.safeStringify=y6.stringify=y6.strConcat=y6.addCodeArg=y6.str=y6._=y6.nil=y6._Code=y6.Name=y6.IDENTIFIER=y6._CodeOrName=void 0;class Gj{}y6._CodeOrName=Gj;y6.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Oz extends Gj{constructor(Q){super();if(!y6.IDENTIFIER.test(Q))throw Error("CodeGen: name must be a valid identifier");this.str=Q}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}y6.Name=Oz;class OG extends Gj{constructor(Q){super();this._items=typeof Q==="string"?[Q]:Q}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let Q=this._items[0];return Q===""||Q==='""'}get str(){var Q;return(Q=this._str)!==null&&Q!==void 0?Q:this._str=this._items.reduce((J,G)=>`${J}${G}`,"")}get names(){var Q;return(Q=this._names)!==null&&Q!==void 0?Q:this._names=this._items.reduce((J,G)=>{if(G instanceof Oz)J[G.str]=(J[G.str]||0)+1;return J},{})}}y6._Code=OG;y6.nil=new OG("");function CU0(Q,...J){let G=[Q[0]],H=0;while(H<J.length)Gt(G,J[H]),G.push(Q[++H]);return new OG(G)}y6._=CU0;var Yt=new OG("+");function IU0(Q,...J){let G=[JZ(Q[0])],H=0;while(H<J.length)G.push(Yt),Gt(G,J[H]),G.push(Yt,JZ(Q[++H]));return _9Q(G),new OG(G)}y6.str=IU0;function Gt(Q,J){if(J instanceof OG)Q.push(...J._items);else if(J instanceof Oz)Q.push(J);else Q.push(u9Q(J))}y6.addCodeArg=Gt;function _9Q(Q){let J=1;while(J<Q.length-1){if(Q[J]===Yt){let G=f9Q(Q[J-1],Q[J+1]);if(G!==void 0){Q.splice(J-1,3,G);continue}Q[J++]="+"}J++}}function f9Q(Q,J){if(J==='""')return Q;if(Q==='""')return J;if(typeof Q=="string"){if(J instanceof Oz||Q[Q.length-1]!=='"')return;if(typeof J!="string")return`${Q.slice(0,-1)}${J}"`;if(J[0]==='"')return Q.slice(0,-1)+J.slice(1);return}if(typeof J=="string"&&J[0]==='"'&&!(Q instanceof Oz))return`"${Q}${J.slice(1)}`;return}function m9Q(Q,J){return J.emptyStr()?Q:Q.emptyStr()?J:IU0`${Q}${J}`}y6.strConcat=m9Q;function u9Q(Q){return typeof Q=="number"||typeof Q=="boolean"||Q===null?Q:JZ(Array.isArray(Q)?Q.join(","):Q)}function p9Q(Q){return new OG(JZ(Q))}y6.stringify=p9Q;function JZ(Q){return JSON.stringify(Q).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}y6.safeStringify=JZ;function l9Q(Q){return typeof Q=="string"&&y6.IDENTIFIER.test(Q)?new OG(`.${Q}`):CU0`[${Q}]`}y6.getProperty=l9Q;function d9Q(Q){if(typeof Q=="string"&&y6.IDENTIFIER.test(Q))return new OG(`${Q}`);throw Error(`CodeGen: invalid export name: ${Q}, use explicit $id name mapping`)}y6.getEsmExportName=d9Q;function c9Q(Q){return new OG(Q.toString())}y6.regexpCode=c9Q});var Bt=i((mJ)=>{Object.defineProperty(mJ,"__esModule",{value:!0});mJ.ValueScope=mJ.ValueScopeName=mJ.Scope=mJ.varKinds=mJ.UsedValueState=void 0;var fJ=YZ();class RU0 extends Error{constructor(Q){super(`CodeGen: "code" for ${Q} not defined`);this.value=Q.value}}var Wj;(function(Q){Q[Q.Started=0]="Started",Q[Q.Completed=1]="Completed"})(Wj||(mJ.UsedValueState=Wj={}));mJ.varKinds={const:new fJ.Name("const"),let:new fJ.Name("let"),var:new fJ.Name("var")};class Wt{constructor({prefixes:Q,parent:J}={}){this._names={},this._prefixes=Q,this._parent=J}toName(Q){return Q instanceof fJ.Name?Q:this.name(Q)}name(Q){return new fJ.Name(this._newName(Q))}_newName(Q){let J=this._names[Q]||this._nameGroup(Q);return`${Q}${J.index++}`}_nameGroup(Q){var J,G;if(((G=(J=this._parent)===null||J===void 0?void 0:J._prefixes)===null||G===void 0?void 0:G.has(Q))||this._prefixes&&!this._prefixes.has(Q))throw Error(`CodeGen: prefix "${Q}" is not allowed in this scope`);return this._names[Q]={prefix:Q,index:0}}}mJ.Scope=Wt;class Ht extends fJ.Name{constructor(Q,J){super(J);this.prefix=Q}setValue(Q,{property:J,itemIndex:G}){this.value=Q,this.scopePath=fJ._`.${new fJ.Name(J)}[${G}]`}}mJ.ValueScopeName=Ht;var i9Q=fJ._`\n`;class wU0 extends Wt{constructor(Q){super(Q);this._values={},this._scope=Q.scope,this.opts={...Q,_n:Q.lines?i9Q:fJ.nil}}get(){return this._scope}name(Q){return new Ht(Q,this._newName(Q))}value(Q,J){var G;if(J.ref===void 0)throw Error("CodeGen: ref must be passed in value");let H=this.toName(Q),{prefix:K}=H,z=(G=J.key)!==null&&G!==void 0?G:J.ref,q=this._values[K];if(q){let V=q.get(z);if(V)return V}else q=this._values[K]=new Map;q.set(z,H);let F=this._scope[K]||(this._scope[K]=[]),D=F.length;return F[D]=J.ref,H.setValue(J,{property:K,itemIndex:D}),H}getValue(Q,J){let G=this._values[Q];if(!G)return;return G.get(J)}scopeRefs(Q,J=this._values){return this._reduceValues(J,(G)=>{if(G.scopePath===void 0)throw Error(`CodeGen: name "${G}" has no value`);return fJ._`${Q}${G.scopePath}`})}scopeCode(Q=this._values,J,G){return this._reduceValues(Q,(H)=>{if(H.value===void 0)throw Error(`CodeGen: name "${H}" has no value`);return H.value.code},J,G)}_reduceValues(Q,J,G={},H){let K=fJ.nil;for(let z in Q){let q=Q[z];if(!q)continue;let F=G[z]=G[z]||new Map;q.forEach((D)=>{if(F.has(D))return;F.set(D,Wj.Started);let V=J(D);if(V){let O=this.opts.es5?mJ.varKinds.var:mJ.varKinds.const;K=fJ._`${K}${O} ${D} = ${V};${this.opts._n}`}else if(V=H===null||H===void 0?void 0:H(D))K=fJ._`${K}${V}${this.opts._n}`;else throw new RU0(D);F.set(D,Wj.Completed)})}return K}}mJ.ValueScope=wU0});var t8=i((J6)=>{Object.defineProperty(J6,"__esModule",{value:!0});J6.or=J6.and=J6.not=J6.CodeGen=J6.operators=J6.varKinds=J6.ValueScopeName=J6.ValueScope=J6.Scope=J6.Name=J6.regexpCode=J6.stringify=J6.getProperty=J6.nil=J6.strConcat=J6.str=J6._=void 0;var O6=YZ(),PG=Bt(),d4=YZ();Object.defineProperty(J6,"_",{enumerable:!0,get:function(){return d4._}});Object.defineProperty(J6,"str",{enumerable:!0,get:function(){return d4.str}});Object.defineProperty(J6,"strConcat",{enumerable:!0,get:function(){return d4.strConcat}});Object.defineProperty(J6,"nil",{enumerable:!0,get:function(){return d4.nil}});Object.defineProperty(J6,"getProperty",{enumerable:!0,get:function(){return d4.getProperty}});Object.defineProperty(J6,"stringify",{enumerable:!0,get:function(){return d4.stringify}});Object.defineProperty(J6,"regexpCode",{enumerable:!0,get:function(){return d4.regexpCode}});Object.defineProperty(J6,"Name",{enumerable:!0,get:function(){return d4.Name}});var Vj=Bt();Object.defineProperty(J6,"Scope",{enumerable:!0,get:function(){return Vj.Scope}});Object.defineProperty(J6,"ValueScope",{enumerable:!0,get:function(){return Vj.ValueScope}});Object.defineProperty(J6,"ValueScopeName",{enumerable:!0,get:function(){return Vj.ValueScopeName}});Object.defineProperty(J6,"varKinds",{enumerable:!0,get:function(){return Vj.varKinds}});J6.operators={GT:new O6._Code(">"),GTE:new O6._Code(">="),LT:new O6._Code("<"),LTE:new O6._Code("<="),EQ:new O6._Code("==="),NEQ:new O6._Code("!=="),NOT:new O6._Code("!"),OR:new O6._Code("||"),AND:new O6._Code("&&"),ADD:new O6._Code("+")};class c4{optimizeNodes(){return this}optimizeNames(Q,J){return this}}class EU0 extends c4{constructor(Q,J,G){super();this.varKind=Q,this.name=J,this.rhs=G}render({es5:Q,_n:J}){let G=Q?PG.varKinds.var:this.varKind,H=this.rhs===void 0?"":` = ${this.rhs}`;return`${G} ${this.name}${H};`+J}optimizeNames(Q,J){if(!Q[this.name.str])return;if(this.rhs)this.rhs=Nz(this.rhs,Q,J);return this}get names(){return this.rhs instanceof O6._CodeOrName?this.rhs.names:{}}}class Vt extends c4{constructor(Q,J,G){super();this.lhs=Q,this.rhs=J,this.sideEffects=G}render({_n:Q}){return`${this.lhs} = ${this.rhs};`+Q}optimizeNames(Q,J){if(this.lhs instanceof O6.Name&&!Q[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Nz(this.rhs,Q,J),this}get names(){let Q=this.lhs instanceof O6.Name?{}:{...this.lhs.names};return zj(Q,this.rhs)}}class SU0 extends Vt{constructor(Q,J,G,H){super(Q,G,H);this.op=J}render({_n:Q}){return`${this.lhs} ${this.op}= ${this.rhs};`+Q}}class TU0 extends c4{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`${this.label}:`+Q}}class kU0 extends c4{constructor(Q){super();this.label=Q,this.names={}}render({_n:Q}){return`break${this.label?` ${this.label}`:""};`+Q}}class yU0 extends c4{constructor(Q){super();this.error=Q}render({_n:Q}){return`throw ${this.error};`+Q}get names(){return this.error.names}}class vU0 extends c4{constructor(Q){super();this.code=Q}render({_n:Q}){return`${this.code};`+Q}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(Q,J){return this.code=Nz(this.code,Q,J),this}get names(){return this.code instanceof O6._CodeOrName?this.code.names:{}}}class qj extends c4{constructor(Q=[]){super();this.nodes=Q}render(Q){return this.nodes.reduce((J,G)=>J+G.render(Q),"")}optimizeNodes(){let{nodes:Q}=this,J=Q.length;while(J--){let G=Q[J].optimizeNodes();if(Array.isArray(G))Q.splice(J,1,...G);else if(G)Q[J]=G;else Q.splice(J,1)}return Q.length>0?this:void 0}optimizeNames(Q,J){let{nodes:G}=this,H=G.length;while(H--){let K=G[H];if(K.optimizeNames(Q,J))continue;o9Q(Q,K.names),G.splice(H,1)}return G.length>0?this:void 0}get names(){return this.nodes.reduce((Q,J)=>R3(Q,J.names),{})}}class i4 extends qj{render(Q){return"{"+Q._n+super.render(Q)+"}"+Q._n}}class xU0 extends qj{}class GZ extends i4{}GZ.kind="else";class I5 extends i4{constructor(Q,J){super(J);this.condition=Q}render(Q){let J=`if(${this.condition})`+super.render(Q);if(this.else)J+="else "+this.else.render(Q);return J}optimizeNodes(){super.optimizeNodes();let Q=this.condition;if(Q===!0)return this.nodes;let J=this.else;if(J){let G=J.optimizeNodes();J=this.else=Array.isArray(G)?new GZ(G):G}if(J){if(Q===!1)return J instanceof I5?J:J.nodes;if(this.nodes.length)return this;return new I5(fU0(Q),J instanceof I5?[J]:J.nodes)}if(Q===!1||!this.nodes.length)return;return this}optimizeNames(Q,J){var G;if(this.else=(G=this.else)===null||G===void 0?void 0:G.optimizeNames(Q,J),!(super.optimizeNames(Q,J)||this.else))return;return this.condition=Nz(this.condition,Q,J),this}get names(){let Q=super.names;if(zj(Q,this.condition),this.else)R3(Q,this.else.names);return Q}}I5.kind="if";class Pz extends i4{}Pz.kind="for";class bU0 extends Pz{constructor(Q){super();this.iteration=Q}render(Q){return`for(${this.iteration})`+super.render(Q)}optimizeNames(Q,J){if(!super.optimizeNames(Q,J))return;return this.iteration=Nz(this.iteration,Q,J),this}get names(){return R3(super.names,this.iteration.names)}}class gU0 extends Pz{constructor(Q,J,G,H){super();this.varKind=Q,this.name=J,this.from=G,this.to=H}render(Q){let J=Q.es5?PG.varKinds.var:this.varKind,{name:G,from:H,to:K}=this;return`for(${J} ${G}=${H}; ${G}<${K}; ${G}++)`+super.render(Q)}get names(){let Q=zj(super.names,this.from);return zj(Q,this.to)}}class Kt extends Pz{constructor(Q,J,G,H){super();this.loop=Q,this.varKind=J,this.name=G,this.iterable=H}render(Q){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(Q)}optimizeNames(Q,J){if(!super.optimizeNames(Q,J))return;return this.iterable=Nz(this.iterable,Q,J),this}get names(){return R3(super.names,this.iterable.names)}}class Hj extends i4{constructor(Q,J,G){super();this.name=Q,this.args=J,this.async=G}render(Q){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(Q)}}Hj.kind="func";class Bj extends qj{render(Q){return"return "+super.render(Q)}}Bj.kind="return";class hU0 extends i4{render(Q){let J="try"+super.render(Q);if(this.catch)J+=this.catch.render(Q);if(this.finally)J+=this.finally.render(Q);return J}optimizeNodes(){var Q,J;return super.optimizeNodes(),(Q=this.catch)===null||Q===void 0||Q.optimizeNodes(),(J=this.finally)===null||J===void 0||J.optimizeNodes(),this}optimizeNames(Q,J){var G,H;return super.optimizeNames(Q,J),(G=this.catch)===null||G===void 0||G.optimizeNames(Q,J),(H=this.finally)===null||H===void 0||H.optimizeNames(Q,J),this}get names(){let Q=super.names;if(this.catch)R3(Q,this.catch.names);if(this.finally)R3(Q,this.finally.names);return Q}}class Aj extends i4{constructor(Q){super();this.error=Q}render(Q){return`catch(${this.error})`+super.render(Q)}}Aj.kind="catch";class Kj extends i4{render(Q){return"finally"+super.render(Q)}}Kj.kind="finally";class _U0{constructor(Q,J={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...J,_n:J.lines?`
`:""},this._extScope=Q,this._scope=new PG.Scope({parent:Q}),this._nodes=[new xU0]}toString(){return this._root.render(this.opts)}name(Q){return this._scope.name(Q)}scopeName(Q){return this._extScope.name(Q)}scopeValue(Q,J){let G=this._extScope.value(Q,J);return(this._values[G.prefix]||(this._values[G.prefix]=new Set)).add(G),G}getScopeValue(Q,J){return this._extScope.getValue(Q,J)}scopeRefs(Q){return this._extScope.scopeRefs(Q,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(Q,J,G,H){let K=this._scope.toName(J);if(G!==void 0&&H)this._constants[K.str]=G;return this._leafNode(new EU0(Q,K,G)),K}const(Q,J,G){return this._def(PG.varKinds.const,Q,J,G)}let(Q,J,G){return this._def(PG.varKinds.let,Q,J,G)}var(Q,J,G){return this._def(PG.varKinds.var,Q,J,G)}assign(Q,J,G){return this._leafNode(new Vt(Q,J,G))}add(Q,J){return this._leafNode(new SU0(Q,J6.operators.ADD,J))}code(Q){if(typeof Q=="function")Q();else if(Q!==O6.nil)this._leafNode(new vU0(Q));return this}object(...Q){let J=["{"];for(let[G,H]of Q){if(J.length>1)J.push(",");if(J.push(G),G!==H||this.opts.es5)J.push(":"),(0,O6.addCodeArg)(J,H)}return J.push("}"),new O6._Code(J)}if(Q,J,G){if(this._blockNode(new I5(Q)),J&&G)this.code(J).else().code(G).endIf();else if(J)this.code(J).endIf();else if(G)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(Q){return this._elseNode(new I5(Q))}else(){return this._elseNode(new GZ)}endIf(){return this._endBlockNode(I5,GZ)}_for(Q,J){if(this._blockNode(Q),J)this.code(J).endFor();return this}for(Q,J){return this._for(new bU0(Q),J)}forRange(Q,J,G,H,K=this.opts.es5?PG.varKinds.var:PG.varKinds.let){let z=this._scope.toName(Q);return this._for(new gU0(K,z,J,G),()=>H(z))}forOf(Q,J,G,H=PG.varKinds.const){let K=this._scope.toName(Q);if(this.opts.es5){let z=J instanceof O6.Name?J:this.var("_arr",J);return this.forRange("_i",0,O6._`${z}.length`,(q)=>{this.var(K,O6._`${z}[${q}]`),G(K)})}return this._for(new Kt("of",H,K,J),()=>G(K))}forIn(Q,J,G,H=this.opts.es5?PG.varKinds.var:PG.varKinds.const){if(this.opts.ownProperties)return this.forOf(Q,O6._`Object.keys(${J})`,G);let K=this._scope.toName(Q);return this._for(new Kt("in",H,K,J),()=>G(K))}endFor(){return this._endBlockNode(Pz)}label(Q){return this._leafNode(new TU0(Q))}break(Q){return this._leafNode(new kU0(Q))}return(Q){let J=new Bj;if(this._blockNode(J),this.code(Q),J.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Bj)}try(Q,J,G){if(!J&&!G)throw Error('CodeGen: "try" without "catch" and "finally"');let H=new hU0;if(this._blockNode(H),this.code(Q),J){let K=this.name("e");this._currNode=H.catch=new Aj(K),J(K)}if(G)this._currNode=H.finally=new Kj,this.code(G);return this._endBlockNode(Aj,Kj)}throw(Q){return this._leafNode(new yU0(Q))}block(Q,J){if(this._blockStarts.push(this._nodes.length),Q)this.code(Q).endBlock(J);return this}endBlock(Q){let J=this._blockStarts.pop();if(J===void 0)throw Error("CodeGen: not in self-balancing block");let G=this._nodes.length-J;if(G<0||Q!==void 0&&G!==Q)throw Error(`CodeGen: wrong number of nodes: ${G} vs ${Q} expected`);return this._nodes.length=J,this}func(Q,J=O6.nil,G,H){if(this._blockNode(new Hj(Q,J,G)),H)this.code(H).endFunc();return this}endFunc(){return this._endBlockNode(Hj)}optimize(Q=1){while(Q-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(Q){return this._currNode.nodes.push(Q),this}_blockNode(Q){this._currNode.nodes.push(Q),this._nodes.push(Q)}_endBlockNode(Q,J){let G=this._currNode;if(G instanceof Q||J&&G instanceof J)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${J?`${Q.kind}/${J.kind}`:Q.kind}"`)}_elseNode(Q){let J=this._currNode;if(!(J instanceof I5))throw Error('CodeGen: "else" without "if"');return this._currNode=J.else=Q,this}get _root(){return this._nodes[0]}get _currNode(){let Q=this._nodes;return Q[Q.length-1]}set _currNode(Q){let J=this._nodes;J[J.length-1]=Q}}J6.CodeGen=_U0;function R3(Q,J){for(let G in J)Q[G]=(Q[G]||0)+(J[G]||0);return Q}function zj(Q,J){return J instanceof O6._CodeOrName?R3(Q,J.names):Q}function Nz(Q,J,G){if(Q instanceof O6.Name)return H(Q);if(!K(Q))return Q;return new O6._Code(Q._items.reduce((z,q)=>{if(q instanceof O6.Name)q=H(q);if(q instanceof O6._Code)z.push(...q._items);else z.push(q);return z},[]));function H(z){let q=G[z.str];if(q===void 0||J[z.str]!==1)return z;return delete J[z.str],q}function K(z){return z instanceof O6._Code&&z._items.some((q)=>q instanceof O6.Name&&J[q.str]===1&&G[q.str]!==void 0)}}function o9Q(Q,J){for(let G in J)Q[G]=(Q[G]||0)-(J[G]||0)}function fU0(Q){return typeof Q=="boolean"||typeof Q=="number"||Q===null?!Q:O6._`!${zt(Q)}`}J6.not=fU0;var n9Q=mU0(J6.operators.AND);function a9Q(...Q){return Q.reduce(n9Q)}J6.and=a9Q;var s9Q=mU0(J6.operators.OR);function r9Q(...Q){return Q.reduce(s9Q)}J6.or=r9Q;function mU0(Q){return(J,G)=>J===O6.nil?G:G===O6.nil?J:O6._`${zt(J)} ${Q} ${zt(G)}`}function zt(Q){return Q instanceof O6.Name?Q:O6._`(${Q})`}});var R6=i((H6)=>{Object.defineProperty(H6,"__esModule",{value:!0});H6.checkStrictMode=H6.getErrorPath=H6.Type=H6.useFunc=H6.setEvaluated=H6.evaluatedPropsToName=H6.mergeEvaluated=H6.eachItem=H6.unescapeJsonPointer=H6.escapeJsonPointer=H6.escapeFragment=H6.unescapeFragment=H6.schemaRefOrVal=H6.schemaHasRulesButRef=H6.schemaHasRules=H6.checkUnknownRules=H6.alwaysValidSchema=H6.toHash=void 0;var $9=t8(),t9Q=YZ();function e9Q(Q){let J={};for(let G of Q)J[G]=!0;return J}H6.toHash=e9Q;function Q1Q(Q,J){if(typeof J=="boolean")return J;if(Object.keys(J).length===0)return!0;return lU0(Q,J),!dU0(J,Q.self.RULES.all)}H6.alwaysValidSchema=Q1Q;function lU0(Q,J=Q.schema){let{opts:G,self:H}=Q;if(!G.strictSchema)return;if(typeof J==="boolean")return;let K=H.RULES.keywords;for(let z in J)if(!K[z])oU0(Q,`unknown keyword: "${z}"`)}H6.checkUnknownRules=lU0;function dU0(Q,J){if(typeof Q=="boolean")return!Q;for(let G in Q)if(J[G])return!0;return!1}H6.schemaHasRules=dU0;function X1Q(Q,J){if(typeof Q=="boolean")return!Q;for(let G in Q)if(G!=="$ref"&&J.all[G])return!0;return!1}H6.schemaHasRulesButRef=X1Q;function J1Q({topSchemaRef:Q,schemaPath:J},G,H,K){if(!K){if(typeof G=="number"||typeof G=="boolean")return G;if(typeof G=="string")return $9._`${G}`}return $9._`${Q}${J}${(0,$9.getProperty)(H)}`}H6.schemaRefOrVal=J1Q;function Y1Q(Q){return cU0(decodeURIComponent(Q))}H6.unescapeFragment=Y1Q;function G1Q(Q){return encodeURIComponent(Ut(Q))}H6.escapeFragment=G1Q;function Ut(Q){if(typeof Q=="number")return`${Q}`;return Q.replace(/~/g,"~0").replace(/\//g,"~1")}H6.escapeJsonPointer=Ut;function cU0(Q){return Q.replace(/~1/g,"/").replace(/~0/g,"~")}H6.unescapeJsonPointer=cU0;function W1Q(Q,J){if(Array.isArray(Q))for(let G of Q)J(G);else J(Q)}H6.eachItem=W1Q;function uU0({mergeNames:Q,mergeToName:J,mergeValues:G,resultToName:H}){return(K,z,q,F)=>{let D=q===void 0?z:q instanceof $9.Name?(z instanceof $9.Name?Q(K,z,q):J(K,z,q),q):z instanceof $9.Name?(J(K,q,z),z):G(z,q);return F===$9.Name&&!(D instanceof $9.Name)?H(K,D):D}}H6.mergeEvaluated={props:uU0({mergeNames:(Q,J,G)=>Q.if($9._`${G} !== true && ${J} !== undefined`,()=>{Q.if($9._`${J} === true`,()=>Q.assign(G,!0),()=>Q.assign(G,$9._`${G} || {}`).code($9._`Object.assign(${G}, ${J})`))}),mergeToName:(Q,J,G)=>Q.if($9._`${G} !== true`,()=>{if(J===!0)Q.assign(G,!0);else Q.assign(G,$9._`${G} || {}`),Zt(Q,G,J)}),mergeValues:(Q,J)=>Q===!0?!0:{...Q,...J},resultToName:iU0}),items:uU0({mergeNames:(Q,J,G)=>Q.if($9._`${G} !== true && ${J} !== undefined`,()=>Q.assign(G,$9._`${J} === true ? true : ${G} > ${J} ? ${G} : ${J}`)),mergeToName:(Q,J,G)=>Q.if($9._`${G} !== true`,()=>Q.assign(G,J===!0?!0:$9._`${G} > ${J} ? ${G} : ${J}`)),mergeValues:(Q,J)=>Q===!0?!0:Math.max(Q,J),resultToName:(Q,J)=>Q.var("items",J)})};function iU0(Q,J){if(J===!0)return Q.var("props",!0);let G=Q.var("props",$9._`{}`);if(J!==void 0)Zt(Q,G,J);return G}H6.evaluatedPropsToName=iU0;function Zt(Q,J,G){Object.keys(G).forEach((H)=>Q.assign($9._`${J}${(0,$9.getProperty)(H)}`,!0))}H6.setEvaluated=Zt;var pU0={};function H1Q(Q,J){return Q.scopeValue("func",{ref:J,code:pU0[J.code]||(pU0[J.code]=new t9Q._Code(J.code))})}H6.useFunc=H1Q;var qt;(function(Q){Q[Q.Num=0]="Num",Q[Q.Str=1]="Str"})(qt||(H6.Type=qt={}));function B1Q(Q,J,G){if(Q instanceof $9.Name){let H=J===qt.Num;return G?H?$9._`"[" + ${Q} + "]"`:$9._`"['" + ${Q} + "']"`:H?$9._`"/" + ${Q}`:$9._`"/" + ${Q}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return G?(0,$9.getProperty)(Q).toString():"/"+Ut(Q)}H6.getErrorPath=B1Q;function oU0(Q,J,G=Q.opts.strictSchema){if(!G)return;if(J=`strict mode: ${J}`,G===!0)throw Error(J);Q.self.logger.warn(J)}H6.checkStrictMode=oU0});var R5=i((Ft)=>{Object.defineProperty(Ft,"__esModule",{value:!0});var mX=t8(),A1Q={data:new mX.Name("data"),valCxt:new mX.Name("valCxt"),instancePath:new mX.Name("instancePath"),parentData:new mX.Name("parentData"),parentDataProperty:new mX.Name("parentDataProperty"),rootData:new mX.Name("rootData"),dynamicAnchors:new mX.Name("dynamicAnchors"),vErrors:new mX.Name("vErrors"),errors:new mX.Name("errors"),this:new mX.Name("this"),self:new mX.Name("self"),scope:new mX.Name("scope"),json:new mX.Name("json"),jsonPos:new mX.Name("jsonPos"),jsonLen:new mX.Name("jsonLen"),jsonPart:new mX.Name("jsonPart")};Ft.default=A1Q});var WZ=i((uX)=>{Object.defineProperty(uX,"__esModule",{value:!0});uX.extendErrors=uX.resetErrorsCount=uX.reportExtraError=uX.reportError=uX.keyword$DataError=uX.keywordError=void 0;var w6=t8(),Uj=R6(),FJ=R5();uX.keywordError={message:({keyword:Q})=>w6.str`must pass "${Q}" keyword validation`};uX.keyword$DataError={message:({keyword:Q,schemaType:J})=>J?w6.str`"${Q}" keyword must be ${J} ($data)`:w6.str`"${Q}" keyword is invalid ($data)`};function K1Q(Q,J=uX.keywordError,G,H){let{it:K}=Q,{gen:z,compositeRule:q,allErrors:F}=K,D=sU0(Q,J,G);if(H!==null&&H!==void 0?H:q||F)nU0(z,D);else aU0(K,w6._`[${D}]`)}uX.reportError=K1Q;function z1Q(Q,J=uX.keywordError,G){let{it:H}=Q,{gen:K,compositeRule:z,allErrors:q}=H,F=sU0(Q,J,G);if(nU0(K,F),!(z||q))aU0(H,FJ.default.vErrors)}uX.reportExtraError=z1Q;function V1Q(Q,J){Q.assign(FJ.default.errors,J),Q.if(w6._`${FJ.default.vErrors} !== null`,()=>Q.if(J,()=>Q.assign(w6._`${FJ.default.vErrors}.length`,J),()=>Q.assign(FJ.default.vErrors,null)))}uX.resetErrorsCount=V1Q;function q1Q({gen:Q,keyword:J,schemaValue:G,data:H,errsCount:K,it:z}){if(K===void 0)throw Error("ajv implementation error");let q=Q.name("err");Q.forRange("i",K,FJ.default.errors,(F)=>{if(Q.const(q,w6._`${FJ.default.vErrors}[${F}]`),Q.if(w6._`${q}.instancePath === undefined`,()=>Q.assign(w6._`${q}.instancePath`,(0,w6.strConcat)(FJ.default.instancePath,z.errorPath))),Q.assign(w6._`${q}.schemaPath`,w6.str`${z.errSchemaPath}/${J}`),z.opts.verbose)Q.assign(w6._`${q}.schema`,G),Q.assign(w6._`${q}.data`,H)})}uX.extendErrors=q1Q;function nU0(Q,J){let G=Q.const("err",J);Q.if(w6._`${FJ.default.vErrors} === null`,()=>Q.assign(FJ.default.vErrors,w6._`[${G}]`),w6._`${FJ.default.vErrors}.push(${G})`),Q.code(w6._`${FJ.default.errors}++`)}function aU0(Q,J){let{gen:G,validateName:H,schemaEnv:K}=Q;if(K.$async)G.throw(w6._`new ${Q.ValidationError}(${J})`);else G.assign(w6._`${H}.errors`,J),G.return(!1)}var w3={keyword:new w6.Name("keyword"),schemaPath:new w6.Name("schemaPath"),params:new w6.Name("params"),propertyName:new w6.Name("propertyName"),message:new w6.Name("message"),schema:new w6.Name("schema"),parentSchema:new w6.Name("parentSchema")};function sU0(Q,J,G){let{createErrors:H}=Q.it;if(H===!1)return w6._`{}`;return U1Q(Q,J,G)}function U1Q(Q,J,G={}){let{gen:H,it:K}=Q,z=[$1Q(K,G),Z1Q(Q,G)];return F1Q(Q,J,z),H.object(...z)}function $1Q({errorPath:Q},{instancePath:J}){let G=J?w6.str`${Q}${(0,Uj.getErrorPath)(J,Uj.Type.Str)}`:Q;return[FJ.default.instancePath,(0,w6.strConcat)(FJ.default.instancePath,G)]}function Z1Q({keyword:Q,it:{errSchemaPath:J}},{schemaPath:G,parentSchema:H}){let K=H?J:w6.str`${J}/${Q}`;if(G)K=w6.str`${K}${(0,Uj.getErrorPath)(G,Uj.Type.Str)}`;return[w3.schemaPath,K]}function F1Q(Q,{params:J,message:G},H){let{keyword:K,data:z,schemaValue:q,it:F}=Q,{opts:D,propertyName:V,topSchemaRef:O,schemaPath:P}=F;if(H.push([w3.keyword,K],[w3.params,typeof J=="function"?J(Q):J||w6._`{}`]),D.messages)H.push([w3.message,typeof G=="function"?G(Q):G]);if(D.verbose)H.push([w3.schema,q],[w3.parentSchema,w6._`${O}${P}`],[FJ.default.data,z]);if(V)H.push([w3.propertyName,V])}});var tU0=i((jz)=>{Object.defineProperty(jz,"__esModule",{value:!0});jz.boolOrEmptySchema=jz.topBoolOrEmptySchema=void 0;var D1Q=WZ(),M1Q=t8(),L1Q=R5(),O1Q={message:"boolean schema is false"};function P1Q(Q){let{gen:J,schema:G,validateName:H}=Q;if(G===!1)rU0(Q,!1);else if(typeof G=="object"&&G.$async===!0)J.return(L1Q.default.data);else J.assign(M1Q._`${H}.errors`,null),J.return(!0)}jz.topBoolOrEmptySchema=P1Q;function N1Q(Q,J){let{gen:G,schema:H}=Q;if(H===!1)G.var(J,!1),rU0(Q);else G.var(J,!0)}jz.boolOrEmptySchema=N1Q;function rU0(Q,J){let{gen:G,data:H}=Q,K={gen:G,keyword:"false schema",data:H,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:Q};(0,D1Q.reportError)(K,O1Q,void 0,J)}});var Dt=i((Cz)=>{Object.defineProperty(Cz,"__esModule",{value:!0});Cz.getRules=Cz.isJSONType=void 0;var j1Q=["string","number","integer","boolean","null","object","array"],C1Q=new Set(j1Q);function I1Q(Q){return typeof Q=="string"&&C1Q.has(Q)}Cz.isJSONType=I1Q;function R1Q(){let Q={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...Q,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},Q.number,Q.string,Q.array,Q.object],post:{rules:[]},all:{},keywords:{}}}Cz.getRules=R1Q});var Mt=i((o4)=>{Object.defineProperty(o4,"__esModule",{value:!0});o4.shouldUseRule=o4.shouldUseGroup=o4.schemaHasRulesForType=void 0;function w1Q({schema:Q,self:J},G){let H=J.RULES.types[G];return H&&H!==!0&&eU0(Q,H)}o4.schemaHasRulesForType=w1Q;function eU0(Q,J){return J.rules.some((G)=>Q$0(Q,G))}o4.shouldUseGroup=eU0;function Q$0(Q,J){var G;return Q[J.keyword]!==void 0||((G=J.definition.implements)===null||G===void 0?void 0:G.some((H)=>Q[H]!==void 0))}o4.shouldUseRule=Q$0});var HZ=i((pX)=>{Object.defineProperty(pX,"__esModule",{value:!0});pX.reportTypeError=pX.checkDataTypes=pX.checkDataType=pX.coerceAndCheckDataType=pX.getJSONTypes=pX.getSchemaTypes=pX.DataType=void 0;var E1Q=Dt(),S1Q=Mt(),T1Q=WZ(),a8=t8(),X$0=R6(),Iz;(function(Q){Q[Q.Correct=0]="Correct",Q[Q.Wrong=1]="Wrong"})(Iz||(pX.DataType=Iz={}));function k1Q(Q){let J=J$0(Q.type);if(J.includes("null")){if(Q.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!J.length&&Q.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(Q.nullable===!0)J.push("null")}return J}pX.getSchemaTypes=k1Q;function J$0(Q){let J=Array.isArray(Q)?Q:Q?[Q]:[];if(J.every(E1Q.isJSONType))return J;throw Error("type must be JSONType or JSONType[]: "+J.join(","))}pX.getJSONTypes=J$0;function y1Q(Q,J){let{gen:G,data:H,opts:K}=Q,z=v1Q(J,K.coerceTypes),q=J.length>0&&!(z.length===0&&J.length===1&&(0,S1Q.schemaHasRulesForType)(Q,J[0]));if(q){let F=Nt(J,H,K.strictNumbers,Iz.Wrong);G.if(F,()=>{if(z.length)x1Q(Q,J,z);else jt(Q)})}return q}pX.coerceAndCheckDataType=y1Q;var Y$0=new Set(["string","number","integer","boolean","null"]);function v1Q(Q,J){return J?Q.filter((G)=>Y$0.has(G)||J==="array"&&G==="array"):[]}function x1Q(Q,J,G){let{gen:H,data:K,opts:z}=Q,q=H.let("dataType",a8._`typeof ${K}`),F=H.let("coerced",a8._`undefined`);if(z.coerceTypes==="array")H.if(a8._`${q} == 'object' && Array.isArray(${K}) && ${K}.length == 1`,()=>H.assign(K,a8._`${K}[0]`).assign(q,a8._`typeof ${K}`).if(Nt(J,K,z.strictNumbers),()=>H.assign(F,K)));H.if(a8._`${F} !== undefined`);for(let V of G)if(Y$0.has(V)||V==="array"&&z.coerceTypes==="array")D(V);H.else(),jt(Q),H.endIf(),H.if(a8._`${F} !== undefined`,()=>{H.assign(K,F),b1Q(Q,F)});function D(V){switch(V){case"string":H.elseIf(a8._`${q} == "number" || ${q} == "boolean"`).assign(F,a8._`"" + ${K}`).elseIf(a8._`${K} === null`).assign(F,a8._`""`);return;case"number":H.elseIf(a8._`${q} == "boolean" || ${K} === null
|| (${q} == "string" && ${K} && ${K} == +${K})`).assign(F,a8._`+${K}`);return;case"integer":H.elseIf(a8._`${q} === "boolean" || ${K} === null
|| (${q} === "string" && ${K} && ${K} == +${K} && !(${K} % 1))`).assign(F,a8._`+${K}`);return;case"boolean":H.elseIf(a8._`${K} === "false" || ${K} === 0 || ${K} === null`).assign(F,!1).elseIf(a8._`${K} === "true" || ${K} === 1`).assign(F,!0);return;case"null":H.elseIf(a8._`${K} === "" || ${K} === 0 || ${K} === false`),H.assign(F,null);return;case"array":H.elseIf(a8._`${q} === "string" || ${q} === "number"
|| ${q} === "boolean" || ${K} === null`).assign(F,a8._`[${K}]`)}}}function b1Q({gen:Q,parentData:J,parentDataProperty:G},H){Q.if(a8._`${J} !== undefined`,()=>Q.assign(a8._`${J}[${G}]`,H))}function Lt(Q,J,G,H=Iz.Correct){let K=H===Iz.Correct?a8.operators.EQ:a8.operators.NEQ,z;switch(Q){case"null":return a8._`${J} ${K} null`;case"array":z=a8._`Array.isArray(${J})`;break;case"object":z=a8._`${J} && typeof ${J} == "object" && !Array.isArray(${J})`;break;case"integer":z=q(a8._`!(${J} % 1) && !isNaN(${J})`);break;case"number":z=q();break;default:return a8._`typeof ${J} ${K} ${Q}`}return H===Iz.Correct?z:(0,a8.not)(z);function q(F=a8.nil){return(0,a8.and)(a8._`typeof ${J} == "number"`,F,G?a8._`isFinite(${J})`:a8.nil)}}pX.checkDataType=Lt;function Nt(Q,J,G,H){if(Q.length===1)return Lt(Q[0],J,G,H);let K,z=(0,X$0.toHash)(Q);if(z.array&&z.object){let q=a8._`typeof ${J} != "object"`;K=z.null?q:a8._`!${J} || ${q}`,delete z.null,delete z.array,delete z.object}else K=a8.nil;if(z.number)delete z.integer;for(let q in z)K=(0,a8.and)(K,Lt(q,J,G,H));return K}pX.checkDataTypes=Nt;var g1Q={message:({schema:Q})=>`must be ${Q}`,params:({schema:Q,schemaValue:J})=>typeof Q=="string"?a8._`{type: ${Q}}`:a8._`{type: ${J}}`};function jt(Q){let J=h1Q(Q);(0,T1Q.reportError)(J,g1Q)}pX.reportTypeError=jt;function h1Q(Q){let{gen:J,data:G,schema:H}=Q,K=(0,X$0.schemaRefOrVal)(Q,H,"type");return{gen:J,keyword:"type",data:G,schema:H.type,schemaCode:K,schemaValue:K,parentSchema:H,params:{},it:Q}}});var W$0=i(($j)=>{Object.defineProperty($j,"__esModule",{value:!0});$j.assignDefaults=void 0;var Rz=t8(),_1Q=R6();function f1Q(Q,J){let{properties:G,items:H}=Q.schema;if(J==="object"&&G)for(let K in G)G$0(Q,K,G[K].default);else if(J==="array"&&Array.isArray(H))H.forEach((K,z)=>G$0(Q,z,K.default))}$j.assignDefaults=f1Q;function G$0(Q,J,G){let{gen:H,compositeRule:K,data:z,opts:q}=Q;if(G===void 0)return;let F=Rz._`${z}${(0,Rz.getProperty)(J)}`;if(K){(0,_1Q.checkStrictMode)(Q,`default is ignored for: ${F}`);return}let D=Rz._`${F} === undefined`;if(q.useDefaults==="empty")D=Rz._`${D} || ${F} === null || ${F} === ""`;H.if(D,Rz._`${F} = ${(0,Rz.stringify)(G)}`)}});var uY=i((B9)=>{Object.defineProperty(B9,"__esModule",{value:!0});B9.validateUnion=B9.validateArray=B9.usePattern=B9.callValidateCode=B9.schemaProperties=B9.allSchemaProperties=B9.noPropertyInData=B9.propertyInData=B9.isOwnProperty=B9.hasPropFunc=B9.reportMissingProp=B9.checkMissingProp=B9.checkReportMissingProp=void 0;var R9=t8(),Ct=R6(),n4=R5(),m1Q=R6();function u1Q(Q,J){let{gen:G,data:H,it:K}=Q;G.if(Rt(G,H,J,K.opts.ownProperties),()=>{Q.setParams({missingProperty:R9._`${J}`},!0),Q.error()})}B9.checkReportMissingProp=u1Q;function p1Q({gen:Q,data:J,it:{opts:G}},H,K){return(0,R9.or)(...H.map((z)=>(0,R9.and)(Rt(Q,J,z,G.ownProperties),R9._`${K} = ${z}`)))}B9.checkMissingProp=p1Q;function l1Q(Q,J){Q.setParams({missingProperty:J},!0),Q.error()}B9.reportMissingProp=l1Q;function H$0(Q){return Q.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:R9._`Object.prototype.hasOwnProperty`})}B9.hasPropFunc=H$0;function It(Q,J,G){return R9._`${H$0(Q)}.call(${J}, ${G})`}B9.isOwnProperty=It;function d1Q(Q,J,G,H){let K=R9._`${J}${(0,R9.getProperty)(G)} !== undefined`;return H?R9._`${K} && ${It(Q,J,G)}`:K}B9.propertyInData=d1Q;function Rt(Q,J,G,H){let K=R9._`${J}${(0,R9.getProperty)(G)} === undefined`;return H?(0,R9.or)(K,(0,R9.not)(It(Q,J,G))):K}B9.noPropertyInData=Rt;function B$0(Q){return Q?Object.keys(Q).filter((J)=>J!=="__proto__"):[]}B9.allSchemaProperties=B$0;function c1Q(Q,J){return B$0(J).filter((G)=>!(0,Ct.alwaysValidSchema)(Q,J[G]))}B9.schemaProperties=c1Q;function i1Q({schemaCode:Q,data:J,it:{gen:G,topSchemaRef:H,schemaPath:K,errorPath:z},it:q},F,D,V){let O=V?R9._`${Q}, ${J}, ${H}${K}`:J,P=[[n4.default.instancePath,(0,R9.strConcat)(n4.default.instancePath,z)],[n4.default.parentData,q.parentData],[n4.default.parentDataProperty,q.parentDataProperty],[n4.default.rootData,n4.default.rootData]];if(q.opts.dynamicRef)P.push([n4.default.dynamicAnchors,n4.default.dynamicAnchors]);let N=R9._`${O}, ${G.object(...P)}`;return D!==R9.nil?R9._`${F}.call(${D}, ${N})`:R9._`${F}(${N})`}B9.callValidateCode=i1Q;var o1Q=R9._`new RegExp`;function n1Q({gen:Q,it:{opts:J}},G){let H=J.unicodeRegExp?"u":"",{regExp:K}=J.code,z=K(G,H);return Q.scopeValue("pattern",{key:z.toString(),ref:z,code:R9._`${K.code==="new RegExp"?o1Q:(0,m1Q.useFunc)(Q,K)}(${G}, ${H})`})}B9.usePattern=n1Q;function a1Q(Q){let{gen:J,data:G,keyword:H,it:K}=Q,z=J.name("valid");if(K.allErrors){let F=J.let("valid",!0);return q(()=>J.assign(F,!1)),F}return J.var(z,!0),q(()=>J.break()),z;function q(F){let D=J.const("len",R9._`${G}.length`);J.forRange("i",0,D,(V)=>{Q.subschema({keyword:H,dataProp:V,dataPropType:Ct.Type.Num},z),J.if((0,R9.not)(z),F)})}}B9.validateArray=a1Q;function s1Q(Q){let{gen:J,schema:G,keyword:H,it:K}=Q;if(!Array.isArray(G))throw Error("ajv implementation error");if(G.some((D)=>(0,Ct.alwaysValidSchema)(K,D))&&!K.opts.unevaluated)return;let q=J.let("valid",!1),F=J.name("_valid");J.block(()=>G.forEach((D,V)=>{let O=Q.subschema({keyword:H,schemaProp:V,compositeRule:!0},F);if(J.assign(q,R9._`${q} || ${F}`),!Q.mergeValidEvaluated(O,F))J.if((0,R9.not)(q))})),Q.result(q,()=>Q.reset(),()=>Q.error(!0))}B9.validateUnion=s1Q});var z$0=i((OW)=>{Object.defineProperty(OW,"__esModule",{value:!0});OW.validateKeywordUsage=OW.validSchemaType=OW.funcKeywordCode=OW.macroKeywordCode=void 0;var DJ=t8(),E3=R5(),r1Q=uY(),t1Q=WZ();function e1Q(Q,J){let{gen:G,keyword:H,schema:K,parentSchema:z,it:q}=Q,F=J.macro.call(q.self,K,z,q),D=K$0(G,H,F);if(q.opts.validateSchema!==!1)q.self.validateSchema(F,!0);let V=G.name("valid");Q.subschema({schema:F,schemaPath:DJ.nil,errSchemaPath:`${q.errSchemaPath}/${H}`,topSchemaRef:D,compositeRule:!0},V),Q.pass(V,()=>Q.error(!0))}OW.macroKeywordCode=e1Q;function Q7Q(Q,J){var G;let{gen:H,keyword:K,schema:z,parentSchema:q,$data:F,it:D}=Q;J7Q(D,J);let V=!F&&J.compile?J.compile.call(D.self,z,q,D):J.validate,O=K$0(H,K,V),P=H.let("valid");Q.block$data(P,N),Q.ok((G=J.valid)!==null&&G!==void 0?G:P);function N(){if(J.errors===!1){if(w(),J.modifying)A$0(Q);E(()=>Q.error())}else{let T=J.async?I():R();if(J.modifying)A$0(Q);E(()=>X7Q(Q,T))}}function I(){let T=H.let("ruleErrs",null);return H.try(()=>w(DJ._`await `),(y)=>H.assign(P,!1).if(DJ._`${y} instanceof ${D.ValidationError}`,()=>H.assign(T,DJ._`${y}.errors`),()=>H.throw(y))),T}function R(){let T=DJ._`${O}.errors`;return H.assign(T,null),w(DJ.nil),T}function w(T=J.async?DJ._`await `:DJ.nil){let y=D.opts.passContext?E3.default.this:E3.default.self,x=!(("compile"in J)&&!F||J.schema===!1);H.assign(P,DJ._`${T}${(0,r1Q.callValidateCode)(Q,O,y,x)}`,J.modifying)}function E(T){var y;H.if((0,DJ.not)((y=J.valid)!==null&&y!==void 0?y:P),T)}}OW.funcKeywordCode=Q7Q;function A$0(Q){let{gen:J,data:G,it:H}=Q;J.if(H.parentData,()=>J.assign(G,DJ._`${H.parentData}[${H.parentDataProperty}]`))}function X7Q(Q,J){let{gen:G}=Q;G.if(DJ._`Array.isArray(${J})`,()=>{G.assign(E3.default.vErrors,DJ._`${E3.default.vErrors} === null ? ${J} : ${E3.default.vErrors}.concat(${J})`).assign(E3.default.errors,DJ._`${E3.default.vErrors}.length`),(0,t1Q.extendErrors)(Q)},()=>Q.error())}function J7Q({schemaEnv:Q},J){if(J.async&&!Q.$async)throw Error("async keyword in sync schema")}function K$0(Q,J,G){if(G===void 0)throw Error(`keyword "${J}" failed to compile`);return Q.scopeValue("keyword",typeof G=="function"?{ref:G}:{ref:G,code:(0,DJ.stringify)(G)})}function Y7Q(Q,J,G=!1){return!J.length||J.some((H)=>H==="array"?Array.isArray(Q):H==="object"?Q&&typeof Q=="object"&&!Array.isArray(Q):typeof Q==H||G&&typeof Q>"u")}OW.validSchemaType=Y7Q;function G7Q({schema:Q,opts:J,self:G,errSchemaPath:H},K,z){if(Array.isArray(K.keyword)?!K.keyword.includes(z):K.keyword!==z)throw Error("ajv implementation error");let q=K.dependencies;if(q===null||q===void 0?void 0:q.some((F)=>!Object.prototype.hasOwnProperty.call(Q,F)))throw Error(`parent schema must have dependencies of ${z}: ${q.join(",")}`);if(K.validateSchema){if(!K.validateSchema(Q[z])){let D=`keyword "${z}" value is invalid at path "${H}": `+G.errorsText(K.validateSchema.errors);if(J.validateSchema==="log")G.logger.error(D);else throw Error(D)}}}OW.validateKeywordUsage=G7Q});var q$0=i((a4)=>{Object.defineProperty(a4,"__esModule",{value:!0});a4.extendSubschemaMode=a4.extendSubschemaData=a4.getSubschema=void 0;var PW=t8(),V$0=R6();function W7Q(Q,{keyword:J,schemaProp:G,schema:H,schemaPath:K,errSchemaPath:z,topSchemaRef:q}){if(J!==void 0&&H!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(J!==void 0){let F=Q.schema[J];return G===void 0?{schema:F,schemaPath:PW._`${Q.schemaPath}${(0,PW.getProperty)(J)}`,errSchemaPath:`${Q.errSchemaPath}/${J}`}:{schema:F[G],schemaPath:PW._`${Q.schemaPath}${(0,PW.getProperty)(J)}${(0,PW.getProperty)(G)}`,errSchemaPath:`${Q.errSchemaPath}/${J}/${(0,V$0.escapeFragment)(G)}`}}if(H!==void 0){if(K===void 0||z===void 0||q===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:H,schemaPath:K,topSchemaRef:q,errSchemaPath:z}}throw Error('either "keyword" or "schema" must be passed')}a4.getSubschema=W7Q;function H7Q(Q,J,{dataProp:G,dataPropType:H,data:K,dataTypes:z,propertyName:q}){if(K!==void 0&&G!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:F}=J;if(G!==void 0){let{errorPath:V,dataPathArr:O,opts:P}=J,N=F.let("data",PW._`${J.data}${(0,PW.getProperty)(G)}`,!0);D(N),Q.errorPath=PW.str`${V}${(0,V$0.getErrorPath)(G,H,P.jsPropertySyntax)}`,Q.parentDataProperty=PW._`${G}`,Q.dataPathArr=[...O,Q.parentDataProperty]}if(K!==void 0){let V=K instanceof PW.Name?K:F.let("data",K,!0);if(D(V),q!==void 0)Q.propertyName=q}if(z)Q.dataTypes=z;function D(V){Q.data=V,Q.dataLevel=J.dataLevel+1,Q.dataTypes=[],J.definedProperties=new Set,Q.parentData=J.data,Q.dataNames=[...J.dataNames,V]}}a4.extendSubschemaData=H7Q;function B7Q(Q,{jtdDiscriminator:J,jtdMetadata:G,compositeRule:H,createErrors:K,allErrors:z}){if(H!==void 0)Q.compositeRule=H;if(K!==void 0)Q.createErrors=K;if(z!==void 0)Q.allErrors=z;Q.jtdDiscriminator=J,Q.jtdMetadata=G}a4.extendSubschemaMode=B7Q});var St=i((rX8,U$0)=>{U$0.exports=function Q(J,G){if(J===G)return!0;if(J&&G&&typeof J=="object"&&typeof G=="object"){if(J.constructor!==G.constructor)return!1;var H,K,z;if(Array.isArray(J)){if(H=J.length,H!=G.length)return!1;for(K=H;K--!==0;)if(!Q(J[K],G[K]))return!1;return!0}if(J.constructor===RegExp)return J.source===G.source&&J.flags===G.flags;if(J.valueOf!==Object.prototype.valueOf)return J.valueOf()===G.valueOf();if(J.toString!==Object.prototype.toString)return J.toString()===G.toString();if(z=Object.keys(J),H=z.length,H!==Object.keys(G).length)return!1;for(K=H;K--!==0;)if(!Object.prototype.hasOwnProperty.call(G,z[K]))return!1;for(K=H;K--!==0;){var q=z[K];if(!Q(J[q],G[q]))return!1}return!0}return J!==J&&G!==G}});var Z$0=i((tX8,$$0)=>{var s4=$$0.exports=function(Q,J,G){if(typeof J=="function")G=J,J={};G=J.cb||G;var H=typeof G=="function"?G:G.pre||function(){},K=G.post||function(){};Zj(J,H,K,Q,"",Q)};s4.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};s4.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};s4.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};s4.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Zj(Q,J,G,H,K,z,q,F,D,V){if(H&&typeof H=="object"&&!Array.isArray(H)){J(H,K,z,q,F,D,V);for(var O in H){var P=H[O];if(Array.isArray(P)){if(O in s4.arrayKeywords)for(var N=0;N<P.length;N++)Zj(Q,J,G,P[N],K+"/"+O+"/"+N,z,K,O,H,N)}else if(O in s4.propsKeywords){if(P&&typeof P=="object")for(var I in P)Zj(Q,J,G,P[I],K+"/"+O+"/"+A7Q(I),z,K,O,H,I)}else if(O in s4.keywords||Q.allKeys&&!(O in s4.skipKeywords))Zj(Q,J,G,P,K+"/"+O,z,K,O,H)}G(H,K,z,q,F,D,V)}}function A7Q(Q){return Q.replace(/~/g,"~0").replace(/\//g,"~1")}});var BZ=i((uJ)=>{Object.defineProperty(uJ,"__esModule",{value:!0});uJ.getSchemaRefs=uJ.resolveUrl=uJ.normalizeId=uJ._getFullPath=uJ.getFullPath=uJ.inlineRef=void 0;var K7Q=R6(),z7Q=St(),V7Q=Z$0(),q7Q=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function U7Q(Q,J=!0){if(typeof Q=="boolean")return!0;if(J===!0)return!kt(Q);if(!J)return!1;return F$0(Q)<=J}uJ.inlineRef=U7Q;var $7Q=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function kt(Q){for(let J in Q){if($7Q.has(J))return!0;let G=Q[J];if(Array.isArray(G)&&G.some(kt))return!0;if(typeof G=="object"&&kt(G))return!0}return!1}function F$0(Q){let J=0;for(let G in Q){if(G==="$ref")return 1/0;if(J++,q7Q.has(G))continue;if(typeof Q[G]=="object")(0,K7Q.eachItem)(Q[G],(H)=>J+=F$0(H));if(J===1/0)return 1/0}return J}function D$0(Q,J="",G){if(G!==!1)J=wz(J);let H=Q.parse(J);return M$0(Q,H)}uJ.getFullPath=D$0;function M$0(Q,J){return Q.serialize(J).split("#")[0]+"#"}uJ._getFullPath=M$0;var Z7Q=/#\/?$/;function wz(Q){return Q?Q.replace(Z7Q,""):""}uJ.normalizeId=wz;function F7Q(Q,J,G){return G=wz(G),Q.resolve(J,G)}uJ.resolveUrl=F7Q;var D7Q=/^[a-z_][-a-z0-9._]*$/i;function M7Q(Q,J){if(typeof Q=="boolean")return{};let{schemaId:G,uriResolver:H}=this.opts,K=wz(Q[G]||J),z={"":K},q=D$0(H,K,!1),F={},D=new Set;return V7Q(Q,{allKeys:!0},(P,N,I,R)=>{if(R===void 0)return;let w=q+N,E=z[R];if(typeof P[G]=="string")E=T.call(this,P[G]);y.call(this,P.$anchor),y.call(this,P.$dynamicAnchor),z[N]=E;function T(x){let b=this.opts.uriResolver.resolve;if(x=wz(E?b(E,x):x),D.has(x))throw O(x);D.add(x);let g=this.refs[x];if(typeof g=="string")g=this.refs[g];if(typeof g=="object")V(P,g.schema,x);else if(x!==wz(w))if(x[0]==="#")V(P,F[x],x),F[x]=P;else this.refs[x]=w;return x}function y(x){if(typeof x=="string"){if(!D7Q.test(x))throw Error(`invalid anchor "${x}"`);T.call(this,`#${x}`)}}}),F;function V(P,N,I){if(N!==void 0&&!z7Q(P,N))throw O(I)}function O(P){return Error(`reference "${P}" resolves to more than one schema`)}}uJ.getSchemaRefs=M7Q});var zZ=i((r4)=>{Object.defineProperty(r4,"__esModule",{value:!0});r4.getData=r4.KeywordCxt=r4.validateFunctionCode=void 0;var j$0=tU0(),L$0=HZ(),xt=Mt(),Fj=HZ(),L7Q=W$0(),KZ=z$0(),vt=q$0(),B8=t8(),b8=R5(),O7Q=BZ(),w5=R6(),AZ=WZ();function P7Q(Q){if(R$0(Q)){if(w$0(Q),I$0(Q)){C7Q(Q);return}}C$0(Q,()=>(0,j$0.topBoolOrEmptySchema)(Q))}r4.validateFunctionCode=P7Q;function C$0({gen:Q,validateName:J,schema:G,schemaEnv:H,opts:K},z){if(K.code.es5)Q.func(J,B8._`${b8.default.data}, ${b8.default.valCxt}`,H.$async,()=>{Q.code(B8._`"use strict"; ${O$0(G,K)}`),j7Q(Q,K),Q.code(z)});else Q.func(J,B8._`${b8.default.data}, ${N7Q(K)}`,H.$async,()=>Q.code(O$0(G,K)).code(z))}function N7Q(Q){return B8._`{${b8.default.instancePath}="", ${b8.default.parentData}, ${b8.default.parentDataProperty}, ${b8.default.rootData}=${b8.default.data}${Q.dynamicRef?B8._`, ${b8.default.dynamicAnchors}={}`:B8.nil}}={}`}function j7Q(Q,J){Q.if(b8.default.valCxt,()=>{if(Q.var(b8.default.instancePath,B8._`${b8.default.valCxt}.${b8.default.instancePath}`),Q.var(b8.default.parentData,B8._`${b8.default.valCxt}.${b8.default.parentData}`),Q.var(b8.default.parentDataProperty,B8._`${b8.default.valCxt}.${b8.default.parentDataProperty}`),Q.var(b8.default.rootData,B8._`${b8.default.valCxt}.${b8.default.rootData}`),J.dynamicRef)Q.var(b8.default.dynamicAnchors,B8._`${b8.default.valCxt}.${b8.default.dynamicAnchors}`)},()=>{if(Q.var(b8.default.instancePath,B8._`""`),Q.var(b8.default.parentData,B8._`undefined`),Q.var(b8.default.parentDataProperty,B8._`undefined`),Q.var(b8.default.rootData,b8.default.data),J.dynamicRef)Q.var(b8.default.dynamicAnchors,B8._`{}`)})}function C7Q(Q){let{schema:J,opts:G,gen:H}=Q;C$0(Q,()=>{if(G.$comment&&J.$comment)S$0(Q);if(S7Q(Q),H.let(b8.default.vErrors,null),H.let(b8.default.errors,0),G.unevaluated)I7Q(Q);E$0(Q),y7Q(Q)});return}function I7Q(Q){let{gen:J,validateName:G}=Q;Q.evaluated=J.const("evaluated",B8._`${G}.evaluated`),J.if(B8._`${Q.evaluated}.dynamicProps`,()=>J.assign(B8._`${Q.evaluated}.props`,B8._`undefined`)),J.if(B8._`${Q.evaluated}.dynamicItems`,()=>J.assign(B8._`${Q.evaluated}.items`,B8._`undefined`))}function O$0(Q,J){let G=typeof Q=="object"&&Q[J.schemaId];return G&&(J.code.source||J.code.process)?B8._`/*# sourceURL=${G} */`:B8.nil}function R7Q(Q,J){if(R$0(Q)){if(w$0(Q),I$0(Q)){w7Q(Q,J);return}}(0,j$0.boolOrEmptySchema)(Q,J)}function I$0({schema:Q,self:J}){if(typeof Q=="boolean")return!Q;for(let G in Q)if(J.RULES.all[G])return!0;return!1}function R$0(Q){return typeof Q.schema!="boolean"}function w7Q(Q,J){let{schema:G,gen:H,opts:K}=Q;if(K.$comment&&G.$comment)S$0(Q);T7Q(Q),k7Q(Q);let z=H.const("_errs",b8.default.errors);E$0(Q,z),H.var(J,B8._`${z} === ${b8.default.errors}`)}function w$0(Q){(0,w5.checkUnknownRules)(Q),E7Q(Q)}function E$0(Q,J){if(Q.opts.jtd)return P$0(Q,[],!1,J);let G=(0,L$0.getSchemaTypes)(Q.schema),H=(0,L$0.coerceAndCheckDataType)(Q,G);P$0(Q,G,!H,J)}function E7Q(Q){let{schema:J,errSchemaPath:G,opts:H,self:K}=Q;if(J.$ref&&H.ignoreKeywordsWithRef&&(0,w5.schemaHasRulesButRef)(J,K.RULES))K.logger.warn(`$ref: keywords ignored in schema at path "${G}"`)}function S7Q(Q){let{schema:J,opts:G}=Q;if(J.default!==void 0&&G.useDefaults&&G.strictSchema)(0,w5.checkStrictMode)(Q,"default is ignored in the schema root")}function T7Q(Q){let J=Q.schema[Q.opts.schemaId];if(J)Q.baseId=(0,O7Q.resolveUrl)(Q.opts.uriResolver,Q.baseId,J)}function k7Q(Q){if(Q.schema.$async&&!Q.schemaEnv.$async)throw Error("async schema in sync schema")}function S$0({gen:Q,schemaEnv:J,schema:G,errSchemaPath:H,opts:K}){let z=G.$comment;if(K.$comment===!0)Q.code(B8._`${b8.default.self}.logger.log(${z})`);else if(typeof K.$comment=="function"){let q=B8.str`${H}/$comment`,F=Q.scopeValue("root",{ref:J.root});Q.code(B8._`${b8.default.self}.opts.$comment(${z}, ${q}, ${F}.schema)`)}}function y7Q(Q){let{gen:J,schemaEnv:G,validateName:H,ValidationError:K,opts:z}=Q;if(G.$async)J.if(B8._`${b8.default.errors} === 0`,()=>J.return(b8.default.data),()=>J.throw(B8._`new ${K}(${b8.default.vErrors})`));else{if(J.assign(B8._`${H}.errors`,b8.default.vErrors),z.unevaluated)v7Q(Q);J.return(B8._`${b8.default.errors} === 0`)}}function v7Q({gen:Q,evaluated:J,props:G,items:H}){if(G instanceof B8.Name)Q.assign(B8._`${J}.props`,G);if(H instanceof B8.Name)Q.assign(B8._`${J}.items`,H)}function P$0(Q,J,G,H){let{gen:K,schema:z,data:q,allErrors:F,opts:D,self:V}=Q,{RULES:O}=V;if(z.$ref&&(D.ignoreKeywordsWithRef||!(0,w5.schemaHasRulesButRef)(z,O))){K.block(()=>k$0(Q,"$ref",O.all.$ref.definition));return}if(!D.jtd)x7Q(Q,J);K.block(()=>{for(let N of O.rules)P(N);P(O.post)});function P(N){if(!(0,xt.shouldUseGroup)(z,N))return;if(N.type){if(K.if((0,Fj.checkDataType)(N.type,q,D.strictNumbers)),N$0(Q,N),J.length===1&&J[0]===N.type&&G)K.else(),(0,Fj.reportTypeError)(Q);K.endIf()}else N$0(Q,N);if(!F)K.if(B8._`${b8.default.errors} === ${H||0}`)}}function N$0(Q,J){let{gen:G,schema:H,opts:{useDefaults:K}}=Q;if(K)(0,L7Q.assignDefaults)(Q,J.type);G.block(()=>{for(let z of J.rules)if((0,xt.shouldUseRule)(H,z))k$0(Q,z.keyword,z.definition,J.type)})}function x7Q(Q,J){if(Q.schemaEnv.meta||!Q.opts.strictTypes)return;if(b7Q(Q,J),!Q.opts.allowUnionTypes)g7Q(Q,J);h7Q(Q,Q.dataTypes)}function b7Q(Q,J){if(!J.length)return;if(!Q.dataTypes.length){Q.dataTypes=J;return}J.forEach((G)=>{if(!T$0(Q.dataTypes,G))ft(Q,`type "${G}" not allowed by context "${Q.dataTypes.join(",")}"`)}),f7Q(Q,J)}function g7Q(Q,J){if(J.length>1&&!(J.length===2&&J.includes("null")))ft(Q,"use allowUnionTypes to allow union type keyword")}function h7Q(Q,J){let G=Q.self.RULES.all;for(let H in G){let K=G[H];if(typeof K=="object"&&(0,xt.shouldUseRule)(Q.schema,K)){let{type:z}=K.definition;if(z.length&&!z.some((q)=>_7Q(J,q)))ft(Q,`missing type "${z.join(",")}" for keyword "${H}"`)}}}function _7Q(Q,J){return Q.includes(J)||J==="number"&&Q.includes("integer")}function T$0(Q,J){return Q.includes(J)||J==="integer"&&Q.includes("number")}function f7Q(Q,J){let G=[];for(let H of Q.dataTypes)if(T$0(J,H))G.push(H);else if(J.includes("integer")&&H==="number")G.push("integer");Q.dataTypes=G}function ft(Q,J){let G=Q.schemaEnv.baseId+Q.errSchemaPath;J+=` at "${G}" (strictTypes)`,(0,w5.checkStrictMode)(Q,J,Q.opts.strictTypes)}class mt{constructor(Q,J,G){if((0,KZ.validateKeywordUsage)(Q,J,G),this.gen=Q.gen,this.allErrors=Q.allErrors,this.keyword=G,this.data=Q.data,this.schema=Q.schema[G],this.$data=J.$data&&Q.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,w5.schemaRefOrVal)(Q,this.schema,G,this.$data),this.schemaType=J.schemaType,this.parentSchema=Q.schema,this.params={},this.it=Q,this.def=J,this.$data)this.schemaCode=Q.gen.const("vSchema",y$0(this.$data,Q));else if(this.schemaCode=this.schemaValue,!(0,KZ.validSchemaType)(this.schema,J.schemaType,J.allowUndefined))throw Error(`${G} value must be ${JSON.stringify(J.schemaType)}`);if("code"in J?J.trackErrors:J.errors!==!1)this.errsCount=Q.gen.const("_errs",b8.default.errors)}result(Q,J,G){this.failResult((0,B8.not)(Q),J,G)}failResult(Q,J,G){if(this.gen.if(Q),G)G();else this.error();if(J){if(this.gen.else(),J(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(Q,J){this.failResult((0,B8.not)(Q),void 0,J)}fail(Q){if(Q===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(Q),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(Q){if(!this.$data)return this.fail(Q);let{schemaCode:J}=this;this.fail(B8._`${J} !== undefined && (${(0,B8.or)(this.invalid$data(),Q)})`)}error(Q,J,G){if(J){this.setParams(J),this._error(Q,G),this.setParams({});return}this._error(Q,G)}_error(Q,J){(Q?AZ.reportExtraError:AZ.reportError)(this,this.def.error,J)}$dataError(){(0,AZ.reportError)(this,this.def.$dataError||AZ.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,AZ.resetErrorsCount)(this.gen,this.errsCount)}ok(Q){if(!this.allErrors)this.gen.if(Q)}setParams(Q,J){if(J)Object.assign(this.params,Q);else this.params=Q}block$data(Q,J,G=B8.nil){this.gen.block(()=>{this.check$data(Q,G),J()})}check$data(Q=B8.nil,J=B8.nil){if(!this.$data)return;let{gen:G,schemaCode:H,schemaType:K,def:z}=this;if(G.if((0,B8.or)(B8._`${H} === undefined`,J)),Q!==B8.nil)G.assign(Q,!0);if(K.length||z.validateSchema){if(G.elseIf(this.invalid$data()),this.$dataError(),Q!==B8.nil)G.assign(Q,!1)}G.else()}invalid$data(){let{gen:Q,schemaCode:J,schemaType:G,def:H,it:K}=this;return(0,B8.or)(z(),q());function z(){if(G.length){if(!(J instanceof B8.Name))throw Error("ajv implementation error");let F=Array.isArray(G)?G:[G];return B8._`${(0,Fj.checkDataTypes)(F,J,K.opts.strictNumbers,Fj.DataType.Wrong)}`}return B8.nil}function q(){if(H.validateSchema){let F=Q.scopeValue("validate$data",{ref:H.validateSchema});return B8._`!${F}(${J})`}return B8.nil}}subschema(Q,J){let G=(0,vt.getSubschema)(this.it,Q);(0,vt.extendSubschemaData)(G,this.it,Q),(0,vt.extendSubschemaMode)(G,Q);let H={...this.it,...G,items:void 0,props:void 0};return R7Q(H,J),H}mergeEvaluated(Q,J){let{it:G,gen:H}=this;if(!G.opts.unevaluated)return;if(G.props!==!0&&Q.props!==void 0)G.props=w5.mergeEvaluated.props(H,Q.props,G.props,J);if(G.items!==!0&&Q.items!==void 0)G.items=w5.mergeEvaluated.items(H,Q.items,G.items,J)}mergeValidEvaluated(Q,J){let{it:G,gen:H}=this;if(G.opts.unevaluated&&(G.props!==!0||G.items!==!0))return H.if(J,()=>this.mergeEvaluated(Q,B8.Name)),!0}}r4.KeywordCxt=mt;function k$0(Q,J,G,H){let K=new mt(Q,G,J);if("code"in G)G.code(K,H);else if(K.$data&&G.validate)(0,KZ.funcKeywordCode)(K,G);else if("macro"in G)(0,KZ.macroKeywordCode)(K,G);else if(G.compile||G.validate)(0,KZ.funcKeywordCode)(K,G)}var m7Q=/^\/(?:[^~]|~0|~1)*$/,u7Q=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function y$0(Q,{dataLevel:J,dataNames:G,dataPathArr:H}){let K,z;if(Q==="")return b8.default.rootData;if(Q[0]==="/"){if(!m7Q.test(Q))throw Error(`Invalid JSON-pointer: ${Q}`);K=Q,z=b8.default.rootData}else{let V=u7Q.exec(Q);if(!V)throw Error(`Invalid JSON-pointer: ${Q}`);let O=+V[1];if(K=V[2],K==="#"){if(O>=J)throw Error(D("property/index",O));return H[J-O]}if(O>J)throw Error(D("data",O));if(z=G[J-O],!K)return z}let q=z,F=K.split("/");for(let V of F)if(V)z=B8._`${z}${(0,B8.getProperty)((0,w5.unescapeJsonPointer)(V))}`,q=B8._`${q} && ${z}`;return q;function D(V,O){return`Cannot access ${V} ${O} levels up, current level is ${J}`}}r4.getData=y$0});var Dj=i((ot)=>{Object.defineProperty(ot,"__esModule",{value:!0});class v$0 extends Error{constructor(Q){super("validation failed");this.errors=Q,this.ajv=this.validation=!0}}ot.default=v$0});var VZ=i((rt)=>{Object.defineProperty(rt,"__esModule",{value:!0});var st=BZ();class x$0 extends Error{constructor(Q,J,G,H){super(H||`can't resolve reference ${G} from id ${J}`);this.missingRef=(0,st.resolveUrl)(Q,J,G),this.missingSchema=(0,st.normalizeId)((0,st.getFullPath)(Q,this.missingRef))}}rt.default=x$0});var Lj=i((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});pY.resolveSchema=pY.getCompilingSchema=pY.resolveRef=pY.compileSchema=pY.SchemaEnv=void 0;var NG=t8(),p7Q=Dj(),S3=R5(),jG=BZ(),b$0=R6(),l7Q=zZ();class qZ{constructor(Q){var J;this.refs={},this.dynamicAnchors={};let G;if(typeof Q.schema=="object")G=Q.schema;this.schema=Q.schema,this.schemaId=Q.schemaId,this.root=Q.root||this,this.baseId=(J=Q.baseId)!==null&&J!==void 0?J:(0,jG.normalizeId)(G===null||G===void 0?void 0:G[Q.schemaId||"$id"]),this.schemaPath=Q.schemaPath,this.localRefs=Q.localRefs,this.meta=Q.meta,this.$async=G===null||G===void 0?void 0:G.$async,this.refs={}}}pY.SchemaEnv=qZ;function Ae(Q){let J=g$0.call(this,Q);if(J)return J;let G=(0,jG.getFullPath)(this.opts.uriResolver,Q.root.baseId),{es5:H,lines:K}=this.opts.code,{ownProperties:z}=this.opts,q=new NG.CodeGen(this.scope,{es5:H,lines:K,ownProperties:z}),F;if(Q.$async)F=q.scopeValue("Error",{ref:p7Q.default,code:NG._`require("ajv/dist/runtime/validation_error").default`});let D=q.scopeName("validate");Q.validateName=D;let V={gen:q,allErrors:this.opts.allErrors,data:S3.default.data,parentData:S3.default.parentData,parentDataProperty:S3.default.parentDataProperty,dataNames:[S3.default.data],dataPathArr:[NG.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:q.scopeValue("schema",this.opts.code.source===!0?{ref:Q.schema,code:(0,NG.stringify)(Q.schema)}:{ref:Q.schema}),validateName:D,ValidationError:F,schema:Q.schema,schemaEnv:Q,rootId:G,baseId:Q.baseId||G,schemaPath:NG.nil,errSchemaPath:Q.schemaPath||(this.opts.jtd?"":"#"),errorPath:NG._`""`,opts:this.opts,self:this},O;try{this._compilations.add(Q),(0,l7Q.validateFunctionCode)(V),q.optimize(this.opts.code.optimize);let P=q.toString();if(O=`${q.scopeRefs(S3.default.scope)}return ${P}`,this.opts.code.process)O=this.opts.code.process(O,Q);let I=Function(`${S3.default.self}`,`${S3.default.scope}`,O)(this,this.scope.get());if(this.scope.value(D,{ref:I}),I.errors=null,I.schema=Q.schema,I.schemaEnv=Q,Q.$async)I.$async=!0;if(this.opts.code.source===!0)I.source={validateName:D,validateCode:P,scopeValues:q._values};if(this.opts.unevaluated){let{props:R,items:w}=V;if(I.evaluated={props:R instanceof NG.Name?void 0:R,items:w instanceof NG.Name?void 0:w,dynamicProps:R instanceof NG.Name,dynamicItems:w instanceof NG.Name},I.source)I.source.evaluated=(0,NG.stringify)(I.evaluated)}return Q.validate=I,Q}catch(P){if(delete Q.validate,delete Q.validateName,O)this.logger.error("Error compiling schema, function code:",O);throw P}finally{this._compilations.delete(Q)}}pY.compileSchema=Ae;function d7Q(Q,J,G){var H;G=(0,jG.resolveUrl)(this.opts.uriResolver,J,G);let K=Q.refs[G];if(K)return K;let z=o7Q.call(this,Q,G);if(z===void 0){let q=(H=Q.localRefs)===null||H===void 0?void 0:H[G],{schemaId:F}=this.opts;if(q)z=new qZ({schema:q,schemaId:F,root:Q,baseId:J})}if(z===void 0)return;return Q.refs[G]=c7Q.call(this,z)}pY.resolveRef=d7Q;function c7Q(Q){if((0,jG.inlineRef)(Q.schema,this.opts.inlineRefs))return Q.schema;return Q.validate?Q:Ae.call(this,Q)}function g$0(Q){for(let J of this._compilations)if(i7Q(J,Q))return J}pY.getCompilingSchema=g$0;function i7Q(Q,J){return Q.schema===J.schema&&Q.root===J.root&&Q.baseId===J.baseId}function o7Q(Q,J){let G;while(typeof(G=this.refs[J])=="string")J=G;return G||this.schemas[J]||Mj.call(this,Q,J)}function Mj(Q,J){let G=this.opts.uriResolver.parse(J),H=(0,jG._getFullPath)(this.opts.uriResolver,G),K=(0,jG.getFullPath)(this.opts.uriResolver,Q.baseId,void 0);if(Object.keys(Q.schema).length>0&&H===K)return Xe.call(this,G,Q);let z=(0,jG.normalizeId)(H),q=this.refs[z]||this.schemas[z];if(typeof q=="string"){let F=Mj.call(this,Q,q);if(typeof(F===null||F===void 0?void 0:F.schema)!=="object")return;return Xe.call(this,G,F)}if(typeof(q===null||q===void 0?void 0:q.schema)!=="object")return;if(!q.validate)Ae.call(this,q);if(z===(0,jG.normalizeId)(J)){let{schema:F}=q,{schemaId:D}=this.opts,V=F[D];if(V)K=(0,jG.resolveUrl)(this.opts.uriResolver,K,V);return new qZ({schema:F,schemaId:D,root:Q,baseId:K})}return Xe.call(this,G,q)}pY.resolveSchema=Mj;var n7Q=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Xe(Q,{baseId:J,schema:G,root:H}){var K;if(((K=Q.fragment)===null||K===void 0?void 0:K[0])!=="/")return;for(let F of Q.fragment.slice(1).split("/")){if(typeof G==="boolean")return;let D=G[(0,b$0.unescapeFragment)(F)];if(D===void 0)return;G=D;let V=typeof G==="object"&&G[this.opts.schemaId];if(!n7Q.has(F)&&V)J=(0,jG.resolveUrl)(this.opts.uriResolver,J,V)}let z;if(typeof G!="boolean"&&G.$ref&&!(0,b$0.schemaHasRulesButRef)(G,this.RULES)){let F=(0,jG.resolveUrl)(this.opts.uriResolver,J,G.$ref);z=Mj.call(this,H,F)}let{schemaId:q}=this.opts;if(z=z||new qZ({schema:G,schemaId:q,root:H,baseId:J}),z.schema!==z.root.schema)return z;return}});var h$0=i((GJ8,a7Q)=>{a7Q.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var $e=i((WJ8,l$0)=>{var s7Q=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),f$0=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),Ke=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),m$0=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),r7Q=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ue(Q){let J="",G=0,H=0;for(H=0;H<Q.length;H++){if(G=Q[H].charCodeAt(0),G===48)continue;if(!(G>=48&&G<=57||G>=65&&G<=70||G>=97&&G<=102))return"";J+=Q[H];break}for(H+=1;H<Q.length;H++){if(G=Q[H].charCodeAt(0),!(G>=48&&G<=57||G>=65&&G<=70||G>=97&&G<=102))return"";J+=Q[H]}return J}var t7Q=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _$0(Q){return Q.length=0,!0}function e7Q(Q,J,G){if(Q.length){let H=Ue(Q);if(H!=="")J.push(H);else return G.error=!0,!1;Q.length=0}return!0}function QXQ(Q){let J=0,G={error:!1,address:"",zone:""},H=[],K=[],z=!1,q=!1,F=e7Q;for(let D=0;D<Q.length;D++){let V=Q[D];if(V==="["||V==="]")continue;if(V===":"){if(z===!0)q=!0;if(!F(K,H,G))break;if(++J>7){G.error=!0;break}if(D>0&&Q[D-1]===":")z=!0;H.push(":");continue}else if(V==="%"){if(!F(K,H,G))break;F=_$0}else{K.push(V);continue}}if(K.length)if(F===_$0)G.zone=K.join("");else if(q)H.push(K.join(""));else H.push(Ue(K));return G.address=H.join(""),G}function u$0(Q){if(XXQ(Q,":")<2)return{host:Q,isIPV6:!1};let J=QXQ(Q);if(!J.error){let{address:G,address:H}=J;if(J.zone)G+="%"+J.zone,H+="%25"+J.zone;return{host:G,isIPV6:!0,escapedHost:H}}else return{host:Q,isIPV6:!1}}function XXQ(Q,J){let G=0;for(let H=0;H<Q.length;H++)if(Q[H]===J)G++;return G}function JXQ(Q){let J=Q,G=[],H=-1,K=0;while(K=J.length){if(K===1)if(J===".")break;else if(J==="/"){G.push("/");break}else{G.push(J);break}else if(K===2){if(J[0]==="."){if(J[1]===".")break;else if(J[1]==="/"){J=J.slice(2);continue}}else if(J[0]==="/"){if(J[1]==="."||J[1]==="/"){G.push("/");break}}}else if(K===3){if(J==="/.."){if(G.length!==0)G.pop();G.push("/");break}}if(J[0]==="."){if(J[1]==="."){if(J[2]==="/"){J=J.slice(3);continue}}else if(J[1]==="/"){J=J.slice(2);continue}}else if(J[0]==="/"){if(J[1]==="."){if(J[2]==="/"){J=J.slice(2);continue}else if(J[2]==="."){if(J[3]==="/"){if(J=J.slice(3),G.length!==0)G.pop();continue}}}}if((H=J.indexOf("/",1))===-1){G.push(J);break}else G.push(J.slice(0,H)),J=J.slice(H)}return G.join("")}var YXQ={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},GXQ=/[@/?#:]/g,WXQ=/[@/?#]/g;function p$0(Q,J){let G=J?WXQ:GXQ;return G.lastIndex=0,Q.replace(G,(H)=>YXQ[H])}function HXQ(Q,J=!1){if(Q.indexOf("%")===-1)return Q;let G="";for(let H=0;H<Q.length;H++){if(Q[H]==="%"&&H+2<Q.length){let K=Q.slice(H+1,H+3);if(Ke(K)){let z=K.toUpperCase(),q=String.fromCharCode(parseInt(z,16));if(J&&m$0(q))G+=q;else G+="%"+z;H+=2;continue}}G+=Q[H]}return G}function BXQ(Q){let J="";for(let G=0;G<Q.length;G++){if(Q[G]==="%"&&G+2<Q.length){let H=Q.slice(G+1,G+3);if(Ke(H)){let K=H.toUpperCase(),z=String.fromCharCode(parseInt(K,16));if(z!=="."&&m$0(z))J+=z;else J+="%"+K;G+=2;continue}}if(r7Q(Q[G]))J+=Q[G];else J+=escape(Q[G])}return J}function AXQ(Q){let J="";for(let G=0;G<Q.length;G++){if(Q[G]==="%"&&G+2<Q.length){let H=Q.slice(G+1,G+3);if(Ke(H)){J+="%"+H.toUpperCase(),G+=2;continue}}J+=escape(Q[G])}return J}function KXQ(Q){let J=[];if(Q.userinfo!==void 0)J.push(Q.userinfo),J.push("@");if(Q.host!==void 0){let G=unescape(Q.host);if(!f$0(G)){let H=u$0(G);if(H.isIPV6===!0)G=`[${H.escapedHost}]`;else G=p$0(G,!1)}J.push(G)}if(typeof Q.port==="number"||typeof Q.port==="string")J.push(":"),J.push(String(Q.port));return J.length?J.join(""):void 0}l$0.exports={nonSimpleDomain:t7Q,recomposeAuthority:KXQ,reescapeHostDelimiters:p$0,normalizePercentEncoding:HXQ,normalizePathEncoding:BXQ,escapePreservingEscapes:AXQ,removeDotSegments:JXQ,isIPv4:f$0,isUUID:s7Q,normalizeIPv6:u$0,stringArrayToHexStripped:Ue}});var n$0=i((HJ8,o$0)=>{var{isUUID:zXQ}=$e(),VXQ=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,qXQ=["http","https","ws","wss","urn","urn:uuid"];function UXQ(Q){return qXQ.indexOf(Q)!==-1}function Le(Q){if(Q.secure===!0)return!0;else if(Q.secure===!1)return!1;else if(Q.scheme)return Q.scheme.length===3&&(Q.scheme[0]==="w"||Q.scheme[0]==="W")&&(Q.scheme[1]==="s"||Q.scheme[1]==="S")&&(Q.scheme[2]==="s"||Q.scheme[2]==="S");else return!1}function d$0(Q){if(!Q.host)Q.error=Q.error||"HTTP URIs must have a host.";return Q}function c$0(Q){let J=String(Q.scheme).toLowerCase()==="https";if(Q.port===(J?443:80)||Q.port==="")Q.port=void 0;if(!Q.path)Q.path="/";return Q}function $XQ(Q){return Q.secure=Le(Q),Q.resourceName=(Q.path||"/")+(Q.query?"?"+Q.query:""),Q.path=void 0,Q.query=void 0,Q}function ZXQ(Q){if(Q.port===(Le(Q)?443:80)||Q.port==="")Q.port=void 0;if(typeof Q.secure==="boolean")Q.scheme=Q.secure?"wss":"ws",Q.secure=void 0;if(Q.resourceName){let[J,G]=Q.resourceName.split("?");Q.path=J&&J!=="/"?J:void 0,Q.query=G,Q.resourceName=void 0}return Q.fragment=void 0,Q}function FXQ(Q,J){if(!Q.path)return Q.error="URN can not be parsed",Q;let G=Q.path.match(VXQ);if(G){let H=J.scheme||Q.scheme||"urn";Q.nid=G[1].toLowerCase(),Q.nss=G[2];let K=`${H}:${J.nid||Q.nid}`,z=Oe(K);if(Q.path=void 0,z)Q=z.parse(Q,J)}else Q.error=Q.error||"URN can not be parsed.";return Q}function DXQ(Q,J){if(Q.nid===void 0)throw Error("URN without nid cannot be serialized");let G=J.scheme||Q.scheme||"urn",H=Q.nid.toLowerCase(),K=`${G}:${J.nid||H}`,z=Oe(K);if(z)Q=z.serialize(Q,J);let q=Q,F=Q.nss;return q.path=`${H||J.nid}:${F}`,J.skipEscape=!0,q}function MXQ(Q,J){let G=Q;if(G.uuid=G.nss,G.nss=void 0,!J.tolerant&&(!G.uuid||!zXQ(G.uuid)))G.error=G.error||"UUID is not valid.";return G}function LXQ(Q){let J=Q;return J.nss=(Q.uuid||"").toLowerCase(),J}var i$0={scheme:"http",domainHost:!0,parse:d$0,serialize:c$0},OXQ={scheme:"https",domainHost:i$0.domainHost,parse:d$0,serialize:c$0},Oj={scheme:"ws",domainHost:!0,parse:$XQ,serialize:ZXQ},PXQ={scheme:"wss",domainHost:Oj.domainHost,parse:Oj.parse,serialize:Oj.serialize},NXQ={scheme:"urn",parse:FXQ,serialize:DXQ,skipNormalize:!0},jXQ={scheme:"urn:uuid",parse:MXQ,serialize:LXQ,skipNormalize:!0},Pj={http:i$0,https:OXQ,ws:Oj,wss:PXQ,urn:NXQ,"urn:uuid":jXQ};Object.setPrototypeOf(Pj,null);function Oe(Q){return Q&&(Pj[Q]||Pj[Q.toLowerCase()])||void 0}o$0.exports={wsIsSecure:Le,SCHEMES:Pj,isValidSchemeName:UXQ,getSchemeHandler:Oe}});var QZ0=i((BJ8,Nj)=>{var{normalizeIPv6:CXQ,removeDotSegments:UZ,recomposeAuthority:IXQ,normalizePercentEncoding:RXQ,normalizePathEncoding:wXQ,escapePreservingEscapes:EXQ,reescapeHostDelimiters:SXQ,isIPv4:TXQ,nonSimpleDomain:kXQ}=$e(),{SCHEMES:yXQ,getSchemeHandler:s$0}=n$0();function vXQ(Q,J){if(typeof Q==="string")Q=_XQ(Q,J);else if(typeof Q==="object")Q=Ez(T3(Q,J),J);return Q}function xXQ(Q,J,G){let H=G?Object.assign({scheme:"null"},G):{scheme:"null"},K=r$0(Ez(Q,H),Ez(J,H),H,!0);return H.skipEscape=!0,T3(K,H)}function r$0(Q,J,G,H){let K={};if(!H)Q=Ez(T3(Q,G),G),J=Ez(T3(J,G),G);if(G=G||{},!G.tolerant&&J.scheme)K.scheme=J.scheme,K.userinfo=J.userinfo,K.host=J.host,K.port=J.port,K.path=UZ(J.path||""),K.query=J.query;else{if(J.userinfo!==void 0||J.host!==void 0||J.port!==void 0)K.userinfo=J.userinfo,K.host=J.host,K.port=J.port,K.path=UZ(J.path||""),K.query=J.query;else{if(!J.path)if(K.path=Q.path,J.query!==void 0)K.query=J.query;else K.query=Q.query;else{if(J.path[0]==="/")K.path=UZ(J.path);else{if((Q.userinfo!==void 0||Q.host!==void 0||Q.port!==void 0)&&!Q.path)K.path="/"+J.path;else if(!Q.path)K.path=J.path;else K.path=Q.path.slice(0,Q.path.lastIndexOf("/")+1)+J.path;K.path=UZ(K.path)}K.query=J.query}K.userinfo=Q.userinfo,K.host=Q.host,K.port=Q.port}K.scheme=Q.scheme}return K.fragment=J.fragment,K}function bXQ(Q,J,G){let H=a$0(Q,G),K=a$0(J,G);return H!==void 0&&K!==void 0&&H.toLowerCase()===K.toLowerCase()}function T3(Q,J){let G={host:Q.host,scheme:Q.scheme,userinfo:Q.userinfo,port:Q.port,path:Q.path,query:Q.query,nid:Q.nid,nss:Q.nss,uuid:Q.uuid,fragment:Q.fragment,reference:Q.reference,resourceName:Q.resourceName,secure:Q.secure,error:""},H=Object.assign({},J),K=[],z=s$0(H.scheme||G.scheme);if(z&&z.serialize)z.serialize(G,H);if(G.path!==void 0)if(!H.skipEscape){if(G.path=EXQ(G.path),G.scheme!==void 0)G.path=G.path.split("%3A").join(":")}else G.path=RXQ(G.path);if(H.reference!=="suffix"&&G.scheme)K.push(G.scheme,":");let q=IXQ(G);if(q!==void 0){if(H.reference!=="suffix")K.push("//");if(K.push(q),G.path&&G.path[0]!=="/")K.push("/")}if(G.path!==void 0){let F=G.path;if(!H.absolutePath&&(!z||!z.absolutePath))F=UZ(F);if(q===void 0&&F[0]==="/"&&F[1]==="/")F="/%2F"+F.slice(2);K.push(F)}if(G.query!==void 0)K.push("?",G.query);if(G.fragment!==void 0)K.push("#",G.fragment);return K.join("")}var gXQ=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function hXQ(Q,J){if(J[2]!==void 0&&Q.path&&Q.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof Q.port==="number"&&(Q.port<0||Q.port>65535))return"URI port is malformed.";return}function t$0(Q,J){let G=Object.assign({},J),H={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},K=!1,z=!1;if(G.reference==="suffix")if(G.scheme)Q=G.scheme+":"+Q;else Q="//"+Q;let q=Q.match(gXQ);if(q){if(H.scheme=q[1],H.userinfo=q[3],H.host=q[4],H.port=parseInt(q[5],10),H.path=q[6]||"",H.query=q[7],H.fragment=q[8],isNaN(H.port))H.port=q[5];let F=hXQ(H,q);if(F!==void 0)H.error=H.error||F,K=!0;if(H.host)if(TXQ(H.host)===!1){let O=CXQ(H.host);H.host=O.host.toLowerCase(),z=O.isIPV6}else z=!0;if(H.scheme===void 0&&H.userinfo===void 0&&H.host===void 0&&H.port===void 0&&H.query===void 0&&!H.path)H.reference="same-document";else if(H.scheme===void 0)H.reference="relative";else if(H.fragment===void 0)H.reference="absolute";else H.reference="uri";if(G.reference&&G.reference!=="suffix"&&G.reference!==H.reference)H.error=H.error||"URI is not a "+G.reference+" reference.";let D=s$0(G.scheme||H.scheme);if(!G.unicodeSupport&&(!D||!D.unicodeSupport)){if(H.host&&(G.domainHost||D&&D.domainHost)&&z===!1&&kXQ(H.host))try{H.host=URL.domainToASCII(H.host.toLowerCase())}catch(V){H.error=H.error||"Host's domain name can not be converted to ASCII: "+V}}if(!D||D&&!D.skipNormalize){if(Q.indexOf("%")!==-1){if(H.scheme!==void 0)H.scheme=unescape(H.scheme);if(H.host!==void 0)H.host=SXQ(unescape(H.host),z)}if(H.path)H.path=wXQ(H.path);if(H.fragment)try{H.fragment=encodeURI(decodeURIComponent(H.fragment))}catch{H.error=H.error||"URI malformed"}}if(D&&D.parse)D.parse(H,G)}else H.error=H.error||"URI can not be parsed.";return{parsed:H,malformedAuthorityOrPort:K}}function Ez(Q,J){return t$0(Q,J).parsed}function _XQ(Q,J){return e$0(Q,J).normalized}function e$0(Q,J){let{parsed:G,malformedAuthorityOrPort:H}=t$0(Q,J);return{normalized:H?Q:T3(G,J),malformedAuthorityOrPort:H}}function a$0(Q,J){if(typeof Q==="string"){let{normalized:G,malformedAuthorityOrPort:H}=e$0(Q,J);return H?void 0:G}if(typeof Q==="object")return T3(Q,J)}var Ne={SCHEMES:yXQ,normalize:vXQ,resolve:xXQ,resolveComponent:r$0,equal:bXQ,serialize:T3,parse:Ez};Nj.exports=Ne;Nj.exports.default=Ne;Nj.exports.fastUri=Ne});var JZ0=i((Ce)=>{Object.defineProperty(Ce,"__esModule",{value:!0});var XZ0=QZ0();XZ0.code='require("ajv/dist/runtime/uri").default';Ce.default=XZ0});var zZ0=i((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});MX.CodeGen=MX.Name=MX.nil=MX.stringify=MX.str=MX._=MX.KeywordCxt=void 0;var fXQ=zZ();Object.defineProperty(MX,"KeywordCxt",{enumerable:!0,get:function(){return fXQ.KeywordCxt}});var Sz=t8();Object.defineProperty(MX,"_",{enumerable:!0,get:function(){return Sz._}});Object.defineProperty(MX,"str",{enumerable:!0,get:function(){return Sz.str}});Object.defineProperty(MX,"stringify",{enumerable:!0,get:function(){return Sz.stringify}});Object.defineProperty(MX,"nil",{enumerable:!0,get:function(){return Sz.nil}});Object.defineProperty(MX,"Name",{enumerable:!0,get:function(){return Sz.Name}});Object.defineProperty(MX,"CodeGen",{enumerable:!0,get:function(){return Sz.CodeGen}});var mXQ=Dj(),BZ0=VZ(),uXQ=Dt(),$Z=Lj(),pXQ=t8(),ZZ=BZ(),jj=HZ(),Re=R6(),YZ0=h$0(),lXQ=JZ0(),AZ0=(Q,J)=>new RegExp(Q,J);AZ0.code="new RegExp";var dXQ=["removeAdditional","useDefaults","coerceTypes"],cXQ=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),iXQ={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},oXQ={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},GZ0=200;function nXQ(Q){var J,G,H,K,z,q,F,D,V,O,P,N,I,R,w,E,T,y,x,b,g,l,_,a,r;let f0=Q.strict,t=(J=Q.code)===null||J===void 0?void 0:J.optimize,p0=t===!0||t===void 0?1:t||0,u0=(H=(G=Q.code)===null||G===void 0?void 0:G.regExp)!==null&&H!==void 0?H:AZ0,d=(K=Q.uriResolver)!==null&&K!==void 0?K:lXQ.default;return{strictSchema:(q=(z=Q.strictSchema)!==null&&z!==void 0?z:f0)!==null&&q!==void 0?q:!0,strictNumbers:(D=(F=Q.strictNumbers)!==null&&F!==void 0?F:f0)!==null&&D!==void 0?D:!0,strictTypes:(O=(V=Q.strictTypes)!==null&&V!==void 0?V:f0)!==null&&O!==void 0?O:"log",strictTuples:(N=(P=Q.strictTuples)!==null&&P!==void 0?P:f0)!==null&&N!==void 0?N:"log",strictRequired:(R=(I=Q.strictRequired)!==null&&I!==void 0?I:f0)!==null&&R!==void 0?R:!1,code:Q.code?{...Q.code,optimize:p0,regExp:u0}:{optimize:p0,regExp:u0},loopRequired:(w=Q.loopRequired)!==null&&w!==void 0?w:GZ0,loopEnum:(E=Q.loopEnum)!==null&&E!==void 0?E:GZ0,meta:(T=Q.meta)!==null&&T!==void 0?T:!0,messages:(y=Q.messages)!==null&&y!==void 0?y:!0,inlineRefs:(x=Q.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(b=Q.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(g=Q.addUsedSchema)!==null&&g!==void 0?g:!0,validateSchema:(l=Q.validateSchema)!==null&&l!==void 0?l:!0,validateFormats:(_=Q.validateFormats)!==null&&_!==void 0?_:!0,unicodeRegExp:(a=Q.unicodeRegExp)!==null&&a!==void 0?a:!0,int32range:(r=Q.int32range)!==null&&r!==void 0?r:!0,uriResolver:d}}class Cj{constructor(Q={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,Q=this.opts={...Q,...nXQ(Q)};let{es5:J,lines:G}=this.opts.code;this.scope=new pXQ.ValueScope({scope:{},prefixes:cXQ,es5:J,lines:G}),this.logger=QJQ(Q.logger);let H=Q.validateFormats;if(Q.validateFormats=!1,this.RULES=(0,uXQ.getRules)(),WZ0.call(this,iXQ,Q,"NOT SUPPORTED"),WZ0.call(this,oXQ,Q,"DEPRECATED","warn"),this._metaOpts=tXQ.call(this),Q.formats)sXQ.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),Q.keywords)rXQ.call(this,Q.keywords);if(typeof Q.meta=="object")this.addMetaSchema(Q.meta);aXQ.call(this),Q.validateFormats=H}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:Q,meta:J,schemaId:G}=this.opts,H=YZ0;if(G==="id")H={...YZ0},H.id=H.$id,delete H.$id;if(J&&Q)this.addMetaSchema(H,H[G],!1)}defaultMeta(){let{meta:Q,schemaId:J}=this.opts;return this.opts.defaultMeta=typeof Q=="object"?Q[J]||Q:void 0}validate(Q,J){let G;if(typeof Q=="string"){if(G=this.getSchema(Q),!G)throw Error(`no schema with key or ref "${Q}"`)}else G=this.compile(Q);let H=G(J);if(!("$async"in G))this.errors=G.errors;return H}compile(Q,J){let G=this._addSchema(Q,J);return G.validate||this._compileSchemaEnv(G)}compileAsync(Q,J){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:G}=this.opts;return H.call(this,Q,J);async function H(V,O){await K.call(this,V.$schema);let P=this._addSchema(V,O);return P.validate||z.call(this,P)}async function K(V){if(V&&!this.getSchema(V))await H.call(this,{$ref:V},!0)}async function z(V){try{return this._compileSchemaEnv(V)}catch(O){if(!(O instanceof BZ0.default))throw O;return q.call(this,O),await F.call(this,O.missingSchema),z.call(this,V)}}function q({missingSchema:V,missingRef:O}){if(this.refs[V])throw Error(`AnySchema ${V} is loaded but ${O} cannot be resolved`)}async function F(V){let O=await D.call(this,V);if(!this.refs[V])await K.call(this,O.$schema);if(!this.refs[V])this.addSchema(O,V,J)}async function D(V){let O=this._loading[V];if(O)return O;try{return await(this._loading[V]=G(V))}finally{delete this._loading[V]}}}addSchema(Q,J,G,H=this.opts.validateSchema){if(Array.isArray(Q)){for(let z of Q)this.addSchema(z,void 0,G,H);return this}let K;if(typeof Q==="object"){let{schemaId:z}=this.opts;if(K=Q[z],K!==void 0&&typeof K!="string")throw Error(`schema ${z} must be string`)}return J=(0,ZZ.normalizeId)(J||K),this._checkUnique(J),this.schemas[J]=this._addSchema(Q,G,J,H,!0),this}addMetaSchema(Q,J,G=this.opts.validateSchema){return this.addSchema(Q,J,!0,G),this}validateSchema(Q,J){if(typeof Q=="boolean")return!0;let G;if(G=Q.$schema,G!==void 0&&typeof G!="string")throw Error("$schema must be a string");if(G=G||this.opts.defaultMeta||this.defaultMeta(),!G)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let H=this.validate(G,Q);if(!H&&J){let K="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(K);else throw Error(K)}return H}getSchema(Q){let J;while(typeof(J=HZ0.call(this,Q))=="string")Q=J;if(J===void 0){let{schemaId:G}=this.opts,H=new $Z.SchemaEnv({schema:{},schemaId:G});if(J=$Z.resolveSchema.call(this,H,Q),!J)return;this.refs[Q]=J}return J.validate||this._compileSchemaEnv(J)}removeSchema(Q){if(Q instanceof RegExp)return this._removeAllSchemas(this.schemas,Q),this._removeAllSchemas(this.refs,Q),this;switch(typeof Q){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let J=HZ0.call(this,Q);if(typeof J=="object")this._cache.delete(J.schema);return delete this.schemas[Q],delete this.refs[Q],this}case"object":{let J=Q;this._cache.delete(J);let G=Q[this.opts.schemaId];if(G)G=(0,ZZ.normalizeId)(G),delete this.schemas[G],delete this.refs[G];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(Q){for(let J of Q)this.addKeyword(J);return this}addKeyword(Q,J){let G;if(typeof Q=="string"){if(G=Q,typeof J=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),J.keyword=G}else if(typeof Q=="object"&&J===void 0){if(J=Q,G=J.keyword,Array.isArray(G)&&!G.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(JJQ.call(this,G,J),!J)return(0,Re.eachItem)(G,(K)=>Ie.call(this,K)),this;GJQ.call(this,J);let H={...J,type:(0,jj.getJSONTypes)(J.type),schemaType:(0,jj.getJSONTypes)(J.schemaType)};return(0,Re.eachItem)(G,H.type.length===0?(K)=>Ie.call(this,K,H):(K)=>H.type.forEach((z)=>Ie.call(this,K,H,z))),this}getKeyword(Q){let J=this.RULES.all[Q];return typeof J=="object"?J.definition:!!J}removeKeyword(Q){let{RULES:J}=this;delete J.keywords[Q],delete J.all[Q];for(let G of J.rules){let H=G.rules.findIndex((K)=>K.keyword===Q);if(H>=0)G.rules.splice(H,1)}return this}addFormat(Q,J){if(typeof J=="string")J=new RegExp(J);return this.formats[Q]=J,this}errorsText(Q=this.errors,{separator:J=", ",dataVar:G="data"}={}){if(!Q||Q.length===0)return"No errors";return Q.map((H)=>`${G}${H.instancePath} ${H.message}`).reduce((H,K)=>H+J+K)}$dataMetaSchema(Q,J){let G=this.RULES.all;Q=JSON.parse(JSON.stringify(Q));for(let H of J){let K=H.split("/").slice(1),z=Q;for(let q of K)z=z[q];for(let q in G){let F=G[q];if(typeof F!="object")continue;let{$data:D}=F.definition,V=z[q];if(D&&V)z[q]=KZ0(V)}}return Q}_removeAllSchemas(Q,J){for(let G in Q){let H=Q[G];if(!J||J.test(G)){if(typeof H=="string")delete Q[G];else if(H&&!H.meta)this._cache.delete(H.schema),delete Q[G]}}}_addSchema(Q,J,G,H=this.opts.validateSchema,K=this.opts.addUsedSchema){let z,{schemaId:q}=this.opts;if(typeof Q=="object")z=Q[q];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof Q!="boolean")throw Error("schema must be object or boolean");let F=this._cache.get(Q);if(F!==void 0)return F;G=(0,ZZ.normalizeId)(z||G);let D=ZZ.getSchemaRefs.call(this,Q,G);if(F=new $Z.SchemaEnv({schema:Q,schemaId:q,meta:J,baseId:G,localRefs:D}),this._cache.set(F.schema,F),K&&!G.startsWith("#")){if(G)this._checkUnique(G);this.refs[G]=F}if(H)this.validateSchema(Q,!0);return F}_checkUnique(Q){if(this.schemas[Q]||this.refs[Q])throw Error(`schema with key or id "${Q}" already exists`)}_compileSchemaEnv(Q){if(Q.meta)this._compileMetaSchema(Q);else $Z.compileSchema.call(this,Q);if(!Q.validate)throw Error("ajv implementation error");return Q.validate}_compileMetaSchema(Q){let J=this.opts;this.opts=this._metaOpts;try{$Z.compileSchema.call(this,Q)}finally{this.opts=J}}}Cj.ValidationError=mXQ.default;Cj.MissingRefError=BZ0.default;MX.default=Cj;function WZ0(Q,J,G,H="error"){for(let K in Q){let z=K;if(z in J)this.logger[H](`${G}: option ${K}. ${Q[z]}`)}}function HZ0(Q){return Q=(0,ZZ.normalizeId)(Q),this.schemas[Q]||this.refs[Q]}function aXQ(){let Q=this.opts.schemas;if(!Q)return;if(Array.isArray(Q))this.addSchema(Q);else for(let J in Q)this.addSchema(Q[J],J)}function sXQ(){for(let Q in this.opts.formats){let J=this.opts.formats[Q];if(J)this.addFormat(Q,J)}}function rXQ(Q){if(Array.isArray(Q)){this.addVocabulary(Q);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let J in Q){let G=Q[J];if(!G.keyword)G.keyword=J;this.addKeyword(G)}}function tXQ(){let Q={...this.opts};for(let J of dXQ)delete Q[J];return Q}var eXQ={log(){},warn(){},error(){}};function QJQ(Q){if(Q===!1)return eXQ;if(Q===void 0)return console;if(Q.log&&Q.warn&&Q.error)return Q;throw Error("logger must implement log, warn and error methods")}var XJQ=/^[a-z_$][a-z0-9_$:-]*$/i;function JJQ(Q,J){let{RULES:G}=this;if((0,Re.eachItem)(Q,(H)=>{if(G.keywords[H])throw Error(`Keyword ${H} is already defined`);if(!XJQ.test(H))throw Error(`Keyword ${H} has invalid name`)}),!J)return;if(J.$data&&!(("code"in J)||("validate"in J)))throw Error('$data keyword must have "code" or "validate" function')}function Ie(Q,J,G){var H;let K=J===null||J===void 0?void 0:J.post;if(G&&K)throw Error('keyword with "post" flag cannot have "type"');let{RULES:z}=this,q=K?z.post:z.rules.find(({type:D})=>D===G);if(!q)q={type:G,rules:[]},z.rules.push(q);if(z.keywords[Q]=!0,!J)return;let F={keyword:Q,definition:{...J,type:(0,jj.getJSONTypes)(J.type),schemaType:(0,jj.getJSONTypes)(J.schemaType)}};if(J.before)YJQ.call(this,q,F,J.before);else q.rules.push(F);z.all[Q]=F,(H=J.implements)===null||H===void 0||H.forEach((D)=>this.addKeyword(D))}function YJQ(Q,J,G){let H=Q.rules.findIndex((K)=>K.keyword===G);if(H>=0)Q.rules.splice(H,0,J);else Q.rules.push(J),this.logger.warn(`rule ${G} is not defined`)}function GJQ(Q){let{metaSchema:J}=Q;if(J===void 0)return;if(Q.$data&&this.opts.$data)J=KZ0(J);Q.validateSchema=this.compile(J,!0)}var WJQ={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function KZ0(Q){return{anyOf:[Q,WJQ]}}});var VZ0=i((Se)=>{Object.defineProperty(Se,"__esModule",{value:!0});var HJQ={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Se.default=HJQ});var ZZ0=i((k3)=>{Object.defineProperty(k3,"__esModule",{value:!0});k3.callRef=k3.getValidate=void 0;var BJQ=VZ(),qZ0=uY(),pJ=t8(),Tz=R5(),UZ0=Lj(),Ij=R6(),AJQ={keyword:"$ref",schemaType:"string",code(Q){let{gen:J,schema:G,it:H}=Q,{baseId:K,schemaEnv:z,validateName:q,opts:F,self:D}=H,{root:V}=z;if((G==="#"||G==="#/")&&K===V.baseId)return P();let O=UZ0.resolveRef.call(D,V,K,G);if(O===void 0)throw new BJQ.default(H.opts.uriResolver,K,G);if(O instanceof UZ0.SchemaEnv)return N(O);return I(O);function P(){if(z===V)return Rj(Q,q,z,z.$async);let R=J.scopeValue("root",{ref:V});return Rj(Q,pJ._`${R}.validate`,V,V.$async)}function N(R){let w=$Z0(Q,R);Rj(Q,w,R,R.$async)}function I(R){let w=J.scopeValue("schema",F.code.source===!0?{ref:R,code:(0,pJ.stringify)(R)}:{ref:R}),E=J.name("valid"),T=Q.subschema({schema:R,dataTypes:[],schemaPath:pJ.nil,topSchemaRef:w,errSchemaPath:G},E);Q.mergeEvaluated(T),Q.ok(E)}}};function $Z0(Q,J){let{gen:G}=Q;return J.validate?G.scopeValue("validate",{ref:J.validate}):pJ._`${G.scopeValue("wrapper",{ref:J})}.validate`}k3.getValidate=$Z0;function Rj(Q,J,G,H){let{gen:K,it:z}=Q,{allErrors:q,schemaEnv:F,opts:D}=z,V=D.passContext?Tz.default.this:pJ.nil;if(H)O();else P();function O(){if(!F.$async)throw Error("async schema referenced by sync schema");let R=K.let("valid");K.try(()=>{if(K.code(pJ._`await ${(0,qZ0.callValidateCode)(Q,J,V)}`),I(J),!q)K.assign(R,!0)},(w)=>{if(K.if(pJ._`!(${w} instanceof ${z.ValidationError})`,()=>K.throw(w)),N(w),!q)K.assign(R,!1)}),Q.ok(R)}function P(){Q.result((0,qZ0.callValidateCode)(Q,J,V),()=>I(J),()=>N(J))}function N(R){let w=pJ._`${R}.errors`;K.assign(Tz.default.vErrors,pJ._`${Tz.default.vErrors} === null ? ${w} : ${Tz.default.vErrors}.concat(${w})`),K.assign(Tz.default.errors,pJ._`${Tz.default.vErrors}.length`)}function I(R){var w;if(!z.opts.unevaluated)return;let E=(w=G===null||G===void 0?void 0:G.validate)===null||w===void 0?void 0:w.evaluated;if(z.props!==!0)if(E&&!E.dynamicProps){if(E.props!==void 0)z.props=Ij.mergeEvaluated.props(K,E.props,z.props)}else{let T=K.var("props",pJ._`${R}.evaluated.props`);z.props=Ij.mergeEvaluated.props(K,T,z.props,pJ.Name)}if(z.items!==!0)if(E&&!E.dynamicItems){if(E.items!==void 0)z.items=Ij.mergeEvaluated.items(K,E.items,z.items)}else{let T=K.var("items",pJ._`${R}.evaluated.items`);z.items=Ij.mergeEvaluated.items(K,T,z.items,pJ.Name)}}}k3.callRef=Rj;k3.default=AJQ});var FZ0=i((ge)=>{Object.defineProperty(ge,"__esModule",{value:!0});var KJQ=VZ0(),zJQ=ZZ0(),VJQ=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",KJQ.default,zJQ.default];ge.default=VJQ});var DZ0=i((me)=>{Object.defineProperty(me,"__esModule",{value:!0});var wj=t8(),t4=wj.operators,Ej={maximum:{okStr:"<=",ok:t4.LTE,fail:t4.GT},minimum:{okStr:">=",ok:t4.GTE,fail:t4.LT},exclusiveMaximum:{okStr:"<",ok:t4.LT,fail:t4.GTE},exclusiveMinimum:{okStr:">",ok:t4.GT,fail:t4.LTE}},qJQ={message:({keyword:Q,schemaCode:J})=>wj.str`must be ${Ej[Q].okStr} ${J}`,params:({keyword:Q,schemaCode:J})=>wj._`{comparison: ${Ej[Q].okStr}, limit: ${J}}`},UJQ={keyword:Object.keys(Ej),type:"number",schemaType:"number",$data:!0,error:qJQ,code(Q){let{keyword:J,data:G,schemaCode:H}=Q;Q.fail$data(wj._`${G} ${Ej[J].fail} ${H} || isNaN(${G})`)}};me.default=UJQ});var MZ0=i((ue)=>{Object.defineProperty(ue,"__esModule",{value:!0});var FZ=t8(),$JQ={message:({schemaCode:Q})=>FZ.str`must be multiple of ${Q}`,params:({schemaCode:Q})=>FZ._`{multipleOf: ${Q}}`},ZJQ={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:$JQ,code(Q){let{gen:J,data:G,schemaCode:H,it:K}=Q,z=K.opts.multipleOfPrecision,q=J.let("res"),F=z?FZ._`Math.abs(Math.round(${q}) - ${q}) > 1e-${z}`:FZ._`${q} !== parseInt(${q})`;Q.fail$data(FZ._`(${H} === 0 || (${q} = ${G}/${H}, ${F}))`)}};ue.default=ZJQ});var OZ0=i((de)=>{Object.defineProperty(de,"__esModule",{value:!0});function LZ0(Q){let J=Q.length,G=0,H=0,K;while(H<J)if(G++,K=Q.charCodeAt(H++),K>=55296&&K<=56319&&H<J){if(K=Q.charCodeAt(H),(K&64512)===56320)H++}return G}de.default=LZ0;LZ0.code='require("ajv/dist/runtime/ucs2length").default'});var PZ0=i((oe)=>{Object.defineProperty(oe,"__esModule",{value:!0});var y3=t8(),FJQ=R6(),DJQ=OZ0(),MJQ={message({keyword:Q,schemaCode:J}){let G=Q==="maxLength"?"more":"fewer";return y3.str`must NOT have ${G} than ${J} characters`},params:({schemaCode:Q})=>y3._`{limit: ${Q}}`},LJQ={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:MJQ,code(Q){let{keyword:J,data:G,schemaCode:H,it:K}=Q,z=J==="maxLength"?y3.operators.GT:y3.operators.LT,q=K.opts.unicode===!1?y3._`${G}.length`:y3._`${(0,FJQ.useFunc)(Q.gen,DJQ.default)}(${G})`;Q.fail$data(y3._`${q} ${z} ${H}`)}};oe.default=LJQ});var NZ0=i((re)=>{Object.defineProperty(re,"__esModule",{value:!0});var OJQ=uY(),PJQ=R6(),kz=t8(),NJQ={message:({schemaCode:Q})=>kz.str`must match pattern "${Q}"`,params:({schemaCode:Q})=>kz._`{pattern: ${Q}}`},jJQ={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:NJQ,code(Q){let{gen:J,data:G,$data:H,schema:K,schemaCode:z,it:q}=Q,F=q.opts.unicodeRegExp?"u":"";if(H){let{regExp:D}=q.opts.code,V=D.code==="new RegExp"?kz._`new RegExp`:(0,PJQ.useFunc)(J,D),O=J.let("valid");J.try(()=>J.assign(O,kz._`${V}(${z}, ${F}).test(${G})`),()=>J.assign(O,!1)),Q.fail$data(kz._`!${O}`)}else{let D=(0,OJQ.usePattern)(Q,K);Q.fail$data(kz._`!${D}.test(${G})`)}}};re.default=jJQ});var jZ0=i((te)=>{Object.defineProperty(te,"__esModule",{value:!0});var DZ=t8(),CJQ={message({keyword:Q,schemaCode:J}){let G=Q==="maxProperties"?"more":"fewer";return DZ.str`must NOT have ${G} than ${J} properties`},params:({schemaCode:Q})=>DZ._`{limit: ${Q}}`},IJQ={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CJQ,code(Q){let{keyword:J,data:G,schemaCode:H}=Q,K=J==="maxProperties"?DZ.operators.GT:DZ.operators.LT;Q.fail$data(DZ._`Object.keys(${G}).length ${K} ${H}`)}};te.default=IJQ});var CZ0=i((Q00)=>{Object.defineProperty(Q00,"__esModule",{value:!0});var MZ=uY(),LZ=t8(),RJQ=R6(),wJQ={message:({params:{missingProperty:Q}})=>LZ.str`must have required property '${Q}'`,params:({params:{missingProperty:Q}})=>LZ._`{missingProperty: ${Q}}`},EJQ={keyword:"required",type:"object",schemaType:"array",$data:!0,error:wJQ,code(Q){let{gen:J,schema:G,schemaCode:H,data:K,$data:z,it:q}=Q,{opts:F}=q;if(!z&&G.length===0)return;let D=G.length>=F.loopRequired;if(q.allErrors)V();else O();if(F.strictRequired){let I=Q.parentSchema.properties,{definedProperties:R}=Q.it;for(let w of G)if((I===null||I===void 0?void 0:I[w])===void 0&&!R.has(w)){let E=q.schemaEnv.baseId+q.errSchemaPath,T=`required property "${w}" is not defined at "${E}" (strictRequired)`;(0,RJQ.checkStrictMode)(q,T,q.opts.strictRequired)}}function V(){if(D||z)Q.block$data(LZ.nil,P);else for(let I of G)(0,MZ.checkReportMissingProp)(Q,I)}function O(){let I=J.let("missing");if(D||z){let R=J.let("valid",!0);Q.block$data(R,()=>N(I,R)),Q.ok(R)}else J.if((0,MZ.checkMissingProp)(Q,G,I)),(0,MZ.reportMissingProp)(Q,I),J.else()}function P(){J.forOf("prop",H,(I)=>{Q.setParams({missingProperty:I}),J.if((0,MZ.noPropertyInData)(J,K,I,F.ownProperties),()=>Q.error())})}function N(I,R){Q.setParams({missingProperty:I}),J.forOf(I,H,()=>{J.assign(R,(0,MZ.propertyInData)(J,K,I,F.ownProperties)),J.if((0,LZ.not)(R),()=>{Q.error(),J.break()})},LZ.nil)}}};Q00.default=EJQ});var IZ0=i((X00)=>{Object.defineProperty(X00,"__esModule",{value:!0});var OZ=t8(),SJQ={message({keyword:Q,schemaCode:J}){let G=Q==="maxItems"?"more":"fewer";return OZ.str`must NOT have ${G} than ${J} items`},params:({schemaCode:Q})=>OZ._`{limit: ${Q}}`},TJQ={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:SJQ,code(Q){let{keyword:J,data:G,schemaCode:H}=Q,K=J==="maxItems"?OZ.operators.GT:OZ.operators.LT;Q.fail$data(OZ._`${G}.length ${K} ${H}`)}};X00.default=TJQ});var Sj=i((J00)=>{Object.defineProperty(J00,"__esModule",{value:!0});var RZ0=St();RZ0.code='require("ajv/dist/runtime/equal").default';J00.default=RZ0});var wZ0=i((G00)=>{Object.defineProperty(G00,"__esModule",{value:!0});var Y00=HZ(),LX=t8(),kJQ=R6(),yJQ=Sj(),vJQ={message:({params:{i:Q,j:J}})=>LX.str`must NOT have duplicate items (items ## ${J} and ${Q} are identical)`,params:({params:{i:Q,j:J}})=>LX._`{i: ${Q}, j: ${J}}`},xJQ={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:vJQ,code(Q){let{gen:J,data:G,$data:H,schema:K,parentSchema:z,schemaCode:q,it:F}=Q;if(!H&&!K)return;let D=J.let("valid"),V=z.items?(0,Y00.getSchemaTypes)(z.items):[];Q.block$data(D,O,LX._`${q} === false`),Q.ok(D);function O(){let R=J.let("i",LX._`${G}.length`),w=J.let("j");Q.setParams({i:R,j:w}),J.assign(D,!0),J.if(LX._`${R} > 1`,()=>(P()?N:I)(R,w))}function P(){return V.length>0&&!V.some((R)=>R==="object"||R==="array")}function N(R,w){let E=J.name("item"),T=(0,Y00.checkDataTypes)(V,E,F.opts.strictNumbers,Y00.DataType.Wrong),y=J.const("indices",LX._`{}`);J.for(LX._`;${R}--;`,()=>{if(J.let(E,LX._`${G}[${R}]`),J.if(T,LX._`continue`),V.length>1)J.if(LX._`typeof ${E} == "string"`,LX._`${E} += "_"`);J.if(LX._`typeof ${y}[${E}] == "number"`,()=>{J.assign(w,LX._`${y}[${E}]`),Q.error(),J.assign(D,!1).break()}).code(LX._`${y}[${E}] = ${R}`)})}function I(R,w){let E=(0,kJQ.useFunc)(J,yJQ.default),T=J.name("outer");J.label(T).for(LX._`;${R}--;`,()=>J.for(LX._`${w} = ${R}; ${w}--;`,()=>J.if(LX._`${E}(${G}[${R}], ${G}[${w}])`,()=>{Q.error(),J.assign(D,!1).break(T)})))}}};G00.default=xJQ});var EZ0=i((H00)=>{Object.defineProperty(H00,"__esModule",{value:!0});var W00=t8(),bJQ=R6(),gJQ=Sj(),hJQ={message:"must be equal to constant",params:({schemaCode:Q})=>W00._`{allowedValue: ${Q}}`},_JQ={keyword:"const",$data:!0,error:hJQ,code(Q){let{gen:J,data:G,$data:H,schemaCode:K,schema:z}=Q;if(H||z&&typeof z=="object")Q.fail$data(W00._`!${(0,bJQ.useFunc)(J,gJQ.default)}(${G}, ${K})`);else Q.fail(W00._`${z} !== ${G}`)}};H00.default=_JQ});var SZ0=i((B00)=>{Object.defineProperty(B00,"__esModule",{value:!0});var PZ=t8(),fJQ=R6(),mJQ=Sj(),uJQ={message:"must be equal to one of the allowed values",params:({schemaCode:Q})=>PZ._`{allowedValues: ${Q}}`},pJQ={keyword:"enum",schemaType:"array",$data:!0,error:uJQ,code(Q){let{gen:J,data:G,$data:H,schema:K,schemaCode:z,it:q}=Q;if(!H&&K.length===0)throw Error("enum must have non-empty array");let F=K.length>=q.opts.loopEnum,D,V=()=>D!==null&&D!==void 0?D:D=(0,fJQ.useFunc)(J,mJQ.default),O;if(F||H)O=J.let("valid"),Q.block$data(O,P);else{if(!Array.isArray(K))throw Error("ajv implementation error");let I=J.const("vSchema",z);O=(0,PZ.or)(...K.map((R,w)=>N(I,w)))}Q.pass(O);function P(){J.assign(O,!1),J.forOf("v",z,(I)=>J.if(PZ._`${V()}(${G}, ${I})`,()=>J.assign(O,!0).break()))}function N(I,R){let w=K[R];return typeof w==="object"&&w!==null?PZ._`${V()}(${G}, ${I}[${R}])`:PZ._`${G} === ${w}`}}};B00.default=pJQ});var TZ0=i((A00)=>{Object.defineProperty(A00,"__esModule",{value:!0});var lJQ=DZ0(),dJQ=MZ0(),cJQ=PZ0(),iJQ=NZ0(),oJQ=jZ0(),nJQ=CZ0(),aJQ=IZ0(),sJQ=wZ0(),rJQ=EZ0(),tJQ=SZ0(),eJQ=[lJQ.default,dJQ.default,cJQ.default,iJQ.default,oJQ.default,nJQ.default,aJQ.default,sJQ.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rJQ.default,tJQ.default];A00.default=eJQ});var z00=i((NZ)=>{Object.defineProperty(NZ,"__esModule",{value:!0});NZ.validateAdditionalItems=void 0;var v3=t8(),K00=R6(),QYQ={message:({params:{len:Q}})=>v3.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>v3._`{limit: ${Q}}`},XYQ={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:QYQ,code(Q){let{parentSchema:J,it:G}=Q,{items:H}=J;if(!Array.isArray(H)){(0,K00.checkStrictMode)(G,'"additionalItems" is ignored when "items" is not an array of schemas');return}kZ0(Q,H)}};function kZ0(Q,J){let{gen:G,schema:H,data:K,keyword:z,it:q}=Q;q.items=!0;let F=G.const("len",v3._`${K}.length`);if(H===!1)Q.setParams({len:J.length}),Q.pass(v3._`${F} <= ${J.length}`);else if(typeof H=="object"&&!(0,K00.alwaysValidSchema)(q,H)){let V=G.var("valid",v3._`${F} <= ${J.length}`);G.if((0,v3.not)(V),()=>D(V)),Q.ok(V)}function D(V){G.forRange("i",J.length,F,(O)=>{if(Q.subschema({keyword:z,dataProp:O,dataPropType:K00.Type.Num},V),!q.allErrors)G.if((0,v3.not)(V),()=>G.break())})}}NZ.validateAdditionalItems=kZ0;NZ.default=XYQ});var V00=i((jZ)=>{Object.defineProperty(jZ,"__esModule",{value:!0});jZ.validateTuple=void 0;var yZ0=t8(),Tj=R6(),JYQ=uY(),YYQ={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(Q){let{schema:J,it:G}=Q;if(Array.isArray(J))return vZ0(Q,"additionalItems",J);if(G.items=!0,(0,Tj.alwaysValidSchema)(G,J))return;Q.ok((0,JYQ.validateArray)(Q))}};function vZ0(Q,J,G=Q.schema){let{gen:H,parentSchema:K,data:z,keyword:q,it:F}=Q;if(O(K),F.opts.unevaluated&&G.length&&F.items!==!0)F.items=Tj.mergeEvaluated.items(H,G.length,F.items);let D=H.name("valid"),V=H.const("len",yZ0._`${z}.length`);G.forEach((P,N)=>{if((0,Tj.alwaysValidSchema)(F,P))return;H.if(yZ0._`${V} > ${N}`,()=>Q.subschema({keyword:q,schemaProp:N,dataProp:N},D)),Q.ok(D)});function O(P){let{opts:N,errSchemaPath:I}=F,R=G.length,w=R===P.minItems&&(R===P.maxItems||P[J]===!1);if(N.strictTuples&&!w){let E=`"${q}" is ${R}-tuple, but minItems or maxItems/${J} are not specified or different at path "${I}"`;(0,Tj.checkStrictMode)(F,E,N.strictTuples)}}}jZ.validateTuple=vZ0;jZ.default=YYQ});var xZ0=i((q00)=>{Object.defineProperty(q00,"__esModule",{value:!0});var GYQ=V00(),WYQ={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(Q)=>(0,GYQ.validateTuple)(Q,"items")};q00.default=WYQ});var gZ0=i((U00)=>{Object.defineProperty(U00,"__esModule",{value:!0});var bZ0=t8(),HYQ=R6(),BYQ=uY(),AYQ=z00(),KYQ={message:({params:{len:Q}})=>bZ0.str`must NOT have more than ${Q} items`,params:({params:{len:Q}})=>bZ0._`{limit: ${Q}}`},zYQ={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:KYQ,code(Q){let{schema:J,parentSchema:G,it:H}=Q,{prefixItems:K}=G;if(H.items=!0,(0,HYQ.alwaysValidSchema)(H,J))return;if(K)(0,AYQ.validateAdditionalItems)(Q,K);else Q.ok((0,BYQ.validateArray)(Q))}};U00.default=zYQ});var hZ0=i(($00)=>{Object.defineProperty($00,"__esModule",{value:!0});var lY=t8(),kj=R6(),VYQ={message:({params:{min:Q,max:J}})=>J===void 0?lY.str`must contain at least ${Q} valid item(s)`:lY.str`must contain at least ${Q} and no more than ${J} valid item(s)`,params:({params:{min:Q,max:J}})=>J===void 0?lY._`{minContains: ${Q}}`:lY._`{minContains: ${Q}, maxContains: ${J}}`},qYQ={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:VYQ,code(Q){let{gen:J,schema:G,parentSchema:H,data:K,it:z}=Q,q,F,{minContains:D,maxContains:V}=H;if(z.opts.next)q=D===void 0?1:D,F=V;else q=1;let O=J.const("len",lY._`${K}.length`);if(Q.setParams({min:q,max:F}),F===void 0&&q===0){(0,kj.checkStrictMode)(z,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(F!==void 0&&q>F){(0,kj.checkStrictMode)(z,'"minContains" > "maxContains" is always invalid'),Q.fail();return}if((0,kj.alwaysValidSchema)(z,G)){let w=lY._`${O} >= ${q}`;if(F!==void 0)w=lY._`${w} && ${O} <= ${F}`;Q.pass(w);return}z.items=!0;let P=J.name("valid");if(F===void 0&&q===1)I(P,()=>J.if(P,()=>J.break()));else if(q===0){if(J.let(P,!0),F!==void 0)J.if(lY._`${K}.length > 0`,N)}else J.let(P,!1),N();Q.result(P,()=>Q.reset());function N(){let w=J.name("_valid"),E=J.let("count",0);I(w,()=>J.if(w,()=>R(E)))}function I(w,E){J.forRange("i",0,O,(T)=>{Q.subschema({keyword:"contains",dataProp:T,dataPropType:kj.Type.Num,compositeRule:!0},w),E()})}function R(w){if(J.code(lY._`${w}++`),F===void 0)J.if(lY._`${w} >= ${q}`,()=>J.assign(P,!0).break());else if(J.if(lY._`${w} > ${F}`,()=>J.assign(P,!1).break()),q===1)J.assign(P,!0);else J.if(lY._`${w} >= ${q}`,()=>J.assign(P,!0))}}};$00.default=qYQ});var mZ0=i((NW)=>{Object.defineProperty(NW,"__esModule",{value:!0});NW.validateSchemaDeps=NW.validatePropertyDeps=NW.error=void 0;var Z00=t8(),UYQ=R6(),CZ=uY();NW.error={message:({params:{property:Q,depsCount:J,deps:G}})=>{let H=J===1?"property":"properties";return Z00.str`must have ${H} ${G} when property ${Q} is present`},params:({params:{property:Q,depsCount:J,deps:G,missingProperty:H}})=>Z00._`{property: ${Q},
missingProperty: ${H},
depsCount: ${J},
deps: ${G}}`};var $YQ={keyword:"dependencies",type:"object",schemaType:"object",error:NW.error,code(Q){let[J,G]=ZYQ(Q);_Z0(Q,J),fZ0(Q,G)}};function ZYQ({schema:Q}){let J={},G={};for(let H in Q){if(H==="__proto__")continue;let K=Array.isArray(Q[H])?J:G;K[H]=Q[H]}return[J,G]}function _Z0(Q,J=Q.schema){let{gen:G,data:H,it:K}=Q;if(Object.keys(J).length===0)return;let z=G.let("missing");for(let q in J){let F=J[q];if(F.length===0)continue;let D=(0,CZ.propertyInData)(G,H,q,K.opts.ownProperties);if(Q.setParams({property:q,depsCount:F.length,deps:F.join(", ")}),K.allErrors)G.if(D,()=>{for(let V of F)(0,CZ.checkReportMissingProp)(Q,V)});else G.if(Z00._`${D} && (${(0,CZ.checkMissingProp)(Q,F,z)})`),(0,CZ.reportMissingProp)(Q,z),G.else()}}NW.validatePropertyDeps=_Z0;function fZ0(Q,J=Q.schema){let{gen:G,data:H,keyword:K,it:z}=Q,q=G.name("valid");for(let F in J){if((0,UYQ.alwaysValidSchema)(z,J[F]))continue;G.if((0,CZ.propertyInData)(G,H,F,z.opts.ownProperties),()=>{let D=Q.subschema({keyword:K,schemaProp:F},q);Q.mergeValidEvaluated(D,q)},()=>G.var(q,!0)),Q.ok(q)}}NW.validateSchemaDeps=fZ0;NW.default=$YQ});var pZ0=i((F00)=>{Object.defineProperty(F00,"__esModule",{value:!0});var uZ0=t8(),FYQ=R6(),DYQ={message:"property name must be valid",params:({params:Q})=>uZ0._`{propertyName: ${Q.propertyName}}`},MYQ={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:DYQ,code(Q){let{gen:J,schema:G,data:H,it:K}=Q;if((0,FYQ.alwaysValidSchema)(K,G))return;let z=J.name("valid");J.forIn("key",H,(q)=>{Q.setParams({propertyName:q}),Q.subschema({keyword:"propertyNames",data:q,dataTypes:["string"],propertyName:q,compositeRule:!0},z),J.if((0,uZ0.not)(z),()=>{if(Q.error(!0),!K.allErrors)J.break()})}),Q.ok(z)}};F00.default=MYQ});var M00=i((D00)=>{Object.defineProperty(D00,"__esModule",{value:!0});var yj=uY(),CG=t8(),LYQ=R5(),vj=R6(),OYQ={message:"must NOT have additional properties",params:({params:Q})=>CG._`{additionalProperty: ${Q.additionalProperty}}`},PYQ={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:OYQ,code(Q){let{gen:J,schema:G,parentSchema:H,data:K,errsCount:z,it:q}=Q;if(!z)throw Error("ajv implementation error");let{allErrors:F,opts:D}=q;if(q.props=!0,D.removeAdditional!=="all"&&(0,vj.alwaysValidSchema)(q,G))return;let V=(0,yj.allSchemaProperties)(H.properties),O=(0,yj.allSchemaProperties)(H.patternProperties);P(),Q.ok(CG._`${z} === ${LYQ.default.errors}`);function P(){J.forIn("key",K,(E)=>{if(!V.length&&!O.length)R(E);else J.if(N(E),()=>R(E))})}function N(E){let T;if(V.length>8){let y=(0,vj.schemaRefOrVal)(q,H.properties,"properties");T=(0,yj.isOwnProperty)(J,y,E)}else if(V.length)T=(0,CG.or)(...V.map((y)=>CG._`${E} === ${y}`));else T=CG.nil;if(O.length)T=(0,CG.or)(T,...O.map((y)=>CG._`${(0,yj.usePattern)(Q,y)}.test(${E})`));return(0,CG.not)(T)}function I(E){J.code(CG._`delete ${K}[${E}]`)}function R(E){if(D.removeAdditional==="all"||D.removeAdditional&&G===!1){I(E);return}if(G===!1){if(Q.setParams({additionalProperty:E}),Q.error(),!F)J.break();return}if(typeof G=="object"&&!(0,vj.alwaysValidSchema)(q,G)){let T=J.name("valid");if(D.removeAdditional==="failing")w(E,T,!1),J.if((0,CG.not)(T),()=>{Q.reset(),I(E)});else if(w(E,T),!F)J.if((0,CG.not)(T),()=>J.break())}}function w(E,T,y){let x={keyword:"additionalProperties",dataProp:E,dataPropType:vj.Type.Str};if(y===!1)Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1});Q.subschema(x,T)}}};D00.default=PYQ});var cZ0=i((O00)=>{Object.defineProperty(O00,"__esModule",{value:!0});var NYQ=zZ(),lZ0=uY(),L00=R6(),dZ0=M00(),jYQ={keyword:"properties",type:"object",schemaType:"object",code(Q){let{gen:J,schema:G,parentSchema:H,data:K,it:z}=Q;if(z.opts.removeAdditional==="all"&&H.additionalProperties===void 0)dZ0.default.code(new NYQ.KeywordCxt(z,dZ0.default,"additionalProperties"));let q=(0,lZ0.allSchemaProperties)(G);for(let P of q)z.definedProperties.add(P);if(z.opts.unevaluated&&q.length&&z.props!==!0)z.props=L00.mergeEvaluated.props(J,(0,L00.toHash)(q),z.props);let F=q.filter((P)=>!(0,L00.alwaysValidSchema)(z,G[P]));if(F.length===0)return;let D=J.name("valid");for(let P of F){if(V(P))O(P);else{if(J.if((0,lZ0.propertyInData)(J,K,P,z.opts.ownProperties)),O(P),!z.allErrors)J.else().var(D,!0);J.endIf()}Q.it.definedProperties.add(P),Q.ok(D)}function V(P){return z.opts.useDefaults&&!z.compositeRule&&G[P].default!==void 0}function O(P){Q.subschema({keyword:"properties",schemaProp:P,dataProp:P},D)}}};O00.default=jYQ});var aZ0=i((P00)=>{Object.defineProperty(P00,"__esModule",{value:!0});var iZ0=uY(),xj=t8(),oZ0=R6(),nZ0=R6(),CYQ={keyword:"patternProperties",type:"object",schemaType:"object",code(Q){let{gen:J,schema:G,data:H,parentSchema:K,it:z}=Q,{opts:q}=z,F=(0,iZ0.allSchemaProperties)(G),D=F.filter((w)=>(0,oZ0.alwaysValidSchema)(z,G[w]));if(F.length===0||D.length===F.length&&(!z.opts.unevaluated||z.props===!0))return;let V=q.strictSchema&&!q.allowMatchingProperties&&K.properties,O=J.name("valid");if(z.props!==!0&&!(z.props instanceof xj.Name))z.props=(0,nZ0.evaluatedPropsToName)(J,z.props);let{props:P}=z;N();function N(){for(let w of F){if(V)I(w);if(z.allErrors)R(w);else J.var(O,!0),R(w),J.if(O)}}function I(w){for(let E in V)if(new RegExp(w).test(E))(0,oZ0.checkStrictMode)(z,`property ${E} matches pattern ${w} (use allowMatchingProperties)`)}function R(w){J.forIn("key",H,(E)=>{J.if(xj._`${(0,iZ0.usePattern)(Q,w)}.test(${E})`,()=>{let T=D.includes(w);if(!T)Q.subschema({keyword:"patternProperties",schemaProp:w,dataProp:E,dataPropType:nZ0.Type.Str},O);if(z.opts.unevaluated&&P!==!0)J.assign(xj._`${P}[${E}]`,!0);else if(!T&&!z.allErrors)J.if((0,xj.not)(O),()=>J.break())})})}}};P00.default=CYQ});var sZ0=i((N00)=>{Object.defineProperty(N00,"__esModule",{value:!0});var IYQ=R6(),RYQ={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(Q){let{gen:J,schema:G,it:H}=Q;if((0,IYQ.alwaysValidSchema)(H,G)){Q.fail();return}let K=J.name("valid");Q.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},K),Q.failResult(K,()=>Q.reset(),()=>Q.error())},error:{message:"must NOT be valid"}};N00.default=RYQ});var rZ0=i((j00)=>{Object.defineProperty(j00,"__esModule",{value:!0});var wYQ=uY(),EYQ={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:wYQ.validateUnion,error:{message:"must match a schema in anyOf"}};j00.default=EYQ});var tZ0=i((C00)=>{Object.defineProperty(C00,"__esModule",{value:!0});var bj=t8(),SYQ=R6(),TYQ={message:"must match exactly one schema in oneOf",params:({params:Q})=>bj._`{passingSchemas: ${Q.passing}}`},kYQ={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:TYQ,code(Q){let{gen:J,schema:G,parentSchema:H,it:K}=Q;if(!Array.isArray(G))throw Error("ajv implementation error");if(K.opts.discriminator&&H.discriminator)return;let z=G,q=J.let("valid",!1),F=J.let("passing",null),D=J.name("_valid");Q.setParams({passing:F}),J.block(V),Q.result(q,()=>Q.reset(),()=>Q.error(!0));function V(){z.forEach((O,P)=>{let N;if((0,SYQ.alwaysValidSchema)(K,O))J.var(D,!0);else N=Q.subschema({keyword:"oneOf",schemaProp:P,compositeRule:!0},D);if(P>0)J.if(bj._`${D} && ${q}`).assign(q,!1).assign(F,bj._`[${F}, ${P}]`).else();J.if(D,()=>{if(J.assign(q,!0),J.assign(F,P),N)Q.mergeEvaluated(N,bj.Name)})})}}};C00.default=kYQ});var eZ0=i((I00)=>{Object.defineProperty(I00,"__esModule",{value:!0});var yYQ=R6(),vYQ={keyword:"allOf",schemaType:"array",code(Q){let{gen:J,schema:G,it:H}=Q;if(!Array.isArray(G))throw Error("ajv implementation error");let K=J.name("valid");G.forEach((z,q)=>{if((0,yYQ.alwaysValidSchema)(H,z))return;let F=Q.subschema({keyword:"allOf",schemaProp:q},K);Q.ok(K),Q.mergeEvaluated(F)})}};I00.default=vYQ});var JF0=i((R00)=>{Object.defineProperty(R00,"__esModule",{value:!0});var gj=t8(),XF0=R6(),xYQ={message:({params:Q})=>gj.str`must match "${Q.ifClause}" schema`,params:({params:Q})=>gj._`{failingKeyword: ${Q.ifClause}}`},bYQ={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:xYQ,code(Q){let{gen:J,parentSchema:G,it:H}=Q;if(G.then===void 0&&G.else===void 0)(0,XF0.checkStrictMode)(H,'"if" without "then" and "else" is ignored');let K=QF0(H,"then"),z=QF0(H,"else");if(!K&&!z)return;let q=J.let("valid",!0),F=J.name("_valid");if(D(),Q.reset(),K&&z){let O=J.let("ifClause");Q.setParams({ifClause:O}),J.if(F,V("then",O),V("else",O))}else if(K)J.if(F,V("then"));else J.if((0,gj.not)(F),V("else"));Q.pass(q,()=>Q.error(!0));function D(){let O=Q.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},F);Q.mergeEvaluated(O)}function V(O,P){return()=>{let N=Q.subschema({keyword:O},F);if(J.assign(q,F),Q.mergeValidEvaluated(N,q),P)J.assign(P,gj._`${O}`);else Q.setParams({ifClause:O})}}}};function QF0(Q,J){let G=Q.schema[J];return G!==void 0&&!(0,XF0.alwaysValidSchema)(Q,G)}R00.default=bYQ});var YF0=i((w00)=>{Object.defineProperty(w00,"__esModule",{value:!0});var gYQ=R6(),hYQ={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:Q,parentSchema:J,it:G}){if(J.if===void 0)(0,gYQ.checkStrictMode)(G,`"${Q}" without "if" is ignored`)}};w00.default=hYQ});var GF0=i((E00)=>{Object.defineProperty(E00,"__esModule",{value:!0});var _YQ=z00(),fYQ=xZ0(),mYQ=V00(),uYQ=gZ0(),pYQ=hZ0(),lYQ=mZ0(),dYQ=pZ0(),cYQ=M00(),iYQ=cZ0(),oYQ=aZ0(),nYQ=sZ0(),aYQ=rZ0(),sYQ=tZ0(),rYQ=eZ0(),tYQ=JF0(),eYQ=YF0();function QGQ(Q=!1){let J=[nYQ.default,aYQ.default,sYQ.default,rYQ.default,tYQ.default,eYQ.default,dYQ.default,cYQ.default,lYQ.default,iYQ.default,oYQ.default];if(Q)J.push(fYQ.default,uYQ.default);else J.push(_YQ.default,mYQ.default);return J.push(pYQ.default),J}E00.default=QGQ});var WF0=i((S00)=>{Object.defineProperty(S00,"__esModule",{value:!0});var Z7=t8(),XGQ={message:({schemaCode:Q})=>Z7.str`must match format "${Q}"`,params:({schemaCode:Q})=>Z7._`{format: ${Q}}`},JGQ={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:XGQ,code(Q,J){let{gen:G,data:H,$data:K,schema:z,schemaCode:q,it:F}=Q,{opts:D,errSchemaPath:V,schemaEnv:O,self:P}=F;if(!D.validateFormats)return;if(K)N();else I();function N(){let R=G.scopeValue("formats",{ref:P.formats,code:D.code.formats}),w=G.const("fDef",Z7._`${R}[${q}]`),E=G.let("fType"),T=G.let("format");G.if(Z7._`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>G.assign(E,Z7._`${w}.type || "string"`).assign(T,Z7._`${w}.validate`),()=>G.assign(E,Z7._`"string"`).assign(T,w)),Q.fail$data((0,Z7.or)(y(),x()));function y(){if(D.strictSchema===!1)return Z7.nil;return Z7._`${q} && !${T}`}function x(){let b=O.$async?Z7._`(${w}.async ? await ${T}(${H}) : ${T}(${H}))`:Z7._`${T}(${H})`,g=Z7._`(typeof ${T} == "function" ? ${b} : ${T}.test(${H}))`;return Z7._`${T} && ${T} !== true && ${E} === ${J} && !${g}`}}function I(){let R=P.formats[z];if(!R){y();return}if(R===!0)return;let[w,E,T]=x(R);if(w===J)Q.pass(b());function y(){if(D.strictSchema===!1){P.logger.warn(g());return}throw Error(g());function g(){return`unknown format "${z}" ignored in schema at path "${V}"`}}function x(g){let l=g instanceof RegExp?(0,Z7.regexpCode)(g):D.code.formats?Z7._`${D.code.formats}${(0,Z7.getProperty)(z)}`:void 0,_=G.scopeValue("formats",{key:z,ref:g,code:l});if(typeof g=="object"&&!(g instanceof RegExp))return[g.type||"string",g.validate,Z7._`${_}.validate`];return["string",g,_]}function b(){if(typeof R=="object"&&!(R instanceof RegExp)&&R.async){if(!O.$async)throw Error("async format in sync schema");return Z7._`await ${T}(${H})`}return typeof E=="function"?Z7._`${T}(${H})`:Z7._`${T}.test(${H})`}}}};S00.default=JGQ});var HF0=i((T00)=>{Object.defineProperty(T00,"__esModule",{value:!0});var YGQ=WF0(),GGQ=[YGQ.default];T00.default=GGQ});var BF0=i((yz)=>{Object.defineProperty(yz,"__esModule",{value:!0});yz.contentVocabulary=yz.metadataVocabulary=void 0;yz.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];yz.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var KF0=i((k00)=>{Object.defineProperty(k00,"__esModule",{value:!0});var WGQ=FZ0(),HGQ=TZ0(),BGQ=GF0(),AGQ=HF0(),AF0=BF0(),KGQ=[WGQ.default,HGQ.default,(0,BGQ.default)(),AGQ.default,AF0.metadataVocabulary,AF0.contentVocabulary];k00.default=KGQ});var VF0=i((hj)=>{Object.defineProperty(hj,"__esModule",{value:!0});hj.DiscrError=void 0;var zF0;(function(Q){Q.Tag="tag",Q.Mapping="mapping"})(zF0||(hj.DiscrError=zF0={}))});var UF0=i((v00)=>{Object.defineProperty(v00,"__esModule",{value:!0});var vz=t8(),y00=VF0(),qF0=Lj(),zGQ=VZ(),VGQ=R6(),qGQ={message:({params:{discrError:Q,tagName:J}})=>Q===y00.DiscrError.Tag?`tag "${J}" must be string`:`value of tag "${J}" must be in oneOf`,params:({params:{discrError:Q,tag:J,tagName:G}})=>vz._`{error: ${Q}, tag: ${G}, tagValue: ${J}}`},UGQ={keyword:"discriminator",type:"object",schemaType:"object",error:qGQ,code(Q){let{gen:J,data:G,schema:H,parentSchema:K,it:z}=Q,{oneOf:q}=K;if(!z.opts.discriminator)throw Error("discriminator: requires discriminator option");let F=H.propertyName;if(typeof F!="string")throw Error("discriminator: requires propertyName");if(H.mapping)throw Error("discriminator: mapping is not supported");if(!q)throw Error("discriminator: requires oneOf keyword");let D=J.let("valid",!1),V=J.const("tag",vz._`${G}${(0,vz.getProperty)(F)}`);J.if(vz._`typeof ${V} == "string"`,()=>O(),()=>Q.error(!1,{discrError:y00.DiscrError.Tag,tag:V,tagName:F})),Q.ok(D);function O(){let I=N();J.if(!1);for(let R in I)J.elseIf(vz._`${V} === ${R}`),J.assign(D,P(I[R]));J.else(),Q.error(!1,{discrError:y00.DiscrError.Mapping,tag:V,tagName:F}),J.endIf()}function P(I){let R=J.name("valid"),w=Q.subschema({keyword:"oneOf",schemaProp:I},R);return Q.mergeEvaluated(w,vz.Name),R}function N(){var I;let R={},w=T(K),E=!0;for(let b=0;b<q.length;b++){let g=q[b];if((g===null||g===void 0?void 0:g.$ref)&&!(0,VGQ.schemaHasRulesButRef)(g,z.self.RULES)){let _=g.$ref;if(g=qF0.resolveRef.call(z.self,z.schemaEnv.root,z.baseId,_),g instanceof qF0.SchemaEnv)g=g.schema;if(g===void 0)throw new zGQ.default(z.opts.uriResolver,z.baseId,_)}let l=(I=g===null||g===void 0?void 0:g.properties)===null||I===void 0?void 0:I[F];if(typeof l!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${F}"`);E=E&&(w||T(g)),y(l,b)}if(!E)throw Error(`discriminator: "${F}" must be required`);return R;function T({required:b}){return Array.isArray(b)&&b.includes(F)}function y(b,g){if(b.const)x(b.const,g);else if(b.enum)for(let l of b.enum)x(l,g);else throw Error(`discriminator: "properties/${F}" must have "const" or "enum"`)}function x(b,g){if(typeof b!="string"||b in R)throw Error(`discriminator: "${F}" values must be unique strings`);R[b]=g}}}};v00.default=UGQ});var $F0=i((aJ8,$GQ)=>{$GQ.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var b00=i((w9,x00)=>{Object.defineProperty(w9,"__esModule",{value:!0});w9.MissingRefError=w9.ValidationError=w9.CodeGen=w9.Name=w9.nil=w9.stringify=w9.str=w9._=w9.KeywordCxt=w9.Ajv=void 0;var ZGQ=zZ0(),FGQ=KF0(),DGQ=UF0(),ZF0=$F0(),MGQ=["/properties"],_j="http://json-schema.org/draft-07/schema";class IZ extends ZGQ.default{_addVocabularies(){if(super._addVocabularies(),FGQ.default.forEach((Q)=>this.addVocabulary(Q)),this.opts.discriminator)this.addKeyword(DGQ.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let Q=this.opts.$data?this.$dataMetaSchema(ZF0,MGQ):ZF0;this.addMetaSchema(Q,_j,!1),this.refs["http://json-schema.org/schema"]=_j}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_j)?_j:void 0)}}w9.Ajv=IZ;x00.exports=w9=IZ;x00.exports.Ajv=IZ;Object.defineProperty(w9,"__esModule",{value:!0});w9.default=IZ;var LGQ=zZ();Object.defineProperty(w9,"KeywordCxt",{enumerable:!0,get:function(){return LGQ.KeywordCxt}});var xz=t8();Object.defineProperty(w9,"_",{enumerable:!0,get:function(){return xz._}});Object.defineProperty(w9,"str",{enumerable:!0,get:function(){return xz.str}});Object.defineProperty(w9,"stringify",{enumerable:!0,get:function(){return xz.stringify}});Object.defineProperty(w9,"nil",{enumerable:!0,get:function(){return xz.nil}});Object.defineProperty(w9,"Name",{enumerable:!0,get:function(){return xz.Name}});Object.defineProperty(w9,"CodeGen",{enumerable:!0,get:function(){return xz.CodeGen}});var OGQ=Dj();Object.defineProperty(w9,"ValidationError",{enumerable:!0,get:function(){return OGQ.default}});var PGQ=VZ();Object.defineProperty(w9,"MissingRefError",{enumerable:!0,get:function(){return PGQ.default}})});var jF0=i((CW)=>{Object.defineProperty(CW,"__esModule",{value:!0});CW.formatNames=CW.fastFormats=CW.fullFormats=void 0;function jW(Q,J){return{validate:Q,compare:J}}CW.fullFormats={date:jW(LF0,f00),time:jW(h00(!0),m00),"date-time":jW(FF0(!0),PF0),"iso-time":jW(h00(),OF0),"iso-date-time":jW(FF0(),NF0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:wGQ,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:xGQ,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:EGQ,int32:{type:"number",validate:kGQ},int64:{type:"number",validate:yGQ},float:{type:"number",validate:MF0},double:{type:"number",validate:MF0},password:!0,binary:!0};CW.fastFormats={...CW.fullFormats,date:jW(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,f00),time:jW(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,m00),"date-time":jW(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,PF0),"iso-time":jW(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,OF0),"iso-date-time":jW(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,NF0),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};CW.formatNames=Object.keys(CW.fullFormats);function NGQ(Q){return Q%4===0&&(Q%100!==0||Q%400===0)}var jGQ=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,CGQ=[0,31,28,31,30,31,30,31,31,30,31,30,31];function LF0(Q){let J=jGQ.exec(Q);if(!J)return!1;let G=+J[1],H=+J[2],K=+J[3];return H>=1&&H<=12&&K>=1&&K<=(H===2&&NGQ(G)?29:CGQ[H])}function f00(Q,J){if(!(Q&&J))return;if(Q>J)return 1;if(Q<J)return-1;return 0}var g00=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function h00(Q){return function(G){let H=g00.exec(G);if(!H)return!1;let K=+H[1],z=+H[2],q=+H[3],F=H[4],D=H[5]==="-"?-1:1,V=+(H[6]||0),O=+(H[7]||0);if(V>23||O>59||Q&&!F)return!1;if(K<=23&&z<=59&&q<60)return!0;let P=z-O*D,N=K-V*D-(P<0?1:0);return(N===23||N===-1)&&(P===59||P===-1)&&q<61}}function m00(Q,J){if(!(Q&&J))return;let G=new Date("2020-01-01T"+Q).valueOf(),H=new Date("2020-01-01T"+J).valueOf();if(!(G&&H))return;return G-H}function OF0(Q,J){if(!(Q&&J))return;let G=g00.exec(Q),H=g00.exec(J);if(!(G&&H))return;if(Q=G[1]+G[2]+G[3],J=H[1]+H[2]+H[3],Q>J)return 1;if(Q<J)return-1;return 0}var _00=/t|\s/i;function FF0(Q){let J=h00(Q);return function(H){let K=H.split(_00);return K.length===2&&LF0(K[0])&&J(K[1])}}function PF0(Q,J){if(!(Q&&J))return;let G=new Date(Q).valueOf(),H=new Date(J).valueOf();if(!(G&&H))return;return G-H}function NF0(Q,J){if(!(Q&&J))return;let[G,H]=Q.split(_00),[K,z]=J.split(_00),q=f00(G,K);if(q===void 0)return;return q||m00(H,z)}var IGQ=/\/|:/,RGQ=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function wGQ(Q){return IGQ.test(Q)&&RGQ.test(Q)}var DF0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function EGQ(Q){return DF0.lastIndex=0,DF0.test(Q)}var SGQ=-2147483648,TGQ=2147483647;function kGQ(Q){return Number.isInteger(Q)&&Q<=TGQ&&Q>=SGQ}function yGQ(Q){return Number.isInteger(Q)}function MF0(){return!0}var vGQ=/[^\\]\\Z/;function xGQ(Q){if(vGQ.test(Q))return!1;try{return new RegExp(Q),!0}catch(J){return!1}}});var CF0=i((bz)=>{Object.defineProperty(bz,"__esModule",{value:!0});bz.formatLimitDefinition=void 0;var bGQ=b00(),IG=t8(),e4=IG.operators,fj={formatMaximum:{okStr:"<=",ok:e4.LTE,fail:e4.GT},formatMinimum:{okStr:">=",ok:e4.GTE,fail:e4.LT},formatExclusiveMaximum:{okStr:"<",ok:e4.LT,fail:e4.GTE},formatExclusiveMinimum:{okStr:">",ok:e4.GT,fail:e4.LTE}},gGQ={message:({keyword:Q,schemaCode:J})=>IG.str`should be ${fj[Q].okStr} ${J}`,params:({keyword:Q,schemaCode:J})=>IG._`{comparison: ${fj[Q].okStr}, limit: ${J}}`};bz.formatLimitDefinition={keyword:Object.keys(fj),type:"string",schemaType:"string",$data:!0,error:gGQ,code(Q){let{gen:J,data:G,schemaCode:H,keyword:K,it:z}=Q,{opts:q,self:F}=z;if(!q.validateFormats)return;let D=new bGQ.KeywordCxt(z,F.RULES.all.format.definition,"format");if(D.$data)V();else O();function V(){let N=J.scopeValue("formats",{ref:F.formats,code:q.code.formats}),I=J.const("fmt",IG._`${N}[${D.schemaCode}]`);Q.fail$data((0,IG.or)(IG._`typeof ${I} != "object"`,IG._`${I} instanceof RegExp`,IG._`typeof ${I}.compare != "function"`,P(I)))}function O(){let N=D.schema,I=F.formats[N];if(!I||I===!0)return;if(typeof I!="object"||I instanceof RegExp||typeof I.compare!="function")throw Error(`"${K}": format "${N}" does not define "compare" function`);let R=J.scopeValue("formats",{key:N,ref:I,code:q.code.formats?IG._`${q.code.formats}${(0,IG.getProperty)(N)}`:void 0});Q.fail$data(P(R))}function P(N){return IG._`${N}.compare(${G}, ${H}) ${fj[K].fail} 0`}},dependencies:["format"]};var hGQ=(Q)=>{return Q.addKeyword(bz.formatLimitDefinition),Q};bz.default=hGQ});var EF0=i((RZ,wF0)=>{Object.defineProperty(RZ,"__esModule",{value:!0});var gz=jF0(),_GQ=CF0(),u00=t8(),IF0=new u00.Name("fullFormats"),fGQ=new u00.Name("fastFormats"),p00=(Q,J={keywords:!0})=>{if(Array.isArray(J))return RF0(Q,J,gz.fullFormats,IF0),Q;let[G,H]=J.mode==="fast"?[gz.fastFormats,fGQ]:[gz.fullFormats,IF0],K=J.formats||gz.formatNames;if(RF0(Q,K,G,H),J.keywords)(0,_GQ.default)(Q);return Q};p00.get=(Q,J="full")=>{let H=(J==="fast"?gz.fastFormats:gz.fullFormats)[Q];if(!H)throw Error(`Unknown format "${Q}"`);return H};function RF0(Q,J,G,H){var K,z;(K=(z=Q.opts.code).formats)!==null&&K!==void 0||(z.formats=u00._`require("ajv-formats/dist/formats").${H}`);for(let q of J)Q.addFormat(q,G[q])}wF0.exports=RZ=p00;Object.defineProperty(RZ,"__esModule",{value:!0});RZ.default=p00});var fD0=i((PQ0,_D0)=>{(function(Q,J){if(typeof define==="function"&&define.amd)define(J);else if(typeof PQ0==="object")_D0.exports=J();else Q.jsonLogic=J()})(PQ0,function(){if(!Array.isArray)Array.isArray=function(H){return Object.prototype.toString.call(H)==="[object Array]"};function Q(H){var K=[];for(var z=0,q=H.length;z<q;z++)if(K.indexOf(H[z])===-1)K.push(H[z]);return K}var J={},G={"==":function(H,K){return H==K},"===":function(H,K){return H===K},"!=":function(H,K){return H!=K},"!==":function(H,K){return H!==K},">":function(H,K){return H>K},">=":function(H,K){return H>=K},"<":function(H,K,z){return z===void 0?H<K:H<K&&K<z},"<=":function(H,K,z){return z===void 0?H<=K:H<=K&&K<=z},"!!":function(H){return J.truthy(H)},"!":function(H){return!J.truthy(H)},"%":function(H,K){return H%K},log:function(H){return console.log(H),H},in:function(H,K){if(!K||typeof K.indexOf>"u")return!1;return K.indexOf(H)!==-1},cat:function(){return Array.prototype.join.call(arguments,"")},substr:function(H,K,z){if(z<0){var q=String(H).substr(K);return q.substr(0,q.length+z)}return String(H).substr(K,z)},"+":function(){return Array.prototype.reduce.call(arguments,function(H,K){return parseFloat(H,10)+parseFloat(K,10)},0)},"*":function(){return Array.prototype.reduce.call(arguments,function(H,K){return parseFloat(H,10)*parseFloat(K,10)})},"-":function(H,K){if(K===void 0)return-H;else return H-K},"/":function(H,K){return H/K},min:function(){return Math.min.apply(this,arguments)},max:function(){return Math.max.apply(this,arguments)},merge:function(){return Array.prototype.reduce.call(arguments,function(H,K){return H.concat(K)},[])},var:function(H,K){var z=K===void 0?null:K,q=this;if(typeof H>"u"||H===""||H===null)return q;var F=String(H).split(".");for(var D=0;D<F.length;D++){if(q===null||q===void 0)return z;if(q=q[F[D]],q===void 0)return z}return q},missing:function(){var H=[],K=Array.isArray(arguments[0])?arguments[0]:arguments;for(var z=0;z<K.length;z++){var q=K[z],F=J.apply({var:q},this);if(F===null||F==="")H.push(q)}return H},missing_some:function(H,K){var z=J.apply({missing:K},this);if(K.length-z.length>=H)return[];else return z}};return J.is_logic=function(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)&&Object.keys(H).length===1},J.truthy=function(H){if(Array.isArray(H)&&H.length===0)return!1;return!!H},J.get_operator=function(H){return Object.keys(H)[0]},J.get_values=function(H){return H[J.get_operator(H)]},J.apply=function(H,K){if(Array.isArray(H))return H.map(function(R){return J.apply(R,K)});if(!J.is_logic(H))return H;var z=J.get_operator(H),q=H[z],F,D,V,O,P;if(!Array.isArray(q))q=[q];if(z==="if"||z=="?:"){for(F=0;F<q.length-1;F+=2)if(J.truthy(J.apply(q[F],K)))return J.apply(q[F+1],K);if(q.length===F+1)return J.apply(q[F],K);return null}else if(z==="and"){for(F=0;F<q.length;F+=1)if(D=J.apply(q[F],K),!J.truthy(D))return D;return D}else if(z==="or"){for(F=0;F<q.length;F+=1)if(D=J.apply(q[F],K),J.truthy(D))return D;return D}else if(z==="filter"){if(O=J.apply(q[0],K),V=q[1],!Array.isArray(O))return[];return O.filter(function(R){return J.truthy(J.apply(V,R))})}else if(z==="map"){if(O=J.apply(q[0],K),V=q[1],!Array.isArray(O))return[];return O.map(function(R){return J.apply(V,R)})}else if(z==="reduce"){if(O=J.apply(q[0],K),V=q[1],P=typeof q[2]<"u"?J.apply(q[2],K):null,!Array.isArray(O))return P;return O.reduce(function(R,w){return J.apply(V,{current:w,accumulator:R})},P)}else if(z==="all"){if(O=J.apply(q[0],K),V=q[1],!Array.isArray(O)||!O.length)return!1;for(F=0;F<O.length;F+=1)if(!J.truthy(J.apply(V,O[F])))return!1;return!0}else if(z==="none"){if(O=J.apply(q[0],K),V=q[1],!Array.isArray(O)||!O.length)return!0;for(F=0;F<O.length;F+=1)if(J.truthy(J.apply(V,O[F])))return!1;return!0}else if(z==="some"){if(O=J.apply(q[0],K),V=q[1],!Array.isArray(O)||!O.length)return!1;for(F=0;F<O.length;F+=1)if(J.truthy(J.apply(V,O[F])))return!0;return!1}if(q=q.map(function(R){return J.apply(R,K)}),G.hasOwnProperty(z)&&typeof G[z]==="function")return G[z].apply(K,q);else if(z.indexOf(".")>0){var N=String(z).split("."),I=G;for(F=0;F<N.length;F++){if(!I.hasOwnProperty(N[F]))throw Error("Unrecognized operation "+z+" (failed at "+N.slice(0,F+1).join(".")+")");I=I[N[F]]}return I.apply(K,q)}throw Error("Unrecognized operation "+z)},J.uses_data=function(H){var K=[];if(J.is_logic(H)){var z=J.get_operator(H),q=H[z];if(!Array.isArray(q))q=[q];if(z==="var")K.push(q[0]);else q.forEach(function(F){K.push.apply(K,J.uses_data(F))})}return Q(K)},J.add_operation=function(H,K){G[H]=K},J.rm_operation=function(H){delete G[H]},J.rule_like=function(H,K){if(K===H)return!0;if(K==="@")return!0;if(K==="number")return typeof H==="number";if(K==="string")return typeof H==="string";if(K==="array")return Array.isArray(H)&&!J.is_logic(H);if(J.is_logic(K)){if(J.is_logic(H)){var z=J.get_operator(K),q=J.get_operator(H);if(z==="@"||z===q)return J.rule_like(J.get_values(H,!1),J.get_values(K,!1))}return!1}if(Array.isArray(K))if(Array.isArray(H)){if(K.length!==H.length)return!1;for(var F=0;F<K.length;F+=1)if(!J.rule_like(H[F],K[F]))return!1;return!0}else return!1;return!1},J})});var mz=i((SW8,XM0)=>{XM0.exports=g3;g3.CAPTURING_PHASE=1;g3.AT_TARGET=2;g3.BUBBLING_PHASE=3;function g3(Q,J){if(this.type="",this.target=null,this.currentTarget=null,this.eventPhase=g3.AT_TARGET,this.bubbles=!1,this.cancelable=!1,this.isTrusted=!1,this.defaultPrevented=!1,this.timeStamp=Date.now(),this._propagationStopped=!1,this._immediatePropagationStopped=!1,this._initialized=!0,this._dispatching=!1,Q)this.type=Q;if(J)for(var G in J)this[G]=J[G]}g3.prototype=Object.create(Object.prototype,{constructor:{value:g3},stopPropagation:{value:function(){this._propagationStopped=!0}},stopImmediatePropagation:{value:function(){this._propagationStopped=!0,this._immediatePropagationStopped=!0}},preventDefault:{value:function(){if(this.cancelable)this.defaultPrevented=!0}},initEvent:{value:function(J,G,H){if(this._initialized=!0,this._dispatching)return;this._propagationStopped=!1,this._immediatePropagationStopped=!1,this.defaultPrevented=!1,this.isTrusted=!1,this.target=null,this.type=J,this.bubbles=G,this.cancelable=H}}})});var IQ0=i((TW8,YM0)=>{var JM0=mz();YM0.exports=CQ0;function CQ0(){JM0.call(this),this.view=null,this.detail=0}CQ0.prototype=Object.create(JM0.prototype,{constructor:{value:CQ0},initUIEvent:{value:function(Q,J,G,H,K){this.initEvent(Q,J,G),this.view=H,this.detail=K}}})});var wQ0=i((kW8,WM0)=>{var GM0=IQ0();WM0.exports=RQ0;function RQ0(){GM0.call(this),this.screenX=this.screenY=this.clientX=this.clientY=0,this.ctrlKey=this.altKey=this.shiftKey=this.metaKey=!1,this.button=0,this.buttons=1,this.relatedTarget=null}RQ0.prototype=Object.create(GM0.prototype,{constructor:{value:RQ0},initMouseEvent:{value:function(Q,J,G,H,K,z,q,F,D,V,O,P,N,I,R){switch(this.initEvent(Q,J,G,H,K),this.screenX=z,this.screenY=q,this.clientX=F,this.clientY=D,this.ctrlKey=V,this.altKey=O,this.shiftKey=P,this.metaKey=N,this.button=I,I){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2;break;default:this.buttons=0;break}this.relatedTarget=R}},getModifierState:{value:function(Q){switch(Q){case"Alt":return this.altKey;case"Control":return this.ctrlKey;case"Shift":return this.shiftKey;case"Meta":return this.metaKey;default:return!1}}}})});var sj=i((yW8,BM0)=>{BM0.exports=aj;var yWQ=1,vWQ=3,xWQ=4,bWQ=5,gWQ=7,hWQ=8,_WQ=9,fWQ=11,mWQ=12,uWQ=13,pWQ=14,lWQ=15,dWQ=17,cWQ=18,iWQ=19,oWQ=20,nWQ=21,aWQ=22,sWQ=23,rWQ=24,tWQ=25,eWQ=[null,"INDEX_SIZE_ERR",null,"HIERARCHY_REQUEST_ERR","WRONG_DOCUMENT_ERR","INVALID_CHARACTER_ERR",null,"NO_MODIFICATION_ALLOWED_ERR","NOT_FOUND_ERR","NOT_SUPPORTED_ERR","INUSE_ATTRIBUTE_ERR","INVALID_STATE_ERR","SYNTAX_ERR","INVALID_MODIFICATION_ERR","NAMESPACE_ERR","INVALID_ACCESS_ERR",null,"TYPE_MISMATCH_ERR","SECURITY_ERR","NETWORK_ERR","ABORT_ERR","URL_MISMATCH_ERR","QUOTA_EXCEEDED_ERR","TIMEOUT_ERR","INVALID_NODE_TYPE_ERR","DATA_CLONE_ERR"],Q5Q=[null,"INDEX_SIZE_ERR (1): the index is not in the allowed range",null,"HIERARCHY_REQUEST_ERR (3): the operation would yield an incorrect nodes model","WRONG_DOCUMENT_ERR (4): the object is in the wrong Document, a call to importNode is required","INVALID_CHARACTER_ERR (5): the string contains invalid characters",null,"NO_MODIFICATION_ALLOWED_ERR (7): the object can not be modified","NOT_FOUND_ERR (8): the object can not be found here","NOT_SUPPORTED_ERR (9): this operation is not supported","INUSE_ATTRIBUTE_ERR (10): setAttributeNode called on owned Attribute","INVALID_STATE_ERR (11): the object is in an invalid state","SYNTAX_ERR (12): the string did not match the expected pattern","INVALID_MODIFICATION_ERR (13): the object can not be modified in this way","NAMESPACE_ERR (14): the operation is not allowed by Namespaces in XML","INVALID_ACCESS_ERR (15): the object does not support the operation or argument",null,"TYPE_MISMATCH_ERR (17): the type of the object does not match the expected type","SECURITY_ERR (18): the operation is insecure","NETWORK_ERR (19): a network error occurred","ABORT_ERR (20): the user aborted an operation","URL_MISMATCH_ERR (21): the given URL does not match another URL","QUOTA_EXCEEDED_ERR (22): the quota has been exceeded","TIMEOUT_ERR (23): a timeout occurred","INVALID_NODE_TYPE_ERR (24): the supplied node is invalid or has an invalid ancestor for this operation","DATA_CLONE_ERR (25): the object can not be cloned."],HM0={INDEX_SIZE_ERR:yWQ,DOMSTRING_SIZE_ERR:2,HIERARCHY_REQUEST_ERR:vWQ,WRONG_DOCUMENT_ERR:xWQ,INVALID_CHARACTER_ERR:bWQ,NO_DATA_ALLOWED_ERR:6,NO_MODIFICATION_ALLOWED_ERR:gWQ,NOT_FOUND_ERR:hWQ,NOT_SUPPORTED_ERR:_WQ,INUSE_ATTRIBUTE_ERR:10,INVALID_STATE_ERR:fWQ,SYNTAX_ERR:mWQ,INVALID_MODIFICATION_ERR:uWQ,NAMESPACE_ERR:pWQ,INVALID_ACCESS_ERR:lWQ,VALIDATION_ERR:16,TYPE_MISMATCH_ERR:dWQ,SECURITY_ERR:cWQ,NETWORK_ERR:iWQ,ABORT_ERR:oWQ,URL_MISMATCH_ERR:nWQ,QUOTA_EXCEEDED_ERR:aWQ,TIMEOUT_ERR:sWQ,INVALID_NODE_TYPE_ERR:rWQ,DATA_CLONE_ERR:tWQ};function aj(Q){Error.call(this),Error.captureStackTrace(this,this.constructor),this.code=Q,this.message=Q5Q[Q],this.name=eWQ[Q]}aj.prototype.__proto__=Error.prototype;for(xZ in HM0)nj={value:HM0[xZ]},Object.defineProperty(aj,xZ,nj),Object.defineProperty(aj.prototype,xZ,nj);var nj,xZ});var rj=i((AM0)=>{AM0.isApiWritable=!globalThis.__domino_frozen__});var J7=i((_6)=>{var X7=sj(),F7=X7,X5Q=rj().isApiWritable;_6.NAMESPACE={HTML:"http://www.w3.org/1999/xhtml",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/",MATHML:"http://www.w3.org/1998/Math/MathML",SVG:"http://www.w3.org/2000/svg",XLINK:"http://www.w3.org/1999/xlink"};_6.IndexSizeError=function(){throw new X7(F7.INDEX_SIZE_ERR)};_6.HierarchyRequestError=function(){throw new X7(F7.HIERARCHY_REQUEST_ERR)};_6.WrongDocumentError=function(){throw new X7(F7.WRONG_DOCUMENT_ERR)};_6.InvalidCharacterError=function(){throw new X7(F7.INVALID_CHARACTER_ERR)};_6.NoModificationAllowedError=function(){throw new X7(F7.NO_MODIFICATION_ALLOWED_ERR)};_6.NotFoundError=function(){throw new X7(F7.NOT_FOUND_ERR)};_6.NotSupportedError=function(){throw new X7(F7.NOT_SUPPORTED_ERR)};_6.InvalidStateError=function(){throw new X7(F7.INVALID_STATE_ERR)};_6.SyntaxError=function(){throw new X7(F7.SYNTAX_ERR)};_6.InvalidModificationError=function(){throw new X7(F7.INVALID_MODIFICATION_ERR)};_6.NamespaceError=function(){throw new X7(F7.NAMESPACE_ERR)};_6.InvalidAccessError=function(){throw new X7(F7.INVALID_ACCESS_ERR)};_6.TypeMismatchError=function(){throw new X7(F7.TYPE_MISMATCH_ERR)};_6.SecurityError=function(){throw new X7(F7.SECURITY_ERR)};_6.NetworkError=function(){throw new X7(F7.NETWORK_ERR)};_6.AbortError=function(){throw new X7(F7.ABORT_ERR)};_6.UrlMismatchError=function(){throw new X7(F7.URL_MISMATCH_ERR)};_6.QuotaExceededError=function(){throw new X7(F7.QUOTA_EXCEEDED_ERR)};_6.TimeoutError=function(){throw new X7(F7.TIMEOUT_ERR)};_6.InvalidNodeTypeError=function(){throw new X7(F7.INVALID_NODE_TYPE_ERR)};_6.DataCloneError=function(){throw new X7(F7.DATA_CLONE_ERR)};_6.nyi=function(){throw Error("NotYetImplemented")};_6.shouldOverride=function(){throw Error("Abstract function; should be overriding in subclass.")};_6.assert=function(Q,J){if(!Q)throw Error("Assertion failed: "+(J||"")+`
`+Error().stack)};_6.expose=function(Q,J){for(var G in Q)Object.defineProperty(J.prototype,G,{value:Q[G],writable:X5Q})};_6.merge=function(Q,J){for(var G in J)Q[G]=J[G]};_6.documentOrder=function(Q,J){return 3-(Q.compareDocumentPosition(J)&6)};_6.toASCIILowerCase=function(Q){return Q.replace(/[A-Z]+/g,function(J){return J.toLowerCase()})};_6.toASCIIUpperCase=function(Q){return Q.replace(/[a-z]+/g,function(J){return J.toUpperCase()})}});var EQ0=i((bW8,zM0)=>{var h3=mz(),J5Q=wQ0(),Y5Q=J7();zM0.exports=KM0;function KM0(){}KM0.prototype={addEventListener:function(J,G,H){if(!G)return;if(H===void 0)H=!1;if(!this._listeners)this._listeners=Object.create(null);if(!this._listeners[J])this._listeners[J]=[];var K=this._listeners[J];for(var z=0,q=K.length;z<q;z++){var F=K[z];if(F.listener===G&&F.capture===H)return}var D={listener:G,capture:H};if(typeof G==="function")D.f=G;K.push(D)},removeEventListener:function(J,G,H){if(H===void 0)H=!1;if(this._listeners){var K=this._listeners[J];if(K)for(var z=0,q=K.length;z<q;z++){var F=K[z];if(F.listener===G&&F.capture===H){if(K.length===1)this._listeners[J]=void 0;else K.splice(z,1);return}}}},dispatchEvent:function(J){return this._dispatchEvent(J,!1)},_dispatchEvent:function(J,G){if(typeof G!=="boolean")G=!1;function H(V,O){var{type:P,eventPhase:N}=O;if(O.currentTarget=V,N!==h3.CAPTURING_PHASE&&V._handlers&&V._handlers[P]){var I=V._handlers[P],R;if(typeof I==="function")R=I.call(O.currentTarget,O);else{var w=I.handleEvent;if(typeof w!=="function")throw TypeError("handleEvent property of event handler object isnot a function.");R=w.call(I,O)}switch(O.type){case"mouseover":if(R===!0)O.preventDefault();break;case"beforeunload":default:if(R===!1)O.preventDefault();break}}var E=V._listeners&&V._listeners[P];if(!E)return;E=E.slice();for(var T=0,y=E.length;T<y;T++){if(O._immediatePropagationStopped)return;var x=E[T];if(N===h3.CAPTURING_PHASE&&!x.capture||N===h3.BUBBLING_PHASE&&x.capture)continue;if(x.f)x.f.call(O.currentTarget,O);else{var b=x.listener.handleEvent;if(typeof b!=="function")throw TypeError("handleEvent property of event listener object is not a function.");b.call(x.listener,O)}}}if(!J._initialized||J._dispatching)Y5Q.InvalidStateError();J.isTrusted=G,J._dispatching=!0,J.target=this;var K=[];for(var z=this.parentNode;z;z=z.parentNode)K.push(z);J.eventPhase=h3.CAPTURING_PHASE;for(var q=K.length-1;q>=0;q--)if(H(K[q],J),J._propagationStopped)break;if(!J._propagationStopped)J.eventPhase=h3.AT_TARGET,H(this,J);if(J.bubbles&&!J._propagationStopped){J.eventPhase=h3.BUBBLING_PHASE;for(var F=0,D=K.length;F<D;F++)if(H(K[F],J),J._propagationStopped)break}if(J._dispatching=!1,J.eventPhase=h3.AT_TARGET,J.currentTarget=null,G&&!J.defaultPrevented&&J instanceof J5Q)switch(J.type){case"mousedown":this._armed={x:J.clientX,y:J.clientY,t:J.timeStamp};break;case"mouseout":case"mouseover":this._armed=null;break;case"mouseup":if(this._isClick(J))this._doClick(J);this._armed=null;break}return!J.defaultPrevented},_isClick:function(Q){return this._armed!==null&&Q.type==="mouseup"&&Q.isTrusted&&Q.button===0&&Q.timeStamp-this._armed.t<1000&&Math.abs(Q.clientX-this._armed.x)<10&&Math.abs(Q.clientY-this._armed.Y)<10},_doClick:function(Q){if(this._click_in_progress)return;this._click_in_progress=!0;var J=this;while(J&&!J._post_click_activation_steps)J=J.parentNode;if(J&&J._pre_click_activation_steps)J._pre_click_activation_steps();var G=this.ownerDocument.createEvent("MouseEvent");G.initMouseEvent("click",!0,!0,this.ownerDocument.defaultView,1,Q.screenX,Q.screenY,Q.clientX,Q.clientY,Q.ctrlKey,Q.altKey,Q.shiftKey,Q.metaKey,Q.button,null);var H=this._dispatchEvent(G,!0);if(J){if(H){if(J._post_click_activation_steps)J._post_click_activation_steps(G)}else if(J._cancelled_activation_steps)J._cancelled_activation_steps()}},_setEventHandler:function(J,G){if(!this._handlers)this._handlers=Object.create(null);this._handlers[J]=G},_getEventHandler:function(J){return this._handlers&&this._handlers[J]||null}}});var SQ0=i((gW8,VM0)=>{var E5=J7(),dY=VM0.exports={valid:function(Q){return E5.assert(Q,"list falsy"),E5.assert(Q._previousSibling,"previous falsy"),E5.assert(Q._nextSibling,"next falsy"),!0},insertBefore:function(Q,J){E5.assert(dY.valid(Q)&&dY.valid(J));var G=Q,H=Q._previousSibling,K=J,z=J._previousSibling;G._previousSibling=z,H._nextSibling=K,z._nextSibling=G,K._previousSibling=H,E5.assert(dY.valid(Q)&&dY.valid(J))},replace:function(Q,J){if(E5.assert(dY.valid(Q)&&(J===null||dY.valid(J))),J!==null)dY.insertBefore(J,Q);dY.remove(Q),E5.assert(dY.valid(Q)&&(J===null||dY.valid(J)))},remove:function(Q){E5.assert(dY.valid(Q));var J=Q._previousSibling;if(J===Q)return;var G=Q._nextSibling;J._nextSibling=G,G._previousSibling=J,Q._previousSibling=Q._nextSibling=Q,E5.assert(dY.valid(Q))}}});var TQ0=i((hW8,LM0)=>{LM0.exports={serializeOne:z5Q,ɵescapeMatchingClosingTag:FM0,ɵescapeClosingCommentTag:DM0,ɵescapeProcessingInstructionContent:MM0};var ZM0=J7(),_3=ZM0.NAMESPACE,qM0={STYLE:!0,SCRIPT:!0,XMP:!0,IFRAME:!0,NOEMBED:!0,NOFRAMES:!0,PLAINTEXT:!0},G5Q={area:!0,base:!0,basefont:!0,bgsound:!0,br:!0,col:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},W5Q={},UM0=/[&<>\u00A0]/g,$M0=/[&"<>\u00A0]/g;function H5Q(Q){if(!UM0.test(Q))return Q;return Q.replace(UM0,(J)=>{switch(J){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case" ":return"&nbsp;"}})}function B5Q(Q){if(!$M0.test(Q))return Q;return Q.replace($M0,(J)=>{switch(J){case"<":return"&lt;";case">":return"&gt;";case"&":return"&amp;";case'"':return"&quot;";case" ":return"&nbsp;"}})}function A5Q(Q){var J=Q.namespaceURI;if(!J)return Q.localName;if(J===_3.XML)return"xml:"+Q.localName;if(J===_3.XLINK)return"xlink:"+Q.localName;if(J===_3.XMLNS)if(Q.localName==="xmlns")return"xmlns";else return"xmlns:"+Q.localName;return Q.name}function FM0(Q,J){let G="</"+J;if(!Q.toLowerCase().includes(G))return Q;let H=[...Q],K=Q.matchAll(new RegExp(G,"ig"));for(let z of K)H[z.index]="&lt;";return H.join("")}var K5Q=/--!?>/;function DM0(Q){if(!K5Q.test(Q))return Q;return Q.replace(/(--\!?)>/g,"$1&gt;")}function MM0(Q){return Q.includes(">")?Q.replaceAll(">","&gt;"):Q}function z5Q(Q,J){var G="";switch(Q.nodeType){case 1:var H=Q.namespaceURI,K=H===_3.HTML,z=K||H===_3.SVG||H===_3.MATHML?Q.localName:Q.tagName;G+="<"+z;for(var q=0,F=Q._numattrs;q<F;q++){var D=Q._attr(q);if(G+=" "+A5Q(D),D.value!==void 0)G+='="'+B5Q(D.value)+'"'}if(G+=">",!(K&&G5Q[z])){var V=Q.serialize();if(qM0[z.toUpperCase()])V=FM0(V,z);if(K&&W5Q[z]&&V.charAt(0)===`
`)G+=`
`;G+=V,G+="</"+z+">"}break;case 3:case 4:var O;if(J.nodeType===1&&J.namespaceURI===_3.HTML)O=J.tagName;else O="";if(qM0[O]||O==="NOSCRIPT"&&J.ownerDocument._scripting_enabled)G+=Q.data;else G+=H5Q(Q.data);break;case 8:G+="<!--"+DM0(Q.data)+"-->";break;case 7:let P=MM0(Q.data);G+="<?"+Q.target+" "+P+"?>";break;case 10:G+="<!DOCTYPE "+Q.name,G+=">";break;default:ZM0.InvalidStateError()}return G}});var PX=i((_W8,IM0)=>{IM0.exports=p9;var CM0=EQ0(),tj=SQ0(),OM0=TQ0(),f6=J7();function p9(){CM0.call(this),this.parentNode=null,this._nextSibling=this._previousSibling=this,this._index=void 0}var cJ=p9.ELEMENT_NODE=1,kQ0=p9.ATTRIBUTE_NODE=2,ej=p9.TEXT_NODE=3,V5Q=p9.CDATA_SECTION_NODE=4,q5Q=p9.ENTITY_REFERENCE_NODE=5,yQ0=p9.ENTITY_NODE=6,PM0=p9.PROCESSING_INSTRUCTION_NODE=7,NM0=p9.COMMENT_NODE=8,bZ=p9.DOCUMENT_NODE=9,cY=p9.DOCUMENT_TYPE_NODE=10,JH=p9.DOCUMENT_FRAGMENT_NODE=11,vQ0=p9.NOTATION_NODE=12,xQ0=p9.DOCUMENT_POSITION_DISCONNECTED=1,bQ0=p9.DOCUMENT_POSITION_PRECEDING=2,gQ0=p9.DOCUMENT_POSITION_FOLLOWING=4,jM0=p9.DOCUMENT_POSITION_CONTAINS=8,hQ0=p9.DOCUMENT_POSITION_CONTAINED_BY=16,_Q0=p9.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC=32;p9.prototype=Object.create(CM0.prototype,{baseURI:{get:f6.nyi},parentElement:{get:function(){return this.parentNode&&this.parentNode.nodeType===cJ?this.parentNode:null}},hasChildNodes:{value:f6.shouldOverride},firstChild:{get:f6.shouldOverride},lastChild:{get:f6.shouldOverride},isConnected:{get:function(){let Q=this;while(Q!=null){if(Q.nodeType===p9.DOCUMENT_NODE)return!0;if(Q=Q.parentNode,Q!=null&&Q.nodeType===p9.DOCUMENT_FRAGMENT_NODE)Q=Q.host}return!1}},previousSibling:{get:function(){var Q=this.parentNode;if(!Q)return null;if(this===Q.firstChild)return null;return this._previousSibling}},nextSibling:{get:function(){var Q=this.parentNode,J=this._nextSibling;if(!Q)return null;if(J===Q.firstChild)return null;return J}},textContent:{get:function(){return null},set:function(Q){}},innerText:{get:function(){return null},set:function(Q){}},_countChildrenOfType:{value:function(Q){var J=0;for(var G=this.firstChild;G!==null;G=G.nextSibling)if(G.nodeType===Q)J++;return J}},_ensureInsertValid:{value:function(J,G,H){var K=this,z,q;if(!J.nodeType)throw TypeError("not a node");switch(K.nodeType){case bZ:case JH:case cJ:break;default:f6.HierarchyRequestError()}if(J.isAncestor(K))f6.HierarchyRequestError();if(G!==null||!H){if(G.parentNode!==K)f6.NotFoundError()}switch(J.nodeType){case JH:case cY:case cJ:case ej:case PM0:case NM0:break;default:f6.HierarchyRequestError()}if(K.nodeType===bZ)switch(J.nodeType){case ej:f6.HierarchyRequestError();break;case JH:if(J._countChildrenOfType(ej)>0)f6.HierarchyRequestError();switch(J._countChildrenOfType(cJ)){case 0:break;case 1:if(G!==null){if(H&&G.nodeType===cY)f6.HierarchyRequestError();for(q=G.nextSibling;q!==null;q=q.nextSibling)if(q.nodeType===cY)f6.HierarchyRequestError()}if(z=K._countChildrenOfType(cJ),H){if(z>0)f6.HierarchyRequestError()}else if(z>1||z===1&&G.nodeType!==cJ)f6.HierarchyRequestError();break;default:f6.HierarchyRequestError()}break;case cJ:if(G!==null){if(H&&G.nodeType===cY)f6.HierarchyRequestError();for(q=G.nextSibling;q!==null;q=q.nextSibling)if(q.nodeType===cY)f6.HierarchyRequestError()}if(z=K._countChildrenOfType(cJ),H){if(z>0)f6.HierarchyRequestError()}else if(z>1||z===1&&G.nodeType!==cJ)f6.HierarchyRequestError();break;case cY:if(G===null){if(K._countChildrenOfType(cJ))f6.HierarchyRequestError()}else for(q=K.firstChild;q!==null;q=q.nextSibling){if(q===G)break;if(q.nodeType===cJ)f6.HierarchyRequestError()}if(z=K._countChildrenOfType(cY),H){if(z>0)f6.HierarchyRequestError()}else if(z>1||z===1&&G.nodeType!==cY)f6.HierarchyRequestError();break}else if(J.nodeType===cY)f6.HierarchyRequestError()}},insertBefore:{value:function(J,G){var H=this;H._ensureInsertValid(J,G,!0);var K=G;if(K===J)K=J.nextSibling;return H.doc.adoptNode(J),J._insertOrReplace(H,K,!1),J}},appendChild:{value:function(Q){return this.insertBefore(Q,null)}},_appendChild:{value:function(Q){Q._insertOrReplace(this,null,!1)}},removeChild:{value:function(J){var G=this;if(!J.nodeType)throw TypeError("not a node");if(J.parentNode!==G)f6.NotFoundError();return J.remove(),J}},replaceChild:{value:function(J,G){var H=this;if(H._ensureInsertValid(J,G,!1),J.doc!==H.doc)H.doc.adoptNode(J);return J._insertOrReplace(H,G,!0),G}},contains:{value:function(J){if(J===null)return!1;if(this===J)return!0;return(this.compareDocumentPosition(J)&hQ0)!==0}},compareDocumentPosition:{value:function(J){if(this===J)return 0;if(this.doc!==J.doc||this.rooted!==J.rooted)return xQ0+_Q0;var G=[],H=[];for(var K=this;K!==null;K=K.parentNode)G.push(K);for(K=J;K!==null;K=K.parentNode)H.push(K);if(G.reverse(),H.reverse(),G[0]!==H[0])return xQ0+_Q0;K=Math.min(G.length,H.length);for(var z=1;z<K;z++)if(G[z]!==H[z])if(G[z].index<H[z].index)return gQ0;else return bQ0;if(G.length<H.length)return gQ0+hQ0;else return bQ0+jM0}},isSameNode:{value:function(J){return this===J}},isEqualNode:{value:function(J){if(!J)return!1;if(J.nodeType!==this.nodeType)return!1;if(!this.isEqual(J))return!1;for(var G=this.firstChild,H=J.firstChild;G&&H;G=G.nextSibling,H=H.nextSibling)if(!G.isEqualNode(H))return!1;return G===null&&H===null}},cloneNode:{value:function(Q){var J=this.clone();if(Q)for(var G=this.firstChild;G!==null;G=G.nextSibling)J._appendChild(G.cloneNode(!0));return J}},lookupPrefix:{value:function(J){var G;if(J===""||J===null||J===void 0)return null;switch(this.nodeType){case cJ:return this._lookupNamespacePrefix(J,this);case bZ:return G=this.documentElement,G?G.lookupPrefix(J):null;case yQ0:case vQ0:case JH:case cY:return null;case kQ0:return G=this.ownerElement,G?G.lookupPrefix(J):null;default:return G=this.parentElement,G?G.lookupPrefix(J):null}}},lookupNamespaceURI:{value:function(J){if(J===""||J===void 0)J=null;var G;switch(this.nodeType){case cJ:return f6.shouldOverride();case bZ:return G=this.documentElement,G?G.lookupNamespaceURI(J):null;case yQ0:case vQ0:case cY:case JH:return null;case kQ0:return G=this.ownerElement,G?G.lookupNamespaceURI(J):null;default:return G=this.parentElement,G?G.lookupNamespaceURI(J):null}}},isDefaultNamespace:{value:function(J){if(J===""||J===void 0)J=null;var G=this.lookupNamespaceURI(null);return G===J}},index:{get:function(){var Q=this.parentNode;if(this===Q.firstChild)return 0;var J=Q.childNodes;if(this._index===void 0||J[this._index]!==this){for(var G=0;G<J.length;G++)J[G]._index=G;f6.assert(J[this._index]===this)}return this._index}},isAncestor:{value:function(Q){if(this.doc!==Q.doc)return!1;if(this.rooted!==Q.rooted)return!1;for(var J=Q;J;J=J.parentNode)if(J===this)return!0;return!1}},ensureSameDoc:{value:function(Q){if(Q.ownerDocument===null)Q.ownerDocument=this.doc;else if(Q.ownerDocument!==this.doc)f6.WrongDocumentError()}},removeChildren:{value:f6.shouldOverride},_insertOrReplace:{value:function(J,G,H){var K=this,z,q;if(K.nodeType===JH&&K.rooted)f6.HierarchyRequestError();if(J._childNodes){if(z=G===null?J._childNodes.length:G.index,K.parentNode===J){var F=K.index;if(F<z)z--}}if(H){if(G.rooted)G.doc.mutateRemove(G);G.parentNode=null}var D=G;if(D===null)D=J.firstChild;var V=K.rooted&&J.rooted;if(K.nodeType===JH){var O=[0,H?1:0],P;for(var N=K.firstChild;N!==null;N=P)P=N.nextSibling,O.push(N),N.parentNode=J;var I=O.length;if(H)tj.replace(D,I>2?O[2]:null);else if(I>2&&D!==null)tj.insertBefore(O[2],D);if(J._childNodes){O[0]=G===null?J._childNodes.length:G._index,J._childNodes.splice.apply(J._childNodes,O);for(q=2;q<I;q++)O[q]._index=O[0]+(q-2)}else if(J._firstChild===G){if(I>2)J._firstChild=O[2];else if(H)J._firstChild=null}if(K._childNodes)K._childNodes.length=0;else K._firstChild=null;if(J.rooted){J.modify();for(q=2;q<I;q++)J.doc.mutateInsert(O[q])}}else{if(G===K)return;if(V)K._remove();else if(K.parentNode)K.remove();if(K.parentNode=J,H){if(tj.replace(D,K),J._childNodes)K._index=z,J._childNodes[z]=K;else if(J._firstChild===G)J._firstChild=K}else{if(D!==null)tj.insertBefore(K,D);if(J._childNodes)K._index=z,J._childNodes.splice(z,0,K);else if(J._firstChild===G)J._firstChild=K}if(V)J.modify(),J.doc.mutateMove(K);else if(J.rooted)J.modify(),J.doc.mutateInsert(K)}}},lastModTime:{get:function(){if(!this._lastModTime)this._lastModTime=this.doc.modclock;return this._lastModTime}},modify:{value:function(){if(this.doc.modclock){var Q=++this.doc.modclock;for(var J=this;J;J=J.parentElement)if(J._lastModTime)J._lastModTime=Q}}},doc:{get:function(){return this.ownerDocument||this}},rooted:{get:function(){return!!this._nid}},normalize:{value:function(){var Q;for(var J=this.firstChild;J!==null;J=Q){if(Q=J.nextSibling,J.normalize)J.normalize();if(J.nodeType!==p9.TEXT_NODE)continue;if(J.nodeValue===""){this.removeChild(J);continue}var G=J.previousSibling;if(G===null)continue;else if(G.nodeType===p9.TEXT_NODE)G.appendData(J.nodeValue),this.removeChild(J)}}},serialize:{value:function(){if(this._innerHTML)return this._innerHTML;var Q="";for(var J=this.firstChild;J!==null;J=J.nextSibling)Q+=OM0.serializeOne(J,this);return Q}},outerHTML:{get:function(){return OM0.serializeOne(this,{nodeType:0})},set:f6.nyi},ELEMENT_NODE:{value:cJ},ATTRIBUTE_NODE:{value:kQ0},TEXT_NODE:{value:ej},CDATA_SECTION_NODE:{value:V5Q},ENTITY_REFERENCE_NODE:{value:q5Q},ENTITY_NODE:{value:yQ0},PROCESSING_INSTRUCTION_NODE:{value:PM0},COMMENT_NODE:{value:NM0},DOCUMENT_NODE:{value:bZ},DOCUMENT_TYPE_NODE:{value:cY},DOCUMENT_FRAGMENT_NODE:{value:JH},NOTATION_NODE:{value:vQ0},DOCUMENT_POSITION_DISCONNECTED:{value:xQ0},DOCUMENT_POSITION_PRECEDING:{value:bQ0},DOCUMENT_POSITION_FOLLOWING:{value:gQ0},DOCUMENT_POSITION_CONTAINS:{value:jM0},DOCUMENT_POSITION_CONTAINED_BY:{value:hQ0},DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC:{value:_Q0}})});var wM0=i((fW8,RM0)=>{RM0.exports=class extends Array{constructor(J){super(J&&J.length||0);if(J)for(var G in J)this[G]=J[G]}item(J){return this[J]||null}}});var SM0=i((mW8,EM0)=>{function U5Q(Q){return this[Q]||null}function $5Q(Q){if(!Q)Q=[];return Q.item=U5Q,Q}EM0.exports=$5Q});var f3=i((uW8,TM0)=>{var fQ0;try{fQ0=wM0()}catch(Q){fQ0=SM0()}TM0.exports=fQ0});var QC=i((pW8,vM0)=>{vM0.exports=yM0;var kM0=PX(),Z5Q=f3();function yM0(){kM0.call(this),this._firstChild=this._childNodes=null}yM0.prototype=Object.create(kM0.prototype,{hasChildNodes:{value:function(){if(this._childNodes)return this._childNodes.length>0;return this._firstChild!==null}},childNodes:{get:function(){return this._ensureChildNodes(),this._childNodes}},firstChild:{get:function(){if(this._childNodes)return this._childNodes.length===0?null:this._childNodes[0];return this._firstChild}},lastChild:{get:function(){var Q=this._childNodes,J;if(Q)return Q.length===0?null:Q[Q.length-1];if(J=this._firstChild,J===null)return null;return J._previousSibling}},_ensureChildNodes:{value:function(){if(this._childNodes)return;var Q=this._firstChild,J=Q,G=this._childNodes=new Z5Q;if(Q)do G.push(J),J=J._nextSibling;while(J!==Q);this._firstChild=null}},removeChildren:{value:function(){var J=this.rooted?this.ownerDocument:null,G=this.firstChild,H;while(G!==null){if(H=G,G=H.nextSibling,J)J.mutateRemove(H);H.parentNode=null}if(this._childNodes)this._childNodes.length=0;else this._firstChild=null;this.modify()}}})});var XC=i((pQ0)=>{pQ0.isValidName=N5Q;pQ0.isValidQName=j5Q;var F5Q=/^[_:A-Za-z][-.:\w]+$/,D5Q=/^([_A-Za-z][-.\w]+|[_A-Za-z][-.\w]+:[_A-Za-z][-.\w]+)$/,gZ="_A-Za-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-",hZ="-._A-Za-z0-9·À-ÖØ-öø-˿̀-ͽͿ-῿‌‍‿⁀⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-",m3="["+gZ+"]["+hZ+"]*",mQ0=gZ+":",uQ0=hZ+":",M5Q=new RegExp("^["+mQ0+"]["+uQ0+"]*$"),L5Q=new RegExp("^("+m3+"|"+m3+":"+m3+")$"),xM0=/[\uD800-\uDB7F\uDC00-\uDFFF]/,bM0=/[\uD800-\uDB7F\uDC00-\uDFFF]/g,gM0=/[\uD800-\uDB7F][\uDC00-\uDFFF]/g;gZ+="\uD800-\uDB7F\uDC00-\uDFFF";hZ+="\uD800-\uDB7F\uDC00-\uDFFF";m3="["+gZ+"]["+hZ+"]*";mQ0=gZ+":";uQ0=hZ+":";var O5Q=new RegExp("^["+mQ0+"]["+uQ0+"]*$"),P5Q=new RegExp("^("+m3+"|"+m3+":"+m3+")$");function N5Q(Q){if(F5Q.test(Q))return!0;if(M5Q.test(Q))return!0;if(!xM0.test(Q))return!1;if(!O5Q.test(Q))return!1;var J=Q.match(bM0),G=Q.match(gM0);return G!==null&&2*G.length===J.length}function j5Q(Q){if(D5Q.test(Q))return!0;if(L5Q.test(Q))return!0;if(!xM0.test(Q))return!1;if(!P5Q.test(Q))return!1;var J=Q.match(bM0),G=Q.match(gM0);return G!==null&&2*G.length===J.length}});var dQ0=i((lQ0)=>{var hM0=J7();lQ0.property=function(Q){if(Array.isArray(Q.type)){var J=Object.create(null);Q.type.forEach(function(K){J[K.value||K]=K.alias||K});var G=Q.missing;if(G===void 0)G=null;var H=Q.invalid;if(H===void 0)H=G;return{get:function(){var K=this._getattr(Q.name);if(K===null)return G;if(K=J[K.toLowerCase()],K!==void 0)return K;if(H!==null)return H;return K},set:function(K){this._setattr(Q.name,K)}}}else if(Q.type===Boolean)return{get:function(){return this.hasAttribute(Q.name)},set:function(K){if(K)this._setattr(Q.name,"");else this.removeAttribute(Q.name)}};else if(Q.type===Number||Q.type==="long"||Q.type==="unsigned long"||Q.type==="limited unsigned long with fallback")return C5Q(Q);else if(!Q.type||Q.type===String)return{get:function(){return this._getattr(Q.name)||""},set:function(K){if(Q.treatNullAsEmptyString&&K===null)K="";this._setattr(Q.name,K)}};else if(typeof Q.type==="function")return Q.type(Q.name,Q);throw Error("Invalid attribute definition")};function C5Q(Q){var J;if(typeof Q.default==="function")J=Q.default;else if(typeof Q.default==="number")J=function(){return Q.default};else J=function(){hM0.assert(!1,typeof Q.default)};var G=Q.type==="unsigned long",H=Q.type==="long",K=Q.type==="limited unsigned long with fallback",z=Q.min,q=Q.max,F=Q.setmin;if(z===void 0){if(G)z=0;if(H)z=-2147483648;if(K)z=1}if(q===void 0){if(G||H||K)q=2147483647}return{get:function(){var D=this._getattr(Q.name),V=Q.float?parseFloat(D):parseInt(D,10);if(D===null||!isFinite(V)||z!==void 0&&V<z||q!==void 0&&V>q)return J.call(this);if(G||H||K){if(!/^[ \t\n\f\r]*[-+]?[0-9]/.test(D))return J.call(this);V=V|0}return V},set:function(D){if(!Q.float)D=Math.floor(D);if(F!==void 0&&D<F)hM0.IndexSizeError(Q.name+" set to "+D);if(G)D=D<0||D>2147483647?J.call(this):D|0;else if(K)D=D<1||D>2147483647?J.call(this):D|0;else if(H)D=D<-2147483648||D>2147483647?J.call(this):D|0;this._setattr(Q.name,String(D))}}}lQ0.registerChangeHandler=function(Q,J,G){var H=Q.prototype;if(!Object.prototype.hasOwnProperty.call(H,"_attributeChangeHandlers"))H._attributeChangeHandlers=Object.create(H._attributeChangeHandlers||null);H._attributeChangeHandlers[J]=G}});var mM0=i((cW8,fM0)=>{fM0.exports=_M0;var I5Q=PX();function _M0(Q,J){this.root=Q,this.filter=J,this.lastModTime=Q.lastModTime,this.done=!1,this.cache=[],this.traverse()}_M0.prototype=Object.create(Object.prototype,{length:{get:function(){if(this.checkcache(),!this.done)this.traverse();return this.cache.length}},item:{value:function(Q){if(this.checkcache(),!this.done&&Q>=this.cache.length)this.traverse();return this.cache[Q]}},checkcache:{value:function(){if(this.lastModTime!==this.root.lastModTime){for(var Q=this.cache.length-1;Q>=0;Q--)this[Q]=void 0;this.cache.length=0,this.done=!1,this.lastModTime=this.root.lastModTime}}},traverse:{value:function(Q){if(Q!==void 0)Q++;var J;while((J=this.next())!==null)if(this[this.cache.length]=J,this.cache.push(J),Q&&this.cache.length===Q)return;this.done=!0}},next:{value:function(){var Q=this.cache.length===0?this.root:this.cache[this.cache.length-1],J;if(Q.nodeType===I5Q.DOCUMENT_NODE)J=Q.documentElement;else J=Q.nextElement(this.root);while(J){if(this.filter(J))return J;J=J.nextElement(this.root)}return null}}})});var iQ0=i((iW8,lM0)=>{var cQ0=J7();lM0.exports=pM0;function pM0(Q,J){this._getString=Q,this._setString=J,this._length=0,this._lastStringValue="",this._update()}Object.defineProperties(pM0.prototype,{length:{get:function(){return this._length}},item:{value:function(Q){var J=uz(this);if(Q<0||Q>=J.length)return null;return J[Q]}},contains:{value:function(Q){Q=String(Q);var J=uz(this);return J.indexOf(Q)>-1}},add:{value:function(){var Q=uz(this);for(var J=0,G=arguments.length;J<G;J++){var H=_Z(arguments[J]);if(Q.indexOf(H)<0)Q.push(H)}this._update(Q)}},remove:{value:function(){var Q=uz(this);for(var J=0,G=arguments.length;J<G;J++){var H=_Z(arguments[J]),K=Q.indexOf(H);if(K>-1)Q.splice(K,1)}this._update(Q)}},toggle:{value:function(J,G){if(J=_Z(J),this.contains(J)){if(G===void 0||G===!1)return this.remove(J),!1;return!0}else{if(G===void 0||G===!0)return this.add(J),!0;return!1}}},replace:{value:function(J,G){if(String(G)==="")cQ0.SyntaxError();J=_Z(J),G=_Z(G);var H=uz(this),K=H.indexOf(J);if(K<0)return!1;var z=H.indexOf(G);if(z<0)H[K]=G;else if(K<z)H[K]=G,H.splice(z,1);else H.splice(K,1);return this._update(H),!0}},toString:{value:function(){return this._getString()}},value:{get:function(){return this._getString()},set:function(Q){this._setString(Q),this._update()}},_update:{value:function(Q){if(Q)uM0(this,Q),this._setString(Q.join(" ").trim());else uM0(this,uz(this));this._lastStringValue=this._getString()}}});function uM0(Q,J){var G=Q._length,H;Q._length=J.length;for(H=0;H<J.length;H++)Q[H]=J[H];for(;H<G;H++)Q[H]=void 0}function _Z(Q){if(Q=String(Q),Q==="")cQ0.SyntaxError();if(/[ \t\r\n\f]/.test(Q))cQ0.InvalidCharacterError();return Q}function R5Q(Q){var J=Q._length,G=Array(J);for(var H=0;H<J;H++)G[H]=Q[H];return G}function uz(Q){var J=Q._getString();if(J===Q._lastStringValue)return R5Q(Q);var G=J.replace(/(^[ \t\r\n\f]+)|([ \t\r\n\f]+$)/g,"");if(G==="")return[];else{var H=Object.create(null);return G.split(/[ \t\r\n\f]+/g).filter(function(K){var z="$"+K;if(H[z])return!1;return H[z]=!0,!0})}}});var WC=i((dz,aM0)=>{var JC=Object.create(null,{location:{get:function(){throw Error("window.location is not supported.")}}}),w5Q=function(Q,J){return Q.compareDocumentPosition(J)},E5Q=function(Q,J){return w5Q(Q,J)&2?1:-1},GC=function(Q){while((Q=Q.nextSibling)&&Q.nodeType!==1);return Q},lz=function(Q){while((Q=Q.previousSibling)&&Q.nodeType!==1);return Q},S5Q=function(Q){if(Q=Q.firstChild)while(Q.nodeType!==1&&(Q=Q.nextSibling));return Q},T5Q=function(Q){if(Q=Q.lastChild)while(Q.nodeType!==1&&(Q=Q.previousSibling));return Q},pz=function(Q){if(!Q.parentNode)return!1;var J=Q.parentNode.nodeType;return J===1||J===9},dM0=function(Q){if(!Q)return Q;var J=Q[0];if(J==='"'||J==="'"){if(Q[Q.length-1]===J)Q=Q.slice(1,-1);else Q=Q.slice(1);return Q.replace(S8.str_escape,function(G){var H=/^\\(?:([0-9A-Fa-f]+)|([\r\n\f]+))/.exec(G);if(!H)return G.slice(1);if(H[2])return"";var K=parseInt(H[1],16);return String.fromCodePoint?String.fromCodePoint(K):String.fromCharCode(K)})}else if(S8.ident.test(Q))return YH(Q);else return Q},YH=function(Q){return Q.replace(S8.escape,function(J){var G=/^\\([0-9A-Fa-f]+)/.exec(J);if(!G)return J[1];var H=parseInt(G[1],16);return String.fromCodePoint?String.fromCodePoint(H):String.fromCharCode(H)})},k5Q=function(){if(Array.prototype.indexOf)return Array.prototype.indexOf;return function(Q,J){var G=this.length;while(G--)if(this[G]===J)return G;return-1}}(),iM0=function(Q,J){var G=S8.inside.source.replace(/</g,Q).replace(/>/g,J);return new RegExp(G)},iJ=function(Q,J,G){return Q=Q.source,Q=Q.replace(J,G.source||G),new RegExp(Q)},cM0=function(Q,J){return Q.replace(/^(?:\w+:\/\/|\/+)/,"").replace(/(?:\/+|\/*#.*?)$/,"").split("/",J).join("/")},y5Q=function(Q,J){var G=Q.replace(/\s+/g,""),H;if(G==="even")G="2n+0";else if(G==="odd")G="2n+1";else if(G.indexOf("n")===-1)G="0n"+G;return H=/^([+-])?(\d+)?n([+-])?(\d+)?$/.exec(G),{group:H[1]==="-"?-(H[2]||1):+(H[2]||1),offset:H[4]?H[3]==="-"?-H[4]:+H[4]:0}},oQ0=function(Q,J,G){var H=y5Q(Q),K=H.group,z=H.offset,q=!G?S5Q:T5Q,F=!G?GC:lz;return function(D){if(!pz(D))return;var V=q(D.parentNode),O=0;while(V){if(J(V,D))O++;if(V===D)return O-=z,K&&O?O%K===0&&O<0===K<0:!O;V=F(V)}}},t7={"*":function(){return function(){return!0}}(),type:function(Q){return Q=Q.toLowerCase(),function(J){return J.nodeName.toLowerCase()===Q}},attr:function(Q,J,G,H){return J=oM0[J],function(K){var z;switch(Q){case"for":z=K.htmlFor;break;case"class":if(z=K.className,z===""&&K.getAttribute("class")==null)z=null;break;case"href":case"src":z=K.getAttribute(Q,2);break;case"title":z=K.getAttribute("title")||null;break;case"id":case"lang":case"dir":case"accessKey":case"hidden":case"tabIndex":case"style":if(K.getAttribute){z=K.getAttribute(Q);break}default:if(K.hasAttribute&&!K.hasAttribute(Q))break;z=K[Q]!=null?K[Q]:K.getAttribute&&K.getAttribute(Q);break}if(z==null)return;if(z=z+"",H)z=z.toLowerCase(),G=G.toLowerCase();return J(z,G)}},":first-child":function(Q){return!lz(Q)&&pz(Q)},":last-child":function(Q){return!GC(Q)&&pz(Q)},":only-child":function(Q){return!lz(Q)&&!GC(Q)&&pz(Q)},":nth-child":function(Q,J){return oQ0(Q,function(){return!0},J)},":nth-last-child":function(Q){return t7[":nth-child"](Q,!0)},":root":function(Q){return Q.ownerDocument.documentElement===Q},":empty":function(Q){return!Q.firstChild},":not":function(Q){var J=aQ0(Q);return function(G){return!J(G)}},":first-of-type":function(Q){if(!pz(Q))return;var J=Q.nodeName;while(Q=lz(Q))if(Q.nodeName===J)return;return!0},":last-of-type":function(Q){if(!pz(Q))return;var J=Q.nodeName;while(Q=GC(Q))if(Q.nodeName===J)return;return!0},":only-of-type":function(Q){return t7[":first-of-type"](Q)&&t7[":last-of-type"](Q)},":nth-of-type":function(Q,J){return oQ0(Q,function(G,H){return G.nodeName===H.nodeName},J)},":nth-last-of-type":function(Q){return t7[":nth-of-type"](Q,!0)},":checked":function(Q){return!!(Q.checked||Q.selected)},":indeterminate":function(Q){return!t7[":checked"](Q)},":enabled":function(Q){return!Q.disabled&&Q.type!=="hidden"},":disabled":function(Q){return!!Q.disabled},":target":function(Q){return Q.id===JC.location.hash.substring(1)},":focus":function(Q){return Q===Q.ownerDocument.activeElement},":is":function(Q){return aQ0(Q)},":matches":function(Q){return t7[":is"](Q)},":nth-match":function(Q,J){var G=Q.split(/\s*,\s*/),H=G.shift(),K=aQ0(G.join(","));return oQ0(H,K,J)},":nth-last-match":function(Q){return t7[":nth-match"](Q,!0)},":links-here":function(Q){return Q+""===JC.location+""},":lang":function(Q){return function(J){while(J){if(J.lang)return J.lang.indexOf(Q)===0;J=J.parentNode}}},":dir":function(Q){return function(J){while(J){if(J.dir)return J.dir===Q;J=J.parentNode}}},":scope":function(Q,J){var G=J||Q.ownerDocument;if(G.nodeType===9)return Q===G.documentElement;return Q===G},":any-link":function(Q){return typeof Q.href==="string"},":local-link":function(Q){if(Q.nodeName)return Q.href&&Q.host===JC.location.host;var J=+Q+1;return function(G){if(!G.href)return;var H=JC.location+"",K=G+"";return cM0(H,J)===cM0(K,J)}},":default":function(Q){return!!Q.defaultSelected},":valid":function(Q){return Q.willValidate||Q.validity&&Q.validity.valid},":invalid":function(Q){return!t7[":valid"](Q)},":in-range":function(Q){return Q.value>Q.min&&Q.value<=Q.max},":out-of-range":function(Q){return!t7[":in-range"](Q)},":required":function(Q){return!!Q.required},":optional":function(Q){return!Q.required},":read-only":function(Q){if(Q.readOnly)return!0;var J=Q.getAttribute("contenteditable"),G=Q.contentEditable,H=Q.nodeName.toLowerCase();return H=H!=="input"&&H!=="textarea",(H||Q.disabled)&&J==null&&G!=="true"},":read-write":function(Q){return!t7[":read-only"](Q)},":hover":function(){throw Error(":hover is not supported.")},":active":function(){throw Error(":active is not supported.")},":link":function(){throw Error(":link is not supported.")},":visited":function(){throw Error(":visited is not supported.")},":column":function(){throw Error(":column is not supported.")},":nth-column":function(){throw Error(":nth-column is not supported.")},":nth-last-column":function(){throw Error(":nth-last-column is not supported.")},":current":function(){throw Error(":current is not supported.")},":past":function(){throw Error(":past is not supported.")},":future":function(){throw Error(":future is not supported.")},":contains":function(Q){return function(J){var G=J.innerText||J.textContent||J.value||"";return G.indexOf(Q)!==-1}},":has":function(Q){return function(J){return nM0(Q,J).length>0}}},oM0={"-":function(){return!0},"=":function(Q,J){return Q===J},"*=":function(Q,J){return Q.indexOf(J)!==-1},"~=":function(Q,J){var G,H,K,z;for(H=0;;H=G+1){if(G=Q.indexOf(J,H),G===-1)return!1;if(K=Q[G-1],z=Q[G+J.length],(!K||K===" ")&&(!z||z===" "))return!0}},"|=":function(Q,J){var G=Q.indexOf(J),H;if(G!==0)return;return H=Q[G+J.length],H==="-"||!H},"^=":function(Q,J){return Q.indexOf(J)===0},"$=":function(Q,J){var G=Q.lastIndexOf(J);return G!==-1&&G+J.length===Q.length},"!=":function(Q,J){return Q!==J}},fZ={" ":function(Q){return function(J){while(J=J.parentNode)if(Q(J))return J}},">":function(Q){return function(J){if(J=J.parentNode)return Q(J)&&J}},"+":function(Q){return function(J){if(J=lz(J))return Q(J)&&J}},"~":function(Q){return function(J){while(J=lz(J))if(Q(J))return J}},noop:function(Q){return function(J){return Q(J)&&J}},ref:function(Q,J){var G;function H(K){var z=K.ownerDocument,q=z.getElementsByTagName("*"),F=q.length;while(F--)if(G=q[F],H.test(K))return G=null,!0;G=null}return H.combinator=function(K){if(!G||!G.getAttribute)return;var z=G.getAttribute(J)||"";if(z[0]==="#")z=z.substring(1);if(z===K.id&&Q(G))return G},H}},S8={escape:/\\(?:[^0-9A-Fa-f\r\n]|[0-9A-Fa-f]{1,6}[\r\n\t ]?)/g,str_escape:/(escape)|\\(\n|\r\n?|\f)/g,nonascii:/[\u00A0-\uFFFF]/,cssid:/(?:(?!-?[0-9])(?:escape|nonascii|[-_a-zA-Z0-9])+)/,qname:/^ *(cssid|\*)/,simple:/^(?:([.#]cssid)|pseudo|attr)/,ref:/^ *\/(cssid)\/ */,combinator:/^(?: +([^ \w*.#\\]) +|( )+|([^ \w*.#\\]))(?! *$)/,attr:/^\[(cssid)(?:([^\w]?=)(inside))?\]/,pseudo:/^(:cssid)(?:\((inside)\))?/,inside:/(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|<[^"'>]*>|\\["'>]|[^"'>])*/,ident:/^(cssid)$/};S8.cssid=iJ(S8.cssid,"nonascii",S8.nonascii);S8.cssid=iJ(S8.cssid,"escape",S8.escape);S8.qname=iJ(S8.qname,"cssid",S8.cssid);S8.simple=iJ(S8.simple,"cssid",S8.cssid);S8.ref=iJ(S8.ref,"cssid",S8.cssid);S8.attr=iJ(S8.attr,"cssid",S8.cssid);S8.pseudo=iJ(S8.pseudo,"cssid",S8.cssid);S8.inside=iJ(S8.inside,`[^"'>]*`,S8.inside);S8.attr=iJ(S8.attr,"inside",iM0("\\[","\\]"));S8.pseudo=iJ(S8.pseudo,"inside",iM0("\\(","\\)"));S8.simple=iJ(S8.simple,"pseudo",S8.pseudo);S8.simple=iJ(S8.simple,"attr",S8.attr);S8.ident=iJ(S8.ident,"cssid",S8.cssid);S8.str_escape=iJ(S8.str_escape,"escape",S8.escape);var mZ=function(Q){var J=Q.replace(/^\s+|\s+$/g,""),G,H=[],K=[],z,q,F,D,V;while(J){if(F=S8.qname.exec(J))J=J.substring(F[0].length),q=YH(F[1]),K.push(YC(q,!0));else if(F=S8.simple.exec(J))J=J.substring(F[0].length),q="*",K.push(YC(q,!0)),K.push(YC(F));else throw SyntaxError("Invalid selector.");while(F=S8.simple.exec(J))J=J.substring(F[0].length),K.push(YC(F));if(J[0]==="!")J=J.substring(1),z=x5Q(),z.qname=q,K.push(z.simple);if(F=S8.ref.exec(J)){J=J.substring(F[0].length),V=fZ.ref(nQ0(K),YH(F[1])),H.push(V.combinator),K=[];continue}if(F=S8.combinator.exec(J)){if(J=J.substring(F[0].length),D=F[1]||F[2]||F[3],D===","){H.push(fZ.noop(nQ0(K)));break}}else D="noop";if(!fZ[D])throw SyntaxError("Bad combinator.");H.push(fZ[D](nQ0(K))),K=[]}if(G=v5Q(H),G.qname=q,G.sel=J,z)z.lname=G.qname,z.test=G,z.qname=z.qname,z.sel=G.sel,G=z;if(V)V.test=G,V.qname=G.qname,V.sel=G.sel,G=V;return G},YC=function(Q,J){if(J)return Q==="*"?t7["*"]:t7.type(Q);if(Q[1])return Q[1][0]==="."?t7.attr("class","~=",YH(Q[1].substring(1)),!1):t7.attr("id","=",YH(Q[1].substring(1)),!1);if(Q[2])return Q[3]?t7[YH(Q[2])](dM0(Q[3])):t7[YH(Q[2])];if(Q[4]){var G=Q[6],H=/["'\s]\s*I$/i.test(G);if(H)G=G.replace(/\s*I$/i,"");return t7.attr(YH(Q[4]),Q[5]||"-",dM0(G),H)}throw SyntaxError("Unknown Selector.")},nQ0=function(Q){var J=Q.length,G;if(J<2)return Q[0];return function(H){if(!H)return;for(G=0;G<J;G++)if(!Q[G](H))return;return!0}},v5Q=function(Q){if(Q.length<2)return function(J){return!!Q[0](J)};return function(J){var G=Q.length;while(G--)if(!(J=Q[G](J)))return;return!0}},x5Q=function(){var Q;function J(G){var H=G.ownerDocument,K=H.getElementsByTagName(J.lname),z=K.length;while(z--)if(J.test(K[z])&&Q===G)return Q=null,!0;Q=null}return J.simple=function(G){return Q=G,!0},J},aQ0=function(Q){var J=mZ(Q),G=[J];while(J.sel)J=mZ(J.sel),G.push(J);if(G.length<2)return J;return function(H){var K=G.length,z=0;for(;z<K;z++)if(G[z](H))return!0}},nM0=function(Q,J){var G=[],H=mZ(Q),K=J.getElementsByTagName(H.qname),z=0,q;while(q=K[z++])if(H(q))G.push(q);if(H.sel){while(H.sel){H=mZ(H.sel),K=J.getElementsByTagName(H.qname),z=0;while(q=K[z++])if(H(q)&&k5Q.call(G,q)===-1)G.push(q)}G.sort(E5Q)}return G};aM0.exports=dz=function(Q,J){var G,H;if(J.nodeType!==11&&Q.indexOf(" ")===-1){if(Q[0]==="#"&&J.rooted&&/^#[A-Z_][-A-Z0-9_]*$/i.test(Q)){if(J.doc._hasMultipleElementsWithId){if(G=Q.substring(1),!J.doc._hasMultipleElementsWithId(G))return H=J.doc.getElementById(G),H?[H]:[]}}if(Q[0]==="."&&/^\.\w+$/.test(Q))return J.getElementsByClassName(Q.substring(1));if(/^\w+$/.test(Q))return J.getElementsByTagName(Q)}return nM0(Q,J)};dz.selectors=t7;dz.operators=oM0;dz.combinators=fZ;dz.matches=function(Q,J){var G={sel:J};do if(G=mZ(G.sel),G(Q))return!0;while(G.sel);return!1}});var HC=i((oW8,sM0)=>{var b5Q=PX(),g5Q=SQ0(),sQ0=function(Q,J){var G=Q.createDocumentFragment();for(var H=0;H<J.length;H++){var K=J[H],z=K instanceof b5Q;G.appendChild(z?K:Q.createTextNode(String(K)))}return G},h5Q={after:{value:function(){var J=Array.prototype.slice.call(arguments),G=this.parentNode,H=this.nextSibling;if(G===null)return;while(H&&J.some(function(z){return z===H}))H=H.nextSibling;var K=sQ0(this.doc,J);G.insertBefore(K,H)}},before:{value:function(){var J=Array.prototype.slice.call(arguments),G=this.parentNode,H=this.previousSibling;if(G===null)return;while(H&&J.some(function(q){return q===H}))H=H.previousSibling;var K=sQ0(this.doc,J),z=H?H.nextSibling:G.firstChild;G.insertBefore(K,z)}},remove:{value:function(){if(this.parentNode===null)return;if(this.doc){if(this.doc._preremoveNodeIterators(this),this.rooted)this.doc.mutateRemove(this)}this._remove(),this.parentNode=null}},_remove:{value:function(){var J=this.parentNode;if(J===null)return;if(J._childNodes)J._childNodes.splice(this.index,1);else if(J._firstChild===this)if(this._nextSibling===this)J._firstChild=null;else J._firstChild=this._nextSibling;g5Q.remove(this),J.modify()}},replaceWith:{value:function(){var J=Array.prototype.slice.call(arguments),G=this.parentNode,H=this.nextSibling;if(G===null)return;while(H&&J.some(function(z){return z===H}))H=H.nextSibling;var K=sQ0(this.doc,J);if(this.parentNode===G)G.replaceChild(K,this);else G.insertBefore(K,H)}}};sM0.exports=h5Q});var rQ0=i((nW8,tM0)=>{var rM0=PX(),_5Q={nextElementSibling:{get:function(){if(this.parentNode){for(var Q=this.nextSibling;Q!==null;Q=Q.nextSibling)if(Q.nodeType===rM0.ELEMENT_NODE)return Q}return null}},previousElementSibling:{get:function(){if(this.parentNode){for(var Q=this.previousSibling;Q!==null;Q=Q.previousSibling)if(Q.nodeType===rM0.ELEMENT_NODE)return Q}return null}}};tM0.exports=_5Q});var tQ0=i((aW8,QL0)=>{QL0.exports=eM0;var cz=J7();function eM0(Q){this.element=Q}Object.defineProperties(eM0.prototype,{length:{get:cz.shouldOverride},item:{value:cz.shouldOverride},getNamedItem:{value:function(J){return this.element.getAttributeNode(J)}},getNamedItemNS:{value:function(J,G){return this.element.getAttributeNodeNS(J,G)}},setNamedItem:{value:cz.nyi},setNamedItemNS:{value:cz.nyi},removeNamedItem:{value:function(J){var G=this.element.getAttributeNode(J);if(G)return this.element.removeAttribute(J),G;cz.NotFoundError()}},removeNamedItemNS:{value:function(J,G){var H=this.element.getAttributeNodeNS(J,G);if(H)return this.element.removeAttributeNS(J,G),H;cz.NotFoundError()}}})});var oz=i((sW8,WL0)=>{WL0.exports=GH;var eQ0=XC(),a9=J7(),IW=a9.NAMESPACE,AC=dQ0(),wG=PX(),Q80=f3(),f5Q=TQ0(),BC=mM0(),iz=sj(),m5Q=iQ0(),X80=WC(),JL0=QC(),u5Q=HC(),p5Q=rQ0(),YL0=tQ0(),XL0=Object.create(null);function GH(Q,J,G,H){JL0.call(this),this.nodeType=wG.ELEMENT_NODE,this.ownerDocument=Q,this.localName=J,this.namespaceURI=G,this.prefix=H,this._tagName=void 0,this._attrsByQName=Object.create(null),this._attrsByLName=Object.create(null),this._attrKeys=[]}function J80(Q,J){if(Q.nodeType===wG.TEXT_NODE)J.push(Q._data);else for(var G=0,H=Q.childNodes.length;G<H;G++)J80(Q.childNodes[G],J)}GH.prototype=Object.create(JL0.prototype,{isHTML:{get:function(){return this.namespaceURI===IW.HTML&&this.ownerDocument.isHTML}},tagName:{get:function(){if(this._tagName===void 0){var J;if(this.prefix===null)J=this.localName;else J=this.prefix+":"+this.localName;if(this.isHTML){var G=XL0[J];if(!G)XL0[J]=G=a9.toASCIIUpperCase(J);J=G}this._tagName=J}return this._tagName}},nodeName:{get:function(){return this.tagName}},nodeValue:{get:function(){return null},set:function(){}},textContent:{get:function(){var Q=[];return J80(this,Q),Q.join("")},set:function(Q){if(this.removeChildren(),Q!==null&&Q!==void 0&&Q!=="")this._appendChild(this.ownerDocument.createTextNode(Q))}},innerText:{get:function(){var Q=[];return J80(this,Q),Q.join("").replace(/[ \t\n\f\r]+/g," ").trim()},set:function(Q){if(this.removeChildren(),Q!==null&&Q!==void 0&&Q!=="")this._appendChild(this.ownerDocument.createTextNode(Q))}},innerHTML:{get:function(){return this.serialize()},set:a9.nyi},outerHTML:{get:function(){return f5Q.serializeOne(this,{nodeType:0})},set:function(Q){var J=this.ownerDocument,G=this.parentNode;if(G===null)return;if(G.nodeType===wG.DOCUMENT_NODE)a9.NoModificationAllowedError();if(G.nodeType===wG.DOCUMENT_FRAGMENT_NODE)G=G.ownerDocument.createElement("body");var H=J.implementation.mozHTMLParser(J._address,G);H.parse(Q===null?"":String(Q),!0),this.replaceWith(H._asDocumentFragment())}},_insertAdjacent:{value:function(J,G){var H=!1;switch(J){case"beforebegin":H=!0;case"afterend":var K=this.parentNode;if(K===null)return null;return K.insertBefore(G,H?this:this.nextSibling);case"afterbegin":H=!0;case"beforeend":return this.insertBefore(G,H?this.firstChild:null);default:return a9.SyntaxError()}}},insertAdjacentElement:{value:function(J,G){if(G.nodeType!==wG.ELEMENT_NODE)throw TypeError("not an element");return J=a9.toASCIILowerCase(String(J)),this._insertAdjacent(J,G)}},insertAdjacentText:{value:function(J,G){var H=this.ownerDocument.createTextNode(G);J=a9.toASCIILowerCase(String(J)),this._insertAdjacent(J,H)}},insertAdjacentHTML:{value:function(J,G){J=a9.toASCIILowerCase(String(J)),G=String(G);var H;switch(J){case"beforebegin":case"afterend":if(H=this.parentNode,H===null||H.nodeType===wG.DOCUMENT_NODE)a9.NoModificationAllowedError();break;case"afterbegin":case"beforeend":H=this;break;default:a9.SyntaxError()}if(!(H instanceof GH)||H.ownerDocument.isHTML&&H.localName==="html"&&H.namespaceURI===IW.HTML)H=H.ownerDocument.createElementNS(IW.HTML,"body");var K=this.ownerDocument.implementation.mozHTMLParser(this.ownerDocument._address,H);K.parse(G,!0),this._insertAdjacent(J,K._asDocumentFragment())}},children:{get:function(){if(!this._children)this._children=new GL0(this);return this._children}},attributes:{get:function(){if(!this._attributes)this._attributes=new G80(this);return this._attributes}},firstElementChild:{get:function(){for(var Q=this.firstChild;Q!==null;Q=Q.nextSibling)if(Q.nodeType===wG.ELEMENT_NODE)return Q;return null}},lastElementChild:{get:function(){for(var Q=this.lastChild;Q!==null;Q=Q.previousSibling)if(Q.nodeType===wG.ELEMENT_NODE)return Q;return null}},childElementCount:{get:function(){return this.children.length}},nextElement:{value:function(Q){if(!Q)Q=this.ownerDocument.documentElement;var J=this.firstElementChild;if(!J){if(this===Q)return null;J=this.nextElementSibling}if(J)return J;for(var G=this.parentElement;G&&G!==Q;G=G.parentElement)if(J=G.nextElementSibling,J)return J;return null}},getElementsByTagName:{value:function(J){var G;if(!J)return new Q80;if(J==="*")G=function(){return!0};else if(this.isHTML)G=l5Q(J);else G=Y80(J);return new BC(this,G)}},getElementsByTagNameNS:{value:function(J,G){var H;if(J==="*"&&G==="*")H=function(){return!0};else if(J==="*")H=Y80(G);else if(G==="*")H=d5Q(J);else H=c5Q(J,G);return new BC(this,H)}},getElementsByClassName:{value:function(J){if(J=String(J).trim(),J===""){var G=new Q80;return G}return J=J.split(/[ \t\r\n\f]+/),new BC(this,i5Q(J))}},getElementsByName:{value:function(J){return new BC(this,o5Q(String(J)))}},clone:{value:function(){var J;if(this.namespaceURI!==IW.HTML||this.prefix||!this.ownerDocument.isHTML)J=this.ownerDocument.createElementNS(this.namespaceURI,this.prefix!==null?this.prefix+":"+this.localName:this.localName);else J=this.ownerDocument.createElement(this.localName);for(var G=0,H=this._attrKeys.length;G<H;G++){var K=this._attrKeys[G],z=this._attrsByLName[K],q=z.cloneNode();q._setOwnerElement(J),J._attrsByLName[K]=q,J._addQName(q)}return J._attrKeys=this._attrKeys.concat(),J}},isEqual:{value:function(J){if(this.localName!==J.localName||this.namespaceURI!==J.namespaceURI||this.prefix!==J.prefix||this._numattrs!==J._numattrs)return!1;for(var G=0,H=this._numattrs;G<H;G++){var K=this._attr(G);if(!J.hasAttributeNS(K.namespaceURI,K.localName))return!1;if(J.getAttributeNS(K.namespaceURI,K.localName)!==K.value)return!1}return!0}},_lookupNamespacePrefix:{value:function(J,G){if(this.namespaceURI&&this.namespaceURI===J&&this.prefix!==null&&G.lookupNamespaceURI(this.prefix)===J)return this.prefix;for(var H=0,K=this._numattrs;H<K;H++){var z=this._attr(H);if(z.prefix==="xmlns"&&z.value===J&&G.lookupNamespaceURI(z.localName)===J)return z.localName}var q=this.parentElement;return q?q._lookupNamespacePrefix(J,G):null}},lookupNamespaceURI:{value:function(J){if(J===""||J===void 0)J=null;if(this.namespaceURI!==null&&this.prefix===J)return this.namespaceURI;for(var G=0,H=this._numattrs;G<H;G++){var K=this._attr(G);if(K.namespaceURI===IW.XMLNS){if(K.prefix==="xmlns"&&K.localName===J||J===null&&K.prefix===null&&K.localName==="xmlns")return K.value||null}}var z=this.parentElement;return z?z.lookupNamespaceURI(J):null}},getAttribute:{value:function(J){var G=this.getAttributeNode(J);return G?G.value:null}},getAttributeNS:{value:function(J,G){var H=this.getAttributeNodeNS(J,G);return H?H.value:null}},getAttributeNode:{value:function(J){if(J=String(J),/[A-Z]/.test(J)&&this.isHTML)J=a9.toASCIILowerCase(J);var G=this._attrsByQName[J];if(!G)return null;if(Array.isArray(G))G=G[0];return G}},getAttributeNodeNS:{value:function(J,G){J=J===void 0||J===null?"":String(J),G=String(G);var H=this._attrsByLName[J+"|"+G];return H?H:null}},hasAttribute:{value:function(J){if(J=String(J),/[A-Z]/.test(J)&&this.isHTML)J=a9.toASCIILowerCase(J);return this._attrsByQName[J]!==void 0}},hasAttributeNS:{value:function(J,G){J=J===void 0||J===null?"":String(J),G=String(G);var H=J+"|"+G;return this._attrsByLName[H]!==void 0}},hasAttributes:{value:function(){return this._numattrs>0}},toggleAttribute:{value:function(J,G){if(J=String(J),!eQ0.isValidName(J))a9.InvalidCharacterError();if(/[A-Z]/.test(J)&&this.isHTML)J=a9.toASCIILowerCase(J);var H=this._attrsByQName[J];if(H===void 0){if(G===void 0||G===!0)return this._setAttribute(J,""),!0;return!1}else{if(G===void 0||G===!1)return this.removeAttribute(J),!1;return!0}}},_setAttribute:{value:function(J,G){var H=this._attrsByQName[J],K;if(!H)H=this._newattr(J),K=!0;else if(Array.isArray(H))H=H[0];if(H.value=G,this._attributes)this._attributes[J]=H;if(K&&this._newattrhook)this._newattrhook(J,G)}},setAttribute:{value:function(J,G){if(J=String(J),!eQ0.isValidName(J))a9.InvalidCharacterError();if(/[A-Z]/.test(J)&&this.isHTML)J=a9.toASCIILowerCase(J);this._setAttribute(J,String(G))}},_setAttributeNS:{value:function(J,G,H){var K=G.indexOf(":"),z,q;if(K<0)z=null,q=G;else z=G.substring(0,K),q=G.substring(K+1);if(J===""||J===void 0)J=null;var F=(J===null?"":J)+"|"+q,D=this._attrsByLName[F],V;if(!D){if(D=new uZ(this,q,z,J),V=!0,this._attrsByLName[F]=D,this._attributes)this._attributes[this._attrKeys.length]=D;this._attrKeys.push(F),this._addQName(D)}if(D.value=H,V&&this._newattrhook)this._newattrhook(G,H)}},setAttributeNS:{value:function(J,G,H){if(J=J===null||J===void 0||J===""?null:String(J),G=String(G),!eQ0.isValidQName(G))a9.InvalidCharacterError();var K=G.indexOf(":"),z=K<0?null:G.substring(0,K);if(z!==null&&J===null||z==="xml"&&J!==IW.XML||(G==="xmlns"||z==="xmlns")&&J!==IW.XMLNS||J===IW.XMLNS&&!(G==="xmlns"||z==="xmlns"))a9.NamespaceError();this._setAttributeNS(J,G,String(H))}},setAttributeNode:{value:function(J){if(J.ownerElement!==null&&J.ownerElement!==this)throw new iz(iz.INUSE_ATTRIBUTE_ERR);var G=null,H=this._attrsByQName[J.name];if(H){if(!Array.isArray(H))H=[H];if(H.some(function(K){return K===J}))return J;else if(J.ownerElement!==null)throw new iz(iz.INUSE_ATTRIBUTE_ERR);H.forEach(function(K){this.removeAttributeNode(K)},this),G=H[0]}return this.setAttributeNodeNS(J),G}},setAttributeNodeNS:{value:function(J){if(J.ownerElement!==null)throw new iz(iz.INUSE_ATTRIBUTE_ERR);var G=J.namespaceURI,H=(G===null?"":G)+"|"+J.localName,K=this._attrsByLName[H];if(K)this.removeAttributeNode(K);if(J._setOwnerElement(this),this._attrsByLName[H]=J,this._attributes)this._attributes[this._attrKeys.length]=J;if(this._attrKeys.push(H),this._addQName(J),this._newattrhook)this._newattrhook(J.name,J.value);return K||null}},removeAttribute:{value:function(J){if(J=String(J),/[A-Z]/.test(J)&&this.isHTML)J=a9.toASCIILowerCase(J);var G=this._attrsByQName[J];if(!G)return;if(Array.isArray(G))if(G.length>2)G=G.shift();else this._attrsByQName[J]=G[1],G=G[0];else this._attrsByQName[J]=void 0;var H=G.namespaceURI,K=(H===null?"":H)+"|"+G.localName;this._attrsByLName[K]=void 0;var z=this._attrKeys.indexOf(K);if(this._attributes)Array.prototype.splice.call(this._attributes,z,1),this._attributes[J]=void 0;this._attrKeys.splice(z,1);var q=G.onchange;if(G._setOwnerElement(null),q)q.call(G,this,G.localName,G.value,null);if(this.rooted)this.ownerDocument.mutateRemoveAttr(G)}},removeAttributeNS:{value:function(J,G){J=J===void 0||J===null?"":String(J),G=String(G);var H=J+"|"+G,K=this._attrsByLName[H];if(!K)return;this._attrsByLName[H]=void 0;var z=this._attrKeys.indexOf(H);if(this._attributes)Array.prototype.splice.call(this._attributes,z,1);this._attrKeys.splice(z,1),this._removeQName(K);var q=K.onchange;if(K._setOwnerElement(null),q)q.call(K,this,K.localName,K.value,null);if(this.rooted)this.ownerDocument.mutateRemoveAttr(K)}},removeAttributeNode:{value:function(J){var G=J.namespaceURI,H=(G===null?"":G)+"|"+J.localName;if(this._attrsByLName[H]!==J)a9.NotFoundError();return this.removeAttributeNS(G,J.localName),J}},getAttributeNames:{value:function(){var J=this;return this._attrKeys.map(function(G){return J._attrsByLName[G].name})}},_getattr:{value:function(J){var G=this._attrsByQName[J];return G?G.value:null}},_setattr:{value:function(J,G){var H=this._attrsByQName[J],K;if(!H)H=this._newattr(J),K=!0;if(H.value=String(G),this._attributes)this._attributes[J]=H;if(K&&this._newattrhook)this._newattrhook(J,G)}},_newattr:{value:function(J){var G=new uZ(this,J,null,null),H="|"+J;if(this._attrsByQName[J]=G,this._attrsByLName[H]=G,this._attributes)this._attributes[this._attrKeys.length]=G;return this._attrKeys.push(H),G}},_addQName:{value:function(Q){var J=Q.name,G=this._attrsByQName[J];if(!G)this._attrsByQName[J]=Q;else if(Array.isArray(G))G.push(Q);else this._attrsByQName[J]=[G,Q];if(this._attributes)this._attributes[J]=Q}},_removeQName:{value:function(Q){var J=Q.name,G=this._attrsByQName[J];if(Array.isArray(G)){var H=G.indexOf(Q);if(a9.assert(H!==-1),G.length===2){if(this._attrsByQName[J]=G[1-H],this._attributes)this._attributes[J]=this._attrsByQName[J]}else if(G.splice(H,1),this._attributes&&this._attributes[J]===Q)this._attributes[J]=G[0]}else if(a9.assert(G===Q),this._attrsByQName[J]=void 0,this._attributes)this._attributes[J]=void 0}},_numattrs:{get:function(){return this._attrKeys.length}},_attr:{value:function(Q){return this._attrsByLName[this._attrKeys[Q]]}},id:AC.property({name:"id"}),className:AC.property({name:"class"}),classList:{get:function(){var Q=this;if(this._classList)return this._classList;var J=new m5Q(function(){return Q.className||""},function(G){Q.className=G});return this._classList=J,J},set:function(Q){this.className=Q}},matches:{value:function(Q){return X80.matches(this,Q)}},closest:{value:function(Q){var J=this;do{if(J.matches&&J.matches(Q))return J;J=J.parentElement||J.parentNode}while(J!==null&&J.nodeType===wG.ELEMENT_NODE);return null}},querySelector:{value:function(Q){return X80(Q,this)[0]}},querySelectorAll:{value:function(Q){var J=X80(Q,this);return J.item?J:new Q80(J)}}});Object.defineProperties(GH.prototype,u5Q);Object.defineProperties(GH.prototype,p5Q);AC.registerChangeHandler(GH,"id",function(Q,J,G,H){if(Q.rooted){if(G)Q.ownerDocument.delId(G,Q);if(H)Q.ownerDocument.addId(H,Q)}});AC.registerChangeHandler(GH,"class",function(Q,J,G,H){if(Q._classList)Q._classList._update()});function uZ(Q,J,G,H,K){this.localName=J,this.prefix=G===null||G===""?null:""+G,this.namespaceURI=H===null||H===""?null:""+H,this.data=K,this._setOwnerElement(Q)}uZ.prototype=Object.create(Object.prototype,{ownerElement:{get:function(){return this._ownerElement}},_setOwnerElement:{value:function(J){if(this._ownerElement=J,this.prefix===null&&this.namespaceURI===null&&J)this.onchange=J._attributeChangeHandlers[this.localName];else this.onchange=null}},name:{get:function(){return this.prefix?this.prefix+":"+this.localName:this.localName}},specified:{get:function(){return!0}},value:{get:function(){return this.data},set:function(Q){var J=this.data;if(Q=Q===void 0?"":Q+"",Q===J)return;if(this.data=Q,this.ownerElement){if(this.onchange)this.onchange(this.ownerElement,this.localName,J,Q);if(this.ownerElement.rooted)this.ownerElement.ownerDocument.mutateAttr(this,J)}}},cloneNode:{value:function(J){return new uZ(null,this.localName,this.prefix,this.namespaceURI,this.data)}},nodeType:{get:function(){return wG.ATTRIBUTE_NODE}},nodeName:{get:function(){return this.name}},nodeValue:{get:function(){return this.value},set:function(Q){this.value=Q}},textContent:{get:function(){return this.value},set:function(Q){if(Q===null||Q===void 0)Q="";this.value=Q}},innerText:{get:function(){return this.value},set:function(Q){if(Q===null||Q===void 0)Q="";this.value=Q}}});GH._Attr=uZ;function G80(Q){YL0.call(this,Q);for(var J in Q._attrsByQName)this[J]=Q._attrsByQName[J];for(var G=0;G<Q._attrKeys.length;G++)this[G]=Q._attrsByLName[Q._attrKeys[G]]}G80.prototype=Object.create(YL0.prototype,{length:{get:function(){return this.element._attrKeys.length},set:function(){}},item:{value:function(Q){if(Q=Q>>>0,Q>=this.length)return null;return this.element._attrsByLName[this.element._attrKeys[Q]]}}});if(globalThis.Symbol?.iterator)G80.prototype[globalThis.Symbol.iterator]=function(){var Q=0,J=this.length,G=this;return{next:function(){if(Q<J)return{value:G.item(Q++)};return{done:!0}}}};function GL0(Q){this.element=Q,this.updateCache()}GL0.prototype=Object.create(Object.prototype,{length:{get:function(){return this.updateCache(),this.childrenByNumber.length}},item:{value:function(J){return this.updateCache(),this.childrenByNumber[J]||null}},namedItem:{value:function(J){return this.updateCache(),this.childrenByName[J]||null}},namedItems:{get:function(){return this.updateCache(),this.childrenByName}},updateCache:{value:function(){var J=/^(a|applet|area|embed|form|frame|frameset|iframe|img|object)$/;if(this.lastModTime!==this.element.lastModTime){this.lastModTime=this.element.lastModTime;var G=this.childrenByNumber&&this.childrenByNumber.length||0;for(var H=0;H<G;H++)this[H]=void 0;this.childrenByNumber=[],this.childrenByName=Object.create(null);for(var K=this.element.firstChild;K!==null;K=K.nextSibling)if(K.nodeType===wG.ELEMENT_NODE){this[this.childrenByNumber.length]=K,this.childrenByNumber.push(K);var z=K.getAttribute("id");if(z&&!this.childrenByName[z])this.childrenByName[z]=K;var q=K.getAttribute("name");if(q&&this.element.namespaceURI===IW.HTML&&J.test(this.element.localName)&&!this.childrenByName[q])this.childrenByName[z]=K}}}}});function Y80(Q){return function(J){return J.localName===Q}}function l5Q(Q){var J=a9.toASCIILowerCase(Q);if(J===Q)return Y80(Q);return function(G){return G.isHTML?G.localName===J:G.localName===Q}}function d5Q(Q){return function(J){return J.namespaceURI===Q}}function c5Q(Q,J){return function(G){return G.namespaceURI===Q&&G.localName===J}}function i5Q(Q){return function(J){return Q.every(function(G){return J.classList.contains(G)})}}function o5Q(Q){return function(J){if(J.namespaceURI!==IW.HTML)return!1;return J.getAttribute("name")===Q}}});var W80=i((rW8,zL0)=>{zL0.exports=KL0;var BL0=PX(),n5Q=f3(),AL0=J7(),HL0=AL0.HierarchyRequestError,a5Q=AL0.NotFoundError;function KL0(){BL0.call(this)}KL0.prototype=Object.create(BL0.prototype,{hasChildNodes:{value:function(){return!1}},firstChild:{value:null},lastChild:{value:null},insertBefore:{value:function(Q,J){if(!Q.nodeType)throw TypeError("not a node");HL0()}},replaceChild:{value:function(Q,J){if(!Q.nodeType)throw TypeError("not a node");HL0()}},removeChild:{value:function(Q){if(!Q.nodeType)throw TypeError("not a node");a5Q()}},removeChildren:{value:function(){}},childNodes:{get:function(){if(!this._childNodes)this._childNodes=new n5Q;return this._childNodes}}})});var pZ=i((tW8,UL0)=>{UL0.exports=KC;var qL0=W80(),VL0=J7(),s5Q=HC(),r5Q=rQ0();function KC(){qL0.call(this)}KC.prototype=Object.create(qL0.prototype,{substringData:{value:function(J,G){if(arguments.length<2)throw TypeError("Not enough arguments");if(J=J>>>0,G=G>>>0,J>this.data.length||J<0||G<0)VL0.IndexSizeError();return this.data.substring(J,J+G)}},appendData:{value:function(J){if(arguments.length<1)throw TypeError("Not enough arguments");this.data+=String(J)}},insertData:{value:function(J,G){return this.replaceData(J,0,G)}},deleteData:{value:function(J,G){return this.replaceData(J,G,"")}},replaceData:{value:function(J,G,H){var K=this.data,z=K.length;if(J=J>>>0,G=G>>>0,H=String(H),J>z||J<0)VL0.IndexSizeError();if(J+G>z)G=z-J;var q=K.substring(0,J),F=K.substring(J+G);this.data=q+H+F}},isEqual:{value:function(J){return this._data===J._data}},length:{get:function(){return this.data.length}}});Object.defineProperties(KC.prototype,s5Q);Object.defineProperties(KC.prototype,r5Q)});var B80=i((eW8,DL0)=>{DL0.exports=H80;var $L0=J7(),ZL0=PX(),FL0=pZ();function H80(Q,J){FL0.call(this),this.nodeType=ZL0.TEXT_NODE,this.ownerDocument=Q,this._data=J,this._index=void 0}var lZ={get:function(){return this._data},set:function(Q){if(Q===null||Q===void 0)Q="";else Q=String(Q);if(Q===this._data)return;if(this._data=Q,this.rooted)this.ownerDocument.mutateValue(this);if(this.parentNode&&this.parentNode._textchangehook)this.parentNode._textchangehook(this)}};H80.prototype=Object.create(FL0.prototype,{nodeName:{value:"#text"},nodeValue:lZ,textContent:lZ,innerText:lZ,data:{get:lZ.get,set:function(Q){lZ.set.call(this,Q===null?"":String(Q))}},splitText:{value:function(J){if(J>this._data.length||J<0)$L0.IndexSizeError();var G=this._data.substring(J),H=this.ownerDocument.createTextNode(G);this.data=this.data.substring(0,J);var K=this.parentNode;if(K!==null)K.insertBefore(H,this.nextSibling);return H}},wholeText:{get:function(){var J=this.textContent;for(var G=this.nextSibling;G;G=G.nextSibling){if(G.nodeType!==ZL0.TEXT_NODE)break;J+=G.textContent}return J}},replaceWholeText:{value:$L0.nyi},clone:{value:function(){return new H80(this.ownerDocument,this._data)}}})});var K80=i((Q58,LL0)=>{LL0.exports=A80;var t5Q=PX(),ML0=pZ();function A80(Q,J){ML0.call(this),this.nodeType=t5Q.COMMENT_NODE,this.ownerDocument=Q,this._data=J}var dZ={get:function(){return this._data},set:function(Q){if(Q===null||Q===void 0)Q="";else Q=String(Q);if(this._data=Q,this.rooted)this.ownerDocument.mutateValue(this)}};A80.prototype=Object.create(ML0.prototype,{nodeName:{value:"#comment"},nodeValue:dZ,textContent:dZ,innerText:dZ,data:{get:dZ.get,set:function(Q){dZ.set.call(this,Q===null?"":String(Q))}},clone:{value:function(){return new A80(this.ownerDocument,this._data)}}})});var V80=i((X58,NL0)=>{NL0.exports=z80;var e5Q=PX(),Q4Q=f3(),PL0=QC(),zC=oz(),X4Q=WC(),OL0=J7();function z80(Q){PL0.call(this),this.nodeType=e5Q.DOCUMENT_FRAGMENT_NODE,this.ownerDocument=Q}z80.prototype=Object.create(PL0.prototype,{nodeName:{value:"#document-fragment"},nodeValue:{get:function(){return null},set:function(){}},textContent:Object.getOwnPropertyDescriptor(zC.prototype,"textContent"),innerText:Object.getOwnPropertyDescriptor(zC.prototype,"innerText"),querySelector:{value:function(Q){var J=this.querySelectorAll(Q);return J.length?J[0]:null}},querySelectorAll:{value:function(Q){var J=Object.create(this);J.isHTML=!0,J.getElementsByTagName=zC.prototype.getElementsByTagName,J.nextElement=Object.getOwnPropertyDescriptor(zC.prototype,"firstElementChild").get;var G=X4Q(Q,J);return G.item?G:new Q4Q(G)}},clone:{value:function(){return new z80(this.ownerDocument)}},isEqual:{value:function(J){return!0}},innerHTML:{get:function(){return this.serialize()},set:OL0.nyi},outerHTML:{get:function(){return this.serialize()},set:OL0.nyi}})});var U80=i((J58,CL0)=>{CL0.exports=q80;var J4Q=PX(),jL0=pZ();function q80(Q,J,G){jL0.call(this),this.nodeType=J4Q.PROCESSING_INSTRUCTION_NODE,this.ownerDocument=Q,this.target=J,this._data=G}var cZ={get:function(){return this._data},set:function(Q){if(Q===null||Q===void 0)Q="";else Q=String(Q);if(this._data=Q,this.rooted)this.ownerDocument.mutateValue(this)}};q80.prototype=Object.create(jL0.prototype,{nodeName:{get:function(){return this.target}},nodeValue:cZ,textContent:cZ,innerText:cZ,data:{get:cZ.get,set:function(Q){cZ.set.call(this,Q===null?"":String(Q))}},clone:{value:function(){return new q80(this.ownerDocument,this.target,this._data)}},isEqual:{value:function(J){return this.target===J.target&&this._data===J._data}}})});var iZ=i((Y58,IL0)=>{var $80={FILTER_ACCEPT:1,FILTER_REJECT:2,FILTER_SKIP:3,SHOW_ALL:4294967295,SHOW_ELEMENT:1,SHOW_ATTRIBUTE:2,SHOW_TEXT:4,SHOW_CDATA_SECTION:8,SHOW_ENTITY_REFERENCE:16,SHOW_ENTITY:32,SHOW_PROCESSING_INSTRUCTION:64,SHOW_COMMENT:128,SHOW_DOCUMENT:256,SHOW_DOCUMENT_TYPE:512,SHOW_DOCUMENT_FRAGMENT:1024,SHOW_NOTATION:2048};IL0.exports=$80.constructor=$80.prototype=$80});var F80=i((W58,wL0)=>{var G58=wL0.exports={nextSkippingChildren:Y4Q,nextAncestorSibling:Z80,next:G4Q,previous:W4Q,deepLastChild:RL0};function Y4Q(Q,J){if(Q===J)return null;if(Q.nextSibling!==null)return Q.nextSibling;return Z80(Q,J)}function Z80(Q,J){for(Q=Q.parentNode;Q!==null;Q=Q.parentNode){if(Q===J)return null;if(Q.nextSibling!==null)return Q.nextSibling}return null}function G4Q(Q,J){var G=Q.firstChild;if(G!==null)return G;if(Q===J)return null;if(G=Q.nextSibling,G!==null)return G;return Z80(Q,J)}function RL0(Q){while(Q.lastChild)Q=Q.lastChild;return Q}function W4Q(Q,J){var G=Q.previousSibling;if(G!==null)return RL0(G);if(G=Q.parentNode,G===J)return null;return G}});var xL0=i((H58,vL0)=>{vL0.exports=yL0;var H4Q=PX(),NX=iZ(),EL0=F80(),kL0=J7(),D80={first:"firstChild",last:"lastChild",next:"firstChild",previous:"lastChild"},M80={first:"nextSibling",last:"previousSibling",next:"nextSibling",previous:"previousSibling"};function SL0(Q,J){var G,H,K,z,q;H=Q._currentNode[D80[J]];while(H!==null){if(z=Q._internalFilter(H),z===NX.FILTER_ACCEPT)return Q._currentNode=H,H;if(z===NX.FILTER_SKIP){if(G=H[D80[J]],G!==null){H=G;continue}}while(H!==null){if(q=H[M80[J]],q!==null){H=q;break}if(K=H.parentNode,K===null||K===Q.root||K===Q._currentNode)return null;else H=K}}return null}function TL0(Q,J){var G,H,K;if(G=Q._currentNode,G===Q.root)return null;while(!0){K=G[M80[J]];while(K!==null){if(G=K,H=Q._internalFilter(G),H===NX.FILTER_ACCEPT)return Q._currentNode=G,G;if(K=G[D80[J]],H===NX.FILTER_REJECT||K===null)K=G[M80[J]]}if(G=G.parentNode,G===null||G===Q.root)return null;if(Q._internalFilter(G)===NX.FILTER_ACCEPT)return null}}function yL0(Q,J,G){if(!Q||!Q.nodeType)kL0.NotSupportedError();this._root=Q,this._whatToShow=Number(J)||0,this._filter=G||null,this._active=!1,this._currentNode=Q}Object.defineProperties(yL0.prototype,{root:{get:function(){return this._root}},whatToShow:{get:function(){return this._whatToShow}},filter:{get:function(){return this._filter}},currentNode:{get:function(){return this._currentNode},set:function(J){if(!(J instanceof H4Q))throw TypeError("Not a Node");this._currentNode=J}},_internalFilter:{value:function(J){var G,H;if(this._active)kL0.InvalidStateError();if(!(1<<J.nodeType-1&this._whatToShow))return NX.FILTER_SKIP;if(H=this._filter,H===null)G=NX.FILTER_ACCEPT;else{this._active=!0;try{if(typeof H==="function")G=H(J);else G=H.acceptNode(J)}finally{this._active=!1}}return+G}},parentNode:{value:function(){var J=this._currentNode;while(J!==this.root){if(J=J.parentNode,J===null)return null;if(this._internalFilter(J)===NX.FILTER_ACCEPT)return this._currentNode=J,J}return null}},firstChild:{value:function(){return SL0(this,"first")}},lastChild:{value:function(){return SL0(this,"last")}},previousSibling:{value:function(){return TL0(this,"previous")}},nextSibling:{value:function(){return TL0(this,"next")}},previousNode:{value:function(){var J,G,H,K;J=this._currentNode;while(J!==this._root){for(H=J.previousSibling;H;H=J.previousSibling){if(J=H,G=this._internalFilter(J),G===NX.FILTER_REJECT)continue;for(K=J.lastChild;K;K=J.lastChild)if(J=K,G=this._internalFilter(J),G===NX.FILTER_REJECT)break;if(G===NX.FILTER_ACCEPT)return this._currentNode=J,J}if(J===this.root||J.parentNode===null)return null;if(J=J.parentNode,this._internalFilter(J)===NX.FILTER_ACCEPT)return this._currentNode=J,J}return null}},nextNode:{value:function(){var J,G,H,K;J=this._currentNode,G=NX.FILTER_ACCEPT;Q:while(!0){for(H=J.firstChild;H;H=J.firstChild)if(J=H,G=this._internalFilter(J),G===NX.FILTER_ACCEPT)return this._currentNode=J,J;else if(G===NX.FILTER_REJECT)break;for(K=EL0.nextSkippingChildren(J,this.root);K;K=EL0.nextSkippingChildren(J,this.root))if(J=K,G=this._internalFilter(J),G===NX.FILTER_ACCEPT)return this._currentNode=J,J;else if(G===NX.FILTER_SKIP)continue Q;return null}}},toString:{value:function(){return"[object TreeWalker]"}}})});var mL0=i((B58,fL0)=>{fL0.exports=_L0;var L80=iZ(),O80=F80(),hL0=J7();function B4Q(Q,J,G){if(G)return O80.next(Q,J);else{if(Q===J)return null;return O80.previous(Q,null)}}function bL0(Q,J){for(;J;J=J.parentNode)if(Q===J)return!0;return!1}function gL0(Q,J){var G,H;G=Q._referenceNode,H=Q._pointerBeforeReferenceNode;while(!0){if(H===J)H=!H;else if(G=B4Q(G,Q._root,J),G===null)return null;var K=Q._internalFilter(G);if(K===L80.FILTER_ACCEPT)break}return Q._referenceNode=G,Q._pointerBeforeReferenceNode=H,G}function _L0(Q,J,G){if(!Q||!Q.nodeType)hL0.NotSupportedError();this._root=Q,this._referenceNode=Q,this._pointerBeforeReferenceNode=!0,this._whatToShow=Number(J)||0,this._filter=G||null,this._active=!1,Q.doc._attachNodeIterator(this)}Object.defineProperties(_L0.prototype,{root:{get:function(){return this._root}},referenceNode:{get:function(){return this._referenceNode}},pointerBeforeReferenceNode:{get:function(){return this._pointerBeforeReferenceNode}},whatToShow:{get:function(){return this._whatToShow}},filter:{get:function(){return this._filter}},_internalFilter:{value:function(J){var G,H;if(this._active)hL0.InvalidStateError();if(!(1<<J.nodeType-1&this._whatToShow))return L80.FILTER_SKIP;if(H=this._filter,H===null)G=L80.FILTER_ACCEPT;else{this._active=!0;try{if(typeof H==="function")G=H(J);else G=H.acceptNode(J)}finally{this._active=!1}}return+G}},_preremove:{value:function(J){if(bL0(J,this._root))return;if(!bL0(J,this._referenceNode))return;if(this._pointerBeforeReferenceNode){var G=J;while(G.lastChild)G=G.lastChild;if(G=O80.next(G,this.root),G){this._referenceNode=G;return}this._pointerBeforeReferenceNode=!1}if(J.previousSibling===null)this._referenceNode=J.parentNode;else{this._referenceNode=J.previousSibling;var H;for(H=this._referenceNode.lastChild;H;H=this._referenceNode.lastChild)this._referenceNode=H}}},nextNode:{value:function(){return gL0(this,!0)}},previousNode:{value:function(){return gL0(this,!1)}},detach:{value:function(){}},toString:{value:function(){return"[object NodeIterator]"}}})});var VC=i((A58,uL0)=>{uL0.exports=jX;function jX(Q){if(!Q)return Object.create(jX.prototype);this.url=Q.replace(/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g,"");var J=jX.pattern.exec(this.url);if(J){if(J[2])this.scheme=J[2];if(J[4]){var G=J[4].match(jX.userinfoPattern);if(G)this.username=G[1],this.password=G[3],J[4]=J[4].substring(G[0].length);if(J[4].match(jX.portPattern)){var H=J[4].lastIndexOf(":");this.host=J[4].substring(0,H),this.port=J[4].substring(H+1)}else this.host=J[4]}if(J[5])this.path=J[5];if(J[6])this.query=J[7];if(J[8])this.fragment=J[9]}}jX.pattern=/^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/;jX.userinfoPattern=/^([^@:]*)(:([^@]*))?@/;jX.portPattern=/:\d+$/;jX.authorityPattern=/^[^:\/?#]+:\/\//;jX.hierarchyPattern=/^[^:\/?#]+:\//;jX.percentEncode=function(J){var G=J.charCodeAt(0);if(G<256)return"%"+G.toString(16);else throw Error("can't percent-encode codepoints > 255 yet")};jX.prototype={constructor:jX,isAbsolute:function(){return!!this.scheme},isAuthorityBased:function(){return jX.authorityPattern.test(this.url)},isHierarchical:function(){return jX.hierarchyPattern.test(this.url)},toString:function(){var Q="";if(this.scheme!==void 0)Q+=this.scheme+":";if(this.isAbsolute()){if(Q+="//",this.username||this.password){if(Q+=this.username||"",this.password)Q+=":"+this.password;Q+="@"}if(this.host)Q+=this.host}if(this.port!==void 0)Q+=":"+this.port;if(this.path!==void 0)Q+=this.path;if(this.query!==void 0)Q+="?"+this.query;if(this.fragment!==void 0)Q+="#"+this.fragment;return Q},resolve:function(Q){var J=this,G=new jX(Q),H=new jX;if(G.scheme!==void 0)H.scheme=G.scheme,H.username=G.username,H.password=G.password,H.host=G.host,H.port=G.port,H.path=z(G.path),H.query=G.query;else if(H.scheme=J.scheme,G.host!==void 0)H.username=G.username,H.password=G.password,H.host=G.host,H.port=G.port,H.path=z(G.path),H.query=G.query;else if(H.username=J.username,H.password=J.password,H.host=J.host,H.port=J.port,!G.path)if(H.path=J.path,G.query!==void 0)H.query=G.query;else H.query=J.query;else{if(G.path.charAt(0)==="/")H.path=z(G.path);else H.path=K(J.path,G.path),H.path=z(H.path);H.query=G.query}return H.fragment=G.fragment,H.toString();function K(q,F){if(J.host!==void 0&&!J.path)return"/"+F;var D=q.lastIndexOf("/");if(D===-1)return F;else return q.substring(0,D+1)+F}function z(q){if(!q)return q;var F="";while(q.length>0){if(q==="."||q===".."){q="";break}var D=q.substring(0,2),V=q.substring(0,3),O=q.substring(0,4);if(V==="../")q=q.substring(3);else if(D==="./")q=q.substring(2);else if(V==="/./")q="/"+q.substring(3);else if(D==="/."&&q.length===2)q="/";else if(O==="/../"||V==="/.."&&q.length===3)q="/"+q.substring(4),F=F.replace(/\/?[^\/]*$/,"");else{var P=q.match(/(\/?([^\/]*))/)[0];F+=P,q=q.substring(P.length)}}return F}}}});var dL0=i((K58,lL0)=>{lL0.exports=P80;var pL0=mz();function P80(Q,J){pL0.call(this,Q,J)}P80.prototype=Object.create(pL0.prototype,{constructor:{value:P80}})});var N80=i((z58,cL0)=>{cL0.exports={Event:mz(),UIEvent:IQ0(),MouseEvent:wQ0(),CustomEvent:dL0()}});var oL0=i((nz)=>{Object.defineProperty(nz,"__esModule",{value:!0});nz.hyphenate=nz.parse=void 0;function A4Q(Q){let J=[],G=0,H=0,K=0,z=0,q=0,F=null;while(G<Q.length)switch(Q.charCodeAt(G++)){case 40:H++;break;case 41:H--;break;case 39:if(K===0)K=39;else if(K===39&&Q.charCodeAt(G-1)!==92)K=0;break;case 34:if(K===0)K=34;else if(K===34&&Q.charCodeAt(G-1)!==92)K=0;break;case 58:if(!F&&H===0&&K===0)F=iL0(Q.substring(q,G-1).trim()),z=G;break;case 59:if(F&&z>0&&H===0&&K===0){let V=Q.substring(z,G-1).trim();J.push(F,V),q=G,z=0,F=null}break}if(F&&z){let D=Q.slice(z).trim();J.push(F,D)}return J}nz.parse=A4Q;function iL0(Q){return Q.replace(/[a-z][A-Z]/g,(J)=>{return J.charAt(0)+"-"+J.charAt(1)}).toLowerCase()}nz.hyphenate=iL0});var qC=i((q58,tL0)=>{var{parse:K4Q}=oL0();tL0.exports=function(Q){let J=new rL0(Q);return new Proxy(J,{get:function(H,K){return K in H?H[K]:H.getPropertyValue(nL0(K))},has:function(H,K){return!0},set:function(H,K,z){if(K in H)H[K]=z;else H.setProperty(nL0(K),z??void 0);return!0}})};function nL0(Q){return Q.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}function rL0(Q){this._element=Q}var aL0="!important";function sL0(Q){let J={property:{},priority:{}};if(!Q)return J;let G=K4Q(Q);if(G.length<2)return J;for(let H=0;H<G.length;H+=2){let K=G[H],z=G[H+1];if(z.endsWith(aL0))J.priority[K]="important",z=z.slice(0,-aL0.length).trim();J.property[K]=z}return J}var az={};rL0.prototype=Object.create(Object.prototype,{_parsed:{get:function(){if(!this._parsedStyles||this.cssText!==this._lastParsedText){var Q=this.cssText;this._parsedStyles=sL0(Q),this._lastParsedText=Q,delete this._names}return this._parsedStyles}},_serialize:{value:function(){var Q=this._parsed,J="";for(var G in Q.property){if(J)J+=" ";if(J+=G+": "+Q.property[G],Q.priority[G])J+=" !"+Q.priority[G];J+=";"}this.cssText=J,this._lastParsedText=J,delete this._names}},cssText:{get:function(){return this._element.getAttribute("style")},set:function(Q){this._element.setAttribute("style",Q)}},length:{get:function(){if(!this._names)this._names=Object.getOwnPropertyNames(this._parsed.property);return this._names.length}},item:{value:function(Q){if(!this._names)this._names=Object.getOwnPropertyNames(this._parsed.property);return this._names[Q]}},getPropertyValue:{value:function(Q){return Q=Q.toLowerCase(),this._parsed.property[Q]||""}},getPropertyPriority:{value:function(Q){return Q=Q.toLowerCase(),this._parsed.priority[Q]||""}},setProperty:{value:function(Q,J,G){if(Q=Q.toLowerCase(),J===null||J===void 0)J="";if(G===null||G===void 0)G="";if(J!==az)J=""+J;if(J=J.trim(),J===""){this.removeProperty(Q);return}if(G!==""&&G!==az&&!/^important$/i.test(G))return;var H=this._parsed;if(J===az){if(!H.property[Q])return;if(G!=="")H.priority[Q]="important";else delete H.priority[Q]}else{if(J.indexOf(";")!==-1)return;var K=sL0(Q+":"+J);if(Object.getOwnPropertyNames(K.property).length===0)return;if(Object.getOwnPropertyNames(K.priority).length!==0)return;for(var z in K.property)if(H.property[z]=K.property[z],G===az)continue;else if(G!=="")H.priority[z]="important";else if(H.priority[z])delete H.priority[z]}this._serialize()}},setPropertyValue:{value:function(Q,J){return this.setProperty(Q,J,az)}},setPropertyPriority:{value:function(Q,J){return this.setProperty(Q,az,J)}},removeProperty:{value:function(Q){Q=Q.toLowerCase();var J=this._parsed;if(Q in J.property)delete J.property[Q],delete J.priority[Q],this._serialize()}}})});var j80=i((U58,eL0)=>{var e7=VC();eL0.exports=oZ;function oZ(){}oZ.prototype=Object.create(Object.prototype,{_url:{get:function(){return new e7(this.href)}},protocol:{get:function(){var Q=this._url;if(Q&&Q.scheme)return Q.scheme+":";else return":"},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()){if(Q=Q.replace(/:+$/,""),Q=Q.replace(/[^-+\.a-zA-Z0-9]/g,e7.percentEncode),Q.length>0)G.scheme=Q,J=G.toString()}this.href=J}},host:{get:function(){var Q=this._url;if(Q.isAbsolute()&&Q.isAuthorityBased())return Q.host+(Q.port?":"+Q.port:"");else return""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()&&G.isAuthorityBased()){if(Q=Q.replace(/[^-+\._~!$&'()*,;:=a-zA-Z0-9]/g,e7.percentEncode),Q.length>0)G.host=Q,delete G.port,J=G.toString()}this.href=J}},hostname:{get:function(){var Q=this._url;if(Q.isAbsolute()&&Q.isAuthorityBased())return Q.host;else return""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()&&G.isAuthorityBased()){if(Q=Q.replace(/^\/+/,""),Q=Q.replace(/[^-+\._~!$&'()*,;:=a-zA-Z0-9]/g,e7.percentEncode),Q.length>0)G.host=Q,J=G.toString()}this.href=J}},port:{get:function(){var Q=this._url;if(Q.isAbsolute()&&Q.isAuthorityBased()&&Q.port!==void 0)return Q.port;else return""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()&&G.isAuthorityBased()){if(Q=""+Q,Q=Q.replace(/[^0-9].*$/,""),Q=Q.replace(/^0+/,""),Q.length===0)Q="0";if(parseInt(Q,10)<=65535)G.port=Q,J=G.toString()}this.href=J}},pathname:{get:function(){var Q=this._url;if(Q.isAbsolute()&&Q.isHierarchical())return Q.path;else return""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()&&G.isHierarchical()){if(Q.charAt(0)!=="/")Q="/"+Q;Q=Q.replace(/[^-+\._~!$&'()*,;:=@\/a-zA-Z0-9]/g,e7.percentEncode),G.path=Q,J=G.toString()}this.href=J}},search:{get:function(){var Q=this._url;if(Q.isAbsolute()&&Q.isHierarchical()&&Q.query!==void 0)return"?"+Q.query;else return""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()&&G.isHierarchical()){if(Q.charAt(0)==="?")Q=Q.substring(1);Q=Q.replace(/[^-+\._~!$&'()*,;:=@\/?a-zA-Z0-9]/g,e7.percentEncode),G.query=Q,J=G.toString()}this.href=J}},hash:{get:function(){var Q=this._url;if(Q==null||Q.fragment==null||Q.fragment==="")return"";else return"#"+Q.fragment},set:function(Q){var J=this.href,G=new e7(J);if(Q.charAt(0)==="#")Q=Q.substring(1);Q=Q.replace(/[^-+\._~!$&'()*,;:=@\/?a-zA-Z0-9]/g,e7.percentEncode),G.fragment=Q,J=G.toString(),this.href=J}},username:{get:function(){var Q=this._url;return Q.username||""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute())Q=Q.replace(/[\x00-\x1F\x7F-\uFFFF "#<>?`\/@\\:]/g,e7.percentEncode),G.username=Q,J=G.toString();this.href=J}},password:{get:function(){var Q=this._url;return Q.password||""},set:function(Q){var J=this.href,G=new e7(J);if(G.isAbsolute()){if(Q==="")G.password=null;else Q=Q.replace(/[\x00-\x1F\x7F-\uFFFF "#<>?`\/@\\]/g,e7.percentEncode),G.password=Q;J=G.toString()}this.href=J}},origin:{get:function(){var Q=this._url;if(Q==null)return"";var J=function(G){var H=[Q.scheme,Q.host,+Q.port||G];return H[0]+"://"+H[1]+(H[2]===G?"":":"+H[2])};switch(Q.scheme){case"ftp":return J(21);case"gopher":return J(70);case"http":case"ws":return J(80);case"https":case"wss":return J(443);default:return Q.scheme+"://"}}}});oZ._inherit=function(Q){Object.getOwnPropertyNames(oZ.prototype).forEach(function(J){if(J==="constructor"||J==="href")return;var G=Object.getOwnPropertyDescriptor(oZ.prototype,J);Object.defineProperty(Q,J,G)})}});var C80=i(($58,JO0)=>{var QO0=dQ0(),z4Q=rj().isApiWritable;JO0.exports=function(Q,J,G,H){var K=Q.ctor;if(K){var z=Q.props||{};if(Q.attributes)for(var q in Q.attributes){var F=Q.attributes[q];if(typeof F!=="object"||Array.isArray(F))F={type:F};if(!F.name)F.name=q.toLowerCase();z[q]=QO0.property(F)}if(z.constructor={value:K,writable:z4Q},K.prototype=Object.create((Q.superclass||J).prototype,z),Q.events)q4Q(K,Q.events);G[Q.name]=K}else K=J;return(Q.tags||Q.tag&&[Q.tag]||[]).forEach(function(D){H[D]=K}),K};function XO0(Q,J,G,H){this.body=Q,this.document=J,this.form=G,this.element=H}XO0.prototype.build=function(){return()=>{}};function V4Q(Q,J,G,H){var K=Q.ownerDocument||Object.create(null),z=Q.form||Object.create(null);Q[J]=new XO0(H,K,z,Q).build()}function q4Q(Q,J){var G=Q.prototype;J.forEach(function(H){Object.defineProperty(G,"on"+H,{get:function(){return this._getEventHandler(H)},set:function(K){this._setEventHandler(H,K)}}),QO0.registerChangeHandler(Q,"on"+H,V4Q)})}});var ZC=i(($C)=>{var I80=PX(),YO0=oz(),U4Q=qC(),qY=J7(),GO0=j80(),$4Q=C80(),S5=$C.elements={},nZ=Object.create(null);$C.createElement=function(Q,J,G){var H=nZ[J]||F4Q;return new H(Q,J,G)};function fQ(Q){return $4Q(Q,A8,S5,nZ)}function Y7(Q){return{get:function(){var J=this._getattr(Q);if(J===null)return"";var G=this.doc._resolve(J);return G===null?J:G},set:function(J){this._setattr(Q,J)}}}function UC(Q){return{get:function(){var J=this._getattr(Q);if(J===null)return null;if(J.toLowerCase()==="use-credentials")return"use-credentials";return"anonymous"},set:function(J){if(J===null||J===void 0)this.removeAttribute(Q);else this._setattr(Q,J)}}}var sz={type:["","no-referrer","no-referrer-when-downgrade","same-origin","origin","strict-origin","origin-when-cross-origin","strict-origin-when-cross-origin","unsafe-url"],missing:""},Z4Q={A:!0,LINK:!0,BUTTON:!0,INPUT:!0,SELECT:!0,TEXTAREA:!0,COMMAND:!0},EG=function(Q,J,G){A8.call(this,Q,J,G),this._form=null},A8=$C.HTMLElement=fQ({superclass:YO0,name:"HTMLElement",ctor:function(J,G,H){YO0.call(this,J,G,qY.NAMESPACE.HTML,H)},props:{dangerouslySetInnerHTML:{set:function(Q){this._innerHTML=Q}},innerHTML:{get:function(){return this.serialize()},set:function(Q){var J=this.ownerDocument.implementation.mozHTMLParser(this.ownerDocument._address,this);J.parse(Q===null?"":String(Q),!0);var G=this instanceof nZ.template?this.content:this;while(G.hasChildNodes())G.removeChild(G.firstChild);G.appendChild(J._asDocumentFragment())}},style:{get:function(){if(!this._style)this._style=new U4Q(this);return this._style},set:function(Q){if(Q===null||Q===void 0)Q="";this._setattr("style",String(Q))}},blur:{value:function(){}},focus:{value:function(){}},forceSpellCheck:{value:function(){}},click:{value:function(){if(this._click_in_progress)return;this._click_in_progress=!0;try{if(this._pre_click_activation_steps)this._pre_click_activation_steps();var Q=this.ownerDocument.createEvent("MouseEvent");Q.initMouseEvent("click",!0,!0,this.ownerDocument.defaultView,1,0,0,0,0,!1,!1,!1,!1,0,null);var J=this.dispatchEvent(Q);if(J){if(this._post_click_activation_steps)this._post_click_activation_steps(Q)}else if(this._cancelled_activation_steps)this._cancelled_activation_steps()}finally{this._click_in_progress=!1}}},submit:{value:qY.nyi}},attributes:{title:String,lang:String,dir:{type:["ltr","rtl","auto"],missing:""},draggable:{type:["true","false"],treatNullAsEmptyString:!0},spellcheck:{type:["true","false"],missing:""},enterKeyHint:{type:["enter","done","go","next","previous","search","send"],missing:""},autoCapitalize:{type:["off","on","none","sentences","words","characters"],missing:""},autoFocus:Boolean,accessKey:String,nonce:String,hidden:Boolean,translate:{type:["no","yes"],missing:""},tabIndex:{type:"long",default:function(){if(this.tagName in Z4Q||this.contentEditable)return 0;else return-1}}},events:["abort","canplay","canplaythrough","change","click","contextmenu","cuechange","dblclick","drag","dragend","dragenter","dragleave","dragover","dragstart","drop","durationchange","emptied","ended","input","invalid","keydown","keypress","keyup","loadeddata","loadedmetadata","loadstart","mousedown","mousemove","mouseout","mouseover","mouseup","mousewheel","pause","play","playing","progress","ratechange","readystatechange","reset","seeked","seeking","select","show","stalled","submit","suspend","timeupdate","volumechange","waiting","blur","error","focus","load","scroll"]}),F4Q=fQ({name:"HTMLUnknownElement",ctor:function(J,G,H){A8.call(this,J,G,H)}}),SG={form:{get:function(){return this._form}}};fQ({tag:"a",name:"HTMLAnchorElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{_post_click_activation_steps:{value:function(Q){if(this.href)this.ownerDocument.defaultView.location=this.href}}},attributes:{href:Y7,ping:String,download:String,target:String,rel:String,media:String,hreflang:String,type:String,referrerPolicy:sz,coords:String,charset:String,name:String,rev:String,shape:String}});GO0._inherit(nZ.a.prototype);fQ({tag:"area",name:"HTMLAreaElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{alt:String,target:String,download:String,rel:String,media:String,href:Y7,hreflang:String,type:String,shape:String,coords:String,ping:String,referrerPolicy:sz,noHref:Boolean}});GO0._inherit(nZ.area.prototype);fQ({tag:"br",name:"HTMLBRElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{clear:String}});fQ({tag:"base",name:"HTMLBaseElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{target:String}});fQ({tag:"body",name:"HTMLBodyElement",ctor:function(J,G,H){A8.call(this,J,G,H)},events:["afterprint","beforeprint","beforeunload","blur","error","focus","hashchange","load","message","offline","online","pagehide","pageshow","popstate","resize","scroll","storage","unload"],attributes:{text:{type:String,treatNullAsEmptyString:!0},link:{type:String,treatNullAsEmptyString:!0},vLink:{type:String,treatNullAsEmptyString:!0},aLink:{type:String,treatNullAsEmptyString:!0},bgColor:{type:String,treatNullAsEmptyString:!0},background:String}});fQ({tag:"button",name:"HTMLButtonElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{name:String,value:String,disabled:Boolean,autofocus:Boolean,type:{type:["submit","reset","button","menu"],missing:"submit"},formTarget:String,formAction:Y7,formNoValidate:Boolean,formMethod:{type:["get","post","dialog"],invalid:"get",missing:""},formEnctype:{type:["application/x-www-form-urlencoded","multipart/form-data","text/plain"],invalid:"application/x-www-form-urlencoded",missing:""}}});fQ({tag:"dl",name:"HTMLDListElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{compact:Boolean}});fQ({tag:"data",name:"HTMLDataElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{value:String}});fQ({tag:"datalist",name:"HTMLDataListElement",ctor:function(J,G,H){A8.call(this,J,G,H)}});fQ({tag:"details",name:"HTMLDetailsElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{open:Boolean}});fQ({tag:"div",name:"HTMLDivElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{align:String}});fQ({tag:"embed",name:"HTMLEmbedElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{src:Y7,type:String,width:String,height:String,align:String,name:String}});fQ({tag:"fieldset",name:"HTMLFieldSetElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{disabled:Boolean,name:String}});fQ({tag:"form",name:"HTMLFormElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{action:String,autocomplete:{type:["on","off"],missing:"on"},name:String,acceptCharset:{name:"accept-charset"},target:String,noValidate:Boolean,method:{type:["get","post","dialog"],invalid:"get",missing:"get"},enctype:{type:["application/x-www-form-urlencoded","multipart/form-data","text/plain"],invalid:"application/x-www-form-urlencoded",missing:"application/x-www-form-urlencoded"},encoding:{name:"enctype",type:["application/x-www-form-urlencoded","multipart/form-data","text/plain"],invalid:"application/x-www-form-urlencoded",missing:"application/x-www-form-urlencoded"}}});fQ({tag:"hr",name:"HTMLHRElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{align:String,color:String,noShade:Boolean,size:String,width:String}});fQ({tag:"head",name:"HTMLHeadElement",ctor:function(J,G,H){A8.call(this,J,G,H)}});fQ({tags:["h1","h2","h3","h4","h5","h6"],name:"HTMLHeadingElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{align:String}});fQ({tag:"html",name:"HTMLHtmlElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{xmlns:Y7,version:String}});fQ({tag:"iframe",name:"HTMLIFrameElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{src:Y7,srcdoc:String,name:String,width:String,height:String,seamless:Boolean,allow:Boolean,allowFullscreen:Boolean,allowUserMedia:Boolean,allowPaymentRequest:Boolean,referrerPolicy:sz,loading:{type:["eager","lazy"],treatNullAsEmptyString:!0},align:String,scrolling:String,frameBorder:String,longDesc:Y7,marginHeight:{type:String,treatNullAsEmptyString:!0},marginWidth:{type:String,treatNullAsEmptyString:!0}}});fQ({tag:"img",name:"HTMLImageElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{alt:String,src:Y7,srcset:String,crossOrigin:UC,useMap:String,isMap:Boolean,sizes:String,height:{type:"unsigned long",default:0},width:{type:"unsigned long",default:0},referrerPolicy:sz,loading:{type:["eager","lazy"],missing:""},name:String,lowsrc:Y7,align:String,hspace:{type:"unsigned long",default:0},vspace:{type:"unsigned long",default:0},longDesc:Y7,border:{type:String,treatNullAsEmptyString:!0}}});fQ({tag:"input",name:"HTMLInputElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:{form:SG.form,_post_click_activation_steps:{value:function(Q){if(this.type==="checkbox")this.checked=!this.checked;else if(this.type==="radio"){var J=this.form.getElementsByName(this.name);for(var G=J.length-1;G>=0;G--){var H=J[G];H.checked=H===this}}}}},attributes:{name:String,disabled:Boolean,autofocus:Boolean,accept:String,alt:String,max:String,min:String,pattern:String,placeholder:String,step:String,dirName:String,defaultValue:{name:"value"},multiple:Boolean,required:Boolean,readOnly:Boolean,checked:Boolean,value:String,src:Y7,defaultChecked:{name:"checked",type:Boolean},size:{type:"unsigned long",default:20,min:1,setmin:1},width:{type:"unsigned long",min:0,setmin:0,default:0},height:{type:"unsigned long",min:0,setmin:0,default:0},minLength:{type:"unsigned long",min:0,setmin:0,default:-1},maxLength:{type:"unsigned long",min:0,setmin:0,default:-1},autocomplete:String,type:{type:["text","hidden","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"],missing:"text"},formTarget:String,formNoValidate:Boolean,formMethod:{type:["get","post"],invalid:"get",missing:""},formEnctype:{type:["application/x-www-form-urlencoded","multipart/form-data","text/plain"],invalid:"application/x-www-form-urlencoded",missing:""},inputMode:{type:["verbatim","latin","latin-name","latin-prose","full-width-latin","kana","kana-name","katakana","numeric","tel","email","url"],missing:""},align:String,useMap:String}});fQ({tag:"keygen",name:"HTMLKeygenElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{name:String,disabled:Boolean,autofocus:Boolean,challenge:String,keytype:{type:["rsa"],missing:""}}});fQ({tag:"li",name:"HTMLLIElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{value:{type:"long",default:0},type:String}});fQ({tag:"label",name:"HTMLLabelElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{htmlFor:{name:"for",type:String}}});fQ({tag:"legend",name:"HTMLLegendElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{align:String}});fQ({tag:"link",name:"HTMLLinkElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{href:Y7,rel:String,media:String,hreflang:String,type:String,crossOrigin:UC,nonce:String,integrity:String,referrerPolicy:sz,imageSizes:String,imageSrcset:String,charset:String,rev:String,target:String}});fQ({tag:"map",name:"HTMLMapElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{name:String}});fQ({tag:"menu",name:"HTMLMenuElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{type:{type:["context","popup","toolbar"],missing:"toolbar"},label:String,compact:Boolean}});fQ({tag:"meta",name:"HTMLMetaElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{name:String,content:String,httpEquiv:{name:"http-equiv",type:String},scheme:String}});fQ({tag:"meter",name:"HTMLMeterElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG});fQ({tags:["ins","del"],name:"HTMLModElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{cite:Y7,dateTime:String}});fQ({tag:"ol",name:"HTMLOListElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{_numitems:{get:function(){var Q=0;return this.childNodes.forEach(function(J){if(J.nodeType===I80.ELEMENT_NODE&&J.tagName==="LI")Q++}),Q}}},attributes:{type:String,reversed:Boolean,start:{type:"long",default:function(){if(this.reversed)return this._numitems;else return 1}},compact:Boolean}});fQ({tag:"object",name:"HTMLObjectElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{data:Y7,type:String,name:String,useMap:String,typeMustMatch:Boolean,width:String,height:String,align:String,archive:String,code:String,declare:Boolean,hspace:{type:"unsigned long",default:0},standby:String,vspace:{type:"unsigned long",default:0},codeBase:Y7,codeType:String,border:{type:String,treatNullAsEmptyString:!0}}});fQ({tag:"optgroup",name:"HTMLOptGroupElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{disabled:Boolean,label:String}});fQ({tag:"option",name:"HTMLOptionElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{form:{get:function(){var Q=this.parentNode;while(Q&&Q.nodeType===I80.ELEMENT_NODE){if(Q.localName==="select")return Q.form;Q=Q.parentNode}}},value:{get:function(){return this._getattr("value")||this.text},set:function(Q){this._setattr("value",Q)}},text:{get:function(){return this.textContent.replace(/[ \t\n\f\r]+/g," ").trim()},set:function(Q){this.textContent=Q}}},attributes:{disabled:Boolean,defaultSelected:{name:"selected",type:Boolean},label:String}});fQ({tag:"output",name:"HTMLOutputElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{name:String}});fQ({tag:"p",name:"HTMLParagraphElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{align:String}});fQ({tag:"param",name:"HTMLParamElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{name:String,value:String,type:String,valueType:String}});fQ({tags:["pre","listing","xmp"],name:"HTMLPreElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{width:{type:"long",default:0}}});fQ({tag:"progress",name:"HTMLProgressElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:SG,attributes:{max:{type:Number,float:!0,default:1,min:0}}});fQ({tags:["q","blockquote"],name:"HTMLQuoteElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{cite:Y7}});fQ({tag:"script",name:"HTMLScriptElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{text:{get:function(){var Q="";for(var J=0,G=this.childNodes.length;J<G;J++){var H=this.childNodes[J];if(H.nodeType===I80.TEXT_NODE)Q+=H._data}return Q},set:function(Q){if(this.removeChildren(),Q!==null&&Q!=="")this.appendChild(this.ownerDocument.createTextNode(Q))}}},attributes:{src:Y7,type:String,charset:String,referrerPolicy:sz,defer:Boolean,async:Boolean,nomodule:Boolean,crossOrigin:UC,nonce:String,integrity:String}});fQ({tag:"select",name:"HTMLSelectElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:{form:SG.form,options:{get:function(){return this.getElementsByTagName("option")}}},attributes:{autocomplete:String,name:String,disabled:Boolean,autofocus:Boolean,multiple:Boolean,required:Boolean,size:{type:"unsigned long",default:0}}});fQ({tag:"span",name:"HTMLSpanElement",ctor:function(J,G,H){A8.call(this,J,G,H)}});fQ({tag:"style",name:"HTMLStyleElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{media:String,type:String,scoped:Boolean}});fQ({tag:"caption",name:"HTMLTableCaptionElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{align:String}});fQ({name:"HTMLTableCellElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{colSpan:{type:"unsigned long",default:1},rowSpan:{type:"unsigned long",default:1},scope:{type:["row","col","rowgroup","colgroup"],missing:""},abbr:String,align:String,axis:String,height:String,width:String,ch:{name:"char",type:String},chOff:{name:"charoff",type:String},noWrap:Boolean,vAlign:String,bgColor:{type:String,treatNullAsEmptyString:!0}}});fQ({tags:["col","colgroup"],name:"HTMLTableColElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{span:{type:"limited unsigned long with fallback",default:1,min:1},align:String,ch:{name:"char",type:String},chOff:{name:"charoff",type:String},vAlign:String,width:String}});fQ({tag:"table",name:"HTMLTableElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{rows:{get:function(){return this.getElementsByTagName("tr")}}},attributes:{align:String,border:String,frame:String,rules:String,summary:String,width:String,bgColor:{type:String,treatNullAsEmptyString:!0},cellPadding:{type:String,treatNullAsEmptyString:!0},cellSpacing:{type:String,treatNullAsEmptyString:!0}}});fQ({tag:"template",name:"HTMLTemplateElement",ctor:function(J,G,H){A8.call(this,J,G,H),this._contentFragment=J._templateDoc.createDocumentFragment()},props:{content:{get:function(){return this._contentFragment}},serialize:{value:function(){return this.content.serialize()}}}});fQ({tag:"tr",name:"HTMLTableRowElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{cells:{get:function(){return this.querySelectorAll("td,th")}}},attributes:{align:String,ch:{name:"char",type:String},chOff:{name:"charoff",type:String},vAlign:String,bgColor:{type:String,treatNullAsEmptyString:!0}}});fQ({tags:["thead","tfoot","tbody"],name:"HTMLTableSectionElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{rows:{get:function(){return this.getElementsByTagName("tr")}}},attributes:{align:String,ch:{name:"char",type:String},chOff:{name:"charoff",type:String},vAlign:String}});fQ({tag:"textarea",name:"HTMLTextAreaElement",ctor:function(J,G,H){EG.call(this,J,G,H)},props:{form:SG.form,type:{get:function(){return"textarea"}},defaultValue:{get:function(){return this.textContent},set:function(Q){this.textContent=Q}},value:{get:function(){return this.defaultValue},set:function(Q){this.defaultValue=Q}},textLength:{get:function(){return this.value.length}}},attributes:{autocomplete:String,name:String,disabled:Boolean,autofocus:Boolean,placeholder:String,wrap:String,dirName:String,required:Boolean,readOnly:Boolean,rows:{type:"limited unsigned long with fallback",default:2},cols:{type:"limited unsigned long with fallback",default:20},maxLength:{type:"unsigned long",min:0,setmin:0,default:-1},minLength:{type:"unsigned long",min:0,setmin:0,default:-1},inputMode:{type:["verbatim","latin","latin-name","latin-prose","full-width-latin","kana","kana-name","katakana","numeric","tel","email","url"],missing:""}}});fQ({tag:"time",name:"HTMLTimeElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{dateTime:String,pubDate:Boolean}});fQ({tag:"title",name:"HTMLTitleElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{text:{get:function(){return this.textContent}}}});fQ({tag:"ul",name:"HTMLUListElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{type:String,compact:Boolean}});fQ({name:"HTMLMediaElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{src:Y7,crossOrigin:UC,preload:{type:["metadata","none","auto",{value:"",alias:"auto"}],missing:"auto"},loop:Boolean,autoplay:Boolean,mediaGroup:String,controls:Boolean,defaultMuted:{name:"muted",type:Boolean}}});fQ({name:"HTMLAudioElement",tag:"audio",superclass:S5.HTMLMediaElement,ctor:function(J,G,H){S5.HTMLMediaElement.call(this,J,G,H)}});fQ({name:"HTMLVideoElement",tag:"video",superclass:S5.HTMLMediaElement,ctor:function(J,G,H){S5.HTMLMediaElement.call(this,J,G,H)},attributes:{poster:Y7,width:{type:"unsigned long",min:0,default:0},height:{type:"unsigned long",min:0,default:0}}});fQ({tag:"td",name:"HTMLTableDataCellElement",superclass:S5.HTMLTableCellElement,ctor:function(J,G,H){S5.HTMLTableCellElement.call(this,J,G,H)}});fQ({tag:"th",name:"HTMLTableHeaderCellElement",superclass:S5.HTMLTableCellElement,ctor:function(J,G,H){S5.HTMLTableCellElement.call(this,J,G,H)}});fQ({tag:"frameset",name:"HTMLFrameSetElement",ctor:function(J,G,H){A8.call(this,J,G,H)}});fQ({tag:"frame",name:"HTMLFrameElement",ctor:function(J,G,H){A8.call(this,J,G,H)}});fQ({tag:"canvas",name:"HTMLCanvasElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{getContext:{value:qY.nyi},probablySupportsContext:{value:qY.nyi},setContext:{value:qY.nyi},transferControlToProxy:{value:qY.nyi},toDataURL:{value:qY.nyi},toBlob:{value:qY.nyi}},attributes:{width:{type:"unsigned long",default:300},height:{type:"unsigned long",default:150}}});fQ({tag:"dialog",name:"HTMLDialogElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{show:{value:qY.nyi},showModal:{value:qY.nyi},close:{value:qY.nyi}},attributes:{open:Boolean,returnValue:String}});fQ({tag:"menuitem",name:"HTMLMenuItemElement",ctor:function(J,G,H){A8.call(this,J,G,H)},props:{_label:{get:function(){var Q=this._getattr("label");if(Q!==null&&Q!=="")return Q;return Q=this.textContent,Q.replace(/[ \t\n\f\r]+/g," ").trim()}},label:{get:function(){var Q=this._getattr("label");if(Q!==null)return Q;return this._label},set:function(Q){this._setattr("label",Q)}}},attributes:{type:{type:["command","checkbox","radio"],missing:"command"},icon:Y7,disabled:Boolean,checked:Boolean,radiogroup:String,default:Boolean}});fQ({tag:"source",name:"HTMLSourceElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{srcset:String,sizes:String,media:String,src:Y7,type:String,width:String,height:String}});fQ({tag:"track",name:"HTMLTrackElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{src:Y7,srclang:String,label:String,default:Boolean,kind:{type:["subtitles","captions","descriptions","chapters","metadata"],missing:"subtitles",invalid:"metadata"}},props:{NONE:{get:function(){return 0}},LOADING:{get:function(){return 1}},LOADED:{get:function(){return 2}},ERROR:{get:function(){return 3}},readyState:{get:qY.nyi},track:{get:qY.nyi}}});fQ({tag:"font",name:"HTMLFontElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{color:{type:String,treatNullAsEmptyString:!0},face:{type:String},size:{type:String}}});fQ({tag:"dir",name:"HTMLDirectoryElement",ctor:function(J,G,H){A8.call(this,J,G,H)},attributes:{compact:Boolean}});fQ({tags:["abbr","address","article","aside","b","bdi","bdo","cite","content","code","dd","dfn","dt","em","figcaption","figure","footer","header","hgroup","i","kbd","main","mark","nav","noscript","rb","rp","rt","rtc","ruby","s","samp","section","small","strong","sub","summary","sup","u","var","wbr","acronym","basefont","big","center","nobr","noembed","noframes","plaintext","strike","tt"]})});var E80=i((FC)=>{var WO0=oz(),D4Q=C80(),M4Q=J7(),L4Q=qC(),O4Q=FC.elements={},HO0=Object.create(null);FC.createElement=function(Q,J,G){var H=HO0[J]||w80;return new H(Q,J,G)};function R80(Q){return D4Q(Q,w80,O4Q,HO0)}var w80=R80({superclass:WO0,name:"SVGElement",ctor:function(J,G,H){WO0.call(this,J,G,M4Q.NAMESPACE.SVG,H)},props:{style:{get:function(){if(!this._style)this._style=new L4Q(this);return this._style}}}});R80({name:"SVGSVGElement",ctor:function(J,G,H){w80.call(this,J,G,H)},tag:"svg",props:{createSVGRect:{value:function(){return FC.createElement(this.ownerDocument,"rect",null)}}}});R80({tags:["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","hkern","image","line","linearGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"]})});var AO0=i((D58,BO0)=>{BO0.exports={VALUE:1,ATTR:2,REMOVE_ATTR:3,REMOVE:4,MOVE:5,INSERT:6}});var MC=i((M58,MO0)=>{MO0.exports=sZ;var lX=PX(),P4Q=f3(),$O0=QC(),WH=oz(),N4Q=B80(),j4Q=K80(),aZ=mz(),C4Q=V80(),I4Q=U80(),R4Q=rZ(),w4Q=xL0(),E4Q=mL0(),KO0=iZ(),zO0=VC(),VO0=WC(),S4Q=N80(),DC=XC(),S80=ZC(),T4Q=E80(),b6=J7(),rz=AO0(),ez=b6.NAMESPACE,T80=rj().isApiWritable;function sZ(Q,J){$O0.call(this),this.nodeType=lX.DOCUMENT_NODE,this.isHTML=Q,this._address=J||"about:blank",this.readyState="loading",this.implementation=new R4Q(this),this.ownerDocument=null,this._contentType=Q?"text/html":"application/xml",this.doctype=null,this.documentElement=null,this._templateDocCache=null,this._nodeIterators=null,this._nid=1,this._nextnid=2,this._nodes=[null,this],this.byId=Object.create(null),this.modclock=0}var k4Q={event:"Event",customevent:"CustomEvent",uievent:"UIEvent",mouseevent:"MouseEvent"},y4Q={events:"event",htmlevents:"event",mouseevents:"mouseevent",mutationevents:"mutationevent",uievents:"uievent"},tz=function(Q,J,G){return{get:function(){var H=Q.call(this);if(H)return H[J];return G},set:function(H){var K=Q.call(this);if(K)K[J]=H}}};function qO0(Q,J){var G,H,K;if(Q==="")Q=null;if(!DC.isValidQName(J))b6.InvalidCharacterError();if(G=null,H=J,K=J.indexOf(":"),K>=0)G=J.substring(0,K),H=J.substring(K+1);if(G!==null&&Q===null)b6.NamespaceError();if(G==="xml"&&Q!==ez.XML)b6.NamespaceError();if((G==="xmlns"||J==="xmlns")&&Q!==ez.XMLNS)b6.NamespaceError();if(Q===ez.XMLNS&&!(G==="xmlns"||J==="xmlns"))b6.NamespaceError();return{namespace:Q,prefix:G,localName:H}}sZ.prototype=Object.create($O0.prototype,{_setMutationHandler:{value:function(Q){this.mutationHandler=Q}},_dispatchRendererEvent:{value:function(Q,J,G){var H=this._nodes[Q];if(!H)return;H._dispatchEvent(new aZ(J,G),!0)}},nodeName:{value:"#document"},nodeValue:{get:function(){return null},set:function(){}},documentURI:{get:function(){return this._address},set:b6.nyi},compatMode:{get:function(){return this._quirks?"BackCompat":"CSS1Compat"}},createTextNode:{value:function(Q){return new N4Q(this,String(Q))}},createComment:{value:function(Q){return new j4Q(this,Q)}},createDocumentFragment:{value:function(){return new C4Q(this)}},createProcessingInstruction:{value:function(Q,J){if(!DC.isValidName(Q)||J.indexOf("?>")!==-1)b6.InvalidCharacterError();return new I4Q(this,Q,J)}},createAttribute:{value:function(Q){if(Q=String(Q),!DC.isValidName(Q))b6.InvalidCharacterError();if(this.isHTML)Q=b6.toASCIILowerCase(Q);return new WH._Attr(null,Q,null,null,"")}},createAttributeNS:{value:function(Q,J){Q=Q===null||Q===void 0||Q===""?null:String(Q),J=String(J);var G=qO0(Q,J);return new WH._Attr(null,G.localName,G.prefix,G.namespace,"")}},createElement:{value:function(Q){if(Q=String(Q),!DC.isValidName(Q))b6.InvalidCharacterError();if(this.isHTML){if(/[A-Z]/.test(Q))Q=b6.toASCIILowerCase(Q);return S80.createElement(this,Q,null)}else if(this.contentType==="application/xhtml+xml")return S80.createElement(this,Q,null);else return new WH(this,Q,null,null)},writable:T80},createElementNS:{value:function(Q,J){Q=Q===null||Q===void 0||Q===""?null:String(Q),J=String(J);var G=qO0(Q,J);return this._createElementNS(G.localName,G.namespace,G.prefix)},writable:T80},_createElementNS:{value:function(Q,J,G){if(J===ez.HTML)return S80.createElement(this,Q,G);else if(J===ez.SVG)return T4Q.createElement(this,Q,G);return new WH(this,Q,J,G)}},createEvent:{value:function(J){J=J.toLowerCase();var G=y4Q[J]||J,H=S4Q[k4Q[G]];if(H){var K=new H;return K._initialized=!1,K}else b6.NotSupportedError()}},createTreeWalker:{value:function(Q,J,G){if(!Q)throw TypeError("root argument is required");if(!(Q instanceof lX))throw TypeError("root not a node");return J=J===void 0?KO0.SHOW_ALL:+J,G=G===void 0?null:G,new w4Q(Q,J,G)}},createNodeIterator:{value:function(Q,J,G){if(!Q)throw TypeError("root argument is required");if(!(Q instanceof lX))throw TypeError("root not a node");return J=J===void 0?KO0.SHOW_ALL:+J,G=G===void 0?null:G,new E4Q(Q,J,G)}},_attachNodeIterator:{value:function(Q){if(!this._nodeIterators)this._nodeIterators=[];this._nodeIterators.push(Q)}},_detachNodeIterator:{value:function(Q){var J=this._nodeIterators.indexOf(Q);this._nodeIterators.splice(J,1)}},_preremoveNodeIterators:{value:function(Q){if(this._nodeIterators)this._nodeIterators.forEach(function(J){J._preremove(Q)})}},_updateDocTypeElement:{value:function(){this.doctype=this.documentElement=null;for(var J=this.firstChild;J!==null;J=J.nextSibling)if(J.nodeType===lX.DOCUMENT_TYPE_NODE)this.doctype=J;else if(J.nodeType===lX.ELEMENT_NODE)this.documentElement=J}},insertBefore:{value:function(J,G){return lX.prototype.insertBefore.call(this,J,G),this._updateDocTypeElement(),J}},replaceChild:{value:function(J,G){return lX.prototype.replaceChild.call(this,J,G),this._updateDocTypeElement(),G}},removeChild:{value:function(J){return lX.prototype.removeChild.call(this,J),this._updateDocTypeElement(),J}},getElementById:{value:function(Q){var J=this.byId[Q];if(!J)return null;if(J instanceof T5)return J.getFirst();return J}},_hasMultipleElementsWithId:{value:function(Q){return this.byId[Q]instanceof T5}},getElementsByName:{value:WH.prototype.getElementsByName},getElementsByTagName:{value:WH.prototype.getElementsByTagName},getElementsByTagNameNS:{value:WH.prototype.getElementsByTagNameNS},getElementsByClassName:{value:WH.prototype.getElementsByClassName},adoptNode:{value:function(J){if(J.nodeType===lX.DOCUMENT_NODE)b6.NotSupportedError();if(J.nodeType===lX.ATTRIBUTE_NODE)return J;if(J.parentNode)J.parentNode.removeChild(J);if(J.ownerDocument!==this)DO0(J,this);return J}},importNode:{value:function(J,G){return this.adoptNode(J.cloneNode(G))},writable:T80},origin:{get:function(){return null}},characterSet:{get:function(){return"UTF-8"}},contentType:{get:function(){return this._contentType}},URL:{get:function(){return this._address}},domain:{get:b6.nyi,set:b6.nyi},referrer:{get:b6.nyi},cookie:{get:b6.nyi,set:b6.nyi},lastModified:{get:b6.nyi},location:{get:function(){return this.defaultView?this.defaultView.location:null},set:b6.nyi},_titleElement:{get:function(){return this.getElementsByTagName("title").item(0)||null}},title:{get:function(){var Q=this._titleElement,J=Q?Q.textContent:"";return J.replace(/[ \t\n\r\f]+/g," ").replace(/(^ )|( $)/g,"")},set:function(Q){var J=this._titleElement,G=this.head;if(!J&&!G)return;if(!J)J=this.createElement("title"),G.appendChild(J);J.textContent=Q}},dir:tz(function(){var Q=this.documentElement;if(Q&&Q.tagName==="HTML")return Q},"dir",""),fgColor:tz(function(){return this.body},"text",""),linkColor:tz(function(){return this.body},"link",""),vlinkColor:tz(function(){return this.body},"vLink",""),alinkColor:tz(function(){return this.body},"aLink",""),bgColor:tz(function(){return this.body},"bgColor",""),charset:{get:function(){return this.characterSet}},inputEncoding:{get:function(){return this.characterSet}},scrollingElement:{get:function(){return this._quirks?this.body:this.documentElement}},body:{get:function(){return UO0(this.documentElement,"body")},set:b6.nyi},head:{get:function(){return UO0(this.documentElement,"head")}},images:{get:b6.nyi},embeds:{get:b6.nyi},plugins:{get:b6.nyi},links:{get:b6.nyi},forms:{get:b6.nyi},scripts:{get:b6.nyi},applets:{get:function(){return[]}},activeElement:{get:function(){return null}},innerHTML:{get:function(){return this.serialize()},set:b6.nyi},outerHTML:{get:function(){return this.serialize()},set:b6.nyi},write:{value:function(Q){if(!this.isHTML)b6.InvalidStateError();if(!this._parser)return;if(!this._parser);var J=arguments.join("");this._parser.parse(J)}},writeln:{value:function(J){this.write(Array.prototype.join.call(arguments,"")+`
`)}},open:{value:function(){this.documentElement=null}},close:{value:function(){if(this.readyState="interactive",this._dispatchEvent(new aZ("readystatechange"),!0),this._dispatchEvent(new aZ("DOMContentLoaded"),!0),this.readyState="complete",this._dispatchEvent(new aZ("readystatechange"),!0),this.defaultView)this.defaultView._dispatchEvent(new aZ("load"),!0)}},clone:{value:function(){var J=new sZ(this.isHTML,this._address);return J._quirks=this._quirks,J._contentType=this._contentType,J}},cloneNode:{value:function(J){var G=lX.prototype.cloneNode.call(this,!1);if(J)for(var H=this.firstChild;H!==null;H=H.nextSibling)G._appendChild(G.importNode(H,!0));return G._updateDocTypeElement(),G}},isEqual:{value:function(J){return!0}},mutateValue:{value:function(Q){if(this.mutationHandler)this.mutationHandler({type:rz.VALUE,target:Q,data:Q.data})}},mutateAttr:{value:function(Q,J){if(this.mutationHandler)this.mutationHandler({type:rz.ATTR,target:Q.ownerElement,attr:Q})}},mutateRemoveAttr:{value:function(Q){if(this.mutationHandler)this.mutationHandler({type:rz.REMOVE_ATTR,target:Q.ownerElement,attr:Q})}},mutateRemove:{value:function(Q){if(this.mutationHandler)this.mutationHandler({type:rz.REMOVE,target:Q.parentNode,node:Q});FO0(Q)}},mutateInsert:{value:function(Q){if(ZO0(Q),this.mutationHandler)this.mutationHandler({type:rz.INSERT,target:Q.parentNode,node:Q})}},mutateMove:{value:function(Q){if(this.mutationHandler)this.mutationHandler({type:rz.MOVE,target:Q})}},addId:{value:function(J,G){var H=this.byId[J];if(!H)this.byId[J]=G;else{if(!(H instanceof T5))H=new T5(H),this.byId[J]=H;H.add(G)}}},delId:{value:function(J,G){var H=this.byId[J];if(b6.assert(H),H instanceof T5){if(H.del(G),H.length===1)this.byId[J]=H.downgrade()}else this.byId[J]=void 0}},_resolve:{value:function(Q){return new zO0(this._documentBaseURL).resolve(Q)}},_documentBaseURL:{get:function(){var Q=this._address;if(Q==="about:blank")Q="/";var J=this.querySelector("base[href]");if(J)return new zO0(Q).resolve(J.getAttribute("href"));return Q}},_templateDoc:{get:function(){if(!this._templateDocCache){var Q=new sZ(this.isHTML,this._address);this._templateDocCache=Q._templateDocCache=Q}return this._templateDocCache}},querySelector:{value:function(Q){return VO0(Q,this)[0]}},querySelectorAll:{value:function(Q){var J=VO0(Q,this);return J.item?J:new P4Q(J)}}});var v4Q=["abort","canplay","canplaythrough","change","click","contextmenu","cuechange","dblclick","drag","dragend","dragenter","dragleave","dragover","dragstart","drop","durationchange","emptied","ended","input","invalid","keydown","keypress","keyup","loadeddata","loadedmetadata","loadstart","mousedown","mousemove","mouseout","mouseover","mouseup","mousewheel","pause","play","playing","progress","ratechange","readystatechange","reset","seeked","seeking","select","show","stalled","submit","suspend","timeupdate","volumechange","waiting","blur","error","focus","load","scroll"];v4Q.forEach(function(Q){Object.defineProperty(sZ.prototype,"on"+Q,{get:function(){return this._getEventHandler(Q)},set:function(J){this._setEventHandler(Q,J)}})});function UO0(Q,J){if(Q&&Q.isHTML){for(var G=Q.firstChild;G!==null;G=G.nextSibling)if(G.nodeType===lX.ELEMENT_NODE&&G.localName===J&&G.namespaceURI===ez.HTML)return G}return null}function x4Q(Q){if(Q._nid=Q.ownerDocument._nextnid++,Q.ownerDocument._nodes[Q._nid]=Q,Q.nodeType===lX.ELEMENT_NODE){var J=Q.getAttribute("id");if(J)Q.ownerDocument.addId(J,Q);if(Q._roothook)Q._roothook()}}function b4Q(Q){if(Q.nodeType===lX.ELEMENT_NODE){var J=Q.getAttribute("id");if(J)Q.ownerDocument.delId(J,Q)}Q.ownerDocument._nodes[Q._nid]=void 0,Q._nid=void 0}function ZO0(Q){if(x4Q(Q),Q.nodeType===lX.ELEMENT_NODE)for(var J=Q.firstChild;J!==null;J=J.nextSibling)ZO0(J)}function FO0(Q){b4Q(Q);for(var J=Q.firstChild;J!==null;J=J.nextSibling)FO0(J)}function DO0(Q,J){if(Q.ownerDocument=J,Q._lastModTime=void 0,Object.prototype.hasOwnProperty.call(Q,"_tagName"))Q._tagName=void 0;for(var G=Q.firstChild;G!==null;G=G.nextSibling)DO0(G,J)}function T5(Q){this.nodes=Object.create(null),this.nodes[Q._nid]=Q,this.length=1,this.firstNode=void 0}T5.prototype.add=function(Q){if(!this.nodes[Q._nid])this.nodes[Q._nid]=Q,this.length++,this.firstNode=void 0};T5.prototype.del=function(Q){if(this.nodes[Q._nid])delete this.nodes[Q._nid],this.length--,this.firstNode=void 0};T5.prototype.getFirst=function(){if(!this.firstNode){var Q;for(Q in this.nodes)if(this.firstNode===void 0||this.firstNode.compareDocumentPosition(this.nodes[Q])&lX.DOCUMENT_POSITION_PRECEDING)this.firstNode=this.nodes[Q]}return this.firstNode};T5.prototype.downgrade=function(){if(this.length===1){var Q;for(Q in this.nodes)return this.nodes[Q]}return this}});var OC=i((L58,OO0)=>{OO0.exports=LC;var g4Q=PX(),LO0=W80(),h4Q=HC();function LC(Q,J,G,H){LO0.call(this),this.nodeType=g4Q.DOCUMENT_TYPE_NODE,this.ownerDocument=Q||null,this.name=J,this.publicId=G||"",this.systemId=H||""}LC.prototype=Object.create(LO0.prototype,{nodeName:{get:function(){return this.name}},nodeValue:{get:function(){return null},set:function(){}},clone:{value:function(){return new LC(this.ownerDocument,this.name,this.publicId,this.systemId)}},isEqual:{value:function(J){return this.name===J.name&&this.publicId===J.publicId&&this.systemId===J.systemId}}});Object.defineProperties(LC.prototype,h4Q)});var wC=i((O58,lO0)=>{lO0.exports=v6;var _4Q=MC(),f4Q=OC(),k80=PX(),O8=J7().NAMESPACE,bO0=ZC(),a6=bO0.elements,u3=Function.prototype.apply.bind(Array.prototype.push),PC=-1,QV=1,dX=2,K6=3,RW=4,m4Q=5,u4Q=[],p4Q=/^HTML$|^-\/\/W3O\/\/DTD W3 HTML Strict 3\.0\/\/EN\/\/$|^-\/W3C\/DTD HTML 4\.0 Transitional\/EN$|^\+\/\/Silmaril\/\/dtd html Pro v0r11 19970101\/\/|^-\/\/AdvaSoft Ltd\/\/DTD HTML 3\.0 asWedit \+ extensions\/\/|^-\/\/AS\/\/DTD HTML 3\.0 asWedit \+ extensions\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Level 1\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Level 2\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict Level 1\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict Level 2\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict\/\/|^-\/\/IETF\/\/DTD HTML 2\.0\/\/|^-\/\/IETF\/\/DTD HTML 2\.1E\/\/|^-\/\/IETF\/\/DTD HTML 3\.0\/\/|^-\/\/IETF\/\/DTD HTML 3\.2 Final\/\/|^-\/\/IETF\/\/DTD HTML 3\.2\/\/|^-\/\/IETF\/\/DTD HTML 3\/\/|^-\/\/IETF\/\/DTD HTML Level 0\/\/|^-\/\/IETF\/\/DTD HTML Level 1\/\/|^-\/\/IETF\/\/DTD HTML Level 2\/\/|^-\/\/IETF\/\/DTD HTML Level 3\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 0\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 1\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 2\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 3\/\/|^-\/\/IETF\/\/DTD HTML Strict\/\/|^-\/\/IETF\/\/DTD HTML\/\/|^-\/\/Metrius\/\/DTD Metrius Presentational\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 HTML Strict\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 HTML\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 Tables\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 HTML Strict\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 HTML\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 Tables\/\/|^-\/\/Netscape Comm\. Corp\.\/\/DTD HTML\/\/|^-\/\/Netscape Comm\. Corp\.\/\/DTD Strict HTML\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML 2\.0\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML Extended 1\.0\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML Extended Relaxed 1\.0\/\/|^-\/\/SoftQuad Software\/\/DTD HoTMetaL PRO 6\.0::19990601::extensions to HTML 4\.0\/\/|^-\/\/SoftQuad\/\/DTD HoTMetaL PRO 4\.0::19971010::extensions to HTML 4\.0\/\/|^-\/\/Spyglass\/\/DTD HTML 2\.0 Extended\/\/|^-\/\/SQ\/\/DTD HTML 2\.0 HoTMetaL \+ extensions\/\/|^-\/\/Sun Microsystems Corp\.\/\/DTD HotJava HTML\/\/|^-\/\/Sun Microsystems Corp\.\/\/DTD HotJava Strict HTML\/\/|^-\/\/W3C\/\/DTD HTML 3 1995-03-24\/\/|^-\/\/W3C\/\/DTD HTML 3\.2 Draft\/\/|^-\/\/W3C\/\/DTD HTML 3\.2 Final\/\/|^-\/\/W3C\/\/DTD HTML 3\.2\/\/|^-\/\/W3C\/\/DTD HTML 3\.2S Draft\/\/|^-\/\/W3C\/\/DTD HTML 4\.0 Frameset\/\/|^-\/\/W3C\/\/DTD HTML 4\.0 Transitional\/\/|^-\/\/W3C\/\/DTD HTML Experimental 19960712\/\/|^-\/\/W3C\/\/DTD HTML Experimental 970421\/\/|^-\/\/W3C\/\/DTD W3 HTML\/\/|^-\/\/W3O\/\/DTD W3 HTML 3\.0\/\/|^-\/\/WebTechs\/\/DTD Mozilla HTML 2\.0\/\/|^-\/\/WebTechs\/\/DTD Mozilla HTML\/\//i,l4Q="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",PO0=/^-\/\/W3C\/\/DTD HTML 4\.01 Frameset\/\/|^-\/\/W3C\/\/DTD HTML 4\.01 Transitional\/\//i,d4Q=/^-\/\/W3C\/\/DTD XHTML 1\.0 Frameset\/\/|^-\/\/W3C\/\/DTD XHTML 1\.0 Transitional\/\//i,l3=Object.create(null);l3[O8.HTML]={__proto__:null,address:!0,applet:!0,area:!0,article:!0,aside:!0,base:!0,basefont:!0,bgsound:!0,blockquote:!0,body:!0,br:!0,button:!0,caption:!0,center:!0,col:!0,colgroup:!0,dd:!0,details:!0,dir:!0,div:!0,dl:!0,dt:!0,embed:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,frame:!0,frameset:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,head:!0,header:!0,hgroup:!0,hr:!0,html:!0,iframe:!0,img:!0,input:!0,li:!0,link:!0,listing:!0,main:!0,marquee:!0,menu:!0,meta:!0,nav:!0,noembed:!0,noframes:!0,noscript:!0,object:!0,ol:!0,p:!0,param:!0,plaintext:!0,pre:!0,script:!0,section:!0,select:!0,source:!0,style:!0,summary:!0,table:!0,tbody:!0,td:!0,template:!0,textarea:!0,tfoot:!0,th:!0,thead:!0,title:!0,tr:!0,track:!0,ul:!0,wbr:!0,xmp:!0};l3[O8.SVG]={__proto__:null,foreignObject:!0,desc:!0,title:!0};l3[O8.MATHML]={__proto__:null,mi:!0,mo:!0,mn:!0,ms:!0,mtext:!0,"annotation-xml":!0};var x80=Object.create(null);x80[O8.HTML]={__proto__:null,address:!0,div:!0,p:!0};var gO0=Object.create(null);gO0[O8.HTML]={__proto__:null,dd:!0,dt:!0};var XV=Object.create(null);XV[O8.HTML]={__proto__:null,table:!0,thead:!0,tbody:!0,tfoot:!0,tr:!0};var hO0=Object.create(null);hO0[O8.HTML]={__proto__:null,dd:!0,dt:!0,li:!0,menuitem:!0,optgroup:!0,option:!0,p:!0,rb:!0,rp:!0,rt:!0,rtc:!0};var _O0=Object.create(null);_O0[O8.HTML]={__proto__:null,caption:!0,colgroup:!0,dd:!0,dt:!0,li:!0,optgroup:!0,option:!0,p:!0,rb:!0,rp:!0,rt:!0,rtc:!0,tbody:!0,td:!0,tfoot:!0,th:!0,thead:!0,tr:!0};var CC=Object.create(null);CC[O8.HTML]={__proto__:null,table:!0,template:!0,html:!0};var IC=Object.create(null);IC[O8.HTML]={__proto__:null,tbody:!0,tfoot:!0,thead:!0,template:!0,html:!0};var b80=Object.create(null);b80[O8.HTML]={__proto__:null,tr:!0,template:!0,html:!0};var fO0=Object.create(null);fO0[O8.HTML]={__proto__:null,button:!0,fieldset:!0,input:!0,keygen:!0,object:!0,output:!0,select:!0,textarea:!0,img:!0};var wW=Object.create(null);wW[O8.HTML]={__proto__:null,applet:!0,caption:!0,html:!0,table:!0,td:!0,th:!0,marquee:!0,object:!0,template:!0};wW[O8.MATHML]={__proto__:null,mi:!0,mo:!0,mn:!0,ms:!0,mtext:!0,"annotation-xml":!0};wW[O8.SVG]={__proto__:null,foreignObject:!0,desc:!0,title:!0};var RC=Object.create(wW);RC[O8.HTML]=Object.create(wW[O8.HTML]);RC[O8.HTML].ol=!0;RC[O8.HTML].ul=!0;var g80=Object.create(wW);g80[O8.HTML]=Object.create(wW[O8.HTML]);g80[O8.HTML].button=!0;var mO0=Object.create(null);mO0[O8.HTML]={__proto__:null,html:!0,table:!0,template:!0};var c4Q=Object.create(null);c4Q[O8.HTML]={__proto__:null,optgroup:!0,option:!0};var uO0=Object.create(null);uO0[O8.MATHML]={__proto__:null,mi:!0,mo:!0,mn:!0,ms:!0,mtext:!0};var pO0=Object.create(null);pO0[O8.SVG]={__proto__:null,foreignObject:!0,desc:!0,title:!0};var NO0={__proto__:null,"xlink:actuate":O8.XLINK,"xlink:arcrole":O8.XLINK,"xlink:href":O8.XLINK,"xlink:role":O8.XLINK,"xlink:show":O8.XLINK,"xlink:title":O8.XLINK,"xlink:type":O8.XLINK,"xml:base":O8.XML,"xml:lang":O8.XML,"xml:space":O8.XML,xmlns:O8.XMLNS,"xmlns:xlink":O8.XMLNS},jO0={__proto__:null,attributename:"attributeName",attributetype:"attributeType",basefrequency:"baseFrequency",baseprofile:"baseProfile",calcmode:"calcMode",clippathunits:"clipPathUnits",diffuseconstant:"diffuseConstant",edgemode:"edgeMode",filterunits:"filterUnits",glyphref:"glyphRef",gradienttransform:"gradientTransform",gradientunits:"gradientUnits",kernelmatrix:"kernelMatrix",kernelunitlength:"kernelUnitLength",keypoints:"keyPoints",keysplines:"keySplines",keytimes:"keyTimes",lengthadjust:"lengthAdjust",limitingconeangle:"limitingConeAngle",markerheight:"markerHeight",markerunits:"markerUnits",markerwidth:"markerWidth",maskcontentunits:"maskContentUnits",maskunits:"maskUnits",numoctaves:"numOctaves",pathlength:"pathLength",patterncontentunits:"patternContentUnits",patterntransform:"patternTransform",patternunits:"patternUnits",pointsatx:"pointsAtX",pointsaty:"pointsAtY",pointsatz:"pointsAtZ",preservealpha:"preserveAlpha",preserveaspectratio:"preserveAspectRatio",primitiveunits:"primitiveUnits",refx:"refX",refy:"refY",repeatcount:"repeatCount",repeatdur:"repeatDur",requiredextensions:"requiredExtensions",requiredfeatures:"requiredFeatures",specularconstant:"specularConstant",specularexponent:"specularExponent",spreadmethod:"spreadMethod",startoffset:"startOffset",stddeviation:"stdDeviation",stitchtiles:"stitchTiles",surfacescale:"surfaceScale",systemlanguage:"systemLanguage",tablevalues:"tableValues",targetx:"targetX",targety:"targetY",textlength:"textLength",viewbox:"viewBox",viewtarget:"viewTarget",xchannelselector:"xChannelSelector",ychannelselector:"yChannelSelector",zoomandpan:"zoomAndPan"},CO0={__proto__:null,altglyph:"altGlyph",altglyphdef:"altGlyphDef",altglyphitem:"altGlyphItem",animatecolor:"animateColor",animatemotion:"animateMotion",animatetransform:"animateTransform",clippath:"clipPath",feblend:"feBlend",fecolormatrix:"feColorMatrix",fecomponenttransfer:"feComponentTransfer",fecomposite:"feComposite",feconvolvematrix:"feConvolveMatrix",fediffuselighting:"feDiffuseLighting",fedisplacementmap:"feDisplacementMap",fedistantlight:"feDistantLight",feflood:"feFlood",fefunca:"feFuncA",fefuncb:"feFuncB",fefuncg:"feFuncG",fefuncr:"feFuncR",fegaussianblur:"feGaussianBlur",feimage:"feImage",femerge:"feMerge",femergenode:"feMergeNode",femorphology:"feMorphology",feoffset:"feOffset",fepointlight:"fePointLight",fespecularlighting:"feSpecularLighting",fespotlight:"feSpotLight",fetile:"feTile",feturbulence:"feTurbulence",foreignobject:"foreignObject",glyphref:"glyphRef",lineargradient:"linearGradient",radialgradient:"radialGradient",textpath:"textPath"},IO0={__proto__:null,0:65533,128:8364,130:8218,131:402,132:8222,133:8230,134:8224,135:8225,136:710,137:8240,138:352,139:8249,140:338,142:381,145:8216,146:8217,147:8220,148:8221,149:8226,150:8211,151:8212,152:732,153:8482,154:353,155:8250,156:339,158:382,159:376},i4Q={__proto__:null,AElig:198,"AElig;":198,AMP:38,"AMP;":38,Aacute:193,"Aacute;":193,"Abreve;":258,Acirc:194,"Acirc;":194,"Acy;":1040,"Afr;":[55349,56580],Agrave:192,"Agrave;":192,"Alpha;":913,"Amacr;":256,"And;":10835,"Aogon;":260,"Aopf;":[55349,56632],"ApplyFunction;":8289,Aring:197,"Aring;":197,"Ascr;":[55349,56476],"Assign;":8788,Atilde:195,"Atilde;":195,Auml:196,"Auml;":196,"Backslash;":8726,"Barv;":10983,"Barwed;":8966,"Bcy;":1041,"Because;":8757,"Bernoullis;":8492,"Beta;":914,"Bfr;":[55349,56581],"Bopf;":[55349,56633],"Breve;":728,"Bscr;":8492,"Bumpeq;":8782,"CHcy;":1063,COPY:169,"COPY;":169,"Cacute;":262,"Cap;":8914,"CapitalDifferentialD;":8517,"Cayleys;":8493,"Ccaron;":268,Ccedil:199,"Ccedil;":199,"Ccirc;":264,"Cconint;":8752,"Cdot;":266,"Cedilla;":184,"CenterDot;":183,"Cfr;":8493,"Chi;":935,"CircleDot;":8857,"CircleMinus;":8854,"CirclePlus;":8853,"CircleTimes;":8855,"ClockwiseContourIntegral;":8754,"CloseCurlyDoubleQuote;":8221,"CloseCurlyQuote;":8217,"Colon;":8759,"Colone;":10868,"Congruent;":8801,"Conint;":8751,"ContourIntegral;":8750,"Copf;":8450,"Coproduct;":8720,"CounterClockwiseContourIntegral;":8755,"Cross;":10799,"Cscr;":[55349,56478],"Cup;":8915,"CupCap;":8781,"DD;":8517,"DDotrahd;":10513,"DJcy;":1026,"DScy;":1029,"DZcy;":1039,"Dagger;":8225,"Darr;":8609,"Dashv;":10980,"Dcaron;":270,"Dcy;":1044,"Del;":8711,"Delta;":916,"Dfr;":[55349,56583],"DiacriticalAcute;":180,"DiacriticalDot;":729,"DiacriticalDoubleAcute;":733,"DiacriticalGrave;":96,"DiacriticalTilde;":732,"Diamond;":8900,"DifferentialD;":8518,"Dopf;":[55349,56635],"Dot;":168,"DotDot;":8412,"DotEqual;":8784,"DoubleContourIntegral;":8751,"DoubleDot;":168,"DoubleDownArrow;":8659,"DoubleLeftArrow;":8656,"DoubleLeftRightArrow;":8660,"DoubleLeftTee;":10980,"DoubleLongLeftArrow;":10232,"DoubleLongLeftRightArrow;":10234,"DoubleLongRightArrow;":10233,"DoubleRightArrow;":8658,"DoubleRightTee;":8872,"DoubleUpArrow;":8657,"DoubleUpDownArrow;":8661,"DoubleVerticalBar;":8741,"DownArrow;":8595,"DownArrowBar;":10515,"DownArrowUpArrow;":8693,"DownBreve;":785,"DownLeftRightVector;":10576,"DownLeftTeeVector;":10590,"DownLeftVector;":8637,"DownLeftVectorBar;":10582,"DownRightTeeVector;":10591,"DownRightVector;":8641,"DownRightVectorBar;":10583,"DownTee;":8868,"DownTeeArrow;":8615,"Downarrow;":8659,"Dscr;":[55349,56479],"Dstrok;":272,"ENG;":330,ETH:208,"ETH;":208,Eacute:201,"Eacute;":201,"Ecaron;":282,Ecirc:202,"Ecirc;":202,"Ecy;":1069,"Edot;":278,"Efr;":[55349,56584],Egrave:200,"Egrave;":200,"Element;":8712,"Emacr;":274,"EmptySmallSquare;":9723,"EmptyVerySmallSquare;":9643,"Eogon;":280,"Eopf;":[55349,56636],"Epsilon;":917,"Equal;":10869,"EqualTilde;":8770,"Equilibrium;":8652,"Escr;":8496,"Esim;":10867,"Eta;":919,Euml:203,"Euml;":203,"Exists;":8707,"ExponentialE;":8519,"Fcy;":1060,"Ffr;":[55349,56585],"FilledSmallSquare;":9724,"FilledVerySmallSquare;":9642,"Fopf;":[55349,56637],"ForAll;":8704,"Fouriertrf;":8497,"Fscr;":8497,"GJcy;":1027,GT:62,"GT;":62,"Gamma;":915,"Gammad;":988,"Gbreve;":286,"Gcedil;":290,"Gcirc;":284,"Gcy;":1043,"Gdot;":288,"Gfr;":[55349,56586],"Gg;":8921,"Gopf;":[55349,56638],"GreaterEqual;":8805,"GreaterEqualLess;":8923,"GreaterFullEqual;":8807,"GreaterGreater;":10914,"GreaterLess;":8823,"GreaterSlantEqual;":10878,"GreaterTilde;":8819,"Gscr;":[55349,56482],"Gt;":8811,"HARDcy;":1066,"Hacek;":711,"Hat;":94,"Hcirc;":292,"Hfr;":8460,"HilbertSpace;":8459,"Hopf;":8461,"HorizontalLine;":9472,"Hscr;":8459,"Hstrok;":294,"HumpDownHump;":8782,"HumpEqual;":8783,"IEcy;":1045,"IJlig;":306,"IOcy;":1025,Iacute:205,"Iacute;":205,Icirc:206,"Icirc;":206,"Icy;":1048,"Idot;":304,"Ifr;":8465,Igrave:204,"Igrave;":204,"Im;":8465,"Imacr;":298,"ImaginaryI;":8520,"Implies;":8658,"Int;":8748,"Integral;":8747,"Intersection;":8898,"InvisibleComma;":8291,"InvisibleTimes;":8290,"Iogon;":302,"Iopf;":[55349,56640],"Iota;":921,"Iscr;":8464,"Itilde;":296,"Iukcy;":1030,Iuml:207,"Iuml;":207,"Jcirc;":308,"Jcy;":1049,"Jfr;":[55349,56589],"Jopf;":[55349,56641],"Jscr;":[55349,56485],"Jsercy;":1032,"Jukcy;":1028,"KHcy;":1061,"KJcy;":1036,"Kappa;":922,"Kcedil;":310,"Kcy;":1050,"Kfr;":[55349,56590],"Kopf;":[55349,56642],"Kscr;":[55349,56486],"LJcy;":1033,LT:60,"LT;":60,"Lacute;":313,"Lambda;":923,"Lang;":10218,"Laplacetrf;":8466,"Larr;":8606,"Lcaron;":317,"Lcedil;":315,"Lcy;":1051,"LeftAngleBracket;":10216,"LeftArrow;":8592,"LeftArrowBar;":8676,"LeftArrowRightArrow;":8646,"LeftCeiling;":8968,"LeftDoubleBracket;":10214,"LeftDownTeeVector;":10593,"LeftDownVector;":8643,"LeftDownVectorBar;":10585,"LeftFloor;":8970,"LeftRightArrow;":8596,"LeftRightVector;":10574,"LeftTee;":8867,"LeftTeeArrow;":8612,"LeftTeeVector;":10586,"LeftTriangle;":8882,"LeftTriangleBar;":10703,"LeftTriangleEqual;":8884,"LeftUpDownVector;":10577,"LeftUpTeeVector;":10592,"LeftUpVector;":8639,"LeftUpVectorBar;":10584,"LeftVector;":8636,"LeftVectorBar;":10578,"Leftarrow;":8656,"Leftrightarrow;":8660,"LessEqualGreater;":8922,"LessFullEqual;":8806,"LessGreater;":8822,"LessLess;":10913,"LessSlantEqual;":10877,"LessTilde;":8818,"Lfr;":[55349,56591],"Ll;":8920,"Lleftarrow;":8666,"Lmidot;":319,"LongLeftArrow;":10229,"LongLeftRightArrow;":10231,"LongRightArrow;":10230,"Longleftarrow;":10232,"Longleftrightarrow;":10234,"Longrightarrow;":10233,"Lopf;":[55349,56643],"LowerLeftArrow;":8601,"LowerRightArrow;":8600,"Lscr;":8466,"Lsh;":8624,"Lstrok;":321,"Lt;":8810,"Map;":10501,"Mcy;":1052,"MediumSpace;":8287,"Mellintrf;":8499,"Mfr;":[55349,56592],"MinusPlus;":8723,"Mopf;":[55349,56644],"Mscr;":8499,"Mu;":924,"NJcy;":1034,"Nacute;":323,"Ncaron;":327,"Ncedil;":325,"Ncy;":1053,"NegativeMediumSpace;":8203,"NegativeThickSpace;":8203,"NegativeThinSpace;":8203,"NegativeVeryThinSpace;":8203,"NestedGreaterGreater;":8811,"NestedLessLess;":8810,"NewLine;":10,"Nfr;":[55349,56593],"NoBreak;":8288,"NonBreakingSpace;":160,"Nopf;":8469,"Not;":10988,"NotCongruent;":8802,"NotCupCap;":8813,"NotDoubleVerticalBar;":8742,"NotElement;":8713,"NotEqual;":8800,"NotEqualTilde;":[8770,824],"NotExists;":8708,"NotGreater;":8815,"NotGreaterEqual;":8817,"NotGreaterFullEqual;":[8807,824],"NotGreaterGreater;":[8811,824],"NotGreaterLess;":8825,"NotGreaterSlantEqual;":[10878,824],"NotGreaterTilde;":8821,"NotHumpDownHump;":[8782,824],"NotHumpEqual;":[8783,824],"NotLeftTriangle;":8938,"NotLeftTriangleBar;":[10703,824],"NotLeftTriangleEqual;":8940,"NotLess;":8814,"NotLessEqual;":8816,"NotLessGreater;":8824,"NotLessLess;":[8810,824],"NotLessSlantEqual;":[10877,824],"NotLessTilde;":8820,"NotNestedGreaterGreater;":[10914,824],"NotNestedLessLess;":[10913,824],"NotPrecedes;":8832,"NotPrecedesEqual;":[10927,824],"NotPrecedesSlantEqual;":8928,"NotReverseElement;":8716,"NotRightTriangle;":8939,"NotRightTriangleBar;":[10704,824],"NotRightTriangleEqual;":8941,"NotSquareSubset;":[8847,824],"NotSquareSubsetEqual;":8930,"NotSquareSuperset;":[8848,824],"NotSquareSupersetEqual;":8931,"NotSubset;":[8834,8402],"NotSubsetEqual;":8840,"NotSucceeds;":8833,"NotSucceedsEqual;":[10928,824],"NotSucceedsSlantEqual;":8929,"NotSucceedsTilde;":[8831,824],"NotSuperset;":[8835,8402],"NotSupersetEqual;":8841,"NotTilde;":8769,"NotTildeEqual;":8772,"NotTildeFullEqual;":8775,"NotTildeTilde;":8777,"NotVerticalBar;":8740,"Nscr;":[55349,56489],Ntilde:209,"Ntilde;":209,"Nu;":925,"OElig;":338,Oacute:211,"Oacute;":211,Ocirc:212,"Ocirc;":212,"Ocy;":1054,"Odblac;":336,"Ofr;":[55349,56594],Ograve:210,"Ograve;":210,"Omacr;":332,"Omega;":937,"Omicron;":927,"Oopf;":[55349,56646],"OpenCurlyDoubleQuote;":8220,"OpenCurlyQuote;":8216,"Or;":10836,"Oscr;":[55349,56490],Oslash:216,"Oslash;":216,Otilde:213,"Otilde;":213,"Otimes;":10807,Ouml:214,"Ouml;":214,"OverBar;":8254,"OverBrace;":9182,"OverBracket;":9140,"OverParenthesis;":9180,"PartialD;":8706,"Pcy;":1055,"Pfr;":[55349,56595],"Phi;":934,"Pi;":928,"PlusMinus;":177,"Poincareplane;":8460,"Popf;":8473,"Pr;":10939,"Precedes;":8826,"PrecedesEqual;":10927,"PrecedesSlantEqual;":8828,"PrecedesTilde;":8830,"Prime;":8243,"Product;":8719,"Proportion;":8759,"Proportional;":8733,"Pscr;":[55349,56491],"Psi;":936,QUOT:34,"QUOT;":34,"Qfr;":[55349,56596],"Qopf;":8474,"Qscr;":[55349,56492],"RBarr;":10512,REG:174,"REG;":174,"Racute;":340,"Rang;":10219,"Rarr;":8608,"Rarrtl;":10518,"Rcaron;":344,"Rcedil;":342,"Rcy;":1056,"Re;":8476,"ReverseElement;":8715,"ReverseEquilibrium;":8651,"ReverseUpEquilibrium;":10607,"Rfr;":8476,"Rho;":929,"RightAngleBracket;":10217,"RightArrow;":8594,"RightArrowBar;":8677,"RightArrowLeftArrow;":8644,"RightCeiling;":8969,"RightDoubleBracket;":10215,"RightDownTeeVector;":10589,"RightDownVector;":8642,"RightDownVectorBar;":10581,"RightFloor;":8971,"RightTee;":8866,"RightTeeArrow;":8614,"RightTeeVector;":10587,"RightTriangle;":8883,"RightTriangleBar;":10704,"RightTriangleEqual;":8885,"RightUpDownVector;":10575,"RightUpTeeVector;":10588,"RightUpVector;":8638,"RightUpVectorBar;":10580,"RightVector;":8640,"RightVectorBar;":10579,"Rightarrow;":8658,"Ropf;":8477,"RoundImplies;":10608,"Rrightarrow;":8667,"Rscr;":8475,"Rsh;":8625,"RuleDelayed;":10740,"SHCHcy;":1065,"SHcy;":1064,"SOFTcy;":1068,"Sacute;":346,"Sc;":10940,"Scaron;":352,"Scedil;":350,"Scirc;":348,"Scy;":1057,"Sfr;":[55349,56598],"ShortDownArrow;":8595,"ShortLeftArrow;":8592,"ShortRightArrow;":8594,"ShortUpArrow;":8593,"Sigma;":931,"SmallCircle;":8728,"Sopf;":[55349,56650],"Sqrt;":8730,"Square;":9633,"SquareIntersection;":8851,"SquareSubset;":8847,"SquareSubsetEqual;":8849,"SquareSuperset;":8848,"SquareSupersetEqual;":8850,"SquareUnion;":8852,"Sscr;":[55349,56494],"Star;":8902,"Sub;":8912,"Subset;":8912,"SubsetEqual;":8838,"Succeeds;":8827,"SucceedsEqual;":10928,"SucceedsSlantEqual;":8829,"SucceedsTilde;":8831,"SuchThat;":8715,"Sum;":8721,"Sup;":8913,"Superset;":8835,"SupersetEqual;":8839,"Supset;":8913,THORN:222,"THORN;":222,"TRADE;":8482,"TSHcy;":1035,"TScy;":1062,"Tab;":9,"Tau;":932,"Tcaron;":356,"Tcedil;":354,"Tcy;":1058,"Tfr;":[55349,56599],"Therefore;":8756,"Theta;":920,"ThickSpace;":[8287,8202],"ThinSpace;":8201,"Tilde;":8764,"TildeEqual;":8771,"TildeFullEqual;":8773,"TildeTilde;":8776,"Topf;":[55349,56651],"TripleDot;":8411,"Tscr;":[55349,56495],"Tstrok;":358,Uacute:218,"Uacute;":218,"Uarr;":8607,"Uarrocir;":10569,"Ubrcy;":1038,"Ubreve;":364,Ucirc:219,"Ucirc;":219,"Ucy;":1059,"Udblac;":368,"Ufr;":[55349,56600],Ugrave:217,"Ugrave;":217,"Umacr;":362,"UnderBar;":95,"UnderBrace;":9183,"UnderBracket;":9141,"UnderParenthesis;":9181,"Union;":8899,"UnionPlus;":8846,"Uogon;":370,"Uopf;":[55349,56652],"UpArrow;":8593,"UpArrowBar;":10514,"UpArrowDownArrow;":8645,"UpDownArrow;":8597,"UpEquilibrium;":10606,"UpTee;":8869,"UpTeeArrow;":8613,"Uparrow;":8657,"Updownarrow;":8661,"UpperLeftArrow;":8598,"UpperRightArrow;":8599,"Upsi;":978,"Upsilon;":933,"Uring;":366,"Uscr;":[55349,56496],"Utilde;":360,Uuml:220,"Uuml;":220,"VDash;":8875,"Vbar;":10987,"Vcy;":1042,"Vdash;":8873,"Vdashl;":10982,"Vee;":8897,"Verbar;":8214,"Vert;":8214,"VerticalBar;":8739,"VerticalLine;":124,"VerticalSeparator;":10072,"VerticalTilde;":8768,"VeryThinSpace;":8202,"Vfr;":[55349,56601],"Vopf;":[55349,56653],"Vscr;":[55349,56497],"Vvdash;":8874,"Wcirc;":372,"Wedge;":8896,"Wfr;":[55349,56602],"Wopf;":[55349,56654],"Wscr;":[55349,56498],"Xfr;":[55349,56603],"Xi;":926,"Xopf;":[55349,56655],"Xscr;":[55349,56499],"YAcy;":1071,"YIcy;":1031,"YUcy;":1070,Yacute:221,"Yacute;":221,"Ycirc;":374,"Ycy;":1067,"Yfr;":[55349,56604],"Yopf;":[55349,56656],"Yscr;":[55349,56500],"Yuml;":376,"ZHcy;":1046,"Zacute;":377,"Zcaron;":381,"Zcy;":1047,"Zdot;":379,"ZeroWidthSpace;":8203,"Zeta;":918,"Zfr;":8488,"Zopf;":8484,"Zscr;":[55349,56501],aacute:225,"aacute;":225,"abreve;":259,"ac;":8766,"acE;":[8766,819],"acd;":8767,acirc:226,"acirc;":226,acute:180,"acute;":180,"acy;":1072,aelig:230,"aelig;":230,"af;":8289,"afr;":[55349,56606],agrave:224,"agrave;":224,"alefsym;":8501,"aleph;":8501,"alpha;":945,"amacr;":257,"amalg;":10815,amp:38,"amp;":38,"and;":8743,"andand;":10837,"andd;":10844,"andslope;":10840,"andv;":10842,"ang;":8736,"ange;":10660,"angle;":8736,"angmsd;":8737,"angmsdaa;":10664,"angmsdab;":10665,"angmsdac;":10666,"angmsdad;":10667,"angmsdae;":10668,"angmsdaf;":10669,"angmsdag;":10670,"angmsdah;":10671,"angrt;":8735,"angrtvb;":8894,"angrtvbd;":10653,"angsph;":8738,"angst;":197,"angzarr;":9084,"aogon;":261,"aopf;":[55349,56658],"ap;":8776,"apE;":10864,"apacir;":10863,"ape;":8778,"apid;":8779,"apos;":39,"approx;":8776,"approxeq;":8778,aring:229,"aring;":229,"ascr;":[55349,56502],"ast;":42,"asymp;":8776,"asympeq;":8781,atilde:227,"atilde;":227,auml:228,"auml;":228,"awconint;":8755,"awint;":10769,"bNot;":10989,"backcong;":8780,"backepsilon;":1014,"backprime;":8245,"backsim;":8765,"backsimeq;":8909,"barvee;":8893,"barwed;":8965,"barwedge;":8965,"bbrk;":9141,"bbrktbrk;":9142,"bcong;":8780,"bcy;":1073,"bdquo;":8222,"becaus;":8757,"because;":8757,"bemptyv;":10672,"bepsi;":1014,"bernou;":8492,"beta;":946,"beth;":8502,"between;":8812,"bfr;":[55349,56607],"bigcap;":8898,"bigcirc;":9711,"bigcup;":8899,"bigodot;":10752,"bigoplus;":10753,"bigotimes;":10754,"bigsqcup;":10758,"bigstar;":9733,"bigtriangledown;":9661,"bigtriangleup;":9651,"biguplus;":10756,"bigvee;":8897,"bigwedge;":8896,"bkarow;":10509,"blacklozenge;":10731,"blacksquare;":9642,"blacktriangle;":9652,"blacktriangledown;":9662,"blacktriangleleft;":9666,"blacktriangleright;":9656,"blank;":9251,"blk12;":9618,"blk14;":9617,"blk34;":9619,"block;":9608,"bne;":[61,8421],"bnequiv;":[8801,8421],"bnot;":8976,"bopf;":[55349,56659],"bot;":8869,"bottom;":8869,"bowtie;":8904,"boxDL;":9559,"boxDR;":9556,"boxDl;":9558,"boxDr;":9555,"boxH;":9552,"boxHD;":9574,"boxHU;":9577,"boxHd;":9572,"boxHu;":9575,"boxUL;":9565,"boxUR;":9562,"boxUl;":9564,"boxUr;":9561,"boxV;":9553,"boxVH;":9580,"boxVL;":9571,"boxVR;":9568,"boxVh;":9579,"boxVl;":9570,"boxVr;":9567,"boxbox;":10697,"boxdL;":9557,"boxdR;":9554,"boxdl;":9488,"boxdr;":9484,"boxh;":9472,"boxhD;":9573,"boxhU;":9576,"boxhd;":9516,"boxhu;":9524,"boxminus;":8863,"boxplus;":8862,"boxtimes;":8864,"boxuL;":9563,"boxuR;":9560,"boxul;":9496,"boxur;":9492,"boxv;":9474,"boxvH;":9578,"boxvL;":9569,"boxvR;":9566,"boxvh;":9532,"boxvl;":9508,"boxvr;":9500,"bprime;":8245,"breve;":728,brvbar:166,"brvbar;":166,"bscr;":[55349,56503],"bsemi;":8271,"bsim;":8765,"bsime;":8909,"bsol;":92,"bsolb;":10693,"bsolhsub;":10184,"bull;":8226,"bullet;":8226,"bump;":8782,"bumpE;":10926,"bumpe;":8783,"bumpeq;":8783,"cacute;":263,"cap;":8745,"capand;":10820,"capbrcup;":10825,"capcap;":10827,"capcup;":10823,"capdot;":10816,"caps;":[8745,65024],"caret;":8257,"caron;":711,"ccaps;":10829,"ccaron;":269,ccedil:231,"ccedil;":231,"ccirc;":265,"ccups;":10828,"ccupssm;":10832,"cdot;":267,cedil:184,"cedil;":184,"cemptyv;":10674,cent:162,"cent;":162,"centerdot;":183,"cfr;":[55349,56608],"chcy;":1095,"check;":10003,"checkmark;":10003,"chi;":967,"cir;":9675,"cirE;":10691,"circ;":710,"circeq;":8791,"circlearrowleft;":8634,"circlearrowright;":8635,"circledR;":174,"circledS;":9416,"circledast;":8859,"circledcirc;":8858,"circleddash;":8861,"cire;":8791,"cirfnint;":10768,"cirmid;":10991,"cirscir;":10690,"clubs;":9827,"clubsuit;":9827,"colon;":58,"colone;":8788,"coloneq;":8788,"comma;":44,"commat;":64,"comp;":8705,"compfn;":8728,"complement;":8705,"complexes;":8450,"cong;":8773,"congdot;":10861,"conint;":8750,"copf;":[55349,56660],"coprod;":8720,copy:169,"copy;":169,"copysr;":8471,"crarr;":8629,"cross;":10007,"cscr;":[55349,56504],"csub;":10959,"csube;":10961,"csup;":10960,"csupe;":10962,"ctdot;":8943,"cudarrl;":10552,"cudarrr;":10549,"cuepr;":8926,"cuesc;":8927,"cularr;":8630,"cularrp;":10557,"cup;":8746,"cupbrcap;":10824,"cupcap;":10822,"cupcup;":10826,"cupdot;":8845,"cupor;":10821,"cups;":[8746,65024],"curarr;":8631,"curarrm;":10556,"curlyeqprec;":8926,"curlyeqsucc;":8927,"curlyvee;":8910,"curlywedge;":8911,curren:164,"curren;":164,"curvearrowleft;":8630,"curvearrowright;":8631,"cuvee;":8910,"cuwed;":8911,"cwconint;":8754,"cwint;":8753,"cylcty;":9005,"dArr;":8659,"dHar;":10597,"dagger;":8224,"daleth;":8504,"darr;":8595,"dash;":8208,"dashv;":8867,"dbkarow;":10511,"dblac;":733,"dcaron;":271,"dcy;":1076,"dd;":8518,"ddagger;":8225,"ddarr;":8650,"ddotseq;":10871,deg:176,"deg;":176,"delta;":948,"demptyv;":10673,"dfisht;":10623,"dfr;":[55349,56609],"dharl;":8643,"dharr;":8642,"diam;":8900,"diamond;":8900,"diamondsuit;":9830,"diams;":9830,"die;":168,"digamma;":989,"disin;":8946,"div;":247,divide:247,"divide;":247,"divideontimes;":8903,"divonx;":8903,"djcy;":1106,"dlcorn;":8990,"dlcrop;":8973,"dollar;":36,"dopf;":[55349,56661],"dot;":729,"doteq;":8784,"doteqdot;":8785,"dotminus;":8760,"dotplus;":8724,"dotsquare;":8865,"doublebarwedge;":8966,"downarrow;":8595,"downdownarrows;":8650,"downharpoonleft;":8643,"downharpoonright;":8642,"drbkarow;":10512,"drcorn;":8991,"drcrop;":8972,"dscr;":[55349,56505],"dscy;":1109,"dsol;":10742,"dstrok;":273,"dtdot;":8945,"dtri;":9663,"dtrif;":9662,"duarr;":8693,"duhar;":10607,"dwangle;":10662,"dzcy;":1119,"dzigrarr;":10239,"eDDot;":10871,"eDot;":8785,eacute:233,"eacute;":233,"easter;":10862,"ecaron;":283,"ecir;":8790,ecirc:234,"ecirc;":234,"ecolon;":8789,"ecy;":1101,"edot;":279,"ee;":8519,"efDot;":8786,"efr;":[55349,56610],"eg;":10906,egrave:232,"egrave;":232,"egs;":10902,"egsdot;":10904,"el;":10905,"elinters;":9191,"ell;":8467,"els;":10901,"elsdot;":10903,"emacr;":275,"empty;":8709,"emptyset;":8709,"emptyv;":8709,"emsp13;":8196,"emsp14;":8197,"emsp;":8195,"eng;":331,"ensp;":8194,"eogon;":281,"eopf;":[55349,56662],"epar;":8917,"eparsl;":10723,"eplus;":10865,"epsi;":949,"epsilon;":949,"epsiv;":1013,"eqcirc;":8790,"eqcolon;":8789,"eqsim;":8770,"eqslantgtr;":10902,"eqslantless;":10901,"equals;":61,"equest;":8799,"equiv;":8801,"equivDD;":10872,"eqvparsl;":10725,"erDot;":8787,"erarr;":10609,"escr;":8495,"esdot;":8784,"esim;":8770,"eta;":951,eth:240,"eth;":240,euml:235,"euml;":235,"euro;":8364,"excl;":33,"exist;":8707,"expectation;":8496,"exponentiale;":8519,"fallingdotseq;":8786,"fcy;":1092,"female;":9792,"ffilig;":64259,"fflig;":64256,"ffllig;":64260,"ffr;":[55349,56611],"filig;":64257,"fjlig;":[102,106],"flat;":9837,"fllig;":64258,"fltns;":9649,"fnof;":402,"fopf;":[55349,56663],"forall;":8704,"fork;":8916,"forkv;":10969,"fpartint;":10765,frac12:189,"frac12;":189,"frac13;":8531,frac14:188,"frac14;":188,"frac15;":8533,"frac16;":8537,"frac18;":8539,"frac23;":8532,"frac25;":8534,frac34:190,"frac34;":190,"frac35;":8535,"frac38;":8540,"frac45;":8536,"frac56;":8538,"frac58;":8541,"frac78;":8542,"frasl;":8260,"frown;":8994,"fscr;":[55349,56507],"gE;":8807,"gEl;":10892,"gacute;":501,"gamma;":947,"gammad;":989,"gap;":10886,"gbreve;":287,"gcirc;":285,"gcy;":1075,"gdot;":289,"ge;":8805,"gel;":8923,"geq;":8805,"geqq;":8807,"geqslant;":10878,"ges;":10878,"gescc;":10921,"gesdot;":10880,"gesdoto;":10882,"gesdotol;":10884,"gesl;":[8923,65024],"gesles;":10900,"gfr;":[55349,56612],"gg;":8811,"ggg;":8921,"gimel;":8503,"gjcy;":1107,"gl;":8823,"glE;":10898,"gla;":10917,"glj;":10916,"gnE;":8809,"gnap;":10890,"gnapprox;":10890,"gne;":10888,"gneq;":10888,"gneqq;":8809,"gnsim;":8935,"gopf;":[55349,56664],"grave;":96,"gscr;":8458,"gsim;":8819,"gsime;":10894,"gsiml;":10896,gt:62,"gt;":62,"gtcc;":10919,"gtcir;":10874,"gtdot;":8919,"gtlPar;":10645,"gtquest;":10876,"gtrapprox;":10886,"gtrarr;":10616,"gtrdot;":8919,"gtreqless;":8923,"gtreqqless;":10892,"gtrless;":8823,"gtrsim;":8819,"gvertneqq;":[8809,65024],"gvnE;":[8809,65024],"hArr;":8660,"hairsp;":8202,"half;":189,"hamilt;":8459,"hardcy;":1098,"harr;":8596,"harrcir;":10568,"harrw;":8621,"hbar;":8463,"hcirc;":293,"hearts;":9829,"heartsuit;":9829,"hellip;":8230,"hercon;":8889,"hfr;":[55349,56613],"hksearow;":10533,"hkswarow;":10534,"hoarr;":8703,"homtht;":8763,"hookleftarrow;":8617,"hookrightarrow;":8618,"hopf;":[55349,56665],"horbar;":8213,"hscr;":[55349,56509],"hslash;":8463,"hstrok;":295,"hybull;":8259,"hyphen;":8208,iacute:237,"iacute;":237,"ic;":8291,icirc:238,"icirc;":238,"icy;":1080,"iecy;":1077,iexcl:161,"iexcl;":161,"iff;":8660,"ifr;":[55349,56614],igrave:236,"igrave;":236,"ii;":8520,"iiiint;":10764,"iiint;":8749,"iinfin;":10716,"iiota;":8489,"ijlig;":307,"imacr;":299,"image;":8465,"imagline;":8464,"imagpart;":8465,"imath;":305,"imof;":8887,"imped;":437,"in;":8712,"incare;":8453,"infin;":8734,"infintie;":10717,"inodot;":305,"int;":8747,"intcal;":8890,"integers;":8484,"intercal;":8890,"intlarhk;":10775,"intprod;":10812,"iocy;":1105,"iogon;":303,"iopf;":[55349,56666],"iota;":953,"iprod;":10812,iquest:191,"iquest;":191,"iscr;":[55349,56510],"isin;":8712,"isinE;":8953,"isindot;":8949,"isins;":8948,"isinsv;":8947,"isinv;":8712,"it;":8290,"itilde;":297,"iukcy;":1110,iuml:239,"iuml;":239,"jcirc;":309,"jcy;":1081,"jfr;":[55349,56615],"jmath;":567,"jopf;":[55349,56667],"jscr;":[55349,56511],"jsercy;":1112,"jukcy;":1108,"kappa;":954,"kappav;":1008,"kcedil;":311,"kcy;":1082,"kfr;":[55349,56616],"kgreen;":312,"khcy;":1093,"kjcy;":1116,"kopf;":[55349,56668],"kscr;":[55349,56512],"lAarr;":8666,"lArr;":8656,"lAtail;":10523,"lBarr;":10510,"lE;":8806,"lEg;":10891,"lHar;":10594,"lacute;":314,"laemptyv;":10676,"lagran;":8466,"lambda;":955,"lang;":10216,"langd;":10641,"langle;":10216,"lap;":10885,laquo:171,"laquo;":171,"larr;":8592,"larrb;":8676,"larrbfs;":10527,"larrfs;":10525,"larrhk;":8617,"larrlp;":8619,"larrpl;":10553,"larrsim;":10611,"larrtl;":8610,"lat;":10923,"latail;":10521,"late;":10925,"lates;":[10925,65024],"lbarr;":10508,"lbbrk;":10098,"lbrace;":123,"lbrack;":91,"lbrke;":10635,"lbrksld;":10639,"lbrkslu;":10637,"lcaron;":318,"lcedil;":316,"lceil;":8968,"lcub;":123,"lcy;":1083,"ldca;":10550,"ldquo;":8220,"ldquor;":8222,"ldrdhar;":10599,"ldrushar;":10571,"ldsh;":8626,"le;":8804,"leftarrow;":8592,"leftarrowtail;":8610,"leftharpoondown;":8637,"leftharpoonup;":8636,"leftleftarrows;":8647,"leftrightarrow;":8596,"leftrightarrows;":8646,"leftrightharpoons;":8651,"leftrightsquigarrow;":8621,"leftthreetimes;":8907,"leg;":8922,"leq;":8804,"leqq;":8806,"leqslant;":10877,"les;":10877,"lescc;":10920,"lesdot;":10879,"lesdoto;":10881,"lesdotor;":10883,"lesg;":[8922,65024],"lesges;":10899,"lessapprox;":10885,"lessdot;":8918,"lesseqgtr;":8922,"lesseqqgtr;":10891,"lessgtr;":8822,"lesssim;":8818,"lfisht;":10620,"lfloor;":8970,"lfr;":[55349,56617],"lg;":8822,"lgE;":10897,"lhard;":8637,"lharu;":8636,"lharul;":10602,"lhblk;":9604,"ljcy;":1113,"ll;":8810,"llarr;":8647,"llcorner;":8990,"llhard;":10603,"lltri;":9722,"lmidot;":320,"lmoust;":9136,"lmoustache;":9136,"lnE;":8808,"lnap;":10889,"lnapprox;":10889,"lne;":10887,"lneq;":10887,"lneqq;":8808,"lnsim;":8934,"loang;":10220,"loarr;":8701,"lobrk;":10214,"longleftarrow;":10229,"longleftrightarrow;":10231,"longmapsto;":10236,"longrightarrow;":10230,"looparrowleft;":8619,"looparrowright;":8620,"lopar;":10629,"lopf;":[55349,56669],"loplus;":10797,"lotimes;":10804,"lowast;":8727,"lowbar;":95,"loz;":9674,"lozenge;":9674,"lozf;":10731,"lpar;":40,"lparlt;":10643,"lrarr;":8646,"lrcorner;":8991,"lrhar;":8651,"lrhard;":10605,"lrm;":8206,"lrtri;":8895,"lsaquo;":8249,"lscr;":[55349,56513],"lsh;":8624,"lsim;":8818,"lsime;":10893,"lsimg;":10895,"lsqb;":91,"lsquo;":8216,"lsquor;":8218,"lstrok;":322,lt:60,"lt;":60,"ltcc;":10918,"ltcir;":10873,"ltdot;":8918,"lthree;":8907,"ltimes;":8905,"ltlarr;":10614,"ltquest;":10875,"ltrPar;":10646,"ltri;":9667,"ltrie;":8884,"ltrif;":9666,"lurdshar;":10570,"luruhar;":10598,"lvertneqq;":[8808,65024],"lvnE;":[8808,65024],"mDDot;":8762,macr:175,"macr;":175,"male;":9794,"malt;":10016,"maltese;":10016,"map;":8614,"mapsto;":8614,"mapstodown;":8615,"mapstoleft;":8612,"mapstoup;":8613,"marker;":9646,"mcomma;":10793,"mcy;":1084,"mdash;":8212,"measuredangle;":8737,"mfr;":[55349,56618],"mho;":8487,micro:181,"micro;":181,"mid;":8739,"midast;":42,"midcir;":10992,middot:183,"middot;":183,"minus;":8722,"minusb;":8863,"minusd;":8760,"minusdu;":10794,"mlcp;":10971,"mldr;":8230,"mnplus;":8723,"models;":8871,"mopf;":[55349,56670],"mp;":8723,"mscr;":[55349,56514],"mstpos;":8766,"mu;":956,"multimap;":8888,"mumap;":8888,"nGg;":[8921,824],"nGt;":[8811,8402],"nGtv;":[8811,824],"nLeftarrow;":8653,"nLeftrightarrow;":8654,"nLl;":[8920,824],"nLt;":[8810,8402],"nLtv;":[8810,824],"nRightarrow;":8655,"nVDash;":8879,"nVdash;":8878,"nabla;":8711,"nacute;":324,"nang;":[8736,8402],"nap;":8777,"napE;":[10864,824],"napid;":[8779,824],"napos;":329,"napprox;":8777,"natur;":9838,"natural;":9838,"naturals;":8469,nbsp:160,"nbsp;":160,"nbump;":[8782,824],"nbumpe;":[8783,824],"ncap;":10819,"ncaron;":328,"ncedil;":326,"ncong;":8775,"ncongdot;":[10861,824],"ncup;":10818,"ncy;":1085,"ndash;":8211,"ne;":8800,"neArr;":8663,"nearhk;":10532,"nearr;":8599,"nearrow;":8599,"nedot;":[8784,824],"nequiv;":8802,"nesear;":10536,"nesim;":[8770,824],"nexist;":8708,"nexists;":8708,"nfr;":[55349,56619],"ngE;":[8807,824],"nge;":8817,"ngeq;":8817,"ngeqq;":[8807,824],"ngeqslant;":[10878,824],"nges;":[10878,824],"ngsim;":8821,"ngt;":8815,"ngtr;":8815,"nhArr;":8654,"nharr;":8622,"nhpar;":10994,"ni;":8715,"nis;":8956,"nisd;":8954,"niv;":8715,"njcy;":1114,"nlArr;":8653,"nlE;":[8806,824],"nlarr;":8602,"nldr;":8229,"nle;":8816,"nleftarrow;":8602,"nleftrightarrow;":8622,"nleq;":8816,"nleqq;":[8806,824],"nleqslant;":[10877,824],"nles;":[10877,824],"nless;":8814,"nlsim;":8820,"nlt;":8814,"nltri;":8938,"nltrie;":8940,"nmid;":8740,"nopf;":[55349,56671],not:172,"not;":172,"notin;":8713,"notinE;":[8953,824],"notindot;":[8949,824],"notinva;":8713,"notinvb;":8951,"notinvc;":8950,"notni;":8716,"notniva;":8716,"notnivb;":8958,"notnivc;":8957,"npar;":8742,"nparallel;":8742,"nparsl;":[11005,8421],"npart;":[8706,824],"npolint;":10772,"npr;":8832,"nprcue;":8928,"npre;":[10927,824],"nprec;":8832,"npreceq;":[10927,824],"nrArr;":8655,"nrarr;":8603,"nrarrc;":[10547,824],"nrarrw;":[8605,824],"nrightarrow;":8603,"nrtri;":8939,"nrtrie;":8941,"nsc;":8833,"nsccue;":8929,"nsce;":[10928,824],"nscr;":[55349,56515],"nshortmid;":8740,"nshortparallel;":8742,"nsim;":8769,"nsime;":8772,"nsimeq;":8772,"nsmid;":8740,"nspar;":8742,"nsqsube;":8930,"nsqsupe;":8931,"nsub;":8836,"nsubE;":[10949,824],"nsube;":8840,"nsubset;":[8834,8402],"nsubseteq;":8840,"nsubseteqq;":[10949,824],"nsucc;":8833,"nsucceq;":[10928,824],"nsup;":8837,"nsupE;":[10950,824],"nsupe;":8841,"nsupset;":[8835,8402],"nsupseteq;":8841,"nsupseteqq;":[10950,824],"ntgl;":8825,ntilde:241,"ntilde;":241,"ntlg;":8824,"ntriangleleft;":8938,"ntrianglelefteq;":8940,"ntriangleright;":8939,"ntrianglerighteq;":8941,"nu;":957,"num;":35,"numero;":8470,"numsp;":8199,"nvDash;":8877,"nvHarr;":10500,"nvap;":[8781,8402],"nvdash;":8876,"nvge;":[8805,8402],"nvgt;":[62,8402],"nvinfin;":10718,"nvlArr;":10498,"nvle;":[8804,8402],"nvlt;":[60,8402],"nvltrie;":[8884,8402],"nvrArr;":10499,"nvrtrie;":[8885,8402],"nvsim;":[8764,8402],"nwArr;":8662,"nwarhk;":10531,"nwarr;":8598,"nwarrow;":8598,"nwnear;":10535,"oS;":9416,oacute:243,"oacute;":243,"oast;":8859,"ocir;":8858,ocirc:244,"ocirc;":244,"ocy;":1086,"odash;":8861,"odblac;":337,"odiv;":10808,"odot;":8857,"odsold;":10684,"oelig;":339,"ofcir;":10687,"ofr;":[55349,56620],"ogon;":731,ograve:242,"ograve;":242,"ogt;":10689,"ohbar;":10677,"ohm;":937,"oint;":8750,"olarr;":8634,"olcir;":10686,"olcross;":10683,"oline;":8254,"olt;":10688,"omacr;":333,"omega;":969,"omicron;":959,"omid;":10678,"ominus;":8854,"oopf;":[55349,56672],"opar;":10679,"operp;":10681,"oplus;":8853,"or;":8744,"orarr;":8635,"ord;":10845,"order;":8500,"orderof;":8500,ordf:170,"ordf;":170,ordm:186,"ordm;":186,"origof;":8886,"oror;":10838,"orslope;":10839,"orv;":10843,"oscr;":8500,oslash:248,"oslash;":248,"osol;":8856,otilde:245,"otilde;":245,"otimes;":8855,"otimesas;":10806,ouml:246,"ouml;":246,"ovbar;":9021,"par;":8741,para:182,"para;":182,"parallel;":8741,"parsim;":10995,"parsl;":11005,"part;":8706,"pcy;":1087,"percnt;":37,"period;":46,"permil;":8240,"perp;":8869,"pertenk;":8241,"pfr;":[55349,56621],"phi;":966,"phiv;":981,"phmmat;":8499,"phone;":9742,"pi;":960,"pitchfork;":8916,"piv;":982,"planck;":8463,"planckh;":8462,"plankv;":8463,"plus;":43,"plusacir;":10787,"plusb;":8862,"pluscir;":10786,"plusdo;":8724,"plusdu;":10789,"pluse;":10866,plusmn:177,"plusmn;":177,"plussim;":10790,"plustwo;":10791,"pm;":177,"pointint;":10773,"popf;":[55349,56673],pound:163,"pound;":163,"pr;":8826,"prE;":10931,"prap;":10935,"prcue;":8828,"pre;":10927,"prec;":8826,"precapprox;":10935,"preccurlyeq;":8828,"preceq;":10927,"precnapprox;":10937,"precneqq;":10933,"precnsim;":8936,"precsim;":8830,"prime;":8242,"primes;":8473,"prnE;":10933,"prnap;":10937,"prnsim;":8936,"prod;":8719,"profalar;":9006,"profline;":8978,"profsurf;":8979,"prop;":8733,"propto;":8733,"prsim;":8830,"prurel;":8880,"pscr;":[55349,56517],"psi;":968,"puncsp;":8200,"qfr;":[55349,56622],"qint;":10764,"qopf;":[55349,56674],"qprime;":8279,"qscr;":[55349,56518],"quaternions;":8461,"quatint;":10774,"quest;":63,"questeq;":8799,quot:34,"quot;":34,"rAarr;":8667,"rArr;":8658,"rAtail;":10524,"rBarr;":10511,"rHar;":10596,"race;":[8765,817],"racute;":341,"radic;":8730,"raemptyv;":10675,"rang;":10217,"rangd;":10642,"range;":10661,"rangle;":10217,raquo:187,"raquo;":187,"rarr;":8594,"rarrap;":10613,"rarrb;":8677,"rarrbfs;":10528,"rarrc;":10547,"rarrfs;":10526,"rarrhk;":8618,"rarrlp;":8620,"rarrpl;":10565,"rarrsim;":10612,"rarrtl;":8611,"rarrw;":8605,"ratail;":10522,"ratio;":8758,"rationals;":8474,"rbarr;":10509,"rbbrk;":10099,"rbrace;":125,"rbrack;":93,"rbrke;":10636,"rbrksld;":10638,"rbrkslu;":10640,"rcaron;":345,"rcedil;":343,"rceil;":8969,"rcub;":125,"rcy;":1088,"rdca;":10551,"rdldhar;":10601,"rdquo;":8221,"rdquor;":8221,"rdsh;":8627,"real;":8476,"realine;":8475,"realpart;":8476,"reals;":8477,"rect;":9645,reg:174,"reg;":174,"rfisht;":10621,"rfloor;":8971,"rfr;":[55349,56623],"rhard;":8641,"rharu;":8640,"rharul;":10604,"rho;":961,"rhov;":1009,"rightarrow;":8594,"rightarrowtail;":8611,"rightharpoondown;":8641,"rightharpoonup;":8640,"rightleftarrows;":8644,"rightleftharpoons;":8652,"rightrightarrows;":8649,"rightsquigarrow;":8605,"rightthreetimes;":8908,"ring;":730,"risingdotseq;":8787,"rlarr;":8644,"rlhar;":8652,"rlm;":8207,"rmoust;":9137,"rmoustache;":9137,"rnmid;":10990,"roang;":10221,"roarr;":8702,"robrk;":10215,"ropar;":10630,"ropf;":[55349,56675],"roplus;":10798,"rotimes;":10805,"rpar;":41,"rpargt;":10644,"rppolint;":10770,"rrarr;":8649,"rsaquo;":8250,"rscr;":[55349,56519],"rsh;":8625,"rsqb;":93,"rsquo;":8217,"rsquor;":8217,"rthree;":8908,"rtimes;":8906,"rtri;":9657,"rtrie;":8885,"rtrif;":9656,"rtriltri;":10702,"ruluhar;":10600,"rx;":8478,"sacute;":347,"sbquo;":8218,"sc;":8827,"scE;":10932,"scap;":10936,"scaron;":353,"sccue;":8829,"sce;":10928,"scedil;":351,"scirc;":349,"scnE;":10934,"scnap;":10938,"scnsim;":8937,"scpolint;":10771,"scsim;":8831,"scy;":1089,"sdot;":8901,"sdotb;":8865,"sdote;":10854,"seArr;":8664,"searhk;":10533,"searr;":8600,"searrow;":8600,sect:167,"sect;":167,"semi;":59,"seswar;":10537,"setminus;":8726,"setmn;":8726,"sext;":10038,"sfr;":[55349,56624],"sfrown;":8994,"sharp;":9839,"shchcy;":1097,"shcy;":1096,"shortmid;":8739,"shortparallel;":8741,shy:173,"shy;":173,"sigma;":963,"sigmaf;":962,"sigmav;":962,"sim;":8764,"simdot;":10858,"sime;":8771,"simeq;":8771,"simg;":10910,"simgE;":10912,"siml;":10909,"simlE;":10911,"simne;":8774,"simplus;":10788,"simrarr;":10610,"slarr;":8592,"smallsetminus;":8726,"smashp;":10803,"smeparsl;":10724,"smid;":8739,"smile;":8995,"smt;":10922,"smte;":10924,"smtes;":[10924,65024],"softcy;":1100,"sol;":47,"solb;":10692,"solbar;":9023,"sopf;":[55349,56676],"spades;":9824,"spadesuit;":9824,"spar;":8741,"sqcap;":8851,"sqcaps;":[8851,65024],"sqcup;":8852,"sqcups;":[8852,65024],"sqsub;":8847,"sqsube;":8849,"sqsubset;":8847,"sqsubseteq;":8849,"sqsup;":8848,"sqsupe;":8850,"sqsupset;":8848,"sqsupseteq;":8850,"squ;":9633,"square;":9633,"squarf;":9642,"squf;":9642,"srarr;":8594,"sscr;":[55349,56520],"ssetmn;":8726,"ssmile;":8995,"sstarf;":8902,"star;":9734,"starf;":9733,"straightepsilon;":1013,"straightphi;":981,"strns;":175,"sub;":8834,"subE;":10949,"subdot;":10941,"sube;":8838,"subedot;":10947,"submult;":10945,"subnE;":10955,"subne;":8842,"subplus;":10943,"subrarr;":10617,"subset;":8834,"subseteq;":8838,"subseteqq;":10949,"subsetneq;":8842,"subsetneqq;":10955,"subsim;":10951,"subsub;":10965,"subsup;":10963,"succ;":8827,"succapprox;":10936,"succcurlyeq;":8829,"succeq;":10928,"succnapprox;":10938,"succneqq;":10934,"succnsim;":8937,"succsim;":8831,"sum;":8721,"sung;":9834,sup1:185,"sup1;":185,sup2:178,"sup2;":178,sup3:179,"sup3;":179,"sup;":8835,"supE;":10950,"supdot;":10942,"supdsub;":10968,"supe;":8839,"supedot;":10948,"suphsol;":10185,"suphsub;":10967,"suplarr;":10619,"supmult;":10946,"supnE;":10956,"supne;":8843,"supplus;":10944,"supset;":8835,"supseteq;":8839,"supseteqq;":10950,"supsetneq;":8843,"supsetneqq;":10956,"supsim;":10952,"supsub;":10964,"supsup;":10966,"swArr;":8665,"swarhk;":10534,"swarr;":8601,"swarrow;":8601,"swnwar;":10538,szlig:223,"szlig;":223,"target;":8982,"tau;":964,"tbrk;":9140,"tcaron;":357,"tcedil;":355,"tcy;":1090,"tdot;":8411,"telrec;":8981,"tfr;":[55349,56625],"there4;":8756,"therefore;":8756,"theta;":952,"thetasym;":977,"thetav;":977,"thickapprox;":8776,"thicksim;":8764,"thinsp;":8201,"thkap;":8776,"thksim;":8764,thorn:254,"thorn;":254,"tilde;":732,times:215,"times;":215,"timesb;":8864,"timesbar;":10801,"timesd;":10800,"tint;":8749,"toea;":10536,"top;":8868,"topbot;":9014,"topcir;":10993,"topf;":[55349,56677],"topfork;":10970,"tosa;":10537,"tprime;":8244,"trade;":8482,"triangle;":9653,"triangledown;":9663,"triangleleft;":9667,"trianglelefteq;":8884,"triangleq;":8796,"triangleright;":9657,"trianglerighteq;":8885,"tridot;":9708,"trie;":8796,"triminus;":10810,"triplus;":10809,"trisb;":10701,"tritime;":10811,"trpezium;":9186,"tscr;":[55349,56521],"tscy;":1094,"tshcy;":1115,"tstrok;":359,"twixt;":8812,"twoheadleftarrow;":8606,"twoheadrightarrow;":8608,"uArr;":8657,"uHar;":10595,uacute:250,"uacute;":250,"uarr;":8593,"ubrcy;":1118,"ubreve;":365,ucirc:251,"ucirc;":251,"ucy;":1091,"udarr;":8645,"udblac;":369,"udhar;":10606,"ufisht;":10622,"ufr;":[55349,56626],ugrave:249,"ugrave;":249,"uharl;":8639,"uharr;":8638,"uhblk;":9600,"ulcorn;":8988,"ulcorner;":8988,"ulcrop;":8975,"ultri;":9720,"umacr;":363,uml:168,"uml;":168,"uogon;":371,"uopf;":[55349,56678],"uparrow;":8593,"updownarrow;":8597,"upharpoonleft;":8639,"upharpoonright;":8638,"uplus;":8846,"upsi;":965,"upsih;":978,"upsilon;":965,"upuparrows;":8648,"urcorn;":8989,"urcorner;":8989,"urcrop;":8974,"uring;":367,"urtri;":9721,"uscr;":[55349,56522],"utdot;":8944,"utilde;":361,"utri;":9653,"utrif;":9652,"uuarr;":8648,uuml:252,"uuml;":252,"uwangle;":10663,"vArr;":8661,"vBar;":10984,"vBarv;":10985,"vDash;":8872,"vangrt;":10652,"varepsilon;":1013,"varkappa;":1008,"varnothing;":8709,"varphi;":981,"varpi;":982,"varpropto;":8733,"varr;":8597,"varrho;":1009,"varsigma;":962,"varsubsetneq;":[8842,65024],"varsubsetneqq;":[10955,65024],"varsupsetneq;":[8843,65024],"varsupsetneqq;":[10956,65024],"vartheta;":977,"vartriangleleft;":8882,"vartriangleright;":8883,"vcy;":1074,"vdash;":8866,"vee;":8744,"veebar;":8891,"veeeq;":8794,"vellip;":8942,"verbar;":124,"vert;":124,"vfr;":[55349,56627],"vltri;":8882,"vnsub;":[8834,8402],"vnsup;":[8835,8402],"vopf;":[55349,56679],"vprop;":8733,"vrtri;":8883,"vscr;":[55349,56523],"vsubnE;":[10955,65024],"vsubne;":[8842,65024],"vsupnE;":[10956,65024],"vsupne;":[8843,65024],"vzigzag;":10650,"wcirc;":373,"wedbar;":10847,"wedge;":8743,"wedgeq;":8793,"weierp;":8472,"wfr;":[55349,56628],"wopf;":[55349,56680],"wp;":8472,"wr;":8768,"wreath;":8768,"wscr;":[55349,56524],"xcap;":8898,"xcirc;":9711,"xcup;":8899,"xdtri;":9661,"xfr;":[55349,56629],"xhArr;":10234,"xharr;":10231,"xi;":958,"xlArr;":10232,"xlarr;":10229,"xmap;":10236,"xnis;":8955,"xodot;":10752,"xopf;":[55349,56681],"xoplus;":10753,"xotime;":10754,"xrArr;":10233,"xrarr;":10230,"xscr;":[55349,56525],"xsqcup;":10758,"xuplus;":10756,"xutri;":9651,"xvee;":8897,"xwedge;":8896,yacute:253,"yacute;":253,"yacy;":1103,"ycirc;":375,"ycy;":1099,yen:165,"yen;":165,"yfr;":[55349,56630],"yicy;":1111,"yopf;":[55349,56682],"yscr;":[55349,56526],"yucy;":1102,yuml:255,"yuml;":255,"zacute;":378,"zcaron;":382,"zcy;":1079,"zdot;":380,"zeetrf;":8488,"zeta;":950,"zfr;":[55349,56631],"zhcy;":1078,"zigrarr;":8669,"zopf;":[55349,56683],"zscr;":[55349,56527],"zwj;":8205,"zwnj;":8204},RO0=/(A(?:Elig;?|MP;?|acute;?|breve;|c(?:irc;?|y;)|fr;|grave;?|lpha;|macr;|nd;|o(?:gon;|pf;)|pplyFunction;|ring;?|s(?:cr;|sign;)|tilde;?|uml;?)|B(?:a(?:ckslash;|r(?:v;|wed;))|cy;|e(?:cause;|rnoullis;|ta;)|fr;|opf;|reve;|scr;|umpeq;)|C(?:Hcy;|OPY;?|a(?:cute;|p(?:;|italDifferentialD;)|yleys;)|c(?:aron;|edil;?|irc;|onint;)|dot;|e(?:dilla;|nterDot;)|fr;|hi;|ircle(?:Dot;|Minus;|Plus;|Times;)|lo(?:ckwiseContourIntegral;|seCurly(?:DoubleQuote;|Quote;))|o(?:lon(?:;|e;)|n(?:gruent;|int;|tourIntegral;)|p(?:f;|roduct;)|unterClockwiseContourIntegral;)|ross;|scr;|up(?:;|Cap;))|D(?:D(?:;|otrahd;)|Jcy;|Scy;|Zcy;|a(?:gger;|rr;|shv;)|c(?:aron;|y;)|el(?:;|ta;)|fr;|i(?:a(?:critical(?:Acute;|Do(?:t;|ubleAcute;)|Grave;|Tilde;)|mond;)|fferentialD;)|o(?:pf;|t(?:;|Dot;|Equal;)|uble(?:ContourIntegral;|Do(?:t;|wnArrow;)|L(?:eft(?:Arrow;|RightArrow;|Tee;)|ong(?:Left(?:Arrow;|RightArrow;)|RightArrow;))|Right(?:Arrow;|Tee;)|Up(?:Arrow;|DownArrow;)|VerticalBar;)|wn(?:Arrow(?:;|Bar;|UpArrow;)|Breve;|Left(?:RightVector;|TeeVector;|Vector(?:;|Bar;))|Right(?:TeeVector;|Vector(?:;|Bar;))|Tee(?:;|Arrow;)|arrow;))|s(?:cr;|trok;))|E(?:NG;|TH;?|acute;?|c(?:aron;|irc;?|y;)|dot;|fr;|grave;?|lement;|m(?:acr;|pty(?:SmallSquare;|VerySmallSquare;))|o(?:gon;|pf;)|psilon;|qu(?:al(?:;|Tilde;)|ilibrium;)|s(?:cr;|im;)|ta;|uml;?|x(?:ists;|ponentialE;))|F(?:cy;|fr;|illed(?:SmallSquare;|VerySmallSquare;)|o(?:pf;|rAll;|uriertrf;)|scr;)|G(?:Jcy;|T;?|amma(?:;|d;)|breve;|c(?:edil;|irc;|y;)|dot;|fr;|g;|opf;|reater(?:Equal(?:;|Less;)|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;)|scr;|t;)|H(?:ARDcy;|a(?:cek;|t;)|circ;|fr;|ilbertSpace;|o(?:pf;|rizontalLine;)|s(?:cr;|trok;)|ump(?:DownHump;|Equal;))|I(?:Ecy;|Jlig;|Ocy;|acute;?|c(?:irc;?|y;)|dot;|fr;|grave;?|m(?:;|a(?:cr;|ginaryI;)|plies;)|n(?:t(?:;|e(?:gral;|rsection;))|visible(?:Comma;|Times;))|o(?:gon;|pf;|ta;)|scr;|tilde;|u(?:kcy;|ml;?))|J(?:c(?:irc;|y;)|fr;|opf;|s(?:cr;|ercy;)|ukcy;)|K(?:Hcy;|Jcy;|appa;|c(?:edil;|y;)|fr;|opf;|scr;)|L(?:Jcy;|T;?|a(?:cute;|mbda;|ng;|placetrf;|rr;)|c(?:aron;|edil;|y;)|e(?:ft(?:A(?:ngleBracket;|rrow(?:;|Bar;|RightArrow;))|Ceiling;|Do(?:ubleBracket;|wn(?:TeeVector;|Vector(?:;|Bar;)))|Floor;|Right(?:Arrow;|Vector;)|T(?:ee(?:;|Arrow;|Vector;)|riangle(?:;|Bar;|Equal;))|Up(?:DownVector;|TeeVector;|Vector(?:;|Bar;))|Vector(?:;|Bar;)|arrow;|rightarrow;)|ss(?:EqualGreater;|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;))|fr;|l(?:;|eftarrow;)|midot;|o(?:ng(?:Left(?:Arrow;|RightArrow;)|RightArrow;|left(?:arrow;|rightarrow;)|rightarrow;)|pf;|wer(?:LeftArrow;|RightArrow;))|s(?:cr;|h;|trok;)|t;)|M(?:ap;|cy;|e(?:diumSpace;|llintrf;)|fr;|inusPlus;|opf;|scr;|u;)|N(?:Jcy;|acute;|c(?:aron;|edil;|y;)|e(?:gative(?:MediumSpace;|Thi(?:ckSpace;|nSpace;)|VeryThinSpace;)|sted(?:GreaterGreater;|LessLess;)|wLine;)|fr;|o(?:Break;|nBreakingSpace;|pf;|t(?:;|C(?:ongruent;|upCap;)|DoubleVerticalBar;|E(?:lement;|qual(?:;|Tilde;)|xists;)|Greater(?:;|Equal;|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;)|Hump(?:DownHump;|Equal;)|Le(?:ftTriangle(?:;|Bar;|Equal;)|ss(?:;|Equal;|Greater;|Less;|SlantEqual;|Tilde;))|Nested(?:GreaterGreater;|LessLess;)|Precedes(?:;|Equal;|SlantEqual;)|R(?:everseElement;|ightTriangle(?:;|Bar;|Equal;))|S(?:quareSu(?:bset(?:;|Equal;)|perset(?:;|Equal;))|u(?:bset(?:;|Equal;)|cceeds(?:;|Equal;|SlantEqual;|Tilde;)|perset(?:;|Equal;)))|Tilde(?:;|Equal;|FullEqual;|Tilde;)|VerticalBar;))|scr;|tilde;?|u;)|O(?:Elig;|acute;?|c(?:irc;?|y;)|dblac;|fr;|grave;?|m(?:acr;|ega;|icron;)|opf;|penCurly(?:DoubleQuote;|Quote;)|r;|s(?:cr;|lash;?)|ti(?:lde;?|mes;)|uml;?|ver(?:B(?:ar;|rac(?:e;|ket;))|Parenthesis;))|P(?:artialD;|cy;|fr;|hi;|i;|lusMinus;|o(?:incareplane;|pf;)|r(?:;|ecedes(?:;|Equal;|SlantEqual;|Tilde;)|ime;|o(?:duct;|portion(?:;|al;)))|s(?:cr;|i;))|Q(?:UOT;?|fr;|opf;|scr;)|R(?:Barr;|EG;?|a(?:cute;|ng;|rr(?:;|tl;))|c(?:aron;|edil;|y;)|e(?:;|verse(?:E(?:lement;|quilibrium;)|UpEquilibrium;))|fr;|ho;|ight(?:A(?:ngleBracket;|rrow(?:;|Bar;|LeftArrow;))|Ceiling;|Do(?:ubleBracket;|wn(?:TeeVector;|Vector(?:;|Bar;)))|Floor;|T(?:ee(?:;|Arrow;|Vector;)|riangle(?:;|Bar;|Equal;))|Up(?:DownVector;|TeeVector;|Vector(?:;|Bar;))|Vector(?:;|Bar;)|arrow;)|o(?:pf;|undImplies;)|rightarrow;|s(?:cr;|h;)|uleDelayed;)|S(?:H(?:CHcy;|cy;)|OFTcy;|acute;|c(?:;|aron;|edil;|irc;|y;)|fr;|hort(?:DownArrow;|LeftArrow;|RightArrow;|UpArrow;)|igma;|mallCircle;|opf;|q(?:rt;|uare(?:;|Intersection;|Su(?:bset(?:;|Equal;)|perset(?:;|Equal;))|Union;))|scr;|tar;|u(?:b(?:;|set(?:;|Equal;))|c(?:ceeds(?:;|Equal;|SlantEqual;|Tilde;)|hThat;)|m;|p(?:;|erset(?:;|Equal;)|set;)))|T(?:HORN;?|RADE;|S(?:Hcy;|cy;)|a(?:b;|u;)|c(?:aron;|edil;|y;)|fr;|h(?:e(?:refore;|ta;)|i(?:ckSpace;|nSpace;))|ilde(?:;|Equal;|FullEqual;|Tilde;)|opf;|ripleDot;|s(?:cr;|trok;))|U(?:a(?:cute;?|rr(?:;|ocir;))|br(?:cy;|eve;)|c(?:irc;?|y;)|dblac;|fr;|grave;?|macr;|n(?:der(?:B(?:ar;|rac(?:e;|ket;))|Parenthesis;)|ion(?:;|Plus;))|o(?:gon;|pf;)|p(?:Arrow(?:;|Bar;|DownArrow;)|DownArrow;|Equilibrium;|Tee(?:;|Arrow;)|arrow;|downarrow;|per(?:LeftArrow;|RightArrow;)|si(?:;|lon;))|ring;|scr;|tilde;|uml;?)|V(?:Dash;|bar;|cy;|dash(?:;|l;)|e(?:e;|r(?:bar;|t(?:;|ical(?:Bar;|Line;|Separator;|Tilde;))|yThinSpace;))|fr;|opf;|scr;|vdash;)|W(?:circ;|edge;|fr;|opf;|scr;)|X(?:fr;|i;|opf;|scr;)|Y(?:Acy;|Icy;|Ucy;|acute;?|c(?:irc;|y;)|fr;|opf;|scr;|uml;)|Z(?:Hcy;|acute;|c(?:aron;|y;)|dot;|e(?:roWidthSpace;|ta;)|fr;|opf;|scr;)|a(?:acute;?|breve;|c(?:;|E;|d;|irc;?|ute;?|y;)|elig;?|f(?:;|r;)|grave;?|l(?:e(?:fsym;|ph;)|pha;)|m(?:a(?:cr;|lg;)|p;?)|n(?:d(?:;|and;|d;|slope;|v;)|g(?:;|e;|le;|msd(?:;|a(?:a;|b;|c;|d;|e;|f;|g;|h;))|rt(?:;|vb(?:;|d;))|s(?:ph;|t;)|zarr;))|o(?:gon;|pf;)|p(?:;|E;|acir;|e;|id;|os;|prox(?:;|eq;))|ring;?|s(?:cr;|t;|ymp(?:;|eq;))|tilde;?|uml;?|w(?:conint;|int;))|b(?:Not;|a(?:ck(?:cong;|epsilon;|prime;|sim(?:;|eq;))|r(?:vee;|wed(?:;|ge;)))|brk(?:;|tbrk;)|c(?:ong;|y;)|dquo;|e(?:caus(?:;|e;)|mptyv;|psi;|rnou;|t(?:a;|h;|ween;))|fr;|ig(?:c(?:ap;|irc;|up;)|o(?:dot;|plus;|times;)|s(?:qcup;|tar;)|triangle(?:down;|up;)|uplus;|vee;|wedge;)|karow;|l(?:a(?:ck(?:lozenge;|square;|triangle(?:;|down;|left;|right;))|nk;)|k(?:1(?:2;|4;)|34;)|ock;)|n(?:e(?:;|quiv;)|ot;)|o(?:pf;|t(?:;|tom;)|wtie;|x(?:D(?:L;|R;|l;|r;)|H(?:;|D;|U;|d;|u;)|U(?:L;|R;|l;|r;)|V(?:;|H;|L;|R;|h;|l;|r;)|box;|d(?:L;|R;|l;|r;)|h(?:;|D;|U;|d;|u;)|minus;|plus;|times;|u(?:L;|R;|l;|r;)|v(?:;|H;|L;|R;|h;|l;|r;)))|prime;|r(?:eve;|vbar;?)|s(?:cr;|emi;|im(?:;|e;)|ol(?:;|b;|hsub;))|u(?:ll(?:;|et;)|mp(?:;|E;|e(?:;|q;))))|c(?:a(?:cute;|p(?:;|and;|brcup;|c(?:ap;|up;)|dot;|s;)|r(?:et;|on;))|c(?:a(?:ps;|ron;)|edil;?|irc;|ups(?:;|sm;))|dot;|e(?:dil;?|mptyv;|nt(?:;|erdot;|))|fr;|h(?:cy;|eck(?:;|mark;)|i;)|ir(?:;|E;|c(?:;|eq;|le(?:arrow(?:left;|right;)|d(?:R;|S;|ast;|circ;|dash;)))|e;|fnint;|mid;|scir;)|lubs(?:;|uit;)|o(?:lon(?:;|e(?:;|q;))|m(?:ma(?:;|t;)|p(?:;|fn;|le(?:ment;|xes;)))|n(?:g(?:;|dot;)|int;)|p(?:f;|rod;|y(?:;|sr;|)))|r(?:arr;|oss;)|s(?:cr;|u(?:b(?:;|e;)|p(?:;|e;)))|tdot;|u(?:darr(?:l;|r;)|e(?:pr;|sc;)|larr(?:;|p;)|p(?:;|brcap;|c(?:ap;|up;)|dot;|or;|s;)|r(?:arr(?:;|m;)|ly(?:eq(?:prec;|succ;)|vee;|wedge;)|ren;?|vearrow(?:left;|right;))|vee;|wed;)|w(?:conint;|int;)|ylcty;)|d(?:Arr;|Har;|a(?:gger;|leth;|rr;|sh(?:;|v;))|b(?:karow;|lac;)|c(?:aron;|y;)|d(?:;|a(?:gger;|rr;)|otseq;)|e(?:g;?|lta;|mptyv;)|f(?:isht;|r;)|har(?:l;|r;)|i(?:am(?:;|ond(?:;|suit;)|s;)|e;|gamma;|sin;|v(?:;|ide(?:;|ontimes;|)|onx;))|jcy;|lc(?:orn;|rop;)|o(?:llar;|pf;|t(?:;|eq(?:;|dot;)|minus;|plus;|square;)|ublebarwedge;|wn(?:arrow;|downarrows;|harpoon(?:left;|right;)))|r(?:bkarow;|c(?:orn;|rop;))|s(?:c(?:r;|y;)|ol;|trok;)|t(?:dot;|ri(?:;|f;))|u(?:arr;|har;)|wangle;|z(?:cy;|igrarr;))|e(?:D(?:Dot;|ot;)|a(?:cute;?|ster;)|c(?:aron;|ir(?:;|c;?)|olon;|y;)|dot;|e;|f(?:Dot;|r;)|g(?:;|rave;?|s(?:;|dot;))|l(?:;|inters;|l;|s(?:;|dot;))|m(?:acr;|pty(?:;|set;|v;)|sp(?:1(?:3;|4;)|;))|n(?:g;|sp;)|o(?:gon;|pf;)|p(?:ar(?:;|sl;)|lus;|si(?:;|lon;|v;))|q(?:c(?:irc;|olon;)|s(?:im;|lant(?:gtr;|less;))|u(?:als;|est;|iv(?:;|DD;))|vparsl;)|r(?:Dot;|arr;)|s(?:cr;|dot;|im;)|t(?:a;|h;?)|u(?:ml;?|ro;)|x(?:cl;|ist;|p(?:ectation;|onentiale;)))|f(?:allingdotseq;|cy;|emale;|f(?:ilig;|l(?:ig;|lig;)|r;)|ilig;|jlig;|l(?:at;|lig;|tns;)|nof;|o(?:pf;|r(?:all;|k(?:;|v;)))|partint;|r(?:a(?:c(?:1(?:2;?|3;|4;?|5;|6;|8;)|2(?:3;|5;)|3(?:4;?|5;|8;)|45;|5(?:6;|8;)|78;)|sl;)|own;)|scr;)|g(?:E(?:;|l;)|a(?:cute;|mma(?:;|d;)|p;)|breve;|c(?:irc;|y;)|dot;|e(?:;|l;|q(?:;|q;|slant;)|s(?:;|cc;|dot(?:;|o(?:;|l;))|l(?:;|es;)))|fr;|g(?:;|g;)|imel;|jcy;|l(?:;|E;|a;|j;)|n(?:E;|ap(?:;|prox;)|e(?:;|q(?:;|q;))|sim;)|opf;|rave;|s(?:cr;|im(?:;|e;|l;))|t(?:;|c(?:c;|ir;)|dot;|lPar;|quest;|r(?:a(?:pprox;|rr;)|dot;|eq(?:less;|qless;)|less;|sim;)|)|v(?:ertneqq;|nE;))|h(?:Arr;|a(?:irsp;|lf;|milt;|r(?:dcy;|r(?:;|cir;|w;)))|bar;|circ;|e(?:arts(?:;|uit;)|llip;|rcon;)|fr;|ks(?:earow;|warow;)|o(?:arr;|mtht;|ok(?:leftarrow;|rightarrow;)|pf;|rbar;)|s(?:cr;|lash;|trok;)|y(?:bull;|phen;))|i(?:acute;?|c(?:;|irc;?|y;)|e(?:cy;|xcl;?)|f(?:f;|r;)|grave;?|i(?:;|i(?:int;|nt;)|nfin;|ota;)|jlig;|m(?:a(?:cr;|g(?:e;|line;|part;)|th;)|of;|ped;)|n(?:;|care;|fin(?:;|tie;)|odot;|t(?:;|cal;|e(?:gers;|rcal;)|larhk;|prod;))|o(?:cy;|gon;|pf;|ta;)|prod;|quest;?|s(?:cr;|in(?:;|E;|dot;|s(?:;|v;)|v;))|t(?:;|ilde;)|u(?:kcy;|ml;?))|j(?:c(?:irc;|y;)|fr;|math;|opf;|s(?:cr;|ercy;)|ukcy;)|k(?:appa(?:;|v;)|c(?:edil;|y;)|fr;|green;|hcy;|jcy;|opf;|scr;)|l(?:A(?:arr;|rr;|tail;)|Barr;|E(?:;|g;)|Har;|a(?:cute;|emptyv;|gran;|mbda;|ng(?:;|d;|le;)|p;|quo;?|rr(?:;|b(?:;|fs;)|fs;|hk;|lp;|pl;|sim;|tl;)|t(?:;|ail;|e(?:;|s;)))|b(?:arr;|brk;|r(?:ac(?:e;|k;)|k(?:e;|sl(?:d;|u;))))|c(?:aron;|e(?:dil;|il;)|ub;|y;)|d(?:ca;|quo(?:;|r;)|r(?:dhar;|ushar;)|sh;)|e(?:;|ft(?:arrow(?:;|tail;)|harpoon(?:down;|up;)|leftarrows;|right(?:arrow(?:;|s;)|harpoons;|squigarrow;)|threetimes;)|g;|q(?:;|q;|slant;)|s(?:;|cc;|dot(?:;|o(?:;|r;))|g(?:;|es;)|s(?:approx;|dot;|eq(?:gtr;|qgtr;)|gtr;|sim;)))|f(?:isht;|loor;|r;)|g(?:;|E;)|h(?:ar(?:d;|u(?:;|l;))|blk;)|jcy;|l(?:;|arr;|corner;|hard;|tri;)|m(?:idot;|oust(?:;|ache;))|n(?:E;|ap(?:;|prox;)|e(?:;|q(?:;|q;))|sim;)|o(?:a(?:ng;|rr;)|brk;|ng(?:left(?:arrow;|rightarrow;)|mapsto;|rightarrow;)|oparrow(?:left;|right;)|p(?:ar;|f;|lus;)|times;|w(?:ast;|bar;)|z(?:;|enge;|f;))|par(?:;|lt;)|r(?:arr;|corner;|har(?:;|d;)|m;|tri;)|s(?:aquo;|cr;|h;|im(?:;|e;|g;)|q(?:b;|uo(?:;|r;))|trok;)|t(?:;|c(?:c;|ir;)|dot;|hree;|imes;|larr;|quest;|r(?:Par;|i(?:;|e;|f;))|)|ur(?:dshar;|uhar;)|v(?:ertneqq;|nE;))|m(?:DDot;|a(?:cr;?|l(?:e;|t(?:;|ese;))|p(?:;|sto(?:;|down;|left;|up;))|rker;)|c(?:omma;|y;)|dash;|easuredangle;|fr;|ho;|i(?:cro;?|d(?:;|ast;|cir;|dot;?)|nus(?:;|b;|d(?:;|u;)))|l(?:cp;|dr;)|nplus;|o(?:dels;|pf;)|p;|s(?:cr;|tpos;)|u(?:;|ltimap;|map;))|n(?:G(?:g;|t(?:;|v;))|L(?:eft(?:arrow;|rightarrow;)|l;|t(?:;|v;))|Rightarrow;|V(?:Dash;|dash;)|a(?:bla;|cute;|ng;|p(?:;|E;|id;|os;|prox;)|tur(?:;|al(?:;|s;)))|b(?:sp;?|ump(?:;|e;))|c(?:a(?:p;|ron;)|edil;|ong(?:;|dot;)|up;|y;)|dash;|e(?:;|Arr;|ar(?:hk;|r(?:;|ow;))|dot;|quiv;|s(?:ear;|im;)|xist(?:;|s;))|fr;|g(?:E;|e(?:;|q(?:;|q;|slant;)|s;)|sim;|t(?:;|r;))|h(?:Arr;|arr;|par;)|i(?:;|s(?:;|d;)|v;)|jcy;|l(?:Arr;|E;|arr;|dr;|e(?:;|ft(?:arrow;|rightarrow;)|q(?:;|q;|slant;)|s(?:;|s;))|sim;|t(?:;|ri(?:;|e;)))|mid;|o(?:pf;|t(?:;|in(?:;|E;|dot;|v(?:a;|b;|c;))|ni(?:;|v(?:a;|b;|c;))|))|p(?:ar(?:;|allel;|sl;|t;)|olint;|r(?:;|cue;|e(?:;|c(?:;|eq;))))|r(?:Arr;|arr(?:;|c;|w;)|ightarrow;|tri(?:;|e;))|s(?:c(?:;|cue;|e;|r;)|hort(?:mid;|parallel;)|im(?:;|e(?:;|q;))|mid;|par;|qsu(?:be;|pe;)|u(?:b(?:;|E;|e;|set(?:;|eq(?:;|q;)))|cc(?:;|eq;)|p(?:;|E;|e;|set(?:;|eq(?:;|q;)))))|t(?:gl;|ilde;?|lg;|riangle(?:left(?:;|eq;)|right(?:;|eq;)))|u(?:;|m(?:;|ero;|sp;))|v(?:Dash;|Harr;|ap;|dash;|g(?:e;|t;)|infin;|l(?:Arr;|e;|t(?:;|rie;))|r(?:Arr;|trie;)|sim;)|w(?:Arr;|ar(?:hk;|r(?:;|ow;))|near;))|o(?:S;|a(?:cute;?|st;)|c(?:ir(?:;|c;?)|y;)|d(?:ash;|blac;|iv;|ot;|sold;)|elig;|f(?:cir;|r;)|g(?:on;|rave;?|t;)|h(?:bar;|m;)|int;|l(?:arr;|c(?:ir;|ross;)|ine;|t;)|m(?:acr;|ega;|i(?:cron;|d;|nus;))|opf;|p(?:ar;|erp;|lus;)|r(?:;|arr;|d(?:;|er(?:;|of;)|f;?|m;?)|igof;|or;|slope;|v;)|s(?:cr;|lash;?|ol;)|ti(?:lde;?|mes(?:;|as;))|uml;?|vbar;)|p(?:ar(?:;|a(?:;|llel;|)|s(?:im;|l;)|t;)|cy;|er(?:cnt;|iod;|mil;|p;|tenk;)|fr;|h(?:i(?:;|v;)|mmat;|one;)|i(?:;|tchfork;|v;)|l(?:an(?:ck(?:;|h;)|kv;)|us(?:;|acir;|b;|cir;|d(?:o;|u;)|e;|mn;?|sim;|two;))|m;|o(?:intint;|pf;|und;?)|r(?:;|E;|ap;|cue;|e(?:;|c(?:;|approx;|curlyeq;|eq;|n(?:approx;|eqq;|sim;)|sim;))|ime(?:;|s;)|n(?:E;|ap;|sim;)|o(?:d;|f(?:alar;|line;|surf;)|p(?:;|to;))|sim;|urel;)|s(?:cr;|i;)|uncsp;)|q(?:fr;|int;|opf;|prime;|scr;|u(?:at(?:ernions;|int;)|est(?:;|eq;)|ot;?))|r(?:A(?:arr;|rr;|tail;)|Barr;|Har;|a(?:c(?:e;|ute;)|dic;|emptyv;|ng(?:;|d;|e;|le;)|quo;?|rr(?:;|ap;|b(?:;|fs;)|c;|fs;|hk;|lp;|pl;|sim;|tl;|w;)|t(?:ail;|io(?:;|nals;)))|b(?:arr;|brk;|r(?:ac(?:e;|k;)|k(?:e;|sl(?:d;|u;))))|c(?:aron;|e(?:dil;|il;)|ub;|y;)|d(?:ca;|ldhar;|quo(?:;|r;)|sh;)|e(?:al(?:;|ine;|part;|s;)|ct;|g;?)|f(?:isht;|loor;|r;)|h(?:ar(?:d;|u(?:;|l;))|o(?:;|v;))|i(?:ght(?:arrow(?:;|tail;)|harpoon(?:down;|up;)|left(?:arrows;|harpoons;)|rightarrows;|squigarrow;|threetimes;)|ng;|singdotseq;)|l(?:arr;|har;|m;)|moust(?:;|ache;)|nmid;|o(?:a(?:ng;|rr;)|brk;|p(?:ar;|f;|lus;)|times;)|p(?:ar(?:;|gt;)|polint;)|rarr;|s(?:aquo;|cr;|h;|q(?:b;|uo(?:;|r;)))|t(?:hree;|imes;|ri(?:;|e;|f;|ltri;))|uluhar;|x;)|s(?:acute;|bquo;|c(?:;|E;|a(?:p;|ron;)|cue;|e(?:;|dil;)|irc;|n(?:E;|ap;|sim;)|polint;|sim;|y;)|dot(?:;|b;|e;)|e(?:Arr;|ar(?:hk;|r(?:;|ow;))|ct;?|mi;|swar;|tm(?:inus;|n;)|xt;)|fr(?:;|own;)|h(?:arp;|c(?:hcy;|y;)|ort(?:mid;|parallel;)|y;?)|i(?:gma(?:;|f;|v;)|m(?:;|dot;|e(?:;|q;)|g(?:;|E;)|l(?:;|E;)|ne;|plus;|rarr;))|larr;|m(?:a(?:llsetminus;|shp;)|eparsl;|i(?:d;|le;)|t(?:;|e(?:;|s;)))|o(?:ftcy;|l(?:;|b(?:;|ar;))|pf;)|pa(?:des(?:;|uit;)|r;)|q(?:c(?:ap(?:;|s;)|up(?:;|s;))|su(?:b(?:;|e;|set(?:;|eq;))|p(?:;|e;|set(?:;|eq;)))|u(?:;|ar(?:e;|f;)|f;))|rarr;|s(?:cr;|etmn;|mile;|tarf;)|t(?:ar(?:;|f;)|r(?:aight(?:epsilon;|phi;)|ns;))|u(?:b(?:;|E;|dot;|e(?:;|dot;)|mult;|n(?:E;|e;)|plus;|rarr;|s(?:et(?:;|eq(?:;|q;)|neq(?:;|q;))|im;|u(?:b;|p;)))|cc(?:;|approx;|curlyeq;|eq;|n(?:approx;|eqq;|sim;)|sim;)|m;|ng;|p(?:1;?|2;?|3;?|;|E;|d(?:ot;|sub;)|e(?:;|dot;)|hs(?:ol;|ub;)|larr;|mult;|n(?:E;|e;)|plus;|s(?:et(?:;|eq(?:;|q;)|neq(?:;|q;))|im;|u(?:b;|p;))))|w(?:Arr;|ar(?:hk;|r(?:;|ow;))|nwar;)|zlig;?)|t(?:a(?:rget;|u;)|brk;|c(?:aron;|edil;|y;)|dot;|elrec;|fr;|h(?:e(?:re(?:4;|fore;)|ta(?:;|sym;|v;))|i(?:ck(?:approx;|sim;)|nsp;)|k(?:ap;|sim;)|orn;?)|i(?:lde;|mes(?:;|b(?:;|ar;)|d;|)|nt;)|o(?:ea;|p(?:;|bot;|cir;|f(?:;|ork;))|sa;)|prime;|r(?:ade;|i(?:angle(?:;|down;|left(?:;|eq;)|q;|right(?:;|eq;))|dot;|e;|minus;|plus;|sb;|time;)|pezium;)|s(?:c(?:r;|y;)|hcy;|trok;)|w(?:ixt;|ohead(?:leftarrow;|rightarrow;)))|u(?:Arr;|Har;|a(?:cute;?|rr;)|br(?:cy;|eve;)|c(?:irc;?|y;)|d(?:arr;|blac;|har;)|f(?:isht;|r;)|grave;?|h(?:ar(?:l;|r;)|blk;)|l(?:c(?:orn(?:;|er;)|rop;)|tri;)|m(?:acr;|l;?)|o(?:gon;|pf;)|p(?:arrow;|downarrow;|harpoon(?:left;|right;)|lus;|si(?:;|h;|lon;)|uparrows;)|r(?:c(?:orn(?:;|er;)|rop;)|ing;|tri;)|scr;|t(?:dot;|ilde;|ri(?:;|f;))|u(?:arr;|ml;?)|wangle;)|v(?:Arr;|Bar(?:;|v;)|Dash;|a(?:ngrt;|r(?:epsilon;|kappa;|nothing;|p(?:hi;|i;|ropto;)|r(?:;|ho;)|s(?:igma;|u(?:bsetneq(?:;|q;)|psetneq(?:;|q;)))|t(?:heta;|riangle(?:left;|right;))))|cy;|dash;|e(?:e(?:;|bar;|eq;)|llip;|r(?:bar;|t;))|fr;|ltri;|nsu(?:b;|p;)|opf;|prop;|rtri;|s(?:cr;|u(?:bn(?:E;|e;)|pn(?:E;|e;)))|zigzag;)|w(?:circ;|e(?:d(?:bar;|ge(?:;|q;))|ierp;)|fr;|opf;|p;|r(?:;|eath;)|scr;)|x(?:c(?:ap;|irc;|up;)|dtri;|fr;|h(?:Arr;|arr;)|i;|l(?:Arr;|arr;)|map;|nis;|o(?:dot;|p(?:f;|lus;)|time;)|r(?:Arr;|arr;)|s(?:cr;|qcup;)|u(?:plus;|tri;)|vee;|wedge;)|y(?:ac(?:ute;?|y;)|c(?:irc;|y;)|en;?|fr;|icy;|opf;|scr;|u(?:cy;|ml;?))|z(?:acute;|c(?:aron;|y;)|dot;|e(?:etrf;|ta;)|fr;|hcy;|igrarr;|opf;|scr;|w(?:j;|nj;)))|[\s\S]/g,o4Q=32,n4Q=/[^\r"&\u0000]+/g,a4Q=/[^\r'&\u0000]+/g,s4Q=/[^\r\t\n\f &>\u0000]+/g,r4Q=/[^\r\t\n\f \/>A-Z\u0000]+/g,t4Q=/[^\r\t\n\f \/=>A-Z\u0000]+/g,e4Q=/[^\]\r\u0000\uffff]*/g,QHQ=/[^&<\r\u0000\uffff]*/g,wO0=/[^<\r\u0000\uffff]*/g,XHQ=/[^\r\u0000\uffff]*/g,EO0=/(?:(\/)?([a-z]+)>)|[\s\S]/g,SO0=/(?:([-a-z]+)[ \t\n\f]*=[ \t\n\f]*('[^'&\r\u0000]*'|"[^"&\r\u0000]*"|[^\t\n\r\f "&'\u0000>][^&> \t\n\r\f\u0000]*[ \t\n\f]))|[\s\S]/g,NC=/[^\x09\x0A\x0C\x0D\x20]/,y80=/[^\x09\x0A\x0C\x0D\x20]/g,JHQ=/[^\x00\x09\x0A\x0C\x0D\x20]/,p3=/^[\x09\x0A\x0C\x0D\x20]+/,jC=/\x00/g;function cX(Q){var J=16384;if(Q.length<J)return String.fromCharCode.apply(String,Q);var G="";for(var H=0;H<Q.length;H+=J)G+=String.fromCharCode.apply(String,Q.slice(H,H+J));return G}function YHQ(Q){var J=[];for(var G=0;G<Q.length;G++)J[G]=Q.charCodeAt(G);return J}function s6(Q,J){if(typeof J==="string")return Q.namespaceURI===O8.HTML&&Q.localName===J;var G=J[Q.namespaceURI];return G&&G[Q.localName]}function TO0(Q){return s6(Q,uO0)}function kO0(Q){if(s6(Q,pO0))return!0;if(Q.namespaceURI===O8.MATHML&&Q.localName==="annotation-xml"){var J=Q.getAttribute("encoding");if(J)J=J.toLowerCase();if(J==="text/html"||J==="application/xhtml+xml")return!0}return!1}function GHQ(Q){if(Q in CO0)return CO0[Q];else return Q}function yO0(Q){for(var J=0,G=Q.length;J<G;J++)if(Q[J][0]in jO0)Q[J][0]=jO0[Q[J][0]]}function vO0(Q){for(var J=0,G=Q.length;J<G;J++)if(Q[J][0]==="definitionurl"){Q[J][0]="definitionURL";break}}function v80(Q){for(var J=0,G=Q.length;J<G;J++)if(Q[J][0]in NO0)Q[J].push(NO0[Q[J][0]])}function xO0(Q,J){for(var G=0,H=Q.length;G<H;G++){var K=Q[G][0],z=Q[G][1];if(J.hasAttribute(K))continue;J._setAttribute(K,z)}}v6.ElementStack=function(){this.elements=[],this.top=null};v6.ElementStack.prototype.push=function(Q){this.elements.push(Q),this.top=Q};v6.ElementStack.prototype.pop=function(Q){this.elements.pop(),this.top=this.elements[this.elements.length-1]};v6.ElementStack.prototype.popTag=function(Q){for(var J=this.elements.length-1;J>0;J--){var G=this.elements[J];if(s6(G,Q))break}this.elements.length=J,this.top=this.elements[J-1]};v6.ElementStack.prototype.popElementType=function(Q){for(var J=this.elements.length-1;J>0;J--)if(this.elements[J]instanceof Q)break;this.elements.length=J,this.top=this.elements[J-1]};v6.ElementStack.prototype.popElement=function(Q){for(var J=this.elements.length-1;J>0;J--)if(this.elements[J]===Q)break;this.elements.length=J,this.top=this.elements[J-1]};v6.ElementStack.prototype.removeElement=function(Q){if(this.top===Q)this.pop();else{var J=this.elements.lastIndexOf(Q);if(J!==-1)this.elements.splice(J,1)}};v6.ElementStack.prototype.clearToContext=function(Q){for(var J=this.elements.length-1;J>0;J--)if(s6(this.elements[J],Q))break;this.elements.length=J+1,this.top=this.elements[J]};v6.ElementStack.prototype.contains=function(Q){return this.inSpecificScope(Q,Object.create(null))};v6.ElementStack.prototype.inSpecificScope=function(Q,J){for(var G=this.elements.length-1;G>=0;G--){var H=this.elements[G];if(s6(H,Q))return!0;if(s6(H,J))return!1}return!1};v6.ElementStack.prototype.elementInSpecificScope=function(Q,J){for(var G=this.elements.length-1;G>=0;G--){var H=this.elements[G];if(H===Q)return!0;if(s6(H,J))return!1}return!1};v6.ElementStack.prototype.elementTypeInSpecificScope=function(Q,J){for(var G=this.elements.length-1;G>=0;G--){var H=this.elements[G];if(H instanceof Q)return!0;if(s6(H,J))return!1}return!1};v6.ElementStack.prototype.inScope=function(Q){return this.inSpecificScope(Q,wW)};v6.ElementStack.prototype.elementInScope=function(Q){return this.elementInSpecificScope(Q,wW)};v6.ElementStack.prototype.elementTypeInScope=function(Q){return this.elementTypeInSpecificScope(Q,wW)};v6.ElementStack.prototype.inButtonScope=function(Q){return this.inSpecificScope(Q,g80)};v6.ElementStack.prototype.inListItemScope=function(Q){return this.inSpecificScope(Q,RC)};v6.ElementStack.prototype.inTableScope=function(Q){return this.inSpecificScope(Q,mO0)};v6.ElementStack.prototype.inSelectScope=function(Q){for(var J=this.elements.length-1;J>=0;J--){var G=this.elements[J];if(G.namespaceURI!==O8.HTML)return!1;var H=G.localName;if(H===Q)return!0;if(H!=="optgroup"&&H!=="option")return!1}return!1};v6.ElementStack.prototype.generateImpliedEndTags=function(Q,J){var G=J?_O0:hO0;for(var H=this.elements.length-1;H>=0;H--){var K=this.elements[H];if(Q&&s6(K,Q))break;if(!s6(this.elements[H],G))break}this.elements.length=H+1,this.top=this.elements[H]};v6.ActiveFormattingElements=function(){this.list=[],this.attrs=[]};v6.ActiveFormattingElements.prototype.MARKER={localName:"|"};v6.ActiveFormattingElements.prototype.insertMarker=function(){this.list.push(this.MARKER),this.attrs.push(this.MARKER)};v6.ActiveFormattingElements.prototype.push=function(Q,J){var G=0;for(var H=this.list.length-1;H>=0;H--){if(this.list[H]===this.MARKER)break;if(q(Q,this.list[H],this.attrs[H])){if(G++,G===3){this.list.splice(H,1),this.attrs.splice(H,1);break}}}this.list.push(Q);var K=[];for(var z=0;z<J.length;z++)K[z]=J[z];this.attrs.push(K);function q(F,D,V){if(F.localName!==D.localName)return!1;if(F._numattrs!==V.length)return!1;for(var O=0,P=V.length;O<P;O++){var N=V[O][0],I=V[O][1];if(!F.hasAttribute(N))return!1;if(F.getAttribute(N)!==I)return!1}return!0}};v6.ActiveFormattingElements.prototype.clearToMarker=function(){for(var Q=this.list.length-1;Q>=0;Q--)if(this.list[Q]===this.MARKER)break;if(Q<0)Q=0;this.list.length=Q,this.attrs.length=Q};v6.ActiveFormattingElements.prototype.findElementByTag=function(Q){for(var J=this.list.length-1;J>=0;J--){var G=this.list[J];if(G===this.MARKER)break;if(G.localName===Q)return G}return null};v6.ActiveFormattingElements.prototype.indexOf=function(Q){return this.list.lastIndexOf(Q)};v6.ActiveFormattingElements.prototype.remove=function(Q){var J=this.list.lastIndexOf(Q);if(J!==-1)this.list.splice(J,1),this.attrs.splice(J,1)};v6.ActiveFormattingElements.prototype.replace=function(Q,J,G){var H=this.list.lastIndexOf(Q);if(H!==-1)this.list[H]=J,this.attrs[H]=G};v6.ActiveFormattingElements.prototype.insertAfter=function(Q,J){var G=this.list.lastIndexOf(Q);if(G!==-1)this.list.splice(G,0,J),this.attrs.splice(G,0,J)};function v6(Q,J,G){var H=null,K=0,z=0,q=!1,F=!1,D=0,V=[],O="",P=!0,N=0,I=$8,R,w,E="",T="",y=[],x="",b="",g=[],l=[],_=[],a=[],r=[],f0=!1,t=GD,p0=null,u0=[],d=new v6.ElementStack,n=new v6.ActiveFormattingElements,c0=J!==void 0,WQ=null,R0=null,l0=!0;if(J)l0=J.ownerDocument._scripting_enabled;if(G&&G.scripting_enabled===!1)l0=!1;var d0=!0,m0=!1,ZQ,LQ,h0=[],pQ=!1,iQ=!1,mQ={document:function(){return AQ},_asDocumentFragment:function(){var u=AQ.createDocumentFragment(),p=AQ.firstChild;while(p.hasChildNodes())u.appendChild(p.firstChild);return u},pause:function(){N++},resume:function(){N--,this.parse("")},parse:function(u,p,Z0){var XQ;if(N>0)return O+=u,!0;if(D===0){if(O)u=O+u,O="";if(p)u+="￿",q=!0;if(H=u,K=u.length,z=0,P){if(P=!1,H.charCodeAt(0)===65279)z=1}D++,XQ=bQ(Z0),O=H.substring(z,K),D--}else{if(D++,V.push(H,K,z),H=u,K=u.length,z=0,bQ(),XQ=!1,O=H.substring(z,K),z=V.pop(),K=V.pop(),H=V.pop(),O)H=O+H.substring(z),K=H.length,z=0,O="";D--}return XQ}},AQ=new _4Q(!0,Q);if(AQ._parser=mQ,AQ._scripting_enabled=l0,J){if(J.ownerDocument._quirks)AQ._quirks=!0;if(J.ownerDocument._limitedQuirks)AQ._limitedQuirks=!0;if(J.namespaceURI===O8.HTML)switch(J.localName){case"title":case"textarea":I=c6;break;case"style":case"xmp":case"iframe":case"noembed":case"noframes":case"script":case"plaintext":I=LY;break}var MQ=AQ.createElement("html");if(AQ._appendChild(MQ),d.push(MQ),J instanceof a6.HTMLTemplateElement)u0.push(eV);x6();for(var DQ=J;DQ!==null;DQ=DQ.parentElement)if(DQ instanceof a6.HTMLFormElement){R0=DQ;break}}function bQ(u){var p,Z0,XQ,KQ;while(z<K){if(N>0||u&&u())return!0;switch(typeof I.lookahead){case"undefined":if(p=H.charCodeAt(z++),F){if(F=!1,p===10){z++;continue}}switch(p){case 13:if(z<K){if(H.charCodeAt(z)===10)z++}else F=!0;I(10);break;case 65535:if(q&&z===K){I(PC);break}default:I(p);break}break;case"number":p=H.charCodeAt(z);var yQ=I.lookahead,L8=!0;if(yQ<0)L8=!1,yQ=-yQ;if(yQ<K-z)Z0=L8?H.substring(z,z+yQ):null,KQ=!1;else if(q){if(Z0=L8?H.substring(z,K):null,KQ=!0,p===65535&&z===K-1)p=PC}else return!0;I(p,Z0,KQ);break;case"string":p=H.charCodeAt(z),XQ=I.lookahead;var Q6=H.indexOf(XQ,z);if(Q6!==-1)Z0=H.substring(z,Q6+XQ.length),KQ=!1;else{if(!q)return!0;if(Z0=H.substring(z,K),p===65535&&z===K-1)p=PC;KQ=!0}I(p,Z0,KQ);break}}return!1}function j8(u,p){for(var Z0=0;Z0<r.length;Z0++)if(r[Z0][0]===u)return;if(p!==void 0)r.push([u,p]);else r.push([u])}function tQ(){SO0.lastIndex=z-1;var u=SO0.exec(H);if(!u)throw Error("should never happen");var p=u[1];if(!p)return!1;var Z0=u[2],XQ=Z0.length;switch(Z0[0]){case'"':case"'":Z0=Z0.substring(1,XQ-1),z+=u[0].length-1,I=nV;break;default:I=O7,z+=u[0].length-1,Z0=Z0.substring(0,XQ-1);break}for(var KQ=0;KQ<r.length;KQ++)if(r[KQ][0]===p)return!0;return r.push([p,Z0]),!0}function K8(){f0=!1,E="",r.length=0}function k8(){f0=!0,E="",r.length=0}function d6(){y.length=0}function r9(){x=""}function H7(){b=""}function LJ(){g.length=0}function OJ(){l.length=0,_=null,a=null}function w7(){_=[]}function QJ(){a=[]}function e8(){m0=!0}function wQ(){return d.top&&d.top.namespaceURI!=="http://www.w3.org/1999/xhtml"}function lQ(u){return T===u}function U8(){if(h0.length>0){var u=cX(h0);if(h0.length=0,iQ){if(iQ=!1,u[0]===`
`)u=u.substring(1);if(u.length===0)return}S6(QV,u),pQ=!1}iQ=!1}function P6(u){u.lastIndex=z-1;var p=u.exec(H);if(p&&p.index===z-1){if(p=p[0],z+=p.length-1,q&&z===K)p=p.slice(0,-1),z--;return p}else throw Error("should never happen")}function N6(u){u.lastIndex=z-1;var p=u.exec(H)[0];if(!p)return!1;return t9(p),z+=p.length-1,!0}function t9(u){if(h0.length>0)U8();if(iQ){if(iQ=!1,u[0]===`
`)u=u.substring(1);if(u.length===0)return}S6(QV,u)}function F8(){if(f0)S6(K6,E);else{var u=E;E="",T=u,S6(dX,u,r)}}function SX(){if(z===K)return!1;EO0.lastIndex=z;var u=EO0.exec(H);if(!u)throw Error("should never happen");var p=u[2];if(!p)return!1;var Z0=u[1];if(Z0)z+=p.length+2,S6(K6,p);else z+=p.length+1,T=p,S6(dX,p,u4Q);return!0}function B7(){if(f0)S6(K6,E,null,!0);else S6(dX,E,r,!0)}function f8(){S6(m4Q,cX(l),_?cX(_):void 0,a?cX(a):void 0)}function D8(){U8(),t(PC),AQ.modclock=1}var S6=mQ.insertToken=function(p,Z0,XQ,KQ){U8();var yQ=d.top;if(!yQ||yQ.namespaceURI===O8.HTML)t(p,Z0,XQ,KQ);else if(p!==dX&&p!==QV)SB(p,Z0,XQ,KQ);else if(TO0(yQ)&&(p===QV||p===dX&&Z0!=="mglyph"&&Z0!=="malignmark")||p===dX&&Z0==="svg"&&yQ.namespaceURI===O8.MATHML&&yQ.localName==="annotation-xml"||kO0(yQ))LQ=!0,t(p,Z0,XQ,KQ),LQ=!1;else SB(p,Z0,XQ,KQ)};function IQ(u){var p=d.top;if(U6&&s6(p,XV))s8(function(Z0){return Z0.createComment(u)});else{if(p instanceof a6.HTMLTemplateElement)p=p.content;p._appendChild(p.ownerDocument.createComment(u))}}function rQ(u){var p=d.top;if(U6&&s6(p,XV))s8(function(XQ){return XQ.createTextNode(u)});else{if(p instanceof a6.HTMLTemplateElement)p=p.content;var Z0=p.lastChild;if(Z0&&Z0.nodeType===k80.TEXT_NODE)Z0.appendData(u);else p._appendChild(p.ownerDocument.createTextNode(u))}}function l8(u,p,Z0){var XQ=bO0.createElement(u,p,null);if(Z0)for(var KQ=0,yQ=Z0.length;KQ<yQ;KQ++)XQ._setAttribute(Z0[KQ][0],Z0[KQ][1]);return XQ}var U6=!1;function G8(u,p){var Z0=e9(function(XQ){return l8(XQ,u,p)});if(s6(Z0,fO0))Z0._form=R0;return Z0}function e9(u){var p;if(U6&&s6(d.top,XV))p=s8(u);else if(d.top instanceof a6.HTMLTemplateElement)p=u(d.top.content.ownerDocument),d.top.content._appendChild(p);else p=u(d.top.ownerDocument),d.top._appendChild(p);return d.push(p),p}function TX(u,p,Z0){return e9(function(XQ){var KQ=XQ._createElementNS(u,Z0,null);if(p)for(var yQ=0,L8=p.length;yQ<L8;yQ++){var Q6=p[yQ];if(Q6.length===2)KQ._setAttribute(Q6[0],Q6[1]);else KQ._setAttributeNS(Q6[2],Q6[0],Q6[1])}return KQ})}function j6(u){for(var p=d.elements.length-1;p>=0;p--)if(d.elements[p]instanceof u)return p;return-1}function s8(u){var p,Z0,XQ=-1,KQ=-1,yQ;if(XQ=j6(a6.HTMLTableElement),KQ=j6(a6.HTMLTemplateElement),KQ>=0&&(XQ<0||KQ>XQ))p=d.elements[KQ];else if(XQ>=0)if(p=d.elements[XQ].parentNode,p)Z0=d.elements[XQ];else p=d.elements[XQ-1];if(!p)p=d.elements[0];if(p instanceof a6.HTMLTemplateElement)p=p.content;if(yQ=u(p.ownerDocument),yQ.nodeType===k80.TEXT_NODE){var L8;if(Z0)L8=Z0.previousSibling;else L8=p.lastChild;if(L8&&L8.nodeType===k80.TEXT_NODE)return L8.appendData(yQ.data),yQ}if(Z0)p.insertBefore(yQ,Z0);else p._appendChild(yQ);return yQ}function x6(){var u=!1;for(var p=d.elements.length-1;p>=0;p--){var Z0=d.elements[p];if(p===0){if(u=!0,c0)Z0=J}if(Z0.namespaceURI===O8.HTML){var XQ=Z0.localName;switch(XQ){case"select":for(var KQ=p;KQ>0;){var yQ=d.elements[--KQ];if(yQ instanceof a6.HTMLTemplateElement)break;else if(yQ instanceof a6.HTMLTableElement){t=oG;return}}t=jY;return;case"tr":t=IH;return;case"tbody":case"tfoot":case"thead":t=mW;return;case"caption":t=EB;return;case"colgroup":t=CH;return;case"table":t=jJ;return;case"template":t=u0[u0.length-1];return;case"body":t=M8;return;case"frameset":t=Xq;return;case"html":if(WQ===null)t=RB;else t=tV;return;default:if(!u){if(XQ==="head"){t=k9;return}if(XQ==="td"||XQ==="th"){t=uW;return}}}}if(u){t=M8;return}}}function t6(u,p){G8(u,p),I=XJ,p0=t,t=wB}function M7(u,p){G8(u,p),I=c6,p0=t,t=wB}function Z9(u,p){return{elt:l8(u,n.list[p].localName,n.attrs[p]),attrs:n.attrs[p]}}function h8(){if(n.list.length===0)return;var u=n.list[n.list.length-1];if(u===n.MARKER)return;if(d.elements.lastIndexOf(u)!==-1)return;for(var p=n.list.length-2;p>=0;p--){if(u=n.list[p],u===n.MARKER)break;if(d.elements.lastIndexOf(u)!==-1)break}for(p=p+1;p<n.list.length;p++){var Z0=e9(function(XQ){return Z9(XQ,p).elt});n.list[p]=Z0}}var F6={localName:"BM"};function L7(u){if(s6(d.top,u)&&n.indexOf(d.top)===-1)return d.pop(),!0;var p=0;while(p<8){p++;var Z0=n.findElementByTag(u);if(!Z0)return!1;var XQ=d.elements.lastIndexOf(Z0);if(XQ===-1)return n.remove(Z0),!0;if(!d.elementInScope(Z0))return!0;var KQ=null,yQ;for(var L8=XQ+1;L8<d.elements.length;L8++)if(s6(d.elements[L8],l3)){KQ=d.elements[L8],yQ=L8;break}if(!KQ)return d.popElement(Z0),n.remove(Z0),!0;else{var Q6=d.elements[XQ-1];n.insertAfter(Z0,F6);var P9=KQ,S7=KQ,i9=yQ,GJ,sJ=0;while(!0){if(sJ++,P9=d.elements[--i9],P9===Z0)break;if(GJ=n.indexOf(P9),sJ>3&&GJ!==-1)n.remove(P9),GJ=-1;if(GJ===-1){d.removeElement(P9);continue}var F9=Z9(Q6.ownerDocument,GJ);if(n.replace(P9,F9.elt,F9.attrs),d.elements[i9]=F9.elt,P9=F9.elt,S7===KQ)n.remove(F6),n.insertAfter(F9.elt,F6);P9._appendChild(S7),S7=P9}if(U6&&s6(Q6,XV))s8(function(){return S7});else if(Q6 instanceof a6.HTMLTemplateElement)Q6.content._appendChild(S7);else Q6._appendChild(S7);var RH=Z9(KQ.ownerDocument,n.indexOf(Z0));while(KQ.hasChildNodes())RH.elt._appendChild(KQ.firstChild);KQ._appendChild(RH.elt),n.remove(Z0),n.replace(F6,RH.elt,RH.attrs),d.removeElement(Z0);var eY=d.elements.lastIndexOf(KQ);d.elements.splice(eY+1,0,RH.elt)}}return!0}function C6(){d.pop(),t=p0;return}function A9(){if(delete AQ._parser,d.elements.length=0,AQ.defaultView)AQ.defaultView.dispatchEvent(new a6.Event("load",{}))}function kQ(u,p){I=p,z--}function $8(u){switch(u){case 38:R=$8,I=jH;break;case 60:if(SX())break;I=sY;break;case 0:h0.push(u),pQ=!0;break;case-1:D8();break;default:N6(QHQ)||h0.push(u);break}}function c6(u){switch(u){case 38:R=c6,I=jH;break;case 60:I=pG;break;case 0:h0.push(65533),pQ=!0;break;case-1:D8();break;default:h0.push(u);break}}function XJ(u){switch(u){case 60:I=JJ;break;case 0:h0.push(65533);break;case-1:D8();break;default:N6(wO0)||h0.push(u);break}}function YX(u){switch(u){case 60:I=rY;break;case 0:h0.push(65533);break;case-1:D8();break;default:N6(wO0)||h0.push(u);break}}function LY(u){switch(u){case 0:h0.push(65533);break;case-1:D8();break;default:N6(XHQ)||h0.push(u);break}}function sY(u){switch(u){case 33:I=tF;break;case 47:I=OY;break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:K8(),kQ(u,hW);break;case 63:kQ(u,LB);break;default:h0.push(60),kQ(u,$8);break}}function OY(u){switch(u){case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:k8(),kQ(u,hW);break;case 62:I=$8;break;case-1:h0.push(60),h0.push(47),D8();break;default:kQ(u,LB);break}}function hW(u){switch(u){case 9:case 10:case 12:case 32:I=O7;break;case 47:I=dG;break;case 62:I=$8,F8();break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:E+=String.fromCharCode(u+32);break;case 0:E+=String.fromCharCode(65533);break;case-1:D8();break;default:E+=P6(r4Q);break}}function pG(u){if(u===47)d6(),I=MH;else h0.push(60),kQ(u,c6)}function MH(u){switch(u){case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:k8(),kQ(u,A7);break;default:h0.push(60),h0.push(47),kQ(u,c6);break}}function A7(u){switch(u){case 9:case 10:case 12:case 32:if(lQ(E)){I=O7;return}break;case 47:if(lQ(E)){I=dG;return}break;case 62:if(lQ(E)){I=$8,F8();return}break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:E+=String.fromCharCode(u+32),y.push(u);return;case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:E+=String.fromCharCode(u),y.push(u);return;default:break}h0.push(60),h0.push(47),u3(h0,y),kQ(u,c6)}function JJ(u){if(u===47)d6(),I=E7;else h0.push(60),kQ(u,XJ)}function E7(u){switch(u){case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:k8(),kQ(u,u5);break;default:h0.push(60),h0.push(47),kQ(u,XJ);break}}function u5(u){switch(u){case 9:case 10:case 12:case 32:if(lQ(E)){I=O7;return}break;case 47:if(lQ(E)){I=dG;return}break;case 62:if(lQ(E)){I=$8,F8();return}break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:E+=String.fromCharCode(u+32),y.push(u);return;case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:E+=String.fromCharCode(u),y.push(u);return;default:break}h0.push(60),h0.push(47),u3(h0,y),kQ(u,XJ)}function rY(u){switch(u){case 47:d6(),I=PJ;break;case 33:I=ZB,h0.push(60),h0.push(33);break;default:h0.push(60),kQ(u,YX);break}}function PJ(u){switch(u){case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:k8(),kQ(u,tY);break;default:h0.push(60),h0.push(47),kQ(u,YX);break}}function tY(u){switch(u){case 9:case 10:case 12:case 32:if(lQ(E)){I=O7;return}break;case 47:if(lQ(E)){I=dG;return}break;case 62:if(lQ(E)){I=$8,F8();return}break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:E+=String.fromCharCode(u+32),y.push(u);return;case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:E+=String.fromCharCode(u),y.push(u);return;default:break}h0.push(60),h0.push(47),u3(h0,y),kQ(u,YX)}function ZB(u){if(u===45)I=cV,h0.push(45);else kQ(u,YX)}function cV(u){if(u===45)I=lG,h0.push(45);else kQ(u,YX)}function YJ(u){switch(u){case 45:I=PY,h0.push(45);break;case 60:I=m7;break;case 0:h0.push(65533);break;case-1:D8();break;default:h0.push(u);break}}function PY(u){switch(u){case 45:I=lG,h0.push(45);break;case 60:I=m7;break;case 0:I=YJ,h0.push(65533);break;case-1:D8();break;default:I=YJ,h0.push(u);break}}function lG(u){switch(u){case 45:h0.push(45);break;case 60:I=m7;break;case 62:I=YX,h0.push(62);break;case 0:I=YJ,h0.push(65533);break;case-1:D8();break;default:I=YJ,h0.push(u);break}}function m7(u){switch(u){case 47:d6(),I=kX;break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:d6(),h0.push(60),kQ(u,_W);break;default:h0.push(60),kQ(u,YJ);break}}function kX(u){switch(u){case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:k8(),kQ(u,LH);break;default:h0.push(60),h0.push(47),kQ(u,YJ);break}}function LH(u){switch(u){case 9:case 10:case 12:case 32:if(lQ(E)){I=O7;return}break;case 47:if(lQ(E)){I=dG;return}break;case 62:if(lQ(E)){I=$8,F8();return}break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:E+=String.fromCharCode(u+32),y.push(u);return;case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:E+=String.fromCharCode(u),y.push(u);return;default:break}h0.push(60),h0.push(47),u3(h0,y),kQ(u,YJ)}function _W(u){switch(u){case 9:case 10:case 12:case 32:case 47:case 62:if(cX(y)==="script")I=NJ;else I=YJ;h0.push(u);break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:y.push(u+32),h0.push(u);break;case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:y.push(u),h0.push(u);break;default:kQ(u,YJ);break}}function NJ(u){switch(u){case 45:I=Jw,h0.push(45);break;case 60:I=iV,h0.push(60);break;case 0:h0.push(65533);break;case-1:D8();break;default:h0.push(u);break}}function Jw(u){switch(u){case 45:I=Yw,h0.push(45);break;case 60:I=iV,h0.push(60);break;case 0:I=NJ,h0.push(65533);break;case-1:D8();break;default:I=NJ,h0.push(u);break}}function Yw(u){switch(u){case 45:h0.push(45);break;case 60:I=iV,h0.push(60);break;case 62:I=YX,h0.push(62);break;case 0:I=NJ,h0.push(65533);break;case-1:D8();break;default:I=NJ,h0.push(u);break}}function iV(u){if(u===47)d6(),I=Gw,h0.push(47);else kQ(u,NJ)}function Gw(u){switch(u){case 9:case 10:case 12:case 32:case 47:case 62:if(cX(y)==="script")I=YJ;else I=NJ;h0.push(u);break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:y.push(u+32),h0.push(u);break;case 97:case 98:case 99:case 100:case 101:case 102:case 103:case 104:case 105:case 106:case 107:case 108:case 109:case 110:case 111:case 112:case 113:case 114:case 115:case 116:case 117:case 118:case 119:case 120:case 121:case 122:y.push(u),h0.push(u);break;default:kQ(u,NJ);break}}function O7(u){switch(u){case 9:case 10:case 12:case 32:break;case 47:I=dG;break;case 62:I=$8,F8();break;case-1:D8();break;case 61:r9(),x+=String.fromCharCode(u),I=aJ;break;default:if(tQ())break;r9(),kQ(u,aJ);break}}function aJ(u){switch(u){case 9:case 10:case 12:case 32:case 47:case 62:case-1:kQ(u,Ww);break;case 61:I=oV;break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:x+=String.fromCharCode(u+32);break;case 0:x+=String.fromCharCode(65533);break;case 34:case 39:case 60:default:x+=P6(t4Q);break}}function Ww(u){switch(u){case 9:case 10:case 12:case 32:break;case 47:j8(x),I=dG;break;case 61:I=oV;break;case 62:I=$8,j8(x),F8();break;case-1:j8(x),D8();break;default:j8(x),r9(),kQ(u,aJ);break}}function oV(u){switch(u){case 9:case 10:case 12:case 32:break;case 34:H7(),I=FB;break;case 39:H7(),I=DB;break;case 62:default:H7(),kQ(u,MB);break}}function FB(u){switch(u){case 34:j8(x,b),I=nV;break;case 38:R=FB,I=jH;break;case 0:b+=String.fromCharCode(65533);break;case-1:D8();break;case 10:b+=String.fromCharCode(u);break;default:b+=P6(n4Q);break}}function DB(u){switch(u){case 39:j8(x,b),I=nV;break;case 38:R=DB,I=jH;break;case 0:b+=String.fromCharCode(65533);break;case-1:D8();break;case 10:b+=String.fromCharCode(u);break;default:b+=P6(a4Q);break}}function MB(u){switch(u){case 9:case 10:case 12:case 32:j8(x,b),I=O7;break;case 38:R=MB,I=jH;break;case 62:j8(x,b),I=$8,F8();break;case 0:b+=String.fromCharCode(65533);break;case-1:z--,I=$8;break;case 34:case 39:case 60:case 61:case 96:default:b+=P6(s4Q);break}}function nV(u){switch(u){case 9:case 10:case 12:case 32:I=O7;break;case 47:I=dG;break;case 62:I=$8,F8();break;case-1:D8();break;default:kQ(u,O7);break}}function dG(u){switch(u){case 62:I=$8,B7(!0);break;case-1:D8();break;default:kQ(u,O7);break}}function LB(u,p,Z0){var XQ=p.length;if(Z0)z+=XQ-1;else z+=XQ;var KQ=p.substring(0,XQ-1);KQ=KQ.replace(/\u0000/g,""),KQ=KQ.replace(/\u000D\u000A/g,`
`),KQ=KQ.replace(/\u000D/g,`
`),S6(RW,KQ),I=$8}LB.lookahead=">";function tF(u,p,Z0){if(p[0]==="-"&&p[1]==="-"){z+=2,LJ(),I=Hw;return}if(p.toUpperCase()==="DOCTYPE")z+=7,I=Vw;else if(p==="[CDATA["&&wQ())z+=7,I=NH;else I=LB}tF.lookahead=7;function Hw(u){switch(LJ(),u){case 45:I=Bw;break;case 62:I=$8,S6(RW,cX(g));break;default:kQ(u,c9);break}}function Bw(u){switch(u){case 45:I=PB;break;case 62:I=$8,S6(RW,cX(g));break;case-1:S6(RW,cX(g)),D8();break;default:g.push(45),kQ(u,c9);break}}function c9(u){switch(u){case 60:g.push(u),I=Aw;break;case 45:I=OH;break;case 0:g.push(65533);break;case-1:S6(RW,cX(g)),D8();break;default:g.push(u);break}}function Aw(u){switch(u){case 33:g.push(u),I=aV;break;case 60:g.push(u);break;default:kQ(u,c9);break}}function aV(u){switch(u){case 45:I=OB;break;default:kQ(u,c9);break}}function OB(u){switch(u){case 45:I=Kw;break;default:kQ(u,OH);break}}function Kw(u){switch(u){case 62:case-1:kQ(u,PB);break;default:kQ(u,PB);break}}function OH(u){switch(u){case 45:I=PB;break;case-1:S6(RW,cX(g)),D8();break;default:g.push(45),kQ(u,c9);break}}function PB(u){switch(u){case 62:I=$8,S6(RW,cX(g));break;case 33:I=zw;break;case 45:g.push(45);break;case-1:S6(RW,cX(g)),D8();break;default:g.push(45),g.push(45),kQ(u,c9);break}}function zw(u){switch(u){case 45:g.push(45),g.push(45),g.push(33),I=OH;break;case 62:I=$8,S6(RW,cX(g));break;case-1:S6(RW,cX(g)),D8();break;default:g.push(45),g.push(45),g.push(33),kQ(u,c9);break}}function Vw(u){switch(u){case 9:case 10:case 12:case 32:I=eF;break;case-1:OJ(),e8(),f8(),D8();break;default:kQ(u,eF);break}}function eF(u){switch(u){case 9:case 10:case 12:case 32:break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:OJ(),l.push(u+32),I=p5;break;case 0:OJ(),l.push(65533),I=p5;break;case 62:OJ(),e8(),I=$8,f8();break;case-1:OJ(),e8(),f8(),D8();break;default:OJ(),l.push(u),I=p5;break}}function p5(u){switch(u){case 9:case 10:case 12:case 32:I=QD;break;case 62:I=$8,f8();break;case 65:case 66:case 67:case 68:case 69:case 70:case 71:case 72:case 73:case 74:case 75:case 76:case 77:case 78:case 79:case 80:case 81:case 82:case 83:case 84:case 85:case 86:case 87:case 88:case 89:case 90:l.push(u+32);break;case 0:l.push(65533);break;case-1:e8(),f8(),D8();break;default:l.push(u);break}}function QD(u,p,Z0){switch(u){case 9:case 10:case 12:case 32:z+=1;break;case 62:I=$8,z+=1,f8();break;case-1:e8(),f8(),D8();break;default:if(p=p.toUpperCase(),p==="PUBLIC")z+=6,I=cG;else if(p==="SYSTEM")z+=6,I=JD;else e8(),I=iG;break}}QD.lookahead=6;function cG(u){switch(u){case 9:case 10:case 12:case 32:I=NY;break;case 34:w7(),I=sV;break;case 39:w7(),I=PH;break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:e8(),I=iG;break}}function NY(u){switch(u){case 9:case 10:case 12:case 32:break;case 34:w7(),I=sV;break;case 39:w7(),I=PH;break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:e8(),I=iG;break}}function sV(u){switch(u){case 34:I=NB;break;case 0:_.push(65533);break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:_.push(u);break}}function PH(u){switch(u){case 39:I=NB;break;case 0:_.push(65533);break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:_.push(u);break}}function NB(u){switch(u){case 9:case 10:case 12:case 32:I=XD;break;case 62:I=$8,f8();break;case 34:QJ(),I=l5;break;case 39:QJ(),I=jB;break;case-1:e8(),f8(),D8();break;default:e8(),I=iG;break}}function XD(u){switch(u){case 9:case 10:case 12:case 32:break;case 62:I=$8,f8();break;case 34:QJ(),I=l5;break;case 39:QJ(),I=jB;break;case-1:e8(),f8(),D8();break;default:e8(),I=iG;break}}function JD(u){switch(u){case 9:case 10:case 12:case 32:I=qw;break;case 34:QJ(),I=l5;break;case 39:QJ(),I=jB;break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:e8(),I=iG;break}}function qw(u){switch(u){case 9:case 10:case 12:case 32:break;case 34:QJ(),I=l5;break;case 39:QJ(),I=jB;break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:e8(),I=iG;break}}function l5(u){switch(u){case 34:I=rV;break;case 0:a.push(65533);break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:a.push(u);break}}function jB(u){switch(u){case 39:I=rV;break;case 0:a.push(65533);break;case 62:e8(),I=$8,f8();break;case-1:e8(),f8(),D8();break;default:a.push(u);break}}function rV(u){switch(u){case 9:case 10:case 12:case 32:break;case 62:I=$8,f8();break;case-1:e8(),f8(),D8();break;default:I=iG;break}}function iG(u){switch(u){case 62:I=$8,f8();break;case-1:f8(),D8();break;default:break}}function NH(u){switch(u){case 93:I=Uw;break;case-1:D8();break;case 0:pQ=!0;default:N6(e4Q)||h0.push(u);break}}function Uw(u){switch(u){case 93:I=$w;break;default:h0.push(93),kQ(u,NH);break}}function $w(u){switch(u){case 93:h0.push(93);break;case 62:U8(),I=$8;break;default:h0.push(93),h0.push(93),kQ(u,NH);break}}function jH(u){switch(d6(),y.push(38),u){case 9:case 10:case 12:case 32:case 60:case 38:case-1:kQ(u,fW);break;case 35:y.push(u),I=CB;break;default:kQ(u,YD);break}}function YD(u){RO0.lastIndex=z;var p=RO0.exec(H);if(!p)throw Error("should never happen");var Z0=p[1];if(!Z0){I=fW;return}switch(z+=Z0.length,u3(y,YHQ(Z0)),R){case FB:case DB:case MB:if(Z0[Z0.length-1]!==";"){if(/[=A-Za-z0-9]/.test(H[z])){I=fW;return}}break;default:break}d6();var XQ=i4Q[Z0];if(typeof XQ==="number")y.push(XQ);else u3(y,XQ);I=fW}YD.lookahead=-o4Q;function CB(u){switch(w=0,u){case 120:case 88:y.push(u),I=Zw;break;default:kQ(u,Fw);break}}function Zw(u){switch(u){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 65:case 66:case 67:case 68:case 69:case 70:case 97:case 98:case 99:case 100:case 101:case 102:kQ(u,Dw);break;default:kQ(u,fW);break}}function Fw(u){switch(u){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:kQ(u,Mw);break;default:kQ(u,fW);break}}function Dw(u){switch(u){case 65:case 66:case 67:case 68:case 69:case 70:w*=16,w+=u-55;break;case 97:case 98:case 99:case 100:case 101:case 102:w*=16,w+=u-87;break;case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:w*=16,w+=u-48;break;case 59:I=IB;break;default:kQ(u,IB);break}}function Mw(u){switch(u){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:w*=10,w+=u-48;break;case 59:I=IB;break;default:kQ(u,IB);break}}function IB(u){if(w in IO0)w=IO0[w];else if(w>1114111||w>=55296&&w<57344)w=65533;if(d6(),w<=65535)y.push(w);else w=w-65536,y.push(55296+(w>>10)),y.push(56320+(w&1023));kQ(u,fW)}function fW(u){switch(R){case FB:case DB:case MB:b+=cX(y);break;default:u3(h0,y);break}kQ(u,R)}function GD(u,p,Z0,XQ){switch(u){case 1:if(p=p.replace(p3,""),p.length===0)return;break;case 4:AQ._appendChild(AQ.createComment(p));return;case 5:var KQ=p,yQ=Z0,L8=XQ;if(AQ.appendChild(new f4Q(AQ,KQ,yQ,L8)),m0||KQ.toLowerCase()!=="html"||p4Q.test(yQ)||L8&&L8.toLowerCase()===l4Q||L8===void 0&&PO0.test(yQ))AQ._quirks=!0;else if(d4Q.test(yQ)||L8!==void 0&&PO0.test(yQ))AQ._limitedQuirks=!0;t=WD;return}AQ._quirks=!0,t=WD,t(u,p,Z0,XQ)}function WD(u,p,Z0,XQ){var KQ;switch(u){case 1:if(p=p.replace(p3,""),p.length===0)return;break;case 5:return;case 4:AQ._appendChild(AQ.createComment(p));return;case 2:if(p==="html"){KQ=l8(AQ,p,Z0),d.push(KQ),AQ.appendChild(KQ),t=RB;return}break;case 3:switch(p){case"html":case"head":case"body":case"br":break;default:return}}KQ=l8(AQ,"html",null),d.push(KQ),AQ.appendChild(KQ),t=RB,t(u,p,Z0,XQ)}function RB(u,p,Z0,XQ){switch(u){case 1:if(p=p.replace(p3,""),p.length===0)return;break;case 5:return;case 4:IQ(p);return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"head":var KQ=G8(p,Z0);WQ=KQ,t=k9;return}break;case 3:switch(p){case"html":case"head":case"body":case"br":break;default:return}}RB(dX,"head",null),t(u,p,Z0,XQ)}function k9(u,p,Z0,XQ){switch(u){case 1:var KQ=p.match(p3);if(KQ)rQ(KQ[0]),p=p.substring(KQ[0].length);if(p.length===0)return;break;case 4:IQ(p);return;case 5:return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"meta":case"base":case"basefont":case"bgsound":case"link":G8(p,Z0),d.pop();return;case"title":M7(p,Z0);return;case"noscript":if(!l0){G8(p,Z0),t=HD;return}case"noframes":case"style":t6(p,Z0);return;case"script":e9(function(yQ){var L8=l8(yQ,p,Z0);if(L8._parser_inserted=!0,L8._force_async=!1,c0)L8._already_started=!0;return U8(),L8}),I=YX,p0=t,t=wB;return;case"template":G8(p,Z0),n.insertMarker(),d0=!1,t=eV,u0.push(t);return;case"head":return}break;case 3:switch(p){case"head":d.pop(),t=tV;return;case"body":case"html":case"br":break;case"template":if(!d.contains("template"))return;d.generateImpliedEndTags(null,"thorough"),d.popTag("template"),n.clearToMarker(),u0.pop(),x6();return;default:return}break}k9(K6,"head",null),t(u,p,Z0,XQ)}function HD(u,p,Z0,XQ){switch(u){case 5:return;case 4:k9(u,p);return;case 1:var KQ=p.match(p3);if(KQ)k9(u,KQ[0]),p=p.substring(KQ[0].length);if(p.length===0)return;break;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"basefont":case"bgsound":case"link":case"meta":case"noframes":case"style":k9(u,p,Z0);return;case"head":case"noscript":return}break;case 3:switch(p){case"noscript":d.pop(),t=k9;return;case"br":break;default:return}break}HD(K6,"noscript",null),t(u,p,Z0,XQ)}function tV(u,p,Z0,XQ){switch(u){case 1:var KQ=p.match(p3);if(KQ)rQ(KQ[0]),p=p.substring(KQ[0].length);if(p.length===0)return;break;case 4:IQ(p);return;case 5:return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"body":G8(p,Z0),d0=!1,t=M8;return;case"frameset":G8(p,Z0),t=Xq;return;case"base":case"basefont":case"bgsound":case"link":case"meta":case"noframes":case"script":case"style":case"template":case"title":d.push(WQ),k9(dX,p,Z0),d.removeElement(WQ);return;case"head":return}break;case 3:switch(p){case"template":return k9(u,p,Z0,XQ);case"body":case"html":case"br":break;default:return}break}tV(dX,"body",null),d0=!0,t(u,p,Z0,XQ)}function M8(u,p,Z0,XQ){var KQ,yQ,L8,Q6;switch(u){case 1:if(pQ){if(p=p.replace(jC,""),p.length===0)return}if(d0&&NC.test(p))d0=!1;h8(),rQ(p);return;case 5:return;case 4:IQ(p);return;case-1:if(u0.length)return eV(u);A9();return;case 2:switch(p){case"html":if(d.contains("template"))return;xO0(Z0,d.elements[0]);return;case"base":case"basefont":case"bgsound":case"link":case"meta":case"noframes":case"script":case"style":case"template":case"title":k9(dX,p,Z0);return;case"body":if(KQ=d.elements[1],!KQ||!(KQ instanceof a6.HTMLBodyElement)||d.contains("template"))return;d0=!1,xO0(Z0,KQ);return;case"frameset":if(!d0)return;if(KQ=d.elements[1],!KQ||!(KQ instanceof a6.HTMLBodyElement))return;if(KQ.parentNode)KQ.parentNode.removeChild(KQ);while(!(d.top instanceof a6.HTMLHtmlElement))d.pop();G8(p,Z0),t=Xq;return;case"address":case"article":case"aside":case"blockquote":case"center":case"details":case"dialog":case"dir":case"div":case"dl":case"fieldset":case"figcaption":case"figure":case"footer":case"header":case"hgroup":case"main":case"nav":case"ol":case"p":case"section":case"summary":case"ul":if(d.inButtonScope("p"))M8(K6,"p");G8(p,Z0);return;case"menu":if(d.inButtonScope("p"))M8(K6,"p");if(s6(d.top,"menuitem"))d.pop();G8(p,Z0);return;case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":if(d.inButtonScope("p"))M8(K6,"p");if(d.top instanceof a6.HTMLHeadingElement)d.pop();G8(p,Z0);return;case"pre":case"listing":if(d.inButtonScope("p"))M8(K6,"p");G8(p,Z0),iQ=!0,d0=!1;return;case"form":if(R0&&!d.contains("template"))return;if(d.inButtonScope("p"))M8(K6,"p");if(Q6=G8(p,Z0),!d.contains("template"))R0=Q6;return;case"li":d0=!1;for(yQ=d.elements.length-1;yQ>=0;yQ--){if(L8=d.elements[yQ],L8 instanceof a6.HTMLLIElement){M8(K6,"li");break}if(s6(L8,l3)&&!s6(L8,x80))break}if(d.inButtonScope("p"))M8(K6,"p");G8(p,Z0);return;case"dd":case"dt":d0=!1;for(yQ=d.elements.length-1;yQ>=0;yQ--){if(L8=d.elements[yQ],s6(L8,gO0)){M8(K6,L8.localName);break}if(s6(L8,l3)&&!s6(L8,x80))break}if(d.inButtonScope("p"))M8(K6,"p");G8(p,Z0);return;case"plaintext":if(d.inButtonScope("p"))M8(K6,"p");G8(p,Z0),I=LY;return;case"button":if(d.inScope("button"))M8(K6,"button"),t(u,p,Z0,XQ);else h8(),G8(p,Z0),d0=!1;return;case"a":var P9=n.findElementByTag("a");if(P9)M8(K6,p),n.remove(P9),d.removeElement(P9);case"b":case"big":case"code":case"em":case"font":case"i":case"s":case"small":case"strike":case"strong":case"tt":case"u":h8(),n.push(G8(p,Z0),Z0);return;case"nobr":if(h8(),d.inScope(p))M8(K6,p),h8();n.push(G8(p,Z0),Z0);return;case"applet":case"marquee":case"object":h8(),G8(p,Z0),n.insertMarker(),d0=!1;return;case"table":if(!AQ._quirks&&d.inButtonScope("p"))M8(K6,"p");G8(p,Z0),d0=!1,t=jJ;return;case"area":case"br":case"embed":case"img":case"keygen":case"wbr":h8(),G8(p,Z0),d.pop(),d0=!1;return;case"input":h8(),Q6=G8(p,Z0),d.pop();var S7=Q6.getAttribute("type");if(!S7||S7.toLowerCase()!=="hidden")d0=!1;return;case"param":case"source":case"track":G8(p,Z0),d.pop();return;case"hr":if(d.inButtonScope("p"))M8(K6,"p");if(s6(d.top,"menuitem"))d.pop();G8(p,Z0),d.pop(),d0=!1;return;case"image":M8(dX,"img",Z0,XQ);return;case"textarea":G8(p,Z0),iQ=!0,d0=!1,I=c6,p0=t,t=wB;return;case"xmp":if(d.inButtonScope("p"))M8(K6,"p");h8(),d0=!1,t6(p,Z0);return;case"iframe":d0=!1,t6(p,Z0);return;case"noembed":t6(p,Z0);return;case"select":if(h8(),G8(p,Z0),d0=!1,t===jJ||t===EB||t===mW||t===IH||t===uW)t=oG;else t=jY;return;case"optgroup":case"option":if(d.top instanceof a6.HTMLOptionElement)M8(K6,"option");h8(),G8(p,Z0);return;case"menuitem":if(s6(d.top,"menuitem"))d.pop();h8(),G8(p,Z0);return;case"rb":case"rtc":if(d.inScope("ruby"))d.generateImpliedEndTags();G8(p,Z0);return;case"rp":case"rt":if(d.inScope("ruby"))d.generateImpliedEndTags("rtc");G8(p,Z0);return;case"math":if(h8(),vO0(Z0),v80(Z0),TX(p,Z0,O8.MATHML),XQ)d.pop();return;case"svg":if(h8(),yO0(Z0),v80(Z0),TX(p,Z0,O8.SVG),XQ)d.pop();return;case"caption":case"col":case"colgroup":case"frame":case"head":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":return}h8(),G8(p,Z0);return;case 3:switch(p){case"template":k9(K6,p,Z0);return;case"body":if(!d.inScope("body"))return;t=Qq;return;case"html":if(!d.inScope("body"))return;t=Qq,t(u,p,Z0);return;case"address":case"article":case"aside":case"blockquote":case"button":case"center":case"details":case"dialog":case"dir":case"div":case"dl":case"fieldset":case"figcaption":case"figure":case"footer":case"header":case"hgroup":case"listing":case"main":case"menu":case"nav":case"ol":case"pre":case"section":case"summary":case"ul":if(!d.inScope(p))return;d.generateImpliedEndTags(),d.popTag(p);return;case"form":if(!d.contains("template")){var i9=R0;if(R0=null,!i9||!d.elementInScope(i9))return;d.generateImpliedEndTags(),d.removeElement(i9)}else{if(!d.inScope("form"))return;d.generateImpliedEndTags(),d.popTag("form")}return;case"p":if(!d.inButtonScope(p))M8(dX,p,null),t(u,p,Z0,XQ);else d.generateImpliedEndTags(p),d.popTag(p);return;case"li":if(!d.inListItemScope(p))return;d.generateImpliedEndTags(p),d.popTag(p);return;case"dd":case"dt":if(!d.inScope(p))return;d.generateImpliedEndTags(p),d.popTag(p);return;case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":if(!d.elementTypeInScope(a6.HTMLHeadingElement))return;d.generateImpliedEndTags(),d.popElementType(a6.HTMLHeadingElement);return;case"sarcasm":break;case"a":case"b":case"big":case"code":case"em":case"font":case"i":case"nobr":case"s":case"small":case"strike":case"strong":case"tt":case"u":var GJ=L7(p);if(GJ)return;break;case"applet":case"marquee":case"object":if(!d.inScope(p))return;d.generateImpliedEndTags(),d.popTag(p),n.clearToMarker();return;case"br":M8(dX,p,null);return}for(yQ=d.elements.length-1;yQ>=0;yQ--)if(L8=d.elements[yQ],s6(L8,p)){d.generateImpliedEndTags(p),d.popElement(L8);break}else if(s6(L8,l3))return;return}}function wB(u,p,Z0,XQ){switch(u){case 1:rQ(p);return;case-1:if(d.top instanceof a6.HTMLScriptElement)d.top._already_started=!0;d.pop(),t=p0,t(u);return;case 3:if(p==="script")C6();else d.pop(),t=p0;return;default:return}}function jJ(u,p,Z0,XQ){function KQ(L8){for(var Q6=0,P9=L8.length;Q6<P9;Q6++)if(L8[Q6][0]==="type")return L8[Q6][1].toLowerCase();return null}switch(u){case 1:if(LQ){M8(u,p,Z0,XQ);return}else if(s6(d.top,XV)){ZQ=[],p0=t,t=BD,t(u,p,Z0,XQ);return}break;case 4:IQ(p);return;case 5:return;case 2:switch(p){case"caption":d.clearToContext(CC),n.insertMarker(),G8(p,Z0),t=EB;return;case"colgroup":d.clearToContext(CC),G8(p,Z0),t=CH;return;case"col":jJ(dX,"colgroup",null),t(u,p,Z0,XQ);return;case"tbody":case"tfoot":case"thead":d.clearToContext(CC),G8(p,Z0),t=mW;return;case"td":case"th":case"tr":jJ(dX,"tbody",null),t(u,p,Z0,XQ);return;case"table":if(!d.inTableScope(p))return;jJ(K6,p),t(u,p,Z0,XQ);return;case"style":case"script":case"template":k9(u,p,Z0,XQ);return;case"input":var yQ=KQ(Z0);if(yQ!=="hidden")break;G8(p,Z0),d.pop();return;case"form":if(R0||d.contains("template"))return;R0=G8(p,Z0),d.popElement(R0);return}break;case 3:switch(p){case"table":if(!d.inTableScope(p))return;d.popTag(p),x6();return;case"body":case"caption":case"col":case"colgroup":case"html":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":return;case"template":k9(u,p,Z0,XQ);return}break;case-1:M8(u,p,Z0,XQ);return}U6=!0,M8(u,p,Z0,XQ),U6=!1}function BD(u,p,Z0,XQ){if(u===QV){if(pQ){if(p=p.replace(jC,""),p.length===0)return}ZQ.push(p)}else{var KQ=ZQ.join("");if(ZQ.length=0,NC.test(KQ))U6=!0,M8(QV,KQ),U6=!1;else rQ(KQ);t=p0,t(u,p,Z0,XQ)}}function EB(u,p,Z0,XQ){function KQ(){if(!d.inTableScope("caption"))return!1;return d.generateImpliedEndTags(),d.popTag("caption"),n.clearToMarker(),t=jJ,!0}switch(u){case 2:switch(p){case"caption":case"col":case"colgroup":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":if(KQ())t(u,p,Z0,XQ);return}break;case 3:switch(p){case"caption":KQ();return;case"table":if(KQ())t(u,p,Z0,XQ);return;case"body":case"col":case"colgroup":case"html":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":return}break}M8(u,p,Z0,XQ)}function CH(u,p,Z0,XQ){switch(u){case 1:var KQ=p.match(p3);if(KQ)rQ(KQ[0]),p=p.substring(KQ[0].length);if(p.length===0)return;break;case 4:IQ(p);return;case 5:return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"col":G8(p,Z0),d.pop();return;case"template":k9(u,p,Z0,XQ);return}break;case 3:switch(p){case"colgroup":if(!s6(d.top,"colgroup"))return;d.pop(),t=jJ;return;case"col":return;case"template":k9(u,p,Z0,XQ);return}break;case-1:M8(u,p,Z0,XQ);return}if(!s6(d.top,"colgroup"))return;CH(K6,"colgroup"),t(u,p,Z0,XQ)}function mW(u,p,Z0,XQ){function KQ(){if(!d.inTableScope("tbody")&&!d.inTableScope("thead")&&!d.inTableScope("tfoot"))return;d.clearToContext(IC),mW(K6,d.top.localName,null),t(u,p,Z0,XQ)}switch(u){case 2:switch(p){case"tr":d.clearToContext(IC),G8(p,Z0),t=IH;return;case"th":case"td":mW(dX,"tr",null),t(u,p,Z0,XQ);return;case"caption":case"col":case"colgroup":case"tbody":case"tfoot":case"thead":KQ();return}break;case 3:switch(p){case"table":KQ();return;case"tbody":case"tfoot":case"thead":if(d.inTableScope(p))d.clearToContext(IC),d.pop(),t=jJ;return;case"body":case"caption":case"col":case"colgroup":case"html":case"td":case"th":case"tr":return}break}jJ(u,p,Z0,XQ)}function IH(u,p,Z0,XQ){function KQ(){if(!d.inTableScope("tr"))return!1;return d.clearToContext(b80),d.pop(),t=mW,!0}switch(u){case 2:switch(p){case"th":case"td":d.clearToContext(b80),G8(p,Z0),t=uW,n.insertMarker();return;case"caption":case"col":case"colgroup":case"tbody":case"tfoot":case"thead":case"tr":if(KQ())t(u,p,Z0,XQ);return}break;case 3:switch(p){case"tr":KQ();return;case"table":if(KQ())t(u,p,Z0,XQ);return;case"tbody":case"tfoot":case"thead":if(d.inTableScope(p)){if(KQ())t(u,p,Z0,XQ)}return;case"body":case"caption":case"col":case"colgroup":case"html":case"td":case"th":return}break}jJ(u,p,Z0,XQ)}function uW(u,p,Z0,XQ){switch(u){case 2:switch(p){case"caption":case"col":case"colgroup":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":if(d.inTableScope("td"))uW(K6,"td"),t(u,p,Z0,XQ);else if(d.inTableScope("th"))uW(K6,"th"),t(u,p,Z0,XQ);return}break;case 3:switch(p){case"td":case"th":if(!d.inTableScope(p))return;d.generateImpliedEndTags(),d.popTag(p),n.clearToMarker(),t=IH;return;case"body":case"caption":case"col":case"colgroup":case"html":return;case"table":case"tbody":case"tfoot":case"thead":case"tr":if(!d.inTableScope(p))return;uW(K6,d.inTableScope("td")?"td":"th"),t(u,p,Z0,XQ);return}break}M8(u,p,Z0,XQ)}function jY(u,p,Z0,XQ){switch(u){case 1:if(pQ){if(p=p.replace(jC,""),p.length===0)return}rQ(p);return;case 4:IQ(p);return;case 5:return;case-1:M8(u,p,Z0,XQ);return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"option":if(d.top instanceof a6.HTMLOptionElement)jY(K6,p);G8(p,Z0);return;case"optgroup":if(d.top instanceof a6.HTMLOptionElement)jY(K6,"option");if(d.top instanceof a6.HTMLOptGroupElement)jY(K6,p);G8(p,Z0);return;case"select":jY(K6,p);return;case"input":case"keygen":case"textarea":if(!d.inSelectScope("select"))return;jY(K6,"select"),t(u,p,Z0,XQ);return;case"script":case"template":k9(u,p,Z0,XQ);return}break;case 3:switch(p){case"optgroup":if(d.top instanceof a6.HTMLOptionElement&&d.elements[d.elements.length-2]instanceof a6.HTMLOptGroupElement)jY(K6,"option");if(d.top instanceof a6.HTMLOptGroupElement)d.pop();return;case"option":if(d.top instanceof a6.HTMLOptionElement)d.pop();return;case"select":if(!d.inSelectScope(p))return;d.popTag(p),x6();return;case"template":k9(u,p,Z0,XQ);return}break}}function oG(u,p,Z0,XQ){switch(p){case"caption":case"table":case"tbody":case"tfoot":case"thead":case"tr":case"td":case"th":switch(u){case 2:oG(K6,"select"),t(u,p,Z0,XQ);return;case 3:if(d.inTableScope(p))oG(K6,"select"),t(u,p,Z0,XQ);return}}jY(u,p,Z0,XQ)}function eV(u,p,Z0,XQ){function KQ(yQ){t=yQ,u0[u0.length-1]=t,t(u,p,Z0,XQ)}switch(u){case 1:case 4:case 5:M8(u,p,Z0,XQ);return;case-1:if(!d.contains("template"))A9();else d.popTag("template"),n.clearToMarker(),u0.pop(),x6(),t(u,p,Z0,XQ);return;case 2:switch(p){case"base":case"basefont":case"bgsound":case"link":case"meta":case"noframes":case"script":case"style":case"template":case"title":k9(u,p,Z0,XQ);return;case"caption":case"colgroup":case"tbody":case"tfoot":case"thead":KQ(jJ);return;case"col":KQ(CH);return;case"tr":KQ(mW);return;case"td":case"th":KQ(IH);return}KQ(M8);return;case 3:switch(p){case"template":k9(u,p,Z0,XQ);return;default:return}}}function Qq(u,p,Z0,XQ){switch(u){case 1:if(NC.test(p))break;M8(u,p);return;case 4:d.elements[0]._appendChild(AQ.createComment(p));return;case 5:return;case-1:A9();return;case 2:if(p==="html"){M8(u,p,Z0,XQ);return}break;case 3:if(p==="html"){if(c0)return;t=Ow;return}break}t=M8,t(u,p,Z0,XQ)}function Xq(u,p,Z0,XQ){switch(u){case 1:if(p=p.replace(y80,""),p.length>0)rQ(p);return;case 4:IQ(p);return;case 5:return;case-1:A9();return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"frameset":G8(p,Z0);return;case"frame":G8(p,Z0),d.pop();return;case"noframes":k9(u,p,Z0,XQ);return}break;case 3:if(p==="frameset"){if(c0&&d.top instanceof a6.HTMLHtmlElement)return;if(d.pop(),!c0&&!(d.top instanceof a6.HTMLFrameSetElement))t=Lw;return}break}}function Lw(u,p,Z0,XQ){switch(u){case 1:if(p=p.replace(y80,""),p.length>0)rQ(p);return;case 4:IQ(p);return;case 5:return;case-1:A9();return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"noframes":k9(u,p,Z0,XQ);return}break;case 3:if(p==="html"){t=Pw;return}break}}function Ow(u,p,Z0,XQ){switch(u){case 1:if(NC.test(p))break;M8(u,p,Z0,XQ);return;case 4:AQ._appendChild(AQ.createComment(p));return;case 5:M8(u,p,Z0,XQ);return;case-1:A9();return;case 2:if(p==="html"){M8(u,p,Z0,XQ);return}break}t=M8,t(u,p,Z0,XQ)}function Pw(u,p,Z0,XQ){switch(u){case 1:if(p=p.replace(y80,""),p.length>0)M8(u,p,Z0,XQ);return;case 4:AQ._appendChild(AQ.createComment(p));return;case 5:M8(u,p,Z0,XQ);return;case-1:A9();return;case 2:switch(p){case"html":M8(u,p,Z0,XQ);return;case"noframes":k9(u,p,Z0,XQ);return}break}}function SB(u,p,Z0,XQ){function KQ(P9){for(var S7=0,i9=P9.length;S7<i9;S7++)switch(P9[S7][0]){case"color":case"face":case"size":return!0}return!1}var yQ;switch(u){case 1:if(d0&&JHQ.test(p))d0=!1;if(pQ)p=p.replace(jC,"");rQ(p);return;case 4:IQ(p);return;case 5:return;case 2:switch(p){case"font":if(!KQ(Z0))break;case"b":case"big":case"blockquote":case"body":case"br":case"center":case"code":case"dd":case"div":case"dl":case"dt":case"em":case"embed":case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":case"head":case"hr":case"i":case"img":case"li":case"listing":case"menu":case"meta":case"nobr":case"ol":case"p":case"pre":case"ruby":case"s":case"small":case"span":case"strong":case"strike":case"sub":case"sup":case"table":case"tt":case"u":case"ul":case"var":if(c0)break;do d.pop(),yQ=d.top;while(yQ.namespaceURI!==O8.HTML&&!TO0(yQ)&&!kO0(yQ));S6(u,p,Z0,XQ);return}if(yQ=d.elements.length===1&&c0?J:d.top,yQ.namespaceURI===O8.MATHML)vO0(Z0);else if(yQ.namespaceURI===O8.SVG)p=GHQ(p),yO0(Z0);if(v80(Z0),TX(p,Z0,yQ.namespaceURI),XQ){if(p==="script"&&yQ.namespaceURI===O8.SVG);d.pop()}return;case 3:if(yQ=d.top,p==="script"&&yQ.namespaceURI===O8.SVG&&yQ.localName==="script")d.pop();else{var L8=d.elements.length-1,Q6=d.elements[L8];for(;;){if(Q6.localName.toLowerCase()===p){d.popElement(Q6);break}if(Q6=d.elements[--L8],Q6.namespaceURI!==O8.HTML)continue;t(u,p,Z0,XQ);break}}return}}return mQ.testTokenizer=function(u,p,Z0,XQ){var KQ=[];switch(p){case"PCDATA state":I=$8;break;case"RCDATA state":I=c6;break;case"RAWTEXT state":I=XJ;break;case"PLAINTEXT state":I=LY;break}if(Z0)T=Z0;if(S6=function(L8,Q6,P9,S7){switch(U8(),L8){case 1:if(KQ.length>0&&KQ[KQ.length-1][0]==="Character")KQ[KQ.length-1][1]+=Q6;else KQ.push(["Character",Q6]);break;case 4:KQ.push(["Comment",Q6]);break;case 5:KQ.push(["DOCTYPE",Q6,P9===void 0?null:P9,S7===void 0?null:S7,!m0]);break;case 2:var i9=Object.create(null);for(var GJ=0;GJ<P9.length;GJ++){var sJ=P9[GJ];if(sJ.length===1)i9[sJ[0]]="";else i9[sJ[0]]=sJ[1]}var F9=["StartTag",Q6,i9];if(S7)F9.push(!0);KQ.push(F9);break;case 3:KQ.push(["EndTag",Q6]);break;case-1:break}},!XQ)this.parse(u,!0);else{for(var yQ=0;yQ<u.length;yQ++)this.parse(u[yQ]);this.parse("",!0)}return KQ},mQ}});var rZ=i((P58,oO0)=>{oO0.exports=iO0;var dO0=MC(),cO0=OC(),WHQ=wC(),EC=J7(),HHQ=XC();function iO0(Q){this.contextObject=Q}var BHQ={xml:{"":!0,"1.0":!0,"2.0":!0},core:{"":!0,"2.0":!0},html:{"":!0,"1.0":!0,"2.0":!0},xhtml:{"":!0,"1.0":!0,"2.0":!0}};iO0.prototype={hasFeature:function(J,G){var H=BHQ[(J||"").toLowerCase()];return H&&H[G||""]||!1},createDocumentType:function(J,G,H){if(!HHQ.isValidQName(J))EC.InvalidCharacterError();return new cO0(this.contextObject,J,G,H)},createDocument:function(J,G,H){var K=new dO0(!1,null),z;if(G)z=K.createElementNS(J,G);else z=null;if(H)K.appendChild(H);if(z)K.appendChild(z);if(J===EC.NAMESPACE.HTML)K._contentType="application/xhtml+xml";else if(J===EC.NAMESPACE.SVG)K._contentType="image/svg+xml";else K._contentType="application/xml";return K},createHTMLDocument:function(J){var G=new dO0(!0,null);G.appendChild(new cO0(G,"html"));var H=G.createElement("html");G.appendChild(H);var K=G.createElement("head");if(H.appendChild(K),J!==void 0){var z=G.createElement("title");K.appendChild(z),z.appendChild(G.createTextNode(J))}return H.appendChild(G.createElement("body")),G.modclock=1,G},mozSetOutputMutationHandler:function(Q,J){Q.mutationHandler=J},mozGetInputMutationHandler:function(Q){EC.nyi()},mozHTMLParser:WHQ}});var aO0=i((N58,nO0)=>{var AHQ=VC(),KHQ=j80();nO0.exports=h80;function h80(Q,J){this._window=Q,this._href=J}h80.prototype=Object.create(KHQ.prototype,{constructor:{value:h80},href:{get:function(){return this._href},set:function(Q){this.assign(Q)}},assign:{value:function(Q){var J=new AHQ(this._href),G=J.resolve(Q);this._href=G}},replace:{value:function(Q){this.assign(Q)}},reload:{value:function(){this.assign(this.href)}},toString:{value:function(){return this.href}}})});var rO0=i((j58,sO0)=>{var zHQ=Object.create(null,{appCodeName:{value:"Mozilla"},appName:{value:"Netscape"},appVersion:{value:"4.0"},platform:{value:""},product:{value:"Gecko"},productSub:{value:"20100101"},userAgent:{value:""},vendor:{value:""},vendorSub:{value:""},taintEnabled:{value:function(){return!1}}});sO0.exports=zHQ});var eO0=i((C58,tO0)=>{var VHQ={setTimeout,clearTimeout,setInterval,clearInterval};tO0.exports=VHQ});var f80=i((tZ,QP0)=>{var _80=J7();tZ=QP0.exports={CSSStyleDeclaration:qC(),CharacterData:pZ(),Comment:K80(),DOMException:sj(),DOMImplementation:rZ(),DOMTokenList:iQ0(),Document:MC(),DocumentFragment:V80(),DocumentType:OC(),Element:oz(),HTMLParser:wC(),NamedNodeMap:tQ0(),Node:PX(),NodeList:f3(),NodeFilter:iZ(),ProcessingInstruction:U80(),Text:B80(),Window:m80()};_80.merge(tZ,N80());_80.merge(tZ,ZC().elements);_80.merge(tZ,E80().elements)});var m80=i((I58,XP0)=>{var qHQ=rZ(),UHQ=EQ0(),$HQ=aO0(),eZ=J7();XP0.exports=SC;function SC(Q){this.document=Q||new qHQ(null).createHTMLDocument(""),this.document._scripting_enabled=!0,this.document.defaultView=this,this.location=new $HQ(this,this.document._address||"about:blank")}SC.prototype=Object.create(UHQ.prototype,{console:{value:console},history:{value:{back:eZ.nyi,forward:eZ.nyi,go:eZ.nyi}},navigator:{value:rO0()},window:{get:function(){return this}},self:{get:function(){return this}},frames:{get:function(){return this}},parent:{get:function(){return this}},top:{get:function(){return this}},length:{value:0},frameElement:{value:null},opener:{value:null},onload:{get:function(){return this._getEventHandler("load")},set:function(Q){this._setEventHandler("load",Q)}},getComputedStyle:{value:function(J){return J.style}}});eZ.expose(eO0(),SC);eZ.expose(f80(),SC)});var WP0=i((d3)=>{var JP0=rZ(),YP0=wC(),R58=m80(),GP0=f80();d3.createDOMImplementation=function(){return new JP0(null)};d3.createDocument=function(Q,J){if(Q||J){var G=new YP0;return G.parse(Q||"",!0),G.document()}return new JP0(null).createHTMLDocument("")};d3.createIncrementalHTMLParser=function(){var Q=new YP0;return{write:function(J){if(J.length>0)Q.parse(J,!1,function(){return!0})},end:function(J){Q.parse(J||"",!0,function(){return!0})},process:function(J){return Q.parse("",!1,J)},document:function(){return Q.document()}}};d3.createWindow=function(Q,J){var G=d3.createDocument(Q);if(J!==void 0)G._address=J;return new GP0.Window(G)};d3.impl=GP0});var DP0=i((E58,FP0)=>{function ZHQ(Q){for(var J=1;J<arguments.length;J++){var G=arguments[J];for(var H in G)if(G.hasOwnProperty(H))Q[H]=G[H]}return Q}function d80(Q,J){return Array(J+1).join(Q)}function FHQ(Q){return Q.replace(/^\n*/,"")}function DHQ(Q){var J=Q.length;while(J>0&&Q[J-1]===`
`)J--;return Q.substring(0,J)}var MHQ=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function c80(Q){return i80(Q,MHQ)}var AP0=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function KP0(Q){return i80(Q,AP0)}function LHQ(Q){return VP0(Q,AP0)}var zP0=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function OHQ(Q){return i80(Q,zP0)}function PHQ(Q){return VP0(Q,zP0)}function i80(Q,J){return J.indexOf(Q.nodeName)>=0}function VP0(Q,J){return Q.getElementsByTagName&&J.some(function(G){return Q.getElementsByTagName(G).length})}var iX={};iX.paragraph={filter:"p",replacement:function(Q){return`
`+Q+`
`}};iX.lineBreak={filter:"br",replacement:function(Q,J,G){return G.br+`
`}};iX.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(Q,J,G){var H=Number(J.nodeName.charAt(1));if(G.headingStyle==="setext"&&H<3){var K=d80(H===1?"=":"-",Q.length);return`
`+Q+`
`+K+`
`}else return`
`+d80("#",H)+" "+Q+`
`}};iX.blockquote={filter:"blockquote",replacement:function(Q){return Q=Q.replace(/^\n+|\n+$/g,""),Q=Q.replace(/^/gm,"> "),`
`+Q+`
`}};iX.list={filter:["ul","ol"],replacement:function(Q,J){var G=J.parentNode;if(G.nodeName==="LI"&&G.lastElementChild===J)return`
`+Q;else return`
`+Q+`
`}};iX.listItem={filter:"li",replacement:function(Q,J,G){Q=Q.replace(/^\n+/,"").replace(/\n+$/,`
`).replace(/\n/gm,`
`);var H=G.bulletListMarker+" ",K=J.parentNode;if(K.nodeName==="OL"){var z=K.getAttribute("start"),q=Array.prototype.indexOf.call(K.children,J);H=(z?Number(z)+q:q+1)+". "}return H+Q+(J.nextSibling&&!/\n$/.test(Q)?`
`:"")}};iX.indentedCodeBlock={filter:function(Q,J){return J.codeBlockStyle==="indented"&&Q.nodeName==="PRE"&&Q.firstChild&&Q.firstChild.nodeName==="CODE"},replacement:function(Q,J,G){return`
`+J.firstChild.textContent.replace(/\n/g,`
`)+`
`}};iX.fencedCodeBlock={filter:function(Q,J){return J.codeBlockStyle==="fenced"&&Q.nodeName==="PRE"&&Q.firstChild&&Q.firstChild.nodeName==="CODE"},replacement:function(Q,J,G){var H=J.firstChild.getAttribute("class")||"",K=(H.match(/language-(\S+)/)||[null,""])[1],z=J.firstChild.textContent,q=G.fence.charAt(0),F=3,D=new RegExp("^"+q+"{3,}","gm"),V;while(V=D.exec(z))if(V[0].length>=F)F=V[0].length+1;var O=d80(q,F);return`
`+O+K+`
`+z.replace(/\n$/,"")+`
`+O+`
`}};iX.horizontalRule={filter:"hr",replacement:function(Q,J,G){return`
`+G.hr+`
`}};iX.inlineLink={filter:function(Q,J){return J.linkStyle==="inlined"&&Q.nodeName==="A"&&Q.getAttribute("href")},replacement:function(Q,J){var G=J.getAttribute("href");if(G)G=G.replace(/([()])/g,"\\$1");var H=TC(J.getAttribute("title"));if(H)H=' "'+H.replace(/"/g,"\\\"")+'"';return"["+Q+"]("+G+H+")"}};iX.referenceLink={filter:function(Q,J){return J.linkStyle==="referenced"&&Q.nodeName==="A"&&Q.getAttribute("href")},replacement:function(Q,J,G){var H=J.getAttribute("href"),K=TC(J.getAttribute("title"));if(K)K=' "'+K+'"';var z,q;switch(G.linkReferenceStyle){case"collapsed":z="["+Q+"][]",q="["+Q+"]: "+H+K;break;case"shortcut":z="["+Q+"]",q="["+Q+"]: "+H+K;break;default:var F=this.references.length+1;z="["+Q+"]["+F+"]",q="["+F+"]: "+H+K}return this.references.push(q),z},references:[],append:function(Q){var J="";if(this.references.length)J=`
`+this.references.join(`
`)+`
`,this.references=[];return J}};iX.emphasis={filter:["em","i"],replacement:function(Q,J,G){if(!Q.trim())return"";return G.emDelimiter+Q+G.emDelimiter}};iX.strong={filter:["strong","b"],replacement:function(Q,J,G){if(!Q.trim())return"";return G.strongDelimiter+Q+G.strongDelimiter}};iX.code={filter:function(Q){var J=Q.previousSibling||Q.nextSibling,G=Q.parentNode.nodeName==="PRE"&&!J;return Q.nodeName==="CODE"&&!G},replacement:function(Q){if(!Q)return"";Q=Q.replace(/\r?\n|\r/g," ");var J=/^`|^ .*?[^ ].* $|`$/.test(Q)?" ":"",G="`",H=Q.match(/`+/gm)||[];while(H.indexOf(G)!==-1)G=G+"`";return G+J+Q+J+G}};iX.image={filter:"img",replacement:function(Q,J){var G=TC(J.getAttribute("alt")),H=J.getAttribute("src")||"",K=TC(J.getAttribute("title")),z=K?' "'+K+'"':"";return H?"!["+G+"]("+H+z+")":""}};function TC(Q){return Q?Q.replace(/(\n+\s*)+/g,`
`):""}function qP0(Q){this.options=Q,this._keep=[],this._remove=[],this.blankRule={replacement:Q.blankReplacement},this.keepReplacement=Q.keepReplacement,this.defaultRule={replacement:Q.defaultReplacement},this.array=[];for(var J in Q.rules)this.array.push(Q.rules[J])}qP0.prototype={add:function(Q,J){this.array.unshift(J)},keep:function(Q){this._keep.unshift({filter:Q,replacement:this.keepReplacement})},remove:function(Q){this._remove.unshift({filter:Q,replacement:function(){return""}})},forNode:function(Q){if(Q.isBlank)return this.blankRule;var J;if(J=u80(this.array,Q,this.options))return J;if(J=u80(this._keep,Q,this.options))return J;if(J=u80(this._remove,Q,this.options))return J;return this.defaultRule},forEach:function(Q){for(var J=0;J<this.array.length;J++)Q(this.array[J],J)}};function u80(Q,J,G){for(var H=0;H<Q.length;H++){var K=Q[H];if(NHQ(K,J,G))return K}return}function NHQ(Q,J,G){var H=Q.filter;if(typeof H==="string"){if(H===J.nodeName.toLowerCase())return!0}else if(Array.isArray(H)){if(H.indexOf(J.nodeName.toLowerCase())>-1)return!0}else if(typeof H==="function"){if(H.call(Q,J,G))return!0}else throw TypeError("`filter` needs to be a string, array, or function")}function jHQ(Q){var{element:J,isBlock:G,isVoid:H}=Q,K=Q.isPre||function(P){return P.nodeName==="PRE"};if(!J.firstChild||K(J))return;var z=null,q=!1,F=null,D=HP0(F,J,K);while(D!==J){if(D.nodeType===3||D.nodeType===4){var V=D.data.replace(/[ \r\n\t]+/g," ");if((!z||/ $/.test(z.data))&&!q&&V[0]===" ")V=V.substr(1);if(!V){D=p80(D);continue}D.data=V,z=D}else if(D.nodeType===1){if(G(D)||D.nodeName==="BR"){if(z)z.data=z.data.replace(/ $/,"");z=null,q=!1}else if(H(D)||K(D))z=null,q=!0;else if(z)q=!1}else{D=p80(D);continue}var O=HP0(F,D,K);F=D,D=O}if(z){if(z.data=z.data.replace(/ $/,""),!z.data)p80(z)}}function p80(Q){var J=Q.nextSibling||Q.parentNode;return Q.parentNode.removeChild(Q),J}function HP0(Q,J,G){if(Q&&Q.parentNode===J||G(J))return J.nextSibling||J.parentNode;return J.firstChild||J.nextSibling||J.parentNode}var UP0=typeof window<"u"?window:{};function CHQ(){var Q=UP0.DOMParser,J=!1;try{if(new Q().parseFromString("","text/html"))J=!0}catch(G){}return J}function IHQ(){var Q=function(){};{var J=WP0();Q.prototype.parseFromString=function(G){return J.createDocument(G)}}return Q}var RHQ=CHQ()?UP0.DOMParser:IHQ();function wHQ(Q,J){var G;if(typeof Q==="string"){var H=EHQ().parseFromString('<x-turndown id="turndown-root">'+Q+"</x-turndown>","text/html");G=H.getElementById("turndown-root")}else G=Q.cloneNode(!0);return jHQ({element:G,isBlock:c80,isVoid:KP0,isPre:J.preformattedCode?SHQ:null}),G}var l80;function EHQ(){return l80=l80||new RHQ,l80}function SHQ(Q){return Q.nodeName==="PRE"||Q.nodeName==="CODE"}function THQ(Q,J){return Q.isBlock=c80(Q),Q.isCode=Q.nodeName==="CODE"||Q.parentNode.isCode,Q.isBlank=kHQ(Q),Q.flankingWhitespace=yHQ(Q,J),Q}function kHQ(Q){return!KP0(Q)&&!OHQ(Q)&&/^\s*$/i.test(Q.textContent)&&!LHQ(Q)&&!PHQ(Q)}function yHQ(Q,J){if(Q.isBlock||J.preformattedCode&&Q.isCode)return{leading:"",trailing:""};var G=vHQ(Q.textContent);if(G.leadingAscii&&BP0("left",Q,J))G.leading=G.leadingNonAscii;if(G.trailingAscii&&BP0("right",Q,J))G.trailing=G.trailingNonAscii;return{leading:G.leading,trailing:G.trailing}}function vHQ(Q){var J=Q.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:J[1],leadingAscii:J[2],leadingNonAscii:J[3],trailing:J[4],trailingNonAscii:J[5],trailingAscii:J[6]}}function BP0(Q,J,G){var H,K,z;if(Q==="left")H=J.previousSibling,K=/ $/;else H=J.nextSibling,K=/^ /;if(H){if(H.nodeType===3)z=K.test(H.nodeValue);else if(G.preformattedCode&&H.nodeName==="CODE")z=!1;else if(H.nodeType===1&&!c80(H))z=K.test(H.textContent)}return z}var xHQ=Array.prototype.reduce,bHQ=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function kC(Q){if(!(this instanceof kC))return new kC(Q);var J={rules:iX,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(G,H){return H.isBlock?`
`:""},keepReplacement:function(G,H){return H.isBlock?`
`+H.outerHTML+`
`:H.outerHTML},defaultReplacement:function(G,H){return H.isBlock?`
`+G+`
`:G}};this.options=ZHQ({},J,Q),this.rules=new qP0(this.options)}kC.prototype={turndown:function(Q){if(!_HQ(Q))throw TypeError(Q+" is not a string, or an element/document/fragment node.");if(Q==="")return"";var J=$P0.call(this,new wHQ(Q,this.options));return gHQ.call(this,J)},use:function(Q){if(Array.isArray(Q))for(var J=0;J<Q.length;J++)this.use(Q[J]);else if(typeof Q==="function")Q(this);else throw TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(Q,J){return this.rules.add(Q,J),this},keep:function(Q){return this.rules.keep(Q),this},remove:function(Q){return this.rules.remove(Q),this},escape:function(Q){return bHQ.reduce(function(J,G){return J.replace(G[0],G[1])},Q)}};function $P0(Q){var J=this;return xHQ.call(Q.childNodes,function(G,H){H=new THQ(H,J.options);var K="";if(H.nodeType===3)K=H.isCode?H.nodeValue:J.escape(H.nodeValue);else if(H.nodeType===1)K=hHQ.call(J,H);return ZP0(G,K)},"")}function gHQ(Q){var J=this;return this.rules.forEach(function(G){if(typeof G.append==="function")Q=ZP0(Q,G.append(J.options))}),Q.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function hHQ(Q){var J=this.rules.forNode(Q),G=$P0.call(this,Q),H=Q.flankingWhitespace;if(H.leading||H.trailing)G=G.trim();return H.leading+J.replacement(G,Q,this.options)+H.trailing}function ZP0(Q,J){var G=DHQ(Q),H=FHQ(J),K=Math.max(Q.length-G.length,J.length-H.length),z=`
`.substring(0,K);return G+z+H}function _HQ(Q){return Q!=null&&(typeof Q==="string"||Q.nodeType&&(Q.nodeType===1||Q.nodeType===9||Q.nodeType===11))}FP0.exports=kC});var zN0=i((B6)=>{Object.defineProperty(B6,"__esModule",{value:!0});var s9=require("obsidian"),n80="YYYY-MM-DD",a80="gggg-[W]ww",iP0="YYYY-MM",oP0="YYYY-[Q]Q",nP0="YYYY";function QF(Q){let J=window.app.plugins.getPlugin("periodic-notes");return J&&J.settings?.[Q]?.enabled}function XF(){try{let{internalPlugins:Q,plugins:J}=window.app;if(QF("daily")){let{format:z,folder:q,template:F}=J.getPlugin("periodic-notes")?.settings?.daily||{};return{format:z||n80,folder:q?.trim()||"",template:F?.trim()||""}}let{folder:G,format:H,template:K}=Q.getPluginById("daily-notes")?.instance?.options||{};return{format:H||n80,folder:G?.trim()||"",template:K?.trim()||""}}catch(Q){console.info("No custom daily note settings found!",Q)}}function JF(){try{let Q=window.app.plugins,J=Q.getPlugin("calendar")?.options,G=Q.getPlugin("periodic-notes")?.settings?.weekly;if(QF("weekly"))return{format:G.format||a80,folder:G.folder?.trim()||"",template:G.template?.trim()||""};let H=J||{};return{format:H.weeklyNoteFormat||a80,folder:H.weeklyNoteFolder?.trim()||"",template:H.weeklyNoteTemplate?.trim()||""}}catch(Q){console.info("No custom weekly note settings found!",Q)}}function YF(){let Q=window.app.plugins;try{let J=QF("monthly")&&Q.getPlugin("periodic-notes")?.settings?.monthly||{};return{format:J.format||iP0,folder:J.folder?.trim()||"",template:J.template?.trim()||""}}catch(J){console.info("No custom monthly note settings found!",J)}}function GF(){let Q=window.app.plugins;try{let J=QF("quarterly")&&Q.getPlugin("periodic-notes")?.settings?.quarterly||{};return{format:J.format||oP0,folder:J.folder?.trim()||"",template:J.template?.trim()||""}}catch(J){console.info("No custom quarterly note settings found!",J)}}function WF(){let Q=window.app.plugins;try{let J=QF("yearly")&&Q.getPlugin("periodic-notes")?.settings?.yearly||{};return{format:J.format||nP0,folder:J.folder?.trim()||"",template:J.template?.trim()||""}}catch(J){console.info("No custom yearly note settings found!",J)}}function aP0(...Q){let J=[];for(let H=0,K=Q.length;H<K;H++)J=J.concat(Q[H].split("/"));let G=[];for(let H=0,K=J.length;H<K;H++){let z=J[H];if(!z||z===".")continue;else G.push(z)}if(J[0]==="")G.unshift("");return G.join("/")}function nHQ(Q){let J=Q.substring(Q.lastIndexOf("/")+1);if(J.lastIndexOf(".")!=-1)J=J.substring(0,J.lastIndexOf("."));return J}async function aHQ(Q){let J=Q.replace(/\\/g,"/").split("/");if(J.pop(),J.length){let G=aP0(...J);if(!window.app.vault.getAbstractFileByPath(G))await window.app.vault.createFolder(G)}}async function HF(Q,J){if(!J.endsWith(".md"))J+=".md";let G=s9.normalizePath(aP0(Q,J));return await aHQ(G),G}async function JV(Q){let{metadataCache:J,vault:G}=window.app,H=s9.normalizePath(Q);if(H==="/")return Promise.resolve(["",null]);try{let K=J.getFirstLinkpathDest(H,""),z=await G.cachedRead(K),q=window.app.foldManager.load(K);return[z,q]}catch(K){return console.error(`Failed to read the daily note template '${H}'`,K),new s9.Notice("Failed to read the daily note template"),["",null]}}function TG(Q,J="day"){let G=Q.clone().startOf(J).format();return`${J}-${G}`}function sP0(Q){return Q.replace(/\[[^\]]*\]/g,"")}function sHQ(Q,J){if(J==="week"){let G=sP0(Q);return/w{1,2}/i.test(G)&&(/M{1,4}/.test(G)||/D{1,4}/.test(G))}return!1}function YV(Q,J){return rP0(Q.basename,J)}function rHQ(Q,J){return rP0(nHQ(Q),J)}function rP0(Q,J){let H={day:XF,week:JF,month:YF,quarter:GF,year:WF}[J]().format.split("/").pop(),K=window.moment(Q,H,!0);if(!K.isValid())return null;if(sHQ(H,J)){if(J==="week"){let z=sP0(H);if(/w{1,2}/i.test(z))return window.moment(Q,H.replace(/M{1,4}/g,"").replace(/D{1,4}/g,""),!1)}}return K}class tP0 extends Error{}async function eP0(Q){let J=window.app,{vault:G}=J,H=window.moment,{template:K,format:z,folder:q}=XF(),[F,D]=await JV(K),V=Q.format(z),O=await HF(q,V);try{let P=await G.create(O,F.replace(/{{\s*date\s*}}/gi,V).replace(/{{\s*time\s*}}/gi,H().format("HH:mm")).replace(/{{\s*title\s*}}/gi,V).replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(N,I,R,w,E,T)=>{let y=H(),x=Q.clone().set({hour:y.get("hour"),minute:y.get("minute"),second:y.get("second")});if(R)x.add(parseInt(w,10),E);if(T)return x.format(T.substring(1).trim());return x.format(z)}).replace(/{{\s*yesterday\s*}}/gi,Q.clone().subtract(1,"day").format(z)).replace(/{{\s*tomorrow\s*}}/gi,Q.clone().add(1,"d").format(z)));return J.foldManager.save(P,D),P}catch(P){console.error(`Failed to create file: '${O}'`,P),new s9.Notice("Unable to create new file.")}}function tHQ(Q,J){return J[TG(Q,"day")]??null}function eHQ(){let{vault:Q}=window.app,{folder:J}=XF(),G=Q.getAbstractFileByPath(s9.normalizePath(J));if(!G)throw new tP0("Failed to find daily notes folder");let H={};return s9.Vault.recurseChildren(G,(K)=>{if(K instanceof s9.TFile){let z=YV(K,"day");if(z){let q=TG(z,"day");H[q]=K}}}),H}class QN0 extends Error{}function Q3Q(){let{moment:Q}=window,J=Q.localeData()._week.dow,G=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"];while(J)G.push(G.shift()),J--;return G}function X3Q(Q){return Q3Q().indexOf(Q.toLowerCase())}async function XN0(Q){let{vault:J}=window.app,{template:G,format:H,folder:K}=JF(),[z,q]=await JV(G),F=Q.format(H),D=await HF(K,F);try{let V=await J.create(D,z.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(O,P,N,I,R,w)=>{let E=window.moment(),T=Q.clone().set({hour:E.get("hour"),minute:E.get("minute"),second:E.get("second")});if(N)T.add(parseInt(I,10),R);if(w)return T.format(w.substring(1).trim());return T.format(H)}).replace(/{{\s*title\s*}}/gi,F).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*:(.*?)}}/gi,(O,P,N)=>{let I=X3Q(P);return Q.weekday(I).format(N.trim())}));return window.app.foldManager.save(V,q),V}catch(V){console.error(`Failed to create file: '${D}'`,V),new s9.Notice("Unable to create new file.")}}function J3Q(Q,J){return J[TG(Q,"week")]??null}function Y3Q(){let Q={};if(!HN0())return Q;let{vault:J}=window.app,{folder:G}=JF(),H=J.getAbstractFileByPath(s9.normalizePath(G));if(!H)throw new QN0("Failed to find weekly notes folder");return s9.Vault.recurseChildren(H,(K)=>{if(K instanceof s9.TFile){let z=YV(K,"week");if(z){let q=TG(z,"week");Q[q]=K}}}),Q}class JN0 extends Error{}async function YN0(Q){let{vault:J}=window.app,{template:G,format:H,folder:K}=YF(),[z,q]=await JV(G),F=Q.format(H),D=await HF(K,F);try{let V=await J.create(D,z.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(O,P,N,I,R,w)=>{let E=window.moment(),T=Q.clone().set({hour:E.get("hour"),minute:E.get("minute"),second:E.get("second")});if(N)T.add(parseInt(I,10),R);if(w)return T.format(w.substring(1).trim());return T.format(H)}).replace(/{{\s*date\s*}}/gi,F).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,F));return window.app.foldManager.save(V,q),V}catch(V){console.error(`Failed to create file: '${D}'`,V),new s9.Notice("Unable to create new file.")}}function G3Q(Q,J){return J[TG(Q,"month")]??null}function W3Q(){let Q={};if(!BN0())return Q;let{vault:J}=window.app,{folder:G}=YF(),H=J.getAbstractFileByPath(s9.normalizePath(G));if(!H)throw new JN0("Failed to find monthly notes folder");return s9.Vault.recurseChildren(H,(K)=>{if(K instanceof s9.TFile){let z=YV(K,"month");if(z){let q=TG(z,"month");Q[q]=K}}}),Q}class GN0 extends Error{}async function H3Q(Q){let{vault:J}=window.app,{template:G,format:H,folder:K}=GF(),[z,q]=await JV(G),F=Q.format(H),D=await HF(K,F);try{let V=await J.create(D,z.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(O,P,N,I,R,w)=>{let E=window.moment(),T=Q.clone().set({hour:E.get("hour"),minute:E.get("minute"),second:E.get("second")});if(N)T.add(parseInt(I,10),R);if(w)return T.format(w.substring(1).trim());return T.format(H)}).replace(/{{\s*date\s*}}/gi,F).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,F));return window.app.foldManager.save(V,q),V}catch(V){console.error(`Failed to create file: '${D}'`,V),new s9.Notice("Unable to create new file.")}}function B3Q(Q,J){return J[TG(Q,"quarter")]??null}function A3Q(){let Q={};if(!AN0())return Q;let{vault:J}=window.app,{folder:G}=GF(),H=J.getAbstractFileByPath(s9.normalizePath(G));if(!H)throw new GN0("Failed to find quarterly notes folder");return s9.Vault.recurseChildren(H,(K)=>{if(K instanceof s9.TFile){let z=YV(K,"quarter");if(z){let q=TG(z,"quarter");Q[q]=K}}}),Q}class WN0 extends Error{}async function K3Q(Q){let{vault:J}=window.app,{template:G,format:H,folder:K}=WF(),[z,q]=await JV(G),F=Q.format(H),D=await HF(K,F);try{let V=await J.create(D,z.replace(/{{\s*(date|time)\s*(([+-]\d+)([yqmwdhs]))?\s*(:.+?)?}}/gi,(O,P,N,I,R,w)=>{let E=window.moment(),T=Q.clone().set({hour:E.get("hour"),minute:E.get("minute"),second:E.get("second")});if(N)T.add(parseInt(I,10),R);if(w)return T.format(w.substring(1).trim());return T.format(H)}).replace(/{{\s*date\s*}}/gi,F).replace(/{{\s*time\s*}}/gi,window.moment().format("HH:mm")).replace(/{{\s*title\s*}}/gi,F));return window.app.foldManager.save(V,q),V}catch(V){console.error(`Failed to create file: '${D}'`,V),new s9.Notice("Unable to create new file.")}}function z3Q(Q,J){return J[TG(Q,"year")]??null}function V3Q(){let Q={};if(!KN0())return Q;let{vault:J}=window.app,{folder:G}=WF(),H=J.getAbstractFileByPath(s9.normalizePath(G));if(!H)throw new WN0("Failed to find yearly notes folder");return s9.Vault.recurseChildren(H,(K)=>{if(K instanceof s9.TFile){let z=YV(K,"year");if(z){let q=TG(z,"year");Q[q]=K}}}),Q}function q3Q(){let{app:Q}=window,J=Q.internalPlugins.plugins["daily-notes"];if(J&&J.enabled)return!0;let G=Q.plugins.getPlugin("periodic-notes");return G&&G.settings?.daily?.enabled}function HN0(){let{app:Q}=window;if(Q.plugins.getPlugin("calendar"))return!0;let J=Q.plugins.getPlugin("periodic-notes");return J&&J.settings?.weekly?.enabled}function BN0(){let{app:Q}=window,J=Q.plugins.getPlugin("periodic-notes");return J&&J.settings?.monthly?.enabled}function AN0(){let{app:Q}=window,J=Q.plugins.getPlugin("periodic-notes");return J&&J.settings?.quarterly?.enabled}function KN0(){let{app:Q}=window,J=Q.plugins.getPlugin("periodic-notes");return J&&J.settings?.yearly?.enabled}function U3Q(Q){let J={day:XF,week:JF,month:YF,quarter:GF,year:WF}[Q];return J()}function $3Q(Q,J){return{day:eP0,month:YN0,week:XN0}[Q](J)}B6.DEFAULT_DAILY_NOTE_FORMAT=n80;B6.DEFAULT_MONTHLY_NOTE_FORMAT=iP0;B6.DEFAULT_QUARTERLY_NOTE_FORMAT=oP0;B6.DEFAULT_WEEKLY_NOTE_FORMAT=a80;B6.DEFAULT_YEARLY_NOTE_FORMAT=nP0;B6.appHasDailyNotesPluginLoaded=q3Q;B6.appHasMonthlyNotesPluginLoaded=BN0;B6.appHasQuarterlyNotesPluginLoaded=AN0;B6.appHasWeeklyNotesPluginLoaded=HN0;B6.appHasYearlyNotesPluginLoaded=KN0;B6.createDailyNote=eP0;B6.createMonthlyNote=YN0;B6.createPeriodicNote=$3Q;B6.createQuarterlyNote=H3Q;B6.createWeeklyNote=XN0;B6.createYearlyNote=K3Q;B6.getAllDailyNotes=eHQ;B6.getAllMonthlyNotes=W3Q;B6.getAllQuarterlyNotes=A3Q;B6.getAllWeeklyNotes=Y3Q;B6.getAllYearlyNotes=V3Q;B6.getDailyNote=tHQ;B6.getDailyNoteSettings=XF;B6.getDateFromFile=YV;B6.getDateFromPath=rHQ;B6.getDateUID=TG;B6.getMonthlyNote=G3Q;B6.getMonthlyNoteSettings=YF;B6.getPeriodicNoteSettings=U3Q;B6.getQuarterlyNote=B3Q;B6.getQuarterlyNoteSettings=GF;B6.getTemplateInfo=JV;B6.getWeeklyNote=J3Q;B6.getWeeklyNoteSettings=JF;B6.getYearlyNote=z3Q;B6.getYearlyNoteSettings=WF});var lj0=i((O60,cC)=>{/*!
* ONNX Runtime Web v1.26.0
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/var SBQ=(()=>{var{create:$x,defineProperty:co,getOwnPropertyDescriptor:Ax,getOwnPropertyNames:Px,getPrototypeOf:Ox}=Object,Ex=Object.prototype.hasOwnProperty,ua=((Q)=>require)(function(Q){return require.apply(this,arguments)}),$=(Q,J)=>()=>(Q&&(J=Q(Q=0)),J),W=(Q,J)=>()=>(J||Q((J={exports:{}}).exports,J),J.exports),Wn=(Q,J)=>{for(var G in J)co(Q,G,{get:J[G],enumerable:!0})},$l=(Q,J,G,H)=>{if(J&&typeof J=="object"||typeof J=="function")for(let K of Px(J))!Ex.call(Q,K)&&K!==G&&co(Q,K,{get:()=>J[K],enumerable:!(H=Ax(J,K))||H.enumerable});return Q},ae=(Q,J,G)=>(G=Q!=null?$x(Ox(Q)):{},$l(J||!Q||!Q.__esModule?co(G,"default",{value:Q,enumerable:!0}):G,Q)),pr=(Q)=>$l(co({},"__esModule",{value:!0}),Q),po,Hn,vn,Cx,Al,la=$(()=>{po=new Map,Hn=[],vn=(Q,J,G)=>{if(J&&typeof J.init=="function"&&typeof J.createInferenceSessionHandler=="function"){let H=po.get(Q);if(H===void 0)po.set(Q,{backend:J,priority:G});else{if(H.priority>G)return;if(H.priority===G&&H.backend!==J)throw Error(`cannot register backend "${Q}" using priority ${G}`)}if(G>=0){let K=Hn.indexOf(Q);K!==-1&&Hn.splice(K,1);for(let z=0;z<Hn.length;z++)if(po.get(Hn[z]).priority<=G){Hn.splice(z,0,Q);return}Hn.push(Q)}return}throw TypeError("not a valid backend")},Cx=async(Q)=>{let J=po.get(Q);if(!J)return"backend not found.";if(J.initialized)return J.backend;if(J.aborted)return J.error;{let G=!!J.initPromise;try{return G||(J.initPromise=J.backend.init(Q)),await J.initPromise,J.initialized=!0,J.backend}catch(H){return G||(J.error=`${H}`,J.aborted=!0),J.error}finally{delete J.initPromise}}},Al=async(Q)=>{let J=Q.executionProviders||[],G=J.map((D)=>typeof D=="string"?D:D.name),H=G.length===0?Hn:G,K,z=[],q=new Set;for(let D of H){let V=await Cx(D);typeof V=="string"?z.push({name:D,err:V}):(K||(K=V),K===V&&q.add(D))}if(!K)throw Error(`no available backend found. ERR: ${z.map((D)=>`[${D.name}] ${D.err}`).join(", ")}`);for(let{name:D,err:V}of z)G.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${V}`);let F=J.filter((D)=>q.has(typeof D=="string"?D:D.name));return[K,new Proxy(Q,{get:(D,V)=>V==="executionProviders"?F:Reflect.get(D,V)})]}}),Pl=$(()=>{la()}),Ol,El=$(()=>{Ol="1.26.0"}),Cl,Fe,ca=$(()=>{El(),Cl="warning",Fe={wasm:{},webgl:{},webgpu:{},versions:{common:Ol},set logLevel(Q){if(Q!==void 0){if(typeof Q!="string"||["verbose","info","warning","error","fatal"].indexOf(Q)===-1)throw Error(`Unsupported logging level: ${Q}`);Cl=Q}},get logLevel(){return Cl}},Object.defineProperty(Fe,"logLevel",{enumerable:!0})}),Y,Dl=$(()=>{ca(),Y=Fe}),kl,Ll,Rl=$(()=>{kl=(Q,J)=>{let G=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);G.width=Q.dims[3],G.height=Q.dims[2];let H=G.getContext("2d");if(H!=null){let K,z;J?.tensorLayout!==void 0&&J.tensorLayout==="NHWC"?(K=Q.dims[2],z=Q.dims[3]):(K=Q.dims[3],z=Q.dims[2]);let q=J?.format!==void 0?J.format:"RGB",F=J?.norm,D,V;F===void 0||F.mean===void 0?D=[255,255,255,255]:typeof F.mean=="number"?D=[F.mean,F.mean,F.mean,F.mean]:(D=[F.mean[0],F.mean[1],F.mean[2],0],F.mean[3]!==void 0&&(D[3]=F.mean[3])),F===void 0||F.bias===void 0?V=[0,0,0,0]:typeof F.bias=="number"?V=[F.bias,F.bias,F.bias,F.bias]:(V=[F.bias[0],F.bias[1],F.bias[2],0],F.bias[3]!==void 0&&(V[3]=F.bias[3]));let O=z*K,P=0,N=O,I=O*2,R=-1;q==="RGBA"?(P=0,N=O,I=O*2,R=O*3):q==="RGB"?(P=0,N=O,I=O*2):q==="RBG"&&(P=0,I=O,N=O*2);for(let w=0;w<z;w++)for(let E=0;E<K;E++){let T=(Q.data[P++]-V[0])*D[0],y=(Q.data[N++]-V[1])*D[1],x=(Q.data[I++]-V[2])*D[2],b=R===-1?255:(Q.data[R++]-V[3])*D[3];H.fillStyle="rgba("+T+","+y+","+x+","+b+")",H.fillRect(E,w,1,1)}if("toDataURL"in G)return G.toDataURL();throw Error("toDataURL is not supported")}else throw Error("Can not access image data")},Ll=(Q,J)=>{let G=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),H;if(G!=null){let K,z,q;J?.tensorLayout!==void 0&&J.tensorLayout==="NHWC"?(K=Q.dims[2],z=Q.dims[1],q=Q.dims[3]):(K=Q.dims[3],z=Q.dims[2],q=Q.dims[1]);let F=J!==void 0&&J.format!==void 0?J.format:"RGB",D=J?.norm,V,O;D===void 0||D.mean===void 0?V=[255,255,255,255]:typeof D.mean=="number"?V=[D.mean,D.mean,D.mean,D.mean]:(V=[D.mean[0],D.mean[1],D.mean[2],255],D.mean[3]!==void 0&&(V[3]=D.mean[3])),D===void 0||D.bias===void 0?O=[0,0,0,0]:typeof D.bias=="number"?O=[D.bias,D.bias,D.bias,D.bias]:(O=[D.bias[0],D.bias[1],D.bias[2],0],D.bias[3]!==void 0&&(O[3]=D.bias[3]));let P=z*K;if(J!==void 0&&(J.format!==void 0&&q===4&&J.format!=="RGBA"||q===3&&J.format!=="RGB"&&J.format!=="BGR"))throw Error("Tensor format doesn't match input tensor dims");let N=4,I=0,R=1,w=2,E=3,T=0,y=P,x=P*2,b=-1;F==="RGBA"?(T=0,y=P,x=P*2,b=P*3):F==="RGB"?(T=0,y=P,x=P*2):F==="RBG"&&(T=0,x=P,y=P*2),H=G.createImageData(K,z);for(let g=0;g<z*K;I+=N,R+=N,w+=N,E+=N,g++)H.data[I]=(Q.data[T++]-O[0])*V[0],H.data[R]=(Q.data[y++]-O[1])*V[1],H.data[w]=(Q.data[x++]-O[2])*V[2],H.data[E]=b===-1?255:(Q.data[b++]-O[3])*V[3]}else throw Error("Can not access image data");return H}}),da,Nl,zl,Ml,Bl,Fl,Vl=$(()=>{fo(),da=(Q,J)=>{if(Q===void 0)throw Error("Image buffer must be defined");if(J.height===void 0||J.width===void 0)throw Error("Image height and width must be defined");if(J.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:G,width:H}=J,K=J.norm??{mean:255,bias:0},z,q;typeof K.mean=="number"?z=[K.mean,K.mean,K.mean,K.mean]:z=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?q=[K.bias,K.bias,K.bias,K.bias]:q=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];let F=J.format!==void 0?J.format:"RGBA",D=J.tensorFormat!==void 0&&J.tensorFormat!==void 0?J.tensorFormat:"RGB",V=G*H,O=D==="RGBA"?new Float32Array(V*4):new Float32Array(V*3),P=4,N=0,I=1,R=2,w=3,E=0,T=V,y=V*2,x=-1;F==="RGB"&&(P=3,N=0,I=1,R=2,w=-1),D==="RGBA"?x=V*3:D==="RBG"?(E=0,y=V,T=V*2):D==="BGR"&&(y=0,T=V,E=V*2);for(let b=0;b<V;b++,N+=P,R+=P,I+=P,w+=P)O[E++]=(Q[N]+q[0])/z[0],O[T++]=(Q[I]+q[1])/z[1],O[y++]=(Q[R]+q[2])/z[2],x!==-1&&w!==-1&&(O[x++]=(Q[w]+q[3])/z[3]);return D==="RGBA"?new He("float32",O,[1,4,G,H]):new He("float32",O,[1,3,G,H])},Nl=async(Q,J)=>{let G=typeof HTMLImageElement<"u"&&Q instanceof HTMLImageElement,H=typeof ImageData<"u"&&Q instanceof ImageData,K=typeof ImageBitmap<"u"&&Q instanceof ImageBitmap,z=typeof Q=="string",q,F=J??{},D=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw Error("Canvas is not supported")},V=(O)=>typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||O instanceof OffscreenCanvas?O.getContext("2d"):null;if(G){let O=D();O.width=Q.width,O.height=Q.height;let P=V(O);if(P!=null){let{height:N,width:I}=Q;if(J!==void 0&&J.resizedHeight!==void 0&&J.resizedWidth!==void 0&&(N=J.resizedHeight,I=J.resizedWidth),J!==void 0){if(F=J,J.tensorFormat!==void 0)throw Error("Image input config format must be RGBA for HTMLImageElement");F.tensorFormat="RGBA",F.height=N,F.width=I}else F.tensorFormat="RGBA",F.height=N,F.width=I;P.drawImage(Q,0,0),q=P.getImageData(0,0,I,N).data}else throw Error("Can not access image data")}else if(H){let O,P;if(J!==void 0&&J.resizedWidth!==void 0&&J.resizedHeight!==void 0?(O=J.resizedHeight,P=J.resizedWidth):(O=Q.height,P=Q.width),J!==void 0&&(F=J),F.format="RGBA",F.height=O,F.width=P,J!==void 0){let N=D();N.width=P,N.height=O;let I=V(N);if(I!=null)I.putImageData(Q,0,0),q=I.getImageData(0,0,P,O).data;else throw Error("Can not access image data")}else q=Q.data}else if(K){if(J===void 0)throw Error("Please provide image config with format for Imagebitmap");let O=D();O.width=Q.width,O.height=Q.height;let P=V(O);if(P!=null){let{height:N,width:I}=Q;return P.drawImage(Q,0,0,I,N),q=P.getImageData(0,0,I,N).data,F.height=N,F.width=I,da(q,F)}else throw Error("Can not access image data")}else{if(z)return new Promise((O,P)=>{let N=D(),I=V(N);if(!Q||!I)return P();let R=new Image;R.crossOrigin="Anonymous",R.src=Q,R.onload=()=>{N.width=R.width,N.height=R.height,I.drawImage(R,0,0,N.width,N.height);let w=I.getImageData(0,0,N.width,N.height);F.height=N.height,F.width=N.width,O(da(w.data,F))}});throw Error("Input data provided is not supported - aborted tensor creation")}if(q!==void 0)return da(q,F);throw Error("Input data provided is not supported - aborted tensor creation")},zl=(Q,J)=>{let{width:G,height:H,download:K,dispose:z}=J;return new He({location:"texture",type:"float32",texture:Q,dims:[1,H,G,4],download:K,dispose:z})},Ml=(Q,J)=>{let{dataType:G,dims:H,download:K,dispose:z}=J;return new He({location:"gpu-buffer",type:G??"float32",gpuBuffer:Q,dims:H,download:K,dispose:z})},Bl=(Q,J)=>{let{dataType:G,dims:H,download:K,dispose:z}=J;return new He({location:"ml-tensor",type:G??"float32",mlTensor:Q,dims:H,download:K,dispose:z})},Fl=(Q,J,G)=>new He({location:"cpu-pinned",type:Q,data:J,dims:G??[J.length]})}),qn,Dr,Gl,Ul,Wl=$(()=>{qn=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Dr=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Gl=!1,Ul=()=>{if(!Gl){Gl=!0;let Q=typeof BigInt64Array<"u"&&BigInt64Array.from,J=typeof BigUint64Array<"u"&&BigUint64Array.from,G=globalThis.Float16Array,H=typeof G<"u"&&G.from;Q&&(qn.set("int64",BigInt64Array),Dr.set(BigInt64Array,"int64")),J&&(qn.set("uint64",BigUint64Array),Dr.set(BigUint64Array,"uint64")),H?(qn.set("float16",G),Dr.set(G,"float16")):qn.set("float16",Uint16Array)}}}),Hl,ql,jl=$(()=>{fo(),Hl=(Q)=>{let J=1;for(let G=0;G<Q.length;G++){let H=Q[G];if(typeof H!="number"||!Number.isSafeInteger(H))throw TypeError(`dims[${G}] must be an integer, got: ${H}`);if(H<0)throw RangeError(`dims[${G}] must be a non-negative integer, got: ${H}`);J*=H}return J},ql=(Q,J)=>{switch(Q.location){case"cpu":return new He(Q.type,Q.data,J);case"cpu-pinned":return new He({location:"cpu-pinned",data:Q.data,type:Q.type,dims:J});case"texture":return new He({location:"texture",texture:Q.texture,type:Q.type,dims:J});case"gpu-buffer":return new He({location:"gpu-buffer",gpuBuffer:Q.gpuBuffer,type:Q.type,dims:J});case"ml-tensor":return new He({location:"ml-tensor",mlTensor:Q.mlTensor,type:Q.type,dims:J});default:throw Error(`tensorReshape: tensor location ${Q.location} is not supported`)}}}),He,fo=$(()=>{Rl(),Vl(),Wl(),jl(),He=class{constructor(Q,J,G){Ul();let H,K;if(typeof Q=="object"&&"location"in Q)switch(this.dataLocation=Q.location,H=Q.type,K=Q.dims,Q.location){case"cpu-pinned":{let q=qn.get(H);if(!q)throw TypeError(`unsupported type "${H}" to create tensor from pinned buffer`);if(!(Q.data instanceof q))throw TypeError(`buffer should be of type ${q.name}`);this.cpuData=Q.data;break}case"texture":{if(H!=="float32")throw TypeError(`unsupported type "${H}" to create tensor from texture`);this.gpuTextureData=Q.texture,this.downloader=Q.download,this.disposer=Q.dispose;break}case"gpu-buffer":{if(H!=="float32"&&H!=="float16"&&H!=="int32"&&H!=="int64"&&H!=="uint32"&&H!=="uint8"&&H!=="bool"&&H!=="uint4"&&H!=="int4")throw TypeError(`unsupported type "${H}" to create tensor from gpu buffer`);this.gpuBufferData=Q.gpuBuffer,this.downloader=Q.download,this.disposer=Q.dispose;break}case"ml-tensor":{if(H!=="float32"&&H!=="float16"&&H!=="int32"&&H!=="int64"&&H!=="uint32"&&H!=="uint64"&&H!=="int8"&&H!=="uint8"&&H!=="bool"&&H!=="uint4"&&H!=="int4")throw TypeError(`unsupported type "${H}" to create tensor from MLTensor`);this.mlTensorData=Q.mlTensor,this.downloader=Q.download,this.disposer=Q.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let q,F;if(typeof Q=="string")if(H=Q,F=G,Q==="string"){if(!Array.isArray(J))throw TypeError("A string tensor's data must be a string array.");q=J}else{let D=qn.get(Q);if(D===void 0)throw TypeError(`Unsupported tensor type: ${Q}.`);if(Array.isArray(J)){if(Q==="float16"&&D===Uint16Array||Q==="uint4"||Q==="int4")throw TypeError(`Creating a ${Q} tensor from number array is not supported. Please use ${D.name} as data.`);Q==="uint64"||Q==="int64"?q=D.from(J,BigInt):q=D.from(J)}else if(J instanceof D)q=J;else if(J instanceof Uint8ClampedArray)if(Q==="uint8")q=Uint8Array.from(J);else throw TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Q==="float16"&&J instanceof Uint16Array&&D!==Uint16Array)q=new globalThis.Float16Array(J.buffer,J.byteOffset,J.length);else throw TypeError(`A ${H} tensor's data must be type of ${D}`)}else if(F=J,Array.isArray(Q)){if(Q.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let D=typeof Q[0];if(D==="string")H="string",q=Q;else if(D==="boolean")H="bool",q=Uint8Array.from(Q);else throw TypeError(`Invalid element type of data array: ${D}.`)}else if(Q instanceof Uint8ClampedArray)H="uint8",q=Uint8Array.from(Q);else{let D=Dr.get(Q.constructor);if(D===void 0)throw TypeError(`Unsupported type for tensor data: ${Q.constructor}.`);H=D,q=Q}if(F===void 0)F=[q.length];else if(!Array.isArray(F))throw TypeError("A tensor's dims must be a number array");K=F,this.cpuData=q,this.dataLocation="cpu"}let z=Hl(K);if(this.cpuData&&z!==this.cpuData.length&&!((H==="uint4"||H==="int4")&&Math.ceil(z/2)===this.cpuData.length))throw Error(`Tensor's size(${z}) does not match data length(${this.cpuData.length}).`);this.type=H,this.dims=K,this.size=z}static async fromImage(Q,J){return Nl(Q,J)}static fromTexture(Q,J){return zl(Q,J)}static fromGpuBuffer(Q,J){return Ml(Q,J)}static fromMLTensor(Q,J){return Bl(Q,J)}static fromPinnedBuffer(Q,J,G){return Fl(Q,J,G)}toDataURL(Q){return kl(this,Q)}toImageData(Q){return Ll(this,Q)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(Q){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let J=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=J,Q&&this.disposer&&(this.disposer(),this.disposer=void 0),J}finally{this.isDownloading=!1}}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw 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.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw Error("The tensor is disposed.")}reshape(Q){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return ql(this,Q)}}}),et,pa=$(()=>{fo(),et=He}),kr,Kl,tt,Je,In,Sn,fa=$(()=>{ca(),kr=(Q,J)=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||console.timeStamp(`${Q}::ORT::${J}`)},Kl=(Q,J)=>{let G=Error().stack?.split(/\r\n|\r|\n/g)||[],H=!1;for(let K=0;K<G.length;K++){if(H&&!G[K].includes("TRACE_FUNC")){let z=`FUNC_${Q}::${G[K].trim().split(" ")[1]}`;J&&(z+=`::${J}`),kr("CPU",z);return}G[K].includes("TRACE_FUNC")&&(H=!0)}},tt=(Q)=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||Kl("BEGIN",Q)},Je=(Q)=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||Kl("END",Q)},In=(Q)=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||console.time(`ORT::${Q}`)},Sn=(Q)=>{(typeof Fe.trace>"u"?!Fe.wasm.trace:!Fe.trace)||console.timeEnd(`ORT::${Q}`)}}),ho,Xl=$(()=>{la(),pa(),fa(),ho=class Q{constructor(J){this.handler=J}async run(J,G,H){tt(),In("InferenceSession.run");let K={},z={};if(typeof J!="object"||J===null||J instanceof et||Array.isArray(J))throw TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let q=!0;if(typeof G=="object"){if(G===null)throw TypeError("Unexpected argument[1]: cannot be null.");if(G instanceof et)throw TypeError("'fetches' cannot be a Tensor");if(Array.isArray(G)){if(G.length===0)throw TypeError("'fetches' cannot be an empty array.");q=!1;for(let V of G){if(typeof V!="string")throw TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(V)===-1)throw RangeError(`'fetches' contains invalid output name: ${V}.`);K[V]=null}if(typeof H=="object"&&H!==null)z=H;else if(typeof H<"u")throw TypeError("'options' must be an object.")}else{let V=!1,O=Object.getOwnPropertyNames(G);for(let P of this.outputNames)if(O.indexOf(P)!==-1){let N=G[P];(N===null||N instanceof et)&&(V=!0,q=!1,K[P]=N)}if(V){if(typeof H=="object"&&H!==null)z=H;else if(typeof H<"u")throw TypeError("'options' must be an object.")}else z=G}}else if(typeof G<"u")throw TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let V of this.inputNames)if(typeof J[V]>"u")throw Error(`input '${V}' is missing in 'feeds'.`);if(q)for(let V of this.outputNames)K[V]=null;let F=await this.handler.run(J,K,z),D={};for(let V in F)if(Object.hasOwnProperty.call(F,V)){let O=F[V];O instanceof et?D[V]=O:D[V]=new et(O.type,O.data,O.dims)}return Sn("InferenceSession.run"),Je(),D}async release(){return this.handler.dispose()}static async create(J,G,H,K){tt(),In("InferenceSession.create");let z,q={};if(typeof J=="string"){if(z=J,typeof G=="object"&&G!==null)q=G;else if(typeof G<"u")throw TypeError("'options' must be an object.")}else if(J instanceof Uint8Array){if(z=J,typeof G=="object"&&G!==null)q=G;else if(typeof G<"u")throw TypeError("'options' must be an object.")}else if(J instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&J instanceof SharedArrayBuffer){let O=J,P=0,N=J.byteLength;if(typeof G=="object"&&G!==null)q=G;else if(typeof G=="number"){if(P=G,!Number.isSafeInteger(P))throw RangeError("'byteOffset' must be an integer.");if(P<0||P>=O.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${O.byteLength}).`);if(N=J.byteLength-P,typeof H=="number"){if(N=H,!Number.isSafeInteger(N))throw RangeError("'byteLength' must be an integer.");if(N<=0||P+N>O.byteLength)throw RangeError(`'byteLength' is out of range (0, ${O.byteLength-P}].`);if(typeof K=="object"&&K!==null)q=K;else if(typeof K<"u")throw TypeError("'options' must be an object.")}else if(typeof H<"u")throw TypeError("'byteLength' must be a number.")}else if(typeof G<"u")throw TypeError("'options' must be an object.");z=new Uint8Array(O,P,N)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[F,D]=await Al(q),V=await F.createInferenceSessionHandler(z,D);return Sn("InferenceSession.create"),Je(),new Q(V)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Zl,Jl=$(()=>{Xl(),Zl=ho}),Ql=$(()=>{}),Yl=$(()=>{}),ec=$(()=>{}),tc=$(()=>{}),ha={};Wn(ha,{InferenceSession:()=>Zl,TRACE:()=>kr,TRACE_EVENT_BEGIN:()=>In,TRACE_EVENT_END:()=>Sn,TRACE_FUNC_BEGIN:()=>tt,TRACE_FUNC_END:()=>Je,Tensor:()=>et,env:()=>Y,registerBackend:()=>vn});var qe=$(()=>{Pl(),Dl(),Jl(),pa(),Ql(),Yl(),fa(),ec(),tc()});function Cn(Q,J,G,H){if(J===void 0)return kx(Q);if(G===void 0)mo(Q,J,1);else if(typeof G=="number"&&H===void 0)mo(Q,J,G);else if(typeof G=="string"&&H===void 0)mo(Q,G,1,J);else if(typeof G=="string"&&typeof H=="number")mo(Q,G,H,J);else throw TypeError("input is valid")}function kx(Q){return{verbose:Cn.verbose.bind(null,Q),info:Cn.info.bind(null,Q),warning:Cn.warning.bind(null,Q),error:Cn.error.bind(null,Q),fatal:Cn.fatal.bind(null,Q)}}function mo(Q,J,G,H){let K=Lr[H||""]||Lr[""];rc[Q]<rc[K.minimalSeverity]||(K.logDateTime&&(J=`${new Date().toISOString()}|${J}`),K.logSourceLocation,Dx[K.provider].log(Q,J,H))}var ma,ga,rc,Dx,oc,Lr,Te,bo,yo,_o,go,ct=$(()=>{ma=class{log(Q,J,G){}},ga=class{log(Q,J,G){console.log(`${this.color(Q)} ${G?"\x1B[35m"+G+"\x1B[0m ":""}${J}`)}color(Q){switch(Q){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw Error(`unsupported severity: ${Q}`)}}},rc={verbose:1000,info:2000,warning:4000,error:5000,fatal:6000},Dx={none:new ma,console:new ga},oc={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},Lr={"":oc},((Q)=>{function J(V,O){Q("verbose",V,O)}Q.verbose=J;function G(V,O){Q("info",V,O)}Q.info=G;function H(V,O){Q("warning",V,O)}Q.warning=H;function K(V,O){Q("error",V,O)}Q.error=K;function z(V,O){Q("fatal",V,O)}Q.fatal=z;function q(V){Lr={},F("",V||{})}Q.reset=q;function F(V,O){if(V==="*")q(O);else{let P=Lr[V]||oc;Lr[V]={provider:O.provider||P.provider,minimalSeverity:O.minimalSeverity||P.minimalSeverity,logDateTime:O.logDateTime===void 0?P.logDateTime:O.logDateTime,logSourceLocation:O.logSourceLocation===void 0?P.logSourceLocation:O.logSourceLocation}}}Q.set=F;function D(V){let O={};V.logLevel&&(O.minimalSeverity=V.logLevel),F("",O)}Q.setWithEnv=D})(Cn||={}),Te=Cn,bo=class{constructor(Q,J,G,H,K,z){this.category=Q,this.name=J,this.startTime=G,this.endCallback=H,this.timer=K,this.ctx=z}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},yo=class{constructor(Q,J,G,H){this.category=Q,this.name=J,this.startTime=G,this.endTime=H}},_o=class{constructor(Q,J,G){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=Q===void 0?1e4:Q,this._flushBatchSize=J===void 0?10:J,this._flushIntervalInMilliseconds=G===void 0?5000:G}static create(Q){return Q===void 0?new this:new this(Q.maxNumberEvents,Q.flushBatchSize,Q.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=go(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer])}event(Q,J,G,H){let K=this._started?this.begin(Q,J,H):void 0,z=!1,q=G();if(q&&typeof q.then=="function")return z=!0,new Promise((F,D)=>{q.then(async(V)=>{K&&await K.end(),F(V)},async(V)=>{K&&await K.end(),D(V)})});if(!z&&K){let F=K.end();if(F&&typeof F.then=="function")return new Promise((D,V)=>{F.then(()=>{D(q)},(O)=>{V(O)})})}return q}begin(Q,J,G){if(!this._started)throw Error("profiler is not started yet");if(G===void 0){let H=go();return this.flush(H),new bo(Q,J,H,(K)=>this.endSync(K))}else{let H=G.beginTimer();return new bo(Q,J,0,async(K)=>this.end(K),H,G)}}async end(Q){let J=await Q.checkTimer();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new yo(Q.category,Q.name,Q.startTime,J)),this.flush(J))}endSync(Q){let J=go();this._timingEvents.length<this._maxNumberEvents&&(this._timingEvents.push(new yo(Q.category,Q.name,Q.startTime,J)),this.flush(J))}logOneEvent(Q){Te.verbose(`Profiler.${Q.category}`,`${(Q.endTime-Q.startTime).toFixed(2)}ms on event '${Q.name}' at ${Q.endTime.toFixed(2)}`)}flush(Q){if(this._timingEvents.length-this._flushPointer>=this._flushBatchSize||Q-this._flushTime>=this._flushIntervalInMilliseconds){for(let J=this._flushPointer;this._flushPointer<J+this._flushBatchSize&&this._flushPointer<this._timingEvents.length;this._flushPointer++)this.logOneEvent(this._timingEvents[this._flushPointer]);this._flushTime=go()}}get started(){return this._started}},go=typeof performance<"u"&&performance.now?()=>performance.now():Date.now});function ic(Q,J,G){for(let H of G){let K=H[0],z=H[1],q=H[2],F=H[3],D=H[4];if(Q.opType===K){for(let V of J)if((V.domain===z||V.domain==="ai.onnx"&&z==="")&&Lx(V.version,q))return{opImpl:F,opInit:D}}}throw TypeError(`cannot resolve operator '${Q.opType}' with opsets: ${J.map((H)=>`${H.domain||"ai.onnx"} v${H.version}`).join(", ")}`)}function Lx(Q,J){if(J.endsWith("+")){let G=Number.parseInt(J.substring(0,J.length-1),10);return!isNaN(G)&&G<=Q}else if(J.split("-").length===2){let G=J.split("-"),H=Number.parseInt(G[0],10),K=Number.parseInt(G[1],10);return!isNaN(H)&&!isNaN(K)&&H<=Q&&Q<=K}else return Number.parseInt(J,10)===Q}var ac=$(()=>{}),sc=W((Q)=>{Q.__esModule=!0;var J=function(){function G(H){if(!H)throw TypeError("Invalid argument; `value` has no value.");this.value=G.EMPTY,H&&G.isGuid(H)&&(this.value=H)}return G.isGuid=function(H){var K=H.toString();return H&&(H instanceof G||G.validator.test(K))},G.create=function(){return new G([G.gen(2),G.gen(1),G.gen(1),G.gen(1),G.gen(3)].join("-"))},G.createEmpty=function(){return new G("emptyguid")},G.parse=function(H){return new G(H)},G.raw=function(){return[G.gen(2),G.gen(1),G.gen(1),G.gen(1),G.gen(3)].join("-")},G.gen=function(H){for(var K="",z=0;z<H;z++)K+=((1+Math.random())*65536|0).toString(16).substring(1);return K},G.prototype.equals=function(H){return G.isGuid(H)&&this.value===H.toString()},G.prototype.isEmpty=function(){return this.value===G.EMPTY},G.prototype.toString=function(){return this.value},G.prototype.toJSON=function(){return{value:this.value}},G.validator=new RegExp("^[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}$","i"),G.EMPTY="00000000-0000-0000-0000-000000000000",G}();Q.Guid=J});function Pe(Q,J,G){this.low=Q|0,this.high=J|0,this.unsigned=!!G}function Ze(Q){return(Q&&Q.__isLong__)===!0}function uc(Q){var J=Math.clz32(Q&-Q);return Q?31-J:J}function jn(Q,J){var G,H,K;return J?(Q>>>=0,(K=0<=Q&&Q<256)&&(H=cc[Q],H)?H:(G=ye(Q,0,!0),K&&(cc[Q]=G),G)):(Q|=0,(K=-128<=Q&&Q<128)&&(H=lc[Q],H)?H:(G=ye(Q,Q<0?-1:0,!1),K&&(lc[Q]=G),G))}function pt(Q,J){if(isNaN(Q))return J?$n:wt;if(J){if(Q<0)return $n;if(Q>=hc)return bc}else{if(Q<=-pc)return nt;if(Q+1>=pc)return gc}return Q<0?pt(-Q,J).neg():ye(Q%hr|0,Q/hr|0,J)}function ye(Q,J,G){return new Pe(Q,J,G)}function _a(Q,J,G){if(Q.length===0)throw Error("empty string");if(typeof J=="number"?(G=J,J=!1):J=!!J,Q==="NaN"||Q==="Infinity"||Q==="+Infinity"||Q==="-Infinity")return J?$n:wt;if(G=G||10,G<2||36<G)throw RangeError("radix");var H;if((H=Q.indexOf("-"))>0)throw Error("interior hyphen");if(H===0)return _a(Q.substring(1),J,G).neg();for(var K=pt(xo(G,8)),z=wt,q=0;q<Q.length;q+=8){var F=Math.min(8,Q.length-q),D=parseInt(Q.substring(q,q+F),G);if(F<8){var V=pt(xo(G,F));z=z.mul(V).add(pt(D))}else z=z.mul(K),z=z.add(pt(D))}return z.unsigned=J,z}function Tt(Q,J){return typeof Q=="number"?pt(Q,J):typeof Q=="string"?_a(Q,J):ye(Q.low,Q.high,typeof J=="boolean"?J:Q.unsigned)}var dt,lc,cc,xo,dc,Nx,hr,hc,pc,fc,wt,$n,fr,mc,ya,gc,bc,nt,L,Dn,xa=$(()=>{dt=null;try{dt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}Pe.prototype.__isLong__,Object.defineProperty(Pe.prototype,"__isLong__",{value:!0}),Pe.isLong=Ze,lc={},cc={},Pe.fromInt=jn,Pe.fromNumber=pt,Pe.fromBits=ye,xo=Math.pow,Pe.fromString=_a,Pe.fromValue=Tt,dc=65536,Nx=16777216,hr=dc*dc,hc=hr*hr,pc=hc/2,fc=jn(Nx),wt=jn(0),Pe.ZERO=wt,$n=jn(0,!0),Pe.UZERO=$n,fr=jn(1),Pe.ONE=fr,mc=jn(1,!0),Pe.UONE=mc,ya=jn(-1),Pe.NEG_ONE=ya,gc=ye(-1,2147483647,!1),Pe.MAX_VALUE=gc,bc=ye(-1,-1,!0),Pe.MAX_UNSIGNED_VALUE=bc,nt=ye(0,-2147483648,!1),Pe.MIN_VALUE=nt,L=Pe.prototype,L.toInt=function(){return this.unsigned?this.low>>>0:this.low},L.toNumber=function(){return this.unsigned?(this.high>>>0)*hr+(this.low>>>0):this.high*hr+(this.low>>>0)},L.toString=function(Q){if(Q=Q||10,Q<2||36<Q)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(nt)){var J=pt(Q),G=this.div(J),H=G.mul(J).sub(this);return G.toString(Q)+H.toInt().toString(Q)}else return"-"+this.neg().toString(Q);for(var K=pt(xo(Q,6),this.unsigned),z=this,q="";;){var F=z.div(K),D=z.sub(F.mul(K)).toInt()>>>0,V=D.toString(Q);if(z=F,z.isZero())return V+q;for(;V.length<6;)V="0"+V;q=""+V+q}},L.getHighBits=function(){return this.high},L.getHighBitsUnsigned=function(){return this.high>>>0},L.getLowBits=function(){return this.low},L.getLowBitsUnsigned=function(){return this.low>>>0},L.getNumBitsAbs=function(){if(this.isNegative())return this.eq(nt)?64:this.neg().getNumBitsAbs();for(var Q=this.high!=0?this.high:this.low,J=31;J>0&&(Q&1<<J)==0;J--);return this.high!=0?J+33:J+1},L.isZero=function(){return this.high===0&&this.low===0},L.eqz=L.isZero,L.isNegative=function(){return!this.unsigned&&this.high<0},L.isPositive=function(){return this.unsigned||this.high>=0},L.isOdd=function(){return(this.low&1)===1},L.isEven=function(){return(this.low&1)===0},L.equals=function(Q){return Ze(Q)||(Q=Tt(Q)),this.unsigned!==Q.unsigned&&this.high>>>31===1&&Q.high>>>31===1?!1:this.high===Q.high&&this.low===Q.low},L.eq=L.equals,L.notEquals=function(Q){return!this.eq(Q)},L.neq=L.notEquals,L.ne=L.notEquals,L.lessThan=function(Q){return this.comp(Q)<0},L.lt=L.lessThan,L.lessThanOrEqual=function(Q){return this.comp(Q)<=0},L.lte=L.lessThanOrEqual,L.le=L.lessThanOrEqual,L.greaterThan=function(Q){return this.comp(Q)>0},L.gt=L.greaterThan,L.greaterThanOrEqual=function(Q){return this.comp(Q)>=0},L.gte=L.greaterThanOrEqual,L.ge=L.greaterThanOrEqual,L.compare=function(Q){if(Ze(Q)||(Q=Tt(Q)),this.eq(Q))return 0;var J=this.isNegative(),G=Q.isNegative();return J&&!G?-1:!J&&G?1:this.unsigned?Q.high>>>0>this.high>>>0||Q.high===this.high&&Q.low>>>0>this.low>>>0?-1:1:this.sub(Q).isNegative()?-1:1},L.comp=L.compare,L.negate=function(){return!this.unsigned&&this.eq(nt)?nt:this.not().add(fr)},L.neg=L.negate,L.add=function(Q){Ze(Q)||(Q=Tt(Q));var J=this.high>>>16,G=this.high&65535,H=this.low>>>16,K=this.low&65535,z=Q.high>>>16,q=Q.high&65535,F=Q.low>>>16,D=Q.low&65535,V=0,O=0,P=0,N=0;return N+=K+D,P+=N>>>16,N&=65535,P+=H+F,O+=P>>>16,P&=65535,O+=G+q,V+=O>>>16,O&=65535,V+=J+z,V&=65535,ye(P<<16|N,V<<16|O,this.unsigned)},L.subtract=function(Q){return Ze(Q)||(Q=Tt(Q)),this.add(Q.neg())},L.sub=L.subtract,L.multiply=function(Q){if(this.isZero())return this;if(Ze(Q)||(Q=Tt(Q)),dt){var J=dt.mul(this.low,this.high,Q.low,Q.high);return ye(J,dt.get_high(),this.unsigned)}if(Q.isZero())return this.unsigned?$n:wt;if(this.eq(nt))return Q.isOdd()?nt:wt;if(Q.eq(nt))return this.isOdd()?nt:wt;if(this.isNegative())return Q.isNegative()?this.neg().mul(Q.neg()):this.neg().mul(Q).neg();if(Q.isNegative())return this.mul(Q.neg()).neg();if(this.lt(fc)&&Q.lt(fc))return pt(this.toNumber()*Q.toNumber(),this.unsigned);var G=this.high>>>16,H=this.high&65535,K=this.low>>>16,z=this.low&65535,q=Q.high>>>16,F=Q.high&65535,D=Q.low>>>16,V=Q.low&65535,O=0,P=0,N=0,I=0;return I+=z*V,N+=I>>>16,I&=65535,N+=K*V,P+=N>>>16,N&=65535,N+=z*D,P+=N>>>16,N&=65535,P+=H*V,O+=P>>>16,P&=65535,P+=K*D,O+=P>>>16,P&=65535,P+=z*F,O+=P>>>16,P&=65535,O+=G*V+H*D+K*F+z*q,O&=65535,ye(N<<16|I,O<<16|P,this.unsigned)},L.mul=L.multiply,L.divide=function(Q){if(Ze(Q)||(Q=Tt(Q)),Q.isZero())throw Error("division by zero");if(dt){if(!this.unsigned&&this.high===-2147483648&&Q.low===-1&&Q.high===-1)return this;var J=(this.unsigned?dt.div_u:dt.div_s)(this.low,this.high,Q.low,Q.high);return ye(J,dt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?$n:wt;var G,H,K;if(this.unsigned){if(Q.unsigned||(Q=Q.toUnsigned()),Q.gt(this))return $n;if(Q.gt(this.shru(1)))return mc;K=$n}else{if(this.eq(nt)){if(Q.eq(fr)||Q.eq(ya))return nt;if(Q.eq(nt))return fr;var z=this.shr(1);return G=z.div(Q).shl(1),G.eq(wt)?Q.isNegative()?fr:ya:(H=this.sub(Q.mul(G)),K=G.add(H.div(Q)),K)}else if(Q.eq(nt))return this.unsigned?$n:wt;if(this.isNegative())return Q.isNegative()?this.neg().div(Q.neg()):this.neg().div(Q).neg();if(Q.isNegative())return this.div(Q.neg()).neg();K=wt}for(H=this;H.gte(Q);){G=Math.max(1,Math.floor(H.toNumber()/Q.toNumber()));for(var q=Math.ceil(Math.log(G)/Math.LN2),F=q<=48?1:xo(2,q-48),D=pt(G),V=D.mul(Q);V.isNegative()||V.gt(H);)G-=F,D=pt(G,this.unsigned),V=D.mul(Q);D.isZero()&&(D=fr),K=K.add(D),H=H.sub(V)}return K},L.div=L.divide,L.modulo=function(Q){if(Ze(Q)||(Q=Tt(Q)),dt){var J=(this.unsigned?dt.rem_u:dt.rem_s)(this.low,this.high,Q.low,Q.high);return ye(J,dt.get_high(),this.unsigned)}return this.sub(this.div(Q).mul(Q))},L.mod=L.modulo,L.rem=L.modulo,L.not=function(){return ye(~this.low,~this.high,this.unsigned)},L.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},L.clz=L.countLeadingZeros,L.countTrailingZeros=function(){return this.low?uc(this.low):uc(this.high)+32},L.ctz=L.countTrailingZeros,L.and=function(Q){return Ze(Q)||(Q=Tt(Q)),ye(this.low&Q.low,this.high&Q.high,this.unsigned)},L.or=function(Q){return Ze(Q)||(Q=Tt(Q)),ye(this.low|Q.low,this.high|Q.high,this.unsigned)},L.xor=function(Q){return Ze(Q)||(Q=Tt(Q)),ye(this.low^Q.low,this.high^Q.high,this.unsigned)},L.shiftLeft=function(Q){return Ze(Q)&&(Q=Q.toInt()),(Q&=63)===0?this:Q<32?ye(this.low<<Q,this.high<<Q|this.low>>>32-Q,this.unsigned):ye(0,this.low<<Q-32,this.unsigned)},L.shl=L.shiftLeft,L.shiftRight=function(Q){return Ze(Q)&&(Q=Q.toInt()),(Q&=63)===0?this:Q<32?ye(this.low>>>Q|this.high<<32-Q,this.high>>Q,this.unsigned):ye(this.high>>Q-32,this.high>=0?0:-1,this.unsigned)},L.shr=L.shiftRight,L.shiftRightUnsigned=function(Q){return Ze(Q)&&(Q=Q.toInt()),(Q&=63)===0?this:Q<32?ye(this.low>>>Q|this.high<<32-Q,this.high>>>Q,this.unsigned):Q===32?ye(this.high,0,this.unsigned):ye(this.high>>>Q-32,0,this.unsigned)},L.shru=L.shiftRightUnsigned,L.shr_u=L.shiftRightUnsigned,L.rotateLeft=function(Q){var J;return Ze(Q)&&(Q=Q.toInt()),(Q&=63)===0?this:Q===32?ye(this.high,this.low,this.unsigned):Q<32?(J=32-Q,ye(this.low<<Q|this.high>>>J,this.high<<Q|this.low>>>J,this.unsigned)):(Q-=32,J=32-Q,ye(this.high<<Q|this.low>>>J,this.low<<Q|this.high>>>J,this.unsigned))},L.rotl=L.rotateLeft,L.rotateRight=function(Q){var J;return Ze(Q)&&(Q=Q.toInt()),(Q&=63)===0?this:Q===32?ye(this.high,this.low,this.unsigned):Q<32?(J=32-Q,ye(this.high<<J|this.low>>>Q,this.low<<J|this.high>>>Q,this.unsigned)):(Q-=32,J=32-Q,ye(this.low<<J|this.high>>>Q,this.high<<J|this.low>>>Q,this.unsigned))},L.rotr=L.rotateRight,L.toSigned=function(){return this.unsigned?ye(this.low,this.high,!1):this},L.toUnsigned=function(){return this.unsigned?this:ye(this.low,this.high,!0)},L.toBytes=function(Q){return Q?this.toBytesLE():this.toBytesBE()},L.toBytesLE=function(){var Q=this.high,J=this.low;return[J&255,J>>>8&255,J>>>16&255,J>>>24,Q&255,Q>>>8&255,Q>>>16&255,Q>>>24]},L.toBytesBE=function(){var Q=this.high,J=this.low;return[Q>>>24,Q>>>16&255,Q>>>8&255,Q&255,J>>>24,J>>>16&255,J>>>8&255,J&255]},Pe.fromBytes=function(Q,J,G){return G?Pe.fromBytesLE(Q,J):Pe.fromBytesBE(Q,J)},Pe.fromBytesLE=function(Q,J){return new Pe(Q[0]|Q[1]<<8|Q[2]<<16|Q[3]<<24,Q[4]|Q[5]<<8|Q[6]<<16|Q[7]<<24,J)},Pe.fromBytesBE=function(Q,J){return new Pe(Q[4]<<24|Q[5]<<16|Q[6]<<8|Q[7],Q[0]<<24|Q[1]<<16|Q[2]<<8|Q[3],J)},Dn=Pe}),wa=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.ArgType=void 0;var J;(function(G){G[G.INPUT=0]="INPUT",G[G.OUTPUT=1]="OUTPUT"})(J||(Q.ArgType=J={}))}),Kn=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.SIZE_PREFIX_LENGTH=Q.FILE_IDENTIFIER_LENGTH=Q.SIZEOF_INT=Q.SIZEOF_SHORT=void 0,Q.SIZEOF_SHORT=2,Q.SIZEOF_INT=4,Q.FILE_IDENTIFIER_LENGTH=4,Q.SIZE_PREFIX_LENGTH=4}),Ta=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.isLittleEndian=Q.float64=Q.float32=Q.int32=void 0,Q.int32=new Int32Array(2),Q.float32=new Float32Array(Q.int32.buffer),Q.float64=new Float64Array(Q.int32.buffer),Q.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1}),va=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.Encoding=void 0;var J;(function(G){G[G.UTF8_BYTES=1]="UTF8_BYTES",G[G.UTF16_STRING=2]="UTF16_STRING"})(J||(Q.Encoding=J={}))}),Sa=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.ByteBuffer=void 0;var J=Kn(),G=Ta(),H=va(),K=class z{constructor(q){this.bytes_=q,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(q){return new z(new Uint8Array(q))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(q){this.position_=q}capacity(){return this.bytes_.length}readInt8(q){return this.readUint8(q)<<24>>24}readUint8(q){return this.bytes_[q]}readInt16(q){return this.readUint16(q)<<16>>16}readUint16(q){return this.bytes_[q]|this.bytes_[q+1]<<8}readInt32(q){return this.bytes_[q]|this.bytes_[q+1]<<8|this.bytes_[q+2]<<16|this.bytes_[q+3]<<24}readUint32(q){return this.readInt32(q)>>>0}readInt64(q){return BigInt.asIntN(64,BigInt(this.readUint32(q))+(BigInt(this.readUint32(q+4))<<BigInt(32)))}readUint64(q){return BigInt.asUintN(64,BigInt(this.readUint32(q))+(BigInt(this.readUint32(q+4))<<BigInt(32)))}readFloat32(q){return G.int32[0]=this.readInt32(q),G.float32[0]}readFloat64(q){return G.int32[G.isLittleEndian?0:1]=this.readInt32(q),G.int32[G.isLittleEndian?1:0]=this.readInt32(q+4),G.float64[0]}writeInt8(q,F){this.bytes_[q]=F}writeUint8(q,F){this.bytes_[q]=F}writeInt16(q,F){this.bytes_[q]=F,this.bytes_[q+1]=F>>8}writeUint16(q,F){this.bytes_[q]=F,this.bytes_[q+1]=F>>8}writeInt32(q,F){this.bytes_[q]=F,this.bytes_[q+1]=F>>8,this.bytes_[q+2]=F>>16,this.bytes_[q+3]=F>>24}writeUint32(q,F){this.bytes_[q]=F,this.bytes_[q+1]=F>>8,this.bytes_[q+2]=F>>16,this.bytes_[q+3]=F>>24}writeInt64(q,F){this.writeInt32(q,Number(BigInt.asIntN(32,F))),this.writeInt32(q+4,Number(BigInt.asIntN(32,F>>BigInt(32))))}writeUint64(q,F){this.writeUint32(q,Number(BigInt.asUintN(32,F))),this.writeUint32(q+4,Number(BigInt.asUintN(32,F>>BigInt(32))))}writeFloat32(q,F){G.float32[0]=F,this.writeInt32(q,G.int32[0])}writeFloat64(q,F){G.float64[0]=F,this.writeInt32(q,G.int32[G.isLittleEndian?0:1]),this.writeInt32(q+4,G.int32[G.isLittleEndian?1:0])}getBufferIdentifier(){if(this.bytes_.length<this.position_+J.SIZEOF_INT+J.FILE_IDENTIFIER_LENGTH)throw Error("FlatBuffers: ByteBuffer is too short to contain an identifier.");let q="";for(let F=0;F<J.FILE_IDENTIFIER_LENGTH;F++)q+=String.fromCharCode(this.readInt8(this.position_+J.SIZEOF_INT+F));return q}__offset(q,F){let D=q-this.readInt32(q);return F<this.readInt16(D)?this.readInt16(D+F):0}__union(q,F){return q.bb_pos=F+this.readInt32(F),q.bb=this,q}__string(q,F){q+=this.readInt32(q);let D=this.readInt32(q);q+=J.SIZEOF_INT;let V=this.bytes_.subarray(q,q+D);return F===H.Encoding.UTF8_BYTES?V:this.text_decoder_.decode(V)}__union_with_string(q,F){return typeof q=="string"?this.__string(F):this.__union(q,F)}__indirect(q){return q+this.readInt32(q)}__vector(q){return q+this.readInt32(q)+J.SIZEOF_INT}__vector_len(q){return this.readInt32(q+this.readInt32(q))}__has_identifier(q){if(q.length!=J.FILE_IDENTIFIER_LENGTH)throw Error("FlatBuffers: file identifier must be length "+J.FILE_IDENTIFIER_LENGTH);for(let F=0;F<J.FILE_IDENTIFIER_LENGTH;F++)if(q.charCodeAt(F)!=this.readInt8(this.position()+J.SIZEOF_INT+F))return!1;return!0}createScalarList(q,F){let D=[];for(let V=0;V<F;++V){let O=q(V);O!==null&&D.push(O)}return D}createObjList(q,F){let D=[];for(let V=0;V<F;++V){let O=q(V);O!==null&&D.push(O.unpack())}return D}};Q.ByteBuffer=K}),wc=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.Builder=void 0;var J=Sa(),G=Kn(),H=class K{constructor(z){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let q;z?q=z:q=1024,this.bb=J.ByteBuffer.allocate(q),this.space=q}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(z){this.force_defaults=z}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(z,q){z>this.minalign&&(this.minalign=z);let F=~(this.bb.capacity()-this.space+q)+1&z-1;for(;this.space<F+z+q;){let D=this.bb.capacity();this.bb=K.growByteBuffer(this.bb),this.space+=this.bb.capacity()-D}this.pad(F)}pad(z){for(let q=0;q<z;q++)this.bb.writeInt8(--this.space,0)}writeInt8(z){this.bb.writeInt8(this.space-=1,z)}writeInt16(z){this.bb.writeInt16(this.space-=2,z)}writeInt32(z){this.bb.writeInt32(this.space-=4,z)}writeInt64(z){this.bb.writeInt64(this.space-=8,z)}writeFloat32(z){this.bb.writeFloat32(this.space-=4,z)}writeFloat64(z){this.bb.writeFloat64(this.space-=8,z)}addInt8(z){this.prep(1,0),this.writeInt8(z)}addInt16(z){this.prep(2,0),this.writeInt16(z)}addInt32(z){this.prep(4,0),this.writeInt32(z)}addInt64(z){this.prep(8,0),this.writeInt64(z)}addFloat32(z){this.prep(4,0),this.writeFloat32(z)}addFloat64(z){this.prep(8,0),this.writeFloat64(z)}addFieldInt8(z,q,F){(this.force_defaults||q!=F)&&(this.addInt8(q),this.slot(z))}addFieldInt16(z,q,F){(this.force_defaults||q!=F)&&(this.addInt16(q),this.slot(z))}addFieldInt32(z,q,F){(this.force_defaults||q!=F)&&(this.addInt32(q),this.slot(z))}addFieldInt64(z,q,F){(this.force_defaults||q!==F)&&(this.addInt64(q),this.slot(z))}addFieldFloat32(z,q,F){(this.force_defaults||q!=F)&&(this.addFloat32(q),this.slot(z))}addFieldFloat64(z,q,F){(this.force_defaults||q!=F)&&(this.addFloat64(q),this.slot(z))}addFieldOffset(z,q,F){(this.force_defaults||q!=F)&&(this.addOffset(q),this.slot(z))}addFieldStruct(z,q,F){q!=F&&(this.nested(q),this.slot(z))}nested(z){if(z!=this.offset())throw TypeError("FlatBuffers: struct must be serialized inline.")}notNested(){if(this.isNested)throw TypeError("FlatBuffers: object serialization must not be nested.")}slot(z){this.vtable!==null&&(this.vtable[z]=this.offset())}offset(){return this.bb.capacity()-this.space}static growByteBuffer(z){let q=z.capacity();if(q&3221225472)throw Error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.");let F=q<<1,D=J.ByteBuffer.allocate(F);return D.setPosition(F-q),D.bytes().set(z.bytes(),F-q),D}addOffset(z){this.prep(G.SIZEOF_INT,0),this.writeInt32(this.offset()-z+G.SIZEOF_INT)}startObject(z){this.notNested(),this.vtable==null&&(this.vtable=[]),this.vtable_in_use=z;for(let q=0;q<z;q++)this.vtable[q]=0;this.isNested=!0,this.object_start=this.offset()}endObject(){if(this.vtable==null||!this.isNested)throw Error("FlatBuffers: endObject called without startObject");this.addInt32(0);let z=this.offset(),q=this.vtable_in_use-1;for(;q>=0&&this.vtable[q]==0;q--);let F=q+1;for(;q>=0;q--)this.addInt16(this.vtable[q]!=0?z-this.vtable[q]:0);let D=2;this.addInt16(z-this.object_start);let V=(F+D)*G.SIZEOF_SHORT;this.addInt16(V);let O=0,P=this.space;Q:for(q=0;q<this.vtables.length;q++){let N=this.bb.capacity()-this.vtables[q];if(V==this.bb.readInt16(N)){for(let I=G.SIZEOF_SHORT;I<V;I+=G.SIZEOF_SHORT)if(this.bb.readInt16(P+I)!=this.bb.readInt16(N+I))continue Q;O=this.vtables[q];break}}return O?(this.space=this.bb.capacity()-z,this.bb.writeInt32(this.space,O-z)):(this.vtables.push(this.offset()),this.bb.writeInt32(this.bb.capacity()-z,this.offset()-z)),this.isNested=!1,z}finish(z,q,F){let D=F?G.SIZE_PREFIX_LENGTH:0;if(q){let V=q;if(this.prep(this.minalign,G.SIZEOF_INT+G.FILE_IDENTIFIER_LENGTH+D),V.length!=G.FILE_IDENTIFIER_LENGTH)throw TypeError("FlatBuffers: file identifier must be length "+G.FILE_IDENTIFIER_LENGTH);for(let O=G.FILE_IDENTIFIER_LENGTH-1;O>=0;O--)this.writeInt8(V.charCodeAt(O))}this.prep(this.minalign,G.SIZEOF_INT+D),this.addOffset(z),D&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(z,q){this.finish(z,q,!0)}requiredField(z,q){let F=this.bb.capacity()-z,D=F-this.bb.readInt32(F);if(!(q<this.bb.readInt16(D)&&this.bb.readInt16(D+q)!=0))throw TypeError("FlatBuffers: field "+q+" must be set")}startVector(z,q,F){this.notNested(),this.vector_num_elems=q,this.prep(G.SIZEOF_INT,z*q),this.prep(F,z*q)}endVector(){return this.writeInt32(this.vector_num_elems),this.offset()}createSharedString(z){if(!z)return 0;if(this.string_maps||(this.string_maps=new Map),this.string_maps.has(z))return this.string_maps.get(z);let q=this.createString(z);return this.string_maps.set(z,q),q}createString(z){if(z==null)return 0;let q;return z instanceof Uint8Array?q=z:q=this.text_encoder.encode(z),this.addInt8(0),this.startVector(1,q.length,1),this.bb.setPosition(this.space-=q.length),this.bb.bytes().set(q,this.space),this.endVector()}createByteVector(z){return z==null?0:(this.startVector(1,z.length,1),this.bb.setPosition(this.space-=z.length),this.bb.bytes().set(z,this.space),this.endVector())}createObjectOffset(z){return z===null?0:typeof z=="string"?this.createString(z):z.pack(this)}createObjectOffsetList(z){let q=[];for(let F=0;F<z.length;++F){let D=z[F];if(D!==null)q.push(this.createObjectOffset(D));else throw TypeError("FlatBuffers: Argument for createObjectOffsetList cannot contain null.")}return q}createStructOffsetList(z,q){return q(this,z.length),this.createObjectOffsetList(z.slice().reverse()),this.endVector()}};Q.Builder=H}),_e=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.ByteBuffer=Q.Builder=Q.Encoding=Q.isLittleEndian=Q.float64=Q.float32=Q.int32=Q.SIZE_PREFIX_LENGTH=Q.FILE_IDENTIFIER_LENGTH=Q.SIZEOF_INT=Q.SIZEOF_SHORT=void 0;var J=Kn();Object.defineProperty(Q,"SIZEOF_SHORT",{enumerable:!0,get:function(){return J.SIZEOF_SHORT}});var G=Kn();Object.defineProperty(Q,"SIZEOF_INT",{enumerable:!0,get:function(){return G.SIZEOF_INT}});var H=Kn();Object.defineProperty(Q,"FILE_IDENTIFIER_LENGTH",{enumerable:!0,get:function(){return H.FILE_IDENTIFIER_LENGTH}});var K=Kn();Object.defineProperty(Q,"SIZE_PREFIX_LENGTH",{enumerable:!0,get:function(){return K.SIZE_PREFIX_LENGTH}});var z=Ta();Object.defineProperty(Q,"int32",{enumerable:!0,get:function(){return z.int32}}),Object.defineProperty(Q,"float32",{enumerable:!0,get:function(){return z.float32}}),Object.defineProperty(Q,"float64",{enumerable:!0,get:function(){return z.float64}}),Object.defineProperty(Q,"isLittleEndian",{enumerable:!0,get:function(){return z.isLittleEndian}});var q=va();Object.defineProperty(Q,"Encoding",{enumerable:!0,get:function(){return q.Encoding}});var F=wc();Object.defineProperty(Q,"Builder",{enumerable:!0,get:function(){return F.Builder}});var D=Sa();Object.defineProperty(Q,"ByteBuffer",{enumerable:!0,get:function(){return D.ByteBuffer}})}),Pa=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.ArgTypeAndIndex=void 0;var K=H(_e()),z=wa(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsArgTypeAndIndex(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsArgTypeAndIndex(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}argType(){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.readInt8(this.bb_pos+D):z.ArgType.INPUT}index(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.readUint32(this.bb_pos+D):0}static startArgTypeAndIndex(D){D.startObject(2)}static addArgType(D,V){D.addFieldInt8(0,V,z.ArgType.INPUT)}static addIndex(D,V){D.addFieldInt32(1,V,0)}static endArgTypeAndIndex(D){return D.endObject()}static createArgTypeAndIndex(D,V,O){return F.startArgTypeAndIndex(D),F.addArgType(D,V),F.addIndex(D,O),F.endArgTypeAndIndex(D)}};Q.ArgTypeAndIndex=q}),Oa=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.AttributeType=void 0;var J;(function(G){G[G.UNDEFINED=0]="UNDEFINED",G[G.FLOAT=1]="FLOAT",G[G.INT=2]="INT",G[G.STRING=3]="STRING",G[G.TENSOR=4]="TENSOR",G[G.GRAPH=5]="GRAPH",G[G.FLOATS=6]="FLOATS",G[G.INTS=7]="INTS",G[G.STRINGS=8]="STRINGS",G[G.TENSORS=9]="TENSORS",G[G.GRAPHS=10]="GRAPHS",G[G.SPARSE_TENSOR=11]="SPARSE_TENSOR",G[G.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(J||(Q.AttributeType=J={}))}),Ea=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.NodeType=void 0;var J;(function(G){G[G.Primitive=0]="Primitive",G[G.Fused=1]="Fused"})(J||(Q.NodeType=J={}))}),Da=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(D,V,O,P){P===void 0&&(P=O);var N=Object.getOwnPropertyDescriptor(V,O);(!N||("get"in N?!V.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return V[O]}}),Object.defineProperty(D,P,N)}:function(D,V,O,P){P===void 0&&(P=O),D[P]=V[O]}),G=Q&&Q.__setModuleDefault||(Object.create?function(D,V){Object.defineProperty(D,"default",{enumerable:!0,value:V})}:function(D,V){D.default=V}),H=Q&&Q.__importStar||function(D){if(D&&D.__esModule)return D;var V={};if(D!=null)for(var O in D)O!=="default"&&Object.prototype.hasOwnProperty.call(D,O)&&J(V,D,O);return G(V,D),V};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Node=void 0;var K=H(_e()),z=ka(),q=Ea(),F=class D{constructor(){this.bb=null,this.bb_pos=0}__init(V,O){return this.bb_pos=V,this.bb=O,this}static getRootAsNode(V,O){return(O||new D).__init(V.readInt32(V.position())+V.position(),V)}static getSizePrefixedRootAsNode(V,O){return V.setPosition(V.position()+K.SIZE_PREFIX_LENGTH),(O||new D).__init(V.readInt32(V.position())+V.position(),V)}name(V){let O=this.bb.__offset(this.bb_pos,4);return O?this.bb.__string(this.bb_pos+O,V):null}docString(V){let O=this.bb.__offset(this.bb_pos,6);return O?this.bb.__string(this.bb_pos+O,V):null}domain(V){let O=this.bb.__offset(this.bb_pos,8);return O?this.bb.__string(this.bb_pos+O,V):null}sinceVersion(){let V=this.bb.__offset(this.bb_pos,10);return V?this.bb.readInt32(this.bb_pos+V):0}index(){let V=this.bb.__offset(this.bb_pos,12);return V?this.bb.readUint32(this.bb_pos+V):0}opType(V){let O=this.bb.__offset(this.bb_pos,14);return O?this.bb.__string(this.bb_pos+O,V):null}type(){let V=this.bb.__offset(this.bb_pos,16);return V?this.bb.readInt32(this.bb_pos+V):q.NodeType.Primitive}executionProviderType(V){let O=this.bb.__offset(this.bb_pos,18);return O?this.bb.__string(this.bb_pos+O,V):null}inputs(V,O){let P=this.bb.__offset(this.bb_pos,20);return P?this.bb.__string(this.bb.__vector(this.bb_pos+P)+V*4,O):null}inputsLength(){let V=this.bb.__offset(this.bb_pos,20);return V?this.bb.__vector_len(this.bb_pos+V):0}outputs(V,O){let P=this.bb.__offset(this.bb_pos,22);return P?this.bb.__string(this.bb.__vector(this.bb_pos+P)+V*4,O):null}outputsLength(){let V=this.bb.__offset(this.bb_pos,22);return V?this.bb.__vector_len(this.bb_pos+V):0}attributes(V,O){let P=this.bb.__offset(this.bb_pos,24);return P?(O||new z.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+P)+V*4),this.bb):null}attributesLength(){let V=this.bb.__offset(this.bb_pos,24);return V?this.bb.__vector_len(this.bb_pos+V):0}inputArgCounts(V){let O=this.bb.__offset(this.bb_pos,26);return O?this.bb.readInt32(this.bb.__vector(this.bb_pos+O)+V*4):0}inputArgCountsLength(){let V=this.bb.__offset(this.bb_pos,26);return V?this.bb.__vector_len(this.bb_pos+V):0}inputArgCountsArray(){let V=this.bb.__offset(this.bb_pos,26);return V?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+V),this.bb.__vector_len(this.bb_pos+V)):null}implicitInputs(V,O){let P=this.bb.__offset(this.bb_pos,28);return P?this.bb.__string(this.bb.__vector(this.bb_pos+P)+V*4,O):null}implicitInputsLength(){let V=this.bb.__offset(this.bb_pos,28);return V?this.bb.__vector_len(this.bb_pos+V):0}static startNode(V){V.startObject(13)}static addName(V,O){V.addFieldOffset(0,O,0)}static addDocString(V,O){V.addFieldOffset(1,O,0)}static addDomain(V,O){V.addFieldOffset(2,O,0)}static addSinceVersion(V,O){V.addFieldInt32(3,O,0)}static addIndex(V,O){V.addFieldInt32(4,O,0)}static addOpType(V,O){V.addFieldOffset(5,O,0)}static addType(V,O){V.addFieldInt32(6,O,q.NodeType.Primitive)}static addExecutionProviderType(V,O){V.addFieldOffset(7,O,0)}static addInputs(V,O){V.addFieldOffset(8,O,0)}static createInputsVector(V,O){V.startVector(4,O.length,4);for(let P=O.length-1;P>=0;P--)V.addOffset(O[P]);return V.endVector()}static startInputsVector(V,O){V.startVector(4,O,4)}static addOutputs(V,O){V.addFieldOffset(9,O,0)}static createOutputsVector(V,O){V.startVector(4,O.length,4);for(let P=O.length-1;P>=0;P--)V.addOffset(O[P]);return V.endVector()}static startOutputsVector(V,O){V.startVector(4,O,4)}static addAttributes(V,O){V.addFieldOffset(10,O,0)}static createAttributesVector(V,O){V.startVector(4,O.length,4);for(let P=O.length-1;P>=0;P--)V.addOffset(O[P]);return V.endVector()}static startAttributesVector(V,O){V.startVector(4,O,4)}static addInputArgCounts(V,O){V.addFieldOffset(11,O,0)}static createInputArgCountsVector(V,O){V.startVector(4,O.length,4);for(let P=O.length-1;P>=0;P--)V.addInt32(O[P]);return V.endVector()}static startInputArgCountsVector(V,O){V.startVector(4,O,4)}static addImplicitInputs(V,O){V.addFieldOffset(12,O,0)}static createImplicitInputsVector(V,O){V.startVector(4,O.length,4);for(let P=O.length-1;P>=0;P--)V.addOffset(O[P]);return V.endVector()}static startImplicitInputsVector(V,O){V.startVector(4,O,4)}static endNode(V){return V.endObject()}static createNode(V,O,P,N,I,R,w,E,T,y,x,b,g,l){return D.startNode(V),D.addName(V,O),D.addDocString(V,P),D.addDomain(V,N),D.addSinceVersion(V,I),D.addIndex(V,R),D.addOpType(V,w),D.addType(V,E),D.addExecutionProviderType(V,T),D.addInputs(V,y),D.addOutputs(V,x),D.addAttributes(V,b),D.addInputArgCounts(V,g),D.addImplicitInputs(V,l),D.endNode(V)}};Q.Node=F}),Ra=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.EdgeEnd=void 0;var J=class{constructor(){this.bb=null,this.bb_pos=0}__init(G,H){return this.bb_pos=G,this.bb=H,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static sizeOf(){return 12}static createEdgeEnd(G,H,K,z){return G.prep(4,12),G.writeInt32(z),G.writeInt32(K),G.writeInt32(H),G.offset()}};Q.EdgeEnd=J}),za=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.NodeEdge=void 0;var K=H(_e()),z=Ra(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsNodeEdge(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsNodeEdge(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}nodeIndex(){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.readUint32(this.bb_pos+D):0}inputEdges(D,V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new z.EdgeEnd).__init(this.bb.__vector(this.bb_pos+O)+D*12,this.bb):null}inputEdgesLength(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.__vector_len(this.bb_pos+D):0}outputEdges(D,V){let O=this.bb.__offset(this.bb_pos,8);return O?(V||new z.EdgeEnd).__init(this.bb.__vector(this.bb_pos+O)+D*12,this.bb):null}outputEdgesLength(){let D=this.bb.__offset(this.bb_pos,8);return D?this.bb.__vector_len(this.bb_pos+D):0}static startNodeEdge(D){D.startObject(3)}static addNodeIndex(D,V){D.addFieldInt32(0,V,0)}static addInputEdges(D,V){D.addFieldOffset(1,V,0)}static startInputEdgesVector(D,V){D.startVector(12,V,4)}static addOutputEdges(D,V){D.addFieldOffset(2,V,0)}static startOutputEdgesVector(D,V){D.startVector(12,V,4)}static endNodeEdge(D){return D.endObject()}static createNodeEdge(D,V,O,P){return F.startNodeEdge(D),F.addNodeIndex(D,V),F.addInputEdges(D,O),F.addOutputEdges(D,P),F.endNodeEdge(D)}};Q.NodeEdge=q}),Ba=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(q,F,D,V){V===void 0&&(V=D);var O=Object.getOwnPropertyDescriptor(F,D);(!O||("get"in O?!F.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return F[D]}}),Object.defineProperty(q,V,O)}:function(q,F,D,V){V===void 0&&(V=D),q[V]=F[D]}),G=Q&&Q.__setModuleDefault||(Object.create?function(q,F){Object.defineProperty(q,"default",{enumerable:!0,value:F})}:function(q,F){q.default=F}),H=Q&&Q.__importStar||function(q){if(q&&q.__esModule)return q;var F={};if(q!=null)for(var D in q)D!=="default"&&Object.prototype.hasOwnProperty.call(q,D)&&J(F,q,D);return G(F,q),F};Object.defineProperty(Q,"__esModule",{value:!0}),Q.NodesToOptimizeIndices=void 0;var K=H(_e()),z=class q{constructor(){this.bb=null,this.bb_pos=0}__init(F,D){return this.bb_pos=F,this.bb=D,this}static getRootAsNodesToOptimizeIndices(F,D){return(D||new q).__init(F.readInt32(F.position())+F.position(),F)}static getSizePrefixedRootAsNodesToOptimizeIndices(F,D){return F.setPosition(F.position()+K.SIZE_PREFIX_LENGTH),(D||new q).__init(F.readInt32(F.position())+F.position(),F)}nodeIndices(F){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.readUint32(this.bb.__vector(this.bb_pos+D)+F*4):0}nodeIndicesLength(){let F=this.bb.__offset(this.bb_pos,4);return F?this.bb.__vector_len(this.bb_pos+F):0}nodeIndicesArray(){let F=this.bb.__offset(this.bb_pos,4);return F?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+F),this.bb.__vector_len(this.bb_pos+F)):null}numInputs(){let F=this.bb.__offset(this.bb_pos,6);return F?this.bb.readUint32(this.bb_pos+F):0}numOutputs(){let F=this.bb.__offset(this.bb_pos,8);return F?this.bb.readUint32(this.bb_pos+F):0}hasVariadicInput(){let F=this.bb.__offset(this.bb_pos,10);return F?!!this.bb.readInt8(this.bb_pos+F):!1}hasVariadicOutput(){let F=this.bb.__offset(this.bb_pos,12);return F?!!this.bb.readInt8(this.bb_pos+F):!1}numVariadicInputs(){let F=this.bb.__offset(this.bb_pos,14);return F?this.bb.readUint32(this.bb_pos+F):0}numVariadicOutputs(){let F=this.bb.__offset(this.bb_pos,16);return F?this.bb.readUint32(this.bb_pos+F):0}static startNodesToOptimizeIndices(F){F.startObject(7)}static addNodeIndices(F,D){F.addFieldOffset(0,D,0)}static createNodeIndicesVector(F,D){F.startVector(4,D.length,4);for(let V=D.length-1;V>=0;V--)F.addInt32(D[V]);return F.endVector()}static startNodeIndicesVector(F,D){F.startVector(4,D,4)}static addNumInputs(F,D){F.addFieldInt32(1,D,0)}static addNumOutputs(F,D){F.addFieldInt32(2,D,0)}static addHasVariadicInput(F,D){F.addFieldInt8(3,+D,0)}static addHasVariadicOutput(F,D){F.addFieldInt8(4,+D,0)}static addNumVariadicInputs(F,D){F.addFieldInt32(5,D,0)}static addNumVariadicOutputs(F,D){F.addFieldInt32(6,D,0)}static endNodesToOptimizeIndices(F){return F.endObject()}static createNodesToOptimizeIndices(F,D,V,O,P,N,I,R){return q.startNodesToOptimizeIndices(F),q.addNodeIndices(F,D),q.addNumInputs(F,V),q.addNumOutputs(F,O),q.addHasVariadicInput(F,P),q.addHasVariadicOutput(F,N),q.addNumVariadicInputs(F,I),q.addNumVariadicOutputs(F,R),q.endNodesToOptimizeIndices(F)}};Q.NodesToOptimizeIndices=z}),Va=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.RuntimeOptimizationRecord=void 0;var K=H(_e()),z=Ba(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsRuntimeOptimizationRecord(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsRuntimeOptimizationRecord(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}actionId(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}nodesToOptimizeIndices(D){let V=this.bb.__offset(this.bb_pos,6);return V?(D||new z.NodesToOptimizeIndices).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}producedOpIds(D,V){let O=this.bb.__offset(this.bb_pos,10);return O?this.bb.__string(this.bb.__vector(this.bb_pos+O)+D*4,V):null}producedOpIdsLength(){let D=this.bb.__offset(this.bb_pos,10);return D?this.bb.__vector_len(this.bb_pos+D):0}static startRuntimeOptimizationRecord(D){D.startObject(4)}static addActionId(D,V){D.addFieldOffset(0,V,0)}static addNodesToOptimizeIndices(D,V){D.addFieldOffset(1,V,0)}static addProducedOpIds(D,V){D.addFieldOffset(3,V,0)}static createProducedOpIdsVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startProducedOpIdsVector(D,V){D.startVector(4,V,4)}static endRuntimeOptimizationRecord(D){return D.endObject()}};Q.RuntimeOptimizationRecord=q}),Ua=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.RuntimeOptimizationRecordContainerEntry=void 0;var K=H(_e()),z=Va(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsRuntimeOptimizationRecordContainerEntry(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsRuntimeOptimizationRecordContainerEntry(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}optimizerName(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}runtimeOptimizationRecords(D,V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new z.RuntimeOptimizationRecord).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+O)+D*4),this.bb):null}runtimeOptimizationRecordsLength(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.__vector_len(this.bb_pos+D):0}static startRuntimeOptimizationRecordContainerEntry(D){D.startObject(2)}static addOptimizerName(D,V){D.addFieldOffset(0,V,0)}static addRuntimeOptimizationRecords(D,V){D.addFieldOffset(1,V,0)}static createRuntimeOptimizationRecordsVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startRuntimeOptimizationRecordsVector(D,V){D.startVector(4,V,4)}static endRuntimeOptimizationRecordContainerEntry(D){let V=D.endObject();return D.requiredField(V,4),V}static createRuntimeOptimizationRecordContainerEntry(D,V,O){return F.startRuntimeOptimizationRecordContainerEntry(D),F.addOptimizerName(D,V),F.addRuntimeOptimizationRecords(D,O),F.endRuntimeOptimizationRecordContainerEntry(D)}};Q.RuntimeOptimizationRecordContainerEntry=q}),Ha=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.RuntimeOptimizations=void 0;var K=H(_e()),z=Ua(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsRuntimeOptimizations(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsRuntimeOptimizations(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}records(D,V){let O=this.bb.__offset(this.bb_pos,4);return O?(V||new z.RuntimeOptimizationRecordContainerEntry).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+O)+D*4),this.bb):null}recordsLength(){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.__vector_len(this.bb_pos+D):0}static startRuntimeOptimizations(D){D.startObject(1)}static addRecords(D,V){D.addFieldOffset(0,V,0)}static createRecordsVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startRecordsVector(D,V){D.startVector(4,V,4)}static endRuntimeOptimizations(D){return D.endObject()}static createRuntimeOptimizations(D,V){return F.startRuntimeOptimizations(D),F.addRecords(D,V),F.endRuntimeOptimizations(D)}};Q.RuntimeOptimizations=q}),Rr=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.TensorDataType=void 0;var J;(function(G){G[G.UNDEFINED=0]="UNDEFINED",G[G.FLOAT=1]="FLOAT",G[G.UINT8=2]="UINT8",G[G.INT8=3]="INT8",G[G.UINT16=4]="UINT16",G[G.INT16=5]="INT16",G[G.INT32=6]="INT32",G[G.INT64=7]="INT64",G[G.STRING=8]="STRING",G[G.BOOL=9]="BOOL",G[G.FLOAT16=10]="FLOAT16",G[G.DOUBLE=11]="DOUBLE",G[G.UINT32=12]="UINT32",G[G.UINT64=13]="UINT64",G[G.COMPLEX64=14]="COMPLEX64",G[G.COMPLEX128=15]="COMPLEX128",G[G.BFLOAT16=16]="BFLOAT16",G[G.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",G[G.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",G[G.FLOAT8E5M2=19]="FLOAT8E5M2",G[G.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"})(J||(Q.TensorDataType=J={}))}),Nr=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Tensor=void 0;var K=H(_e()),z=Rr(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsTensor(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsTensor(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}name(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}docString(D){let V=this.bb.__offset(this.bb_pos,6);return V?this.bb.__string(this.bb_pos+V,D):null}dims(D){let V=this.bb.__offset(this.bb_pos,8);return V?this.bb.readInt64(this.bb.__vector(this.bb_pos+V)+D*8):BigInt(0)}dimsLength(){let D=this.bb.__offset(this.bb_pos,8);return D?this.bb.__vector_len(this.bb_pos+D):0}dataType(){let D=this.bb.__offset(this.bb_pos,10);return D?this.bb.readInt32(this.bb_pos+D):z.TensorDataType.UNDEFINED}rawData(D){let V=this.bb.__offset(this.bb_pos,12);return V?this.bb.readUint8(this.bb.__vector(this.bb_pos+V)+D):0}rawDataLength(){let D=this.bb.__offset(this.bb_pos,12);return D?this.bb.__vector_len(this.bb_pos+D):0}rawDataArray(){let D=this.bb.__offset(this.bb_pos,12);return D?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+D),this.bb.__vector_len(this.bb_pos+D)):null}stringData(D,V){let O=this.bb.__offset(this.bb_pos,14);return O?this.bb.__string(this.bb.__vector(this.bb_pos+O)+D*4,V):null}stringDataLength(){let D=this.bb.__offset(this.bb_pos,14);return D?this.bb.__vector_len(this.bb_pos+D):0}externalDataOffset(){let D=this.bb.__offset(this.bb_pos,16);return D?this.bb.readInt64(this.bb_pos+D):BigInt("-1")}static startTensor(D){D.startObject(7)}static addName(D,V){D.addFieldOffset(0,V,0)}static addDocString(D,V){D.addFieldOffset(1,V,0)}static addDims(D,V){D.addFieldOffset(2,V,0)}static createDimsVector(D,V){D.startVector(8,V.length,8);for(let O=V.length-1;O>=0;O--)D.addInt64(V[O]);return D.endVector()}static startDimsVector(D,V){D.startVector(8,V,8)}static addDataType(D,V){D.addFieldInt32(3,V,z.TensorDataType.UNDEFINED)}static addRawData(D,V){D.addFieldOffset(4,V,0)}static createRawDataVector(D,V){D.startVector(1,V.length,1);for(let O=V.length-1;O>=0;O--)D.addInt8(V[O]);return D.endVector()}static startRawDataVector(D,V){D.startVector(1,V,1)}static addStringData(D,V){D.addFieldOffset(5,V,0)}static createStringDataVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startStringDataVector(D,V){D.startVector(4,V,4)}static addExternalDataOffset(D,V){D.addFieldInt64(6,V,BigInt("-1"))}static endTensor(D){return D.endObject()}static createTensor(D,V,O,P,N,I,R,w){return F.startTensor(D),F.addName(D,V),F.addDocString(D,O),F.addDims(D,P),F.addDataType(D,N),F.addRawData(D,I),F.addStringData(D,R),F.addExternalDataOffset(D,w),F.endTensor(D)}};Q.Tensor=q}),Ka=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.SparseTensor=void 0;var K=H(_e()),z=Nr(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsSparseTensor(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsSparseTensor(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}values(D){let V=this.bb.__offset(this.bb_pos,4);return V?(D||new z.Tensor).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}indices(D){let V=this.bb.__offset(this.bb_pos,6);return V?(D||new z.Tensor).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}dims(D){let V=this.bb.__offset(this.bb_pos,8);return V?this.bb.readInt64(this.bb.__vector(this.bb_pos+V)+D*8):BigInt(0)}dimsLength(){let D=this.bb.__offset(this.bb_pos,8);return D?this.bb.__vector_len(this.bb_pos+D):0}static startSparseTensor(D){D.startObject(3)}static addValues(D,V){D.addFieldOffset(0,V,0)}static addIndices(D,V){D.addFieldOffset(1,V,0)}static addDims(D,V){D.addFieldOffset(2,V,0)}static createDimsVector(D,V){D.startVector(8,V.length,8);for(let O=V.length-1;O>=0;O--)D.addInt64(V[O]);return D.endVector()}static startDimsVector(D,V){D.startVector(8,V,8)}static endSparseTensor(D){return D.endObject()}};Q.SparseTensor=q}),Za=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(D,V,O,P){P===void 0&&(P=O);var N=Object.getOwnPropertyDescriptor(V,O);(!N||("get"in N?!V.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return V[O]}}),Object.defineProperty(D,P,N)}:function(D,V,O,P){P===void 0&&(P=O),D[P]=V[O]}),G=Q&&Q.__setModuleDefault||(Object.create?function(D,V){Object.defineProperty(D,"default",{enumerable:!0,value:V})}:function(D,V){D.default=V}),H=Q&&Q.__importStar||function(D){if(D&&D.__esModule)return D;var V={};if(D!=null)for(var O in D)O!=="default"&&Object.prototype.hasOwnProperty.call(D,O)&&J(V,D,O);return G(V,D),V};Object.defineProperty(Q,"__esModule",{value:!0}),Q.MapType=void 0;var K=H(_e()),z=Rr(),q=zr(),F=class D{constructor(){this.bb=null,this.bb_pos=0}__init(V,O){return this.bb_pos=V,this.bb=O,this}static getRootAsMapType(V,O){return(O||new D).__init(V.readInt32(V.position())+V.position(),V)}static getSizePrefixedRootAsMapType(V,O){return V.setPosition(V.position()+K.SIZE_PREFIX_LENGTH),(O||new D).__init(V.readInt32(V.position())+V.position(),V)}keyType(){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.readInt32(this.bb_pos+V):z.TensorDataType.UNDEFINED}valueType(V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new q.TypeInfo).__init(this.bb.__indirect(this.bb_pos+O),this.bb):null}static startMapType(V){V.startObject(2)}static addKeyType(V,O){V.addFieldInt32(0,O,z.TensorDataType.UNDEFINED)}static addValueType(V,O){V.addFieldOffset(1,O,0)}static endMapType(V){return V.endObject()}};Q.MapType=F}),Qa=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.SequenceType=void 0;var K=H(_e()),z=zr(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsSequenceType(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsSequenceType(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}elemType(D){let V=this.bb.__offset(this.bb_pos,4);return V?(D||new z.TypeInfo).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}static startSequenceType(D){D.startObject(1)}static addElemType(D,V){D.addFieldOffset(0,V,0)}static endSequenceType(D){return D.endObject()}static createSequenceType(D,V){return F.startSequenceType(D),F.addElemType(D,V),F.endSequenceType(D)}};Q.SequenceType=q}),Ya=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.DimensionValueType=void 0;var J;(function(G){G[G.UNKNOWN=0]="UNKNOWN",G[G.VALUE=1]="VALUE",G[G.PARAM=2]="PARAM"})(J||(Q.DimensionValueType=J={}))}),ts=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.DimensionValue=void 0;var K=H(_e()),z=Ya(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsDimensionValue(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsDimensionValue(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}dimType(){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.readInt8(this.bb_pos+D):z.DimensionValueType.UNKNOWN}dimValue(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.readInt64(this.bb_pos+D):BigInt("0")}dimParam(D){let V=this.bb.__offset(this.bb_pos,8);return V?this.bb.__string(this.bb_pos+V,D):null}static startDimensionValue(D){D.startObject(3)}static addDimType(D,V){D.addFieldInt8(0,V,z.DimensionValueType.UNKNOWN)}static addDimValue(D,V){D.addFieldInt64(1,V,BigInt("0"))}static addDimParam(D,V){D.addFieldOffset(2,V,0)}static endDimensionValue(D){return D.endObject()}static createDimensionValue(D,V,O,P){return F.startDimensionValue(D),F.addDimType(D,V),F.addDimValue(D,O),F.addDimParam(D,P),F.endDimensionValue(D)}};Q.DimensionValue=q}),rs=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Dimension=void 0;var K=H(_e()),z=ts(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsDimension(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsDimension(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}value(D){let V=this.bb.__offset(this.bb_pos,4);return V?(D||new z.DimensionValue).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}denotation(D){let V=this.bb.__offset(this.bb_pos,6);return V?this.bb.__string(this.bb_pos+V,D):null}static startDimension(D){D.startObject(2)}static addValue(D,V){D.addFieldOffset(0,V,0)}static addDenotation(D,V){D.addFieldOffset(1,V,0)}static endDimension(D){return D.endObject()}static createDimension(D,V,O){return F.startDimension(D),F.addValue(D,V),F.addDenotation(D,O),F.endDimension(D)}};Q.Dimension=q}),is=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Shape=void 0;var K=H(_e()),z=rs(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsShape(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsShape(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}dim(D,V){let O=this.bb.__offset(this.bb_pos,4);return O?(V||new z.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+O)+D*4),this.bb):null}dimLength(){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.__vector_len(this.bb_pos+D):0}static startShape(D){D.startObject(1)}static addDim(D,V){D.addFieldOffset(0,V,0)}static createDimVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startDimVector(D,V){D.startVector(4,V,4)}static endShape(D){return D.endObject()}static createShape(D,V){return F.startShape(D),F.addDim(D,V),F.endShape(D)}};Q.Shape=q}),ss=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(D,V,O,P){P===void 0&&(P=O);var N=Object.getOwnPropertyDescriptor(V,O);(!N||("get"in N?!V.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return V[O]}}),Object.defineProperty(D,P,N)}:function(D,V,O,P){P===void 0&&(P=O),D[P]=V[O]}),G=Q&&Q.__setModuleDefault||(Object.create?function(D,V){Object.defineProperty(D,"default",{enumerable:!0,value:V})}:function(D,V){D.default=V}),H=Q&&Q.__importStar||function(D){if(D&&D.__esModule)return D;var V={};if(D!=null)for(var O in D)O!=="default"&&Object.prototype.hasOwnProperty.call(D,O)&&J(V,D,O);return G(V,D),V};Object.defineProperty(Q,"__esModule",{value:!0}),Q.TensorTypeAndShape=void 0;var K=H(_e()),z=is(),q=Rr(),F=class D{constructor(){this.bb=null,this.bb_pos=0}__init(V,O){return this.bb_pos=V,this.bb=O,this}static getRootAsTensorTypeAndShape(V,O){return(O||new D).__init(V.readInt32(V.position())+V.position(),V)}static getSizePrefixedRootAsTensorTypeAndShape(V,O){return V.setPosition(V.position()+K.SIZE_PREFIX_LENGTH),(O||new D).__init(V.readInt32(V.position())+V.position(),V)}elemType(){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.readInt32(this.bb_pos+V):q.TensorDataType.UNDEFINED}shape(V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new z.Shape).__init(this.bb.__indirect(this.bb_pos+O),this.bb):null}static startTensorTypeAndShape(V){V.startObject(2)}static addElemType(V,O){V.addFieldInt32(0,O,q.TensorDataType.UNDEFINED)}static addShape(V,O){V.addFieldOffset(1,O,0)}static endTensorTypeAndShape(V){return V.endObject()}};Q.TensorTypeAndShape=F}),us=W((Q)=>{Object.defineProperty(Q,"__esModule",{value:!0}),Q.unionListToTypeInfoValue=Q.unionToTypeInfoValue=Q.TypeInfoValue=void 0;var J=Za(),G=Qa(),H=ss(),K;(function(F){F[F.NONE=0]="NONE",F[F.tensor_type=1]="tensor_type",F[F.sequence_type=2]="sequence_type",F[F.map_type=3]="map_type"})(K||(Q.TypeInfoValue=K={}));function z(F,D){switch(K[F]){case"NONE":return null;case"tensor_type":return D(new H.TensorTypeAndShape);case"sequence_type":return D(new G.SequenceType);case"map_type":return D(new J.MapType);default:return null}}Q.unionToTypeInfoValue=z;function q(F,D,V){switch(K[F]){case"NONE":return null;case"tensor_type":return D(V,new H.TensorTypeAndShape);case"sequence_type":return D(V,new G.SequenceType);case"map_type":return D(V,new J.MapType);default:return null}}Q.unionListToTypeInfoValue=q}),zr=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.TypeInfo=void 0;var K=H(_e()),z=us(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsTypeInfo(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsTypeInfo(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}denotation(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}valueType(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.readUint8(this.bb_pos+D):z.TypeInfoValue.NONE}value(D){let V=this.bb.__offset(this.bb_pos,8);return V?this.bb.__union(D,this.bb_pos+V):null}static startTypeInfo(D){D.startObject(3)}static addDenotation(D,V){D.addFieldOffset(0,V,0)}static addValueType(D,V){D.addFieldInt8(1,V,z.TypeInfoValue.NONE)}static addValue(D,V){D.addFieldOffset(2,V,0)}static endTypeInfo(D){return D.endObject()}static createTypeInfo(D,V,O,P){return F.startTypeInfo(D),F.addDenotation(D,V),F.addValueType(D,O),F.addValue(D,P),F.endTypeInfo(D)}};Q.TypeInfo=q}),ds=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.ValueInfo=void 0;var K=H(_e()),z=zr(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsValueInfo(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsValueInfo(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}name(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}docString(D){let V=this.bb.__offset(this.bb_pos,6);return V?this.bb.__string(this.bb_pos+V,D):null}type(D){let V=this.bb.__offset(this.bb_pos,8);return V?(D||new z.TypeInfo).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}static startValueInfo(D){D.startObject(3)}static addName(D,V){D.addFieldOffset(0,V,0)}static addDocString(D,V){D.addFieldOffset(1,V,0)}static addType(D,V){D.addFieldOffset(2,V,0)}static endValueInfo(D){return D.endObject()}};Q.ValueInfo=q}),Do=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(N,I,R,w){w===void 0&&(w=R);var E=Object.getOwnPropertyDescriptor(I,R);(!E||("get"in E?!I.__esModule:E.writable||E.configurable))&&(E={enumerable:!0,get:function(){return I[R]}}),Object.defineProperty(N,w,E)}:function(N,I,R,w){w===void 0&&(w=R),N[w]=I[R]}),G=Q&&Q.__setModuleDefault||(Object.create?function(N,I){Object.defineProperty(N,"default",{enumerable:!0,value:I})}:function(N,I){N.default=I}),H=Q&&Q.__importStar||function(N){if(N&&N.__esModule)return N;var I={};if(N!=null)for(var R in N)R!=="default"&&Object.prototype.hasOwnProperty.call(N,R)&&J(I,N,R);return G(I,N),I};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Graph=void 0;var K=H(_e()),z=Da(),q=za(),F=Ha(),D=Ka(),V=Nr(),O=ds(),P=class N{constructor(){this.bb=null,this.bb_pos=0}__init(I,R){return this.bb_pos=I,this.bb=R,this}static getRootAsGraph(I,R){return(R||new N).__init(I.readInt32(I.position())+I.position(),I)}static getSizePrefixedRootAsGraph(I,R){return I.setPosition(I.position()+K.SIZE_PREFIX_LENGTH),(R||new N).__init(I.readInt32(I.position())+I.position(),I)}initializers(I,R){let w=this.bb.__offset(this.bb_pos,4);return w?(R||new V.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+w)+I*4),this.bb):null}initializersLength(){let I=this.bb.__offset(this.bb_pos,4);return I?this.bb.__vector_len(this.bb_pos+I):0}nodeArgs(I,R){let w=this.bb.__offset(this.bb_pos,6);return w?(R||new O.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+w)+I*4),this.bb):null}nodeArgsLength(){let I=this.bb.__offset(this.bb_pos,6);return I?this.bb.__vector_len(this.bb_pos+I):0}nodes(I,R){let w=this.bb.__offset(this.bb_pos,8);return w?(R||new z.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+w)+I*4),this.bb):null}nodesLength(){let I=this.bb.__offset(this.bb_pos,8);return I?this.bb.__vector_len(this.bb_pos+I):0}maxNodeIndex(){let I=this.bb.__offset(this.bb_pos,10);return I?this.bb.readUint32(this.bb_pos+I):0}nodeEdges(I,R){let w=this.bb.__offset(this.bb_pos,12);return w?(R||new q.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+w)+I*4),this.bb):null}nodeEdgesLength(){let I=this.bb.__offset(this.bb_pos,12);return I?this.bb.__vector_len(this.bb_pos+I):0}inputs(I,R){let w=this.bb.__offset(this.bb_pos,14);return w?this.bb.__string(this.bb.__vector(this.bb_pos+w)+I*4,R):null}inputsLength(){let I=this.bb.__offset(this.bb_pos,14);return I?this.bb.__vector_len(this.bb_pos+I):0}outputs(I,R){let w=this.bb.__offset(this.bb_pos,16);return w?this.bb.__string(this.bb.__vector(this.bb_pos+w)+I*4,R):null}outputsLength(){let I=this.bb.__offset(this.bb_pos,16);return I?this.bb.__vector_len(this.bb_pos+I):0}sparseInitializers(I,R){let w=this.bb.__offset(this.bb_pos,18);return w?(R||new D.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+w)+I*4),this.bb):null}sparseInitializersLength(){let I=this.bb.__offset(this.bb_pos,18);return I?this.bb.__vector_len(this.bb_pos+I):0}runtimeOptimizations(I){let R=this.bb.__offset(this.bb_pos,20);return R?(I||new F.RuntimeOptimizations).__init(this.bb.__indirect(this.bb_pos+R),this.bb):null}static startGraph(I){I.startObject(9)}static addInitializers(I,R){I.addFieldOffset(0,R,0)}static createInitializersVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startInitializersVector(I,R){I.startVector(4,R,4)}static addNodeArgs(I,R){I.addFieldOffset(1,R,0)}static createNodeArgsVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startNodeArgsVector(I,R){I.startVector(4,R,4)}static addNodes(I,R){I.addFieldOffset(2,R,0)}static createNodesVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startNodesVector(I,R){I.startVector(4,R,4)}static addMaxNodeIndex(I,R){I.addFieldInt32(3,R,0)}static addNodeEdges(I,R){I.addFieldOffset(4,R,0)}static createNodeEdgesVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startNodeEdgesVector(I,R){I.startVector(4,R,4)}static addInputs(I,R){I.addFieldOffset(5,R,0)}static createInputsVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startInputsVector(I,R){I.startVector(4,R,4)}static addOutputs(I,R){I.addFieldOffset(6,R,0)}static createOutputsVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startOutputsVector(I,R){I.startVector(4,R,4)}static addSparseInitializers(I,R){I.addFieldOffset(7,R,0)}static createSparseInitializersVector(I,R){I.startVector(4,R.length,4);for(let w=R.length-1;w>=0;w--)I.addOffset(R[w]);return I.endVector()}static startSparseInitializersVector(I,R){I.startVector(4,R,4)}static addRuntimeOptimizations(I,R){I.addFieldOffset(8,R,0)}static endGraph(I){return I.endObject()}};Q.Graph=P}),ka=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(V,O,P,N){N===void 0&&(N=P);var I=Object.getOwnPropertyDescriptor(O,P);(!I||("get"in I?!O.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return O[P]}}),Object.defineProperty(V,N,I)}:function(V,O,P,N){N===void 0&&(N=P),V[N]=O[P]}),G=Q&&Q.__setModuleDefault||(Object.create?function(V,O){Object.defineProperty(V,"default",{enumerable:!0,value:O})}:function(V,O){V.default=O}),H=Q&&Q.__importStar||function(V){if(V&&V.__esModule)return V;var O={};if(V!=null)for(var P in V)P!=="default"&&Object.prototype.hasOwnProperty.call(V,P)&&J(O,V,P);return G(O,V),O};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Attribute=void 0;var K=H(_e()),z=Oa(),q=Do(),F=Nr(),D=class V{constructor(){this.bb=null,this.bb_pos=0}__init(O,P){return this.bb_pos=O,this.bb=P,this}static getRootAsAttribute(O,P){return(P||new V).__init(O.readInt32(O.position())+O.position(),O)}static getSizePrefixedRootAsAttribute(O,P){return O.setPosition(O.position()+K.SIZE_PREFIX_LENGTH),(P||new V).__init(O.readInt32(O.position())+O.position(),O)}name(O){let P=this.bb.__offset(this.bb_pos,4);return P?this.bb.__string(this.bb_pos+P,O):null}docString(O){let P=this.bb.__offset(this.bb_pos,6);return P?this.bb.__string(this.bb_pos+P,O):null}type(){let O=this.bb.__offset(this.bb_pos,8);return O?this.bb.readInt32(this.bb_pos+O):z.AttributeType.UNDEFINED}f(){let O=this.bb.__offset(this.bb_pos,10);return O?this.bb.readFloat32(this.bb_pos+O):0}i(){let O=this.bb.__offset(this.bb_pos,12);return O?this.bb.readInt64(this.bb_pos+O):BigInt("0")}s(O){let P=this.bb.__offset(this.bb_pos,14);return P?this.bb.__string(this.bb_pos+P,O):null}t(O){let P=this.bb.__offset(this.bb_pos,16);return P?(O||new F.Tensor).__init(this.bb.__indirect(this.bb_pos+P),this.bb):null}g(O){let P=this.bb.__offset(this.bb_pos,18);return P?(O||new q.Graph).__init(this.bb.__indirect(this.bb_pos+P),this.bb):null}floats(O){let P=this.bb.__offset(this.bb_pos,20);return P?this.bb.readFloat32(this.bb.__vector(this.bb_pos+P)+O*4):0}floatsLength(){let O=this.bb.__offset(this.bb_pos,20);return O?this.bb.__vector_len(this.bb_pos+O):0}floatsArray(){let O=this.bb.__offset(this.bb_pos,20);return O?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+O),this.bb.__vector_len(this.bb_pos+O)):null}ints(O){let P=this.bb.__offset(this.bb_pos,22);return P?this.bb.readInt64(this.bb.__vector(this.bb_pos+P)+O*8):BigInt(0)}intsLength(){let O=this.bb.__offset(this.bb_pos,22);return O?this.bb.__vector_len(this.bb_pos+O):0}strings(O,P){let N=this.bb.__offset(this.bb_pos,24);return N?this.bb.__string(this.bb.__vector(this.bb_pos+N)+O*4,P):null}stringsLength(){let O=this.bb.__offset(this.bb_pos,24);return O?this.bb.__vector_len(this.bb_pos+O):0}tensors(O,P){let N=this.bb.__offset(this.bb_pos,26);return N?(P||new F.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+N)+O*4),this.bb):null}tensorsLength(){let O=this.bb.__offset(this.bb_pos,26);return O?this.bb.__vector_len(this.bb_pos+O):0}graphs(O,P){let N=this.bb.__offset(this.bb_pos,28);return N?(P||new q.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+N)+O*4),this.bb):null}graphsLength(){let O=this.bb.__offset(this.bb_pos,28);return O?this.bb.__vector_len(this.bb_pos+O):0}static startAttribute(O){O.startObject(13)}static addName(O,P){O.addFieldOffset(0,P,0)}static addDocString(O,P){O.addFieldOffset(1,P,0)}static addType(O,P){O.addFieldInt32(2,P,z.AttributeType.UNDEFINED)}static addF(O,P){O.addFieldFloat32(3,P,0)}static addI(O,P){O.addFieldInt64(4,P,BigInt("0"))}static addS(O,P){O.addFieldOffset(5,P,0)}static addT(O,P){O.addFieldOffset(6,P,0)}static addG(O,P){O.addFieldOffset(7,P,0)}static addFloats(O,P){O.addFieldOffset(8,P,0)}static createFloatsVector(O,P){O.startVector(4,P.length,4);for(let N=P.length-1;N>=0;N--)O.addFloat32(P[N]);return O.endVector()}static startFloatsVector(O,P){O.startVector(4,P,4)}static addInts(O,P){O.addFieldOffset(9,P,0)}static createIntsVector(O,P){O.startVector(8,P.length,8);for(let N=P.length-1;N>=0;N--)O.addInt64(P[N]);return O.endVector()}static startIntsVector(O,P){O.startVector(8,P,8)}static addStrings(O,P){O.addFieldOffset(10,P,0)}static createStringsVector(O,P){O.startVector(4,P.length,4);for(let N=P.length-1;N>=0;N--)O.addOffset(P[N]);return O.endVector()}static startStringsVector(O,P){O.startVector(4,P,4)}static addTensors(O,P){O.addFieldOffset(11,P,0)}static createTensorsVector(O,P){O.startVector(4,P.length,4);for(let N=P.length-1;N>=0;N--)O.addOffset(P[N]);return O.endVector()}static startTensorsVector(O,P){O.startVector(4,P,4)}static addGraphs(O,P){O.addFieldOffset(12,P,0)}static createGraphsVector(O,P){O.startVector(4,P.length,4);for(let N=P.length-1;N>=0;N--)O.addOffset(P[N]);return O.endVector()}static startGraphsVector(O,P){O.startVector(4,P,4)}static endAttribute(O){return O.endObject()}};Q.Attribute=D}),ms=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(q,F,D,V){V===void 0&&(V=D);var O=Object.getOwnPropertyDescriptor(F,D);(!O||("get"in O?!F.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return F[D]}}),Object.defineProperty(q,V,O)}:function(q,F,D,V){V===void 0&&(V=D),q[V]=F[D]}),G=Q&&Q.__setModuleDefault||(Object.create?function(q,F){Object.defineProperty(q,"default",{enumerable:!0,value:F})}:function(q,F){q.default=F}),H=Q&&Q.__importStar||function(q){if(q&&q.__esModule)return q;var F={};if(q!=null)for(var D in q)D!=="default"&&Object.prototype.hasOwnProperty.call(q,D)&&J(F,q,D);return G(F,q),F};Object.defineProperty(Q,"__esModule",{value:!0}),Q.DeprecatedKernelCreateInfos=void 0;var K=H(_e()),z=class q{constructor(){this.bb=null,this.bb_pos=0}__init(F,D){return this.bb_pos=F,this.bb=D,this}static getRootAsDeprecatedKernelCreateInfos(F,D){return(D||new q).__init(F.readInt32(F.position())+F.position(),F)}static getSizePrefixedRootAsDeprecatedKernelCreateInfos(F,D){return F.setPosition(F.position()+K.SIZE_PREFIX_LENGTH),(D||new q).__init(F.readInt32(F.position())+F.position(),F)}nodeIndices(F){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.readUint32(this.bb.__vector(this.bb_pos+D)+F*4):0}nodeIndicesLength(){let F=this.bb.__offset(this.bb_pos,4);return F?this.bb.__vector_len(this.bb_pos+F):0}nodeIndicesArray(){let F=this.bb.__offset(this.bb_pos,4);return F?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+F),this.bb.__vector_len(this.bb_pos+F)):null}kernelDefHashes(F){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.readUint64(this.bb.__vector(this.bb_pos+D)+F*8):BigInt(0)}kernelDefHashesLength(){let F=this.bb.__offset(this.bb_pos,6);return F?this.bb.__vector_len(this.bb_pos+F):0}static startDeprecatedKernelCreateInfos(F){F.startObject(2)}static addNodeIndices(F,D){F.addFieldOffset(0,D,0)}static createNodeIndicesVector(F,D){F.startVector(4,D.length,4);for(let V=D.length-1;V>=0;V--)F.addInt32(D[V]);return F.endVector()}static startNodeIndicesVector(F,D){F.startVector(4,D,4)}static addKernelDefHashes(F,D){F.addFieldOffset(1,D,0)}static createKernelDefHashesVector(F,D){F.startVector(8,D.length,8);for(let V=D.length-1;V>=0;V--)F.addInt64(D[V]);return F.endVector()}static startKernelDefHashesVector(F,D){F.startVector(8,D,8)}static endDeprecatedKernelCreateInfos(F){return F.endObject()}static createDeprecatedKernelCreateInfos(F,D,V){return q.startDeprecatedKernelCreateInfos(F),q.addNodeIndices(F,D),q.addKernelDefHashes(F,V),q.endDeprecatedKernelCreateInfos(F)}};Q.DeprecatedKernelCreateInfos=z}),Vc=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(q,F,D,V){V===void 0&&(V=D);var O=Object.getOwnPropertyDescriptor(F,D);(!O||("get"in O?!F.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return F[D]}}),Object.defineProperty(q,V,O)}:function(q,F,D,V){V===void 0&&(V=D),q[V]=F[D]}),G=Q&&Q.__setModuleDefault||(Object.create?function(q,F){Object.defineProperty(q,"default",{enumerable:!0,value:F})}:function(q,F){q.default=F}),H=Q&&Q.__importStar||function(q){if(q&&q.__esModule)return q;var F={};if(q!=null)for(var D in q)D!=="default"&&Object.prototype.hasOwnProperty.call(q,D)&&J(F,q,D);return G(F,q),F};Object.defineProperty(Q,"__esModule",{value:!0}),Q.DeprecatedNodeIndexAndKernelDefHash=void 0;var K=H(_e()),z=class q{constructor(){this.bb=null,this.bb_pos=0}__init(F,D){return this.bb_pos=F,this.bb=D,this}static getRootAsDeprecatedNodeIndexAndKernelDefHash(F,D){return(D||new q).__init(F.readInt32(F.position())+F.position(),F)}static getSizePrefixedRootAsDeprecatedNodeIndexAndKernelDefHash(F,D){return F.setPosition(F.position()+K.SIZE_PREFIX_LENGTH),(D||new q).__init(F.readInt32(F.position())+F.position(),F)}nodeIndex(){let F=this.bb.__offset(this.bb_pos,4);return F?this.bb.readUint32(this.bb_pos+F):0}kernelDefHash(){let F=this.bb.__offset(this.bb_pos,6);return F?this.bb.readUint64(this.bb_pos+F):BigInt("0")}static startDeprecatedNodeIndexAndKernelDefHash(F){F.startObject(2)}static addNodeIndex(F,D){F.addFieldInt32(0,D,0)}static addKernelDefHash(F,D){F.addFieldInt64(1,D,BigInt("0"))}static endDeprecatedNodeIndexAndKernelDefHash(F){return F.endObject()}static createDeprecatedNodeIndexAndKernelDefHash(F,D,V){return q.startDeprecatedNodeIndexAndKernelDefHash(F),q.addNodeIndex(F,D),q.addKernelDefHash(F,V),q.endDeprecatedNodeIndexAndKernelDefHash(F)}};Q.DeprecatedNodeIndexAndKernelDefHash=z}),ys=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.DeprecatedSubGraphSessionState=void 0;var K=H(_e()),z=_s(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsDeprecatedSubGraphSessionState(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsDeprecatedSubGraphSessionState(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}graphId(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}sessionState(D){let V=this.bb.__offset(this.bb_pos,6);return V?(D||new z.DeprecatedSessionState).__init(this.bb.__indirect(this.bb_pos+V),this.bb):null}static startDeprecatedSubGraphSessionState(D){D.startObject(2)}static addGraphId(D,V){D.addFieldOffset(0,V,0)}static addSessionState(D,V){D.addFieldOffset(1,V,0)}static endDeprecatedSubGraphSessionState(D){let V=D.endObject();return D.requiredField(V,4),V}};Q.DeprecatedSubGraphSessionState=q}),_s=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(D,V,O,P){P===void 0&&(P=O);var N=Object.getOwnPropertyDescriptor(V,O);(!N||("get"in N?!V.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return V[O]}}),Object.defineProperty(D,P,N)}:function(D,V,O,P){P===void 0&&(P=O),D[P]=V[O]}),G=Q&&Q.__setModuleDefault||(Object.create?function(D,V){Object.defineProperty(D,"default",{enumerable:!0,value:V})}:function(D,V){D.default=V}),H=Q&&Q.__importStar||function(D){if(D&&D.__esModule)return D;var V={};if(D!=null)for(var O in D)O!=="default"&&Object.prototype.hasOwnProperty.call(D,O)&&J(V,D,O);return G(V,D),V};Object.defineProperty(Q,"__esModule",{value:!0}),Q.DeprecatedSessionState=void 0;var K=H(_e()),z=ms(),q=ys(),F=class D{constructor(){this.bb=null,this.bb_pos=0}__init(V,O){return this.bb_pos=V,this.bb=O,this}static getRootAsDeprecatedSessionState(V,O){return(O||new D).__init(V.readInt32(V.position())+V.position(),V)}static getSizePrefixedRootAsDeprecatedSessionState(V,O){return V.setPosition(V.position()+K.SIZE_PREFIX_LENGTH),(O||new D).__init(V.readInt32(V.position())+V.position(),V)}kernels(V){let O=this.bb.__offset(this.bb_pos,4);return O?(V||new z.DeprecatedKernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+O),this.bb):null}subGraphSessionStates(V,O){let P=this.bb.__offset(this.bb_pos,6);return P?(O||new q.DeprecatedSubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+P)+V*4),this.bb):null}subGraphSessionStatesLength(){let V=this.bb.__offset(this.bb_pos,6);return V?this.bb.__vector_len(this.bb_pos+V):0}static startDeprecatedSessionState(V){V.startObject(2)}static addKernels(V,O){V.addFieldOffset(0,O,0)}static addSubGraphSessionStates(V,O){V.addFieldOffset(1,O,0)}static createSubGraphSessionStatesVector(V,O){V.startVector(4,O.length,4);for(let P=O.length-1;P>=0;P--)V.addOffset(O[P]);return V.endVector()}static startSubGraphSessionStatesVector(V,O){V.startVector(4,O,4)}static endDeprecatedSessionState(V){return V.endObject()}static createDeprecatedSessionState(V,O,P){return D.startDeprecatedSessionState(V),D.addKernels(V,O),D.addSubGraphSessionStates(V,P),D.endDeprecatedSessionState(V)}};Q.DeprecatedSessionState=F}),Ts=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.KernelTypeStrArgsEntry=void 0;var K=H(_e()),z=Pa(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsKernelTypeStrArgsEntry(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsKernelTypeStrArgsEntry(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}kernelTypeStr(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}args(D,V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new z.ArgTypeAndIndex).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+O)+D*4),this.bb):null}argsLength(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.__vector_len(this.bb_pos+D):0}static startKernelTypeStrArgsEntry(D){D.startObject(2)}static addKernelTypeStr(D,V){D.addFieldOffset(0,V,0)}static addArgs(D,V){D.addFieldOffset(1,V,0)}static createArgsVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startArgsVector(D,V){D.startVector(4,V,4)}static endKernelTypeStrArgsEntry(D){let V=D.endObject();return D.requiredField(V,4),V}static createKernelTypeStrArgsEntry(D,V,O){return F.startKernelTypeStrArgsEntry(D),F.addKernelTypeStr(D,V),F.addArgs(D,O),F.endKernelTypeStrArgsEntry(D)}};Q.KernelTypeStrArgsEntry=q}),Is=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.OpIdKernelTypeStrArgsEntry=void 0;var K=H(_e()),z=Ts(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsOpIdKernelTypeStrArgsEntry(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsOpIdKernelTypeStrArgsEntry(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}opId(D){let V=this.bb.__offset(this.bb_pos,4);return V?this.bb.__string(this.bb_pos+V,D):null}kernelTypeStrArgs(D,V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new z.KernelTypeStrArgsEntry).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+O)+D*4),this.bb):null}kernelTypeStrArgsLength(){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.__vector_len(this.bb_pos+D):0}static startOpIdKernelTypeStrArgsEntry(D){D.startObject(2)}static addOpId(D,V){D.addFieldOffset(0,V,0)}static addKernelTypeStrArgs(D,V){D.addFieldOffset(1,V,0)}static createKernelTypeStrArgsVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startKernelTypeStrArgsVector(D,V){D.startVector(4,V,4)}static endOpIdKernelTypeStrArgsEntry(D){let V=D.endObject();return D.requiredField(V,4),V}static createOpIdKernelTypeStrArgsEntry(D,V,O){return F.startOpIdKernelTypeStrArgsEntry(D),F.addOpId(D,V),F.addKernelTypeStrArgs(D,O),F.endOpIdKernelTypeStrArgsEntry(D)}};Q.OpIdKernelTypeStrArgsEntry=q}),$s=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(F,D,V,O){O===void 0&&(O=V);var P=Object.getOwnPropertyDescriptor(D,V);(!P||("get"in P?!D.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return D[V]}}),Object.defineProperty(F,O,P)}:function(F,D,V,O){O===void 0&&(O=V),F[O]=D[V]}),G=Q&&Q.__setModuleDefault||(Object.create?function(F,D){Object.defineProperty(F,"default",{enumerable:!0,value:D})}:function(F,D){F.default=D}),H=Q&&Q.__importStar||function(F){if(F&&F.__esModule)return F;var D={};if(F!=null)for(var V in F)V!=="default"&&Object.prototype.hasOwnProperty.call(F,V)&&J(D,F,V);return G(D,F),D};Object.defineProperty(Q,"__esModule",{value:!0}),Q.KernelTypeStrResolver=void 0;var K=H(_e()),z=Is(),q=class F{constructor(){this.bb=null,this.bb_pos=0}__init(D,V){return this.bb_pos=D,this.bb=V,this}static getRootAsKernelTypeStrResolver(D,V){return(V||new F).__init(D.readInt32(D.position())+D.position(),D)}static getSizePrefixedRootAsKernelTypeStrResolver(D,V){return D.setPosition(D.position()+K.SIZE_PREFIX_LENGTH),(V||new F).__init(D.readInt32(D.position())+D.position(),D)}opKernelTypeStrArgs(D,V){let O=this.bb.__offset(this.bb_pos,4);return O?(V||new z.OpIdKernelTypeStrArgsEntry).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+O)+D*4),this.bb):null}opKernelTypeStrArgsLength(){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.__vector_len(this.bb_pos+D):0}static startKernelTypeStrResolver(D){D.startObject(1)}static addOpKernelTypeStrArgs(D,V){D.addFieldOffset(0,V,0)}static createOpKernelTypeStrArgsVector(D,V){D.startVector(4,V.length,4);for(let O=V.length-1;O>=0;O--)D.addOffset(V[O]);return D.endVector()}static startOpKernelTypeStrArgsVector(D,V){D.startVector(4,V,4)}static endKernelTypeStrResolver(D){return D.endObject()}static createKernelTypeStrResolver(D,V){return F.startKernelTypeStrResolver(D),F.addOpKernelTypeStrArgs(D,V),F.endKernelTypeStrResolver(D)}};Q.KernelTypeStrResolver=q}),Ps=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(q,F,D,V){V===void 0&&(V=D);var O=Object.getOwnPropertyDescriptor(F,D);(!O||("get"in O?!F.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return F[D]}}),Object.defineProperty(q,V,O)}:function(q,F,D,V){V===void 0&&(V=D),q[V]=F[D]}),G=Q&&Q.__setModuleDefault||(Object.create?function(q,F){Object.defineProperty(q,"default",{enumerable:!0,value:F})}:function(q,F){q.default=F}),H=Q&&Q.__importStar||function(q){if(q&&q.__esModule)return q;var F={};if(q!=null)for(var D in q)D!=="default"&&Object.prototype.hasOwnProperty.call(q,D)&&J(F,q,D);return G(F,q),F};Object.defineProperty(Q,"__esModule",{value:!0}),Q.OperatorSetId=void 0;var K=H(_e()),z=class q{constructor(){this.bb=null,this.bb_pos=0}__init(F,D){return this.bb_pos=F,this.bb=D,this}static getRootAsOperatorSetId(F,D){return(D||new q).__init(F.readInt32(F.position())+F.position(),F)}static getSizePrefixedRootAsOperatorSetId(F,D){return F.setPosition(F.position()+K.SIZE_PREFIX_LENGTH),(D||new q).__init(F.readInt32(F.position())+F.position(),F)}domain(F){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.__string(this.bb_pos+D,F):null}version(){let F=this.bb.__offset(this.bb_pos,6);return F?this.bb.readInt64(this.bb_pos+F):BigInt("0")}static startOperatorSetId(F){F.startObject(2)}static addDomain(F,D){F.addFieldOffset(0,D,0)}static addVersion(F,D){F.addFieldInt64(1,D,BigInt("0"))}static endOperatorSetId(F){return F.endObject()}static createOperatorSetId(F,D,V){return q.startOperatorSetId(F),q.addDomain(F,D),q.addVersion(F,V),q.endOperatorSetId(F)}};Q.OperatorSetId=z}),Es=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(q,F,D,V){V===void 0&&(V=D);var O=Object.getOwnPropertyDescriptor(F,D);(!O||("get"in O?!F.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return F[D]}}),Object.defineProperty(q,V,O)}:function(q,F,D,V){V===void 0&&(V=D),q[V]=F[D]}),G=Q&&Q.__setModuleDefault||(Object.create?function(q,F){Object.defineProperty(q,"default",{enumerable:!0,value:F})}:function(q,F){q.default=F}),H=Q&&Q.__importStar||function(q){if(q&&q.__esModule)return q;var F={};if(q!=null)for(var D in q)D!=="default"&&Object.prototype.hasOwnProperty.call(q,D)&&J(F,q,D);return G(F,q),F};Object.defineProperty(Q,"__esModule",{value:!0}),Q.StringStringEntry=void 0;var K=H(_e()),z=class q{constructor(){this.bb=null,this.bb_pos=0}__init(F,D){return this.bb_pos=F,this.bb=D,this}static getRootAsStringStringEntry(F,D){return(D||new q).__init(F.readInt32(F.position())+F.position(),F)}static getSizePrefixedRootAsStringStringEntry(F,D){return F.setPosition(F.position()+K.SIZE_PREFIX_LENGTH),(D||new q).__init(F.readInt32(F.position())+F.position(),F)}key(F){let D=this.bb.__offset(this.bb_pos,4);return D?this.bb.__string(this.bb_pos+D,F):null}value(F){let D=this.bb.__offset(this.bb_pos,6);return D?this.bb.__string(this.bb_pos+D,F):null}static startStringStringEntry(F){F.startObject(2)}static addKey(F,D){F.addFieldOffset(0,D,0)}static addValue(F,D){F.addFieldOffset(1,D,0)}static endStringStringEntry(F){return F.endObject()}static createStringStringEntry(F,D,V){return q.startStringStringEntry(F),q.addKey(F,D),q.addValue(F,V),q.endStringStringEntry(F)}};Q.StringStringEntry=z}),Ds=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(V,O,P,N){N===void 0&&(N=P);var I=Object.getOwnPropertyDescriptor(O,P);(!I||("get"in I?!O.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return O[P]}}),Object.defineProperty(V,N,I)}:function(V,O,P,N){N===void 0&&(N=P),V[N]=O[P]}),G=Q&&Q.__setModuleDefault||(Object.create?function(V,O){Object.defineProperty(V,"default",{enumerable:!0,value:O})}:function(V,O){V.default=O}),H=Q&&Q.__importStar||function(V){if(V&&V.__esModule)return V;var O={};if(V!=null)for(var P in V)P!=="default"&&Object.prototype.hasOwnProperty.call(V,P)&&J(O,V,P);return G(O,V),O};Object.defineProperty(Q,"__esModule",{value:!0}),Q.Model=void 0;var K=H(_e()),z=Do(),q=Ps(),F=Es(),D=class V{constructor(){this.bb=null,this.bb_pos=0}__init(O,P){return this.bb_pos=O,this.bb=P,this}static getRootAsModel(O,P){return(P||new V).__init(O.readInt32(O.position())+O.position(),O)}static getSizePrefixedRootAsModel(O,P){return O.setPosition(O.position()+K.SIZE_PREFIX_LENGTH),(P||new V).__init(O.readInt32(O.position())+O.position(),O)}irVersion(){let O=this.bb.__offset(this.bb_pos,4);return O?this.bb.readInt64(this.bb_pos+O):BigInt("0")}opsetImport(O,P){let N=this.bb.__offset(this.bb_pos,6);return N?(P||new q.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+N)+O*4),this.bb):null}opsetImportLength(){let O=this.bb.__offset(this.bb_pos,6);return O?this.bb.__vector_len(this.bb_pos+O):0}producerName(O){let P=this.bb.__offset(this.bb_pos,8);return P?this.bb.__string(this.bb_pos+P,O):null}producerVersion(O){let P=this.bb.__offset(this.bb_pos,10);return P?this.bb.__string(this.bb_pos+P,O):null}domain(O){let P=this.bb.__offset(this.bb_pos,12);return P?this.bb.__string(this.bb_pos+P,O):null}modelVersion(){let O=this.bb.__offset(this.bb_pos,14);return O?this.bb.readInt64(this.bb_pos+O):BigInt("0")}docString(O){let P=this.bb.__offset(this.bb_pos,16);return P?this.bb.__string(this.bb_pos+P,O):null}graph(O){let P=this.bb.__offset(this.bb_pos,18);return P?(O||new z.Graph).__init(this.bb.__indirect(this.bb_pos+P),this.bb):null}graphDocString(O){let P=this.bb.__offset(this.bb_pos,20);return P?this.bb.__string(this.bb_pos+P,O):null}metadataProps(O,P){let N=this.bb.__offset(this.bb_pos,22);return N?(P||new F.StringStringEntry).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+N)+O*4),this.bb):null}metadataPropsLength(){let O=this.bb.__offset(this.bb_pos,22);return O?this.bb.__vector_len(this.bb_pos+O):0}static startModel(O){O.startObject(10)}static addIrVersion(O,P){O.addFieldInt64(0,P,BigInt("0"))}static addOpsetImport(O,P){O.addFieldOffset(1,P,0)}static createOpsetImportVector(O,P){O.startVector(4,P.length,4);for(let N=P.length-1;N>=0;N--)O.addOffset(P[N]);return O.endVector()}static startOpsetImportVector(O,P){O.startVector(4,P,4)}static addProducerName(O,P){O.addFieldOffset(2,P,0)}static addProducerVersion(O,P){O.addFieldOffset(3,P,0)}static addDomain(O,P){O.addFieldOffset(4,P,0)}static addModelVersion(O,P){O.addFieldInt64(5,P,BigInt("0"))}static addDocString(O,P){O.addFieldOffset(6,P,0)}static addGraph(O,P){O.addFieldOffset(7,P,0)}static addGraphDocString(O,P){O.addFieldOffset(8,P,0)}static addMetadataProps(O,P){O.addFieldOffset(9,P,0)}static createMetadataPropsVector(O,P){O.startVector(4,P.length,4);for(let N=P.length-1;N>=0;N--)O.addOffset(P[N]);return O.endVector()}static startMetadataPropsVector(O,P){O.startVector(4,P,4)}static endModel(O){return O.endObject()}};Q.Model=D}),Gc=W((Q)=>{var J=Q&&Q.__createBinding||(Object.create?function(D,V,O,P){P===void 0&&(P=O);var N=Object.getOwnPropertyDescriptor(V,O);(!N||("get"in N?!V.__esModule:N.writable||N.configurable))&&(N={enumerable:!0,get:function(){return V[O]}}),Object.defineProperty(D,P,N)}:function(D,V,O,P){P===void 0&&(P=O),D[P]=V[O]}),G=Q&&Q.__setModuleDefault||(Object.create?function(D,V){Object.defineProperty(D,"default",{enumerable:!0,value:V})}:function(D,V){D.default=V}),H=Q&&Q.__importStar||function(D){if(D&&D.__esModule)return D;var V={};if(D!=null)for(var O in D)O!=="default"&&Object.prototype.hasOwnProperty.call(D,O)&&J(V,D,O);return G(V,D),V};Object.defineProperty(Q,"__esModule",{value:!0}),Q.InferenceSession=void 0;var K=H(_e()),z=$s(),q=Ds(),F=class D{constructor(){this.bb=null,this.bb_pos=0}__init(V,O){return this.bb_pos=V,this.bb=O,this}static getRootAsInferenceSession(V,O){return(O||new D).__init(V.readInt32(V.position())+V.position(),V)}static getSizePrefixedRootAsInferenceSession(V,O){return V.setPosition(V.position()+K.SIZE_PREFIX_LENGTH),(O||new D).__init(V.readInt32(V.position())+V.position(),V)}static bufferHasIdentifier(V){return V.__has_identifier("ORTM")}ortVersion(V){let O=this.bb.__offset(this.bb_pos,4);return O?this.bb.__string(this.bb_pos+O,V):null}model(V){let O=this.bb.__offset(this.bb_pos,6);return O?(V||new q.Model).__init(this.bb.__indirect(this.bb_pos+O),this.bb):null}kernelTypeStrResolver(V){let O=this.bb.__offset(this.bb_pos,10);return O?(V||new z.KernelTypeStrResolver).__init(this.bb.__indirect(this.bb_pos+O),this.bb):null}static startInferenceSession(V){V.startObject(4)}static addOrtVersion(V,O){V.addFieldOffset(0,O,0)}static addModel(V,O){V.addFieldOffset(1,O,0)}static addKernelTypeStrResolver(V,O){V.addFieldOffset(3,O,0)}static endInferenceSession(V){return V.endObject()}static finishInferenceSessionBuffer(V,O){V.finish(O,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(V,O){V.finish(O,"ORTM",!0)}};Q.InferenceSession=F}),Dv,kv,ko,ht,Lv,Rv,Nv,zv,Mv,Bv,Fv,Vv,Ls,Rs,Gv,Uv,Wv,Hv,Ns,qv,jv,Kv,Xv,Zv,Jv,Qv,Yv,e0,t0,n0,r0,o0,Mr,zs,i0,Ms,a0,Uc=$(()=>{Dv=ae(wa()),kv=ae(Pa()),ko=ae(ka()),ht=ae(Oa()),Lv=ae(ms()),Rv=ae(Vc()),Nv=ae(_s()),zv=ae(ys()),Mv=ae(rs()),Bv=ae(ts()),Fv=ae(Ya()),Vv=ae(Ra()),Ls=ae(Do()),Rs=ae(Gc()),Gv=ae(Ts()),Uv=ae($s()),Wv=ae(Za()),Hv=ae(Ds()),Ns=ae(Da()),qv=ae(za()),jv=ae(Ea()),Kv=ae(Ba()),Xv=ae(Is()),Zv=ae(Ps()),Jv=ae(Va()),Qv=ae(Ua()),Yv=ae(Ha()),e0=ae(Qa()),t0=ae(is()),n0=ae(Ka()),r0=ae(Es()),o0=ae(Nr()),Mr=ae(Rr()),zs=ae(ss()),i0=ae(zr()),Ms=ae(us()),a0=ae(ds())}),Br=$(()=>{Uc()}),Hc=W((Q,J)=>{J.exports=G;function G(H,K){for(var z=Array(arguments.length-1),q=0,F=2,D=!0;F<arguments.length;)z[q++]=arguments[F++];return new Promise(function(V,O){z[q]=function(P){if(D)if(D=!1,P)O(P);else{for(var N=Array(arguments.length-1),I=0;I<N.length;)N[I++]=arguments[I];V.apply(null,N)}};try{H.apply(K||null,z)}catch(P){D&&(D=!1,O(P))}})}}),Xc=W((Q)=>{var J=Q;J.length=function(q){var F=q.length;if(!F)return 0;for(var D=0;--F%4>1&&q.charAt(F)==="=";)++D;return Math.ceil(q.length*3)/4-D};var G=Array(64),H=Array(123);for(K=0;K<64;)H[G[K]=K<26?K+65:K<52?K+71:K<62?K-4:K-59|43]=K++;var K;J.encode=function(q,F,D){for(var V=null,O=[],P=0,N=0,I;F<D;){var R=q[F++];switch(N){case 0:O[P++]=G[R>>2],I=(R&3)<<4,N=1;break;case 1:O[P++]=G[I|R>>4],I=(R&15)<<2,N=2;break;case 2:O[P++]=G[I|R>>6],O[P++]=G[R&63],N=0;break}P>8191&&((V||(V=[])).push(String.fromCharCode.apply(String,O)),P=0)}return N&&(O[P++]=G[I],O[P++]=61,N===1&&(O[P++]=61)),V?(P&&V.push(String.fromCharCode.apply(String,O.slice(0,P))),V.join("")):String.fromCharCode.apply(String,O.slice(0,P))};var z="invalid encoding";J.decode=function(q,F,D){for(var V=D,O=0,P,N=0;N<q.length;){var I=q.charCodeAt(N++);if(I===61&&O>1)break;if((I=H[I])===void 0)throw Error(z);switch(O){case 0:P=I,O=1;break;case 1:F[D++]=P<<2|(I&48)>>4,P=I,O=2;break;case 2:F[D++]=(P&15)<<4|(I&60)>>2,P=I,O=3;break;case 3:F[D++]=(P&3)<<6|I,O=0;break}}if(O===1)throw Error(z);return D-V},J.test=function(q){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(q)}}),Jc=W((Q,J)=>{J.exports=G;function G(){this._listeners={}}G.prototype.on=function(H,K,z){return(this._listeners[H]||(this._listeners[H]=[])).push({fn:K,ctx:z||this}),this},G.prototype.off=function(H,K){if(H===void 0)this._listeners={};else if(K===void 0)this._listeners[H]=[];else for(var z=this._listeners[H],q=0;q<z.length;)z[q].fn===K?z.splice(q,1):++q;return this},G.prototype.emit=function(H){var K=this._listeners[H];if(K){for(var z=[],q=1;q<arguments.length;)z.push(arguments[q++]);for(q=0;q<K.length;)K[q].fn.apply(K[q++].ctx,z)}return this}}),od=W((Q,J)=>{J.exports=G(G);function G(F){return typeof Float32Array<"u"?function(){var D=new Float32Array([-0]),V=new Uint8Array(D.buffer),O=V[3]===128;function P(w,E,T){D[0]=w,E[T]=V[0],E[T+1]=V[1],E[T+2]=V[2],E[T+3]=V[3]}function N(w,E,T){D[0]=w,E[T]=V[3],E[T+1]=V[2],E[T+2]=V[1],E[T+3]=V[0]}F.writeFloatLE=O?P:N,F.writeFloatBE=O?N:P;function I(w,E){return V[0]=w[E],V[1]=w[E+1],V[2]=w[E+2],V[3]=w[E+3],D[0]}function R(w,E){return V[3]=w[E],V[2]=w[E+1],V[1]=w[E+2],V[0]=w[E+3],D[0]}F.readFloatLE=O?I:R,F.readFloatBE=O?R:I}():function(){function D(O,P,N,I){var R=P<0?1:0;if(R&&(P=-P),P===0)O(1/P>0?0:2147483648,N,I);else if(isNaN(P))O(2143289344,N,I);else if(P>340282346638528860000000000000000000000)O((R<<31|2139095040)>>>0,N,I);else if(P<0.000000000000000000000000000000000000011754943508222875)O((R<<31|Math.round(P/0.000000000000000000000000000000000000000000001401298464324817))>>>0,N,I);else{var w=Math.floor(Math.log(P)/Math.LN2),E=Math.round(P*Math.pow(2,-w)*8388608)&8388607;O((R<<31|w+127<<23|E)>>>0,N,I)}}F.writeFloatLE=D.bind(null,H),F.writeFloatBE=D.bind(null,K);function V(O,P,N){var I=O(P,N),R=(I>>31)*2+1,w=I>>>23&255,E=I&8388607;return w===255?E?NaN:R*(1/0):w===0?R*0.000000000000000000000000000000000000000000001401298464324817*E:R*Math.pow(2,w-150)*(E+8388608)}F.readFloatLE=V.bind(null,z),F.readFloatBE=V.bind(null,q)}(),typeof Float64Array<"u"?function(){var D=new Float64Array([-0]),V=new Uint8Array(D.buffer),O=V[7]===128;function P(w,E,T){D[0]=w,E[T]=V[0],E[T+1]=V[1],E[T+2]=V[2],E[T+3]=V[3],E[T+4]=V[4],E[T+5]=V[5],E[T+6]=V[6],E[T+7]=V[7]}function N(w,E,T){D[0]=w,E[T]=V[7],E[T+1]=V[6],E[T+2]=V[5],E[T+3]=V[4],E[T+4]=V[3],E[T+5]=V[2],E[T+6]=V[1],E[T+7]=V[0]}F.writeDoubleLE=O?P:N,F.writeDoubleBE=O?N:P;function I(w,E){return V[0]=w[E],V[1]=w[E+1],V[2]=w[E+2],V[3]=w[E+3],V[4]=w[E+4],V[5]=w[E+5],V[6]=w[E+6],V[7]=w[E+7],D[0]}function R(w,E){return V[7]=w[E],V[6]=w[E+1],V[5]=w[E+2],V[4]=w[E+3],V[3]=w[E+4],V[2]=w[E+5],V[1]=w[E+6],V[0]=w[E+7],D[0]}F.readDoubleLE=O?I:R,F.readDoubleBE=O?R:I}():function(){function D(O,P,N,I,R,w){var E=I<0?1:0;if(E&&(I=-I),I===0)O(0,R,w+P),O(1/I>0?0:2147483648,R,w+N);else if(isNaN(I))O(0,R,w+P),O(2146959360,R,w+N);else if(I>179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)O(0,R,w+P),O((E<<31|2146435072)>>>0,R,w+N);else{var T;if(I<0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022250738585072014)T=I/0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005,O(T>>>0,R,w+P),O((E<<31|T/4294967296)>>>0,R,w+N);else{var y=Math.floor(Math.log(I)/Math.LN2);y===1024&&(y=1023),T=I*Math.pow(2,-y),O(T*4503599627370496>>>0,R,w+P),O((E<<31|y+1023<<20|T*1048576&1048575)>>>0,R,w+N)}}}F.writeDoubleLE=D.bind(null,H,0,4),F.writeDoubleBE=D.bind(null,K,4,0);function V(O,P,N,I,R){var w=O(I,R+P),E=O(I,R+N),T=(E>>31)*2+1,y=E>>>20&2047,x=4294967296*(E&1048575)+w;return y===2047?x?NaN:T*(1/0):y===0?T*0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005*x:T*Math.pow(2,y-1075)*(x+4503599627370496)}F.readDoubleLE=V.bind(null,z,0,4),F.readDoubleBE=V.bind(null,q,4,0)}(),F}function H(F,D,V){D[V]=F&255,D[V+1]=F>>>8&255,D[V+2]=F>>>16&255,D[V+3]=F>>>24}function K(F,D,V){D[V]=F>>>24,D[V+1]=F>>>16&255,D[V+2]=F>>>8&255,D[V+3]=F&255}function z(F,D){return(F[D]|F[D+1]<<8|F[D+2]<<16|F[D+3]<<24)>>>0}function q(F,D){return(F[D]<<24|F[D+1]<<16|F[D+2]<<8|F[D+3])>>>0}}),id=W((exports,module)=>{module.exports=inquire;function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(Q){}return null}}),sd=W((Q)=>{var J=Q;J.length=function(G){for(var H=0,K=0,z=0;z<G.length;++z)K=G.charCodeAt(z),K<128?H+=1:K<2048?H+=2:(K&64512)===55296&&(G.charCodeAt(z+1)&64512)===56320?(++z,H+=4):H+=3;return H},J.read=function(G,H,K){var z=K-H;if(z<1)return"";for(var q=null,F=[],D=0,V;H<K;)V=G[H++],V<128?F[D++]=V:V>191&&V<224?F[D++]=(V&31)<<6|G[H++]&63:V>239&&V<365?(V=((V&7)<<18|(G[H++]&63)<<12|(G[H++]&63)<<6|G[H++]&63)-65536,F[D++]=55296+(V>>10),F[D++]=56320+(V&1023)):F[D++]=(V&15)<<12|(G[H++]&63)<<6|G[H++]&63,D>8191&&((q||(q=[])).push(String.fromCharCode.apply(String,F)),D=0);return q?(D&&q.push(String.fromCharCode.apply(String,F.slice(0,D))),q.join("")):String.fromCharCode.apply(String,F.slice(0,D))},J.write=function(G,H,K){for(var z=K,q,F,D=0;D<G.length;++D)q=G.charCodeAt(D),q<128?H[K++]=q:q<2048?(H[K++]=q>>6|192,H[K++]=q&63|128):(q&64512)===55296&&((F=G.charCodeAt(D+1))&64512)===56320?(q=65536+((q&1023)<<10)+(F&1023),++D,H[K++]=q>>18|240,H[K++]=q>>12&63|128,H[K++]=q>>6&63|128,H[K++]=q&63|128):(H[K++]=q>>12|224,H[K++]=q>>6&63|128,H[K++]=q&63|128);return K-z}}),ld=W((Q,J)=>{J.exports=G;function G(H,K,z){var q=z||8192,F=q>>>1,D=null,V=q;return function(O){if(O<1||O>F)return H(O);V+O>q&&(D=H(q),V=0);var P=K.call(D,V,V+=O);return V&7&&(V=(V|7)+1),P}}}),dd=W((Q,J)=>{J.exports=H;var G=Rn();function H(F,D){this.lo=F>>>0,this.hi=D>>>0}var K=H.zero=new H(0,0);K.toNumber=function(){return 0},K.zzEncode=K.zzDecode=function(){return this},K.length=function(){return 1};var z=H.zeroHash="\x00\x00\x00\x00\x00\x00\x00\x00";H.fromNumber=function(F){if(F===0)return K;var D=F<0;D&&(F=-F);var V=F>>>0,O=(F-V)/4294967296>>>0;return D&&(O=~O>>>0,V=~V>>>0,++V>4294967295&&(V=0,++O>4294967295&&(O=0))),new H(V,O)},H.from=function(F){if(typeof F=="number")return H.fromNumber(F);if(G.isString(F))if(G.Long)F=G.Long.fromString(F);else return H.fromNumber(parseInt(F,10));return F.low||F.high?new H(F.low>>>0,F.high>>>0):K},H.prototype.toNumber=function(F){if(!F&&this.hi>>>31){var D=~this.lo+1>>>0,V=~this.hi>>>0;return D||(V=V+1>>>0),-(D+V*4294967296)}return this.lo+this.hi*4294967296},H.prototype.toLong=function(F){return G.Long?new G.Long(this.lo|0,this.hi|0,!!F):{low:this.lo|0,high:this.hi|0,unsigned:!!F}};var q=String.prototype.charCodeAt;H.fromHash=function(F){return F===z?K:new H((q.call(F,0)|q.call(F,1)<<8|q.call(F,2)<<16|q.call(F,3)<<24)>>>0,(q.call(F,4)|q.call(F,5)<<8|q.call(F,6)<<16|q.call(F,7)<<24)>>>0)},H.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},H.prototype.zzEncode=function(){var F=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^F)>>>0,this.lo=(this.lo<<1^F)>>>0,this},H.prototype.zzDecode=function(){var F=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^F)>>>0,this.hi=(this.hi>>>1^F)>>>0,this},H.prototype.length=function(){var F=this.lo,D=(this.lo>>>28|this.hi<<4)>>>0,V=this.hi>>>24;return V===0?D===0?F<16384?F<128?1:2:F<2097152?3:4:D<16384?D<128?5:6:D<2097152?7:8:V<128?9:10}}),Rn=W((Q)=>{var J=Q;J.asPromise=Hc(),J.base64=Xc(),J.EventEmitter=Jc(),J.float=od(),J.inquire=id(),J.utf8=sd(),J.pool=ld(),J.LongBits=dd(),J.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),J.global=J.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||Q,J.emptyArray=Object.freeze?Object.freeze([]):[],J.emptyObject=Object.freeze?Object.freeze({}):{},J.isInteger=Number.isInteger||function(K){return typeof K=="number"&&isFinite(K)&&Math.floor(K)===K},J.isString=function(K){return typeof K=="string"||K instanceof String},J.isObject=function(K){return K&&typeof K=="object"},J.isset=J.isSet=function(K,z){var q=K[z];return q!=null&&K.hasOwnProperty(z)?typeof q!="object"||(Array.isArray(q)?q.length:Object.keys(q).length)>0:!1},J.Buffer=function(){try{var K=J.inquire("buffer").Buffer;return K.prototype.utf8Write?K:null}catch{return null}}(),J._Buffer_from=null,J._Buffer_allocUnsafe=null,J.newBuffer=function(K){return typeof K=="number"?J.Buffer?J._Buffer_allocUnsafe(K):new J.Array(K):J.Buffer?J._Buffer_from(K):typeof Uint8Array>"u"?K:new Uint8Array(K)},J.Array=typeof Uint8Array<"u"?Uint8Array:Array,J.Long=J.global.dcodeIO&&J.global.dcodeIO.Long||J.global.Long||J.inquire("long"),J.key2Re=/^true|false|0|1$/,J.key32Re=/^-?(?:0|[1-9][0-9]*)$/,J.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,J.longToHash=function(K){return K?J.LongBits.from(K).toHash():J.LongBits.zeroHash},J.longFromHash=function(K,z){var q=J.LongBits.fromHash(K);return J.Long?J.Long.fromBits(q.lo,q.hi,z):q.toNumber(!!z)};function G(K,z,q){for(var F=Object.keys(z),D=0;D<F.length;++D)(K[F[D]]===void 0||!q)&&(K[F[D]]=z[F[D]]);return K}J.merge=G,J.lcFirst=function(K){return K.charAt(0).toLowerCase()+K.substring(1)};function H(K){function z(q,F){if(!(this instanceof z))return new z(q,F);Object.defineProperty(this,"message",{get:function(){return q}}),Error.captureStackTrace?Error.captureStackTrace(this,z):Object.defineProperty(this,"stack",{value:Error().stack||""}),F&&G(this,F)}return z.prototype=Object.create(Error.prototype,{constructor:{value:z,writable:!0,enumerable:!1,configurable:!0},name:{get:function(){return K},set:void 0,enumerable:!1,configurable:!0},toString:{value:function(){return this.name+": "+this.message},writable:!0,enumerable:!1,configurable:!0}}),z}J.newError=H,J.ProtocolError=H("ProtocolError"),J.oneOfGetter=function(K){for(var z={},q=0;q<K.length;++q)z[K[q]]=1;return function(){for(var F=Object.keys(this),D=F.length-1;D>-1;--D)if(z[F[D]]===1&&this[F[D]]!==void 0&&this[F[D]]!==null)return F[D]}},J.oneOfSetter=function(K){return function(z){for(var q=0;q<K.length;++q)K[q]!==z&&delete this[K[q]]}},J.toJSONOptions={longs:String,enums:String,bytes:String,json:!0},J._configure=function(){var K=J.Buffer;if(!K){J._Buffer_from=J._Buffer_allocUnsafe=null;return}J._Buffer_from=K.from!==Uint8Array.from&&K.from||function(z,q){return new K(z,q)},J._Buffer_allocUnsafe=K.allocUnsafe||function(z){return new K(z)}}}),js=W((Q,J)=>{J.exports=O;var G=Rn(),H,K=G.LongBits,z=G.base64,q=G.utf8;function F(y,x,b){this.fn=y,this.len=x,this.next=void 0,this.val=b}function D(){}function V(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function O(){this.len=0,this.head=new F(D,0,0),this.tail=this.head,this.states=null}var P=function(){return G.Buffer?function(){return(O.create=function(){return new H})()}:function(){return new O}};O.create=P(),O.alloc=function(y){return new G.Array(y)},G.Array!==Array&&(O.alloc=G.pool(O.alloc,G.Array.prototype.subarray)),O.prototype._push=function(y,x,b){return this.tail=this.tail.next=new F(y,x,b),this.len+=x,this};function N(y,x,b){x[b]=y&255}function I(y,x,b){for(;y>127;)x[b++]=y&127|128,y>>>=7;x[b]=y}function R(y,x){this.len=y,this.next=void 0,this.val=x}R.prototype=Object.create(F.prototype),R.prototype.fn=I,O.prototype.uint32=function(y){return this.len+=(this.tail=this.tail.next=new R((y=y>>>0)<128?1:y<16384?2:y<2097152?3:y<268435456?4:5,y)).len,this},O.prototype.int32=function(y){return y<0?this._push(w,10,K.fromNumber(y)):this.uint32(y)},O.prototype.sint32=function(y){return this.uint32((y<<1^y>>31)>>>0)};function w(y,x,b){for(;y.hi;)x[b++]=y.lo&127|128,y.lo=(y.lo>>>7|y.hi<<25)>>>0,y.hi>>>=7;for(;y.lo>127;)x[b++]=y.lo&127|128,y.lo=y.lo>>>7;x[b++]=y.lo}O.prototype.uint64=function(y){var x=K.from(y);return this._push(w,x.length(),x)},O.prototype.int64=O.prototype.uint64,O.prototype.sint64=function(y){var x=K.from(y).zzEncode();return this._push(w,x.length(),x)},O.prototype.bool=function(y){return this._push(N,1,y?1:0)};function E(y,x,b){x[b]=y&255,x[b+1]=y>>>8&255,x[b+2]=y>>>16&255,x[b+3]=y>>>24}O.prototype.fixed32=function(y){return this._push(E,4,y>>>0)},O.prototype.sfixed32=O.prototype.fixed32,O.prototype.fixed64=function(y){var x=K.from(y);return this._push(E,4,x.lo)._push(E,4,x.hi)},O.prototype.sfixed64=O.prototype.fixed64,O.prototype.float=function(y){return this._push(G.float.writeFloatLE,4,y)},O.prototype.double=function(y){return this._push(G.float.writeDoubleLE,8,y)};var T=G.Array.prototype.set?function(y,x,b){x.set(y,b)}:function(y,x,b){for(var g=0;g<y.length;++g)x[b+g]=y[g]};O.prototype.bytes=function(y){var x=y.length>>>0;if(!x)return this._push(N,1,0);if(G.isString(y)){var b=O.alloc(x=z.length(y));z.decode(y,b,0),y=b}return this.uint32(x)._push(T,x,y)},O.prototype.string=function(y){var x=q.length(y);return x?this.uint32(x)._push(q.write,x,y):this._push(N,1,0)},O.prototype.fork=function(){return this.states=new V(this),this.head=this.tail=new F(D,0,0),this.len=0,this},O.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new F(D,0,0),this.len=0),this},O.prototype.ldelim=function(){var y=this.head,x=this.tail,b=this.len;return this.reset().uint32(b),b&&(this.tail.next=y.next,this.tail=x,this.len+=b),this},O.prototype.finish=function(){for(var y=this.head.next,x=this.constructor.alloc(this.len),b=0;y;)y.fn(y.val,x,b),b+=y.len,y=y.next;return x},O._configure=function(y){H=y,O.create=P(),H._configure()}}),xd=W((Q,J)=>{J.exports=K;var G=js();(K.prototype=Object.create(G.prototype)).constructor=K;var H=Rn();function K(){G.call(this)}K._configure=function(){K.alloc=H._Buffer_allocUnsafe,K.writeBytesBuffer=H.Buffer&&H.Buffer.prototype instanceof Uint8Array&&H.Buffer.prototype.set.name==="set"?function(q,F,D){F.set(q,D)}:function(q,F,D){if(q.copy)q.copy(F,D,0,q.length);else for(var V=0;V<q.length;)F[D++]=q[V++]}},K.prototype.bytes=function(q){H.isString(q)&&(q=H._Buffer_from(q,"base64"));var F=q.length>>>0;return this.uint32(F),F&&this._push(K.writeBytesBuffer,F,q),this};function z(q,F,D){q.length<40?H.utf8.write(q,F,D):F.utf8Write?F.utf8Write(q,D):F.write(q,D)}K.prototype.string=function(q){var F=H.Buffer.byteLength(q);return this.uint32(F),F&&this._push(z,F,q),this},K._configure()}),Zs=W((Q,J)=>{J.exports=F;var G=Rn(),H,K=G.LongBits,z=G.utf8;function q(I,R){return RangeError("index out of range: "+I.pos+" + "+(R||1)+" > "+I.len)}function F(I){this.buf=I,this.pos=0,this.len=I.length}var D=typeof Uint8Array<"u"?function(I){if(I instanceof Uint8Array||Array.isArray(I))return new F(I);throw Error("illegal buffer")}:function(I){if(Array.isArray(I))return new F(I);throw Error("illegal buffer")},V=function(){return G.Buffer?function(I){return(F.create=function(R){return G.Buffer.isBuffer(R)?new H(R):D(R)})(I)}:D};F.create=V(),F.prototype._slice=G.Array.prototype.subarray||G.Array.prototype.slice,F.prototype.uint32=function(){var I=4294967295;return function(){if(I=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(I=(I|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(I=(I|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(I=(I|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(I=(I|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return I;if((this.pos+=5)>this.len)throw this.pos=this.len,q(this,10);return I}}(),F.prototype.int32=function(){return this.uint32()|0},F.prototype.sint32=function(){var I=this.uint32();return I>>>1^-(I&1)|0};function O(){var I=new K(0,0),R=0;if(this.len-this.pos>4){for(;R<4;++R)if(I.lo=(I.lo|(this.buf[this.pos]&127)<<R*7)>>>0,this.buf[this.pos++]<128)return I;if(I.lo=(I.lo|(this.buf[this.pos]&127)<<28)>>>0,I.hi=(I.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return I;R=0}else{for(;R<3;++R){if(this.pos>=this.len)throw q(this);if(I.lo=(I.lo|(this.buf[this.pos]&127)<<R*7)>>>0,this.buf[this.pos++]<128)return I}return I.lo=(I.lo|(this.buf[this.pos++]&127)<<R*7)>>>0,I}if(this.len-this.pos>4){for(;R<5;++R)if(I.hi=(I.hi|(this.buf[this.pos]&127)<<R*7+3)>>>0,this.buf[this.pos++]<128)return I}else for(;R<5;++R){if(this.pos>=this.len)throw q(this);if(I.hi=(I.hi|(this.buf[this.pos]&127)<<R*7+3)>>>0,this.buf[this.pos++]<128)return I}throw Error("invalid varint encoding")}F.prototype.bool=function(){return this.uint32()!==0};function P(I,R){return(I[R-4]|I[R-3]<<8|I[R-2]<<16|I[R-1]<<24)>>>0}F.prototype.fixed32=function(){if(this.pos+4>this.len)throw q(this,4);return P(this.buf,this.pos+=4)},F.prototype.sfixed32=function(){if(this.pos+4>this.len)throw q(this,4);return P(this.buf,this.pos+=4)|0};function N(){if(this.pos+8>this.len)throw q(this,8);return new K(P(this.buf,this.pos+=4),P(this.buf,this.pos+=4))}F.prototype.float=function(){if(this.pos+4>this.len)throw q(this,4);var I=G.float.readFloatLE(this.buf,this.pos);return this.pos+=4,I},F.prototype.double=function(){if(this.pos+8>this.len)throw q(this,4);var I=G.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,I},F.prototype.bytes=function(){var I=this.uint32(),R=this.pos,w=this.pos+I;if(w>this.len)throw q(this,I);if(this.pos+=I,Array.isArray(this.buf))return this.buf.slice(R,w);if(R===w){var E=G.Buffer;return E?E.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,R,w)},F.prototype.string=function(){var I=this.bytes();return z.read(I,0,I.length)},F.prototype.skip=function(I){if(typeof I=="number"){if(this.pos+I>this.len)throw q(this,I);this.pos+=I}else do if(this.pos>=this.len)throw q(this);while(this.buf[this.pos++]&128);return this},F.prototype.skipType=function(I){switch(I){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(I=this.uint32()&7)!==4;)this.skipType(I);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+I+" at offset "+this.pos)}return this},F._configure=function(I){H=I,F.create=V(),H._configure();var R=G.Long?"toLong":"toNumber";G.merge(F.prototype,{int64:function(){return O.call(this)[R](!1)},uint64:function(){return O.call(this)[R](!0)},sint64:function(){return O.call(this).zzDecode()[R](!1)},fixed64:function(){return N.call(this)[R](!0)},sfixed64:function(){return N.call(this)[R](!1)}})}}),Od=W((Q,J)=>{J.exports=K;var G=Zs();(K.prototype=Object.create(G.prototype)).constructor=K;var H=Rn();function K(z){G.call(this,z)}K._configure=function(){H.Buffer&&(K.prototype._slice=H.Buffer.prototype.slice)},K.prototype.string=function(){var z=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+z,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+z,this.len))},K._configure()}),Cd=W((Q,J)=>{J.exports=H;var G=Rn();(H.prototype=Object.create(G.EventEmitter.prototype)).constructor=H;function H(K,z,q){if(typeof K!="function")throw TypeError("rpcImpl must be a function");G.EventEmitter.call(this),this.rpcImpl=K,this.requestDelimited=!!z,this.responseDelimited=!!q}H.prototype.rpcCall=function K(z,q,F,D,V){if(!D)throw TypeError("request must be specified");var O=this;if(!V)return G.asPromise(K,O,z,q,F,D);if(!O.rpcImpl){setTimeout(function(){V(Error("already ended"))},0);return}try{return O.rpcImpl(z,q[O.requestDelimited?"encodeDelimited":"encode"](D).finish(),function(P,N){if(P)return O.emit("error",P,z),V(P);if(N===null){O.end(!0);return}if(!(N instanceof F))try{N=F[O.responseDelimited?"decodeDelimited":"decode"](N)}catch(I){return O.emit("error",I,z),V(I)}return O.emit("data",N,z),V(null,N)})}catch(P){O.emit("error",P,z),setTimeout(function(){V(P)},0);return}},H.prototype.end=function(K){return this.rpcImpl&&(K||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),kd=W((Q)=>{var J=Q;J.Service=Cd()}),Rd=W((Q,J)=>{J.exports={}}),Md=W((Q)=>{var J=Q;J.build="minimal",J.Writer=js(),J.BufferWriter=xd(),J.Reader=Zs(),J.BufferReader=Od(),J.util=Rn(),J.rpc=kd(),J.roots=Rd(),J.configure=G;function G(){J.util._configure(),J.Writer._configure(J.BufferWriter),J.Reader._configure(J.BufferReader)}G()}),Fd=W((Q,J)=>{J.exports=Md()}),gr=W((Q,J)=>{var G=Fd(),H=G.Reader,K=G.Writer,z=G.util,q=G.roots.default||(G.roots.default={});q.onnx=function(){var F={};return F.Version=function(){var D={},V=Object.create(D);return V[D[0]="_START_VERSION"]=0,V[D[1]="IR_VERSION_2017_10_10"]=1,V[D[2]="IR_VERSION_2017_10_30"]=2,V[D[3]="IR_VERSION_2017_11_3"]=3,V[D[4]="IR_VERSION_2019_1_22"]=4,V[D[5]="IR_VERSION_2019_3_18"]=5,V[D[6]="IR_VERSION_2019_9_19"]=6,V[D[7]="IR_VERSION_2020_5_8"]=7,V[D[8]="IR_VERSION_2021_7_30"]=8,V[D[9]="IR_VERSION"]=9,V}(),F.AttributeProto=function(){function D(V){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.name="",D.prototype.refAttrName="",D.prototype.docString="",D.prototype.type=0,D.prototype.f=0,D.prototype.i=z.Long?z.Long.fromBits(0,0,!1):0,D.prototype.s=z.newBuffer([]),D.prototype.t=null,D.prototype.g=null,D.prototype.sparseTensor=null,D.prototype.tp=null,D.prototype.floats=z.emptyArray,D.prototype.ints=z.emptyArray,D.prototype.strings=z.emptyArray,D.prototype.tensors=z.emptyArray,D.prototype.graphs=z.emptyArray,D.prototype.sparseTensors=z.emptyArray,D.prototype.typeProtos=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.name!=null&&Object.hasOwnProperty.call(V,"name")&&O.uint32(10).string(V.name),V.f!=null&&Object.hasOwnProperty.call(V,"f")&&O.uint32(21).float(V.f),V.i!=null&&Object.hasOwnProperty.call(V,"i")&&O.uint32(24).int64(V.i),V.s!=null&&Object.hasOwnProperty.call(V,"s")&&O.uint32(34).bytes(V.s),V.t!=null&&Object.hasOwnProperty.call(V,"t")&&q.onnx.TensorProto.encode(V.t,O.uint32(42).fork()).ldelim(),V.g!=null&&Object.hasOwnProperty.call(V,"g")&&q.onnx.GraphProto.encode(V.g,O.uint32(50).fork()).ldelim(),V.floats!=null&&V.floats.length){O.uint32(58).fork();for(var P=0;P<V.floats.length;++P)O.float(V.floats[P]);O.ldelim()}if(V.ints!=null&&V.ints.length){O.uint32(66).fork();for(var P=0;P<V.ints.length;++P)O.int64(V.ints[P]);O.ldelim()}if(V.strings!=null&&V.strings.length)for(var P=0;P<V.strings.length;++P)O.uint32(74).bytes(V.strings[P]);if(V.tensors!=null&&V.tensors.length)for(var P=0;P<V.tensors.length;++P)q.onnx.TensorProto.encode(V.tensors[P],O.uint32(82).fork()).ldelim();if(V.graphs!=null&&V.graphs.length)for(var P=0;P<V.graphs.length;++P)q.onnx.GraphProto.encode(V.graphs[P],O.uint32(90).fork()).ldelim();if(V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(106).string(V.docString),V.tp!=null&&Object.hasOwnProperty.call(V,"tp")&&q.onnx.TypeProto.encode(V.tp,O.uint32(114).fork()).ldelim(),V.typeProtos!=null&&V.typeProtos.length)for(var P=0;P<V.typeProtos.length;++P)q.onnx.TypeProto.encode(V.typeProtos[P],O.uint32(122).fork()).ldelim();if(V.type!=null&&Object.hasOwnProperty.call(V,"type")&&O.uint32(160).int32(V.type),V.refAttrName!=null&&Object.hasOwnProperty.call(V,"refAttrName")&&O.uint32(170).string(V.refAttrName),V.sparseTensor!=null&&Object.hasOwnProperty.call(V,"sparseTensor")&&q.onnx.SparseTensorProto.encode(V.sparseTensor,O.uint32(178).fork()).ldelim(),V.sparseTensors!=null&&V.sparseTensors.length)for(var P=0;P<V.sparseTensors.length;++P)q.onnx.SparseTensorProto.encode(V.sparseTensors[P],O.uint32(186).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.AttributeProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.name=V.string();break}case 21:{N.refAttrName=V.string();break}case 13:{N.docString=V.string();break}case 20:{N.type=V.int32();break}case 2:{N.f=V.float();break}case 3:{N.i=V.int64();break}case 4:{N.s=V.bytes();break}case 5:{N.t=q.onnx.TensorProto.decode(V,V.uint32());break}case 6:{N.g=q.onnx.GraphProto.decode(V,V.uint32());break}case 22:{N.sparseTensor=q.onnx.SparseTensorProto.decode(V,V.uint32());break}case 14:{N.tp=q.onnx.TypeProto.decode(V,V.uint32());break}case 7:{if(N.floats&&N.floats.length||(N.floats=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.floats.push(V.float());else N.floats.push(V.float());break}case 8:{if(N.ints&&N.ints.length||(N.ints=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.ints.push(V.int64());else N.ints.push(V.int64());break}case 9:{N.strings&&N.strings.length||(N.strings=[]),N.strings.push(V.bytes());break}case 10:{N.tensors&&N.tensors.length||(N.tensors=[]),N.tensors.push(q.onnx.TensorProto.decode(V,V.uint32()));break}case 11:{N.graphs&&N.graphs.length||(N.graphs=[]),N.graphs.push(q.onnx.GraphProto.decode(V,V.uint32()));break}case 23:{N.sparseTensors&&N.sparseTensors.length||(N.sparseTensors=[]),N.sparseTensors.push(q.onnx.SparseTensorProto.decode(V,V.uint32()));break}case 15:{N.typeProtos&&N.typeProtos.length||(N.typeProtos=[]),N.typeProtos.push(q.onnx.TypeProto.decode(V,V.uint32()));break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.name!=null&&V.hasOwnProperty("name")&&!z.isString(V.name))return"name: string expected";if(V.refAttrName!=null&&V.hasOwnProperty("refAttrName")&&!z.isString(V.refAttrName))return"refAttrName: string expected";if(V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString))return"docString: string expected";if(V.type!=null&&V.hasOwnProperty("type"))switch(V.type){default:return"type: enum value expected";case 0:case 1:case 2:case 3:case 4:case 5:case 11:case 13:case 6:case 7:case 8:case 9:case 10:case 12:case 14:break}if(V.f!=null&&V.hasOwnProperty("f")&&typeof V.f!="number")return"f: number expected";if(V.i!=null&&V.hasOwnProperty("i")&&!z.isInteger(V.i)&&!(V.i&&z.isInteger(V.i.low)&&z.isInteger(V.i.high)))return"i: integer|Long expected";if(V.s!=null&&V.hasOwnProperty("s")&&!(V.s&&typeof V.s.length=="number"||z.isString(V.s)))return"s: buffer expected";if(V.t!=null&&V.hasOwnProperty("t")){var O=q.onnx.TensorProto.verify(V.t);if(O)return"t."+O}if(V.g!=null&&V.hasOwnProperty("g")){var O=q.onnx.GraphProto.verify(V.g);if(O)return"g."+O}if(V.sparseTensor!=null&&V.hasOwnProperty("sparseTensor")){var O=q.onnx.SparseTensorProto.verify(V.sparseTensor);if(O)return"sparseTensor."+O}if(V.tp!=null&&V.hasOwnProperty("tp")){var O=q.onnx.TypeProto.verify(V.tp);if(O)return"tp."+O}if(V.floats!=null&&V.hasOwnProperty("floats")){if(!Array.isArray(V.floats))return"floats: array expected";for(var P=0;P<V.floats.length;++P)if(typeof V.floats[P]!="number")return"floats: number[] expected"}if(V.ints!=null&&V.hasOwnProperty("ints")){if(!Array.isArray(V.ints))return"ints: array expected";for(var P=0;P<V.ints.length;++P)if(!z.isInteger(V.ints[P])&&!(V.ints[P]&&z.isInteger(V.ints[P].low)&&z.isInteger(V.ints[P].high)))return"ints: integer|Long[] expected"}if(V.strings!=null&&V.hasOwnProperty("strings")){if(!Array.isArray(V.strings))return"strings: array expected";for(var P=0;P<V.strings.length;++P)if(!(V.strings[P]&&typeof V.strings[P].length=="number"||z.isString(V.strings[P])))return"strings: buffer[] expected"}if(V.tensors!=null&&V.hasOwnProperty("tensors")){if(!Array.isArray(V.tensors))return"tensors: array expected";for(var P=0;P<V.tensors.length;++P){var O=q.onnx.TensorProto.verify(V.tensors[P]);if(O)return"tensors."+O}}if(V.graphs!=null&&V.hasOwnProperty("graphs")){if(!Array.isArray(V.graphs))return"graphs: array expected";for(var P=0;P<V.graphs.length;++P){var O=q.onnx.GraphProto.verify(V.graphs[P]);if(O)return"graphs."+O}}if(V.sparseTensors!=null&&V.hasOwnProperty("sparseTensors")){if(!Array.isArray(V.sparseTensors))return"sparseTensors: array expected";for(var P=0;P<V.sparseTensors.length;++P){var O=q.onnx.SparseTensorProto.verify(V.sparseTensors[P]);if(O)return"sparseTensors."+O}}if(V.typeProtos!=null&&V.hasOwnProperty("typeProtos")){if(!Array.isArray(V.typeProtos))return"typeProtos: array expected";for(var P=0;P<V.typeProtos.length;++P){var O=q.onnx.TypeProto.verify(V.typeProtos[P]);if(O)return"typeProtos."+O}}return null},D.fromObject=function(V){if(V instanceof q.onnx.AttributeProto)return V;var O=new q.onnx.AttributeProto;switch(V.name!=null&&(O.name=String(V.name)),V.refAttrName!=null&&(O.refAttrName=String(V.refAttrName)),V.docString!=null&&(O.docString=String(V.docString)),V.type){default:if(typeof V.type=="number"){O.type=V.type;break}break;case"UNDEFINED":case 0:O.type=0;break;case"FLOAT":case 1:O.type=1;break;case"INT":case 2:O.type=2;break;case"STRING":case 3:O.type=3;break;case"TENSOR":case 4:O.type=4;break;case"GRAPH":case 5:O.type=5;break;case"SPARSE_TENSOR":case 11:O.type=11;break;case"TYPE_PROTO":case 13:O.type=13;break;case"FLOATS":case 6:O.type=6;break;case"INTS":case 7:O.type=7;break;case"STRINGS":case 8:O.type=8;break;case"TENSORS":case 9:O.type=9;break;case"GRAPHS":case 10:O.type=10;break;case"SPARSE_TENSORS":case 12:O.type=12;break;case"TYPE_PROTOS":case 14:O.type=14;break}if(V.f!=null&&(O.f=Number(V.f)),V.i!=null&&(z.Long?(O.i=z.Long.fromValue(V.i)).unsigned=!1:typeof V.i=="string"?O.i=parseInt(V.i,10):typeof V.i=="number"?O.i=V.i:typeof V.i=="object"&&(O.i=new z.LongBits(V.i.low>>>0,V.i.high>>>0).toNumber())),V.s!=null&&(typeof V.s=="string"?z.base64.decode(V.s,O.s=z.newBuffer(z.base64.length(V.s)),0):V.s.length>=0&&(O.s=V.s)),V.t!=null){if(typeof V.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");O.t=q.onnx.TensorProto.fromObject(V.t)}if(V.g!=null){if(typeof V.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");O.g=q.onnx.GraphProto.fromObject(V.g)}if(V.sparseTensor!=null){if(typeof V.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");O.sparseTensor=q.onnx.SparseTensorProto.fromObject(V.sparseTensor)}if(V.tp!=null){if(typeof V.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");O.tp=q.onnx.TypeProto.fromObject(V.tp)}if(V.floats){if(!Array.isArray(V.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");O.floats=[];for(var P=0;P<V.floats.length;++P)O.floats[P]=Number(V.floats[P])}if(V.ints){if(!Array.isArray(V.ints))throw TypeError(".onnx.AttributeProto.ints: array expected");O.ints=[];for(var P=0;P<V.ints.length;++P)z.Long?(O.ints[P]=z.Long.fromValue(V.ints[P])).unsigned=!1:typeof V.ints[P]=="string"?O.ints[P]=parseInt(V.ints[P],10):typeof V.ints[P]=="number"?O.ints[P]=V.ints[P]:typeof V.ints[P]=="object"&&(O.ints[P]=new z.LongBits(V.ints[P].low>>>0,V.ints[P].high>>>0).toNumber())}if(V.strings){if(!Array.isArray(V.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");O.strings=[];for(var P=0;P<V.strings.length;++P)typeof V.strings[P]=="string"?z.base64.decode(V.strings[P],O.strings[P]=z.newBuffer(z.base64.length(V.strings[P])),0):V.strings[P].length>=0&&(O.strings[P]=V.strings[P])}if(V.tensors){if(!Array.isArray(V.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");O.tensors=[];for(var P=0;P<V.tensors.length;++P){if(typeof V.tensors[P]!="object")throw TypeError(".onnx.AttributeProto.tensors: object expected");O.tensors[P]=q.onnx.TensorProto.fromObject(V.tensors[P])}}if(V.graphs){if(!Array.isArray(V.graphs))throw TypeError(".onnx.AttributeProto.graphs: array expected");O.graphs=[];for(var P=0;P<V.graphs.length;++P){if(typeof V.graphs[P]!="object")throw TypeError(".onnx.AttributeProto.graphs: object expected");O.graphs[P]=q.onnx.GraphProto.fromObject(V.graphs[P])}}if(V.sparseTensors){if(!Array.isArray(V.sparseTensors))throw TypeError(".onnx.AttributeProto.sparseTensors: array expected");O.sparseTensors=[];for(var P=0;P<V.sparseTensors.length;++P){if(typeof V.sparseTensors[P]!="object")throw TypeError(".onnx.AttributeProto.sparseTensors: object expected");O.sparseTensors[P]=q.onnx.SparseTensorProto.fromObject(V.sparseTensors[P])}}if(V.typeProtos){if(!Array.isArray(V.typeProtos))throw TypeError(".onnx.AttributeProto.typeProtos: array expected");O.typeProtos=[];for(var P=0;P<V.typeProtos.length;++P){if(typeof V.typeProtos[P]!="object")throw TypeError(".onnx.AttributeProto.typeProtos: object expected");O.typeProtos[P]=q.onnx.TypeProto.fromObject(V.typeProtos[P])}}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.floats=[],P.ints=[],P.strings=[],P.tensors=[],P.graphs=[],P.typeProtos=[],P.sparseTensors=[]),O.defaults){if(P.name="",P.f=0,z.Long){var N=new z.Long(0,0,!1);P.i=O.longs===String?N.toString():O.longs===Number?N.toNumber():N}else P.i=O.longs===String?"0":0;O.bytes===String?P.s="":(P.s=[],O.bytes!==Array&&(P.s=z.newBuffer(P.s))),P.t=null,P.g=null,P.docString="",P.tp=null,P.type=O.enums===String?"UNDEFINED":0,P.refAttrName="",P.sparseTensor=null}if(V.name!=null&&V.hasOwnProperty("name")&&(P.name=V.name),V.f!=null&&V.hasOwnProperty("f")&&(P.f=O.json&&!isFinite(V.f)?String(V.f):V.f),V.i!=null&&V.hasOwnProperty("i")&&(typeof V.i=="number"?P.i=O.longs===String?String(V.i):V.i:P.i=O.longs===String?z.Long.prototype.toString.call(V.i):O.longs===Number?new z.LongBits(V.i.low>>>0,V.i.high>>>0).toNumber():V.i),V.s!=null&&V.hasOwnProperty("s")&&(P.s=O.bytes===String?z.base64.encode(V.s,0,V.s.length):O.bytes===Array?Array.prototype.slice.call(V.s):V.s),V.t!=null&&V.hasOwnProperty("t")&&(P.t=q.onnx.TensorProto.toObject(V.t,O)),V.g!=null&&V.hasOwnProperty("g")&&(P.g=q.onnx.GraphProto.toObject(V.g,O)),V.floats&&V.floats.length){P.floats=[];for(var I=0;I<V.floats.length;++I)P.floats[I]=O.json&&!isFinite(V.floats[I])?String(V.floats[I]):V.floats[I]}if(V.ints&&V.ints.length){P.ints=[];for(var I=0;I<V.ints.length;++I)typeof V.ints[I]=="number"?P.ints[I]=O.longs===String?String(V.ints[I]):V.ints[I]:P.ints[I]=O.longs===String?z.Long.prototype.toString.call(V.ints[I]):O.longs===Number?new z.LongBits(V.ints[I].low>>>0,V.ints[I].high>>>0).toNumber():V.ints[I]}if(V.strings&&V.strings.length){P.strings=[];for(var I=0;I<V.strings.length;++I)P.strings[I]=O.bytes===String?z.base64.encode(V.strings[I],0,V.strings[I].length):O.bytes===Array?Array.prototype.slice.call(V.strings[I]):V.strings[I]}if(V.tensors&&V.tensors.length){P.tensors=[];for(var I=0;I<V.tensors.length;++I)P.tensors[I]=q.onnx.TensorProto.toObject(V.tensors[I],O)}if(V.graphs&&V.graphs.length){P.graphs=[];for(var I=0;I<V.graphs.length;++I)P.graphs[I]=q.onnx.GraphProto.toObject(V.graphs[I],O)}if(V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),V.tp!=null&&V.hasOwnProperty("tp")&&(P.tp=q.onnx.TypeProto.toObject(V.tp,O)),V.typeProtos&&V.typeProtos.length){P.typeProtos=[];for(var I=0;I<V.typeProtos.length;++I)P.typeProtos[I]=q.onnx.TypeProto.toObject(V.typeProtos[I],O)}if(V.type!=null&&V.hasOwnProperty("type")&&(P.type=O.enums===String?q.onnx.AttributeProto.AttributeType[V.type]===void 0?V.type:q.onnx.AttributeProto.AttributeType[V.type]:V.type),V.refAttrName!=null&&V.hasOwnProperty("refAttrName")&&(P.refAttrName=V.refAttrName),V.sparseTensor!=null&&V.hasOwnProperty("sparseTensor")&&(P.sparseTensor=q.onnx.SparseTensorProto.toObject(V.sparseTensor,O)),V.sparseTensors&&V.sparseTensors.length){P.sparseTensors=[];for(var I=0;I<V.sparseTensors.length;++I)P.sparseTensors[I]=q.onnx.SparseTensorProto.toObject(V.sparseTensors[I],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.AttributeProto"},D.AttributeType=function(){var V={},O=Object.create(V);return O[V[0]="UNDEFINED"]=0,O[V[1]="FLOAT"]=1,O[V[2]="INT"]=2,O[V[3]="STRING"]=3,O[V[4]="TENSOR"]=4,O[V[5]="GRAPH"]=5,O[V[11]="SPARSE_TENSOR"]=11,O[V[13]="TYPE_PROTO"]=13,O[V[6]="FLOATS"]=6,O[V[7]="INTS"]=7,O[V[8]="STRINGS"]=8,O[V[9]="TENSORS"]=9,O[V[10]="GRAPHS"]=10,O[V[12]="SPARSE_TENSORS"]=12,O[V[14]="TYPE_PROTOS"]=14,O}(),D}(),F.ValueInfoProto=function(){function D(V){if(V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.name="",D.prototype.type=null,D.prototype.docString="",D.create=function(V){return new D(V)},D.encode=function(V,O){return O||(O=K.create()),V.name!=null&&Object.hasOwnProperty.call(V,"name")&&O.uint32(10).string(V.name),V.type!=null&&Object.hasOwnProperty.call(V,"type")&&q.onnx.TypeProto.encode(V.type,O.uint32(18).fork()).ldelim(),V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(26).string(V.docString),O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.ValueInfoProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.name=V.string();break}case 2:{N.type=q.onnx.TypeProto.decode(V,V.uint32());break}case 3:{N.docString=V.string();break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.name!=null&&V.hasOwnProperty("name")&&!z.isString(V.name))return"name: string expected";if(V.type!=null&&V.hasOwnProperty("type")){var O=q.onnx.TypeProto.verify(V.type);if(O)return"type."+O}return V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString)?"docString: string expected":null},D.fromObject=function(V){if(V instanceof q.onnx.ValueInfoProto)return V;var O=new q.onnx.ValueInfoProto;if(V.name!=null&&(O.name=String(V.name)),V.type!=null){if(typeof V.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");O.type=q.onnx.TypeProto.fromObject(V.type)}return V.docString!=null&&(O.docString=String(V.docString)),O},D.toObject=function(V,O){O||(O={});var P={};return O.defaults&&(P.name="",P.type=null,P.docString=""),V.name!=null&&V.hasOwnProperty("name")&&(P.name=V.name),V.type!=null&&V.hasOwnProperty("type")&&(P.type=q.onnx.TypeProto.toObject(V.type,O)),V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.ValueInfoProto"},D}(),F.NodeProto=function(){function D(V){if(this.input=[],this.output=[],this.attribute=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.input=z.emptyArray,D.prototype.output=z.emptyArray,D.prototype.name="",D.prototype.opType="",D.prototype.domain="",D.prototype.attribute=z.emptyArray,D.prototype.docString="",D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.input!=null&&V.input.length)for(var P=0;P<V.input.length;++P)O.uint32(10).string(V.input[P]);if(V.output!=null&&V.output.length)for(var P=0;P<V.output.length;++P)O.uint32(18).string(V.output[P]);if(V.name!=null&&Object.hasOwnProperty.call(V,"name")&&O.uint32(26).string(V.name),V.opType!=null&&Object.hasOwnProperty.call(V,"opType")&&O.uint32(34).string(V.opType),V.attribute!=null&&V.attribute.length)for(var P=0;P<V.attribute.length;++P)q.onnx.AttributeProto.encode(V.attribute[P],O.uint32(42).fork()).ldelim();return V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(50).string(V.docString),V.domain!=null&&Object.hasOwnProperty.call(V,"domain")&&O.uint32(58).string(V.domain),O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.NodeProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.input&&N.input.length||(N.input=[]),N.input.push(V.string());break}case 2:{N.output&&N.output.length||(N.output=[]),N.output.push(V.string());break}case 3:{N.name=V.string();break}case 4:{N.opType=V.string();break}case 7:{N.domain=V.string();break}case 5:{N.attribute&&N.attribute.length||(N.attribute=[]),N.attribute.push(q.onnx.AttributeProto.decode(V,V.uint32()));break}case 6:{N.docString=V.string();break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.input!=null&&V.hasOwnProperty("input")){if(!Array.isArray(V.input))return"input: array expected";for(var O=0;O<V.input.length;++O)if(!z.isString(V.input[O]))return"input: string[] expected"}if(V.output!=null&&V.hasOwnProperty("output")){if(!Array.isArray(V.output))return"output: array expected";for(var O=0;O<V.output.length;++O)if(!z.isString(V.output[O]))return"output: string[] expected"}if(V.name!=null&&V.hasOwnProperty("name")&&!z.isString(V.name))return"name: string expected";if(V.opType!=null&&V.hasOwnProperty("opType")&&!z.isString(V.opType))return"opType: string expected";if(V.domain!=null&&V.hasOwnProperty("domain")&&!z.isString(V.domain))return"domain: string expected";if(V.attribute!=null&&V.hasOwnProperty("attribute")){if(!Array.isArray(V.attribute))return"attribute: array expected";for(var O=0;O<V.attribute.length;++O){var P=q.onnx.AttributeProto.verify(V.attribute[O]);if(P)return"attribute."+P}}return V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString)?"docString: string expected":null},D.fromObject=function(V){if(V instanceof q.onnx.NodeProto)return V;var O=new q.onnx.NodeProto;if(V.input){if(!Array.isArray(V.input))throw TypeError(".onnx.NodeProto.input: array expected");O.input=[];for(var P=0;P<V.input.length;++P)O.input[P]=String(V.input[P])}if(V.output){if(!Array.isArray(V.output))throw TypeError(".onnx.NodeProto.output: array expected");O.output=[];for(var P=0;P<V.output.length;++P)O.output[P]=String(V.output[P])}if(V.name!=null&&(O.name=String(V.name)),V.opType!=null&&(O.opType=String(V.opType)),V.domain!=null&&(O.domain=String(V.domain)),V.attribute){if(!Array.isArray(V.attribute))throw TypeError(".onnx.NodeProto.attribute: array expected");O.attribute=[];for(var P=0;P<V.attribute.length;++P){if(typeof V.attribute[P]!="object")throw TypeError(".onnx.NodeProto.attribute: object expected");O.attribute[P]=q.onnx.AttributeProto.fromObject(V.attribute[P])}}return V.docString!=null&&(O.docString=String(V.docString)),O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.input=[],P.output=[],P.attribute=[]),O.defaults&&(P.name="",P.opType="",P.docString="",P.domain=""),V.input&&V.input.length){P.input=[];for(var N=0;N<V.input.length;++N)P.input[N]=V.input[N]}if(V.output&&V.output.length){P.output=[];for(var N=0;N<V.output.length;++N)P.output[N]=V.output[N]}if(V.name!=null&&V.hasOwnProperty("name")&&(P.name=V.name),V.opType!=null&&V.hasOwnProperty("opType")&&(P.opType=V.opType),V.attribute&&V.attribute.length){P.attribute=[];for(var N=0;N<V.attribute.length;++N)P.attribute[N]=q.onnx.AttributeProto.toObject(V.attribute[N],O)}return V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),V.domain!=null&&V.hasOwnProperty("domain")&&(P.domain=V.domain),P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.NodeProto"},D}(),F.TrainingInfoProto=function(){function D(V){if(this.initializationBinding=[],this.updateBinding=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.initialization=null,D.prototype.algorithm=null,D.prototype.initializationBinding=z.emptyArray,D.prototype.updateBinding=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.initialization!=null&&Object.hasOwnProperty.call(V,"initialization")&&q.onnx.GraphProto.encode(V.initialization,O.uint32(10).fork()).ldelim(),V.algorithm!=null&&Object.hasOwnProperty.call(V,"algorithm")&&q.onnx.GraphProto.encode(V.algorithm,O.uint32(18).fork()).ldelim(),V.initializationBinding!=null&&V.initializationBinding.length)for(var P=0;P<V.initializationBinding.length;++P)q.onnx.StringStringEntryProto.encode(V.initializationBinding[P],O.uint32(26).fork()).ldelim();if(V.updateBinding!=null&&V.updateBinding.length)for(var P=0;P<V.updateBinding.length;++P)q.onnx.StringStringEntryProto.encode(V.updateBinding[P],O.uint32(34).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.TrainingInfoProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.initialization=q.onnx.GraphProto.decode(V,V.uint32());break}case 2:{N.algorithm=q.onnx.GraphProto.decode(V,V.uint32());break}case 3:{N.initializationBinding&&N.initializationBinding.length||(N.initializationBinding=[]),N.initializationBinding.push(q.onnx.StringStringEntryProto.decode(V,V.uint32()));break}case 4:{N.updateBinding&&N.updateBinding.length||(N.updateBinding=[]),N.updateBinding.push(q.onnx.StringStringEntryProto.decode(V,V.uint32()));break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.initialization!=null&&V.hasOwnProperty("initialization")){var O=q.onnx.GraphProto.verify(V.initialization);if(O)return"initialization."+O}if(V.algorithm!=null&&V.hasOwnProperty("algorithm")){var O=q.onnx.GraphProto.verify(V.algorithm);if(O)return"algorithm."+O}if(V.initializationBinding!=null&&V.hasOwnProperty("initializationBinding")){if(!Array.isArray(V.initializationBinding))return"initializationBinding: array expected";for(var P=0;P<V.initializationBinding.length;++P){var O=q.onnx.StringStringEntryProto.verify(V.initializationBinding[P]);if(O)return"initializationBinding."+O}}if(V.updateBinding!=null&&V.hasOwnProperty("updateBinding")){if(!Array.isArray(V.updateBinding))return"updateBinding: array expected";for(var P=0;P<V.updateBinding.length;++P){var O=q.onnx.StringStringEntryProto.verify(V.updateBinding[P]);if(O)return"updateBinding."+O}}return null},D.fromObject=function(V){if(V instanceof q.onnx.TrainingInfoProto)return V;var O=new q.onnx.TrainingInfoProto;if(V.initialization!=null){if(typeof V.initialization!="object")throw TypeError(".onnx.TrainingInfoProto.initialization: object expected");O.initialization=q.onnx.GraphProto.fromObject(V.initialization)}if(V.algorithm!=null){if(typeof V.algorithm!="object")throw TypeError(".onnx.TrainingInfoProto.algorithm: object expected");O.algorithm=q.onnx.GraphProto.fromObject(V.algorithm)}if(V.initializationBinding){if(!Array.isArray(V.initializationBinding))throw TypeError(".onnx.TrainingInfoProto.initializationBinding: array expected");O.initializationBinding=[];for(var P=0;P<V.initializationBinding.length;++P){if(typeof V.initializationBinding[P]!="object")throw TypeError(".onnx.TrainingInfoProto.initializationBinding: object expected");O.initializationBinding[P]=q.onnx.StringStringEntryProto.fromObject(V.initializationBinding[P])}}if(V.updateBinding){if(!Array.isArray(V.updateBinding))throw TypeError(".onnx.TrainingInfoProto.updateBinding: array expected");O.updateBinding=[];for(var P=0;P<V.updateBinding.length;++P){if(typeof V.updateBinding[P]!="object")throw TypeError(".onnx.TrainingInfoProto.updateBinding: object expected");O.updateBinding[P]=q.onnx.StringStringEntryProto.fromObject(V.updateBinding[P])}}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.initializationBinding=[],P.updateBinding=[]),O.defaults&&(P.initialization=null,P.algorithm=null),V.initialization!=null&&V.hasOwnProperty("initialization")&&(P.initialization=q.onnx.GraphProto.toObject(V.initialization,O)),V.algorithm!=null&&V.hasOwnProperty("algorithm")&&(P.algorithm=q.onnx.GraphProto.toObject(V.algorithm,O)),V.initializationBinding&&V.initializationBinding.length){P.initializationBinding=[];for(var N=0;N<V.initializationBinding.length;++N)P.initializationBinding[N]=q.onnx.StringStringEntryProto.toObject(V.initializationBinding[N],O)}if(V.updateBinding&&V.updateBinding.length){P.updateBinding=[];for(var N=0;N<V.updateBinding.length;++N)P.updateBinding[N]=q.onnx.StringStringEntryProto.toObject(V.updateBinding[N],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.TrainingInfoProto"},D}(),F.ModelProto=function(){function D(V){if(this.opsetImport=[],this.metadataProps=[],this.trainingInfo=[],this.functions=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.irVersion=z.Long?z.Long.fromBits(0,0,!1):0,D.prototype.opsetImport=z.emptyArray,D.prototype.producerName="",D.prototype.producerVersion="",D.prototype.domain="",D.prototype.modelVersion=z.Long?z.Long.fromBits(0,0,!1):0,D.prototype.docString="",D.prototype.graph=null,D.prototype.metadataProps=z.emptyArray,D.prototype.trainingInfo=z.emptyArray,D.prototype.functions=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.irVersion!=null&&Object.hasOwnProperty.call(V,"irVersion")&&O.uint32(8).int64(V.irVersion),V.producerName!=null&&Object.hasOwnProperty.call(V,"producerName")&&O.uint32(18).string(V.producerName),V.producerVersion!=null&&Object.hasOwnProperty.call(V,"producerVersion")&&O.uint32(26).string(V.producerVersion),V.domain!=null&&Object.hasOwnProperty.call(V,"domain")&&O.uint32(34).string(V.domain),V.modelVersion!=null&&Object.hasOwnProperty.call(V,"modelVersion")&&O.uint32(40).int64(V.modelVersion),V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(50).string(V.docString),V.graph!=null&&Object.hasOwnProperty.call(V,"graph")&&q.onnx.GraphProto.encode(V.graph,O.uint32(58).fork()).ldelim(),V.opsetImport!=null&&V.opsetImport.length)for(var P=0;P<V.opsetImport.length;++P)q.onnx.OperatorSetIdProto.encode(V.opsetImport[P],O.uint32(66).fork()).ldelim();if(V.metadataProps!=null&&V.metadataProps.length)for(var P=0;P<V.metadataProps.length;++P)q.onnx.StringStringEntryProto.encode(V.metadataProps[P],O.uint32(114).fork()).ldelim();if(V.trainingInfo!=null&&V.trainingInfo.length)for(var P=0;P<V.trainingInfo.length;++P)q.onnx.TrainingInfoProto.encode(V.trainingInfo[P],O.uint32(162).fork()).ldelim();if(V.functions!=null&&V.functions.length)for(var P=0;P<V.functions.length;++P)q.onnx.FunctionProto.encode(V.functions[P],O.uint32(202).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.ModelProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.irVersion=V.int64();break}case 8:{N.opsetImport&&N.opsetImport.length||(N.opsetImport=[]),N.opsetImport.push(q.onnx.OperatorSetIdProto.decode(V,V.uint32()));break}case 2:{N.producerName=V.string();break}case 3:{N.producerVersion=V.string();break}case 4:{N.domain=V.string();break}case 5:{N.modelVersion=V.int64();break}case 6:{N.docString=V.string();break}case 7:{N.graph=q.onnx.GraphProto.decode(V,V.uint32());break}case 14:{N.metadataProps&&N.metadataProps.length||(N.metadataProps=[]),N.metadataProps.push(q.onnx.StringStringEntryProto.decode(V,V.uint32()));break}case 20:{N.trainingInfo&&N.trainingInfo.length||(N.trainingInfo=[]),N.trainingInfo.push(q.onnx.TrainingInfoProto.decode(V,V.uint32()));break}case 25:{N.functions&&N.functions.length||(N.functions=[]),N.functions.push(q.onnx.FunctionProto.decode(V,V.uint32()));break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.irVersion!=null&&V.hasOwnProperty("irVersion")&&!z.isInteger(V.irVersion)&&!(V.irVersion&&z.isInteger(V.irVersion.low)&&z.isInteger(V.irVersion.high)))return"irVersion: integer|Long expected";if(V.opsetImport!=null&&V.hasOwnProperty("opsetImport")){if(!Array.isArray(V.opsetImport))return"opsetImport: array expected";for(var O=0;O<V.opsetImport.length;++O){var P=q.onnx.OperatorSetIdProto.verify(V.opsetImport[O]);if(P)return"opsetImport."+P}}if(V.producerName!=null&&V.hasOwnProperty("producerName")&&!z.isString(V.producerName))return"producerName: string expected";if(V.producerVersion!=null&&V.hasOwnProperty("producerVersion")&&!z.isString(V.producerVersion))return"producerVersion: string expected";if(V.domain!=null&&V.hasOwnProperty("domain")&&!z.isString(V.domain))return"domain: string expected";if(V.modelVersion!=null&&V.hasOwnProperty("modelVersion")&&!z.isInteger(V.modelVersion)&&!(V.modelVersion&&z.isInteger(V.modelVersion.low)&&z.isInteger(V.modelVersion.high)))return"modelVersion: integer|Long expected";if(V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString))return"docString: string expected";if(V.graph!=null&&V.hasOwnProperty("graph")){var P=q.onnx.GraphProto.verify(V.graph);if(P)return"graph."+P}if(V.metadataProps!=null&&V.hasOwnProperty("metadataProps")){if(!Array.isArray(V.metadataProps))return"metadataProps: array expected";for(var O=0;O<V.metadataProps.length;++O){var P=q.onnx.StringStringEntryProto.verify(V.metadataProps[O]);if(P)return"metadataProps."+P}}if(V.trainingInfo!=null&&V.hasOwnProperty("trainingInfo")){if(!Array.isArray(V.trainingInfo))return"trainingInfo: array expected";for(var O=0;O<V.trainingInfo.length;++O){var P=q.onnx.TrainingInfoProto.verify(V.trainingInfo[O]);if(P)return"trainingInfo."+P}}if(V.functions!=null&&V.hasOwnProperty("functions")){if(!Array.isArray(V.functions))return"functions: array expected";for(var O=0;O<V.functions.length;++O){var P=q.onnx.FunctionProto.verify(V.functions[O]);if(P)return"functions."+P}}return null},D.fromObject=function(V){if(V instanceof q.onnx.ModelProto)return V;var O=new q.onnx.ModelProto;if(V.irVersion!=null&&(z.Long?(O.irVersion=z.Long.fromValue(V.irVersion)).unsigned=!1:typeof V.irVersion=="string"?O.irVersion=parseInt(V.irVersion,10):typeof V.irVersion=="number"?O.irVersion=V.irVersion:typeof V.irVersion=="object"&&(O.irVersion=new z.LongBits(V.irVersion.low>>>0,V.irVersion.high>>>0).toNumber())),V.opsetImport){if(!Array.isArray(V.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");O.opsetImport=[];for(var P=0;P<V.opsetImport.length;++P){if(typeof V.opsetImport[P]!="object")throw TypeError(".onnx.ModelProto.opsetImport: object expected");O.opsetImport[P]=q.onnx.OperatorSetIdProto.fromObject(V.opsetImport[P])}}if(V.producerName!=null&&(O.producerName=String(V.producerName)),V.producerVersion!=null&&(O.producerVersion=String(V.producerVersion)),V.domain!=null&&(O.domain=String(V.domain)),V.modelVersion!=null&&(z.Long?(O.modelVersion=z.Long.fromValue(V.modelVersion)).unsigned=!1:typeof V.modelVersion=="string"?O.modelVersion=parseInt(V.modelVersion,10):typeof V.modelVersion=="number"?O.modelVersion=V.modelVersion:typeof V.modelVersion=="object"&&(O.modelVersion=new z.LongBits(V.modelVersion.low>>>0,V.modelVersion.high>>>0).toNumber())),V.docString!=null&&(O.docString=String(V.docString)),V.graph!=null){if(typeof V.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");O.graph=q.onnx.GraphProto.fromObject(V.graph)}if(V.metadataProps){if(!Array.isArray(V.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");O.metadataProps=[];for(var P=0;P<V.metadataProps.length;++P){if(typeof V.metadataProps[P]!="object")throw TypeError(".onnx.ModelProto.metadataProps: object expected");O.metadataProps[P]=q.onnx.StringStringEntryProto.fromObject(V.metadataProps[P])}}if(V.trainingInfo){if(!Array.isArray(V.trainingInfo))throw TypeError(".onnx.ModelProto.trainingInfo: array expected");O.trainingInfo=[];for(var P=0;P<V.trainingInfo.length;++P){if(typeof V.trainingInfo[P]!="object")throw TypeError(".onnx.ModelProto.trainingInfo: object expected");O.trainingInfo[P]=q.onnx.TrainingInfoProto.fromObject(V.trainingInfo[P])}}if(V.functions){if(!Array.isArray(V.functions))throw TypeError(".onnx.ModelProto.functions: array expected");O.functions=[];for(var P=0;P<V.functions.length;++P){if(typeof V.functions[P]!="object")throw TypeError(".onnx.ModelProto.functions: object expected");O.functions[P]=q.onnx.FunctionProto.fromObject(V.functions[P])}}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.opsetImport=[],P.metadataProps=[],P.trainingInfo=[],P.functions=[]),O.defaults){if(z.Long){var N=new z.Long(0,0,!1);P.irVersion=O.longs===String?N.toString():O.longs===Number?N.toNumber():N}else P.irVersion=O.longs===String?"0":0;if(P.producerName="",P.producerVersion="",P.domain="",z.Long){var N=new z.Long(0,0,!1);P.modelVersion=O.longs===String?N.toString():O.longs===Number?N.toNumber():N}else P.modelVersion=O.longs===String?"0":0;P.docString="",P.graph=null}if(V.irVersion!=null&&V.hasOwnProperty("irVersion")&&(typeof V.irVersion=="number"?P.irVersion=O.longs===String?String(V.irVersion):V.irVersion:P.irVersion=O.longs===String?z.Long.prototype.toString.call(V.irVersion):O.longs===Number?new z.LongBits(V.irVersion.low>>>0,V.irVersion.high>>>0).toNumber():V.irVersion),V.producerName!=null&&V.hasOwnProperty("producerName")&&(P.producerName=V.producerName),V.producerVersion!=null&&V.hasOwnProperty("producerVersion")&&(P.producerVersion=V.producerVersion),V.domain!=null&&V.hasOwnProperty("domain")&&(P.domain=V.domain),V.modelVersion!=null&&V.hasOwnProperty("modelVersion")&&(typeof V.modelVersion=="number"?P.modelVersion=O.longs===String?String(V.modelVersion):V.modelVersion:P.modelVersion=O.longs===String?z.Long.prototype.toString.call(V.modelVersion):O.longs===Number?new z.LongBits(V.modelVersion.low>>>0,V.modelVersion.high>>>0).toNumber():V.modelVersion),V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),V.graph!=null&&V.hasOwnProperty("graph")&&(P.graph=q.onnx.GraphProto.toObject(V.graph,O)),V.opsetImport&&V.opsetImport.length){P.opsetImport=[];for(var I=0;I<V.opsetImport.length;++I)P.opsetImport[I]=q.onnx.OperatorSetIdProto.toObject(V.opsetImport[I],O)}if(V.metadataProps&&V.metadataProps.length){P.metadataProps=[];for(var I=0;I<V.metadataProps.length;++I)P.metadataProps[I]=q.onnx.StringStringEntryProto.toObject(V.metadataProps[I],O)}if(V.trainingInfo&&V.trainingInfo.length){P.trainingInfo=[];for(var I=0;I<V.trainingInfo.length;++I)P.trainingInfo[I]=q.onnx.TrainingInfoProto.toObject(V.trainingInfo[I],O)}if(V.functions&&V.functions.length){P.functions=[];for(var I=0;I<V.functions.length;++I)P.functions[I]=q.onnx.FunctionProto.toObject(V.functions[I],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.ModelProto"},D}(),F.StringStringEntryProto=function(){function D(V){if(V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.key="",D.prototype.value="",D.create=function(V){return new D(V)},D.encode=function(V,O){return O||(O=K.create()),V.key!=null&&Object.hasOwnProperty.call(V,"key")&&O.uint32(10).string(V.key),V.value!=null&&Object.hasOwnProperty.call(V,"value")&&O.uint32(18).string(V.value),O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.StringStringEntryProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.key=V.string();break}case 2:{N.value=V.string();break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){return typeof V!="object"||V===null?"object expected":V.key!=null&&V.hasOwnProperty("key")&&!z.isString(V.key)?"key: string expected":V.value!=null&&V.hasOwnProperty("value")&&!z.isString(V.value)?"value: string expected":null},D.fromObject=function(V){if(V instanceof q.onnx.StringStringEntryProto)return V;var O=new q.onnx.StringStringEntryProto;return V.key!=null&&(O.key=String(V.key)),V.value!=null&&(O.value=String(V.value)),O},D.toObject=function(V,O){O||(O={});var P={};return O.defaults&&(P.key="",P.value=""),V.key!=null&&V.hasOwnProperty("key")&&(P.key=V.key),V.value!=null&&V.hasOwnProperty("value")&&(P.value=V.value),P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.StringStringEntryProto"},D}(),F.TensorAnnotation=function(){function D(V){if(this.quantParameterTensorNames=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.tensorName="",D.prototype.quantParameterTensorNames=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.tensorName!=null&&Object.hasOwnProperty.call(V,"tensorName")&&O.uint32(10).string(V.tensorName),V.quantParameterTensorNames!=null&&V.quantParameterTensorNames.length)for(var P=0;P<V.quantParameterTensorNames.length;++P)q.onnx.StringStringEntryProto.encode(V.quantParameterTensorNames[P],O.uint32(18).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.TensorAnnotation;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.tensorName=V.string();break}case 2:{N.quantParameterTensorNames&&N.quantParameterTensorNames.length||(N.quantParameterTensorNames=[]),N.quantParameterTensorNames.push(q.onnx.StringStringEntryProto.decode(V,V.uint32()));break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.tensorName!=null&&V.hasOwnProperty("tensorName")&&!z.isString(V.tensorName))return"tensorName: string expected";if(V.quantParameterTensorNames!=null&&V.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(V.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var O=0;O<V.quantParameterTensorNames.length;++O){var P=q.onnx.StringStringEntryProto.verify(V.quantParameterTensorNames[O]);if(P)return"quantParameterTensorNames."+P}}return null},D.fromObject=function(V){if(V instanceof q.onnx.TensorAnnotation)return V;var O=new q.onnx.TensorAnnotation;if(V.tensorName!=null&&(O.tensorName=String(V.tensorName)),V.quantParameterTensorNames){if(!Array.isArray(V.quantParameterTensorNames))throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: array expected");O.quantParameterTensorNames=[];for(var P=0;P<V.quantParameterTensorNames.length;++P){if(typeof V.quantParameterTensorNames[P]!="object")throw TypeError(".onnx.TensorAnnotation.quantParameterTensorNames: object expected");O.quantParameterTensorNames[P]=q.onnx.StringStringEntryProto.fromObject(V.quantParameterTensorNames[P])}}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.quantParameterTensorNames=[]),O.defaults&&(P.tensorName=""),V.tensorName!=null&&V.hasOwnProperty("tensorName")&&(P.tensorName=V.tensorName),V.quantParameterTensorNames&&V.quantParameterTensorNames.length){P.quantParameterTensorNames=[];for(var N=0;N<V.quantParameterTensorNames.length;++N)P.quantParameterTensorNames[N]=q.onnx.StringStringEntryProto.toObject(V.quantParameterTensorNames[N],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.TensorAnnotation"},D}(),F.GraphProto=function(){function D(V){if(this.node=[],this.initializer=[],this.sparseInitializer=[],this.input=[],this.output=[],this.valueInfo=[],this.quantizationAnnotation=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.node=z.emptyArray,D.prototype.name="",D.prototype.initializer=z.emptyArray,D.prototype.sparseInitializer=z.emptyArray,D.prototype.docString="",D.prototype.input=z.emptyArray,D.prototype.output=z.emptyArray,D.prototype.valueInfo=z.emptyArray,D.prototype.quantizationAnnotation=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.node!=null&&V.node.length)for(var P=0;P<V.node.length;++P)q.onnx.NodeProto.encode(V.node[P],O.uint32(10).fork()).ldelim();if(V.name!=null&&Object.hasOwnProperty.call(V,"name")&&O.uint32(18).string(V.name),V.initializer!=null&&V.initializer.length)for(var P=0;P<V.initializer.length;++P)q.onnx.TensorProto.encode(V.initializer[P],O.uint32(42).fork()).ldelim();if(V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(82).string(V.docString),V.input!=null&&V.input.length)for(var P=0;P<V.input.length;++P)q.onnx.ValueInfoProto.encode(V.input[P],O.uint32(90).fork()).ldelim();if(V.output!=null&&V.output.length)for(var P=0;P<V.output.length;++P)q.onnx.ValueInfoProto.encode(V.output[P],O.uint32(98).fork()).ldelim();if(V.valueInfo!=null&&V.valueInfo.length)for(var P=0;P<V.valueInfo.length;++P)q.onnx.ValueInfoProto.encode(V.valueInfo[P],O.uint32(106).fork()).ldelim();if(V.quantizationAnnotation!=null&&V.quantizationAnnotation.length)for(var P=0;P<V.quantizationAnnotation.length;++P)q.onnx.TensorAnnotation.encode(V.quantizationAnnotation[P],O.uint32(114).fork()).ldelim();if(V.sparseInitializer!=null&&V.sparseInitializer.length)for(var P=0;P<V.sparseInitializer.length;++P)q.onnx.SparseTensorProto.encode(V.sparseInitializer[P],O.uint32(122).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.GraphProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.node&&N.node.length||(N.node=[]),N.node.push(q.onnx.NodeProto.decode(V,V.uint32()));break}case 2:{N.name=V.string();break}case 5:{N.initializer&&N.initializer.length||(N.initializer=[]),N.initializer.push(q.onnx.TensorProto.decode(V,V.uint32()));break}case 15:{N.sparseInitializer&&N.sparseInitializer.length||(N.sparseInitializer=[]),N.sparseInitializer.push(q.onnx.SparseTensorProto.decode(V,V.uint32()));break}case 10:{N.docString=V.string();break}case 11:{N.input&&N.input.length||(N.input=[]),N.input.push(q.onnx.ValueInfoProto.decode(V,V.uint32()));break}case 12:{N.output&&N.output.length||(N.output=[]),N.output.push(q.onnx.ValueInfoProto.decode(V,V.uint32()));break}case 13:{N.valueInfo&&N.valueInfo.length||(N.valueInfo=[]),N.valueInfo.push(q.onnx.ValueInfoProto.decode(V,V.uint32()));break}case 14:{N.quantizationAnnotation&&N.quantizationAnnotation.length||(N.quantizationAnnotation=[]),N.quantizationAnnotation.push(q.onnx.TensorAnnotation.decode(V,V.uint32()));break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.node!=null&&V.hasOwnProperty("node")){if(!Array.isArray(V.node))return"node: array expected";for(var O=0;O<V.node.length;++O){var P=q.onnx.NodeProto.verify(V.node[O]);if(P)return"node."+P}}if(V.name!=null&&V.hasOwnProperty("name")&&!z.isString(V.name))return"name: string expected";if(V.initializer!=null&&V.hasOwnProperty("initializer")){if(!Array.isArray(V.initializer))return"initializer: array expected";for(var O=0;O<V.initializer.length;++O){var P=q.onnx.TensorProto.verify(V.initializer[O]);if(P)return"initializer."+P}}if(V.sparseInitializer!=null&&V.hasOwnProperty("sparseInitializer")){if(!Array.isArray(V.sparseInitializer))return"sparseInitializer: array expected";for(var O=0;O<V.sparseInitializer.length;++O){var P=q.onnx.SparseTensorProto.verify(V.sparseInitializer[O]);if(P)return"sparseInitializer."+P}}if(V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString))return"docString: string expected";if(V.input!=null&&V.hasOwnProperty("input")){if(!Array.isArray(V.input))return"input: array expected";for(var O=0;O<V.input.length;++O){var P=q.onnx.ValueInfoProto.verify(V.input[O]);if(P)return"input."+P}}if(V.output!=null&&V.hasOwnProperty("output")){if(!Array.isArray(V.output))return"output: array expected";for(var O=0;O<V.output.length;++O){var P=q.onnx.ValueInfoProto.verify(V.output[O]);if(P)return"output."+P}}if(V.valueInfo!=null&&V.hasOwnProperty("valueInfo")){if(!Array.isArray(V.valueInfo))return"valueInfo: array expected";for(var O=0;O<V.valueInfo.length;++O){var P=q.onnx.ValueInfoProto.verify(V.valueInfo[O]);if(P)return"valueInfo."+P}}if(V.quantizationAnnotation!=null&&V.hasOwnProperty("quantizationAnnotation")){if(!Array.isArray(V.quantizationAnnotation))return"quantizationAnnotation: array expected";for(var O=0;O<V.quantizationAnnotation.length;++O){var P=q.onnx.TensorAnnotation.verify(V.quantizationAnnotation[O]);if(P)return"quantizationAnnotation."+P}}return null},D.fromObject=function(V){if(V instanceof q.onnx.GraphProto)return V;var O=new q.onnx.GraphProto;if(V.node){if(!Array.isArray(V.node))throw TypeError(".onnx.GraphProto.node: array expected");O.node=[];for(var P=0;P<V.node.length;++P){if(typeof V.node[P]!="object")throw TypeError(".onnx.GraphProto.node: object expected");O.node[P]=q.onnx.NodeProto.fromObject(V.node[P])}}if(V.name!=null&&(O.name=String(V.name)),V.initializer){if(!Array.isArray(V.initializer))throw TypeError(".onnx.GraphProto.initializer: array expected");O.initializer=[];for(var P=0;P<V.initializer.length;++P){if(typeof V.initializer[P]!="object")throw TypeError(".onnx.GraphProto.initializer: object expected");O.initializer[P]=q.onnx.TensorProto.fromObject(V.initializer[P])}}if(V.sparseInitializer){if(!Array.isArray(V.sparseInitializer))throw TypeError(".onnx.GraphProto.sparseInitializer: array expected");O.sparseInitializer=[];for(var P=0;P<V.sparseInitializer.length;++P){if(typeof V.sparseInitializer[P]!="object")throw TypeError(".onnx.GraphProto.sparseInitializer: object expected");O.sparseInitializer[P]=q.onnx.SparseTensorProto.fromObject(V.sparseInitializer[P])}}if(V.docString!=null&&(O.docString=String(V.docString)),V.input){if(!Array.isArray(V.input))throw TypeError(".onnx.GraphProto.input: array expected");O.input=[];for(var P=0;P<V.input.length;++P){if(typeof V.input[P]!="object")throw TypeError(".onnx.GraphProto.input: object expected");O.input[P]=q.onnx.ValueInfoProto.fromObject(V.input[P])}}if(V.output){if(!Array.isArray(V.output))throw TypeError(".onnx.GraphProto.output: array expected");O.output=[];for(var P=0;P<V.output.length;++P){if(typeof V.output[P]!="object")throw TypeError(".onnx.GraphProto.output: object expected");O.output[P]=q.onnx.ValueInfoProto.fromObject(V.output[P])}}if(V.valueInfo){if(!Array.isArray(V.valueInfo))throw TypeError(".onnx.GraphProto.valueInfo: array expected");O.valueInfo=[];for(var P=0;P<V.valueInfo.length;++P){if(typeof V.valueInfo[P]!="object")throw TypeError(".onnx.GraphProto.valueInfo: object expected");O.valueInfo[P]=q.onnx.ValueInfoProto.fromObject(V.valueInfo[P])}}if(V.quantizationAnnotation){if(!Array.isArray(V.quantizationAnnotation))throw TypeError(".onnx.GraphProto.quantizationAnnotation: array expected");O.quantizationAnnotation=[];for(var P=0;P<V.quantizationAnnotation.length;++P){if(typeof V.quantizationAnnotation[P]!="object")throw TypeError(".onnx.GraphProto.quantizationAnnotation: object expected");O.quantizationAnnotation[P]=q.onnx.TensorAnnotation.fromObject(V.quantizationAnnotation[P])}}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.node=[],P.initializer=[],P.input=[],P.output=[],P.valueInfo=[],P.quantizationAnnotation=[],P.sparseInitializer=[]),O.defaults&&(P.name="",P.docString=""),V.node&&V.node.length){P.node=[];for(var N=0;N<V.node.length;++N)P.node[N]=q.onnx.NodeProto.toObject(V.node[N],O)}if(V.name!=null&&V.hasOwnProperty("name")&&(P.name=V.name),V.initializer&&V.initializer.length){P.initializer=[];for(var N=0;N<V.initializer.length;++N)P.initializer[N]=q.onnx.TensorProto.toObject(V.initializer[N],O)}if(V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),V.input&&V.input.length){P.input=[];for(var N=0;N<V.input.length;++N)P.input[N]=q.onnx.ValueInfoProto.toObject(V.input[N],O)}if(V.output&&V.output.length){P.output=[];for(var N=0;N<V.output.length;++N)P.output[N]=q.onnx.ValueInfoProto.toObject(V.output[N],O)}if(V.valueInfo&&V.valueInfo.length){P.valueInfo=[];for(var N=0;N<V.valueInfo.length;++N)P.valueInfo[N]=q.onnx.ValueInfoProto.toObject(V.valueInfo[N],O)}if(V.quantizationAnnotation&&V.quantizationAnnotation.length){P.quantizationAnnotation=[];for(var N=0;N<V.quantizationAnnotation.length;++N)P.quantizationAnnotation[N]=q.onnx.TensorAnnotation.toObject(V.quantizationAnnotation[N],O)}if(V.sparseInitializer&&V.sparseInitializer.length){P.sparseInitializer=[];for(var N=0;N<V.sparseInitializer.length;++N)P.sparseInitializer[N]=q.onnx.SparseTensorProto.toObject(V.sparseInitializer[N],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.GraphProto"},D}(),F.TensorProto=function(){function D(V){if(this.dims=[],this.floatData=[],this.int32Data=[],this.stringData=[],this.int64Data=[],this.externalData=[],this.doubleData=[],this.uint64Data=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.dims=z.emptyArray,D.prototype.dataType=0,D.prototype.segment=null,D.prototype.floatData=z.emptyArray,D.prototype.int32Data=z.emptyArray,D.prototype.stringData=z.emptyArray,D.prototype.int64Data=z.emptyArray,D.prototype.name="",D.prototype.docString="",D.prototype.rawData=z.newBuffer([]),D.prototype.externalData=z.emptyArray,D.prototype.dataLocation=0,D.prototype.doubleData=z.emptyArray,D.prototype.uint64Data=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.dims!=null&&V.dims.length){O.uint32(10).fork();for(var P=0;P<V.dims.length;++P)O.int64(V.dims[P]);O.ldelim()}if(V.dataType!=null&&Object.hasOwnProperty.call(V,"dataType")&&O.uint32(16).int32(V.dataType),V.segment!=null&&Object.hasOwnProperty.call(V,"segment")&&q.onnx.TensorProto.Segment.encode(V.segment,O.uint32(26).fork()).ldelim(),V.floatData!=null&&V.floatData.length){O.uint32(34).fork();for(var P=0;P<V.floatData.length;++P)O.float(V.floatData[P]);O.ldelim()}if(V.int32Data!=null&&V.int32Data.length){O.uint32(42).fork();for(var P=0;P<V.int32Data.length;++P)O.int32(V.int32Data[P]);O.ldelim()}if(V.stringData!=null&&V.stringData.length)for(var P=0;P<V.stringData.length;++P)O.uint32(50).bytes(V.stringData[P]);if(V.int64Data!=null&&V.int64Data.length){O.uint32(58).fork();for(var P=0;P<V.int64Data.length;++P)O.int64(V.int64Data[P]);O.ldelim()}if(V.name!=null&&Object.hasOwnProperty.call(V,"name")&&O.uint32(66).string(V.name),V.rawData!=null&&Object.hasOwnProperty.call(V,"rawData")&&O.uint32(74).bytes(V.rawData),V.doubleData!=null&&V.doubleData.length){O.uint32(82).fork();for(var P=0;P<V.doubleData.length;++P)O.double(V.doubleData[P]);O.ldelim()}if(V.uint64Data!=null&&V.uint64Data.length){O.uint32(90).fork();for(var P=0;P<V.uint64Data.length;++P)O.uint64(V.uint64Data[P]);O.ldelim()}if(V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(98).string(V.docString),V.externalData!=null&&V.externalData.length)for(var P=0;P<V.externalData.length;++P)q.onnx.StringStringEntryProto.encode(V.externalData[P],O.uint32(106).fork()).ldelim();return V.dataLocation!=null&&Object.hasOwnProperty.call(V,"dataLocation")&&O.uint32(112).int32(V.dataLocation),O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.TensorProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{if(N.dims&&N.dims.length||(N.dims=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.dims.push(V.int64());else N.dims.push(V.int64());break}case 2:{N.dataType=V.int32();break}case 3:{N.segment=q.onnx.TensorProto.Segment.decode(V,V.uint32());break}case 4:{if(N.floatData&&N.floatData.length||(N.floatData=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.floatData.push(V.float());else N.floatData.push(V.float());break}case 5:{if(N.int32Data&&N.int32Data.length||(N.int32Data=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.int32Data.push(V.int32());else N.int32Data.push(V.int32());break}case 6:{N.stringData&&N.stringData.length||(N.stringData=[]),N.stringData.push(V.bytes());break}case 7:{if(N.int64Data&&N.int64Data.length||(N.int64Data=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.int64Data.push(V.int64());else N.int64Data.push(V.int64());break}case 8:{N.name=V.string();break}case 12:{N.docString=V.string();break}case 9:{N.rawData=V.bytes();break}case 13:{N.externalData&&N.externalData.length||(N.externalData=[]),N.externalData.push(q.onnx.StringStringEntryProto.decode(V,V.uint32()));break}case 14:{N.dataLocation=V.int32();break}case 10:{if(N.doubleData&&N.doubleData.length||(N.doubleData=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.doubleData.push(V.double());else N.doubleData.push(V.double());break}case 11:{if(N.uint64Data&&N.uint64Data.length||(N.uint64Data=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.uint64Data.push(V.uint64());else N.uint64Data.push(V.uint64());break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.dims!=null&&V.hasOwnProperty("dims")){if(!Array.isArray(V.dims))return"dims: array expected";for(var O=0;O<V.dims.length;++O)if(!z.isInteger(V.dims[O])&&!(V.dims[O]&&z.isInteger(V.dims[O].low)&&z.isInteger(V.dims[O].high)))return"dims: integer|Long[] expected"}if(V.dataType!=null&&V.hasOwnProperty("dataType")&&!z.isInteger(V.dataType))return"dataType: integer expected";if(V.segment!=null&&V.hasOwnProperty("segment")){var P=q.onnx.TensorProto.Segment.verify(V.segment);if(P)return"segment."+P}if(V.floatData!=null&&V.hasOwnProperty("floatData")){if(!Array.isArray(V.floatData))return"floatData: array expected";for(var O=0;O<V.floatData.length;++O)if(typeof V.floatData[O]!="number")return"floatData: number[] expected"}if(V.int32Data!=null&&V.hasOwnProperty("int32Data")){if(!Array.isArray(V.int32Data))return"int32Data: array expected";for(var O=0;O<V.int32Data.length;++O)if(!z.isInteger(V.int32Data[O]))return"int32Data: integer[] expected"}if(V.stringData!=null&&V.hasOwnProperty("stringData")){if(!Array.isArray(V.stringData))return"stringData: array expected";for(var O=0;O<V.stringData.length;++O)if(!(V.stringData[O]&&typeof V.stringData[O].length=="number"||z.isString(V.stringData[O])))return"stringData: buffer[] expected"}if(V.int64Data!=null&&V.hasOwnProperty("int64Data")){if(!Array.isArray(V.int64Data))return"int64Data: array expected";for(var O=0;O<V.int64Data.length;++O)if(!z.isInteger(V.int64Data[O])&&!(V.int64Data[O]&&z.isInteger(V.int64Data[O].low)&&z.isInteger(V.int64Data[O].high)))return"int64Data: integer|Long[] expected"}if(V.name!=null&&V.hasOwnProperty("name")&&!z.isString(V.name))return"name: string expected";if(V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString))return"docString: string expected";if(V.rawData!=null&&V.hasOwnProperty("rawData")&&!(V.rawData&&typeof V.rawData.length=="number"||z.isString(V.rawData)))return"rawData: buffer expected";if(V.externalData!=null&&V.hasOwnProperty("externalData")){if(!Array.isArray(V.externalData))return"externalData: array expected";for(var O=0;O<V.externalData.length;++O){var P=q.onnx.StringStringEntryProto.verify(V.externalData[O]);if(P)return"externalData."+P}}if(V.dataLocation!=null&&V.hasOwnProperty("dataLocation"))switch(V.dataLocation){default:return"dataLocation: enum value expected";case 0:case 1:break}if(V.doubleData!=null&&V.hasOwnProperty("doubleData")){if(!Array.isArray(V.doubleData))return"doubleData: array expected";for(var O=0;O<V.doubleData.length;++O)if(typeof V.doubleData[O]!="number")return"doubleData: number[] expected"}if(V.uint64Data!=null&&V.hasOwnProperty("uint64Data")){if(!Array.isArray(V.uint64Data))return"uint64Data: array expected";for(var O=0;O<V.uint64Data.length;++O)if(!z.isInteger(V.uint64Data[O])&&!(V.uint64Data[O]&&z.isInteger(V.uint64Data[O].low)&&z.isInteger(V.uint64Data[O].high)))return"uint64Data: integer|Long[] expected"}return null},D.fromObject=function(V){if(V instanceof q.onnx.TensorProto)return V;var O=new q.onnx.TensorProto;if(V.dims){if(!Array.isArray(V.dims))throw TypeError(".onnx.TensorProto.dims: array expected");O.dims=[];for(var P=0;P<V.dims.length;++P)z.Long?(O.dims[P]=z.Long.fromValue(V.dims[P])).unsigned=!1:typeof V.dims[P]=="string"?O.dims[P]=parseInt(V.dims[P],10):typeof V.dims[P]=="number"?O.dims[P]=V.dims[P]:typeof V.dims[P]=="object"&&(O.dims[P]=new z.LongBits(V.dims[P].low>>>0,V.dims[P].high>>>0).toNumber())}if(V.dataType!=null&&(O.dataType=V.dataType|0),V.segment!=null){if(typeof V.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");O.segment=q.onnx.TensorProto.Segment.fromObject(V.segment)}if(V.floatData){if(!Array.isArray(V.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");O.floatData=[];for(var P=0;P<V.floatData.length;++P)O.floatData[P]=Number(V.floatData[P])}if(V.int32Data){if(!Array.isArray(V.int32Data))throw TypeError(".onnx.TensorProto.int32Data: array expected");O.int32Data=[];for(var P=0;P<V.int32Data.length;++P)O.int32Data[P]=V.int32Data[P]|0}if(V.stringData){if(!Array.isArray(V.stringData))throw TypeError(".onnx.TensorProto.stringData: array expected");O.stringData=[];for(var P=0;P<V.stringData.length;++P)typeof V.stringData[P]=="string"?z.base64.decode(V.stringData[P],O.stringData[P]=z.newBuffer(z.base64.length(V.stringData[P])),0):V.stringData[P].length>=0&&(O.stringData[P]=V.stringData[P])}if(V.int64Data){if(!Array.isArray(V.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");O.int64Data=[];for(var P=0;P<V.int64Data.length;++P)z.Long?(O.int64Data[P]=z.Long.fromValue(V.int64Data[P])).unsigned=!1:typeof V.int64Data[P]=="string"?O.int64Data[P]=parseInt(V.int64Data[P],10):typeof V.int64Data[P]=="number"?O.int64Data[P]=V.int64Data[P]:typeof V.int64Data[P]=="object"&&(O.int64Data[P]=new z.LongBits(V.int64Data[P].low>>>0,V.int64Data[P].high>>>0).toNumber())}if(V.name!=null&&(O.name=String(V.name)),V.docString!=null&&(O.docString=String(V.docString)),V.rawData!=null&&(typeof V.rawData=="string"?z.base64.decode(V.rawData,O.rawData=z.newBuffer(z.base64.length(V.rawData)),0):V.rawData.length>=0&&(O.rawData=V.rawData)),V.externalData){if(!Array.isArray(V.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");O.externalData=[];for(var P=0;P<V.externalData.length;++P){if(typeof V.externalData[P]!="object")throw TypeError(".onnx.TensorProto.externalData: object expected");O.externalData[P]=q.onnx.StringStringEntryProto.fromObject(V.externalData[P])}}switch(V.dataLocation){default:if(typeof V.dataLocation=="number"){O.dataLocation=V.dataLocation;break}break;case"DEFAULT":case 0:O.dataLocation=0;break;case"EXTERNAL":case 1:O.dataLocation=1;break}if(V.doubleData){if(!Array.isArray(V.doubleData))throw TypeError(".onnx.TensorProto.doubleData: array expected");O.doubleData=[];for(var P=0;P<V.doubleData.length;++P)O.doubleData[P]=Number(V.doubleData[P])}if(V.uint64Data){if(!Array.isArray(V.uint64Data))throw TypeError(".onnx.TensorProto.uint64Data: array expected");O.uint64Data=[];for(var P=0;P<V.uint64Data.length;++P)z.Long?(O.uint64Data[P]=z.Long.fromValue(V.uint64Data[P])).unsigned=!0:typeof V.uint64Data[P]=="string"?O.uint64Data[P]=parseInt(V.uint64Data[P],10):typeof V.uint64Data[P]=="number"?O.uint64Data[P]=V.uint64Data[P]:typeof V.uint64Data[P]=="object"&&(O.uint64Data[P]=new z.LongBits(V.uint64Data[P].low>>>0,V.uint64Data[P].high>>>0).toNumber(!0))}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.dims=[],P.floatData=[],P.int32Data=[],P.stringData=[],P.int64Data=[],P.doubleData=[],P.uint64Data=[],P.externalData=[]),O.defaults&&(P.dataType=0,P.segment=null,P.name="",O.bytes===String?P.rawData="":(P.rawData=[],O.bytes!==Array&&(P.rawData=z.newBuffer(P.rawData))),P.docString="",P.dataLocation=O.enums===String?"DEFAULT":0),V.dims&&V.dims.length){P.dims=[];for(var N=0;N<V.dims.length;++N)typeof V.dims[N]=="number"?P.dims[N]=O.longs===String?String(V.dims[N]):V.dims[N]:P.dims[N]=O.longs===String?z.Long.prototype.toString.call(V.dims[N]):O.longs===Number?new z.LongBits(V.dims[N].low>>>0,V.dims[N].high>>>0).toNumber():V.dims[N]}if(V.dataType!=null&&V.hasOwnProperty("dataType")&&(P.dataType=V.dataType),V.segment!=null&&V.hasOwnProperty("segment")&&(P.segment=q.onnx.TensorProto.Segment.toObject(V.segment,O)),V.floatData&&V.floatData.length){P.floatData=[];for(var N=0;N<V.floatData.length;++N)P.floatData[N]=O.json&&!isFinite(V.floatData[N])?String(V.floatData[N]):V.floatData[N]}if(V.int32Data&&V.int32Data.length){P.int32Data=[];for(var N=0;N<V.int32Data.length;++N)P.int32Data[N]=V.int32Data[N]}if(V.stringData&&V.stringData.length){P.stringData=[];for(var N=0;N<V.stringData.length;++N)P.stringData[N]=O.bytes===String?z.base64.encode(V.stringData[N],0,V.stringData[N].length):O.bytes===Array?Array.prototype.slice.call(V.stringData[N]):V.stringData[N]}if(V.int64Data&&V.int64Data.length){P.int64Data=[];for(var N=0;N<V.int64Data.length;++N)typeof V.int64Data[N]=="number"?P.int64Data[N]=O.longs===String?String(V.int64Data[N]):V.int64Data[N]:P.int64Data[N]=O.longs===String?z.Long.prototype.toString.call(V.int64Data[N]):O.longs===Number?new z.LongBits(V.int64Data[N].low>>>0,V.int64Data[N].high>>>0).toNumber():V.int64Data[N]}if(V.name!=null&&V.hasOwnProperty("name")&&(P.name=V.name),V.rawData!=null&&V.hasOwnProperty("rawData")&&(P.rawData=O.bytes===String?z.base64.encode(V.rawData,0,V.rawData.length):O.bytes===Array?Array.prototype.slice.call(V.rawData):V.rawData),V.doubleData&&V.doubleData.length){P.doubleData=[];for(var N=0;N<V.doubleData.length;++N)P.doubleData[N]=O.json&&!isFinite(V.doubleData[N])?String(V.doubleData[N]):V.doubleData[N]}if(V.uint64Data&&V.uint64Data.length){P.uint64Data=[];for(var N=0;N<V.uint64Data.length;++N)typeof V.uint64Data[N]=="number"?P.uint64Data[N]=O.longs===String?String(V.uint64Data[N]):V.uint64Data[N]:P.uint64Data[N]=O.longs===String?z.Long.prototype.toString.call(V.uint64Data[N]):O.longs===Number?new z.LongBits(V.uint64Data[N].low>>>0,V.uint64Data[N].high>>>0).toNumber(!0):V.uint64Data[N]}if(V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),V.externalData&&V.externalData.length){P.externalData=[];for(var N=0;N<V.externalData.length;++N)P.externalData[N]=q.onnx.StringStringEntryProto.toObject(V.externalData[N],O)}return V.dataLocation!=null&&V.hasOwnProperty("dataLocation")&&(P.dataLocation=O.enums===String?q.onnx.TensorProto.DataLocation[V.dataLocation]===void 0?V.dataLocation:q.onnx.TensorProto.DataLocation[V.dataLocation]:V.dataLocation),P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.TensorProto"},D.DataType=function(){var V={},O=Object.create(V);return O[V[0]="UNDEFINED"]=0,O[V[1]="FLOAT"]=1,O[V[2]="UINT8"]=2,O[V[3]="INT8"]=3,O[V[4]="UINT16"]=4,O[V[5]="INT16"]=5,O[V[6]="INT32"]=6,O[V[7]="INT64"]=7,O[V[8]="STRING"]=8,O[V[9]="BOOL"]=9,O[V[10]="FLOAT16"]=10,O[V[11]="DOUBLE"]=11,O[V[12]="UINT32"]=12,O[V[13]="UINT64"]=13,O[V[14]="COMPLEX64"]=14,O[V[15]="COMPLEX128"]=15,O[V[16]="BFLOAT16"]=16,O[V[17]="FLOAT8E4M3FN"]=17,O[V[18]="FLOAT8E4M3FNUZ"]=18,O[V[19]="FLOAT8E5M2"]=19,O[V[20]="FLOAT8E5M2FNUZ"]=20,O}(),D.Segment=function(){function V(O){if(O)for(var P=Object.keys(O),N=0;N<P.length;++N)O[P[N]]!=null&&(this[P[N]]=O[P[N]])}return V.prototype.begin=z.Long?z.Long.fromBits(0,0,!1):0,V.prototype.end=z.Long?z.Long.fromBits(0,0,!1):0,V.create=function(O){return new V(O)},V.encode=function(O,P){return P||(P=K.create()),O.begin!=null&&Object.hasOwnProperty.call(O,"begin")&&P.uint32(8).int64(O.begin),O.end!=null&&Object.hasOwnProperty.call(O,"end")&&P.uint32(16).int64(O.end),P},V.encodeDelimited=function(O,P){return this.encode(O,P).ldelim()},V.decode=function(O,P){O instanceof H||(O=H.create(O));for(var N=P===void 0?O.len:O.pos+P,I=new q.onnx.TensorProto.Segment;O.pos<N;){var R=O.uint32();switch(R>>>3){case 1:{I.begin=O.int64();break}case 2:{I.end=O.int64();break}default:O.skipType(R&7);break}}return I},V.decodeDelimited=function(O){return O instanceof H||(O=new H(O)),this.decode(O,O.uint32())},V.verify=function(O){return typeof O!="object"||O===null?"object expected":O.begin!=null&&O.hasOwnProperty("begin")&&!z.isInteger(O.begin)&&!(O.begin&&z.isInteger(O.begin.low)&&z.isInteger(O.begin.high))?"begin: integer|Long expected":O.end!=null&&O.hasOwnProperty("end")&&!z.isInteger(O.end)&&!(O.end&&z.isInteger(O.end.low)&&z.isInteger(O.end.high))?"end: integer|Long expected":null},V.fromObject=function(O){if(O instanceof q.onnx.TensorProto.Segment)return O;var P=new q.onnx.TensorProto.Segment;return O.begin!=null&&(z.Long?(P.begin=z.Long.fromValue(O.begin)).unsigned=!1:typeof O.begin=="string"?P.begin=parseInt(O.begin,10):typeof O.begin=="number"?P.begin=O.begin:typeof O.begin=="object"&&(P.begin=new z.LongBits(O.begin.low>>>0,O.begin.high>>>0).toNumber())),O.end!=null&&(z.Long?(P.end=z.Long.fromValue(O.end)).unsigned=!1:typeof O.end=="string"?P.end=parseInt(O.end,10):typeof O.end=="number"?P.end=O.end:typeof O.end=="object"&&(P.end=new z.LongBits(O.end.low>>>0,O.end.high>>>0).toNumber())),P},V.toObject=function(O,P){P||(P={});var N={};if(P.defaults){if(z.Long){var I=new z.Long(0,0,!1);N.begin=P.longs===String?I.toString():P.longs===Number?I.toNumber():I}else N.begin=P.longs===String?"0":0;if(z.Long){var I=new z.Long(0,0,!1);N.end=P.longs===String?I.toString():P.longs===Number?I.toNumber():I}else N.end=P.longs===String?"0":0}return O.begin!=null&&O.hasOwnProperty("begin")&&(typeof O.begin=="number"?N.begin=P.longs===String?String(O.begin):O.begin:N.begin=P.longs===String?z.Long.prototype.toString.call(O.begin):P.longs===Number?new z.LongBits(O.begin.low>>>0,O.begin.high>>>0).toNumber():O.begin),O.end!=null&&O.hasOwnProperty("end")&&(typeof O.end=="number"?N.end=P.longs===String?String(O.end):O.end:N.end=P.longs===String?z.Long.prototype.toString.call(O.end):P.longs===Number?new z.LongBits(O.end.low>>>0,O.end.high>>>0).toNumber():O.end),N},V.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},V.getTypeUrl=function(O){return O===void 0&&(O="type.googleapis.com"),O+"/onnx.TensorProto.Segment"},V}(),D.DataLocation=function(){var V={},O=Object.create(V);return O[V[0]="DEFAULT"]=0,O[V[1]="EXTERNAL"]=1,O}(),D}(),F.SparseTensorProto=function(){function D(V){if(this.dims=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.values=null,D.prototype.indices=null,D.prototype.dims=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.values!=null&&Object.hasOwnProperty.call(V,"values")&&q.onnx.TensorProto.encode(V.values,O.uint32(10).fork()).ldelim(),V.indices!=null&&Object.hasOwnProperty.call(V,"indices")&&q.onnx.TensorProto.encode(V.indices,O.uint32(18).fork()).ldelim(),V.dims!=null&&V.dims.length){O.uint32(26).fork();for(var P=0;P<V.dims.length;++P)O.int64(V.dims[P]);O.ldelim()}return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.SparseTensorProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.values=q.onnx.TensorProto.decode(V,V.uint32());break}case 2:{N.indices=q.onnx.TensorProto.decode(V,V.uint32());break}case 3:{if(N.dims&&N.dims.length||(N.dims=[]),(I&7)===2)for(var R=V.uint32()+V.pos;V.pos<R;)N.dims.push(V.int64());else N.dims.push(V.int64());break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.values!=null&&V.hasOwnProperty("values")){var O=q.onnx.TensorProto.verify(V.values);if(O)return"values."+O}if(V.indices!=null&&V.hasOwnProperty("indices")){var O=q.onnx.TensorProto.verify(V.indices);if(O)return"indices."+O}if(V.dims!=null&&V.hasOwnProperty("dims")){if(!Array.isArray(V.dims))return"dims: array expected";for(var P=0;P<V.dims.length;++P)if(!z.isInteger(V.dims[P])&&!(V.dims[P]&&z.isInteger(V.dims[P].low)&&z.isInteger(V.dims[P].high)))return"dims: integer|Long[] expected"}return null},D.fromObject=function(V){if(V instanceof q.onnx.SparseTensorProto)return V;var O=new q.onnx.SparseTensorProto;if(V.values!=null){if(typeof V.values!="object")throw TypeError(".onnx.SparseTensorProto.values: object expected");O.values=q.onnx.TensorProto.fromObject(V.values)}if(V.indices!=null){if(typeof V.indices!="object")throw TypeError(".onnx.SparseTensorProto.indices: object expected");O.indices=q.onnx.TensorProto.fromObject(V.indices)}if(V.dims){if(!Array.isArray(V.dims))throw TypeError(".onnx.SparseTensorProto.dims: array expected");O.dims=[];for(var P=0;P<V.dims.length;++P)z.Long?(O.dims[P]=z.Long.fromValue(V.dims[P])).unsigned=!1:typeof V.dims[P]=="string"?O.dims[P]=parseInt(V.dims[P],10):typeof V.dims[P]=="number"?O.dims[P]=V.dims[P]:typeof V.dims[P]=="object"&&(O.dims[P]=new z.LongBits(V.dims[P].low>>>0,V.dims[P].high>>>0).toNumber())}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.dims=[]),O.defaults&&(P.values=null,P.indices=null),V.values!=null&&V.hasOwnProperty("values")&&(P.values=q.onnx.TensorProto.toObject(V.values,O)),V.indices!=null&&V.hasOwnProperty("indices")&&(P.indices=q.onnx.TensorProto.toObject(V.indices,O)),V.dims&&V.dims.length){P.dims=[];for(var N=0;N<V.dims.length;++N)typeof V.dims[N]=="number"?P.dims[N]=O.longs===String?String(V.dims[N]):V.dims[N]:P.dims[N]=O.longs===String?z.Long.prototype.toString.call(V.dims[N]):O.longs===Number?new z.LongBits(V.dims[N].low>>>0,V.dims[N].high>>>0).toNumber():V.dims[N]}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.SparseTensorProto"},D}(),F.TensorShapeProto=function(){function D(V){if(this.dim=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.dim=z.emptyArray,D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.dim!=null&&V.dim.length)for(var P=0;P<V.dim.length;++P)q.onnx.TensorShapeProto.Dimension.encode(V.dim[P],O.uint32(10).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.TensorShapeProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.dim&&N.dim.length||(N.dim=[]),N.dim.push(q.onnx.TensorShapeProto.Dimension.decode(V,V.uint32()));break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.dim!=null&&V.hasOwnProperty("dim")){if(!Array.isArray(V.dim))return"dim: array expected";for(var O=0;O<V.dim.length;++O){var P=q.onnx.TensorShapeProto.Dimension.verify(V.dim[O]);if(P)return"dim."+P}}return null},D.fromObject=function(V){if(V instanceof q.onnx.TensorShapeProto)return V;var O=new q.onnx.TensorShapeProto;if(V.dim){if(!Array.isArray(V.dim))throw TypeError(".onnx.TensorShapeProto.dim: array expected");O.dim=[];for(var P=0;P<V.dim.length;++P){if(typeof V.dim[P]!="object")throw TypeError(".onnx.TensorShapeProto.dim: object expected");O.dim[P]=q.onnx.TensorShapeProto.Dimension.fromObject(V.dim[P])}}return O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.dim=[]),V.dim&&V.dim.length){P.dim=[];for(var N=0;N<V.dim.length;++N)P.dim[N]=q.onnx.TensorShapeProto.Dimension.toObject(V.dim[N],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.TensorShapeProto"},D.Dimension=function(){function V(P){if(P)for(var N=Object.keys(P),I=0;I<N.length;++I)P[N[I]]!=null&&(this[N[I]]=P[N[I]])}V.prototype.dimValue=null,V.prototype.dimParam=null,V.prototype.denotation="";var O;return Object.defineProperty(V.prototype,"value",{get:z.oneOfGetter(O=["dimValue","dimParam"]),set:z.oneOfSetter(O)}),V.create=function(P){return new V(P)},V.encode=function(P,N){return N||(N=K.create()),P.dimValue!=null&&Object.hasOwnProperty.call(P,"dimValue")&&N.uint32(8).int64(P.dimValue),P.dimParam!=null&&Object.hasOwnProperty.call(P,"dimParam")&&N.uint32(18).string(P.dimParam),P.denotation!=null&&Object.hasOwnProperty.call(P,"denotation")&&N.uint32(26).string(P.denotation),N},V.encodeDelimited=function(P,N){return this.encode(P,N).ldelim()},V.decode=function(P,N){P instanceof H||(P=H.create(P));for(var I=N===void 0?P.len:P.pos+N,R=new q.onnx.TensorShapeProto.Dimension;P.pos<I;){var w=P.uint32();switch(w>>>3){case 1:{R.dimValue=P.int64();break}case 2:{R.dimParam=P.string();break}case 3:{R.denotation=P.string();break}default:P.skipType(w&7);break}}return R},V.decodeDelimited=function(P){return P instanceof H||(P=new H(P)),this.decode(P,P.uint32())},V.verify=function(P){if(typeof P!="object"||P===null)return"object expected";var N={};if(P.dimValue!=null&&P.hasOwnProperty("dimValue")&&(N.value=1,!z.isInteger(P.dimValue)&&!(P.dimValue&&z.isInteger(P.dimValue.low)&&z.isInteger(P.dimValue.high))))return"dimValue: integer|Long expected";if(P.dimParam!=null&&P.hasOwnProperty("dimParam")){if(N.value===1)return"value: multiple values";if(N.value=1,!z.isString(P.dimParam))return"dimParam: string expected"}return P.denotation!=null&&P.hasOwnProperty("denotation")&&!z.isString(P.denotation)?"denotation: string expected":null},V.fromObject=function(P){if(P instanceof q.onnx.TensorShapeProto.Dimension)return P;var N=new q.onnx.TensorShapeProto.Dimension;return P.dimValue!=null&&(z.Long?(N.dimValue=z.Long.fromValue(P.dimValue)).unsigned=!1:typeof P.dimValue=="string"?N.dimValue=parseInt(P.dimValue,10):typeof P.dimValue=="number"?N.dimValue=P.dimValue:typeof P.dimValue=="object"&&(N.dimValue=new z.LongBits(P.dimValue.low>>>0,P.dimValue.high>>>0).toNumber())),P.dimParam!=null&&(N.dimParam=String(P.dimParam)),P.denotation!=null&&(N.denotation=String(P.denotation)),N},V.toObject=function(P,N){N||(N={});var I={};return N.defaults&&(I.denotation=""),P.dimValue!=null&&P.hasOwnProperty("dimValue")&&(typeof P.dimValue=="number"?I.dimValue=N.longs===String?String(P.dimValue):P.dimValue:I.dimValue=N.longs===String?z.Long.prototype.toString.call(P.dimValue):N.longs===Number?new z.LongBits(P.dimValue.low>>>0,P.dimValue.high>>>0).toNumber():P.dimValue,N.oneofs&&(I.value="dimValue")),P.dimParam!=null&&P.hasOwnProperty("dimParam")&&(I.dimParam=P.dimParam,N.oneofs&&(I.value="dimParam")),P.denotation!=null&&P.hasOwnProperty("denotation")&&(I.denotation=P.denotation),I},V.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},V.getTypeUrl=function(P){return P===void 0&&(P="type.googleapis.com"),P+"/onnx.TensorShapeProto.Dimension"},V}(),D}(),F.TypeProto=function(){function D(O){if(O)for(var P=Object.keys(O),N=0;N<P.length;++N)O[P[N]]!=null&&(this[P[N]]=O[P[N]])}D.prototype.tensorType=null,D.prototype.sequenceType=null,D.prototype.mapType=null,D.prototype.optionalType=null,D.prototype.sparseTensorType=null,D.prototype.denotation="";var V;return Object.defineProperty(D.prototype,"value",{get:z.oneOfGetter(V=["tensorType","sequenceType","mapType","optionalType","sparseTensorType"]),set:z.oneOfSetter(V)}),D.create=function(O){return new D(O)},D.encode=function(O,P){return P||(P=K.create()),O.tensorType!=null&&Object.hasOwnProperty.call(O,"tensorType")&&q.onnx.TypeProto.Tensor.encode(O.tensorType,P.uint32(10).fork()).ldelim(),O.sequenceType!=null&&Object.hasOwnProperty.call(O,"sequenceType")&&q.onnx.TypeProto.Sequence.encode(O.sequenceType,P.uint32(34).fork()).ldelim(),O.mapType!=null&&Object.hasOwnProperty.call(O,"mapType")&&q.onnx.TypeProto.Map.encode(O.mapType,P.uint32(42).fork()).ldelim(),O.denotation!=null&&Object.hasOwnProperty.call(O,"denotation")&&P.uint32(50).string(O.denotation),O.sparseTensorType!=null&&Object.hasOwnProperty.call(O,"sparseTensorType")&&q.onnx.TypeProto.SparseTensor.encode(O.sparseTensorType,P.uint32(66).fork()).ldelim(),O.optionalType!=null&&Object.hasOwnProperty.call(O,"optionalType")&&q.onnx.TypeProto.Optional.encode(O.optionalType,P.uint32(74).fork()).ldelim(),P},D.encodeDelimited=function(O,P){return this.encode(O,P).ldelim()},D.decode=function(O,P){O instanceof H||(O=H.create(O));for(var N=P===void 0?O.len:O.pos+P,I=new q.onnx.TypeProto;O.pos<N;){var R=O.uint32();switch(R>>>3){case 1:{I.tensorType=q.onnx.TypeProto.Tensor.decode(O,O.uint32());break}case 4:{I.sequenceType=q.onnx.TypeProto.Sequence.decode(O,O.uint32());break}case 5:{I.mapType=q.onnx.TypeProto.Map.decode(O,O.uint32());break}case 9:{I.optionalType=q.onnx.TypeProto.Optional.decode(O,O.uint32());break}case 8:{I.sparseTensorType=q.onnx.TypeProto.SparseTensor.decode(O,O.uint32());break}case 6:{I.denotation=O.string();break}default:O.skipType(R&7);break}}return I},D.decodeDelimited=function(O){return O instanceof H||(O=new H(O)),this.decode(O,O.uint32())},D.verify=function(O){if(typeof O!="object"||O===null)return"object expected";var P={};if(O.tensorType!=null&&O.hasOwnProperty("tensorType")){P.value=1;{var N=q.onnx.TypeProto.Tensor.verify(O.tensorType);if(N)return"tensorType."+N}}if(O.sequenceType!=null&&O.hasOwnProperty("sequenceType")){if(P.value===1)return"value: multiple values";P.value=1;{var N=q.onnx.TypeProto.Sequence.verify(O.sequenceType);if(N)return"sequenceType."+N}}if(O.mapType!=null&&O.hasOwnProperty("mapType")){if(P.value===1)return"value: multiple values";P.value=1;{var N=q.onnx.TypeProto.Map.verify(O.mapType);if(N)return"mapType."+N}}if(O.optionalType!=null&&O.hasOwnProperty("optionalType")){if(P.value===1)return"value: multiple values";P.value=1;{var N=q.onnx.TypeProto.Optional.verify(O.optionalType);if(N)return"optionalType."+N}}if(O.sparseTensorType!=null&&O.hasOwnProperty("sparseTensorType")){if(P.value===1)return"value: multiple values";P.value=1;{var N=q.onnx.TypeProto.SparseTensor.verify(O.sparseTensorType);if(N)return"sparseTensorType."+N}}return O.denotation!=null&&O.hasOwnProperty("denotation")&&!z.isString(O.denotation)?"denotation: string expected":null},D.fromObject=function(O){if(O instanceof q.onnx.TypeProto)return O;var P=new q.onnx.TypeProto;if(O.tensorType!=null){if(typeof O.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");P.tensorType=q.onnx.TypeProto.Tensor.fromObject(O.tensorType)}if(O.sequenceType!=null){if(typeof O.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");P.sequenceType=q.onnx.TypeProto.Sequence.fromObject(O.sequenceType)}if(O.mapType!=null){if(typeof O.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");P.mapType=q.onnx.TypeProto.Map.fromObject(O.mapType)}if(O.optionalType!=null){if(typeof O.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");P.optionalType=q.onnx.TypeProto.Optional.fromObject(O.optionalType)}if(O.sparseTensorType!=null){if(typeof O.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");P.sparseTensorType=q.onnx.TypeProto.SparseTensor.fromObject(O.sparseTensorType)}return O.denotation!=null&&(P.denotation=String(O.denotation)),P},D.toObject=function(O,P){P||(P={});var N={};return P.defaults&&(N.denotation=""),O.tensorType!=null&&O.hasOwnProperty("tensorType")&&(N.tensorType=q.onnx.TypeProto.Tensor.toObject(O.tensorType,P),P.oneofs&&(N.value="tensorType")),O.sequenceType!=null&&O.hasOwnProperty("sequenceType")&&(N.sequenceType=q.onnx.TypeProto.Sequence.toObject(O.sequenceType,P),P.oneofs&&(N.value="sequenceType")),O.mapType!=null&&O.hasOwnProperty("mapType")&&(N.mapType=q.onnx.TypeProto.Map.toObject(O.mapType,P),P.oneofs&&(N.value="mapType")),O.denotation!=null&&O.hasOwnProperty("denotation")&&(N.denotation=O.denotation),O.sparseTensorType!=null&&O.hasOwnProperty("sparseTensorType")&&(N.sparseTensorType=q.onnx.TypeProto.SparseTensor.toObject(O.sparseTensorType,P),P.oneofs&&(N.value="sparseTensorType")),O.optionalType!=null&&O.hasOwnProperty("optionalType")&&(N.optionalType=q.onnx.TypeProto.Optional.toObject(O.optionalType,P),P.oneofs&&(N.value="optionalType")),N},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(O){return O===void 0&&(O="type.googleapis.com"),O+"/onnx.TypeProto"},D.Tensor=function(){function O(P){if(P)for(var N=Object.keys(P),I=0;I<N.length;++I)P[N[I]]!=null&&(this[N[I]]=P[N[I]])}return O.prototype.elemType=0,O.prototype.shape=null,O.create=function(P){return new O(P)},O.encode=function(P,N){return N||(N=K.create()),P.elemType!=null&&Object.hasOwnProperty.call(P,"elemType")&&N.uint32(8).int32(P.elemType),P.shape!=null&&Object.hasOwnProperty.call(P,"shape")&&q.onnx.TensorShapeProto.encode(P.shape,N.uint32(18).fork()).ldelim(),N},O.encodeDelimited=function(P,N){return this.encode(P,N).ldelim()},O.decode=function(P,N){P instanceof H||(P=H.create(P));for(var I=N===void 0?P.len:P.pos+N,R=new q.onnx.TypeProto.Tensor;P.pos<I;){var w=P.uint32();switch(w>>>3){case 1:{R.elemType=P.int32();break}case 2:{R.shape=q.onnx.TensorShapeProto.decode(P,P.uint32());break}default:P.skipType(w&7);break}}return R},O.decodeDelimited=function(P){return P instanceof H||(P=new H(P)),this.decode(P,P.uint32())},O.verify=function(P){if(typeof P!="object"||P===null)return"object expected";if(P.elemType!=null&&P.hasOwnProperty("elemType")&&!z.isInteger(P.elemType))return"elemType: integer expected";if(P.shape!=null&&P.hasOwnProperty("shape")){var N=q.onnx.TensorShapeProto.verify(P.shape);if(N)return"shape."+N}return null},O.fromObject=function(P){if(P instanceof q.onnx.TypeProto.Tensor)return P;var N=new q.onnx.TypeProto.Tensor;if(P.elemType!=null&&(N.elemType=P.elemType|0),P.shape!=null){if(typeof P.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");N.shape=q.onnx.TensorShapeProto.fromObject(P.shape)}return N},O.toObject=function(P,N){N||(N={});var I={};return N.defaults&&(I.elemType=0,I.shape=null),P.elemType!=null&&P.hasOwnProperty("elemType")&&(I.elemType=P.elemType),P.shape!=null&&P.hasOwnProperty("shape")&&(I.shape=q.onnx.TensorShapeProto.toObject(P.shape,N)),I},O.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},O.getTypeUrl=function(P){return P===void 0&&(P="type.googleapis.com"),P+"/onnx.TypeProto.Tensor"},O}(),D.Sequence=function(){function O(P){if(P)for(var N=Object.keys(P),I=0;I<N.length;++I)P[N[I]]!=null&&(this[N[I]]=P[N[I]])}return O.prototype.elemType=null,O.create=function(P){return new O(P)},O.encode=function(P,N){return N||(N=K.create()),P.elemType!=null&&Object.hasOwnProperty.call(P,"elemType")&&q.onnx.TypeProto.encode(P.elemType,N.uint32(10).fork()).ldelim(),N},O.encodeDelimited=function(P,N){return this.encode(P,N).ldelim()},O.decode=function(P,N){P instanceof H||(P=H.create(P));for(var I=N===void 0?P.len:P.pos+N,R=new q.onnx.TypeProto.Sequence;P.pos<I;){var w=P.uint32();switch(w>>>3){case 1:{R.elemType=q.onnx.TypeProto.decode(P,P.uint32());break}default:P.skipType(w&7);break}}return R},O.decodeDelimited=function(P){return P instanceof H||(P=new H(P)),this.decode(P,P.uint32())},O.verify=function(P){if(typeof P!="object"||P===null)return"object expected";if(P.elemType!=null&&P.hasOwnProperty("elemType")){var N=q.onnx.TypeProto.verify(P.elemType);if(N)return"elemType."+N}return null},O.fromObject=function(P){if(P instanceof q.onnx.TypeProto.Sequence)return P;var N=new q.onnx.TypeProto.Sequence;if(P.elemType!=null){if(typeof P.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");N.elemType=q.onnx.TypeProto.fromObject(P.elemType)}return N},O.toObject=function(P,N){N||(N={});var I={};return N.defaults&&(I.elemType=null),P.elemType!=null&&P.hasOwnProperty("elemType")&&(I.elemType=q.onnx.TypeProto.toObject(P.elemType,N)),I},O.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},O.getTypeUrl=function(P){return P===void 0&&(P="type.googleapis.com"),P+"/onnx.TypeProto.Sequence"},O}(),D.Map=function(){function O(P){if(P)for(var N=Object.keys(P),I=0;I<N.length;++I)P[N[I]]!=null&&(this[N[I]]=P[N[I]])}return O.prototype.keyType=0,O.prototype.valueType=null,O.create=function(P){return new O(P)},O.encode=function(P,N){return N||(N=K.create()),P.keyType!=null&&Object.hasOwnProperty.call(P,"keyType")&&N.uint32(8).int32(P.keyType),P.valueType!=null&&Object.hasOwnProperty.call(P,"valueType")&&q.onnx.TypeProto.encode(P.valueType,N.uint32(18).fork()).ldelim(),N},O.encodeDelimited=function(P,N){return this.encode(P,N).ldelim()},O.decode=function(P,N){P instanceof H||(P=H.create(P));for(var I=N===void 0?P.len:P.pos+N,R=new q.onnx.TypeProto.Map;P.pos<I;){var w=P.uint32();switch(w>>>3){case 1:{R.keyType=P.int32();break}case 2:{R.valueType=q.onnx.TypeProto.decode(P,P.uint32());break}default:P.skipType(w&7);break}}return R},O.decodeDelimited=function(P){return P instanceof H||(P=new H(P)),this.decode(P,P.uint32())},O.verify=function(P){if(typeof P!="object"||P===null)return"object expected";if(P.keyType!=null&&P.hasOwnProperty("keyType")&&!z.isInteger(P.keyType))return"keyType: integer expected";if(P.valueType!=null&&P.hasOwnProperty("valueType")){var N=q.onnx.TypeProto.verify(P.valueType);if(N)return"valueType."+N}return null},O.fromObject=function(P){if(P instanceof q.onnx.TypeProto.Map)return P;var N=new q.onnx.TypeProto.Map;if(P.keyType!=null&&(N.keyType=P.keyType|0),P.valueType!=null){if(typeof P.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");N.valueType=q.onnx.TypeProto.fromObject(P.valueType)}return N},O.toObject=function(P,N){N||(N={});var I={};return N.defaults&&(I.keyType=0,I.valueType=null),P.keyType!=null&&P.hasOwnProperty("keyType")&&(I.keyType=P.keyType),P.valueType!=null&&P.hasOwnProperty("valueType")&&(I.valueType=q.onnx.TypeProto.toObject(P.valueType,N)),I},O.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},O.getTypeUrl=function(P){return P===void 0&&(P="type.googleapis.com"),P+"/onnx.TypeProto.Map"},O}(),D.Optional=function(){function O(P){if(P)for(var N=Object.keys(P),I=0;I<N.length;++I)P[N[I]]!=null&&(this[N[I]]=P[N[I]])}return O.prototype.elemType=null,O.create=function(P){return new O(P)},O.encode=function(P,N){return N||(N=K.create()),P.elemType!=null&&Object.hasOwnProperty.call(P,"elemType")&&q.onnx.TypeProto.encode(P.elemType,N.uint32(10).fork()).ldelim(),N},O.encodeDelimited=function(P,N){return this.encode(P,N).ldelim()},O.decode=function(P,N){P instanceof H||(P=H.create(P));for(var I=N===void 0?P.len:P.pos+N,R=new q.onnx.TypeProto.Optional;P.pos<I;){var w=P.uint32();switch(w>>>3){case 1:{R.elemType=q.onnx.TypeProto.decode(P,P.uint32());break}default:P.skipType(w&7);break}}return R},O.decodeDelimited=function(P){return P instanceof H||(P=new H(P)),this.decode(P,P.uint32())},O.verify=function(P){if(typeof P!="object"||P===null)return"object expected";if(P.elemType!=null&&P.hasOwnProperty("elemType")){var N=q.onnx.TypeProto.verify(P.elemType);if(N)return"elemType."+N}return null},O.fromObject=function(P){if(P instanceof q.onnx.TypeProto.Optional)return P;var N=new q.onnx.TypeProto.Optional;if(P.elemType!=null){if(typeof P.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");N.elemType=q.onnx.TypeProto.fromObject(P.elemType)}return N},O.toObject=function(P,N){N||(N={});var I={};return N.defaults&&(I.elemType=null),P.elemType!=null&&P.hasOwnProperty("elemType")&&(I.elemType=q.onnx.TypeProto.toObject(P.elemType,N)),I},O.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},O.getTypeUrl=function(P){return P===void 0&&(P="type.googleapis.com"),P+"/onnx.TypeProto.Optional"},O}(),D.SparseTensor=function(){function O(P){if(P)for(var N=Object.keys(P),I=0;I<N.length;++I)P[N[I]]!=null&&(this[N[I]]=P[N[I]])}return O.prototype.elemType=0,O.prototype.shape=null,O.create=function(P){return new O(P)},O.encode=function(P,N){return N||(N=K.create()),P.elemType!=null&&Object.hasOwnProperty.call(P,"elemType")&&N.uint32(8).int32(P.elemType),P.shape!=null&&Object.hasOwnProperty.call(P,"shape")&&q.onnx.TensorShapeProto.encode(P.shape,N.uint32(18).fork()).ldelim(),N},O.encodeDelimited=function(P,N){return this.encode(P,N).ldelim()},O.decode=function(P,N){P instanceof H||(P=H.create(P));for(var I=N===void 0?P.len:P.pos+N,R=new q.onnx.TypeProto.SparseTensor;P.pos<I;){var w=P.uint32();switch(w>>>3){case 1:{R.elemType=P.int32();break}case 2:{R.shape=q.onnx.TensorShapeProto.decode(P,P.uint32());break}default:P.skipType(w&7);break}}return R},O.decodeDelimited=function(P){return P instanceof H||(P=new H(P)),this.decode(P,P.uint32())},O.verify=function(P){if(typeof P!="object"||P===null)return"object expected";if(P.elemType!=null&&P.hasOwnProperty("elemType")&&!z.isInteger(P.elemType))return"elemType: integer expected";if(P.shape!=null&&P.hasOwnProperty("shape")){var N=q.onnx.TensorShapeProto.verify(P.shape);if(N)return"shape."+N}return null},O.fromObject=function(P){if(P instanceof q.onnx.TypeProto.SparseTensor)return P;var N=new q.onnx.TypeProto.SparseTensor;if(P.elemType!=null&&(N.elemType=P.elemType|0),P.shape!=null){if(typeof P.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");N.shape=q.onnx.TensorShapeProto.fromObject(P.shape)}return N},O.toObject=function(P,N){N||(N={});var I={};return N.defaults&&(I.elemType=0,I.shape=null),P.elemType!=null&&P.hasOwnProperty("elemType")&&(I.elemType=P.elemType),P.shape!=null&&P.hasOwnProperty("shape")&&(I.shape=q.onnx.TensorShapeProto.toObject(P.shape,N)),I},O.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},O.getTypeUrl=function(P){return P===void 0&&(P="type.googleapis.com"),P+"/onnx.TypeProto.SparseTensor"},O}(),D}(),F.OperatorSetIdProto=function(){function D(V){if(V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.domain="",D.prototype.version=z.Long?z.Long.fromBits(0,0,!1):0,D.create=function(V){return new D(V)},D.encode=function(V,O){return O||(O=K.create()),V.domain!=null&&Object.hasOwnProperty.call(V,"domain")&&O.uint32(10).string(V.domain),V.version!=null&&Object.hasOwnProperty.call(V,"version")&&O.uint32(16).int64(V.version),O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.OperatorSetIdProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.domain=V.string();break}case 2:{N.version=V.int64();break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){return typeof V!="object"||V===null?"object expected":V.domain!=null&&V.hasOwnProperty("domain")&&!z.isString(V.domain)?"domain: string expected":V.version!=null&&V.hasOwnProperty("version")&&!z.isInteger(V.version)&&!(V.version&&z.isInteger(V.version.low)&&z.isInteger(V.version.high))?"version: integer|Long expected":null},D.fromObject=function(V){if(V instanceof q.onnx.OperatorSetIdProto)return V;var O=new q.onnx.OperatorSetIdProto;return V.domain!=null&&(O.domain=String(V.domain)),V.version!=null&&(z.Long?(O.version=z.Long.fromValue(V.version)).unsigned=!1:typeof V.version=="string"?O.version=parseInt(V.version,10):typeof V.version=="number"?O.version=V.version:typeof V.version=="object"&&(O.version=new z.LongBits(V.version.low>>>0,V.version.high>>>0).toNumber())),O},D.toObject=function(V,O){O||(O={});var P={};if(O.defaults)if(P.domain="",z.Long){var N=new z.Long(0,0,!1);P.version=O.longs===String?N.toString():O.longs===Number?N.toNumber():N}else P.version=O.longs===String?"0":0;return V.domain!=null&&V.hasOwnProperty("domain")&&(P.domain=V.domain),V.version!=null&&V.hasOwnProperty("version")&&(typeof V.version=="number"?P.version=O.longs===String?String(V.version):V.version:P.version=O.longs===String?z.Long.prototype.toString.call(V.version):O.longs===Number?new z.LongBits(V.version.low>>>0,V.version.high>>>0).toNumber():V.version),P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.OperatorSetIdProto"},D}(),F.OperatorStatus=function(){var D={},V=Object.create(D);return V[D[0]="EXPERIMENTAL"]=0,V[D[1]="STABLE"]=1,V}(),F.FunctionProto=function(){function D(V){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],V)for(var O=Object.keys(V),P=0;P<O.length;++P)V[O[P]]!=null&&(this[O[P]]=V[O[P]])}return D.prototype.name="",D.prototype.input=z.emptyArray,D.prototype.output=z.emptyArray,D.prototype.attribute=z.emptyArray,D.prototype.attributeProto=z.emptyArray,D.prototype.node=z.emptyArray,D.prototype.docString="",D.prototype.opsetImport=z.emptyArray,D.prototype.domain="",D.create=function(V){return new D(V)},D.encode=function(V,O){if(O||(O=K.create()),V.name!=null&&Object.hasOwnProperty.call(V,"name")&&O.uint32(10).string(V.name),V.input!=null&&V.input.length)for(var P=0;P<V.input.length;++P)O.uint32(34).string(V.input[P]);if(V.output!=null&&V.output.length)for(var P=0;P<V.output.length;++P)O.uint32(42).string(V.output[P]);if(V.attribute!=null&&V.attribute.length)for(var P=0;P<V.attribute.length;++P)O.uint32(50).string(V.attribute[P]);if(V.node!=null&&V.node.length)for(var P=0;P<V.node.length;++P)q.onnx.NodeProto.encode(V.node[P],O.uint32(58).fork()).ldelim();if(V.docString!=null&&Object.hasOwnProperty.call(V,"docString")&&O.uint32(66).string(V.docString),V.opsetImport!=null&&V.opsetImport.length)for(var P=0;P<V.opsetImport.length;++P)q.onnx.OperatorSetIdProto.encode(V.opsetImport[P],O.uint32(74).fork()).ldelim();if(V.domain!=null&&Object.hasOwnProperty.call(V,"domain")&&O.uint32(82).string(V.domain),V.attributeProto!=null&&V.attributeProto.length)for(var P=0;P<V.attributeProto.length;++P)q.onnx.AttributeProto.encode(V.attributeProto[P],O.uint32(90).fork()).ldelim();return O},D.encodeDelimited=function(V,O){return this.encode(V,O).ldelim()},D.decode=function(V,O){V instanceof H||(V=H.create(V));for(var P=O===void 0?V.len:V.pos+O,N=new q.onnx.FunctionProto;V.pos<P;){var I=V.uint32();switch(I>>>3){case 1:{N.name=V.string();break}case 4:{N.input&&N.input.length||(N.input=[]),N.input.push(V.string());break}case 5:{N.output&&N.output.length||(N.output=[]),N.output.push(V.string());break}case 6:{N.attribute&&N.attribute.length||(N.attribute=[]),N.attribute.push(V.string());break}case 11:{N.attributeProto&&N.attributeProto.length||(N.attributeProto=[]),N.attributeProto.push(q.onnx.AttributeProto.decode(V,V.uint32()));break}case 7:{N.node&&N.node.length||(N.node=[]),N.node.push(q.onnx.NodeProto.decode(V,V.uint32()));break}case 8:{N.docString=V.string();break}case 9:{N.opsetImport&&N.opsetImport.length||(N.opsetImport=[]),N.opsetImport.push(q.onnx.OperatorSetIdProto.decode(V,V.uint32()));break}case 10:{N.domain=V.string();break}default:V.skipType(I&7);break}}return N},D.decodeDelimited=function(V){return V instanceof H||(V=new H(V)),this.decode(V,V.uint32())},D.verify=function(V){if(typeof V!="object"||V===null)return"object expected";if(V.name!=null&&V.hasOwnProperty("name")&&!z.isString(V.name))return"name: string expected";if(V.input!=null&&V.hasOwnProperty("input")){if(!Array.isArray(V.input))return"input: array expected";for(var O=0;O<V.input.length;++O)if(!z.isString(V.input[O]))return"input: string[] expected"}if(V.output!=null&&V.hasOwnProperty("output")){if(!Array.isArray(V.output))return"output: array expected";for(var O=0;O<V.output.length;++O)if(!z.isString(V.output[O]))return"output: string[] expected"}if(V.attribute!=null&&V.hasOwnProperty("attribute")){if(!Array.isArray(V.attribute))return"attribute: array expected";for(var O=0;O<V.attribute.length;++O)if(!z.isString(V.attribute[O]))return"attribute: string[] expected"}if(V.attributeProto!=null&&V.hasOwnProperty("attributeProto")){if(!Array.isArray(V.attributeProto))return"attributeProto: array expected";for(var O=0;O<V.attributeProto.length;++O){var P=q.onnx.AttributeProto.verify(V.attributeProto[O]);if(P)return"attributeProto."+P}}if(V.node!=null&&V.hasOwnProperty("node")){if(!Array.isArray(V.node))return"node: array expected";for(var O=0;O<V.node.length;++O){var P=q.onnx.NodeProto.verify(V.node[O]);if(P)return"node."+P}}if(V.docString!=null&&V.hasOwnProperty("docString")&&!z.isString(V.docString))return"docString: string expected";if(V.opsetImport!=null&&V.hasOwnProperty("opsetImport")){if(!Array.isArray(V.opsetImport))return"opsetImport: array expected";for(var O=0;O<V.opsetImport.length;++O){var P=q.onnx.OperatorSetIdProto.verify(V.opsetImport[O]);if(P)return"opsetImport."+P}}return V.domain!=null&&V.hasOwnProperty("domain")&&!z.isString(V.domain)?"domain: string expected":null},D.fromObject=function(V){if(V instanceof q.onnx.FunctionProto)return V;var O=new q.onnx.FunctionProto;if(V.name!=null&&(O.name=String(V.name)),V.input){if(!Array.isArray(V.input))throw TypeError(".onnx.FunctionProto.input: array expected");O.input=[];for(var P=0;P<V.input.length;++P)O.input[P]=String(V.input[P])}if(V.output){if(!Array.isArray(V.output))throw TypeError(".onnx.FunctionProto.output: array expected");O.output=[];for(var P=0;P<V.output.length;++P)O.output[P]=String(V.output[P])}if(V.attribute){if(!Array.isArray(V.attribute))throw TypeError(".onnx.FunctionProto.attribute: array expected");O.attribute=[];for(var P=0;P<V.attribute.length;++P)O.attribute[P]=String(V.attribute[P])}if(V.attributeProto){if(!Array.isArray(V.attributeProto))throw TypeError(".onnx.FunctionProto.attributeProto: array expected");O.attributeProto=[];for(var P=0;P<V.attributeProto.length;++P){if(typeof V.attributeProto[P]!="object")throw TypeError(".onnx.FunctionProto.attributeProto: object expected");O.attributeProto[P]=q.onnx.AttributeProto.fromObject(V.attributeProto[P])}}if(V.node){if(!Array.isArray(V.node))throw TypeError(".onnx.FunctionProto.node: array expected");O.node=[];for(var P=0;P<V.node.length;++P){if(typeof V.node[P]!="object")throw TypeError(".onnx.FunctionProto.node: object expected");O.node[P]=q.onnx.NodeProto.fromObject(V.node[P])}}if(V.docString!=null&&(O.docString=String(V.docString)),V.opsetImport){if(!Array.isArray(V.opsetImport))throw TypeError(".onnx.FunctionProto.opsetImport: array expected");O.opsetImport=[];for(var P=0;P<V.opsetImport.length;++P){if(typeof V.opsetImport[P]!="object")throw TypeError(".onnx.FunctionProto.opsetImport: object expected");O.opsetImport[P]=q.onnx.OperatorSetIdProto.fromObject(V.opsetImport[P])}}return V.domain!=null&&(O.domain=String(V.domain)),O},D.toObject=function(V,O){O||(O={});var P={};if((O.arrays||O.defaults)&&(P.input=[],P.output=[],P.attribute=[],P.node=[],P.opsetImport=[],P.attributeProto=[]),O.defaults&&(P.name="",P.docString="",P.domain=""),V.name!=null&&V.hasOwnProperty("name")&&(P.name=V.name),V.input&&V.input.length){P.input=[];for(var N=0;N<V.input.length;++N)P.input[N]=V.input[N]}if(V.output&&V.output.length){P.output=[];for(var N=0;N<V.output.length;++N)P.output[N]=V.output[N]}if(V.attribute&&V.attribute.length){P.attribute=[];for(var N=0;N<V.attribute.length;++N)P.attribute[N]=V.attribute[N]}if(V.node&&V.node.length){P.node=[];for(var N=0;N<V.node.length;++N)P.node[N]=q.onnx.NodeProto.toObject(V.node[N],O)}if(V.docString!=null&&V.hasOwnProperty("docString")&&(P.docString=V.docString),V.opsetImport&&V.opsetImport.length){P.opsetImport=[];for(var N=0;N<V.opsetImport.length;++N)P.opsetImport[N]=q.onnx.OperatorSetIdProto.toObject(V.opsetImport[N],O)}if(V.domain!=null&&V.hasOwnProperty("domain")&&(P.domain=V.domain),V.attributeProto&&V.attributeProto.length){P.attributeProto=[];for(var N=0;N<V.attributeProto.length;++N)P.attributeProto[N]=q.onnx.AttributeProto.toObject(V.attributeProto[N],O)}return P},D.prototype.toJSON=function(){return this.constructor.toObject(this,G.util.toJSONOptions)},D.getTypeUrl=function(V){return V===void 0&&(V="type.googleapis.com"),V+"/onnx.FunctionProto"},D}(),F}(),J.exports=q});function br(Q,J){if(!Q)throw Error(typeof J=="string"?J:J())}function Wr(Q){return new TextDecoder().decode(Q)}var Ee,Jn,Qs,Qe,Bo,je,it,U,Ur,Qn,Yn,er,xe=$(()=>{xa(),Ee=ae(gr()),tr(),Jn=class{static arraysEqual(Q,J){if(Q.length!==J.length)return!1;for(let G=0;G<Q.length;G++)if(Q[G]!==J[G])return!1;return!0}},Qs=class{static preprocessInputShapes(Q,J){let G=Q.length===1?[1,Q[0]]:Q,H=J.length===1?[J[0],1]:J;return[G,H]}static postprocessOutputShape(Q,J,G){J===1&&Q.splice(Q.length-2,1),G===1&&Q.pop()}static calcMatMulShape(Q,J){return Q[1]!==J[0]?void 0:[Q[0],J[1]]}},Qe=class Q{static calcShape(J,G,H=!1){let K=J.length,z=G.length;if(K===0)return G;if(z===0)return J;let q=Math.max(J.length,G.length),F=Array(q);if(H){if(K<2||z<2)return;let D=Qs.calcMatMulShape([J[K-2],J[K-1]],[G[z-2],G[z-1]]);if(D===void 0)return;[F[q-2],F[q-1]]=D}for(let D=H?3:1;D<=q;D++){let V=K-D<0?1:J[K-D],O=z-D<0?1:G[z-D];if(V!==O&&V>1&&O>1)return;F[q-D]=Math.max(V,O)}return F}static index(J,G){let H=Array(G.length);return Q.fillIndex(J,G,H),H}static fillIndex(J,G,H){let K=J.length-G.length;for(let z=0;z<G.length;z++)H[z]=J[K+z]%G[z]}static calc(J,G,H,K,z){let q=Q.calcShape(J.dims,G.dims);if(q){if(K&&!U.areEqual(q,J.dims))return;let F=U.size(q),D=K?J:new Me(q,z||J.type);if(q.length===0)D.set([],H(J.get([]),G.get([])));else{let V=Array(q.length),O=Array(J.dims.length),P=Array(G.dims.length),N=0,I=0,R=!1,w=!1;J.dims.length===0&&(N=J.get([]),R=!0),G.dims.length===0&&(I=G.get([]),w=!0);let E;for(let T=0;T<F;T++){E=T;for(let y=q.length-1;y>=0;y--)V[y]=E%q[y],E=Math.floor(E/q[y]);R||(Q.fillIndex(V,J.dims,O),N=J.get(O)),w||(Q.fillIndex(V,G.dims,P),I=G.get(P)),D.set(V,H(N,I))}}return D}}static isValidBroadcast(J,G){let H=J.length,K=G.length;if(H>K)return!1;for(let z=1;z<=H;z++)if(J[H-z]!==1&&J[H-z]!==G[K-z])return!1;return!0}static getBroadcastDims(J,G){let H=J.length,K=[];for(let z=0;z<H;z++){let q=H-1-z,F=J[q]||1;(G[G.length-1-z]||1)>1&&F===1&&K.unshift(q)}return K}},Bo=class{static getShapeOfGemmResult(Q,J,G,H,K){if(Q.length!==2||G.length!==2)throw Error("shape need to be of size 2");let z,q,F;J?(z=Q[1],q=Q[0]):(z=Q[0],q=Q[1]);let D=-1;if(H?(F=G[0],D=1):(F=G[1],D=0),G[D]!==q)throw Error("dimension mismatch");if(z<=0||F<=0||q<=0)throw Error("invalid shape specified");if(K&&!Qe.isValidBroadcast(K,[z,F]))throw Error("gemm: invalid bias shape for broadcast");return[z,F,q]}},je=class Q{static tensorDataTypeFromProto(J){switch(J){case Ee.onnx.TensorProto.DataType.INT8:return"int8";case Ee.onnx.TensorProto.DataType.UINT8:return"uint8";case Ee.onnx.TensorProto.DataType.BOOL:return"bool";case Ee.onnx.TensorProto.DataType.INT16:return"int16";case Ee.onnx.TensorProto.DataType.UINT16:return"uint16";case Ee.onnx.TensorProto.DataType.INT32:return"int32";case Ee.onnx.TensorProto.DataType.UINT32:return"uint32";case Ee.onnx.TensorProto.DataType.FLOAT:return"float32";case Ee.onnx.TensorProto.DataType.DOUBLE:return"float64";case Ee.onnx.TensorProto.DataType.STRING:return"string";case Ee.onnx.TensorProto.DataType.INT64:return"int32";case Ee.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw Error(`unsupported data type: ${Ee.onnx.TensorProto.DataType[J]}`)}}static tensorDataTypeStringToEnum(J){switch(J){case"int8":return Ee.onnx.TensorProto.DataType.INT8;case"uint8":return Ee.onnx.TensorProto.DataType.UINT8;case"bool":return Ee.onnx.TensorProto.DataType.BOOL;case"int16":return Ee.onnx.TensorProto.DataType.INT16;case"uint16":return Ee.onnx.TensorProto.DataType.UINT16;case"int32":return Ee.onnx.TensorProto.DataType.INT32;case"uint32":return Ee.onnx.TensorProto.DataType.UINT32;case"float32":return Ee.onnx.TensorProto.DataType.FLOAT;case"float64":return Ee.onnx.TensorProto.DataType.DOUBLE;case"string":return Ee.onnx.TensorProto.DataType.STRING;case"int64":return Ee.onnx.TensorProto.DataType.INT64;case"uint64":return Ee.onnx.TensorProto.DataType.UINT64;default:throw Error(`unsupported data type: ${J}`)}}static tensorDimsFromProto(J){return J.map((G)=>Dn.isLong(G)?G.toNumber():G)}static tensorValueTypeFromProto(J){return{tensorType:Q.tensorDataTypeFromProto(J.elemType),shape:{dims:Q.tensorDimsFromProto(J.shape.dim.map((G)=>G.dimValue))}}}static tensorDimsFromORTFormat(J){let G=[];for(let H=0;H<J.dimsLength();H++)G.push(it.longToNumber(J.dims(H)));return G}static tensorAttributesFromORTFormat(J){let G=[];for(let H=0;H<J.attributesLength();H++)G.push(J.attributes(H));return G}},it=class{static longToNumber(Q){return Dn.isLong(Q)?Q.toNumber():typeof Q=="bigint"?Number(Q):Q}static isLong(Q){return Dn.isLong(Q)||typeof Q=="bigint"}},U=class Q{static size(J){return Q.getSizeFromDimensionRange(J,0,J.length)}static sizeFromDimension(J,G){if(G<0||G>J.length)throw Error(`invalid dimension of ${G} for sizeFromDimension as Tensor has ${J.length} dimensions.`);return Q.getSizeFromDimensionRange(J,G,J.length)}static sizeToDimension(J,G){if(G<0||G>J.length)throw Error(`invalid dimension of ${G} for sizeToDimension as Tensor has ${J.length} dimensions.`);return Q.getSizeFromDimensionRange(J,0,G)}static getSizeFromDimensionRange(J,G,H){let K=1;for(let z=G;z<H;z++){if(J[z]<=0)throw Error("cannot get valid size from specified dimension range. Most likely the range contains 0 or negative values in them.");K*=J[z]}return K}static computeStrides(J){let G=J.length;if(G===0)return[];if(G===1)return[1];let H=Array(G);H[G-1]=1,H[G-2]=J[G-1];for(let K=G-3;K>=0;--K)H[K]=H[K+1]*J[K+1];return H}static transpose(J){return J.slice().reverse()}static indicesToOffset(J,G,H){H===void 0&&(H=J.length);let K=0;for(let z=0;z<H;++z)K+=G[z]*J[z];return K}static offsetToIndices(J,G){let H=G.length;if(H===0)return[];if(H===1)return[J*G[0]];let K=Array(G.length);for(let z=0;z<K.length-1;++z)K[z]=Math.floor(J/G[z]),J-=K[z]*G[z];return K[K.length-1]=J,K}static normalizeAxis(J,G){if(J<-G&&J>=G)throw Error("unsupported axis for this operation.");return J<0?J+G:J}static normalizeAxes(J,G){return J.map((H)=>this.normalizeAxis(H,G))}static incrementIndex(J,G,H){if(G.length===0||J.length===0)throw Error("Index incrementing unsupported for scalar Tensor");if(H===void 0)H=G.length;else if(H<=0||H>G.length)throw Error("Incorrect axis to increment on");for(let K=H-1;K>=0&&(J[K]++,!(J[K]<G[K]));--K)J[K]=0}static calculateReshapedDims(J,G){if(G.length===0){if(J.length===0||Q.size(J)===1)return[];throw Error("cannot reshape to a scalar Tensor")}let H=G.length,K=Array(H),z=-1,q=1;for(let D=0;D<H;D++){if(G[D]<-1)throw Error("a dimension in shape hints cannot be less than -1");if(G[D]===-1){if(z!==-1)throw Error("at most one dimension in shape hints can be -1");z=D}else{if(G[D]===0){if(D>=J.length)throw Error("the dimension with value zero exceeds the dimension size of the input tensor");K[D]=J[D]}else K[D]=G[D];q*=K[D]}}let F=Q.size(J);if(z!==-1){if(F%q!==0)throw Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${J}] Output shape: [${G}]`);K[z]=F/q}else if(q!==F)throw Error("reshapedDims and originalDims don't have matching sizes");return K}static sortBasedOnPerm(J,G){return G?G.map((H)=>J[H]):J.slice().reverse()}static padShape(J,G){let H=J.length;return J.map((K,z)=>K+G[z]+G[z+H])}static areEqual(J,G){return J.length!==G.length?!1:J.every((H,K)=>H===G[K])}static validateDimsAndCalcSize(J){if(J.length>6)throw TypeError("Only rank 0 to 6 is supported for tensor shape.");let G=1;for(let H of J){if(!Number.isInteger(H))throw TypeError(`Invalid shape: ${H} is not an integer`);if(H<0||H>2147483647)throw TypeError(`Invalid shape: length ${H} is not allowed`);G*=H}return G}static flattenShape(J,G){G<0&&(G+=J.length);let H=J.reduce((z,q)=>z*q,1),K=J.slice(G).reduce((z,q)=>z*q,1);return[H/K,K]}static squeezeShape(J,G){let H=[];G=Q.normalizeAxes(G,J.length);for(let K=0;K<J.length;K++){let z=G.indexOf(K)>=0;if(z&&J[K]!==1)throw Error("squeeze an axis of size different than 1");(G.length===0&&J[K]>1||G.length>0&&!z)&&H.push(J[K])}return H}static unsqueezeShape(J,G){let H=Array(J.length+G.length);H.fill(0);for(let z=0;z<G.length;z++){let q=Q.normalizeAxis(G[z],H.length);if(q>=H.length)throw Error("'axes' has an out of range axis");if(H[q]!==0)throw Error("'axes' has a duplicate axis");H[q]=1}let K=0;for(let z=0;z<H.length;z++)H[z]===0&&(H[z]=J[K++]);if(K!==J.length)throw Error("the unsqueezed dimension could not be established");return H}},Ur=class Q{static splitShape(J,G,H,K){if(H.length===0){if(!K)throw Error("need to know number of outputs when the 'split' attribute is not specified");Q.determineSplit(J[G],K,H)}let z=[],q=[0];for(let F=0;F<H.length;++F){F!==0&&q.push(q[F-1]+H[F-1]);let D=J.slice();D[G]=H[F],z.push(D)}return[z,q]}static determineSplit(J,G,H){if(J%G!==0)throw Error("cannot split tensor to equal sized parts");for(let K=0;K<G;++K)H.push(J/G)}},Qn=class Q{static adjustPoolAttributes(J,G,H,K,z,q){if(!J&&H.length!==G.length-2)throw Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(J)for(let F=0;F<G.length-2;F++)F>=H.length?H.push(G[F+2]):H[F]=G[F+2];for(let F=0;F<H.length;F++)if(F<K.length){if(K[F]<0)throw Error("strides should be greater than or equal to 1")}else K.push(1);for(let F=0;F<H.length;F++)if(F<z.length){if(z[F]<0)throw Error("dilations should be greater than or equal to 1")}else z.push(1);for(let F=0;F<H.length*2;F++)if(F<q.length){if(q[F]<0)throw Error("pad should be greater than or equal to 1")}else q.push(0);for(let F=0;F<H.length;F++){if(H[F]<=0)throw Error("kernel shapes need to be greater than 0");if(q[F]>=H[F]||q[F+H.length]>=H[F])throw Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(J,G,H,K,z,q){if(q){if(z.length!==2*(J.length-2))throw Error("length of pads should be twice the length of data dimensions");if(G.length!==J.length-2)throw Error("length of strides should be the length of data dimensions");if(K.length!==J.length-2)throw Error("length of kernel shapes should be the length of data dimensions");for(let F=0;F<J.length-2;F++)Q.adjustPadAndReturnShape(J[F+2],G[F],H[F],K[F],z,F,F+J.length-2,q)}}static computePoolOutputShape(J,G,H,K,z,q,F){if(G.length<=0)throw Error("input shape must be of size greater than 0");let D=[G[0],G[1]];return Q.computeShapeHelper(J,G,D,H,K,z,q,F),D}static computeConvOutputShape(J,G,H,K,z,q,F){if(J.length<=0||G.length<=0)throw Error("invalid input tensor dims or invalid filter tensor dims");let D=[J[0],G[0]];return Q.computeShapeHelper(!1,J,D,H,K,z,q,F),D}static computeShapeHelper(J,G,H,K,z,q,F,D){if(J)for(let V=0;V<G.length-2;V++)H.push(1);else for(let V=0;V<G.length-2;V++)H.push(Q.adjustPadAndReturnShape(G[V+2],K[V],z[V],q[V],F,V,V+G.length-2,D))}static adjustPadAndReturnShape(J,G,H,K,z,q,F,D){let V=H*(K-1)+1;if(D&&D!=="NOTSET")switch(D){case"VALID":return z[q]=0,z[F]=0,Math.floor((J-V)/G+1);case"SAME_LOWER":case"SAME_UPPER":if(H!==1)throw Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let O=((J+G-1)/G-1)*G+K-J;return z[q]=Math.floor(D==="SAME_LOWER"?(O+1)/2:O/2),z[F]=O-z[q],Math.floor((J+O-K)/G+1)}default:throw Error("Unsupported AutoPad type")}else return Math.floor((J+z[q]+z[F]-V)/G+1)}},Yn=-340282346638528860000000000000000000000,er=340282346638528860000000000000000000000});function g0(Q){switch(Q){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw Error(`cannot calculate sizeof() on type ${Q}`)}}function Gd(Q){switch(Q){case le.onnx.TensorProto.DataType.UINT8:case le.onnx.TensorProto.DataType.INT8:case le.onnx.TensorProto.DataType.BOOL:return 1;case le.onnx.TensorProto.DataType.UINT16:case le.onnx.TensorProto.DataType.INT16:return 2;case le.onnx.TensorProto.DataType.FLOAT:case le.onnx.TensorProto.DataType.INT32:case le.onnx.TensorProto.DataType.UINT32:return 4;case le.onnx.TensorProto.DataType.INT64:case le.onnx.TensorProto.DataType.DOUBLE:case le.onnx.TensorProto.DataType.UINT64:return 8;default:throw Error(`cannot calculate sizeof() on type ${le.onnx.TensorProto.DataType[Q]}`)}}function b0(Q,J){return new(Hd(J))(Q)}function Hd(Q){switch(Q){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw Error("unspecified error")}}function Ys(Q,J){if(J===le.onnx.TensorProto.DataType.INT64||J===Mr.TensorDataType.INT64){if(Q.greaterThanOrEqual(2147483648)||Q.lessThan(-2147483648))throw TypeError("int64 is not supported")}else if(J===le.onnx.TensorProto.DataType.UINT32||J===Mr.TensorDataType.UINT32||J===le.onnx.TensorProto.DataType.UINT64||J===Mr.TensorDataType.UINT64){if(Q.greaterThanOrEqual(4294967296)||Q.lessThan(0))throw TypeError("uint64 is not supported")}else throw TypeError(`not a LONG type: ${le.onnx.TensorProto.DataType[J]}`);return Q.toNumber()}function Ud(Q,J,G){switch(J){case le.onnx.TensorProto.DataType.BOOL:case le.onnx.TensorProto.DataType.UINT8:return Q.getUint8(G);case le.onnx.TensorProto.DataType.INT8:return Q.getInt8(G);case le.onnx.TensorProto.DataType.UINT16:return Q.getUint16(G,!0);case le.onnx.TensorProto.DataType.INT16:return Q.getInt16(G,!0);case le.onnx.TensorProto.DataType.FLOAT:return Q.getFloat32(G,!0);case le.onnx.TensorProto.DataType.INT32:return Q.getInt32(G,!0);case le.onnx.TensorProto.DataType.UINT32:return Q.getUint32(G,!0);case le.onnx.TensorProto.DataType.INT64:return Ys(Dn.fromBits(Q.getUint32(G,!0),Q.getUint32(G+4,!0),!1),J);case le.onnx.TensorProto.DataType.DOUBLE:return Q.getFloat64(G,!0);case le.onnx.TensorProto.DataType.UINT64:return Ys(Dn.fromBits(Q.getUint32(G,!0),Q.getUint32(G+4,!0),!0),J);default:throw Error(`cannot read from DataView for type ${le.onnx.TensorProto.DataType[J]}`)}}var Wd,le,Me,tr=$(()=>{Wd=ae(sc()),xa(),Br(),le=ae(gr()),xe(),Me=class Q{constructor(J,G,H,K,z,q=Wd.Guid.create()){this.dims=J,this.type=G,this.dataProvider=H,this.asyncDataProvider=K,this.cache=z,this.dataId=q,this.size=U.validateDimsAndCalcSize(J);let F=this.size,D=H===void 0&&K===void 0&&z===void 0;if(z!==void 0&&z.length!==F)throw RangeError("Input dims doesn't match data length.");if(G==="string"){if(z!==void 0&&(!Array.isArray(z)||!z.every((V)=>typeof V=="string")))throw TypeError("cache should be a string array");D&&(this.cache=Array(F))}else{if(z!==void 0){let V=Hd(G);if(!(z instanceof V))throw TypeError(`cache should be type ${V.name}`)}if(D){let V=new ArrayBuffer(F*g0(G));this.cache=b0(V,G)}}}get data(){if(this.cache===void 0){let J=this.dataProvider(this.dataId);if(J.length!==this.size)throw Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=J}return this.cache}get stringData(){if(this.type!=="string")throw TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw TypeError("type cannot be non-number (string)")}get(J){return this.data[U.indicesToOffset(J,this.strides)]}set(J,G){this.data[U.indicesToOffset(J,this.strides)]=G}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=U.computeStrides(this.dims)),this._strides}static fromProto(J){if(!J)throw Error("cannot construct Value from an empty tensor");let G=je.tensorDataTypeFromProto(J.dataType),H=je.tensorDimsFromProto(J.dims),K=new Q(H,G);if(G==="string")J.stringData.forEach((z,q)=>{K.data[q]=Wr(z)});else if(J.rawData&&typeof J.rawData.byteLength=="number"&&J.rawData.byteLength>0){let z=K.data,q=new DataView(J.rawData.buffer,J.rawData.byteOffset,J.rawData.byteLength),F=Gd(J.dataType),D=J.rawData.byteLength/F;if(J.rawData.byteLength%F!==0)throw Error("invalid buffer length");if(z.length!==D)throw Error("buffer length mismatch");for(let V=0;V<D;V++){let O=Ud(q,J.dataType,V*F);z[V]=O}}else{let z;switch(J.dataType){case le.onnx.TensorProto.DataType.FLOAT:z=J.floatData;break;case le.onnx.TensorProto.DataType.INT32:case le.onnx.TensorProto.DataType.INT16:case le.onnx.TensorProto.DataType.UINT16:case le.onnx.TensorProto.DataType.INT8:case le.onnx.TensorProto.DataType.UINT8:case le.onnx.TensorProto.DataType.BOOL:z=J.int32Data;break;case le.onnx.TensorProto.DataType.INT64:z=J.int64Data;break;case le.onnx.TensorProto.DataType.DOUBLE:z=J.doubleData;break;case le.onnx.TensorProto.DataType.UINT32:case le.onnx.TensorProto.DataType.UINT64:z=J.uint64Data;break;default:throw Error("unspecific error")}if(z==null)throw Error("failed to populate data from a tensorproto value");let q=K.data;if(q.length!==z.length)throw Error("array length mismatch");for(let F=0;F<z.length;F++){let D=z[F];Dn.isLong(D)?q[F]=Ys(D,J.dataType):q[F]=D}}return K}static fromData(J,G,H){return new Q(G,H,void 0,void 0,J)}static fromOrtTensor(J){if(!J)throw Error("cannot construct Value from an empty tensor");let G=je.tensorDimsFromORTFormat(J),H=je.tensorDataTypeFromProto(J.dataType()),K=new Q(G,H);if(H==="string")for(let z=0;z<J.stringDataLength();z++)K.data[z]=J.stringData(z);else if(J.rawDataArray()&&typeof J.rawDataLength()=="number"&&J.rawDataLength()>0){let z=K.data,q=new DataView(J.rawDataArray().buffer,J.rawDataArray().byteOffset,J.rawDataLength()),F=Gd(J.dataType()),D=J.rawDataLength()/F;if(J.rawDataLength()%F!==0)throw Error("invalid buffer length");if(z.length!==D)throw Error("buffer length mismatch");for(let V=0;V<D;V++){let O=Ud(q,J.dataType(),V*F);z[V]=O}}return K}}});function j(Q){return Q===1?y0:_0}function qd(Q){let J=j(Q);return`${J.version}
precision highp float;
${J.attribute} vec3 position;
${J.attribute} vec2 textureCoord;
${J.varyingVertex} vec2 TexCoords;
void main()
{
gl_Position = vec4(position, 1.0);
TexCoords = textureCoord;
}`}function jd(Q){let J=j(Q);return`${J.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${J.varyingFrag} vec2 TexCoords;
${J.outputDeclaration}
const vec2 halfCR = vec2(0.5, 0.5);
// Custom vector types to handle higher dimenalities.
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
int imod(int x, int y) {
return x - y * (x / y);
}
`}function Kd(Q,J){let G=j(Q);return`
void main() {
int indices[${J}];
toVec(TexCoords, indices);
vec4 result = vec4(process(indices));
${G.output} = result;
}
`}var y0,_0,De=$(()=>{y0={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},_0={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"}}),pe=$(()=>{});async function eu(Q,J=(H)=>0,G){return new Promise((H,K)=>{let z=0,q=()=>{if(Q()){H();return}z++;let F=J(z);if(G!=null&&z>=G){K();return}setTimeout(q,F)};q()})}function Fo(Q){return br(typeof Q<"u"&&Q.length!==0,()=>"empty string found for sampler name"),"get"+Q.charAt(0).toUpperCase()+Q.slice(1)}function Xd(Q){return br(typeof Q<"u"&&Q.length!==0,()=>"empty string found for sampler name"),"get"+Q.charAt(0).toUpperCase()+Q.slice(1)+"AtOutCoords"}function yr(Q,J){let G=JSON.parse(JSON.stringify(Q));return G=J,G}function _r(Q,J){return J.map((G)=>Q[G]).join(", ")}function Ye(Q){if(Q<=1)return"int";if(Q===2)return"ivec2";if(Q===3)return"ivec3";if(Q===4)return"ivec4";if(Q===5)return"ivec5";if(Q===6)return"ivec6";throw Error(`GPU for rank ${Q} is not yet supported`)}function $t(Q=6){return["x","y","z","w","u","v"].slice(0,Q)}var dn=$(()=>{xe()});function x0(Q,J){return $t(J).map((G)=>`${Q}.${G}`)}function xr(Q,J){return J===1?[Q]:x0(Q,J)}function pn(){return`
float getChannel(vec4 frag, int dim) {
int modCoord = imod(dim, 2);
return modCoord == 0 ? frag.r : frag.g;
}
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
`}var nr=$(()=>{dn()});function T0(Q,J,G){if(Q===0)return"false";if(Q===1)return`rc > ${J[0]}`;let H="";for(let K=Q-2;K<Q;K++)H+=`${G[K]} >= ${J[K-Q+2]}`,K<Q-1&&(H+="||");return H}function v0(Q,J){let G=Q.length;if(G===0)return"getA(), 0, 0, 0";if(G===1)return`getA(rc),
rc + 1 >= ${Q[0]} ? 0. : getA(rc + 1),
0, 0`;let H="r, c",K="r, cp1",z="rp1, c",q="rp1, cp1",F="";if(G>2)for(let D=0;D<G-2;++D)F=F+`${J[D]},`;return`getA(${F}${H}),
rEdge ? 0. : getA(${F}${z}),
cEdge ? 0. : getA(${F}${K}),
rEdge || cEdge ? 0. : getA(${F}${q})`}function I0(Q,J,G,H){return Q===0||Q===1?"":`
int r = ${J[Q-2]};
int c = ${J[Q-1]};
int rp1 = ${J[Q-2]} + 1;
int cp1 = ${J[Q-1]} + 1;
bool rEdge = rp1 >= ${H};
bool cEdge = cp1 >= ${G};
`}var Zd,w0,Jd,Qd=$(()=>{De(),pe(),dn(),nr(),Zd={name:"pack",inputNames:["A"],inputTypes:[1]},w0=(Q,J)=>{let G=j(Q.session.backend.glContext.version),H=J.dims,K=H.length,z=J.dims.length,q=Ye(z),F=xr("rc",z),D=I0(z,F,H[H.length-2],H[H.length-1]),V;K===0?V=[1,1]:K===1?V=[H[0],1]:V=[H[z-1],H[z-2]];let O=T0(z,V,F),P=v0(H,F),N=`
void main() {
${q} rc = getOutputCoords();
if(${O}) {
${G.output} = vec4(0);
} else {
${D}
${G.output} = vec4(${P});
}
}
`;return{...Zd,hasMain:!0,output:{dims:J.dims,type:J.type,textureType:2},shaderSource:N}},Jd=(Q,J)=>({...Zd,get:()=>w0(Q,J)})});function tu(Q){if(Q.length===0)return[1,1,1];let J=1;for(let G=0;G<Q.length-2;++G)J*=Q[G];return[J,Q.length>1?Q[Q.length-2]:1,Q[Q.length-1]]}function ep(Q,J){let G=!1;return Q.length===0||J.length===0?G=!0:Q.length<2||J.length<2?G=Q[Q.length-1]===J[J.length-1]:G=Q[Q.length-1]===J[J.length-1]&&Q[Q.length-2]===J[J.length-2],G}function A0(Q){let J=U.computeStrides(Q),G=["b","r","c"],H="index";return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${J.map((K,z)=>{let q=`int ${G[z]} = ${H} / ${K}`,F=z===J.length-1?`int ${G[z+1]} = ${H} - ${G[z]} * ${K}`:`index -= ${G[z]} * ${K}`;return`${q}; ${F};`}).join("")}
return ivec3(b, r, c);
}
`}function P0(Q){let J=U.computeStrides(Q);return`
int getFlattenedIndex(ivec3 coords) {
// reverse y, z order
return coords.x * ${J[0]} + coords.z * ${J[1]} + coords.y;
}
`}var S0,$0,Yd,tp=$(()=>{xe(),De(),pe(),nr(),S0=(Q)=>({name:"Reshape (packed)",inputTypes:[2],inputNames:["A"],cacheHint:`${Q}`}),$0=(Q,J,G,H)=>{let K=J.dims,z=H,q="";for(let V=0;V<4;V++){let O="";switch(V){case 0:O="outputCoords = rc;";break;case 1:O="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:O="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:O="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw Error()}q+=`
${O}
${V>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}
int flattenedIndex = getFlattenedIndex(outputCoords);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);
vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${V}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);
${V>0?"}":""}
`}let F=j(Q.session.backend.glContext.version),D=`
${A0(K)}
${P0(z)}
${pn()}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.0);
ivec3 outputCoords;
int rows = ${z[2]};
int cols = ${z[1]};
${q}
${F.output} = result;
}
`;return{...G,output:{dims:z,type:J.type,textureType:2},shaderSource:D,hasMain:!0}},Yd=(Q,J,G)=>{let H=S0(G);return{...H,get:()=>$0(Q,J,H,G)}}}),nu,np=$(()=>{De(),pe(),nu=(Q,J)=>{let G=J.shape,H=j(Q.session.backend.glContext.version),K=`
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
bool isNaN(float val) {
return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;
}
highp vec4 encodeAsUint8(highp float v) {
if (isNaN(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
void main() {
float value = ${H.texture2D}(X,TexCoords).r;
${H.output} = encodeAsUint8(value);
}`,z={name:"Uint8Encode",inputTypes:[0],inputNames:["X"],output:{dims:G,type:J.tensor.type,textureType:3},shaderSource:K,hasMain:!0};return Q.executeProgram(z,[J.tensor])}});function E0(Q,J){if(Q===1)return"rc";let G="";for(let H=0;H<Q;H++)G+=J[H],H<Q-1&&(G+=",");return G}var rp,O0,op,ip=$(()=>{De(),pe(),dn(),nr(),rp={name:"unpack",inputNames:["A"],inputTypes:[2]},O0=(Q,J)=>{let G=J.dims.length,H=xr("rc",G),K=H.slice(-2),z=Ye(G),q=pn(),F=J.dims.length===0?"":E0(G,H),D=G<=1?"rc":`vec2(${K.join(",")})`,V=j(Q.session.backend.glContext.version),O=`
${q}
void main() {
${z} rc = getOutputCoords();
// Sample the texture with the coords to get the rgba channel value.
vec4 packedInput = getA(${F});
${V.output} = vec4(getChannel(packedInput, ${D}), 0, 0, 0);
}
`;return{...rp,hasMain:!0,output:{dims:J.dims,type:J.type,textureType:0},shaderSource:O}},op=(Q,J)=>({...rp,get:()=>O0(Q,J)})}),Vo,Hr,Go,qr=$(()=>{ct(),Vo=class{constructor(Q,J=1){if(J===1)this.internalFormat=Q.R32F,this.format=Q.RED,this.textureType=Q.FLOAT,this.channelSize=J;else if(J===4)this.internalFormat=Q.RGBA32F,this.format=Q.RGBA,this.textureType=Q.FLOAT,this.channelSize=J;else throw Error(`Invalid number of channels: ${J}`)}encode(Q,J){let G,H;return Q.constructor!==Float32Array&&(Te.warning("Encoder","data was not of type Float32; creating new Float32Array"),H=new Float32Array(Q)),J*this.channelSize>Q.length?(Te.warning("Encoder","Source data too small. Allocating larger array"),H=Q,G=this.allocate(J*this.channelSize),H.forEach((K,z)=>G[z]=K)):(H=Q,G=H),G}allocate(Q){return new Float32Array(Q*4)}decode(Q,J){return this.channelSize===1?Q.filter((G,H)=>H%4===0).subarray(0,J):Q.subarray(0,J)}},Hr=class{constructor(Q,J=1,G){if(J!==1&&J!==4)throw Error(`Invalid number of channels: ${J}`);this.internalFormat=Q.RGBA,this.format=Q.RGBA,this.channelSize=J,this.textureType=G||Q.FLOAT}encode(Q,J){let G=Q;return this.channelSize===1&&(Te.verbose("Encoder","Exploding into a larger array"),G=this.allocate(J),Q.forEach((H,K)=>G[K*4]=H)),G}allocate(Q){return new Float32Array(Q*4)}decode(Q,J){return this.channelSize===1?Q.filter((G,H)=>H%4===0).subarray(0,J):Q.subarray(0,J)}},Go=class{constructor(Q,J=1){if(this.channelSize=4,J===1)this.internalFormat=Q.ALPHA,this.format=Q.ALPHA,this.textureType=Q.UNSIGNED_BYTE,this.channelSize=J;else if(J===4)this.internalFormat=Q.RGBA,this.format=Q.RGBA,this.textureType=Q.UNSIGNED_BYTE,this.channelSize=J;else throw Error(`Invalid number of channels: ${J}`)}encode(Q,J){return new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)}allocate(Q){return new Uint8Array(Q*this.channelSize)}decode(Q,J){if(Q instanceof Uint8Array)return Q.subarray(0,J);throw Error(`Invalid array type: ${Q.constructor}`)}}}),jr,ap,ru,sp=$(()=>{xe(),pe(),jr=(Q,J,G)=>{let H=G===0||G===1?1:4,K=G===2,z=G===1||G===2,q=G===4?J.length-1:void 0,F=G===4?J.map((D,V)=>V===J.length-1?D*4:D):void 0;return ru(Q,J,H,F,{isPacked:K,reverseWH:z,breakAxis:q})},ap=(Q,J,G)=>{let H=jr(Q,J,G);return[H.width,H.height]},ru=(Q,J,G=1,H,K)=>{let z=!!(K&&K.isPacked),[q,F]=Q.computeTextureWH(z&&H||J,K),D=J.length,V=J.slice(0);if(D===0&&(V=[1]),G===1)H=J;else if(z){if(G!==4)throw Error("a packed texture must be 4-channel");H=J,D>0&&(V[D-1]=Math.ceil(V[D-1]/2)),D>1&&(V[D-2]=Math.ceil(V[D-2]/2))}else if(!H)throw Error("Unpacked shape is needed when using channels > 1");return{width:q,height:F,channels:G,isPacked:z,shape:V,strides:U.computeStrides(V),unpackedShape:H,reversedWH:K&&K.reverseWH}}}),D0,Uo,lp=$(()=>{ct(),tr(),xe(),Qd(),tp(),np(),ip(),qr(),sp(),pe(),D0=(Q,J)=>{let G=J.map((K)=>`${K.unpackedShape.join(",")};${K.width}x${K.height}`).join("_"),H=Q.name;return Q.cacheHint&&(H+="["+Q.cacheHint+"]"),H+=":"+G,H},Uo=class{constructor(Q){this.session=Q,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(Q,J){return ap(this.session.layoutStrategy,Q,J)}executeProgram(Q,J){if(J.length<Q.inputNames.length)throw Error(`Input size mustn't be less than ${Q.inputNames.length}.`);if(Q.inputNames.length!==Q.inputTypes.length)throw Error("input names size does not match input types");let G=[];for(let D=0;D<Q.inputNames.length;++D)G[D]=this.getOrCreateTextureData(J[D],Q.inputTypes[D]);let H=D0(Q,G),K=this.session.programManager.getArtifact(H),z=K?K.programInfo:typeof Q.get=="function"?Q.get():Q,q=jr(this.session.layoutStrategy,z.output.dims,z.output.textureType),F=this.createTextureData(q,z.output.type);return K||(K=this.session.programManager.build(z,G,F),this.session.programManager.setArtifact(H,K)),this.runProgram(K,G,F),F}run(Q,J){return this.executeProgram(Q,J).tensor}runProgram(Q,J,G){for(let H=0;H<J.length;++H)if(!!J[H].isPacked!=(Q.programInfo.inputTypes[H]===2))throw Error(`input[${H}] property packed inconsistent`);if(!!G.isPacked!=(Q.programInfo.output.textureType===2))throw Error("output property packed inconsistent");this.session.programManager.run(Q,J,G)}getOrCreateTextureData(Q,J){let G=this.getTextureData(Q.dataId,J===2);if(!G&&(G=this.getTextureData(Q.dataId,J!==2),G))return J===2?this.pack(G):this.unpack(G);if(!G){let H=jr(this.session.layoutStrategy,Q.dims,J);if(J===4){let K=Q.dims;if(K.length===4){let z=[K[0],Math.ceil(K[1]*K[2]*K[3]/4)],q=jr(this.session.layoutStrategy,z,J),F=Q.numberData;if(K[1]*K[2]*K[3]%4!==0){let D=K[0],V=K[1]*K[2]*K[3],O=Math.ceil(V*1/4)*4,P=D*O;F=new Float32Array(P);for(let N=0;N<D;++N){let I=N*V,R=N*O+N%1*V;F.set(Q.numberData.subarray(I,I+V),R)}}return this.createTextureData(q,Q.type,F,Q,1)}}if(J===2){let K=ru(this.session.layoutStrategy,Q.dims,1,[],{reverseWH:!0}),z=this.createTextureData(K,Q.type,Q.numberData,Q,1);G=this.pack(z)}else G=this.createTextureData(H,Q.type,Q.numberData,Q,1)}return G}createTextureDataFromLayoutBindTensor(Q,J,G,H){return this.createTextureData(Q,J,G,H,1)}createTextureData(Q,J,G,H,K){Te.verbose("InferenceHandler",`Creating TextureData: layout:[${JSON.stringify(Q)}]`);let z=this.session.textureManager.createTextureFromLayout(J,Q,G,K);return this.createTextureDataFromTexture(Q,J,z,H)}reshapeUnpacked(Q,J){let G=this.getOrCreateTextureData(Q,0),H={channels:G.channels,height:G.height,width:G.width,shape:J.length!==0?J:[1],strides:U.computeStrides(J),unpackedShape:J};return this.createTextureDataFromTexture(H,Q.type,G.texture).tensor}reshapePacked(Q,J){let G=this.getOrCreateTextureData(Q,2);if(ep(Q.dims,J)){let F={channels:G.channels,height:G.height,width:G.width,shape:J.length!==0?J:[1],strides:U.computeStrides(J),unpackedShape:J,isPacked:!0};return this.createTextureDataFromTexture(F,Q.type,G.texture).tensor}let H=tu(Q.dims),K=tu(J),z=this.reshapePacked(Q,H),q=this.run(Yd(this,z,K),[z]);return this.reshapePacked(q,J)}cast(Q,J){let G=this.getOrCreateTextureData(Q,0);return this.createTextureDataFromTexture(G,J,G.texture).tensor}createTextureDataFromTexture(Q,J,G,H,K){let z={...Q,tensor:H||new Me(Q.unpackedShape,J,(q)=>this.readTexture(z),async(q)=>this.readTextureAsync(z),void 0,K),texture:G};return this.setTextureData(z.tensor.dataId,z,Q.isPacked),z}getTextureData(Q,J=!1){return this.session.isInitializer(Q)?this.session.getTextureData(Q,J):J?this.packedTextureDataCache.get(Q):this.unpackedTextureDataCache.get(Q)}setTextureData(Q,J,G=!1){this.session.isInitializer(Q)?this.session.setTextureData(Q,J,G):(G?this.packedTextureDataCache:this.unpackedTextureDataCache).set(Q,J)}isTextureLayoutCached(Q,J=!1){return!!this.getTextureData(Q.dataId,J)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((Q)=>this.session.textureManager.releaseTexture(Q)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((Q)=>this.session.textureManager.releaseTexture(Q)),this.unpackedTextureDataCache=new Map}readTexture(Q){return Q.isPacked?this.readTexture(this.unpack(Q)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(Q,Q.tensor.type,Q.channels):this.session.textureManager.readUint8TextureAsFloat(nu(this,Q))}async readTextureAsync(Q){return Q.isPacked?this.readTextureAsync(this.unpack(Q)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(Q,Q.tensor.type,Q.channels):this.session.textureManager.readUint8TextureAsFloat(nu(this,Q))}pack(Q){return this.executeProgram(Jd(this,Q.tensor),[Q.tensor])}unpack(Q){return this.executeProgram(op(this,Q.tensor),[Q.tensor])}}}),ou,se,We=$(()=>{ou=class{constructor(Q){Object.assign(this,Q)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map((Q)=>`${this[Q]}`).join(";")),this.key}},se=(Q)=>new ou(Q)}),cp,dp,pp,k0,L0,fp=$(()=>{We(),De(),pe(),cp={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[0,0,0,0,0]},dp=(Q,J,G)=>(L0(J),[Q.run({...cp,cacheHint:G.cacheKey,get:()=>k0(Q,J,G)},J)]),pp=(Q)=>{let J=Q.attributes.getFloat("epsilon",0.00001),G=Q.attributes.getFloat("momentum",0.9),H=Q.attributes.getInt("spatial",1);return se({epsilon:J,momentum:G,spatial:H})},k0=(Q,J,G)=>{let H=j(Q.session.backend.glContext.version),K=J[0].dims.length,[z,q]=Q.calculateTextureWidthAndHeight(J[1].dims,0),F=`
float process(int[${K}] indices) {
vec2 position = offsetToCoords(indices[1], ${z}, ${q});
float scale = getColorAsFloat(${H.texture2D}(Scale, position));
float mean = getColorAsFloat(${H.texture2D}(Mean, position));
float variance = getColorAsFloat(${H.texture2D}(Variance, position));
float b = getColorAsFloat(${H.texture2D}(B, position));
return scale * ( (_A(indices) - mean) / sqrt(variance + float(${G.epsilon})) ) + b;
}`;return{...cp,output:{dims:J[0].dims,type:J[0].type,textureType:0},shaderSource:F}},L0=(Q)=>{if(!Q||Q.length!==5)throw Error("BatchNormalization requires 5 inputs.");let J=Q[0],G=Q[1],H=Q[2],K=Q[3],z=Q[4];if(J.dims.length<3||G.dims.length!==1||H.dims.length!==1||K.dims.length!==1||z.dims.length!==1)throw Error("invalid input shape.");if(G.dims[0]!==J.dims[1]||H.dims[0]!==J.dims[1]||K.dims[0]!==J.dims[1]||z.dims[0]!==J.dims[1])throw Error("invalid input shape.");if(J.type!=="float32"&&J.type!=="float64"||G.type!=="float32"&&G.type!=="float64"||H.type!=="float32"&&H.type!=="float64"||K.type!=="float32"&&K.type!=="float64"||z.type!=="float32"&&z.type!=="float64")throw Error("invalid input tensor types.")}}),Wo,gt,M,Kr,Ho,An=$(()=>{Wo=class{constructor(Q,J,G,H){this.glContext=Q,this.programInfo=J,this.inputTextureLayouts=G,this.outputTextureLayout=H}},gt=class{constructor(Q){this.context=Q}},M=class{constructor(Q,J){this.routineBody=Q,this.dependencies=J}},Kr=class{constructor(Q,J,G){this.name=Q,G?this.dependencies=G:this.dependencies=[],J&&(this.routineBody=J)}addDependency(Q){Q&&this.dependencies.push(Q)}},Ho=class{static returnOrderedNodes(Q){if(!Q||Q.length===0)return[];if(Q.length===1)return Q;let J=new Set,G=new Set,H=[];return this.createOrderedNodes(Q,J,G,H),H}static createOrderedNodes(Q,J,G,H){for(let K=0;K<Q.length;++K)this.dfsTraverse(Q[K],J,G,H)}static dfsTraverse(Q,J,G,H){if(!Q||G.has(Q.name))return;if(J.has(Q.name))throw Error("Cyclic dependency detected. Can't topologically sort routines needed for shader.");J.add(Q.name);let K=Q.dependencies;if(K&&K.length>0)for(let z=0;z<K.length;++z)this.dfsTraverse(K[z],J,G,H);H.push(Q),G.add(Q.name),J.delete(Q.name)}}});function N0(){let Q="add_";return{body:`
float ${Q}(float a, float b) {
return a + b;
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return v1 + v2;
}
`,name:Q,type:0}}function z0(){let Q="div_";return{body:`
float ${Q}(float a, float b) {
return a / b;
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return v1 / v2;
}
`,name:Q,type:0}}function M0(){let Q="mul_";return{body:`
float ${Q}(float a, float b) {
return a * b;
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return v1 * v2;
}
`,name:Q,type:0}}function B0(){let Q="sub_";return{body:`
float ${Q}(float a, float b) {
return a - b;
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return v1 - v2;
}
`,name:Q,type:0}}function F0(){let Q="equal_";return{body:`
float ${Q}(float a, float b) {
return float(a == b);
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return vec4(equal(v1, v2));
}
`,name:Q,type:0}}function V0(){let Q="greater_";return{body:`
float ${Q}(float a, float b) {
return float(a > b);
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return vec4( v1.r > v2.r ,
v1.g > v2.g,
v1.b > v2.b,
v1.a > v2.a );
}
`,name:Q,type:0}}function G0(){let Q="less_";return{body:`
float ${Q}(float a, float b) {
return float(a < b);
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return vec4( v1.r < v2.r ,
v1.g < v2.g,
v1.b < v2.b,
v1.a < v2.a );
}
`,name:Q,type:0}}function U0(){let Q="and_";return{body:`
float ${Q}(float a, float b) {
return float( bool(a) && bool(b) );
}
vec4 ${Q}(vec4 v1, vec4 v2) {
bvec4 b1 = bvec4(v1);
bvec4 b2 = bvec4(v2);
return vec4( b1.r && b2.r ,
b1.g && b2.g,
b1.b && b2.b,
b1.a && b2.a );
}
`,name:Q,type:0}}function W0(){let Q="or_";return{body:`
float ${Q}(float a, float b) {
return float( bool(a) || bool(b) );
}
vec4 ${Q}(vec4 v1, vec4 v2) {
bvec4 b1 = bvec4(v1);
bvec4 b2 = bvec4(v2);
return vec4( b1.r || b2.r ,
b1.g || b2.g,
b1.b || b2.b,
b1.a || b2.a );
}
`,name:Q,type:0}}function H0(){let Q="xor_";return{body:`
float ${Q}(float a, float b) {
return float( bool(a) ^^ bool(b) );
}
vec4 ${Q}(vec4 v1, vec4 v2) {
bvec4 b1 = bvec4(v1);
bvec4 b2 = bvec4(v2);
return vec4( b1.r ^^ b2.r ,
b1.g ^^ b2.g,
b1.b ^^ b2.b,
b1.a ^^ b2.a );
}
`,name:Q,type:0}}function q0(){return K0("pow")}function j0(){let Q="prelu_";return{body:`
float ${Q}(float a, float b) {
return a < 0.0 ? a * b: a;
}
vec4 ${Q}(vec4 v1, vec4 v2) {
return vec4(
v1.r < 0.0 ? v1.r * v2.r: v1.r,
v1.g < 0.0 ? v1.g * v2.g: v1.g,
v1.b < 0.0 ? v1.b * v2.b: v1.b,
v1.a < 0.0 ? v1.a * v2.a: v1.a
);
}
`,name:Q,type:0}}function K0(Q){let J=`${Q}_`;return{body:`
float ${J}(float a, float b) {
return ${Q}(a, b);
}
vec4 ${J}(vec4 v1, vec4 v2) {
return ${Q}(v1, v2);
}
`,name:J,type:0}}var bt,X0,hp,mp,gp,bp,yp,_p,xp,wp,Tp,vp,Ip,Sp,$p=$(()=>{xe(),An(),De(),pe(),bt=(Q,J,G,H=J[0].type,K)=>{let z=Q.session.pack?2:0;return{name:G.name,inputNames:["A","B"],inputTypes:[z,z],cacheHint:K,get:()=>X0(Q,J,G,H)}},X0=(Q,J,G,H=J[0].type)=>{let K=Q.session.pack?2:0,z=!U.areEqual(J[0].dims,J[1].dims),q=J[0].dims,F=Q.session.pack;if(z){let O=Qe.calcShape(J[0].dims,J[1].dims,!1);if(!O)throw Error("Can't perform binary op on the given tensors");q=O;let P=q.length,N=J[0].dims.length!==0?J[0].dims.length:1,I=J[1].dims.length!==0?J[1].dims.length:1,R=J[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",w=J[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",E=j(Q.session.backend.glContext.version),T=F?`
${G.body}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = ${G.name}(a, b);
${E.output} = result;
}`:`
${G.body}
float process(int indices[${P}]) {
int aindices[${N}];
int bindices[${I}];
${R}
${w}
return ${G.name}(_A(aindices), _B(bindices));
}`;return{name:G.name,inputNames:["A","B"],inputTypes:[K,K],output:{dims:q,type:H,textureType:K},shaderSource:T,hasMain:F}}let D=j(Q.session.backend.glContext.version),V=`
${G.body}
void main() {
vec4 v1 = ${D.texture2D}(A, TexCoords);
vec4 v2 = ${D.texture2D}(B, TexCoords);
vec4 result = ${G.name}(v1, v2);
${D.output} = result;
}
`;return{name:G.name,inputNames:["A","B"],inputTypes:[K,K],output:{dims:J[0].dims,type:H,textureType:K},shaderSource:V,hasMain:!0}},hp=(Q,J)=>[Q.run(bt(Q,J,N0()),J)],mp=(Q,J)=>[Q.run(bt(Q,J,U0(),"bool"),J)],gp=(Q,J)=>[Q.run(bt(Q,J,z0()),J)],bp=(Q,J)=>[Q.run(bt(Q,J,F0(),"bool"),J)],yp=(Q,J)=>[Q.run(bt(Q,J,V0(),"bool"),J)],_p=(Q,J)=>[Q.run(bt(Q,J,G0(),"bool"),J)],xp=(Q,J)=>[Q.run(bt(Q,J,M0()),J)],wp=(Q,J)=>[Q.run(bt(Q,J,W0(),"bool"),J)],Tp=(Q,J)=>[Q.run(bt(Q,J,q0()),J)],vp=(Q,J)=>[Q.run(bt(Q,J,j0()),J)],Ip=(Q,J)=>[Q.run(bt(Q,J,B0()),J)],Sp=(Q,J)=>[Q.run(bt(Q,J,H0(),"bool"),J)]}),Ap,Pp,J0,Op=$(()=>{xe(),Ap=(Q,J,G)=>(J0(J),[Q.cast(J[0],G)]),Pp=(Q)=>je.tensorDataTypeFromProto(Q.attributes.getInt("to")),J0=(Q)=>{if(!Q||Q.length!==1)throw Error("Cast requires 1 input.");if(Q[0].type==="string")throw Error("Invalid input type.")}}),Q0,Y0,Ep,qo,Cp=$(()=>{De(),pe(),dn(),nr(),Q0=(Q,J)=>({name:"Concat (packed)",inputNames:Array.from({length:Q},(G,H)=>`X${H}`),inputTypes:Array(Q).fill(2),cacheHint:J}),Y0=(Q,J,G,H)=>{let K=G[0].dims.slice();if(H>=K.length||H<-1*K.length)throw Error("axis specified for concat doesn't match input dimensionality");H<0&&(H=K.length+H);let z=K.slice(0);for(let g=1;g<G.length;g++){let l=G[g].dims.slice();for(let _=0;_<K.length;_++)if(_===H)z[H]+=l[_];else if(K[_]!==l[_])throw Error("non concat dimensions must match")}let q=z.length,F=xr("coords",q),D=Ye(q),V=pn(),O=G.map((g)=>g.dims),P=$t(q),N=Array(O.length-1);N[0]=O[0][H];for(let g=1;g<N.length;g++)N[g]=N[g-1]+O[g][H];let I=P[H],R=P.slice(-2),w=P.join(),E=`if (${I} < ${N[0]}) {
return getChannel(
getX0(${w}), vec2(${R.join()}));
}`;for(let g=1;g<N.length;g++){let l=N[g-1];E+=`
if (${I} < ${N[g]} && ${I} >= ${N[g-1]}) {
return getChannel(
getX${g}(${qo(P,I,l)}),
vec2(${qo(R,I,l)}));
}`}let T=N.length,y=N[N.length-1];E+=`
return getChannel(
getX${T}(${qo(P,I,y)}),
vec2(${qo(R,I,y)}));`;let x=j(Q.session.backend.glContext.version),b=`
${V}
float getValue(${P.map((g)=>"int "+g)}) {
${E}
}
void main() {
${D} coords = getOutputCoords();
int lastDim = coords.${P[q-1]};
coords.${P[q-1]} = coords.${P[q-2]};
coords.${P[q-2]} = lastDim;
vec4 result = vec4(getValue(${F}), 0., 0., 0.);
${F[q-1]} = ${F[q-1]} + 1;
if (${F[q-1]} < ${z[q-1]}) {
result.g = getValue(${F});
}
${F[q-2]} = ${F[q-2]} + 1;
if (${F[q-2]} < ${z[q-2]}) {
result.a = getValue(${F});
}
${F[q-1]} = ${F[q-1]} - 1;
if (${F[q-2]} < ${z[q-2]} &&
${F[q-1]} < ${z[q-1]}) {
result.b = getValue(${F});
}
${x.output} = result;
}
`;return{...J,output:{dims:z,type:G[0].type,textureType:2},shaderSource:b,hasMain:!0}},Ep=(Q,J,G)=>{let H=Q0(J.length,G.cacheKey);return{...H,get:()=>Y0(Q,H,J,G.axis)}},qo=(Q,J,G)=>{let H=Q.indexOf(J);return Q.map((K,z)=>z===H?`${K} - ${G}`:K).join()}}),Dp,eI,tI,nI,kp,rI,oI,iI,Lp,aI,Rp=$(()=>{We(),pe(),Cp(),Dp=(Q,J,G)=>(aI(J),Q.session.pack&&J[0].dims.length>1?[Q.run(Ep(Q,J,G),J)]:[Q.run(nI(Q,J,G),J)]),eI=(Q,J)=>({name:"Concat",inputNames:Array.from({length:Q},(G,H)=>`X${H}`),inputTypes:Array(Q).fill(0),cacheHint:J}),tI=(Q,J,G,H)=>{let K=G[0].dims.slice();if(H>=K.length||H<-1*K.length)throw Error("axis specified for concat doesn't match input dimensionality");H<0&&(H=K.length+H);let z=K.slice(0);for(let I=1;I<G.length;I++){let R=G[I].dims.slice();for(let w=0;w<K.length;w++)if(w===H)z[H]+=R[w];else if(K[w]!==R[w])throw Error("non concat dimensions must match")}let q=z.length,F=Array(G.length),D=0;for(let I=0;I<F.length;++I)D+=G[I].dims[H],F[I]=D;let V="";G.length<5?V=kp(F):V=rI(F);let O=oI(G.length,q),P=iI(F),N=`
${O}
${P}
${V}
float process(int indices[${q}]) {
int textureIndex = getTextureWhereDataResides (indices[${H}]);
if(textureIndex != 0) {
indices[${H}] = indices[${H}] - int(getSizeInConcatAxisValueFromIndex(textureIndex-int(1)));
}
return fetchDataFromCorrectTexture(textureIndex, indices);
}`;return{...J,output:{dims:z,type:G[0].type,textureType:0},shaderSource:N}},nI=(Q,J,G)=>{let H=eI(J.length,G.cacheKey);return{...H,get:()=>tI(Q,H,J,G.axis)}},kp=(Q)=>`int getTextureWhereDataResides(int index) {
${Q.map((J,G)=>`if(index<${J}) {return ${G};}
`).join("")}
}`,rI=(Q)=>kp(Q),oI=(Q,J)=>{let G=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${J}]) {`];for(let H=0;H<Q;++H)H===0?G.push(` if (textureIndex == ${H}) { return _X${H}(indices); }`):H===Q-1?G.push(` else { return _X${H}(indices); }`):G.push(` else if (textureIndex == ${H}) { return _X${H}(indices); }`);return G.push("\t}"),G.join(`
`)},iI=(Q)=>{let J=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let G=0;G<Q.length;++G)G===0?J.push(` if (index == ${G}) { return ${Q[G]}; }`):G===Q.length-1?J.push(` else { return ${Q[G]}; }`):J.push(` else if (index == ${G}) { return ${Q[G]}; }`);return J.push("\t}"),J.join(`
`)},Lp=(Q)=>se({axis:Q.attributes.getInt("axis")}),aI=(Q)=>{if(!Q||Q.length<1)throw Error("too few inputs");let J=Q[0].type,G=Q[0].dims.length;if(J==="string")throw Error("string tensor is not supported yet");for(let H of Q){if(H.type!==J)throw Error("input tensors should be one type");if(H.dims.length!==G)throw Error("input tensors should have the same shape")}}});function sI(){return yt("abs")}function uI(){return yt("acos")}function lI(){return yt("asin")}function cI(){return yt("atan")}function dI(){return yt("ceil")}function pI(){return yt("cos")}function fI(Q){let J="elu";return{body:`
const float alpha = float(${Q});
float ${J}_(float a) {
return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;
}
vec4 ${J}_(vec4 v) {
return vec4(${J}_(v.x), ${J}_(v.y), ${J}_(v.z), ${J}_(v.w));
}
`,name:J,type:0}}function hI(){return yt("exp")}function mI(){return yt("floor")}function iu(Q,J){let G="clip";return{body:`
const float min = float(${Q});
const float max = float(${J});
float ${G}_(float a) {
return clamp(a, min, max);
}
vec4 ${G}_(vec4 v) {
return clamp(v, min, max);
}
`,name:G,type:0}}function gI(){let Q="indentity";return{body:`
float ${Q}_(float a) {
return a;
}
vec4 ${Q}_(vec4 v) {
return v;
}
`,name:Q,type:0}}function bI(Q){let J="leakyRelu";return{body:`
const float alpha = float(${Q});
float ${J}_(float a) {
return a < 0.0 ? a * alpha : a;
}
vec4 ${J}_(vec4 v) {
return vec4(${J}_(v.x), ${J}_(v.y), ${J}_(v.z), ${J}_(v.w));
}
`,name:J,type:0}}function yI(){return yt("log")}function _I(){let Q="neg";return{body:`
float ${Q}_(float a) {
return -a;
}
vec4 ${Q}_(vec4 v) {
return -v;
}
`,name:Q,type:0}}function xI(){let Q="not";return{body:`
float ${Q}_(float a) {
return float( ! bool(a) );
}
bool ${Q}_(bool a) {
return !a;
}
vec4 ${Q}_(vec4 v) {
return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));
}
bvec4 ${Q}_(bvec4 v) {
return bvec4(!v.x, !v.y, !v.z, !v.w);
}
`,name:Q,type:0}}function wI(){return yt("sin")}function au(){let Q="relu";return{body:`
float ${Q}_(float a) {
return max( a, 0.0 );
}
vec4 ${Q}_(vec4 v) {
return max( v, 0.0 );
}
`,name:Q,type:0}}function su(){let Q="sigmoid";return{body:`
float ${Q}_(float a) {
return 1.0 / (1.0 + exp(-a));
}
vec4 ${Q}_(vec4 v) {
return 1.0 / (1.0 + exp(-v));
}
`,name:Q,type:0}}function TI(){return yt("sqrt")}function vI(){return yt("tan")}function II(){let Q="tanh";return{body:`
float ${Q}_(float a) {
a = clamp(a, -10., 10.);
a = exp(2.*a);
return (a - 1.) / (a + 1.);
}
vec4 ${Q}_(vec4 v) {
v = clamp(v, -10., 10.);
v = exp(2.*v);
return (v - 1.) / (v + 1.);
}
`,name:Q,type:0}}function yt(Q){return{body:`
float ${Q}_(float a) {
return ${Q}(a);
}
vec4 ${Q}_(vec4 v) {
return ${Q}(v);
}
`,name:Q,type:0}}var SI,ze,Np,zp,Mp,Bp,uu,Fp,Vp,$I,Gp,Up,Wp,Hp,qp,jp,lu,Kp,Xp,Zp,Jp,Qp,Yp,ef,tf,nf,rf,of,cu=$(()=>{We(),xe(),An(),De(),pe(),SI=(Q,J,G,H)=>{let K=Q.session.pack?2:0,z=j(Q.session.backend.glContext.version);return{...J,output:{dims:G.dims,type:G.type,textureType:K},shaderSource:`
${H.body}
void main() {
vec4 v = ${z.texture2D}(A, TexCoords);
v = ${H.name}_(v);
${z.output} = v;
}
`,hasMain:!0}},ze=(Q,J,G,H)=>{let K=Q.session.pack?2:0,z={name:G.name,inputTypes:[K],inputNames:["A"],cacheHint:H};return{...z,get:()=>SI(Q,z,J,G)}},Np=(Q,J)=>[Q.run(ze(Q,J[0],sI()),J)],zp=(Q,J)=>[Q.run(ze(Q,J[0],uI()),J)],Mp=(Q,J)=>[Q.run(ze(Q,J[0],lI()),J)],Bp=(Q,J)=>[Q.run(ze(Q,J[0],cI()),J)],uu=(Q,J,G)=>[Q.run(ze(Q,J[0],iu(G.min,G.max),G.cacheKey),J)],Fp=(Q)=>se({min:Q.attributes.getFloat("min",Yn),max:Q.attributes.getFloat("max",er)}),Vp=(Q,J)=>{let G=$I(Q,J);return uu(Q,[J[0]],G)},$I=(Q,J)=>{if(J.length>=3&&(!Q.session.isInitializer(J[1].dataId)||!Q.session.isInitializer(J[2].dataId)))throw Error("dynamic clip attributes are not allowed");let G=J.length>=3?J[1].numberData[0]:Yn,H=J.length>=3?J[2].numberData[0]:er;return se({min:G,max:H})},Gp=(Q,J)=>[Q.run(ze(Q,J[0],dI()),J)],Up=(Q,J)=>[Q.run(ze(Q,J[0],pI()),J)],Wp=(Q,J,G)=>[Q.run(ze(Q,J[0],fI(G.alpha),G.cacheKey),J)],Hp=(Q)=>se({alpha:Q.attributes.getFloat("alpha",1)}),qp=(Q,J)=>[Q.run(ze(Q,J[0],hI()),J)],jp=(Q,J)=>[Q.run(ze(Q,J[0],mI()),J)],lu=(Q,J)=>[Q.run(ze(Q,J[0],gI()),J)],Kp=(Q,J,G)=>[Q.run(ze(Q,J[0],bI(G.alpha),G.cacheKey),J)],Xp=(Q)=>se({alpha:Q.attributes.getFloat("alpha",0.01)}),Zp=(Q,J)=>[Q.run(ze(Q,J[0],yI()),J)],Jp=(Q,J)=>[Q.run(ze(Q,J[0],_I()),J)],Qp=(Q,J)=>[Q.run(ze(Q,J[0],xI()),J)],Yp=(Q,J)=>[Q.run(ze(Q,J[0],au()),J)],ef=(Q,J)=>[Q.run(ze(Q,J[0],su()),J)],tf=(Q,J)=>[Q.run(ze(Q,J[0],wI()),J)],nf=(Q,J)=>[Q.run(ze(Q,J[0],TI()),J)],rf=(Q,J)=>[Q.run(ze(Q,J[0],vI()),J)],of=(Q,J)=>[Q.run(ze(Q,J[0],II()),J)]});function fn(Q){let J;switch(Q.activation){case"Relu":J=au();break;case"Sigmoid":J=su();break;case"Clip":J=iu(Q.clipMin,Q.clipMax);break;default:return{activationFunction:"",applyActivation:""}}let{name:G,body:H}=J,K=`value = ${G}_(value);`;return{activationFunction:H,applyActivation:K}}var wr,rr=$(()=>{xe(),cu(),wr=(Q)=>{let J=Q.getString("activation","");if(J==="Clip"){let[G,H]=Q.getFloats("activation_params",[Yn,er]);return{activation:J,clipMax:H,clipMin:G,activationCacheKey:`${J}:${G},${H}`}}return{activation:J,activationCacheKey:J}}}),PI,OI,af,sf=$(()=>{ct(),De(),pe(),jo(),rr(),PI=(Q,J)=>({name:"GroupedConv",inputNames:Q?["X","W","Bias"]:["X","W"],inputTypes:Q?[0,0,0]:[0,0],cacheHint:J}),OI=(Q,J,G,H)=>{let K=J.length>2?"value += getBias(output_channel);":"",z=J[0].dims.slice(),q=J[1].dims.slice(),F=q[0]/H.group;Te.verbose("GroupedConv",`autpPad:${H.autoPad}, dilations:${H.dilations}, group:${H.group}, kernelShape:${H.kernelShape}, pads:${H.pads}, strides:${H.strides}`);let D=Tr(z,q,H.dilations,H.pads,H.strides),V=j(Q.session.backend.glContext.version),{activationFunction:O,applyActivation:P}=fn(H),N=`
const ivec2 strides = ivec2(${H.strides[0]}, ${H.strides[1]});
const ivec2 pads = ivec2(${H.pads[0]}, ${H.pads[1]});
${O}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int output_channel = coords.y;
ivec2 xRCCorner = coords.zw * strides - pads;
int group_id = output_channel / ${F};
float value = 0.0;
for (int wInChannel = 0; wInChannel < ${q[1]}; wInChannel++) {
int input_channel = group_id * ${q[1]} + wInChannel;
for (int wHeight = 0; wHeight < ${q[2]}; wHeight++) {
int xHeight = xRCCorner.x + wHeight * ${H.dilations[0]};
if (xHeight < 0 || xHeight >= ${z[2]}) {
continue;
}
for (int wWidth = 0; wWidth < ${q[3]}; wWidth++) {
int xWidth = xRCCorner.y + wWidth * ${H.dilations[1]};
if (xWidth < 0 || xWidth >= ${z[3]}) {
continue;
}
float xVal = getX(batch, input_channel, xWidth, xHeight);
float wVal = getW(output_channel, wInChannel, wWidth, wHeight);
value += xVal*wVal;
}
}
}
${K}
${P}
${V.output} = vec4(value, .0, .0, .0);
}
`;return{...G,output:{dims:D,type:J[0].type,textureType:0},shaderSource:N,hasMain:!0}},af=(Q,J,G)=>{let H=PI(J.length>2,G.cacheKey);return{...H,get:()=>OI(Q,J,H,G)}}}),EI,CI,uf,lf=$(()=>{De(),pe(),nr(),EI=(Q)=>({name:"Im2Col (packed)",inputNames:["A"],inputTypes:[2],cacheHint:Q}),CI=(Q,J,G,H,K,z)=>{let q=G.dims,F=H.dims,D=2,V=3,O=K.length,P=[F[1]*F[2]*F[3],K[2]*K[3]],N=F[2]*F[3],I=pn(),R=j(Q.session.backend.glContext.version),w="";for(let T=0;T<=1;T++)for(let y=0;y<=1;y++)w+=`
blockIndex = rc.x + ${y};
pos = rc.y + ${T};
if(blockIndex < ${P[1]} && pos < ${P[0]}) {
offsetY = int(blockIndex / (${K[O-1]})) * ${z.strides[0]} -
${z.pads[0]};
d0 = offsetY + ${z.dilations[0]} * (imod(pos, ${N}) / ${F[2]});
if(d0 < ${q[D]} && d0 >= 0) {
offsetX = imod(blockIndex, ${K[O-1]}) * ${z.strides[1]} -
${z.pads[1]};
d1 = offsetX + ${z.dilations[1]} * imod(imod(pos, ${N}), ${F[2]});
if(d1 < ${q[V]} && d1 >= 0) {
ch = int(float(pos)/ ${N}.);
innerDims = vec2(d0, d1);
result[${T*2+y}] = getChannel(
getA(0, ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
`;let E=`
${I}
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0.0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${w}
${R.output} = result;
}
`;return{...J,output:{dims:P,type:G.type,textureType:2},shaderSource:E,hasMain:!0}},uf=(Q,J,G,H,K)=>{let z=EI(K.cacheKey);return{...z,get:()=>CI(Q,z,J,G,H,K)}}});function kI(Q,J,G){let H=J[0].dims,K=J[1].dims,z=Qe.calcShape(H,K,!0);if(!z)throw Error("Can't use matmul on the given tensors");let q=Ye(z.length),F=$t(),{activationFunction:D,applyActivation:V}=fn(G),O=J.length>2,P=O?"value += getBiasForMatmul();":"",N=O?`${pu(q,F,J[2].dims,z,!1)}`:"",I=z.length,R=H.length,w=K.length,E=H[H.length-1],T=`
${D}
${N}
float process(int indices[${I}]) {
int a[${R}];
int b[${w}];
bcastMatmulIndices_A(indices, a);
bcastMatmulIndices_B(indices, b);
float value;
for (int k=0; k<${E}; ++k) {
a[${R-1}] = k;
b[${w-2}] = k;
value += _A(a) * _B(b);
}
${P}
${V}
return value;
}`;return{...Q,output:{dims:z,type:J[0].type,textureType:0},shaderSource:T}}function du(Q,J){let G=DI(Q.length>2,J.activationCacheKey);return{...G,get:()=>kI(G,Q,J)}}function pu(Q,J,G,H,K){let z="",q=G.length,F=H.length,D=F-q;F<2&&q>0?z="coords":z=G.map((N,I)=>`coords.${J[I+D]}`).join(", ");let V=Qe.getBroadcastDims(G,H).map((N)=>`coords.${J[N+D]} = 0;`).join(`
`),O=U.size(G)===1,P="vec4(outputValue.xx, outputValue.yy)";return O&&(P="vec4(outputValue.x)"),K?`
vec4 getBiasForMatmul() {
${Q} coords = getOutputCoords();
${V}
vec4 outputValue = getBias(${z});
return ${P};
}`:`
float getBiasForMatmul() {
${Q} coords = getOutputCoords();
${V}
return getBias(coords.x);
}`}var cf,df,DI,LI,Ko=$(()=>{xe(),pe(),dn(),rr(),fu(),cf=(Q,J,G)=>(LI(J),Q.session.pack?[Q.run(Xo(Q,J,G),J)]:[Q.run(du(J,G),J)]),df=(Q)=>wr(Q.attributes),DI=(Q,J)=>({name:"MatMul",inputNames:Q?["A","B","Bias"]:["A","B"],inputTypes:Q?[0,0,0]:[0,0],cacheHint:J}),LI=(Q)=>{if(!Q||Q.length!==2)throw Error("MatMul requires 2 inputs.");if(Q[0].dims[Q[0].dims.length-1]!==Q[1].dims[Q[1].dims.length-2])throw Error("shared dimension does not match.");if(Q[0].type!=="float32"&&Q[0].type!=="float64"||Q[1].type!=="float32"&&Q[1].type!=="float64")throw Error("inputs should be float type");if(Q[0].type!==Q[1].type)throw Error("inputs types should match")}});function zI(Q,J,G,H){let K=[],z=[],q=G[0].dims,F=G[1].dims,D=q.length,V=F.length,O=H.length,P=O-D,N=O-V;K=q.map((y,x)=>`coords.${J[x+P]}`),K[D-1]="i*2",K.join(", "),z=F.map((y,x)=>`coords.${J[x+N]}`),z[V-2]="i*2",z.join(", ");let I=Qe.getBroadcastDims(q,H),R=Qe.getBroadcastDims(F,H),w=I.map((y)=>`coords.${J[y+P]} = 0;`).join(`
`),E=R.map((y)=>`coords.${J[y+N]} = 0;`).join(`
`),T=`int lastDim = coords.${J[O-1]};
coords.${J[O-1]} = coords.${J[O-2]};
coords.${J[O-2]} = lastDim;`;return`
vec4 getAAtOutCoordsMatmul(int i) {
${Q} coords = getOutputCoords();
${T}
${w}
vec4 outputValue = getA(${K});
return outputValue;
}
vec4 getBAtOutCoordsMatmul(int i) {
${Q} coords = getOutputCoords();
${T}
${E}
vec4 outputValue = getB(${z});
return outputValue;
}`}function MI(Q,J){let G="";for(let H=0;H<J-2;H++)G+=`rc.${Q[H]}, `;return G+=`rc.${Q[J-2]}, i*2`,G}function BI(Q,J){let G="";for(let H=0;H<J-2;H++)G+=`rc.${Q[H]}, `;return G+=`i*2, rc.${Q[J-1]}`,G}var RI,NI,Xo,fu=$(()=>{xe(),De(),pe(),dn(),rr(),Ko(),RI=(Q,J)=>({name:"MatMul (packed)",inputNames:Q?["A","B","Bias"]:["A","B"],inputTypes:Q?[2,2,2]:[2,2],cacheHint:J}),NI=(Q,J,G,H)=>{let K=G.length>2,z=K?"value += getBiasForMatmul();":"",q=G[0].dims,F=G[1].dims,D=Qe.calcShape(q,F,!0),V=!U.areEqual(G[0].dims,G[1].dims);if(!D)throw Error("Can't use matmul on the given tensors");let O=q[q.length-1],P=Math.ceil(O/2),N=q.length,I=F.length,R=j(Q.session.backend.glContext.version),w=Ye(D.length),E=D.length,T=$t(),{activationFunction:y,applyActivation:x}=fn(H),b=K?`${pu(w,T,G[2].dims,D,!0)}`:"",g=V?`${zI(w,T,G,D)}`:"",l=V?"getAAtOutCoordsMatmul(i)":`getA(${MI(T,N)})`,_=V?"getBAtOutCoordsMatmul(i)":`getB(${BI(T,I)})`,a=V?"":`${w} rc =
getOutputCoords(); int lastDim = rc.${T[E-1]}; rc.${T[E-1]} =
rc.${T[E-2]}; rc.${T[E-2]} = lastDim;
`,r=`
${g}
${b}
${y}
void main() {
${a}
vec4 value = vec4(0);
for (int i = 0; i < ${P}; i++) {
vec4 a = ${l};
vec4 b = ${_};
value += (a.rrbb * b.rgrg);
value += (a.ggaa * b.baba);
}
${z}
${x}
${R.output} = value;
}`;return{...J,output:{dims:D,type:G[0].type,textureType:2},shaderSource:r,hasMain:!0}},Xo=(Q,J,G)=>{let H=RI(J.length>2,G.activationCacheKey);return{...H,get:()=>NI(Q,H,J,G)}}}),pf,ff=$(()=>{jo(),lf(),fu(),pf=(Q,J,G)=>{let H=J[0].dims,K=J[1].dims,z=Tr(H,K,G.dilations,G.pads,G.strides),q=Q.run(uf(Q,J[0],J[1],z,G),[J[0]]),F=Q.reshapePacked(J[1],[K[0],K[1]*K[2]*K[3]]),D=J.length===3?[F,q,J[2]]:[F,q],V=Q.run(Xo(Q,D,G),D);return Q.reshapePacked(V,z)}}),FI,VI,hf,hu,mu=$(()=>{pe(),FI=(Q)=>({name:"Im2Col",inputNames:["X"],inputTypes:[0],cacheHint:Q}),VI=(Q,J,G,H,K,z)=>{let q=G.dims,F=H.dims,D=K.length,V=hu(q,F,K,4),O=`
const int XC = ${q[1]};
const int XH = ${q[2]};
const int XW = ${q[3]};
const int KH = ${z.kernelShape[0]};
const int KW = ${z.kernelShape[1]};
const int dilationH = ${z.dilations[0]};
const int dilationW = ${z.dilations[1]};
const int strideH = ${z.strides[0]};
const int strideW = ${z.strides[1]};
const int padH = ${z.pads[0]};
const int padW = ${z.pads[1]};
const int KHKW = KH*KW;
const int XCKHKW = XC * KHKW;
const int outputChannels = 4;
vec4 process(int indices[${D}]) {
int b = indices[0]; // batch size
int oh = indices[1] * strideH - padH; //output height
int ow = indices[2] * strideW - padW; //output width
int p = indices[3] * outputChannels; //patch
vec4 value = vec4(0.0);
for(int i=0; i < outputChannels; ++i) {
if(p < XCKHKW) {
int patchC = p / KHKW;
int patchH = (p - patchC*KHKW) / KW;
int patchW = (p - patchC*KHKW) - patchH * KW;
int xh2 = oh + patchH * dilationH;
int xw2 = ow + patchW * dilationW;
int x[${q.length}];
x[0] = b;
x[1] = patchC;
x[2] = xh2;
x[3] = xw2;
if(xh2 >= 0 &&
xh2 < XH &&
xw2 >= 0 &&
xw2 < XW) {
value[i] = _X(x);
}
}
++p;
}
return value;
}
`;return{...J,output:{dims:V,type:G.type,textureType:4},shaderSource:O}},hf=(Q,J,G,H,K)=>{let z=FI(K.cacheKey);return{...z,get:()=>VI(Q,z,J,G,H,K)}},hu=(Q,J,G,H=4)=>[G[0],G[2],G[3],Math.ceil(Q[1]*J[2]*J[3]/H)]}),GI,UI,mf,gf=$(()=>{xe(),De(),pe(),rr(),mu(),GI=(Q,J)=>({name:"ConvDotProduct",inputNames:Q?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:Q?[0,4,0]:[0,4],cacheKey:J.activationCacheKey}),UI=(Q,J,G,H,K)=>{let z=G[0].dims,q=G[1].dims,F=[q[0],Math.ceil(z[1]*q[2]*q[3]/4)],D=hu(z,q,H),[V,O]=Q.calculateTextureWidthAndHeight(F,4),P=U.computeStrides(D),[N,I]=Q.calculateTextureWidthAndHeight(D,4),R=H.length,w=G.length<3?"0.0":"_B(b)",E=Math.ceil(z[1]*q[2]*q[3]/4),{activationFunction:T,applyActivation:y}=fn(K),x=j(Q.session.backend.glContext.version),b=`
${T}
float process(int indices[${R}]) {
int b[1];
b[0] = indices[1];
int im2col[4];
im2col[0] = indices[0];
im2col[1] = indices[2];
im2col[2] = indices[3];
int im2colOffset = im2col[0] * ${P[0]} + im2col[1] * ${P[1]} + im2col[2] * ${P[2]};
int kernelOffset = indices[1] * ${F[1]};
float value = ${w};
for (int i = 0; i < ${E}; ++i) {
vec2 im2colCoords = offsetToCoords(im2colOffset, ${N}, ${I});
vec2 kernelCoords = offsetToCoords(kernelOffset, ${V}, ${O});
value += dot(${x.texture2D}(Im2Col, im2colCoords), ${x.texture2D}(K, kernelCoords));
++im2colOffset;
++kernelOffset;
}
${y}
return value;
}`;return{...J,output:{dims:H,type:G[0].type,textureType:0},shaderSource:b}},mf=(Q,J,G,H)=>{let K=GI(J.length>2,H);return{...K,get:()=>UI(Q,K,J,G,H)}}}),Tr,gu,WI,HI,qI,jI,bu,KI,jo=$(()=>{We(),xe(),sf(),ff(),gf(),rr(),mu(),Ko(),Tr=(Q,J,G,H,K)=>{let z=Q[0],q=Q.slice(2),F=q.length,D=J[0],V=J.slice(2).map((P,N)=>P+(P-1)*(G[N]-1)),O=q.map((P,N)=>P+H[N]+H[N+F]).map((P,N)=>Math.floor((P-V[N]+K[N])/K[N]));return[z,D].concat(...O)},gu=(Q,J,G)=>(KI(J,G),WI(Q,J,G)),WI=(Q,J,G)=>{let H=jI(G,J),K=Q.session.pack,z=H.kernelShape[0]===1&&H.kernelShape[1]===1;return H.group>1?[Q.run(af(Q,J,H),J)]:z&&K?[HI(Q,J,H)]:K&&J[0].dims.length===4&&J[0].dims[0]===1&&!z?[pf(Q,J,H)]:[qI(Q,J,H)]},HI=(Q,J,G)=>{let H=J[0].dims,K=J[1].dims,z=Tr(H,K,G.dilations,G.pads,G.strides),q=Q.reshapeUnpacked(J[0],[H[1],H[2]*H[3]]),F=Q.reshapeUnpacked(J[1],[K[0],K[1]]),D=J.length>2?[F,q,J[2]]:[F,q],V=Q.run(du(D,G),D);return Q.reshapeUnpacked(V,z)},qI=(Q,J,G)=>{let H=J[0].dims,K=J[1].dims,z=Tr(H,K,G.dilations,G.pads,G.strides),q=Q.run(hf(Q,J[0],J[1],z,G),[J[0]]),F=J.length===3?[q,J[1],J[2]]:[q,J[1]];return Q.run(mf(Q,J,z,G),F)},jI=(Q,J)=>{let G=Q.kernelShape.slice();if(Q.kernelShape.length===0)for(let z=2;z<J[1].dims.length;++z)G.push(J[1].dims[z]);let H=Q.pads.slice();Qn.adjustPadsBasedOnAutoPad(J[0].dims,Q.strides,Q.dilations,G,H,Q.autoPad);let K=Object.assign({},Q);return Object.assign(K,{kernelShape:G,pads:H,cacheKey:Q.cacheKey}),K},bu=(Q)=>{let J=Q.attributes,G=wr(J),H=J.getString("auto_pad","NOTSET"),K=J.getInts("dilations",[1,1]),z=J.getInt("group",1),q=J.getInts("kernel_shape",[]),F=J.getInts("pads",[0,0,0,0]),D=J.getInts("strides",[1,1]);return se({autoPad:H,dilations:K,group:z,kernelShape:q,pads:F,strides:D,...G})},KI=(Q,J)=>{if(!Q||Q.length!==2&&Q.length!==3)throw Error("Conv requires 2 or 3 inputs");if(Q[0].dims.length!==4||Q[1].dims.length!==4)throw Error("currently only support 2-dimensional conv");let G=Q[0].dims[1],H=Q[1].dims[1]*J.group;if(G!==H)throw Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(Q.length===3&&(Q[2].dims.length!==1||Q[1].dims[0]!==Q[2].dims[0]))throw Error("invalid bias");let K=Q[0].dims.length-2;if(J.dilations.length!==K)throw Error(`dilations should be ${K}D`);if(J.strides.length!==K)throw Error(`strides should be ${K}D`);if(J.pads.length!==K*2)throw Error(`pads should be ${K*2}D`);if(J.kernelShape.length!==0&&J.kernelShape.length!==Q[1].dims.length-2)throw Error("invalid kernel shape");if(Q[0].type!=="float32"||Q[1].type!=="float32")throw Error("Conv input(X,W) should be float tensor");if(Q.length===3&&Q[2].type!=="float32")throw Error("Conv input(bias) should be float tensor")}}),XI,ZI,JI,bf,QI,YI,e2,t2,n2,r2,yf,o2,_f=$(()=>{We(),De(),pe(),rr(),XI=(Q,J,G,H,K,z)=>(Q-1)*J+G+(H-1)*K+1-z,ZI=(Q,J,G,H,K)=>{let z=Math.floor(Q/2);J==="SAME_UPPER"?(G[H]=z,G[K]=Q-z):J==="SAME_LOWER"&&(G[H]=Q-z,G[K]=z)},JI=(Q,J,G,H,K,z,q,F)=>{let D=Q.length-2,V=F.length===0;for(let O=0;O<D;++O){let P=V?Q[O+2]*z[O]:F[O],N=XI(Q[O+2],z[O],K[O],J[O],G[O],P);ZI(N,H,K,O,O+D),V&&F.push(z[O]*(Q[O+2]-1)+q[O]+(J[O]-1)*G[O]+1-K[O]-K[O+D])}},bf=(Q,J,G)=>(o2(J,G),QI(Q,J,G)),QI=(Q,J,G)=>{let H=r2(G,J);return[n2(Q,J,H)]},YI=(Q,J)=>({name:"ConvTranspose",inputNames:Q?["X","W","B"]:["X","W"],inputTypes:Q?[0,0,0]:[0,0],cacheHint:J}),e2=(Q,J,G,H)=>{let K=J.length>2?"getB(output_channel)":"0.0",z=J[0].dims,q=J[1].dims,F=q[1],D=q[0]/H.group,V=[J[0].dims[0],J[1].dims[1]*H.group,...H.outputShape],O=j(Q.session.backend.glContext.version),{activationFunction:P,applyActivation:N}=fn(H),I=`
const ivec2 strides = ivec2(${H.strides[0]}, ${H.strides[1]});
const ivec2 pads = ivec2(${H.pads[0]}, ${H.pads[1]});
${P}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
int output_channel = coords.y;
ivec2 loc = coords.zw + pads;
int group_id = output_channel / ${F};
int wOutChannel = output_channel - group_id * ${F};
float value = ${K};
for (int inChannelOffset = 0; inChannelOffset < ${D}; inChannelOffset++) {
int input_channel = group_id * ${D} + inChannelOffset;
for (int wWOff = 0; wWOff < ${q[2]}; wWOff++) {
for (int wHOff = 0; wHOff < ${q[3]}; wHOff++) {
ivec2 wOff = ivec2(wWOff * ${H.dilations[0]}, wHOff * ${H.dilations[1]});
ivec2 wLoc = loc - wOff;
ivec2 wLocIn = wLoc / strides;
if (
wLocIn * strides == wLoc &&
wLocIn.x >= 0 && wLocIn.x < ${z[2]} &&
wLocIn.y >= 0 && wLocIn.y < ${z[3]}
) {
float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);
float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);
value += xVal * wVal;
}
}
}
}
${N}
${O.output} = vec4(value, .0, .0, .0);
}
`;return{...G,output:{dims:V,type:J[0].type,textureType:0},shaderSource:I,hasMain:!0}},t2=(Q,J,G)=>{let H=YI(J.length>2,G.cacheKey);return{...H,get:()=>e2(Q,J,H,G)}},n2=(Q,J,G)=>Q.run(t2(Q,J,G),J),r2=(Q,J)=>{let G=Q.kernelShape.slice();if(Q.kernelShape.length===0)for(let F=2;F<J[1].dims.length;++F)G.push(J[1].dims[F]);let H=Q.pads.slice(),K=Q.outputShape.slice(),z=J[0].dims;JI(z,G,Q.dilations,Q.autoPad,H,Q.strides,Q.outputPadding,K);let q=Object.assign({},Q);return Object.assign(q,{kernelShape:G,pads:H,outputShape:K,cacheKey:Q.cacheKey}),q},yf=(Q)=>{let J=Q.attributes,G=wr(J),H=J.getString("auto_pad","NOTSET"),K=J.getInts("dilations",[1,1]),z=J.getInt("group",1),q=J.getInts("kernel_shape",[]),F=J.getInts("output_padding",[0,0]),D=J.getInts("output_shape",[]),V=J.getInts("pads",[0,0,0,0]),O=J.getInts("strides",[1,1]);return se({autoPad:H,dilations:K,group:z,kernelShape:q,outputPadding:F,outputShape:D,pads:V,strides:O,...G})},o2=(Q,J)=>{if(!Q||Q.length!==2&&Q.length!==3)throw Error("Conv requires 2 or 3 inputs");if(Q[0].dims.length!==4||Q[1].dims.length!==4)throw Error("currently only support 2-dimensional conv");let G=Q[0].dims[1],H=Q[1].dims[0];if(G!==H)throw Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let K=Q[1].dims[1]*J.group;if(Q.length===3&&(Q[2].dims.length!==1||Q[2].dims[0]!==K))throw Error("invalid bias");let z=Q[0].dims.length-2;if(J.dilations.length!==z)throw Error(`dilations should be ${z}D`);if(J.strides.length!==z)throw Error(`strides should be ${z}D`);if(J.pads.length!==z*2)throw Error(`pads should be ${z*2}D`);if(J.outputPadding.length!==z)throw Error(`output_padding should be ${z}D`);if(J.kernelShape.length!==0&&J.kernelShape.length!==Q[1].dims.length-2)throw Error("invalid kernel shape");if(J.outputShape.length!==0&&J.outputShape.length!==Q[0].dims.length-2)throw Error("invalid output shape");if(Q[0].type!=="float32"||Q[1].type!=="float32")throw Error("ConvTranspose input(X,W) should be float tensor");if(Q.length===3&&Q[2].type!=="float32")throw Error("ConvTranspose input(bias) should be float tensor")}}),xf,or,wf,i2,Tf,a2,s2,u2,Zo=$(()=>{We(),xe(),pe(),xf={name:"Transpose",inputNames:["A"],inputTypes:[0]},or=(Q,J,G)=>(u2(J),[Q.run({...xf,cacheHint:G.cacheKey,get:()=>i2(Q,J[0],G.perm)},J)]),wf=(Q)=>se({perm:Q.attributes.getInts("perm",[])}),i2=(Q,J,G)=>{let H=J.dims;G=Tf(H,G);let K=a2(H,G),z=H.length,q=`
${s2("perm",G,z)}
float process(int indices[${z}]) {
int a[${z}];
perm(a, indices);
return _A(a);
}`;return{...xf,output:{dims:K,type:J.type,textureType:0},shaderSource:q}},Tf=(Q,J)=>(J&&J.length!==Q.length&&(J=[...Q.keys()].reverse()),J),a2=(Q,J)=>(J=Tf(Q,J),U.sortBasedOnPerm(Q,J)),s2=(Q,J,G)=>{let H=[];H.push(`void ${Q}(out int a[${G}], int src[${G}]) {`);for(let K=0;K<G;++K)H.push(` a[${J[K]}]=src[${K}];`);return H.push("\t}"),H.join(`
`)},u2=(Q)=>{if(!Q||Q.length!==1)throw Error("Transpose requires 1 input.");if(Q[0].type!=="float32"&&Q[0].type!=="float64")throw Error("input should be float tensor")}}),vf,If,l2,Sf=$(()=>{Zo(),vf=(Q,J,G)=>{l2(J);let H=G.blocksize,K=H*H,z=G.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],q=G.mode==="DCR"?[J[0].dims[0],H,H,J[0].dims[1]/K,J[0].dims[2],J[0].dims[3]]:[J[0].dims[0],J[0].dims[1]/K,H,H,J[0].dims[2],J[0].dims[3]],F=Q.reshapeUnpacked(J[0],q),D={perm:z,cacheKey:`${z}`},[V]=or(Q,[F],D),O=[J[0].dims[0],J[0].dims[1]/K,J[0].dims[2]*H,J[0].dims[3]*H];return[Q.reshapeUnpacked(V,O)]},If=(Q)=>{let J=Q.attributes.getInt("blocksize");if(J<1)throw Error(`blocksize must be >= 1, but got : ${J} for DepthToSpace`);let G=Q.attributes.getString("mode","DCR");if(G!=="DCR"&&G!=="CRD")throw Error(`unrecognized mode: ${G} for DepthToSpace`);return{mode:G,blocksize:J}},l2=(Q)=>{if(Q.length!==1)throw Error(`DepthToSpace expect 1 inputs, but got ${Q.length}`);if(Q[0].type==="string"||Q[0].dims.length!==4)throw TypeError("DepthToSpace input should be a 4-D numeric tensor")}}),$f,Af,c2,Pf=$(()=>{xe(),$f=(Q,J,G)=>{c2(J,G);let H=U.flattenShape(J[0].dims,G);return[Q.reshapeUnpacked(J[0],H)]},Af=(Q)=>Q.attributes.getInt("axis",1),c2=(Q,J)=>{if(!Q||Q.length!==1)throw Error("Flatten requires 1 input.");let G=Q[0].dims.length;if(G===0)throw Error("scalar tensor is not supported.");if(J<-G||J>G)throw Error("Invalid axis");if(Q[0].type==="string")throw Error("string tensor is not supported.")}}),zn,Xr=$(()=>{zn=["float32","float64","int32","int16","int8","uint16","uint32","uint8"]}),Of,Ef,d2,p2,f2,h2,Cf=$(()=>{We(),Xr(),xe(),pe(),Of=(Q,J,G)=>(h2(J,G.axis),[Q.run(f2(Q,J,G),J)]),Ef=(Q)=>se({axis:Q.attributes.getInt("axis",0)}),d2={name:"Gather",inputNames:["A","B"],inputTypes:[0,0]},p2=(Q,J,G,H)=>{let K=G[0].dims.slice(),z=G[1].dims.slice(),q=Array(K.length+z.length-1);H=U.normalizeAxis(H,K.length);let F=[];for(let N=0;N<q.length;N++)N<H?(q[N]=K[N],F.push(`inputIdx[${N}] = outputIdx[${N}];`)):N<H+z.length?(q[N]=z[N-H],F.push(`indexDataIdx[${N-H}] = outputIdx[${N}];`)):(q[N]=K[N-z.length+1],F.push(`inputIdx[${N-z.length+1}] = outputIdx[${N}];`));let D=q.length||1,V=K.length,O=z.length||1,P=`
float process(int outputIdx[${D}]) {
int inputIdx[${V}];
int indexDataIdx[${O}];
indexDataIdx[0] = 0;
${F.join(`
`)}
int idx = int(_B(indexDataIdx));
inputIdx[${H}] = idx < 0 ? idx + ${K[H]} : idx;
return _A(inputIdx);
}`;return{...J,output:{dims:q,type:G[0].type,textureType:0},shaderSource:P}},f2=(Q,J,G)=>{let H={...d2,cacheHint:G.cacheKey};return{...H,get:()=>p2(Q,H,J,G.axis)}},h2=(Q,J)=>{if(!Q||Q.length!==2)throw Error("Gather requires 2 inputs.");let G=Q[0].dims.length;if(G<1)throw Error("Invalid input shape.");if(J<-G||J>G-1)throw Error("Invalid axis.");if(zn.indexOf(Q[0].type)===-1)throw Error("Invaid input type.");if(Q[1].type!=="int32"&&Q[1].type!=="int16")throw Error("Invaid input type.")}}),yu,Df,kf,Lf,m2,g2,b2,Rf=$(()=>{We(),xe(),pe(),yu=(Q,J,G)=>(b2(J,G),[Q.run(m2(J,G),J)]),Df=(Q,J)=>{let G=Q.attributes.getInt("transA",0)!==0,H=Q.attributes.getInt("transB",0)!==0,K=Q.attributes.getFloat("alpha",1),z=Q.attributes.getFloat("beta",1);return se({transA:G,transB:H,alpha:K,beta:z,isOptionalC:J})},kf=(Q)=>Df(Q,!1),Lf=(Q)=>Df(Q,!0),m2=(Q,J)=>{let G={name:"Gemm",inputNames:Q.length===3?["A","B","C"]:["A","B"],inputTypes:Q.length===3?[0,0,0]:[0,0],key:J.cacheKey};return{...G,get:()=>g2(G,Q,J)}},g2=(Q,J,G)=>{let H=J[0].dims.slice(),K=J[1].dims.slice(),[z,q]=Bo.getShapeOfGemmResult(H,G.transA,K,G.transB,J.length===3?J[2].dims:void 0),F=[z,q];if(!F)throw Error("Can't use gemm on the given tensors");let D=H[H.length-1],V="";G.transA&&(D=H[0]),G.transA&&G.transB?V="value += _A_T(a) * _B_T(b);":G.transA&&!G.transB?V="value += _A_T(a) * _B(b);":!G.transA&&G.transB?V="value += _A(a) * _B_T(b);":!G.transA&&!G.transB&&(V="value += _A(a) * _B(b);");let O=F.length,P=J.length===3?`int c[${J[2].dims.length}];`:"",N=J.length===3?"bcastIndices_C(indices, c);":"",I=J.length===3?"value += beta * _C(c);":"",R=`
float process(int indices[${O}]) {
int a[${O}];
int b[${O}];
${P}
copyVec(indices, a);
copyVec(indices, b);
${N}
float value = 0.0;
for (int k=0; k<${D}; ++k) {
a[${O-1}] = k;
b[${O-2}] = k;
${V}
}
value = value * alpha;
${I}
return value;
}`;return{...Q,output:{dims:F,type:J[0].type,textureType:0},variables:[{name:"alpha",type:"float",data:G.alpha},{name:"beta",type:"float",data:G.beta}],shaderSource:R}},b2=(Q,J)=>{if(!Q)throw Error("Input is missing");if(J.isOptionalC&&(Q.length<2||Q.length>3))throw Error("Invaid input shape.");if(!J.isOptionalC&&Q.length!==3)throw Error("Gemm requires 3 inputs");if(Q.length===3&&Q[2].dims.length!==1&&Q[2].dims.length!==2)throw Error("Invalid input shape of C");if(Q[0].type!=="float32"&&Q[0].type!=="float64"||Q[1].type!=="float32"&&Q[1].type!=="float64"||Q.length===3&&Q[2].type!=="float32"&&Q[2].type!=="float64")throw Error("Invalid input type.");if(Q[0].type!==Q[1].type||Q.length===3&&Q[0].type!==Q[2].type)throw Error("Input types are mismatched")}}),Nf,zf,y2,_2,x2,w2,T2,Mf=$(()=>{We(),pe(),Nf=(Q,J,G)=>(T2(J),[Q.run(x2(Q,J,G),J)]),zf=(Q)=>{let J=Q.attributes.getFloat("scale"),G=Q.attributes.getFloats("bias");return se({scale:J,bias:G})},y2={name:"ImageScaler",inputNames:["X"],inputTypes:[0]},_2=(Q,J,G,H)=>{let K=G[0].dims.slice(),z=K.length,q=`
${w2(H.bias.length)}
float process(int indices[${z}]) {
return _X(indices) * scale + getBias(bias, indices[1]);
}`;return{...J,output:{dims:K,type:G[0].type,textureType:0},variables:[{name:"bias",type:"float",arrayLength:H.bias.length,data:H.bias},{name:"scale",type:"float",data:H.scale}],shaderSource:q}},x2=(Q,J,G)=>{let H={...y2,cacheHint:G.cacheKey};return{...H,get:()=>_2(Q,H,J,G)}},w2=(Q)=>{let J=[`float getBias(float bias[${Q}], int channel) {`];for(let G=0;G<Q;++G)G===0?J.push(` if (channel == ${G}) { return bias[${G}]; }`):G===Q-1?J.push(` else { return bias[${G}]; }`):J.push(` else if (channel == ${G}) { return bias[${G}]; }`);return J.push("\t}"),J.join(`
`)},T2=(Q)=>{if(!Q||Q.length!==1)throw Error("ImageScaler requires 1 input.");if(Q[0].dims.length!==4)throw Error("Invalid input shape.");if(Q[0].type!=="float32"&&Q[0].type!=="float64")throw Error("Invalid input type.")}}),Ff,Vf,Bf,v2,I2,S2,$2,A2,P2,Gf=$(()=>{De(),pe(),Ff=(Q,J,G)=>{P2(J);let H=Q.run(I2(J[0]),J);return[Q.run(A2(Q,J[0],G,H.dims),[J[0],H,J[1],J[2]])]},Vf=(Q)=>Q.attributes.getFloat("epsilon",0.00001),Bf={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[0]},v2=(Q,J)=>{let G=J.dims.slice(),H=G[1],K=G[2]*G[3],z=[G[0],H],q=`
vec4 process(int[2] indices) {
vec4 v = vec4(0.0);
int a[4];
a[0] = indices[0];
a[1] = indices[1];
float temp = 0.0;
for(int a2=0; a2<${G[2]}; a2++) {
a[2] = a2;
for(int a3=0; a3<${G[3]}; a3++) {
a[3] = a3;
float x = _X(a);
temp += x;
}
}
float mean = temp / float(${K});
temp = 0.0;
for(int a2=0; a2<${G[2]}; a2++) {
a[2] = a2;
for(int a3=0; a3<${G[3]}; a3++) {
a[3] = a3;
float x = _X(a);
temp += (x - mean) * (x - mean);
}
}
v.r = mean;
v.g = temp / float(${K});
return v;
}`;return{...Q,output:{dims:z,type:J.type,textureType:4},shaderSource:q}},I2=(Q)=>({...Bf,get:()=>v2(Bf,Q)}),S2={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[0,4,0,0]},$2=(Q,J,G,H,K)=>{let z=j(Q.session.backend.glContext.version),[q,F]=Q.calculateTextureWidthAndHeight(K,4),[D,V]=[q/4,F],O=`
vec4 get_MeanAndVariance(int[2] mv) {
int offset = indicesToOffset_MeanAndVariance(mv);
vec2 coords = offsetToCoords(offset, ${D}, ${V});
return ${z.texture2D}(MeanAndVariance, coords);
}
float process(int[4] indices) {
int mv[2];
mv[0] = indices[0];
mv[1] = indices[1];
vec4 mean_and_variance = get_MeanAndVariance(mv);
float mean = mean_and_variance.r;
float variance = mean_and_variance.g;
int sb[1];
sb[0] = indices[1];
float scale = _Scale(sb);
float b = _B(sb);
return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;
}`;return{...J,output:{dims:G.dims,type:G.type,textureType:0},variables:[{name:"epsilon",type:"float",data:H}],shaderSource:O}},A2=(Q,J,G,H)=>{let K={...S2,cacheHint:`${G}`};return{...K,get:()=>$2(Q,K,J,G,H)}},P2=(Q)=>{if(!Q||Q.length!==3)throw Error("InstanceNormalization requires 3 inputs.");let J=Q[0],G=Q[1],H=Q[2];if(J.dims.length<3||G.dims.length!==1||H.dims.length!==1)throw Error("Invalid input shape.");if(G.dims[0]!==J.dims[1]||H.dims[0]!==J.dims[1])throw Error("Input shapes are mismatched.");if(J.type!=="float32"&&J.type!=="float64"||G.type!=="float32"&&G.type!=="float64"||H.type!=="float32"&&H.type!=="float64")throw Error("Invalid input type.");if(Q[0].dims.length!==4)throw Error("Only support 4-D input shape.")}});function O2(Q,J){let G=Q[0].dims[1],H=Q[0].dims.length,K=-Math.floor((J.size-1)/2),z=Math.ceil((J.size-1)/2),q=`float(${J.alpha}) / float(${J.size})`,F=`float(${J.bias})`,D=`float(${J.beta})`,V=`
float process(int indices[${H}]) {
int c = indices[1];
float x = _X(indices);
float square_sum = 0.0;
for (int i = ${K}; i <= ${z}; i++) {
int idx = c + i;
if (c >= 0 && c < ${G}) {
indices[1] = idx;
float j = _X(indices);
square_sum += j * j;
}
}
return x / pow(${F} + ${q} * square_sum, ${D});
}`;return{...Hf,cacheHint:J.cacheKey,output:{dims:Q[0].dims,type:Q[0].type,textureType:0},shaderSource:V}}function E2(Q,J){return{...Hf,cacheHint:J.cacheKey,get:()=>O2(Q,J)}}var Uf,Wf,Hf,C2,qf=$(()=>{We(),pe(),Uf=(Q,J,G)=>(C2(J),[Q.run(E2(J,G),J)]),Wf=(Q)=>{let J=Q.attributes.getFloat("alpha",0.0001),G=Q.attributes.getFloat("beta",0.75),H=Q.attributes.getFloat("bias",1),K=Q.attributes.getInt("size");return se({alpha:J,beta:G,bias:H,size:K})},Hf={name:"LRN",inputNames:["X"],inputTypes:[0]},C2=(Q)=>{if(!Q||Q.length!==1)throw Error("LRN requires 1 input.");if(Q[0].dims.length!==4)throw Error('currently only support LRN for input with "NCHW" format');if(Q[0].type!=="float32")throw Error("input should be float type")}}),D2,_u,jf,Kf,Xf,k2,L2,R2,N2,z2,M2,B2,F2,Zf=$(()=>{We(),xe(),De(),pe(),D2={name:"Pad",inputNames:["A"],inputTypes:[0]},_u=(Q,J,G)=>(R2(J),[Q.run({...D2,cacheHint:G.cacheKey,get:()=>L2(Q,J[0],G)},J)]),jf=(Q)=>{let J=Q.attributes.getString("mode","constant"),G=Q.attributes.getFloat("value",0),H=Q.attributes.getInts("pads");return se({mode:J,value:G,pads:H})},Kf=(Q,J,G)=>{N2(J);let H=k2(Q,J,G);return _u(Q,[J[0]],H)},Xf=(Q)=>Q.attributes.getString("mode","constant"),k2=(Q,J,G)=>{if(!Q.session.isInitializer(J[1].dataId)||J.length>=3&&!Q.session.isInitializer(J[2].dataId))throw Error("dynamic pad attributes are not allowed");let H=Array.from(J[1].integerData),K=J.length>=3?J[2].floatData[0]:0;return se({mode:G,pads:H,value:K})},L2=(Q,J,G)=>{let H=U.padShape(J.dims.slice(),G.pads),K=H.length,z=`
${z2(Q,J,G)}
float process(int[${K}] indices) {
return padA(indices);
}`;return{name:"Pad",inputNames:["A"],inputTypes:[0],output:{dims:H,type:J.type,textureType:0},shaderSource:z}},R2=(Q)=>{if(!Q||Q.length!==1)throw Error("Pad requires 1 input");if(Q[0].type!=="float32"&&Q[0].type!=="float64")throw Error("Invalid input type.")},N2=(Q)=>{if(!Q||Q.length!==2&&Q.length!==3)throw Error("Pad requires 2 or 3 inputs");if(Q[1].type!=="int32")throw Error("Invalid input type.");if(Q.length>=3&&Q[2].type==="string")throw Error("Invalid input type.")},z2=(Q,J,G)=>{let H=j(Q.session.backend.glContext.version),[K,z]=Q.calculateTextureWidthAndHeight(J.dims,0),q=U.computeStrides(J.dims);switch(G.mode){case"constant":return M2(H,J.dims,q,K,z,G.pads,G.value);case"reflect":return B2(H,J.dims,q,K,z,G.pads);case"edge":return F2(H,J.dims,q,K,z,G.pads);default:throw Error("Invalid mode")}},M2=(Q,J,G,H,K,z,q)=>{let F=J.length,D="";for(let V=F-1;V>=0;--V)D+=`
k = m[${V}] - ${z[V]};
if (k < 0) return constant;
if (k >= ${J[V]}) return constant;
offset += k * ${G[V]};
`;return`
float padA(int m[${F}]) {
const float constant = float(${q});
int offset = 0;
int k = 0;
${D}
vec2 coords = offsetToCoords(offset, ${H}, ${K});
float value = getColorAsFloat(${Q.texture2D}(A, coords));
return value;
}
`},B2=(Q,J,G,H,K,z)=>{let q=J.length,F="";for(let D=q-1;D>=0;--D)F+=`
k = m[${D}] - ${z[D]};
if (k < 0) { k = -k; }
{
const int _2n_1 = ${2*(J[D]-1)};
k = int( mod( float(k), float(_2n_1) ) ) ;
if(k >= ${J[D]}) { k = _2n_1 - k; }
}
offset += k * ${G[D]};
`;return`
float padA(int m[${q}]) {
int offset = 0;
int k = 0;
${F}
vec2 coords = offsetToCoords(offset, ${H}, ${K});
float value = getColorAsFloat(${Q.texture2D}(A, coords));
return value;
}
`},F2=(Q,J,G,H,K,z)=>{let q=J.length,F="";for(let D=q-1;D>=0;--D)F+=`
k = m[${D}] - ${z[D]};
if (k < 0) k = 0;
if (k >= ${J[D]}) k = ${J[D]-1};
offset += k * ${G[D]};
`;return`
float padA(int m[${q}]) {
int offset = 0;
int k = 0;
${F}
vec2 coords = offsetToCoords(offset, ${H}, ${K});
float value = getColorAsFloat(${Q.texture2D}(A, coords));
return value;
}
`}}),Qf,Yf,eh,th,nh,rh,oh,ih,ah,V2,Jf,sh,Qo,uh,Jo,G2,lh=$(()=>{We(),xe(),pe(),Qf=(Q,J,G)=>{Qo(J);let H={name:"AveragePool",inputNames:["X"],inputTypes:[0],cacheHint:G.cacheKey};return[Q.run({...H,get:()=>eh(J,H,!1,G)},J)]},Yf=(Q)=>{let J=Q.attributes.getString("auto_pad","NOTSET"),G=Q.attributes.getInt("ceil_mode",0),H=Q.attributes.getInt("count_include_pad",0)!==0,K=Q.attributes.getInts("kernel_shape"),z=Q.attributes.getInts("strides",[]),q=Q.attributes.getInts("pads",[]);if(G!==0)throw Error("using ceil() in shape computation is not yet supported for AveragePool");return se({autoPad:J,ceilMode:G,countIncludePad:H,kernelShape:K,strides:z,pads:q})},eh=(Q,J,G,H)=>{let[K,z]=ah(Q,H,G),q=U.size(K.kernelShape),F="value += _X(x);",D="";K.countIncludePad?D+=`value /= float(${q});`:D+=`value /= float(${q} - pad);`;let V=`
${uh(Q[0].dims,K,F,D,"0.0")}
`;return{...J,output:{dims:z,type:Q[0].type,textureType:0},shaderSource:V}},th=(Q,J,G)=>{Qo(J);let H={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[0],cacheHint:`${G.countIncludePad}`};return[Q.run({...H,get:()=>eh(J,H,!0,G)},J)]},nh=(Q)=>{let J=Q.attributes.getInt("count_include_pad",0)!==0;return se({autoPad:"",ceilMode:0,countIncludePad:J,kernelShape:[],strides:[],pads:[]})},rh=(Q,J,G)=>{Qo(J);let H={name:"MaxPool",inputNames:["X"],inputTypes:[0],cacheHint:G.cacheKey};return[Q.run({...H,get:()=>ih(J,H,!1,G)},J)]},oh=(Q)=>{let J=Q.attributes.getString("auto_pad","NOTSET"),G=Q.attributes.getInt("ceil_mode",0),H=Q.attributes.getInts("kernel_shape"),K=Q.attributes.getInts("strides",[]),z=Q.attributes.getInts("pads",[]),q=Q.attributes.getInt("storage_order",0),F=Q.attributes.getInts("dilations",[]);if(q!==0)throw Error("column major storage order is not yet supported for MaxPool");if(G!==0)throw Error("using ceil() in shape computation is not yet supported for MaxPool");return se({autoPad:J,ceilMode:G,countIncludePad:!1,kernelShape:H,strides:K,pads:z,storageOrder:q,dilations:F})},ih=(Q,J,G,H)=>{let[K,z]=ah(Q,H,G),q=`
${uh(Q[0].dims,K,`
value = max(_X(x), value);
`,"","-1e5")}
`;return{...J,output:{dims:z,type:Q[0].type,textureType:0},shaderSource:q}},ah=(Q,J,G)=>{let H=Q[0].dims.slice(),K=Object.hasOwnProperty.call(J,"dilations"),z=J.kernelShape.slice(),q=J.strides.slice(),F=K?J.dilations.slice():[],D=J.pads.slice();Qn.adjustPoolAttributes(G,H,z,q,F,D);let V=Qn.computePoolOutputShape(G,H,q,F,z,D,J.autoPad),O=Object.assign({},J);return K?Object.assign(O,{kernelShape:z,strides:q,pads:D,dilations:F,cacheKey:J.cacheKey}):Object.assign(O,{kernelShape:z,strides:q,pads:D,cacheKey:J.cacheKey}),[O,V]},V2={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},Jf={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[0]},sh=(Q,J)=>(Qo(J),[Q.run({...Jf,get:()=>ih(J,Jf,!0,V2)},J)]),Qo=(Q)=>{if(!Q||Q.length!==1)throw Error("Pool ops requires 1 input.");if(Q[0].type!=="float32"&&Q[0].type!=="float64")throw Error("Invalid input type.")},uh=(Q,J,G,H,K)=>{let z=Q.length;if(J.kernelShape.length<=2){let q=J.kernelShape[J.kernelShape.length-1],F=J.strides[J.strides.length-1],D=J.pads[J.pads.length/2-1],V=J.pads[J.pads.length-1],O=Q[z-1],P="",N="",I="";if(D+V!==0?P=`
for (int i = 0; i < ${q}; i++) {
x[${z} - 1] = indices[${z} - 1] * ${F} - ${D} + i;
if (x[${z} - 1] < 0 || x[${z} - 1] >= ${O}) {
pad++;
continue;
}
${G}
}`:P=`
for (int i = 0; i < ${q}; i++) {
x[${z} - 1] = indices[${z} - 1] * ${F} - ${D} + i;
${G}
}`,J.kernelShape.length===2){let R=J.kernelShape[J.kernelShape.length-2],w=J.strides[J.strides.length-2],E=J.pads[J.pads.length/2-2],T=J.pads[J.pads.length-2],y=Q[z-2];E+T!==0?N=`
for (int j = 0; j < ${R}; j++) {
x[${z} - 2] = indices[${z} - 2] * ${w} - ${E} + j;
if (x[${z} - 2] < 0 || x[${z} - 2] >= ${y}) {
pad+= ${q};
continue;
}
`:N=`
for (int j = 0; j < ${R}; j++) {
x[${z} - 2] = indices[${z} - 2] * ${w} - ${E} + j;
`,I=`
}
`}return`
float process(int indices[${z}]) {
int x[${z}];
copyVec(indices, x);
float value = ${K};
int pad = 0;
${N}
${P}
${I}
${H}
return value;
}
`}else{let q=U.size(J.kernelShape),F=U.computeStrides(J.kernelShape),D=F.length,V=J.pads.length,O=G2(D),P=Jo(Q,"inputDims"),N=Jo(J.pads,"pads"),I=Jo(F,"kernelStrides"),R=Jo(J.strides,"strides"),w=J.pads.reduce((T,y)=>T+y),E="";return w?E=`
if (x[j] >= inputDims[j] || x[j] < 0) {
pad++;
isPad = true;
break;
}
}
if (!isPad) {
${G}
}`:E=`
}
${G}
`,`
${O}
float process(int indices[${z}]) {
int x[${z}];
copyVec(indices, x);
int offset[${D}];
int pads[${V}];
int inputDims[${z}];
int kernelStrides[${D}];
int strides[${D}];
${N}
${P}
${R}
${I}
float value = ${K};
int pad = 0;
bool isPad = false;
for (int i = 0; i < ${q}; i++) {
offsetToIndices(i, kernelStrides, offset);
isPad = false;
for (int j = ${z} - ${D}; j < ${z}; j++) {
x[j] = indices[j] * strides[j - ${z} + ${D}]
+ offset[j - ${z} + ${D}] - pads[j - 2];
${E}
}
${H}
return value;
}
`}},Jo=(Q,J)=>{let G="";for(let H=0;H<Q.length;H++)G+=`
${J}[${H}] = ${Q[H]};
`;return G},G2=(Q)=>`
void offsetToIndices(int offset, int[${Q}] strides, out int[${Q}] indices) {
if (${Q} == 0) {
return;
}
for (int i = 0; i < ${Q} - 1; ++i) {
indices[i] = offset / strides[i];
offset -= indices[i] * strides[i];
}
indices[${Q} - 1] = offset;
}`}),ir,Mn,U2,W2,ch,dh,ph,fh,hh,mh,gh,bh=$(()=>{We(),Xr(),xe(),pe(),ir=(Q,J,G,H,K)=>{W2(J);let z={name:H,inputNames:["A"],inputTypes:[0]};return[Q.run({...z,cacheHint:G.cacheKey,get:()=>U2(Q,J,G,H,K,z)},J)]},Mn=(Q)=>{let J=Q.attributes.getInts("axes",[]),G=Q.attributes.getInt("keepdims",1)===1;return se({axes:J,keepDims:G})},U2=(Q,J,G,H,K,z)=>{let q=[],F=J[0].dims.length||1,D=[],V=U.normalizeAxes(G.axes,J[0].dims.length),O=K(J,V),P=O[1];for(let I=0;I<J[0].dims.length;I++)V.indexOf(I)>=0||V.length===0?(G.keepDims&&q.push(1),P=`
for(int j${I} = 0; j${I} < ${J[0].dims[I]}; j${I}++) {
inputIdx[${I}] = j${I};
${P}
}`):(D.push(`inputIdx[${I}] = outputIdx[${q.length}];`),q.push(J[0].dims[I]));let N=`
float process(int outputIdx[${q.length||1}]) {
float value; // final result
int inputIdx[${F}]; // addressing input data
${D.join(`
`)}
${O[0]} // init ops for reduce max/min
${P}
${O[2]} // final computation for reduce mean
return value;
}`;return{...z,output:{dims:q,type:J[0].type,textureType:0},shaderSource:N}},W2=(Q)=>{if(!Q||Q.length!==1)throw Error("Reduce op requires 1 input.");if(zn.indexOf(Q[0].type)===-1)throw Error("Invalid input type.")},ch=(Q,J,G)=>ir(Q,J,G,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),dh=(Q,J,G)=>ir(Q,J,G,"ReduceMean",(H,K)=>{let z=1;for(let q=0;q<H[0].dims.length;q++)(K.indexOf(q)>=0||K.length===0)&&(z*=H[0].dims[q]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${z}.;`]}),ph=(Q,J,G)=>ir(Q,J,G,"ReduceMax",(H,K)=>{let z=[];for(let q=0;q<H[0].dims.length;q++)(K.indexOf(q)>=0||K.length===0)&&z.push(`inputIdx[${q}] = 0;`);return[`${z.join(`
`)}
value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),fh=(Q,J,G)=>ir(Q,J,G,"ReduceMin",(H,K)=>{let z=[];for(let q=0;q<H[0].dims.length;q++)(K.indexOf(q)>=0||K.length===0)&&z.push(`inputIdx[${q}] = 0;`);return[`${z.join(`
`)}
value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),hh=(Q,J,G)=>ir(Q,J,G,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),mh=(Q,J,G)=>ir(Q,J,G,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),gh=(Q,J,G)=>ir(Q,J,G,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])}),yh,_h=$(()=>{xe(),yh=(Q,J)=>{let G=U.calculateReshapedDims(J[0].dims,J[1].integerData);return Q.session.pack?[Q.reshapePacked(J[0],G)]:[Q.reshapeUnpacked(J[0],G)]}}),xh,xu,wh,Th,Zr,H2,wu,Yo,Tu=$(()=>{We(),De(),pe(),xh={name:"Upsample",inputNames:["X"],inputTypes:[0]},xu=(Q,J,G)=>(wu(J,G),[Q.run({...xh,cacheHint:G.cacheKey,get:()=>H2(Q,J,G)},J)]),wh=(Q)=>Zr(Q,7),Th=(Q)=>Zr(Q,9),Zr=(Q,J)=>{let G=J>=10,H=Q.attributes.getString("mode","nearest");if(H!=="nearest"&&H!=="linear"&&(J<11||H!=="cubic"))throw Error(`unrecognized mode: ${H}`);let K=[];J<9&&(K=Q.attributes.getFloats("scales"),Yo(K,H,G));let z=Q.attributes.getFloat("extrapolation_value",0),q=J>10?Q.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(q)===-1)throw Error(`coordinate_transform_mode '${q}' is not supported`);let F=q==="tf_crop_and_resize",D=F,V=H==="nearest"&&J>=11?Q.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(V)===-1)throw Error(`nearest_mode '${V}' is not supported`);let O=Q.attributes.getFloat("cubic_coeff_a",-0.75),P=Q.attributes.getInt("exclude_outside",0)!==0;if(P&&H!=="cubic")throw Error("exclude_outside can be set to 1 only when mode is CUBIC.");let N=J<11?!0:H==="nearest"&&q==="asymmetric"&&V==="floor",I=0,R=0,w=0;return J>10?Q.inputs.length>2?(I=1,R=2,w=3):(R=1,w=2):J===9&&(R=1),se({opset:J,isResize:G,mode:H,scales:K,extrapolationValue:z,coordinateTransformMode:q,useExtrapolation:D,needRoiInput:F,nearestMode:V,cubicCoefficientA:O,excludeOutside:P,useNearest2xOptimization:N,roiInputIdx:I,scalesInputIdx:R,sizesInputIdx:w})},H2=(Q,J,G)=>{let H=j(Q.session.backend.glContext.version),[K,z]=Q.calculateTextureWidthAndHeight(J[0].dims,0),q=J[0].dims.map((w,E)=>Math.floor(w*G.scales[E])),[F,D]=Q.calculateTextureWidthAndHeight(q,0),V=q.length,O=Array(V),P=Array(V),N=`
int output_pitches[${V}];
int input_pitches[${V}];
`;for(let w=V-1;w>=0;w--)O[w]=w===V-1?1:O[w+1]*q[w+1],P[w]=w===V-1?1:P[w+1]*J[0].dims[w+1],N+=`
output_pitches[${w}] = ${O[w]};
input_pitches[${w}] = ${P[w]};
`;let I=`
float getInputFloat(int index) {
vec2 coords = offsetToCoords(index, ${K}, ${z});
float value = getColorAsFloat(${H.texture2D}(X, coords));
return value;
}
`,R=G.mode==="nearest"?`
${I}
float process(int indices[${V}]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${F}, ${D});
${N}
int d, m;
for (int dim = 0; dim < ${V}; ++dim) {
d = output_index / output_pitches[dim];
m = output_index - d * output_pitches[dim];
output_index = m;
if (scales[dim] != 1 && d > 0) {
int d2 = d / scales[dim];
m = d - d2 * scales[dim];
d = d2;
}
input_index += input_pitches[dim] * d;
}
return getInputFloat(input_index);
}`:V===4?`
${I}
float process(int indices[4]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${F}, ${D});
${N}
int m;
int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;
index_of_dim0 = output_index / output_pitches[0];
m = output_index - index_of_dim0 * output_pitches[0];
index_of_dim1 = m / output_pitches[1];
m = m - index_of_dim1 * output_pitches[1];
index_of_dim2 = m / output_pitches[2];
m = m - index_of_dim2 * output_pitches[2];
index_of_dim3 = m;
int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;
index_of_input_dim2 = index_of_dim2 / scales[2];
y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];
index_of_input_dim3 = index_of_dim3 / scales[3];
x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];
input_index = index_of_dim0 * input_pitches[0] +
index_of_dim1 * input_pitches[1] +
index_of_input_dim2 * input_pitches[2] +
index_of_input_dim3;
float x00 = getInputFloat(input_index);
float x10, x01, x11;
bool end_of_dim2 = false;
if (index_of_input_dim2 == (${J[0].dims[2]} - 1)) {
// It's the end in dimension 2
x01 = x00;
end_of_dim2 = true;
} else {
x01 = getInputFloat(input_index + input_pitches[2]);
}
if (index_of_input_dim3 == (input_pitches[2] - 1)) {
// It's the end in dimension 3
x10 = x00;
x11 = x01;
}
else {
x10 = getInputFloat(input_index + 1);
x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);
}
float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);
float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);
return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);
}`:`
${I}
float process(int indices[2]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${F}, ${D});
${N}
int m;
int index_of_dim0, index_of_dim1;
index_of_dim0 = output_index / output_pitches[0];
m = output_index - index_of_dim0 * output_pitches[0];
index_of_dim1 = m;
int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;
index_of_input_dim0 = index_of_dim0 / scales[0];
y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];
index_of_input_dim1 = index_of_dim1 / scales[1];
x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];
input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;
float x00 = getInputFloat(input_index);
float x10, x01, x11;
bool end_of_dim0 = false;
if (index_of_input_dim0 == (${J[0].dims[0]} - 1)) {
// It's the end in dimension 0
x01 = x00;
end_of_dim0 = true;
} else {
x01 = getInputFloat(input_index + input_pitches[0]);
}
if (index_of_input_dim1 == (input_pitches[0] - 1)) {
// It's the end in dimension 1
x10 = x00;
x11 = x01;
}
else {
x10 = getInputFloat(input_index + 1);
x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
}
float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
}`;return{...xh,output:{dims:q,type:J[0].type,textureType:0},shaderSource:R,variables:[{name:"scales",type:"int",arrayLength:G.scales.length,data:G.scales.map((w)=>Math.ceil(w))}]}},wu=(Q,J)=>{if(!Q||J.opset<9&&Q.length!==1||J.opset>=9&&J.opset<11&&Q.length!==2||J.opset>=11&&Q.length<2)throw Error("invalid inputs.");if(J.scales.length>0&&Q[0].dims.length!==J.scales.length)throw Error("Invalid input shape.");if(Q[0].type==="string")throw Error("Invalid input tensor types.")},Yo=(Q,J,G)=>{if(G){for(let H of Q)if(H<=0)throw Error("Scale value should be greater than 0.")}else for(let H of Q)if(H<1)throw Error("Scale value should be greater than or equal to 1.");if((J==="linear"||J==="cubic")&&Q.length!==2&&(Q.length!==4||Q[0]!==1||Q[1]!==1))throw Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${G?"Resize":"Upsample"} opeartor.`)}}),vu,Iu,vh,Ih,q2,j2,K2,X2,Sh=$(()=>{De(),pe(),dn(),nr(),Tu(),vu={name:"Resize",inputNames:["A"],inputTypes:[2]},Iu=(Q,J,G)=>(wu(J,G),[Q.run({...vu,cacheHint:G.cacheKey,get:()=>q2(Q,J,G)},J)]),vh=(Q)=>Zr(Q,10),Ih=(Q)=>Zr(Q,11),q2=(Q,J,G)=>{let H=j(Q.session.backend.glContext.version),[K,z]=j2(J,G);if(K.every((y)=>y===1)&&G.coordinateTransformMode!=="tf_crop_and_resize")return{...vu,output:{dims:z,type:J[0].type,textureType:2},hasMain:!0,shaderSource:`void main() {
vec4 v = ${H.texture2D}(X, TexCoords);
${H.output} = v;
}`};let q=z.length;if(q<2)throw Error(`output dimension should be at least 2, but got ${q}`);let F=z[q-2],D=z[q-1],V=J[0].dims;if(q!==V.length)throw Error(`output dimension should match input ${V.length}, but got ${q}`);let O=V[q-2],P=V[q-1],N=K[q-2],I=K[q-1],R="";if(G.mode!=="linear")throw Error(`resize (packed) does not support mode: '${G.mode}'`);switch(G.coordinateTransformMode){case"asymmetric":R=`
vec4 getSourceFracIndex(ivec4 coords) {
return vec4(coords) / scaleWHWH;
}
`;break;case"half_pixel":R=`
vec4 getSourceFracIndex(ivec4 coords) {
return (vec4(coords) + 0.5) / scaleWHWH - 0.5;
}
`;break;case"pytorch_half_pixel":R=`
vec4 getSourceFracIndex(ivec4 coords) {
vec4 fcoords = vec4(coords);
return vec4(
${D}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,
${F}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,
${D}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,
${F}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0
);
}
`;break;case"align_corners":R=`
vec4 getSourceFracIndex(ivec4 coords) {
vec4 resized = vec4(${D}.0 - 1.0, ${F}.0 - 1.0, ${D}.0 - 1.0,
${F}.0 - 1.0);
vec4 original = vec4(${P}.0 - 1.0, ${O}.0 - 1.0, ${P}.0 - 1.0,
${O}.0 - 1.0);
vec4 new_scale = original / resized;
return vec4(coords) * new_scale;
}
`;break;default:throw Error(`resize (packed) does not support coordinateTransformMode: '${G.coordinateTransformMode}'`)}let w=Ye(q),E=pn(),T=`
const vec2 inputWH = vec2(${O}.0, ${P}.0);
const vec4 scaleWHWH = vec4(float(${N}), float(${I}), float(${N}), float(${I}));
${E}
${R}
float getAValue(int x10, int r, int c, int d) {
return getChannel(getA(x10, r, c, d), vec2(c, d));
}
void main() {
${w} rc = getOutputCoords();
int batch = rc[0];
int depth = rc[1];
// retrieve the 4 coordinates that is used in the 4 packed output values.
ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);
// calculate the source index in fraction
vec4 sourceFrac = getSourceFracIndex(coords);
// get the lower and upper bound of the 4 values that will be packed into one texel.
ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));
ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));
ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));
ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));
bool hasNextRow = rc.w < ${F-1};
bool hasNextCol = rc.z < ${D-1};
// pack x00, x01, x10, x11's top-left corner into one vec4 structure
vec4 topLeft = vec4(
getAValue(batch, depth, x00.x, x00.y),
hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);
// pack x00, x01, x10, x11's top-right corner into one vec4 structure
vec4 topRight = vec4(
getAValue(batch, depth, x00.x, x00.w),
hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);
// pack x00, x01, x10, x11's bottom-left corner into one vec4 structure
vec4 bottomLeft = vec4(
getAValue(batch, depth, x00.z, x00.y),
hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);
// pack x00, x01, x10, x11's bottom-right corner into one vec4 structure
vec4 bottomRight = vec4(
getAValue(batch, depth, x00.z, x00.w),
hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,
hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,
(hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);
// calculate the interpolation fraction on u and v direction
vec4 frac = vec4(sourceFrac) - floor(sourceFrac);
vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));
vec4 top = mix(topLeft, topRight, clampFrac.ywyw);
vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);
vec4 newValue = mix(top, bottom, clampFrac.xxzz);
${H.output} = vec4(newValue);
}
`;return{...vu,output:{dims:z,type:J[0].type,textureType:2},hasMain:!0,shaderSource:T}},j2=(Q,J)=>{let G=Q[0].dims,H=J.scales,K;if(H.length===0){let q=Q[J.scalesInputIdx];if(q&&q.size!==0){if(Q[J.sizesInputIdx])throw Error("Only one of scales or sizes must be provided as input.");H=K2(q,J.mode,J.isResize)}else{let F=Q[J.sizesInputIdx];if(!F||F.size===0)throw Error("Either scales or sizes MUST be provided as input.");K=Array.from(F.integerData),H=X2(K,G,J.mode,J.isResize)}}else if(Q[J.sizesInputIdx])throw Error("Only one of scales or sizes must be provided as input.");let z=K||G.map((q,F)=>Math.floor(q*H[F]));return[H,z]},K2=(Q,J,G)=>{let H=Array.from(Q.floatData);return Yo(H,J,G),H},X2=(Q,J,G,H)=>{let K=J.length,z=Array(K);for(let q=0,F=K;q<F;q++)if(J[q]===0){if(Q[q]!==0)throw Error("Input dim is zero but required output dim is non-zero.");z[q]=1}else z[q]=Q[q]/J[q];return Yo(z,G,H),z}}),$h,Z2,Ah=$(()=>{tr(),$h=(Q,J)=>(Z2(J),[new Me([J[0].dims.length],"int32",void 0,void 0,new Int32Array(J[0].dims))]),Z2=(Q)=>{if(!Q||Q.length!==1)throw Error("Shape requires 1 input.")}}),Su,Ph,Oh,Eh,J2,Ch,Q2,Y2,Dh=$(()=>{We(),Xr(),xe(),pe(),Su={name:"Slice",inputNames:["A"],inputTypes:[0]},Ph=(Q,J,G)=>(J2(J),[Q.run({...Su,cacheHint:G.cacheKey,get:()=>Eh(Q,J[0],G)},J)]),Oh=(Q)=>{let J=Q.attributes.getInts("starts"),G=Q.attributes.getInts("ends"),H=Q.attributes.getInts("axes",[]);return se({starts:J,ends:G,axes:H})},Eh=(Q,J,G)=>{let H=G.axes.length===0?J.dims.slice(0).map((O,P)=>P):G.axes,K=U.normalizeAxes(H,J.dims.length),z=G.starts.map((O,P)=>O>J.dims[K[P]]-1?J.dims[K[P]]:U.normalizeAxis(O,J.dims[K[P]])),q=G.ends.map((O,P)=>O>J.dims[K[P]]-1?J.dims[K[P]]:U.normalizeAxis(O,J.dims[K[P]])),F=J.dims.slice(),D=[];for(let O=0;O<K.length;O++)F[K[O]]=q[O]-z[O],z[O]>0&&D.push(`outputIdx[${K[O]}] += ${z[O]};`);let V=`
float process(int outputIdx[${F.length}]) {
${D.join(`
`)}
return _A(outputIdx);
}`;return{...Su,output:{dims:F,type:J.type,textureType:0},shaderSource:V}},J2=(Q)=>{if(!Q||Q.length!==1)throw Error("Slice requires 1 input.");if(zn.indexOf(Q[0].type)===-1)throw Error("Invalid input type.")},Ch=(Q,J)=>{Y2(J);let G=Q2(Q,J);return[Q.run({...Su,cacheHint:G.cacheKey,get:()=>Eh(Q,J[0],G)},[J[0]])]},Q2=(Q,J)=>{if(!Q.session.isInitializer(J[1].dataId)||!Q.session.isInitializer(J[2].dataId)||J.length>=4&&!Q.session.isInitializer(J[3].dataId)||J.length>=5&&!Q.session.isInitializer(J[4].dataId))throw Error("dynamic slice attributes are not allowed");if(J.length>=5&&J[4].integerData.some((q)=>q!==1))throw Error("currently non-1 steps is not supported for Slice");let G=Array.from(J[1].integerData),H=Array.from(J[2].integerData),K=J.length>=4?Array.from(J[3].integerData):[],z=`${K};${G};${H}`;return{starts:G,ends:H,axes:K,cacheKey:z}},Y2=(Q)=>{if(!Q||Q.length<3||Q.length>5)throw Error("Invalid input number.");if(Q[1].type!=="int32"||Q[1].dims.length!==1)throw Error("Invalid input type.");if(Q[2].type!=="int32"||Q[2].dims.length!==1)throw Error("Invalid input type.");if(Q.length>=4&&(Q[3].type!=="int32"||Q[3].dims.length!==1))throw Error("Invalid input type.");if(Q.length>=5&&(Q[4].type!=="int32"||Q[4].dims.length!==1))throw Error("Invalid input type.")}}),kh,Lh,Rh,Nh,zh,Mh,Bh,Fh,eS,tS,nS,Vh,Gh=$(()=>{We(),xe(),De(),pe(),Zo(),kh={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[0]},Lh={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[0,0]},Rh={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[0,0,0]},Nh=(Q,J,G)=>{Vh(J);let H=J[0].dims.slice(),K=U.normalizeAxis(G.axis,H.length),z=U.sizeToDimension(H,K),q=U.sizeFromDimension(H,K);return Fh(Q,J,G,z,q)},zh=(Q)=>se({axis:Q.attributes.getInt("axis",1)}),Mh=(Q)=>se({axis:Q.attributes.getInt("axis",-1)}),Bh=(Q,J,G)=>{Vh(J);let H=J[0].dims.slice(),K=U.normalizeAxis(G.axis,H.length),z=H.length,q=K!==z-1,F=[],D=[],V=[],O;q&&(D=Array.from({length:z}).map((R,w)=>w),D[K]=z-1,D[z-1]=K,D.map((R)=>F.push(H[R])),O=se({perm:D}),V=or(Q,J,O));let P=q?U.sizeToDimension(F,z-1):U.sizeToDimension(H,z-1),N=q?U.sizeFromDimension(F,z-1):U.sizeFromDimension(H,z-1),I=Fh(Q,q?V:J,G,P,N);return q?or(Q,I,O):I},Fh=(Q,J,G,H,K)=>{let z=eS(Q,J[0],H,K,[H]),q=Q.run({...kh,cacheHint:G.cacheKey,get:()=>z},J),F=tS(Q,J[0],H,K,z.output.dims,[H]),D=Q.run({...Lh,cacheHint:G.cacheKey,get:()=>F},[J[0],q]),V=nS(Q,J[0],H,K,z.output.dims,F.output.dims);return[Q.run({...Rh,cacheHint:G.cacheKey,get:()=>V},[J[0],q,D])]},eS=(Q,J,G,H,K)=>{let[z,q]=Q.calculateTextureWidthAndHeight(J.dims,0),F=K.length;if(G<1||H<1)throw Error("Logical row count N and feature count D must be greater than or equal to 1");if(K.length!==1)throw Error("Dimensionality of the output should be 1");if(K[0]!==G)throw Error("Shape of the output should be equal to logical row count");let D=j(Q.session.backend.glContext.version),V=`
float process(int[${F}] indices) {
int logical_row_start_offset = indices[0] * ${H};
float max = getColorAsFloat(${D.texture2D}(A, offsetToCoords(logical_row_start_offset, ${z},
${q} )));
for(int i=1; i<${H}; ++i)
{
float current = getColorAsFloat(${D.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
${z}, ${q})));
if(current > max)
max = current;
}
return max;
}`;return{...kh,output:{dims:K,type:J.type,textureType:0},shaderSource:V}},tS=(Q,J,G,H,K,z)=>{let[q,F]=Q.calculateTextureWidthAndHeight(J.dims,0),D=z.length;if(G<1||H<1)throw Error("Logical row count N and feature count D must be greater than or equal to 1");if(z.length!==1)throw Error("Dimensionality of the output should be 1");if(z[0]!==G)throw Error("Shape of the output should be equal to logical row count");if(K.length!==1)throw Error("Dimensionality of the intermediate results should be 1");if(K[0]!==G)throw Error("Shape of the intermediate results should be equal to logical row count");let V=j(Q.session.backend.glContext.version),O=`
float process(int[${D}] indices) {
int logical_row_start_offset = indices[0] * ${H};
float norm_factor = 0.0;
float max = _Max(indices);
for(int i=0; i<${H}; ++i)
{
norm_factor += exp(getColorAsFloat(${V.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
${q}, ${F}))) - max);
}
return norm_factor;
}`;return{...Lh,output:{dims:z,type:J.type,textureType:0},shaderSource:O}},nS=(Q,J,G,H,K,z)=>{let[q,F]=Q.calculateTextureWidthAndHeight(J.dims,0),D=J.dims.length;if(G<1||H<1)throw Error("Logical row count N and feature count D must be greater than or equal to 1");if(K.length!==1||z.length!==1)throw Error("Dimensionality of the intermediate results should be 1");if(K[0]!==G||z[0]!==G)throw Error("Shape of the intermediate results should be equal to logical row count");let V=`
float process(int[${D}] indices) {
// get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
int offset = coordsToOffset(TexCoords, ${q}, ${F});
//determine the logical row for this index
int logical_row_index[1];
logical_row_index[0] = offset / ${H};
float norm_factor = _Norm(logical_row_index);
// avoid possible division by 0
// if norm_facor is 0, all elements are zero
// if so, return 0
if(norm_factor == 0.0)
return 0.0;
return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
}`;return{...Rh,output:{dims:J.dims,type:J.type,textureType:0},shaderSource:V}},Vh=(Q)=>{if(!Q||Q.length!==1)throw Error("Softmax requires 1 input.");if(Q[0].type!=="float32"&&Q[0].type!=="float64")throw Error("Invalid input type")}}),Uh,Wh,Hh,rS,oS,iS,qh=$(()=>{We(),xe(),pe(),Uh={name:"Split",inputNames:["A"],inputTypes:[0]},Wh=(Q,J,G)=>{iS(J);let H=U.normalizeAxis(G.axis,J[0].dims.length),K=rS(Q,J,H,G),z=[];for(let q=0;q<K;++q)z.push(Q.run({...Uh,cacheHint:`${G.cacheKey};${q}`,get:()=>oS(Q,J[0],G,H,q)},J));return z},Hh=(Q)=>{let J=Q.attributes.getInt("axis",0),G=Q.attributes.getInts("split",[]),H=Q.outputs.length;return se({axis:J,split:G,numOutputs:H})},rS=(Q,J,G,H)=>{let[,K]=Ur.splitShape(J[0].dims,G,H.split,H.numOutputs);return K.length},oS=(Q,J,G,H,K)=>{let[z,q]=Ur.splitShape(J.dims,H,G.split,G.numOutputs),F=q[K],D=z[K],V=`
float process(int indices[${D.length}]) {
indices[${H}] += ${F};
return _A(indices);
}
`;return{...Uh,cacheHint:`${G.cacheKey}:${K}`,output:{dims:D,type:J.type,textureType:0},shaderSource:V}},iS=(Q)=>{if(!Q||Q.length!==1)throw Error("Split requires one input.");if(Q[0].type!=="int8"&&Q[0].type!=="uint8"&&Q[0].type!=="int16"&&Q[0].type!=="uint16"&&Q[0].type!=="int32"&&Q[0].type!=="uint32"&&Q[0].type!=="float32"&&Q[0].type!=="float64"&&Q[0].type!=="bool")throw Error("Invalid input type.")}}),$u,jh,Kh,aS,sS,Xh=$(()=>{xe(),$u=(Q,J,G)=>{aS(J);let H=U.squeezeShape(J[0].dims,G);return[Q.reshapeUnpacked(J[0],H)]},jh=(Q,J)=>(sS(J),$u(Q,[J[0]],Array.from(J[1].integerData))),Kh=(Q)=>Q.attributes.getInts("axes"),aS=(Q)=>{if(!Q||Q.length!==1)throw Error("Squeeze requires 1 input.");if(Q[0].type==="string")throw Error("invalid input tensor types.")},sS=(Q)=>{if(!Q||Q.length!==2)throw Error("Squeeze requires 2 inputs.");if(Q[1].type!=="int32")throw Error("Invalid input type.")}}),Zh,uS,lS,Jh=$(()=>{De(),pe(),Zh=(Q,J)=>{lS(J);let G={name:"Sum",inputNames:J.map((H,K)=>`X${K}`),inputTypes:Array(J.length).fill(0)};return[Q.run({...G,get:()=>uS(Q,J,G)},J)]},uS=(Q,J,G)=>{let H=j(Q.session.backend.glContext.version),K=J[0].dims.slice(),z=`
void main() {
vec4 result = ${J.map((q,F)=>`${H.texture2D}(X${F},TexCoords)`).join(" + ")};
${H.output} = result;
}
`;return{...G,output:{dims:K,type:J[0].type,textureType:0},hasMain:!0,shaderSource:z}},lS=(Q)=>{if(!Q||Q.length===0)throw Error("Sum requires inputs.");let J=Q[0].dims.length;for(let G=1;G<Q.length;G++){if(J!==Q[G].dims.length)throw Error("Input shapes are mismatched.");for(let H=0;H<J;H++)if(Q[0].dims[H]!==Q[G].dims[H])throw Error("Input shapes are not matched.")}if(Q[0].type!=="float32"&&Q[0].type!=="float64")throw Error("Invalid input type.");for(let G=1;G<Q.length;G++)if(Q[0].type!==Q[G].type)throw Error("Input types are not matched.")}}),Qh,cS,dS,Yh=$(()=>{Xr(),pe(),Qh=(Q,J)=>{dS(J);let G={name:"Tile",inputNames:["A"],inputTypes:[0]};return[Q.run({...G,get:()=>cS(Q,J,G)},J)]},cS=(Q,J,G)=>{let H=J[0].dims.slice(),K=Array(H.length),z=[];for(let D=0;D<H.length;D++)K[D]=H[D]*J[1].numberData[D],z.push(`inputIdx[${D}] = int(mod(float(outputIdx[${D}]), ${H[D]}.));`);let q=K.length,F=`
float process(int outputIdx[${q}]) {
int inputIdx[${q}];
${z.join(`
`)}
return _A(inputIdx);
}
`;return{...G,output:{dims:K,type:J[0].type,textureType:0},shaderSource:F}},dS=(Q)=>{if(!Q||Q.length!==2)throw Error("Tile requires 2 input.");if(Q[1].dims.length!==1)throw Error("The second input shape must 1 dimension.");if(Q[1].dims[0]!==Q[0].dims.length)throw Error("Invalid input shape.");if(zn.indexOf(Q[0].type)===-1)throw Error("Invalid input type.");if(Q[1].type!=="int32"&&Q[1].type!=="int16")throw Error("Invalid repeat type.")}}),Au,em,tm,pS,fS,nm=$(()=>{xe(),Au=(Q,J,G)=>{pS(J);let H=U.unsqueezeShape(J[0].dims,G);return[Q.reshapeUnpacked(J[0],H)]},em=(Q,J)=>(fS(J),Au(Q,[J[0]],Array.from(J[1].integerData))),tm=(Q)=>Q.attributes.getInts("axes"),pS=(Q)=>{if(!Q||Q.length!==1)throw Error("Unsqueeze requires 1 input.");if(Q[0].type==="string")throw Error("invalid input tensor types.")},fS=(Q)=>{if(!Q||Q.length!==2)throw Error("Unsqueeze requires 2 inputs.");if(Q[1].type!=="int32")throw Error("Invalid input type.")}}),rm,om=$(()=>{fp(),$p(),Op(),Rp(),jo(),_f(),Sf(),Pf(),Cf(),Rf(),Mf(),Gf(),qf(),Ko(),Zf(),lh(),bh(),_h(),Sh(),Ah(),Dh(),Gh(),qh(),Xh(),Jh(),Yh(),Zo(),cu(),nm(),Tu(),rm=[["Abs","","6+",Np],["Acos","","7+",zp],["Add","","7+",hp],["And","","7+",mp],["Asin","","7+",Mp],["Atan","","7+",Bp],["AveragePool","","7+",Qf,Yf],["BatchNormalization","","7+",dp,pp],["Cast","","6+",Ap,Pp],["Ceil","","6+",Gp],["Clip","","6-10",uu,Fp],["Clip","","11+",Vp],["Concat","","4+",Dp,Lp],["Conv","","1+",gu,bu],["ConvTranspose","","1+",bf,yf],["Cos","","7+",Up],["Div","","7+",gp],["Dropout","","7+",lu],["DepthToSpace","","1+",vf,If],["Equal","","7+",bp],["Elu","","6+",Wp,Hp],["Exp","","6+",qp],["Flatten","","1+",$f,Af],["Floor","","6+",jp],["FusedConv","com.microsoft","1+",gu,bu],["Gather","","1+",Of,Ef],["Gemm","","7-10",yu,kf],["Gemm","","11+",yu,Lf],["GlobalAveragePool","","1+",th,nh],["GlobalMaxPool","","1+",sh],["Greater","","7+",yp],["Identity","","1+",lu],["ImageScaler","","1+",Nf,zf],["InstanceNormalization","","6+",Ff,Vf],["LeakyRelu","","6+",Kp,Xp],["Less","","7+",_p],["LRN","","1+",Uf,Wf],["Log","","6+",Zp],["MatMul","","1+",cf,df],["MaxPool","","1+",rh,oh],["Mul","","7+",xp],["Neg","","6+",Jp],["Not","","1+",Qp],["Or","","7+",wp],["Pad","","2-10",_u,jf],["Pad","","11+",Kf,Xf],["Pow","","7+",Tp],["PRelu","","7+",vp],["ReduceLogSum","","1+",mh,Mn],["ReduceMax","","1+",ph,Mn],["ReduceMean","","1+",dh,Mn],["ReduceMin","","1+",fh,Mn],["ReduceProd","","1+",hh,Mn],["ReduceSum","","1-12",ch,Mn],["ReduceSumSquare","","1+",gh,Mn],["Relu","","6+",Yp],["Reshape","","5+",yh],["Resize","","10",Iu,vh],["Resize","","11+",Iu,Ih],["Shape","","1+",$h],["Sigmoid","","6+",ef],["Sin","","7+",tf],["Slice","","10+",Ch],["Slice","","1-9",Ph,Oh],["Softmax","","1-12",Nh,zh],["Softmax","","13+",Bh,Mh],["Split","","2-12",Wh,Hh],["Sqrt","","6+",nf],["Squeeze","","1-12",$u,Kh],["Squeeze","","13+",jh],["Sub","","7+",Ip],["Sum","","6+",Zh],["Tan","","7+",rf],["Tanh","","6+",of],["Tile","","6+",Qh],["Transpose","","1+",or,wf],["Upsample","","7-8",xu,wh],["Upsample","","9",xu,Th],["Unsqueeze","","1-12",Au,tm],["Unsqueeze","","13+",em],["Xor","","7+",Sp]]});function am(Q){let J={},G;for(;(G=im.exec(Q))!==null;){let H=G[3].split(",").map((K)=>{let z=K.trim().split(" ");return z&&z.length===2?{type:z[0],name:z[1]}:null}).filter((K)=>K!==null);J[G[2]]={params:H,body:G[4]}}for(let H in J){let K=hS.replace("__FUNC__",H),z=new RegExp(K,"gm");for(;(G=z.exec(Q))!==null;){let q=G[1],F=G[2],D=G[3].split(","),V=q?`${q} ${F};`:"",O=J[H].body,P="";J[H].params.forEach((I,R)=>{I&&(P+=`${I.type} ${I.name} = ${D[R]};
`)}),O=`${P}
${O}`,O=O.replace("return",`${F} = `);let N=`
${V}
{
${O}
}
`;Q=Q.replace(G[0],N)}}return Q=Q.replace(im,""),Q}var im,hS,sm=$(()=>{im=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm,hS="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"});function vr(Q,J){let G=[],H=[],K=J!=null&&Array.isArray(J)&&J.length===0,z=J==null||K?null:mS(J,Q).sort(),q=0;for(let F=0;F<Q.length;++F){if(z!=null){if(z[q]===F&&Q[F]!==1)throw Error(`Can't squeeze axis ${F} since its dim '${Q[F]}' is not 1`);(z[q]==null||z[q]>F)&&Q[F]===1&&(G.push(Q[F]),H.push(F)),z[q]<=F&&q++}Q[F]!==1&&(G.push(Q[F]),H.push(F))}return{newShape:G,keptDims:H}}function mS(Q,J){let G=J.length;return Q=Q==null?J.map((H,K)=>K):[].concat(Q),br(Q.every((H)=>H>=-G&&H<G),()=>`All values in axis param must be in range [-${G}, ${G}) but got axis ${Q}`),br(Q.every(gS),()=>`All values in axis param must be integers but got axis ${Q}`),Q.map((H)=>H<0?G+H:H)}function gS(Q){return Q%1===0}function bS(Q){if(Q.length===0)return 1;let J=Q[0];for(let G=1;G<Q.length;G++)J*=Q[G];return J}function um(Q){let J=Math.ceil(Math.sqrt(Q));return[J,Math.ceil(Q/J)]}var ei,Pu=$(()=>{ct(),xe(),ei=class{constructor(Q){this.maxTextureSize=Q}computeTextureWH(Q,J){let G=this.computeTexture(Q,J);return J&&J.isPacked&&(G[0]/=2,G[1]/=2),J&&J.reverseWH?[G[1],G[0]]:G}computeTexture(Q,J){let G=J&&J.isPacked;if(Q.length===0)return G?[2,2]:[1,1];let H=this.maxTextureSize;if(J&&J.breakAxis!==void 0){let q=J.breakAxis>=Q.length?1:Q.slice(J.breakAxis).reduce((D,V)=>D*V),F=J.breakAxis<=0?1:Q.slice(0,J.breakAxis).reduce((D,V)=>D*V);if(q>H||F>H)Te.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${Q}, breakAxis:${J.breakAxis}`);else return[q,F]}let K=Q.slice(0);G&&(H=H*2,K=K.map((q,F)=>F>=K.length-2?K[F]%2===0?K[F]:K[F]+1:K[F]),K.length===1&&(K=[2,K[0]])),K.length!==2&&(K=vr(K).newShape);let z=bS(K);return K.length<=1&&z<=H?[1,z]:K.length===2&&K[0]<=H&&K[1]<=H?K:K.length===3&&K[0]*K[1]<=H&&K[2]<=H?[K[0]*K[1],K[2]]:K.length===3&&K[0]<=H&&K[1]*K[2]<=H?[K[0],K[1]*K[2]]:K.length===4&&K[0]*K[1]*K[2]<=H&&K[3]<=H?[K[0]*K[1]*K[2],K[3]]:K.length===4&&K[0]<=H&&K[1]*K[2]*K[3]<=H?[K[0],K[1]*K[2]*K[3]]:G?um(z/4).map((q)=>q*2):um(z)}}}),ti,lm=$(()=>{xe(),An(),De(),Pu(),dn(),ti=class extends gt{constructor(Q){super(Q)}getFunctions(){return{...this.offsetToCoords(),...this.coordsToOffset(),...this.toVec(),...this.valueFrom(),...this.getCommonUtilFuncs(),...this.getInputsSamplingSnippets(),...this.getOutputSamplingSnippet()}}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new M(`
vec2 ${"offsetToCoords"}(int offset, int width, int height) {
int t = offset / width;
int s = offset - t*width;
vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);
return coords;
}
`)}}coordsToOffset(){return{coordsToOffset:new M(`
int ${"coordsToOffset"}(vec2 coords, int width, int height) {
float s = coords.s * float(width);
float t = coords.t * float(height);
int offset = int(t) * width + int(s);
return offset;
}
`)}}getOutputSamplingSnippet(){let Q=this.context.outputTextureLayout;return Q.isPacked?this.getPackedOutputSamplingSnippet(Q):this.getUnpackedOutputSamplingSnippet(Q)}getPackedOutputSamplingSnippet(Q){let J=Q.unpackedShape,G=[Q.width,Q.height],H={},K="getOutputCoords";switch(J.length){case 0:H[K]=this.getOutputScalarCoords();break;case 1:H[K]=this.getOutputPacked1DCoords(J,G);break;case 2:H[K]=this.getOutputPacked2DCoords(J,G);break;case 3:H[K]=this.getOutputPacked3DCoords(J,G);break;default:H[K]=this.getOutputPackedNDCoords(J,G)}let z=`
void setOutput(vec4 val) {
${j(this.context.glContext.version).output} = val;
}
`,q="floatTextureSetRGBA";return H[q]=new M(z),H}getUnpackedOutputSamplingSnippet(Q){let J=Q.unpackedShape,G=[Q.width,Q.height],H={},K="getOutputCoords";switch(J.length){case 0:H[K]=this.getOutputScalarCoords();break;case 1:H[K]=this.getOutputUnpacked1DCoords(J,G);break;case 2:H[K]=this.getOutputUnpacked2DCoords(J,G);break;case 3:H[K]=this.getOutputUnpacked3DCoords(J,G);break;case 4:H[K]=this.getOutputUnpacked4DCoords(J,G);break;case 5:H[K]=this.getOutputUnpacked5DCoords(J,G);break;case 6:H[K]=this.getOutputUnpacked6DCoords(J,G);break;default:throw Error(`Unsupported output dimensionality: ${J.length}`)}let z=`
void setOutput(float val) {
${j(this.context.glContext.version).output} = vec4(val, 0, 0, 0);
}
`,q="floatTextureSetR";return H[q]=new M(z),H}getOutputScalarCoords(){return new M(`
int getOutputCoords() {
return 0;
}
`)}getOutputPacked1DCoords(Q,J){let G=J,H="";return G[0]===1?(H=`
int getOutputCoords() {
return 2 * int(TexCoords.y * ${G[1]}.0);
}
`,new M(H)):G[1]===1?(H=`
int getOutputCoords() {
return 2 * int(TexCoords.x * ${G[0]}.0);
}
`,new M(H)):(H=`
int getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${G[0]}, ${G[1]}));
return 2 * (resTexRC.y * ${G[0]} + resTexRC.x);
}
`,new M(H))}getOutputPacked2DCoords(Q,J){let G="";if(Jn.arraysEqual(Q,J))return G=`
ivec2 getOutputCoords() {
return 2 * ivec2(TexCoords.xy * vec2(${J[0]}, ${J[1]}));
}
`,new M(G);let H=J,K=Math.ceil(Q[1]/2);return G=`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${H[0]}, ${H[1]}));
int index = resTexRC.y * ${H[0]} + resTexRC.x;
// reverse r and c order for packed texture
int r = imod(index, ${K}) * 2;
int c = 2 * (index / ${K});
return ivec2(r, c);
}
`,new M(G)}getOutputPacked3DCoords(Q,J){let G=[J[0],J[1]],H=Math.ceil(Q[2]/2),K=H*Math.ceil(Q[1]/2),z=`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${G[0]}, ${G[1]}));
int index = resTexRC.y * ${G[0]} + resTexRC.x;
int b = index / ${K};
index -= b * ${K};
// reverse r and c order for packed texture
int r = imod(index, ${H}) * 2;
int c = 2 * (index / ${H});
return ivec3(b, r, c);
}
`;return new M(z)}getOutputPackedNDCoords(Q,J){let G=[J[0],J[1]],H=Math.ceil(Q[Q.length-1]/2),K=H*Math.ceil(Q[Q.length-2]/2),z=K,q="",F="b, r, c";for(let V=2;V<Q.length-1;V++)z*=Q[Q.length-V-1],q=`
int b${V} = index / ${z};
index -= b${V} * ${z};
`+q,F=`b${V}, `+F;let D=`
ivec${Q.length} getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${G[0]}, ${G[1]}));
int index = resTexRC.y * ${G[0]} + resTexRC.x;
${q}
int b = index / ${K};
index -= b * ${K};
// reverse r and c order for packed texture
int r = imod(index, ${H}) * 2;
int c = 2 * (index / ${H});
return ivec${Q.length}(${F});
}
`;return new M(D)}getOutputUnpacked1DCoords(Q,J){let G=`
int getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${J[0]}, ${J[1]}));
return resTexRC.y * ${J[0]} + resTexRC.x;
}
`;return new M(G)}getOutputUnpacked2DCoords(Q,J){let G=`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${J[0]}, ${J[1]}));
int index = resTexRC.y * ${J[0]} + resTexRC.x;
int r = index / ${Q[1]};
int c = index - r * ${Q[1]};
return ivec2(r, c);
}
`;return new M(G)}getOutputUnpacked3DCoords(Q,J){let G="",H=Q.length,K=null;H<2&&(K=[]),K=Array(H-1),K[H-2]=Q[H-1];for(let F=H-3;F>=0;--F)K[F]=K[F+1]*Q[F+1];let z=["r","c","d"],q=K.map((F,D)=>{let V=`int ${z[D]} = index / ${F}`,O=D===K.length-1?`int ${z[D+1]} = index - ${z[D]} * ${F}`:`index -= ${z[D]} * ${F}`;return`${V}; ${O};`}).join("");return G=`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${J[0]}, ${J[1]}));
int index = resTexRC.y * ${J[0]} + resTexRC.x;
${q}
return ivec3(r, c, d);
}
`,new M(G)}getOutputUnpacked4DCoords(Q,J){let G="",H=Q.length,K=null;H<2&&(K=[]),K=Array(H-1),K[H-2]=Q[H-1];for(let F=H-3;F>=0;--F)K[F]=K[F+1]*Q[F+1];let z=["r","c","d","d2"],q=K.map((F,D)=>{let V=`int ${z[D]} = index / ${F}`,O=D===K.length-1?`int ${z[D+1]} = index - ${z[D]} * ${F}`:`index -= ${z[D]} * ${F}`;return`${V}; ${O};`}).join("");return G=`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${J[0]}, ${J[1]}));
int index = resTexRC.y * ${J[0]} + resTexRC.x;
${q}
return ivec4(r, c, d, d2);
}
`,new M(G)}getOutputUnpacked5DCoords(Q,J){let G="",H=Q.length,K=null;H<2&&(K=[]),K=Array(H-1),K[H-2]=Q[H-1];for(let F=H-3;F>=0;--F)K[F]=K[F+1]*Q[F+1];let z=["r","c","d","d2","d3"],q=K.map((F,D)=>{let V=`int ${z[D]} = index / ${F}`,O=D===K.length-1?`int ${z[D+1]} = index - ${z[D]} * ${F}`:`index -= ${z[D]} * ${F}`;return`${V}; ${O};`}).join("");return G=`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${J[0]}, ${J[1]}));
int index = resTexRC.y * ${J[0]} + resTexRC.x;
${q}
return ivec5(r, c, d, d2, d3);
}
`,new M(G)}getOutputUnpacked6DCoords(Q,J){let G="",H=Q.length,K=null;H<2&&(K=[]),K=Array(H-1),K[H-2]=Q[H-1];for(let F=H-3;F>=0;--F)K[F]=K[F+1]*Q[F+1];let z=["r","c","d","d2","d3","d4"],q=K.map((F,D)=>{let V=`int ${z[D]} = index / ${F}`,O=D===K.length-1?`int ${z[D+1]} = index - ${z[D]} * ${F}`:`index -= ${z[D]} * ${F}`;return`${V}; ${O};`}).join("");return G=`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(TexCoords.xy *
vec2(${J[0]}, ${J[1]}));
int index = resTexRC.y * ${J[0]} + resTexRC.x;
${q}
return ivec6(r, c, d, d2, d3, d4);
}
`,new M(G)}getCommonUtilFuncs(){let Q={},J="uvFromFlat";Q[J]=new M(`
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texC = index / texNumR;
int texR = index - texC * texNumR;
// TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to
// v.
return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);
}
`),J="packedUVfrom1D",Q[J]=new M(`
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`),J="packedUVfrom2D",Q[J]=new M(`
vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`),J="packedUVfrom3D",Q[J]=new M(`
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`),J="sampleTexture";let G=j(this.context.glContext.version);return Q[J]=new M(`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${G.texture2D}(textureSampler, uv).r;
}`),Q}getInputsSamplingSnippets(){let Q={},J=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((G,H)=>{let K=this.context.inputTextureLayouts[H],z=Fo(G);K.isPacked?Q[z]=this.getPackedSamplerFromInput(z,G,K):Q[z]=this.getUnpackedSamplerFromInput(z,G,K);let q=Xd(G);K.unpackedShape.length<=J.unpackedShape.length&&(K.isPacked?Q[q]=this.getPackedSamplerAtOutputCoords(q,K,J,G):Q[q]=this.getUnpackedSamplerAtOutputCoords(q,K,J,G))}),Q}getPackedSamplerAtOutputCoords(Q,J,G,H){let K=J.unpackedShape,z=G.unpackedShape,q=Fo(H),F=K.length,D=z.length,V=Qe.getBroadcastDims(K,z),O=Ye(D),P=D-F,N,I=$t();F===0?N="":D<2&&V.length>=1?N="coords = 0;":N=V.map((b)=>`coords.${I[b+P]} = 0;`).join(`
`);let R="";D<2&&F>0?R="coords":R=K.map((b,g)=>`coords.${I[g+P]}`).join(", ");let w="return outputValue;",E=U.size(K)===1,T=U.size(z)===1;if(F===1&&!E&&!T)w=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(E&&!T)D===1?w=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:w=`
return vec4(outputValue.x);
`;else if(V.length){let b=F-2,g=F-1;V.indexOf(b)>-1&&V.indexOf(g)>-1?w="return vec4(outputValue.x);":V.indexOf(b)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":V.indexOf(g)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}let y=`
int lastDim = coords.${I[D-1]};
coords.${I[D-1]} = coords.${I[D-2]};
coords.${I[D-2]} = lastDim;
`,x=`
vec4 ${Q}() {
${O} coords = getOutputCoords();
${y}
${N}
vec4 outputValue = ${q}(${R});
${w}
}
`;return new M(x,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(Q,J,G,H){let K=[G.width,G.height],z=[J.width,J.height],q=J.unpackedShape.length,F=G.unpackedShape.length,D=J.unpackedShape,V=G.unpackedShape,O=Fo(H);if(q===F&&Jn.arraysEqual(z,K)){let y=`
float ${Q}() {
return sampleTexture(${H}, TexCoords);
}
`;return new M(y,["coordinates.sampleTexture"])}let P=Ye(F),N=Qe.getBroadcastDims(D,V),I=F-q,R,w=$t();q===0?R="":F<2&&N.length>=1?R="coords = 0;":R=N.map((y)=>`coords.${w[y+I]} = 0;`).join(`
`);let E="";F<2&&q>0?E="coords":E=J.unpackedShape.map((y,x)=>`coords.${w[x+I]}`).join(", ");let T=`
float ${Q}() {
${P} coords = getOutputCoords();
${R}
return ${O}(${E});
}
`;return new M(T,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(Q,J,G){switch(G.unpackedShape.length){case 0:return this.getPackedSamplerScalar(Q,J);case 1:return this.getPackedSampler1D(Q,J,G);case 2:return this.getPackedSampler2D(Q,J,G);case 3:return this.getPackedSampler3D(Q,J,G);default:return this.getPackedSamplerND(Q,J,G)}}getUnpackedSamplerFromInput(Q,J,G){let H=G.unpackedShape;switch(H.length){case 0:return this.getUnpackedSamplerScalar(Q,J,G);case 1:return this.getUnpackedSampler1D(Q,J,G);case 2:return this.getUnpackedSampler2D(Q,J,G);case 3:return this.getUnpackedSampler3D(Q,J,G);case 4:return this.getUnpackedSampler4D(Q,J,G);case 5:return this.getUnpackedSampler5D(Q,J,G);case 6:return this.getUnpackedSampler6D(Q,J,G);default:throw Error(`Unsupported dimension ${H.length}-D`)}}getPackedSamplerScalar(Q,J){let G=j(this.context.glContext.version),H=`
vec4 ${Q}() {
return ${G.texture2D}(${J}, halfCR);
}
`;return new M(H)}getPackedSampler1D(Q,J,G){let H=[G.width,G.height],K=[H[1],H[0]],z=j(this.context.glContext.version),q=`vec4 ${Q}(int index) {
vec2 uv = packedUVfrom1D(
${K[0]}, ${K[1]}, index);
return ${z.texture2D}(${J}, uv);
}`;return new M(q,["coordinates.packedUVfrom1D"])}getPackedSampler2D(Q,J,G){let H=G.unpackedShape,K=[G.width,G.height],z=j(this.context.glContext.version),q=K[0],F=K[1];if(K!=null&&Jn.arraysEqual(H,K)){let P=`vec4 ${Q}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${F}.0, ${q}.0);
return ${z.texture2D}(${J}, uv);
}`;return new M(P)}let D=K,V=Math.ceil(H[1]/2),O=`vec4 ${Q}(int row, int col) {
vec2 uv = packedUVfrom2D(${D[1]}, ${D[0]}, ${V}, row, col);
return ${z.texture2D}(${J}, uv);
}`;return new M(O,["coordinates.packedUVfrom2D"])}getPackedSampler3D(Q,J,G){let H=G.unpackedShape,K=[G.width,G.height],z=[K[0],K[1]],q=j(this.context.glContext.version);if(H[0]===1){let N=H.slice(1),I=[1,2],R=yr(H,N),w=["b","row","col"],E=JSON.parse(JSON.stringify(G));E.unpackedShape=R;let T=this.getPackedSamplerFromInput(Q,J,E),y=`${T.routineBody}
vec4 ${Q}(int b, int row, int col) {
return ${Q}(${_r(w,I)});
} `;return new M(y,T.dependencies)}let F=z[0],D=z[1],V=Math.ceil(H[2]/2),O=V*Math.ceil(H[1]/2),P=`vec4 ${Q}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${D}, ${F}, ${O}, ${V}, b, row, col);
return ${q.texture2D}(${J}, uv);}`;return new M(P,["coordinates.packedUVfrom3D"])}getPackedSamplerND(Q,J,G){let H=G.unpackedShape,K=H.length,z=[G.width,G.height],q=j(this.context.glContext.version),F=[z[0],z[1]],D=F[1],V=F[0],O=Math.ceil(H[K-1]/2),P=O*Math.ceil(H[K-2]/2),N="int b, int row, int col",I=`b * ${P} + (row / 2) * ${O} + (col / 2)`;for(let w=2;w<K-1;w++)N=`int b${w}, `+N,P*=H[K-w-1],I=`b${w} * ${P} + `+I;let R=`vec4 ${Q}(${N}) {
int index = ${I};
int texR = index / ${V};
int texC = index - texR * ${V};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${V}, ${D});
return ${q.texture2D}(${J}, uv);
}`;return new M(R)}getUnpackedSamplerScalar(Q,J,G){let[H,K]=[G.width,G.height];if(H===1&&K===1){let q=`
float ${Q}() {
return sampleTexture(${J}, halfCR);
}
`;return new M(q,["coordinates.sampleTexture"])}let z=`
float ${Q}() {
int offset_${J} = coordsToOffset(TexCoords, ${H}, ${K});
vec2 uv = uvFromFlat(${H}, ${K}, offset_${J});
return sampleTexture(${J}, uv);
}
`;return new M(z,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler1D(Q,J,G){let{width:H,height:K}=G;if(K===1&&H===1){let q=`
float ${Q}(int index) {
return sampleTexture(${J}, halfCR);
}
`;return new M(q,["coordinates.sampleTexture"])}if(K===1){let q=`
float ${Q}(int index) {
vec2 uv = vec2((float(index) + 0.5) / ${H}.0, 0.5);
return sampleTexture(${J}, uv);
}
`;return new M(q,["coordinates.sampleTexture"])}if(H===1){let q=`
float ${Q}(int index) {
vec2 uv = vec2(0.5, (float(index) + 0.5) / ${K}.0);
return sampleTexture(${J}, uv);
}
`;return new M(q,["coordinates.sampleTexture"])}let z=`
float ${Q}(int index) {
vec2 uv = uvFromFlat(${H}, ${K}, index);
return sampleTexture(${J}, uv);
}
`;return new M(z,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(Q,J,G){let H=G.unpackedShape,K=[G.height,G.width];if(K!=null&&Jn.arraysEqual(H,K)){let P=K[1],N=K[0],I=`
float ${Q}(int row, int col) {
vec2 uv = (vec2(row, col) + halfCR) / vec2(${P}.0, ${N}.0);
return sampleTexture(${J}, uv);
}
`;return new M(I,["coordinates.sampleTexture"])}let{newShape:z,keptDims:q}=vr(H),F=z;if(F.length<H.length){let P=yr(H,F),N=JSON.parse(JSON.stringify(G));N.unpackedShape=P;let I=["col","row"],R=`
${this.getUnpackedSamplerFromInput(Q,J,N).routineBody}
float ${Q}(int row, int col) {
return ${Q}(${_r(I,q)});
}
`;return new M(R,["coordinates.sampleTexture"])}let D=K[1],V=K[0];if(V===1){let P=`
float ${Q}(int row, int col) {
int offset_${J} = coordsToOffset(TexCoords, ${D}, ${V});
float index = dot(vec3(row, col, offset_${J}), vec3(${H[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${D}.0);
return sampleTexture(${J}, uv);
}
`;return new M(P,["coordinates.sampleTexture","coordinates.coordsToOffset"])}if(D===1){let P=`
float ${Q}(int row, int col) {
int offset_${J} = coordsToOffset(TexCoords, ${D}, ${V});
float index = dot(vec3(row, col, offset_${J}), vec3(${H[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${V}.0, 0.5);
return sampleTexture(${J}, uv);
}
`;return new M(P,["coordinates.sampleTexture","coordinates.coordsToOffset"])}let O=`
float ${Q}(int row, int col) {
int index = col * ${H[1]} + row;
vec2 uv = uvFromFlat(${D}, ${V}, index);
return sampleTexture(${J}, uv);
}
`;return new M(O,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(Q,J,G){let H=G.unpackedShape,K=H[1]*H[2],z=H[2],{newShape:q,keptDims:F}=vr(H),D=q;if(D.length<H.length){let N=yr(H,D),I=["batch","col","row"],R=JSON.parse(JSON.stringify(G));R.unpackedShape=N;let w=this.getUnpackedSamplerFromInput(Q,J,R),E=F.reverse(),T=`
${w.routineBody}
float ${Q}(int batch, int row, int col) {
return ${Q}(${_r(I,E)});
}
`;return new M(T,w.dependencies)}let{width:V,height:O}=G,P=`
float ${Q}(int depth, int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = depth * ${K} + col * ${z} + row;
vec2 uv = uvFromFlat(${V}, ${O}, index);
return sampleTexture(${J}, uv);
}
`;return new M(P,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler4D(Q,J,G){let H=G.unpackedShape,K=H[3],z=H[2]*K,q=H[1]*z,F=G.width,D=G.height,V=`
float ${Q}(int row, int col, int depth, int depth2) {
int index = row * ${q} + col * ${z} +
depth2 * ${K} + depth;
vec2 uv = uvFromFlat(${F}, ${D}, index);
return sampleTexture(${J}, uv);
}
`;return new M(V,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(Q,J,G){let H=G.unpackedShape,K=H[4],z=H[3]*K,q=H[2]*z,F=H[1]*q,{newShape:D,keptDims:V}=vr(H);if(D.length<H.length){let I=yr(H,D),R=["row","col","depth","depth2","depth3"],w=JSON.parse(JSON.stringify(G));w.unpackedShape=I;let E=`
${this.getUnpackedSamplerFromInput(Q,J,w).routineBody}
float ${Q}(int row, int col, int depth, int depth2, int depth3) {
return ${Q}(${_r(R,V)});
}
`;return new M(E,["coordinates.sampleTexture","coordinates.uvFromFlat"])}let{width:O,height:P}=G,N=`
float ${Q}(int row, int col, int depth, int depth2, int depth3) {
int index = row * ${F} + col * ${q} + depth * ${z} +
depth3 * ${K} + depth2;
vec2 uv = uvFromFlat(${O}, ${P}, index);
return sampleTexture(${J}, uv);
}
`;return new M(N,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(Q,J,G){let H=G.unpackedShape,K=H[5],z=H[4]*K,q=H[3]*z,F=H[2]*q,D=H[1]*F,{newShape:V,keptDims:O}=vr(H);if(V.length<H.length){let R=yr(H,V),w=["row","col","depth","depth2","depth3","depth4"],E=JSON.parse(JSON.stringify(G));E.unpackedShape=R;let T=`
${this.getUnpackedSamplerFromInput(Q,J,E).routineBody}
float ${Q}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${Q}(${_r(w,O)});
}
`;return new M(T,["coordinates.sampleTexture","coordinates.uvFromFlat"])}let{width:P,height:N}=G,I=`
float ${Q}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = row * ${D} + col * ${F} + depth * ${q} +
depth2 * ${z} + depth3 * ${K} + depth4;
vec2 uv = uvFromFlat(${P}, ${N}, index);
return sampleTexture(${J}, uv);
}
`;return new M(I,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}toVec(){let Q=this.context.outputTextureLayout,J=Q.shape.length,G=Q.strides,H=Q.width,K=Q.height,z=[];for(let F=0;F<J-1;++F)z.push(`
c[${F}] = offset / ${G[F]};`),z.push(`
offset -= c[${F}] * ${G[F]};`);z.push(`
c[${J-1}] = offset;`);let q=`
void toVec(vec2 texCoords, out int c[${J}]) {
int offset = coordsToOffset(texCoords, ${H}, ${K});
${z.join("")}
}
void toVec(int offset, out int c[${J}]) {
${z.join("")}
}
`;return{toVec:new M(q,["coordinates.coordsToOffset"])}}valueFrom(){let Q={};return this.context.programInfo.inputNames.forEach((J,G)=>{let H=this.context.inputTextureLayouts[G],K=(H.unpackedShape.length>0?H.unpackedShape:H.shape).length,z=`_${J}`;Q[z]=new M(this.getValueFromSingle(J,K,H.width,H.height,!1),[`shapeUtils.indicesToOffset${z}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),z=z+"_T",Q[z]=new M(this.getValueFromSingle(J,K,H.width,H.height,!0),[`shapeUtils.indicesToOffset${z}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])}),Q}getValueFromSingle(Q,J,G,H,K){let z=`_${Q}`;K&&(z=z+"_T");let q=j(this.context.glContext.version);return`
float ${z}(int m[${J}]) {
int offset = indicesToOffset${z}(m);
vec2 coords = offsetToCoords(offset, ${G}, ${H});
float value = getColorAsFloat(${q.texture2D}(${Q}, coords));
return value;
}
`}getPackedValueFrom(Q,J,G,H,K){let z=`_${Q}_Pack`;K&&(z=z+"_T");let q=j(this.context.glContext.version);return`
vec4 ${z}(int m[${J}]) {
int offset = indicesToOffset_${Q}(m);
vec2 coords = offsetToCoords(offset, ${G}, ${H});
return ${q.texture2D}(${Q}, coords);
}
`}}}),ni,cm=$(()=>{An(),ni=class Q extends gt{constructor(J){super(J)}getFunctions(){return{...this.encodeFloat32(),...this.decodeFloat32()}}getCustomTypes(){return{}}encodeFloat32(){return{encode:new M(`highp vec4 encode(highp float f) {
return vec4(f, 0.0, 0.0, 0.0);
}
`)}}decodeFloat32(){return{decode:new M(`highp float decode(highp vec4 rgba) {
return rgba.r;
}
`)}}encodeUint8(){let J=Q.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new M(`
highp vec4 encode(highp float f) {
highp float F = abs(f);
highp float Sign = step(0.0,-f);
highp float Exponent = floor(log2(F));
highp float Mantissa = (exp2(- Exponent) * F);
Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));
highp vec4 rgba;
rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));
rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);
rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));
rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));
${J}
rgba = rgba / 255.0; // values need to be normalized to [0,1]
return rgba;
}
`)}}decodeUint8(){let J=Q.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new M(`
highp float decode(highp vec4 rgba) {
rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]
${J}
highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;
highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;
highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);
highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));
return Result;
}
`)}}static isLittleEndian(){let J=new ArrayBuffer(4),G=new Uint32Array(J),H=new Uint8Array(J);if(G[0]=3735928559,H[0]===239)return!0;if(H[0]===222)return!1;throw Error("unknown endianness")}}}),ri,dm=$(()=>{An(),De(),ri=class extends gt{constructor(Q){super(Q)}getFunctions(){return{...this.setFragColor(),...this.getColorAsFloat()}}getCustomTypes(){return{}}setFragColor(){let Q=j(this.context.glContext.version);return{setFragColor:new M(`
void setFragColor(float value) {
${Q.output} = encode(value);
}
`,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new M(`
float getColorAsFloat(vec4 color) {
return decode(color);
}
`,["encoding.decode"])}}}}),oi,pm=$(()=>{An(),oi=class Q extends gt{constructor(J){super(J)}getFunctions(){return{...this.bcastIndex(),...this.bcastMatmulIndex(),...this.offsetToIndices(),...this.indicesToOffset(),...this.incrementIndices()}}getCustomTypes(){return{}}bcastIndex(){let J=this.context.outputTextureLayout.shape.length,G={};return this.context.programInfo.inputNames.forEach((H,K)=>{let z=this.context.inputTextureLayouts[K].unpackedShape;if(z.length<=J){let q=z.length,F=J-q,D=`bcastIndices_${H}`,V="";for(let P=0;P<q;++P)V+=`
realIndices[${P}] = int( mod(float(bcastedIndices[${F+P}]), ${z[P]}.0) );
`;let O=`
void ${D} (int bcastedIndices[${J}], out int realIndices[${q}]) {
${V}
}
`;G[D]=new M(O)}}),G}bcastMatmulIndex(){let J=this.context.outputTextureLayout.shape.length,G={};return this.context.programInfo.inputNames.forEach((H,K)=>{let z=this.context.inputTextureLayouts[K].shape;if(!(z.length<2||z.length>J)){let q=z.length,F=J-q,D=`bcastMatmulIndices_${H}`,V="";for(let P=0;P<q-2;++P)V+=`
realIndices[${P}] = int( mod(float(bcastedIndices[${F+P}]), ${z[P]}.0) );
`;let O=`
void ${D}(int bcastedIndices[${J}], out int realIndices[${q}]) {
${V}
realIndices[${q-1}] = bcastedIndices[${J-1}];
realIndices[${q-2}] = bcastedIndices[${J-2}];
}
`;G[D]=new M(O)}}),G}indicesToOffset(){let J={};return this.context.programInfo.inputNames.forEach((G,H)=>{let K=this.context.inputTextureLayouts[H].shape,z=this.context.inputTextureLayouts[H].strides,q=K.length,F=`indicesToOffset_${G}`;J[F]=new M(Q.indexToOffsetSingle(F,q,z)),F=`indicesToOffset_${G}_T`,J[F]=new M(Q.indexToOffsetSingle(F,q,z.slice().reverse()))}),J}static indexToOffsetSingle(J,G,H){let K="";for(let z=G-1;z>=0;--z)K+=`
offset += indices[${z}] * ${H[z]};
`;return`
int ${J}(int indices[${G}]) {
int offset = 0;
${K}
return offset;
}
`}offsetToIndices(){let J={};return this.context.programInfo.inputNames.forEach((G,H)=>{let K=this.context.inputTextureLayouts[H].shape,z=this.context.inputTextureLayouts[H].strides,q=K.length,F=`offsetToIndices_${G}`;J[F]=new M(Q.offsetToIndicesSingle(F,q,z)),F=`offsetToIndices_${G}_T`,J[F]=new M(Q.offsetToIndicesSingle(F,q,z.slice().reverse()))}),J}static offsetToIndicesSingle(J,G,H){let K=[];for(let z=0;z<G-1;++z)K.push(`
indices[${z}] = offset / ${H[z]};`),K.push(`
offset -= indices[${z}] * ${H[z]};`);return K.push(`
indices[${G-1}] = offset;`),`
void ${J}(int offset, out int indices[${G}]) {
${K.join("")}
}
`}incrementIndices(){let J={};return this.context.programInfo.inputNames.forEach((G,H)=>{let K=this.context.inputTextureLayouts[H].shape,z=K.length,q=`incrementIndices_${G}`,F="";for(let V=0;V<z;++V)F+=`
shape[${V}] = ${K[V]};`;let D=`
void ${q}(int axis, out int indices[${z}]) {
int shape[${z}];
${F};
for(int i = ${z} -1 ; i >= 0; --i) {
if(i > axis) continue;
indices[i] += 1;
if(indices[i] < shape[i]) {
break;
}
indices[i] = 0;
}
}
`;J[q]=new M(D)}),J}}}),ii,fm=$(()=>{An(),ii=class extends gt{constructor(Q){super(Q)}getCustomTypes(){return{}}getFunctions(){return{...this.binaryVecFunctions(),...this.copyVec(),...this.setVecItem(),...this.getVecItem()}}binaryVecFunctions(){let Q=this.context.outputTextureLayout.shape.length,J={add:"+=",sub:"-=",mul:"*=",div:"/="},G={};for(let H in J){let K=`${H}Vec`,z="";for(let F=0;F<Q;++F)z+=`
dest[${F}] ${J[H]} src[${F}];
`;let q=`
void ${K}(int src[${Q}], out int dest[${Q}]) {
${z}
}
`;G[K]=new M(q)}return G}copyVec(){let Q=this.context.outputTextureLayout.shape.length,J="";for(let H=0;H<Q;++H)J+=`
dest[${H}] = src[${H}];
`;let G=`
void copyVec(int src[${Q}], out int dest[${Q}]) {
${J}
}
`;return{copyVec:new M(G)}}setVecItem(){let Q=this.context.outputTextureLayout.shape.length,J=`
if(index < 0)
index =${Q} + index;
if (index == 0)
m[0] = value;
`;for(let H=1;H<Q-1;++H)J+=`
else if (index == ${H})
m[${H}] = value;
`;J+=`
else
m[${Q-1}] = value;
`;let G=`
void setVecItem(out int m[${Q}], int index, int value) {
${J}
}
`;return{setVecItem:new M(G)}}getVecItem(){let Q=this.context.outputTextureLayout.shape.length,J=`
if(index < 0)
index = ${Q} + index;
if (index == 0)
return m[0];
`;for(let H=1;H<Q-1;++H)J+=`
else if (index == ${H})
return m[${H}];
`;J+=`
else
return m[${Q-1}];
`;let G=`
int getVecItem(int m[${Q}], int index) {
${J}
}
`;return{getVecItem:new M(G)}}}}),Ou,hm=$(()=>{lm(),cm(),dm(),pm(),fm(),Ou={encoding:ni,fragcolor:ri,vec:ii,shapeUtils:oi,coordinates:ti}}),ai,mm=$(()=>{An(),sm(),hm(),De(),ai=class{constructor(Q,J,G,H){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new Wo(Q,J,G,H),Object.keys(Ou).forEach((z)=>{let q=new Ou[z](this.context);this.libs[z]=q});let K=this.glslLibRoutineDependencyGraph;for(let z in this.libs){let q=this.libs[z].getFunctions();for(let F in q){let D=z+"."+F,V;K[D]?(V=K[D],V.routineBody=q[F].routineBody):(V=new Kr(D,q[F].routineBody),K[D]=V);let O=q[F].dependencies;if(O)for(let P=0;P<O.length;++P)if(K[O[P]])V.addDependency(K[O[P]]);else{let N=new Kr(O[P]);K[O[P]]=N,V.addDependency(N)}}}}preprocess(){let Q=this.context.programInfo,J=Q.shaderSource;return this.context.programInfo.hasMain||(J=`${J}
${Kd(this.context.glContext.version,this.context.outputTextureLayout.shape.length)}`),J=am(J),`${jd(this.context.glContext.version)}
${this.getUniforms(Q.inputNames,Q.variables)}
${this.getImports(J)}
${J}`}getImports(Q){let J=this.selectGlslLibRoutinesToBeIncluded(Q);if(J.length===0)return"";let G="";for(let H=0;H<J.length;++H)if(J[H].routineBody)G+=J[H].routineBody+`
`;else throw Error(`Missing body for the Glsl Library routine: ${J[H].name}`);return G}selectGlslLibRoutinesToBeIncluded(Q){let J=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach((G)=>{let H=G.split(".")[1];Q.indexOf(H)!==-1&&J.push(this.glslLibRoutineDependencyGraph[G])}),Ho.returnOrderedNodes(J)}getUniforms(Q,J){let G=[];if(Q)for(let H of Q)G.push(`uniform sampler2D ${H};`);if(J)for(let H of J)G.push(`uniform ${H.type} ${H.name}${H.arrayLength?`[${H.arrayLength}]`:""};`);return G.join(`
`)}}}),si,gm=$(()=>{qe(),ct(),mm(),De(),si=class{constructor(Q,J,G){this.profiler=Q,this.glContext=J,this.textureLayoutStrategy=G,this.repo=new Map,this.attributesBound=!1}getArtifact(Q){return this.repo.get(Q)}setArtifact(Q,J){this.repo.set(Q,J)}run(Q,J,G){this.profiler.event("op",`ProgramManager.run ${Q.programInfo.name??"unknown kernel"}`,()=>{let H=this.glContext.gl,K=Q.program;H.useProgram(K);try{this.bindOutput(G),this.attributesBound||this.bindAttributes(Q.attribLocations),this.bindUniforms(Q.uniformLocations,Q.programInfo.variables??[],J)}catch(z){throw Te.error("ProgramManager",Q.programInfo.shaderSource),z}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((Q)=>this.glContext.deleteProgram(Q.program))}build(Q,J,G){return this.profiler.event("backend","ProgramManager.build",()=>{let H=new ai(this.glContext,Q,J,G),K=H.preprocess(),z=this.compile(K);return{programInfo:Q,program:z,uniformLocations:this.getUniformLocations(z,H.context.programInfo.inputNames,H.context.programInfo.variables),attribLocations:this.getAttribLocations(z)}})}compile(Q){if(!this.vertexShader){Te.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");let H=qd(this.glContext.version);this.vertexShader=this.glContext.compileShader(H,this.glContext.gl.VERTEX_SHADER)}Y.debug&&Te.verbose("ProrgramManager",`FragShader:
${Q}
`);let J=this.glContext.compileShader(Q,this.glContext.gl.FRAGMENT_SHADER),G=this.glContext.createProgram(this.vertexShader,J);return this.glContext.deleteShader(J),G}bindOutput(Q){let{width:J,height:G}=Q;Te.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${J}/${G}, shape=${Q.shape}, type=${Q.tensor.type}`),this.glContext.attachFramebuffer(Q.texture,J,G)}bindAttributes(Q){let{position:J,textureCoord:G}=Q;this.glContext.setVertexAttributes(J,G),this.attributesBound=!0}bindUniforms(Q,J,G){let H=this.glContext.gl,K=0;for(let{name:z,type:q,location:F,arrayLength:D}of Q){let V=J.find((O)=>O.name===z)?.data;if(q!=="sampler2D"&&!V)throw Error(`variable '${z}' does not have data defined in program info`);switch(q){case"sampler2D":this.bindTexture(G[K],F,K),K++;break;case"float":D?H.uniform1fv(F,V):H.uniform1f(F,V);break;case"int":D?H.uniform1iv(F,V):H.uniform1i(F,V);break;default:throw Error(`Uniform not implemented: ${q}`)}}}bindTexture(Q,J,G){this.glContext.bindTextureToUniform(Q.texture,G,J)}getAttribLocations(Q){return{position:this.getAttribLocation(Q,"position"),textureCoord:this.getAttribLocation(Q,"textureCoord")}}getUniformLocations(Q,J,G){let H=[];if(J)for(let K of J)H.push({name:K,type:"sampler2D",location:this.getUniformLocation(Q,K)});if(G)for(let K of G)H.push({...K,location:this.getUniformLocation(Q,K.name)});return H}getUniformLocation(Q,J){let G=this.glContext.gl.getUniformLocation(Q,J);if(G===null)throw Error(`Uniform ${J} not found.`);return G}getAttribLocation(Q,J){return this.glContext.gl.getAttribLocation(Q,J)}}}),ui,bm=$(()=>{ct(),qr(),ui=class{constructor(Q,J,G,H){this.glContext=Q,this.layoutStrategy=J,this.profiler=G,this.config=H,this.pendingRead=new Map,H.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(Q,J,G,H){let K=this.toEncoderType(Q),z=this.glContext.getEncoder(K,J.channels||1,H);if(J.isPacked&&H===1)throw Error("not implemented");let{width:q,height:F}=J,D,V;if(this.config.reuseTextures){D=`${q}x${F}_${z.format}_${z.internalFormat}_${z.textureType}`,V=this.inUseTextures.get(D),V||(V=[],this.inUseTextures.set(D,V));let P=this.idleTextures.get(D);if(P&&P.length>0){let N=P.pop();return V.push(N),H===1&&this.glContext.updateTexture(N,q,F,z,this.toTextureData(Q,G)),N}}Te.verbose("TextureManager",`Creating new texture of size ${J.width}x${J.height}`);let O=this.glContext.allocateTexture(q,F,z,this.toTextureData(Q,G));return this.config.reuseTextures&&(V.push(O),this.textureLookup.set(O,D)),O}readTexture(Q,J,G){return G||(G=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let H=Q.shape.reduce((z,q)=>z*q)*G,K=this.glContext.readTexture(Q.texture,Q.width,Q.height,H,this.toEncoderType(J),G);return this.toTensorData(J,K)})}async readTextureAsync(Q,J,G){let H=Q.tensor.dataId;if(G||(G=1),this.pendingRead.has(H)){let K=this.pendingRead.get(H);return new Promise((z)=>K?.push(z))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(H,[]);let K=Q.shape.reduce((D,V)=>D*V)*G;await this.glContext.createAndWaitForFence();let z=this.glContext.readTexture(Q.texture,Q.width,Q.height,K,this.toEncoderType(J),G),q=this.toTensorData(J,z),F=this.pendingRead.get(H);return this.pendingRead.delete(H),F?.forEach((D)=>D(q)),q})}readUint8TextureAsFloat(Q){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let J=Q.shape.reduce((H,K)=>H*K),G=this.glContext.readTexture(Q.texture,Q.width,Q.height,J*4,"byte",4);return new Float32Array(G.buffer,G.byteOffset,J)})}releaseTexture(Q,J){let G;if(this.config.reuseTextures&&(G=this.textureLookup.get(Q.texture),G)){J&&this.textureLookup.delete(G);let H=this.inUseTextures.get(G);if(H){let K=H.indexOf(Q.texture);if(K!==-1){H.splice(K,1);let z=this.idleTextures.get(G);z||(z=[],this.idleTextures.set(G,z)),z.push(Q.texture)}}}(!G||J)&&(Te.verbose("TextureManager",`Deleting texture of size ${Q.width}x${Q.height}`),this.glContext.deleteTexture(Q.texture))}toTensorData(Q,J){switch(Q){case"int16":return J instanceof Int16Array?J:Int16Array.from(J);case"int32":return J instanceof Int32Array?J:Int32Array.from(J);case"int8":return J instanceof Int8Array?J:Int8Array.from(J);case"uint16":return J instanceof Uint16Array?J:Uint16Array.from(J);case"uint32":return J instanceof Uint32Array?J:Uint32Array.from(J);case"uint8":case"bool":return J instanceof Uint8Array?J:Uint8Array.from(J);case"float32":return J instanceof Float32Array?J:Float32Array.from(J);case"float64":return J instanceof Float64Array?J:Float64Array.from(J);default:throw Error(`TensorData type ${Q} is not supported`)}}toTextureData(Q,J){if(J)return J instanceof Float32Array?J:new Float32Array(J)}toEncoderType(Q){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}}),li,ym=$(()=>{ct(),ac(),lp(),om(),gm(),Pu(),bm(),li=class{constructor(Q,J){this.backend=Q,this.context=J,this.layoutStrategy=new ei(Q.glContext.maxTextureSize),this.programManager=new si(this.context.profiler,Q.glContext,this.layoutStrategy),this.textureManager=new ui(Q.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:Q.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=Q.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Uo(this)}onGraphInitialized(Q){let J=Q.getValues().filter((G)=>G.from===-1&&G.tensor).map((G)=>G.tensor.dataId);this.initializers=new Set(J)}isInitializer(Q){return this.initializers?this.initializers.has(Q):!1}addInitializer(Q){this.initializers.add(Q)}getTextureData(Q,J){return J?this.packedTextureDataCache.get(Q):this.unpackedTextureDataCache.get(Q)}setTextureData(Q,J,G=!1){Te.verbose("WebGLSessionHandler","Storing Texture data in cache"),G?this.packedTextureDataCache.set(Q,J):this.unpackedTextureDataCache.set(Q,J)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((Q)=>this.textureManager.releaseTexture(Q,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((Q)=>this.textureManager.releaseTexture(Q,!0)),this.unpackedTextureDataCache=new Map}resolve(Q,J,G){let H=ic(Q,J,rm);return{impl:H.opImpl,context:H.opInit?H.opInit(Q,G):Q}}}});function yS(Q){let J=0;for(;J<Q.length&&Q[J]();++J);return J-1}var Jr,_m=$(()=>{qe(),qr(),qr(),dn(),Jr=class{constructor(Q,J){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=Q,this.version=J,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(Q,J,G,H){let K=this.gl,z=K.createTexture();K.bindTexture(K.TEXTURE_2D,z),K.texParameteri(K.TEXTURE_2D,K.TEXTURE_MIN_FILTER,K.NEAREST),K.texParameteri(K.TEXTURE_2D,K.TEXTURE_MAG_FILTER,K.NEAREST),K.texParameteri(K.TEXTURE_2D,K.TEXTURE_WRAP_S,K.CLAMP_TO_EDGE),K.texParameteri(K.TEXTURE_2D,K.TEXTURE_WRAP_T,K.CLAMP_TO_EDGE);let q=H?G.encode(H,Q*J):null;return K.texImage2D(K.TEXTURE_2D,0,G.internalFormat,Q,J,0,G.format,G.textureType,q),this.checkError(),z}updateTexture(Q,J,G,H,K){let z=this.gl;z.bindTexture(z.TEXTURE_2D,Q);let q=H.encode(K,J*G);z.texSubImage2D(z.TEXTURE_2D,0,0,0,J,G,H.format,H.textureType,q),this.checkError()}attachFramebuffer(Q,J,G){let H=this.gl;H.bindTexture(H.TEXTURE_2D,Q),H.bindFramebuffer(H.FRAMEBUFFER,this.framebuffer),H.framebufferTexture2D(H.FRAMEBUFFER,H.COLOR_ATTACHMENT0,H.TEXTURE_2D,Q,0),this.checkError(),H.viewport(0,0,J,G),H.scissor(0,0,J,G)}readTexture(Q,J,G,H,K,z){let q=this.gl;z||(z=1),this.frameBufferBound||this.attachFramebuffer(Q,J,G);let F=this.getEncoder(K,z),D=F.allocate(J*G);return q.bindTexture(q.TEXTURE_2D,Q),q.framebufferTexture2D(q.FRAMEBUFFER,q.COLOR_ATTACHMENT0,q.TEXTURE_2D,Q,0),q.readPixels(0,0,J,G,q.RGBA,F.textureType,D),this.checkError(),F.decode(D,H)}isFramebufferReady(){return!0}getActiveTexture(){let Q=this.gl;return`TEXTURE${Q.getParameter(this.gl.ACTIVE_TEXTURE)-Q.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(Q,J){let G=this.gl;G.vertexAttribPointer(Q,3,G.FLOAT,!1,20,0),G.enableVertexAttribArray(Q),J!==-1&&(G.vertexAttribPointer(J,2,G.FLOAT,!1,20,12),G.enableVertexAttribArray(J)),this.checkError()}createProgram(Q,J){let G=this.gl,H=G.createProgram();return G.attachShader(H,Q),G.attachShader(H,J),G.linkProgram(H),H}compileShader(Q,J){let G=this.gl,H=G.createShader(J);if(!H)throw Error(`createShader() returned null with type ${J}`);if(G.shaderSource(H,Q),G.compileShader(H),G.getShaderParameter(H,G.COMPILE_STATUS)===!1)throw Error(`Failed to compile shader: ${G.getShaderInfoLog(H)}
Shader source:
${Q}`);return H}deleteShader(Q){this.gl.deleteShader(Q)}bindTextureToUniform(Q,J,G){let H=this.gl;H.activeTexture(H.TEXTURE0+J),this.checkError(),H.bindTexture(H.TEXTURE_2D,Q),this.checkError(),H.uniform1i(G,J),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(Y.debug){let Q=this.gl,J=Q.getError(),G="";switch(J){case Q.NO_ERROR:return;case Q.INVALID_ENUM:G="INVALID_ENUM";break;case Q.INVALID_VALUE:G="INVALID_VALUE";break;case Q.INVALID_OPERATION:G="INVALID_OPERATION";break;case Q.INVALID_FRAMEBUFFER_OPERATION:G="INVALID_FRAMEBUFFER_OPERATION";break;case Q.OUT_OF_MEMORY:G="OUT_OF_MEMORY";break;case Q.CONTEXT_LOST_WEBGL:G="CONTEXT_LOST_WEBGL";break;default:G=`Unknown WebGL Error: ${J.toString(16)}`}throw Error(G)}}deleteTexture(Q){this.gl.deleteTexture(Q)}deleteProgram(Q){this.gl.deleteProgram(Q)}getEncoder(Q,J,G=0){if(this.version===2)return new Vo(this.gl,J);switch(Q){case"float":return G===1||this.isRenderFloat32Supported?new Hr(this.gl,J):new Hr(this.gl,J,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw Error("not implemented");case"byte":return new Go(this.gl,J);default:throw Error(`Invalid dataType: ${Q}`)}}clearActiveTextures(){let Q=this.gl;for(let J=0;J<this.maxTextureImageUnits;++J)Q.activeTexture(Q.TEXTURE0+J),Q.bindTexture(Q.TEXTURE_2D,null)}dispose(){if(this.disposed)return;let Q=this.gl;Q.bindFramebuffer(Q.FRAMEBUFFER,null),Q.deleteFramebuffer(this.framebuffer),Q.bindBuffer(Q.ARRAY_BUFFER,null),Q.deleteBuffer(this.vertexbuffer),Q.bindBuffer(Q.ELEMENT_ARRAY_BUFFER,null),Q.finish(),this.disposed=!0}createDefaultGeometry(){return new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0])}createVertexbuffer(){let Q=this.gl,J=Q.createBuffer();if(!J)throw Error("createBuffer() returned null");let G=this.createDefaultGeometry();return Q.bindBuffer(Q.ARRAY_BUFFER,J),Q.bufferData(Q.ARRAY_BUFFER,G,Q.STATIC_DRAW),this.checkError(),J}createFramebuffer(){let Q=this.gl.createFramebuffer();if(!Q)throw Error("createFramebuffer returned null");return Q}queryVitalParameters(){let Q=this.gl;if(this.isFloatTextureAttachableToFrameBuffer=this.checkFloatTextureAttachableToFrameBuffer(),this.isRenderFloat32Supported=this.checkRenderFloat32(),this.isFloat32DownloadSupported=this.checkFloat32Download(),this.version===1&&!this.textureHalfFloatExtension&&!this.isRenderFloat32Supported)throw Error("both float32 and float16 TextureType are not supported");this.isBlendSupported=!this.isRenderFloat32Supported||this.checkFloat32Blend(),this.maxTextureSize=Q.getParameter(Q.MAX_TEXTURE_SIZE),this.maxTextureImageUnits=Q.getParameter(Q.MAX_TEXTURE_IMAGE_UNITS),this.version}getExtensions(){this.version===2?(this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float"),this.disjointTimerQueryWebgl2Extension=this.gl.getExtension("EXT_disjoint_timer_query_webgl2")):(this.textureFloatExtension=this.gl.getExtension("OES_texture_float"),this.textureHalfFloatExtension=this.gl.getExtension("OES_texture_half_float"))}checkFloatTextureAttachableToFrameBuffer(){let Q=this.gl,J=Q.createTexture();Q.bindTexture(Q.TEXTURE_2D,J);let G=this.version===2?Q.RGBA32F:Q.RGBA;Q.texImage2D(Q.TEXTURE_2D,0,G,1,1,0,Q.RGBA,Q.FLOAT,null);let H=Q.createFramebuffer();Q.bindFramebuffer(Q.FRAMEBUFFER,H),Q.framebufferTexture2D(Q.FRAMEBUFFER,Q.COLOR_ATTACHMENT0,Q.TEXTURE_2D,J,0);let K=Q.checkFramebufferStatus(Q.FRAMEBUFFER)===Q.FRAMEBUFFER_COMPLETE;return Q.bindTexture(Q.TEXTURE_2D,null),Q.bindFramebuffer(Q.FRAMEBUFFER,null),Q.deleteTexture(J),Q.deleteFramebuffer(H),K}checkRenderFloat32(){if(this.version===2){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension)return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Download(){if(this.version===2){if(!this.colorBufferFloatExtension)return!1}else if(!this.textureFloatExtension||!this.gl.getExtension("WEBGL_color_buffer_float"))return!1;return this.isFloatTextureAttachableToFrameBuffer}checkFloat32Blend(){let Q=this.gl,J,G,H,K,z;try{J=Q.createTexture(),G=Q.createFramebuffer(),Q.bindTexture(Q.TEXTURE_2D,J);let q=this.version===2?Q.RGBA32F:Q.RGBA;return Q.texImage2D(Q.TEXTURE_2D,0,q,1,1,0,Q.RGBA,Q.FLOAT,null),Q.bindFramebuffer(Q.FRAMEBUFFER,G),Q.framebufferTexture2D(Q.FRAMEBUFFER,Q.COLOR_ATTACHMENT0,Q.TEXTURE_2D,J,0),Q.enable(Q.BLEND),H=Q.createShader(Q.VERTEX_SHADER),!H||(Q.shaderSource(H,"void main(){}"),Q.compileShader(H),K=Q.createShader(Q.FRAGMENT_SHADER),!K)||(Q.shaderSource(K,"precision highp float;void main(){gl_FragColor=vec4(0.5);}"),Q.compileShader(K),z=Q.createProgram(),!z)?!1:(Q.attachShader(z,H),Q.attachShader(z,K),Q.linkProgram(z),Q.useProgram(z),Q.drawArrays(Q.POINTS,0,1),Q.getError()===Q.NO_ERROR)}finally{Q.disable(Q.BLEND),z&&Q.deleteProgram(z),H&&Q.deleteShader(H),K&&Q.deleteShader(K),G&&(Q.bindFramebuffer(Q.FRAMEBUFFER,null),Q.deleteFramebuffer(G)),J&&(Q.bindTexture(Q.TEXTURE_2D,null),Q.deleteTexture(J))}}beginTimer(){if(this.version===2&&this.disjointTimerQueryWebgl2Extension){let Q=this.gl,J=this.disjointTimerQueryWebgl2Extension,G=Q.createQuery();return Q.beginQuery(J.TIME_ELAPSED_EXT,G),G}else throw Error("WebGL1 profiling currently not supported.")}endTimer(){if(this.version===2&&this.disjointTimerQueryWebgl2Extension){let Q=this.gl,J=this.disjointTimerQueryWebgl2Extension;Q.endQuery(J.TIME_ELAPSED_EXT);return}else throw Error("WebGL1 profiling currently not supported")}isTimerResultAvailable(Q){let J=!1,G=!1;if(this.version===2&&this.disjointTimerQueryWebgl2Extension){let H=this.gl,K=this.disjointTimerQueryWebgl2Extension;J=H.getQueryParameter(Q,H.QUERY_RESULT_AVAILABLE),G=H.getParameter(K.GPU_DISJOINT_EXT)}else throw Error("WebGL1 profiling currently not supported");return J&&!G}getTimerResult(Q){let J=0;if(this.version===2){let G=this.gl;J=G.getQueryParameter(Q,G.QUERY_RESULT),G.deleteQuery(Q)}else throw Error("WebGL1 profiling currently not supported");return J/1e6}async waitForQueryAndGetTime(Q){return await eu(()=>this.isTimerResultAvailable(Q)),this.getTimerResult(Q)}async createAndWaitForFence(){let Q=this.createFence(this.gl);return this.pollFence(Q)}createFence(Q){let J,G=Q,H=G.fenceSync(G.SYNC_GPU_COMMANDS_COMPLETE,0);return Q.flush(),H===null?J=()=>!0:J=()=>{let K=G.clientWaitSync(H,0,0);return K===G.ALREADY_SIGNALED||K===G.CONDITION_SATISFIED},{query:H,isFencePassed:J}}async pollFence(Q){return new Promise((J)=>{this.addItemToPoll(()=>Q.isFencePassed(),()=>J())})}pollItems(){let Q=yS(this.itemsToPoll.map((J)=>J.isDoneFn));for(let J=0;J<=Q;++J){let{resolveFn:G}=this.itemsToPoll[J];G()}this.itemsToPoll=this.itemsToPoll.slice(Q+1)}async addItemToPoll(Q,J){this.itemsToPoll.push({isDoneFn:Q,resolveFn:J}),!(this.itemsToPoll.length>1)&&await eu(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function Eu(Q){let J;if((!Q||Q==="webgl2")&&"webgl2"in Ir?J=Ir.webgl2:(!Q||Q==="webgl")&&("webgl"in Ir)&&(J=Ir.webgl),!J)try{let H=xS();J=xm(H,Q)}catch{let H=_S();J=xm(H,Q)}Q=Q||J.version===1?"webgl":"webgl2";let G=J.gl;return Ir[Q]=J,G.isContextLost()?(delete Ir[Q],Eu(Q)):(G.disable(G.DEPTH_TEST),G.disable(G.STENCIL_TEST),G.disable(G.BLEND),G.disable(G.DITHER),G.disable(G.POLYGON_OFFSET_FILL),G.disable(G.SAMPLE_COVERAGE),G.enable(G.SCISSOR_TEST),G.enable(G.CULL_FACE),G.cullFace(G.BACK),J)}function xm(Q,J){let G={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},H,K=G;if((!J||J==="webgl2")&&(H=Q.getContext("webgl2",K),H))try{return new Jr(H,2)}catch(z){Te.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${z}`)}if((!J||J==="webgl")&&(H=Q.getContext("webgl",K)||Q.getContext("experimental-webgl",K),H))try{return new Jr(H,1)}catch(z){Te.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${z}`)}throw Error("WebGL is not supported")}function _S(){if(typeof document>"u")throw TypeError("failed to create canvas: document is not supported");let Q=document.createElement("canvas");return Q.width=1,Q.height=1,Q}function xS(){if(typeof OffscreenCanvas>"u")throw TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var Ir,wm=$(()=>{ct(),_m(),Ir={}}),ci,Tm=$(()=>{qe(),ct(),ym(),wm(),ci=class{get contextId(){return Y.webgl.contextId}set contextId(Q){Y.webgl.contextId=Q}get matmulMaxBatchSize(){return Y.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(Q){Y.webgl.matmulMaxBatchSize=Q}get textureCacheMode(){return Y.webgl.textureCacheMode}set textureCacheMode(Q){Y.webgl.textureCacheMode=Q}get pack(){return Y.webgl.pack}set pack(Q){Y.webgl.pack=Q}get async(){return Y.webgl.async}set async(Q){Y.webgl.async=Q}initialize(){try{return this.glContext=Eu(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),Te.setWithEnv(Y),Y.webgl.context||Object.defineProperty(Y.webgl,"context",{value:this.glContext.gl}),Te.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(Q){return Te.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${Q}`),!1}}createSessionHandler(Q){return new li(this,Q)}dispose(){this.glContext.dispose()}}});async function Cu(Q){if(Q){let J=typeof Q=="string"?[Q]:Q;for(let G of J){let H=vm.get(G);if(H)return H;let K=await TS(G);if(K)return K}}else return Cu(["webgl"]);throw Error("no available backend to use")}async function TS(Q){let J=wS;if(typeof J[Q]<"u"&&vS(J[Q])){let G=J[Q],H=G.initialize();if(typeof H=="object"&&"then"in H&&(H=await H),H)return vm.set(Q,G),G}}function vS(Q){let J=Q;return"initialize"in J&&typeof J.initialize=="function"&&"createSessionHandler"in J&&typeof J.createSessionHandler=="function"&&"dispose"in J&&typeof J.dispose=="function"}var vm,wS,Im=$(()=>{Tm(),vm=new Map,wS={webgl:new ci}}),Du,di,Sm=$(()=>{ct(),Du=class{constructor(Q,J){this.op=Q,this.node=J}},di=class{constructor(Q,J,G){this.graph=Q,this.profiler=G,this.initialize(J)}initialize(Q){this.profiler.event("session","ExecutionPlan.initialize",()=>{let J=this.graph.getNodes();if(J.length!==Q.length)throw Error("The size of nodes and OPs do not match.");this._ops=Q.map((G,H)=>new Du(G,J[H])),this.reset(),this._starter=[],this._ops.forEach((G,H)=>{let K=!0;for(let z of G.node.inputs)if(!this._values[z]&&this.graph.getInputIndices().indexOf(z)===-1){K=!1;break}K&&this._starter.push(H)})})}reset(){this._values=this.graph.getValues().map((Q)=>Q.tensor)}async execute(Q,J){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let G=Q.createInferenceHandler(),H=this.graph.getInputIndices();if(J.length!==H.length)throw Error(`number of input tensors don't match the number of inputs to the model: actual: ${J.length} expected: ${H.length}`);J.forEach((V,O)=>{let P=H[O];this._values[P]=V});let K=this._starter.slice(0),z=this.graph.getValues(),q=this.graph.getNodes(),F=0;for(;F<K.length;){let V=K[F++],O=this._ops[V],P=O.node.inputs.map((w)=>this._values[w]);if(P.indexOf(void 0)!==-1)throw Error(`unresolved input detected: op: ${O.node}`);let N=P;Te.verbose("ExecPlan",`Running op:${O.node.name} (${N.map((w,E)=>`'${O.node.inputs[E]}': ${w.type}[${w.dims.join(",")}]`).join(", ")})`);let I=await this.profiler.event("node",O.node.name,async()=>O.op.impl(G,N,O.op.context));if(I.length!==O.node.outputs.length)throw Error("the size of output does not match model definition.");I.forEach((w,E)=>{let T=O.node.outputs[E];if(this._values[T])throw Error(`output [${T}] already has value: op:${O.node.name}`);this._values[T]=w});let R=new Set;I.forEach((w,E)=>{let T=O.node.outputs[E];for(let y of z[T].to){let x=q[y],b=!0;for(let g of x.inputs)if(!this._values[g]){b=!1;break}b&&R.add(y)}}),K.push(...R)}let D=[];for(let V=0;V<this.graph.getOutputIndices().length;V++){let O=this.graph.getOutputIndices()[V],P=this._values[O];if(P===void 0)throw Error(`required output [${O}] does not have value`);O===0?await P.getData():P.data,D.push(P)}return Te.verbose("ExecPlan","disposing of inferenceHandler"),G.dispose(),D})}}}),ce,Qr,$m=$(()=>{Br(),ce=ae(gr()),tr(),xe(),Qr=class Q{constructor(J){if(this._attributes=new Map,J!=null){for(let G of J)G instanceof ce.onnx.AttributeProto?this._attributes.set(G.name,[Q.getValue(G),Q.getType(G)]):G instanceof ko.Attribute&&this._attributes.set(G.name(),[Q.getValue(G),Q.getType(G)]);if(this._attributes.size<J.length)throw Error("duplicated attribute names")}}set(J,G,H){this._attributes.set(J,[H,G])}delete(J){this._attributes.delete(J)}getFloat(J,G){return this.get(J,"float",G)}getInt(J,G){return this.get(J,"int",G)}getString(J,G){return this.get(J,"string",G)}getTensor(J,G){return this.get(J,"tensor",G)}getFloats(J,G){return this.get(J,"floats",G)}getInts(J,G){return this.get(J,"ints",G)}getStrings(J,G){return this.get(J,"strings",G)}getTensors(J,G){return this.get(J,"tensors",G)}get(J,G,H){let K=this._attributes.get(J);if(K===void 0){if(H!==void 0)return H;throw Error(`required attribute not found: ${J}`)}if(K[1]!==G)throw Error(`type mismatch: expected ${G} but got ${K[1]}`);return K[0]}static getType(J){let G=J instanceof ce.onnx.AttributeProto?J.type:J.type();switch(G){case ce.onnx.AttributeProto.AttributeType.FLOAT:return"float";case ce.onnx.AttributeProto.AttributeType.INT:return"int";case ce.onnx.AttributeProto.AttributeType.STRING:return"string";case ce.onnx.AttributeProto.AttributeType.TENSOR:return"tensor";case ce.onnx.AttributeProto.AttributeType.FLOATS:return"floats";case ce.onnx.AttributeProto.AttributeType.INTS:return"ints";case ce.onnx.AttributeProto.AttributeType.STRINGS:return"strings";case ce.onnx.AttributeProto.AttributeType.TENSORS:return"tensors";default:throw Error(`attribute type is not supported yet: ${ce.onnx.AttributeProto.AttributeType[G]}`)}}static getValue(J){let G=J instanceof ce.onnx.AttributeProto?J.type:J.type();if(G===ce.onnx.AttributeProto.AttributeType.GRAPH||G===ce.onnx.AttributeProto.AttributeType.GRAPHS)throw Error("graph attribute is not supported yet");let H=this.getValueNoCheck(J);if(G===ce.onnx.AttributeProto.AttributeType.INT&&it.isLong(H))return it.longToNumber(H);if(G===ce.onnx.AttributeProto.AttributeType.INTS){let K=H,z=Array(K.length);for(let q=0;q<K.length;q++){let F=K[q];z[q]=it.longToNumber(F)}return z}if(G===ce.onnx.AttributeProto.AttributeType.TENSOR)return J instanceof ce.onnx.AttributeProto?Me.fromProto(H):Me.fromOrtTensor(H);if(G===ce.onnx.AttributeProto.AttributeType.TENSORS){if(J instanceof ce.onnx.AttributeProto)return H.map((K)=>Me.fromProto(K));if(J instanceof ko.Attribute)return H.map((K)=>Me.fromOrtTensor(K))}return G===ce.onnx.AttributeProto.AttributeType.STRING&&J instanceof ce.onnx.AttributeProto?Wr(H):G===ce.onnx.AttributeProto.AttributeType.STRINGS&&J instanceof ce.onnx.AttributeProto?H.map(Wr):H}static getValueNoCheck(J){return J instanceof ce.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(J):this.getValueNoCheckFromOrtFormat(J)}static getValueNoCheckFromOnnxFormat(J){switch(J.type){case ce.onnx.AttributeProto.AttributeType.FLOAT:return J.f;case ce.onnx.AttributeProto.AttributeType.INT:return J.i;case ce.onnx.AttributeProto.AttributeType.STRING:return J.s;case ce.onnx.AttributeProto.AttributeType.TENSOR:return J.t;case ce.onnx.AttributeProto.AttributeType.GRAPH:return J.g;case ce.onnx.AttributeProto.AttributeType.FLOATS:return J.floats;case ce.onnx.AttributeProto.AttributeType.INTS:return J.ints;case ce.onnx.AttributeProto.AttributeType.STRINGS:return J.strings;case ce.onnx.AttributeProto.AttributeType.TENSORS:return J.tensors;case ce.onnx.AttributeProto.AttributeType.GRAPHS:return J.graphs;default:throw Error(`unsupported attribute type: ${ce.onnx.AttributeProto.AttributeType[J.type]}`)}}static getValueNoCheckFromOrtFormat(J){switch(J.type()){case ht.AttributeType.FLOAT:return J.f();case ht.AttributeType.INT:return J.i();case ht.AttributeType.STRING:return J.s();case ht.AttributeType.TENSOR:return J.t();case ht.AttributeType.GRAPH:return J.g();case ht.AttributeType.FLOATS:return J.floatsArray();case ht.AttributeType.INTS:{let G=[];for(let H=0;H<J.intsLength();H++)G.push(J.ints(H));return G}case ht.AttributeType.STRINGS:{let G=[];for(let H=0;H<J.stringsLength();H++)G.push(J.strings(H));return G}case ht.AttributeType.TENSORS:{let G=[];for(let H=0;H<J.tensorsLength();H++)G.push(J.tensors(H));return G}default:throw Error(`unsupported attribute type: ${ht.AttributeType[J.type()]}`)}}}}),Lu,Ru,hn,pi,ku,Am=$(()=>{$m(),Br(),Lu=ae(gr()),tr(),xe(),Ru={from:(Q,J)=>new ku(Q,J)},hn=class{constructor(Q){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,Q&&(this.type=je.tensorValueTypeFromProto(Q.type.tensorType))}get from(){return this._from}get to(){return this._to}},pi=class{constructor(Q,J){Q instanceof Lu.onnx.NodeProto?(this.name=Q.name,this.opType=Q.opType,this.attributes=new Qr(Q.attribute)):Q instanceof Ns.Node&&(this.name=J??Q.name(),this.opType=Q.opType(),this.attributes=new Qr(je.tensorAttributesFromORTFormat(Q))),this.inputs=[],this.outputs=[],this.executeNode=!0}},ku=class{constructor(Q,J){if(!Q)throw TypeError("graph is empty");this.buildGraph(Q),this.transformGraph(J),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(Q){if(Q instanceof Lu.onnx.GraphProto)this.buildGraphFromOnnxFormat(Q);else if(Q instanceof Ls.Graph)this.buildGraphFromOrtFormat(Q);else throw TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(Q){let J=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let G=new Map;if(!Q.input)throw Error("missing information in graph: input");let H=[];for(let K of Q.input){if(J.has(K.name))throw Error(`duplicated input name: ${K.name}`);let z=this._allData.push(new hn(K))-1;J.set(K.name,z),H.push(K.name)}if(!Q.initializer)throw Error("missing information in graph: initializer");for(let K of Q.initializer){let z=J.get(K.name);if(z===void 0){let q=new hn;q.type={shape:{dims:je.tensorDimsFromProto(K.dims)},tensorType:je.tensorDataTypeFromProto(K.dataType)},z=this._allData.push(q)-1,J.set(K.name,z)}this._allData[z]._from=-1,this._allData[z].tensor=Me.fromProto(K)}for(let K=0;K<this._allData.length;K++)this._allData[K].tensor||(this._allInputIndices.push(K),this._allInputNames.push(H[K]));if(!Q.output)throw Error("missing information in graph: output");for(let K of Q.output){if(J.has(K.name))throw Error(`duplicated output name: ${K.name}`);let z=this._allData.push(new hn(K))-1;J.set(K.name,z),this._allOutputIndices.push(z),this._allOutputNames.push(K.name)}if(!Q.node)throw Error("missing information in graph: node");for(let K of Q.node){if(!K.name)for(let q=0;;q++){let F=`unnamed_${K.opType}_${q}`;if(!G.has(F)){K.name=F;break}}if(G.has(K.name))throw Error(`duplicated node name: ${K.name}`);let z=this._nodes.push(new pi(K))-1;G.set(K.name,z)}for(let K=0;K<this._nodes.length;K++){let z=this._nodes[K],q=Q.node[K];if(!q.output)throw Error(`missing output for node: ${q.name}`);for(let F of q.output){let D=J.get(F);if(typeof D>"u"&&(D=this._allData.push(new hn)-1,J.set(F,D)),z.outputs.push(D),this._allData[D]._from!==void 0)throw Error(`multiple nodes output to one data value: ${D}`);if(this._allData[D]._from=K,q.opType==="Constant"){if(!q.attribute||q.attribute.length!==1||!q.attribute[0].t)throw Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!q.output||q.output.length!==1)throw Error("missing output or incorrect number of outputs for this Constant operator");z.outputs.pop(),z.executeNode=!1,this._allData[D]._from=-1,this._allData[D].tensor=Me.fromProto(q.attribute[0].t)}}}for(let K=0;K<this._nodes.length;K++){let z=this._nodes[K],q=Q.node[K];if(!q.input)throw Error(`missing input for node: ${q.name}`);for(let F of q.input){let D=J.get(F);if(typeof D>"u"){if(F===""&&(q.input.length===3||q.input.length===4)&&q.opType==="Resize")continue;throw Error(`unrecognized input '${F}' for node: ${q.name}`)}z.inputs.push(D),this._allData[D]._to.push(K)}}return!0}buildGraphFromOrtFormat(Q){let J=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let G=new Map,H=[];for(let K=0;K<Q.inputsLength();K++){let z=Q.inputs(K);if(J.has(z))throw Error(`duplicated input name: ${z}`);for(let q=0;q<Q.nodeArgsLength();q++)if(Q.nodeArgs(q)?.name()===z){let F=new hn;if(Q.nodeArgs(q)?.type()?.valueType()!==Ms.TypeInfoValue.tensor_type)throw Error("Unexpected value type for the nodeArg.");let D=Q.nodeArgs(q).type().value(new zs.TensorTypeAndShape),V=je.tensorDataTypeFromProto(D.elemType()),O=D.shape(),P=[];for(let I=0;I<O.dimLength();I++)P.push(it.longToNumber(O.dim(I).value().dimValue()));F.type={shape:{dims:P},tensorType:V};let N=this._allData.push(F)-1;J.set(z,N),H.push(z)}}for(let K=0;K<Q.initializersLength();K++){let z=Q.initializers(K),q=J.get(z.name());if(q===void 0){let F=new hn,D=je.tensorDimsFromORTFormat(z),V=je.tensorDataTypeFromProto(z.dataType());F.type={shape:{dims:D},tensorType:V},q=this._allData.push(F)-1,J.set(z.name(),q)}this._allData[q]._from=-1,this._allData[q].tensor=Me.fromOrtTensor(z)}for(let K=0;K<this._allData.length;K++)this._allData[K].tensor||(this._allInputIndices.push(K),this._allInputNames.push(H[K]));for(let K=0;K<Q.outputsLength();K++){let z=Q.outputs(K);if(J.has(z))throw Error(`duplicated output name: ${z}`);let q=this._allData.push(new hn)-1;J.set(z,q),this._allOutputIndices.push(q),this._allOutputNames.push(z)}if(!Q.nodes)throw Error("missing information in graph: node");for(let K=0;K<Q.nodesLength();K++){let z=Q.nodes(K),q=z.name();if(!q)for(let D=0;q=`unnamed_${z.opType()}_${D}`,!!G.has(q);D++);if(G.has(q))throw Error(`duplicated node name: ${q}`);let F=this._nodes.push(new pi(z,q))-1;G.set(q,F)}for(let K=0;K<this._nodes.length;K++){let z=this._nodes[K],q=Q.nodes(K);if(q==null)throw Error(`No node exists at index ${K}`);if(q?.outputsLength()===0)throw Error(`missing output for node: ${q.name}`);for(let F=0;F<q?.outputsLength();F++){let D=q?.outputs(F),V=J.get(D);if(typeof V>"u"&&(V=this._allData.push(new hn)-1,J.set(D,V)),z.outputs.push(V),this._allData[V]._from!==void 0)throw Error(`multiple nodes output to one data value: ${V}`);if(this._allData[V]._from=K,q.opType()==="Constant"){if(q.attributesLength()!==1||!q.attributes(0).t())throw Error("missing attributes or missing tensor value in attributes for this Constant operator");if(q.outputsLength()!==1)throw Error("missing output or incorrect number of outputs for this Constant operator");z.outputs.pop(),z.executeNode=!1,this._allData[V]._from=-1,this._allData[V].tensor=Me.fromOrtTensor(q.attributes(0).t())}}}for(let K=0;K<this._nodes.length;K++){let z=this._nodes[K],q=Q.nodes(K);if(q.inputsLength()===0)throw Error(`missing input for node: ${q.name}`);for(let F=0;F<q.inputsLength();F++){let D=q.inputs(F),V=J.get(D);if(typeof V>"u")throw Error(`unrecognized input '${D}' for node: ${q.name()}`);z.inputs.push(V),this._allData[V]._to.push(K)}}}checkIsAcyclic(){let Q=new Set;this._allInputIndices.forEach((H)=>{this._allData[H]._to.forEach((K)=>{Q.add(K)})});let J=Array.from(Q),G=Array(this._nodes.length).fill("white");for(;J.length>0;){let H=J.pop();G[H]==="gray"?G[H]="black":(J.push(H),G[H]="gray",this._nodes[H].outputs.forEach((K)=>{let z=this._allData[K];if(typeof z.tensor<"u")throw Error("node outputs should not be initialized");if(z._from!==H)throw Error("from property of the Value object doesn't match index of Node being processed");z._to.forEach((q)=>{if(G[q]==="gray")throw Error("model graph is cyclic");G[q]==="white"&&J.push(q)})}))}}transformGraph(Q){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),Q&&Q.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let Q=0,J=[this._nodes.length,0],G=0;for(let H=0;H<this._nodes.length;H++)J[H]=G,this._nodes[H].executeNode?(G!==H&&(this._nodes[G]=this._nodes[H]),G++):this._nodes[H].outputs.forEach((K)=>{this._allData[K]._from=-2});this._nodes.splice(G,this._nodes.length-G);for(let H=0;H<this._allData.length;H++){let K=this._allData[H];K._from!==void 0&&K._from!==-1&&K._from!==-2&&(K._from=J[K._from]);for(let z=0;z<K._to.length;z++)if(K._to[z]>=0)K._to[z]=J[K._to[z]];else throw Error("Trying to update a removed node")}Q=0;for(let H=0;H<this._allData.length;H++){if(this._allData[H].from===-2&&this._allOutputIndices.indexOf(H+Q)===-1){Q++,this._allData.splice(H,1),H--;continue}if(Q>0){let K=-1;this._allData[H].from!==void 0&&this._allData[H].from!==-1?(K=this._nodes[this._allData[H].from].outputs.indexOf(H+Q),K!==-1&&(this._nodes[this._allData[H].from].outputs[K]=H)):(K=this._allInputIndices.indexOf(H+Q),K!==-1&&(this._allInputIndices[K]=H)),this._allData[H].to.forEach((z)=>{K=this._nodes[z].inputs.indexOf(H+Q),K!==-1&&(this._nodes[z].inputs[K]=H)}),this._allData[H].to.length===0&&(K=this._allOutputIndices.indexOf(H+Q),K!==-1&&(this._allOutputIndices[K]=H))}}}deleteNode(Q){let J=this._nodes[Q];if(J.outputs.length>1){for(let q=1;q<J.outputs.length;q++)if(this._allData[J.outputs[q]].to.length>0)throw Error("Node deletion with more than one output connected to other nodes is not supported. ")}J.executeNode=!1;let G=J.inputs[0],H=J.outputs[0],K=this._allData[H].to;for(let q=0;q<J.inputs.length;q++){let F=this._allData[J.inputs[q]].to.indexOf(Q);if(F===-1)throw Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[J.inputs[q]].to.splice(F,1)}this._allData[H]._to=[];let z=this._allOutputIndices.indexOf(H);if(z!==-1&&(this._allOutputIndices[z]=G),K&&K.length>0)for(let q of K){let F=this._nodes[q].inputs.indexOf(H);if(F===-1)throw Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[q].inputs[F]=G,this._allData[G].to.push(q)}}removeAllDropoutNodes(){let Q=0;for(let J of this._nodes){if(J.opType==="Dropout"){if(J.inputs.length!==1)throw Error("Dropout nodes should only contain one input. ");if(J.outputs.length!==1&&J.outputs.length!==2)throw Error("Dropout nodes should contain either 1 or 2 output(s)");if(J.outputs.length===2&&this._allData[J.outputs[1]]._to.length!==0)throw Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(Q)}Q++}}removeAllIdentityNodes(){let Q=0;for(let J of this._nodes)J.opType==="Identity"&&this.deleteNode(Q),Q++}isActivation(Q){switch(Q.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let Q of this._nodes)if(Q.opType==="Conv"){let J=this._allData[Q.outputs[0]]._to;if(J.length===1&&this.isActivation(this._nodes[J[0]])){let G=this._nodes[J[0]];if(G.opType==="Clip")if(G.inputs.length===1)try{Q.attributes.set("activation_params","floats",[G.attributes.getFloat("min"),G.attributes.getFloat("max")])}catch{Q.attributes.set("activation_params","floats",[Yn,er])}else if(G.inputs.length>=3&&this._allData[G.inputs[1]].tensor!==void 0&&this._allData[G.inputs[2]].tensor!==void 0)Q.attributes.set("activation_params","floats",[this._allData[G.inputs[1]].tensor.floatData[0],this._allData[G.inputs[2]].tensor.floatData[0]]);else continue;Q.attributes.set("activation","string",G.opType),this.deleteNode(J[0])}}}}}),Pm,Om,fi,Em=$(()=>{Pm=ae(_e()),Am(),Br(),Om=ae(gr()),xe(),fi=class{constructor(){}load(Q,J,G){let H;if(!G)try{this.loadFromOnnxFormat(Q,J);return}catch(K){if(G!==void 0)throw K;H=K}try{this.loadFromOrtFormat(Q,J)}catch(K){throw G!==void 0?K:Error(`Failed to load model as ONNX format: ${H}
as ORT format: ${K}`)}}loadFromOnnxFormat(Q,J){let G=Om.onnx.ModelProto.decode(Q);if(it.longToNumber(G.irVersion)<3)throw Error("only support ONNX model with IR_VERSION>=3");this._opsets=G.opsetImport.map((H)=>({domain:H.domain,version:it.longToNumber(H.version)})),this._graph=Ru.from(G.graph,J)}loadFromOrtFormat(Q,J){let G=new Pm.ByteBuffer(Q),H=Rs.InferenceSession.getRootAsInferenceSession(G).model();if(it.longToNumber(H.irVersion())<3)throw Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let K=0;K<H.opsetImportLength();K++){let z=H.opsetImport(K);this._opsets.push({domain:z?.domain(),version:it.longToNumber(z.version())})}this._graph=Ru.from(H.graph(),J)}get graph(){return this._graph}get opsets(){return this._opsets}}}),hi,Cm=$(()=>{Im(),Sm(),ct(),Em(),hi=class{constructor(Q={}){this._initialized=!1,this.backendHint=Q.backendHint,this.profiler=_o.create(Q.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(Q,J,G){await this.profiler.event("session","Session.loadModel",async()=>{let H=await Cu(this.backendHint);if(this.sessionHandler=H.createSessionHandler(this.context),this._model=new fi,typeof Q=="string"){let K=Q.endsWith(".ort");{let z=await(await fetch(Q)).arrayBuffer();this.initialize(new Uint8Array(z),K)}}else if(ArrayBuffer.isView(Q))this.initialize(Q);else{let K=new Uint8Array(Q,J||0,G||Q.byteLength);this.initialize(K)}})}initialize(Q,J){if(this._initialized)throw Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let G=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(Q,G,J),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new di(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(Q){if(!this._initialized)throw Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let J=this.normalizeAndValidateInputs(Q),G=await this._executionPlan.execute(this.sessionHandler,J);return this.createOutput(G)})}normalizeAndValidateInputs(Q){let J=this._model.graph.getInputNames();if(Array.isArray(Q)){if(Q.length!==J.length)throw Error(`incorrect input array length: expected ${J.length} but got ${Q.length}`)}else{if(Q.size!==J.length)throw Error(`incorrect input map size: expected ${J.length} but got ${Q.size}`);let G=Array(Q.size),H=0;for(let K=0;K<J.length;++K){let z=Q.get(J[K]);if(!z)throw Error(`missing input tensor for: '${name}'`);G[H++]=z}Q=G}if(!this.context.graphInputTypes||this.context.graphInputTypes.length===0||!this.context.graphInputDims||this.context.graphInputDims.length===0){let G=this._model.graph.getInputIndices(),H=this._model.graph.getValues(),K=Array(G.length);for(let z=0;z<G.length;++z){let q=H[G[z]];K[z]=q.type.shape.dims,this.context.graphInputTypes.push(q.type.tensorType),this.context.graphInputDims.push(Q[z].dims)}this.validateInputTensorDims(K,Q,!0)}else this.validateInputTensorDims(this.context.graphInputDims,Q,!1);return this.validateInputTensorTypes(this.context.graphInputTypes,Q),Q}validateInputTensorTypes(Q,J){for(let G=0;G<J.length;G++){let H=Q[G],K=J[G].type;if(H!==K)throw Error(`input tensor[${G}] check failed: expected type '${H}' but got ${K}`)}}validateInputTensorDims(Q,J,G){for(let H=0;H<J.length;H++){let K=Q[H],z=J[H].dims;if(!this.compareTensorDims(K,z,G))throw Error(`input tensor[${H}] check failed: expected shape '[${K.join(",")}]' but got [${z.join(",")}]`)}}compareTensorDims(Q,J,G){if(Q.length!==J.length)return!1;for(let H=0;H<Q.length;++H)if(Q[H]!==J[H]&&(!G||Q[H]!==0))return!1;return!0}createOutput(Q){let J=this._model.graph.getOutputNames();if(Q.length!==J.length)throw Error("expected number of outputs do not match number of generated outputs");let G=new Map;for(let H=0;H<J.length;++H)G.set(J[H],Q[H]);return G}initializeOps(Q){let J=Q.getNodes();this._ops=Array(J.length);for(let G=0;G<J.length;G++)this._ops[G]=this.sessionHandler.resolve(J[G],this._model.opsets,Q)}}}),mi,Dm=$(()=>{qe(),tr(),mi=class{constructor(Q){this.session=Q,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}get inputMetadata(){throw Error("Getting model metadata is not supported in webgl backend.")}get outputMetadata(){throw Error("Getting model metadata is not supported in webgl backend.")}async dispose(){}async run(Q,J,G){let H=new Map;for(let q in Q)if(Object.hasOwnProperty.call(Q,q)){let F=Q[q];H.set(q,new Me(F.dims,F.type,void 0,void 0,F.data))}let K=await this.session.run(H),z={};return K.forEach((q,F)=>{z[F]=new et(q.type,q.data,q.dims)}),z}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),km={};Wn(km,{onnxjsBackend:()=>IS});var Nu,IS,Lm=$(()=>{Cm(),Dm(),Nu=class{async init(){}async createInferenceSessionHandler(Q,J){let G=new hi(J);return typeof Q=="string"?await G.loadModel(Q):await G.loadModel(Q),new mi(G)}},IS=new Nu}),gi=$(()=>{}),zm={};Wn(zm,{default:()=>SS});var Rm,Nm,SS,Mm=$(()=>{zu(),Bn(),bi(),Rm="ort-wasm-proxy-worker",Nm=globalThis.self?.name===Rm,Nm&&(self.onmessage=(Q)=>{let{type:J,in:G}=Q.data;try{switch(J){case"init-wasm":yi(G.wasm).then(()=>{_i(G).then(()=>{postMessage({type:J})},(H)=>{postMessage({type:J,err:H})})},(H)=>{postMessage({type:J,err:H})});break;case"init-ep":{let{epName:H,env:K}=G;xi(K,H).then(()=>{postMessage({type:J})},(z)=>{postMessage({type:J,err:z})});break}case"copy-from":{let{buffer:H}=G,K=Yr(H);postMessage({type:J,out:K});break}case"create":{let{model:H,options:K}=G;wi(H,K).then((z)=>{postMessage({type:J,out:z})},(z)=>{postMessage({type:J,err:z})});break}case"release":Ti(G),postMessage({type:J});break;case"run":{let{sessionId:H,inputIndices:K,inputs:z,outputIndices:q,options:F}=G;vi(H,K,z,q,Array(q.length).fill(null),F).then((D)=>{D.some((V)=>V[3]!=="cpu")?postMessage({type:J,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:J,out:D},Si([...z,...D]))},(D)=>{postMessage({type:J,err:D})});break}case"end-profiling":Ii(G),postMessage({type:J});break;default:}}catch(H){postMessage({type:J,err:H})}}),SS=Nm?null:(Q)=>new Worker(Q??ut,{type:"classic",name:Rm})}),$S,AS,ut,$i,Mu,PS,OS,Vm,ES,Bm,Gm,Fm,Um,bi=$(()=>{gi(),$S=typeof location>"u"?void 0:location.origin,AS=()=>{return typeof document<"u"?document.currentScript?.src:typeof self<"u"?self.location?.href:void 0},ut=AS(),$i=()=>{if(ut&&!ut.startsWith("blob:"))return ut.substring(0,ut.lastIndexOf("/")+1)},Mu=(Q,J)=>{try{let G=J??ut;return(G?new URL(Q,G):new URL(Q)).origin===$S}catch{return!1}},PS=(Q,J)=>{let G=J??ut;try{return(G?new URL(Q,G):new URL(Q)).href}catch{return}},OS=(Q,J)=>`${J??"./"}${Q}`,Vm=async(Q)=>{let J=await(await fetch(Q,{credentials:"same-origin"})).blob();return URL.createObjectURL(J)},ES=async(Q)=>(await import(Q)).default,Bm=(Mm(),pr(zm)).default,Gm=async()=>{if(!ut)throw Error("Failed to load proxy worker: cannot determine the script source URL.");if(Mu(ut))return[void 0,Bm()];let Q=await Vm(ut);return[Q,Bm(Q)]},Fm=void 0,Um=async(Q,J,G,H)=>{let K=Fm&&!(Q||J);if(K)if(ut)K=Mu(ut)||H&&!G;else if(H&&!G)K=!0;else throw Error("cannot determine the script source URL.");if(K)return[void 0,Fm];{let z="ort-wasm-simd-threaded.jsep.mjs",q=Q??PS(z,J),F=G&&q&&!Mu(q,J),D=F?await Vm(q):q??OS(z,J);return[F?D:void 0,await ES(D)]}}}),Bu,Fu,Ai,Wm,CS,DS,kS,yi,we,Bn=$(()=>{bi(),Fu=!1,Ai=!1,Wm=!1,CS=()=>{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}},DS=()=>{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}},kS=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},yi=async(Q)=>{if(Fu)return Promise.resolve();if(Ai)throw Error("multiple calls to 'initializeWebAssembly()' detected.");if(Wm)throw Error("previous call to 'initializeWebAssembly()' failed.");Ai=!0;let{initTimeout:J,numThreads:G}=Q;if(Q.simd!==!1){if(Q.simd==="relaxed"){if(!kS())throw Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!DS())throw Error("WebAssembly SIMD is not supported in the current environment.")}let H=CS();G>1&&!H&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+G+", 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."),Q.numThreads=G=1);let K=Q.wasmPaths,z=typeof K=="string"?K:void 0,q=K?.mjs,F=q?.href??q,D=K?.wasm,V=D?.href??D,O=Q.wasmBinary,[P,N]=await Um(F,z,G>1,!!O||!!V),I=!1,R=[];if(J>0&&R.push(new Promise((w)=>{setTimeout(()=>{I=!0,w()},J)})),R.push(new Promise((w,E)=>{let T={numThreads:G};if(O)T.wasmBinary=O,T.locateFile=(y)=>y;else if(V||z)T.locateFile=(y)=>V??z+y;else if(F&&F.indexOf("blob:")!==0)T.locateFile=(y)=>new URL(y,F).href;else if(P){let y=$i();y&&(T.locateFile=(x)=>y+x)}N(T).then((y)=>{Ai=!1,Fu=!0,Bu=y,w(),P&&URL.revokeObjectURL(P)},(y)=>{Ai=!1,Wm=!0,E(y)})})),await Promise.race(R),I)throw Error(`WebAssembly backend initializing failed due to timeout: ${J}ms`)},we=()=>{if(Fu&&Bu)return Bu;throw Error("WebAssembly is not initialized yet.")}}),lt,eo,fe,Pi=$(()=>{Bn(),lt=(Q,J)=>{let G=we(),H=G.lengthBytesUTF8(Q)+1,K=G._malloc(H);return G.stringToUTF8(Q,K,H),J.push(K),K},eo=(Q,J,G,H)=>{if(typeof Q=="object"&&Q!==null){if(G.has(Q))throw Error("Circular reference in options");G.add(Q)}Object.entries(Q).forEach(([K,z])=>{let q=J?J+K:K;if(typeof z=="object")eo(z,q+".",G,H);else if(typeof z=="string"||typeof z=="number")H(q,z.toString());else if(typeof z=="boolean")H(q,z?"1":"0");else throw Error(`Can't handle extra config type: ${typeof z}`)})},fe=(Q)=>{let J=we(),G=J.stackSave();try{let H=J.PTR_SIZE,K=J.stackAlloc(2*H);J._OrtGetLastError(K,K+H);let z=Number(J.getValue(K,H===4?"i32":"i64")),q=J.getValue(K+H,"*"),F=q?J.UTF8ToString(q):"";throw Error(`${Q} ERROR_CODE: ${z}, ERROR_MESSAGE: ${F}`)}finally{J.stackRestore(G)}}}),Hm,qm=$(()=>{Bn(),Pi(),Hm=(Q)=>{let J=we(),G=0,H=[],K=Q||{};try{if(Q?.logSeverityLevel===void 0)K.logSeverityLevel=2;else if(typeof Q.logSeverityLevel!="number"||!Number.isInteger(Q.logSeverityLevel)||Q.logSeverityLevel<0||Q.logSeverityLevel>4)throw Error(`log severity level is not valid: ${Q.logSeverityLevel}`);if(Q?.logVerbosityLevel===void 0)K.logVerbosityLevel=0;else if(typeof Q.logVerbosityLevel!="number"||!Number.isInteger(Q.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${Q.logVerbosityLevel}`);Q?.terminate===void 0&&(K.terminate=!1);let z=0;return Q?.tag!==void 0&&(z=lt(Q.tag,H)),G=J._OrtCreateRunOptions(K.logSeverityLevel,K.logVerbosityLevel,!!K.terminate,z),G===0&&fe("Can't create run options."),Q?.extra!==void 0&&eo(Q.extra,"",new WeakSet,(q,F)=>{let D=lt(q,H),V=lt(F,H);J._OrtAddRunConfigEntry(G,D,V)!==0&&fe(`Can't set a run config entry: ${q} - ${F}.`)}),[G,H]}catch(z){throw G!==0&&J._OrtReleaseRunOptions(G),H.forEach((q)=>J._free(q)),z}}}),LS,RS,NS,Sr,zS,jm,Km=$(()=>{Bn(),Pi(),LS=(Q)=>{switch(Q){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw Error(`unsupported graph optimization level: ${Q}`)}},RS=(Q)=>{switch(Q){case"sequential":return 0;case"parallel":return 1;default:throw Error(`unsupported execution mode: ${Q}`)}},NS=(Q)=>{Q.extra||(Q.extra={}),Q.extra.session||(Q.extra.session={});let J=Q.extra.session;J.use_ort_model_bytes_directly||(J.use_ort_model_bytes_directly="1"),Q.executionProviders&&Q.executionProviders.some((G)=>(typeof G=="string"?G:G.name)==="webgpu")&&(Q.enableMemPattern=!1)},Sr=(Q,J,G,H)=>{let K=lt(J,H),z=lt(G,H);we()._OrtAddSessionConfigEntry(Q,K,z)!==0&&fe(`Can't set a session config entry: ${J} - ${G}.`)},zS=async(Q,J,G)=>{let H=J.executionProviders;for(let K of H){let z=typeof K=="string"?K:K.name,q=[];switch(z){case"webnn":if(z="WEBNN",Sr(Q,"session.disable_quant_qdq","1",G),Sr(Q,"session.disable_qdq_constant_folding","1",G),typeof K!="string"){let P=K?.deviceType;P&&Sr(Q,"deviceType",P,G)}break;case"webgpu":if(z="JS",typeof K!="string"){let P=K;if(P?.preferredLayout){if(P.preferredLayout!=="NCHW"&&P.preferredLayout!=="NHWC")throw Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${P.preferredLayout}`);Sr(Q,"preferredLayout",P.preferredLayout,G)}}break;case"wasm":case"cpu":continue;default:throw Error(`not supported execution provider: ${z}`)}let F=lt(z,G),D=q.length,V=0,O=0;if(D>0){V=we()._malloc(D*we().PTR_SIZE),G.push(V),O=we()._malloc(D*we().PTR_SIZE),G.push(O);for(let P=0;P<D;P++)we().setValue(V+P*we().PTR_SIZE,q[P][0],"*"),we().setValue(O+P*we().PTR_SIZE,q[P][1],"*")}await we()._OrtAppendExecutionProvider(Q,F,V,O,D)!==0&&fe(`Can't append execution provider: ${z}.`)}},jm=async(Q)=>{let J=we(),G=0,H=[],K=Q||{};NS(K);try{let z=LS(K.graphOptimizationLevel??"all"),q=RS(K.executionMode??"sequential"),F=typeof K.logId=="string"?lt(K.logId,H):0,D=K.logSeverityLevel??2;if(!Number.isInteger(D)||D<0||D>4)throw Error(`log severity level is not valid: ${D}`);let V=K.logVerbosityLevel??0;if(!Number.isInteger(V)||V<0||V>4)throw Error(`log verbosity level is not valid: ${V}`);let O=typeof K.optimizedModelFilePath=="string"?lt(K.optimizedModelFilePath,H):0;if(G=J._OrtCreateSessionOptions(z,!!K.enableCpuMemArena,!!K.enableMemPattern,q,!!K.enableProfiling,0,F,D,V,O),G===0&&fe("Can't create session options."),K.executionProviders&&await zS(G,K,H),K.enableGraphCapture!==void 0){if(typeof K.enableGraphCapture!="boolean")throw Error(`enableGraphCapture must be a boolean value: ${K.enableGraphCapture}`);Sr(G,"enableGraphCapture",K.enableGraphCapture.toString(),H)}if(K.freeDimensionOverrides)for(let[P,N]of Object.entries(K.freeDimensionOverrides)){if(typeof P!="string")throw Error(`free dimension override name must be a string: ${P}`);if(typeof N!="number"||!Number.isInteger(N)||N<0)throw Error(`free dimension override value must be a non-negative integer: ${N}`);let I=lt(P,H);J._OrtAddFreeDimensionOverride(G,I,N)!==0&&fe(`Can't set a free dimension override: ${P} - ${N}.`)}return K.extra!==void 0&&eo(K.extra,"",new WeakSet,(P,N)=>{Sr(G,P,N,H)}),[G,H]}catch(z){throw G!==0&&J._OrtReleaseSessionOptions(G)!==0&&fe("Can't release session options."),H.forEach((q)=>J._free(q)),z}}}),Fn,mn,Vn,$r,to,Oi,Ei,Vu,X=$(()=>{Fn=(Q)=>{switch(Q){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw Error(`unsupported data type: ${Q}`)}},mn=(Q)=>{switch(Q){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw Error(`unsupported data type: ${Q}`)}},Vn=(Q,J)=>{let G=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,0.5,0.5][Q],H=typeof J=="number"?J:J.reduce((K,z)=>K*z,1);return G>0?Math.ceil(H*G):void 0},$r=(Q)=>{switch(Q){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 Error(`unsupported type: ${Q}`)}},to=(Q)=>{switch(Q){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw Error(`unsupported logging level: ${Q}`)}},Oi=(Q)=>Q==="float32"||Q==="float16"||Q==="int32"||Q==="int64"||Q==="uint32"||Q==="uint8"||Q==="bool"||Q==="uint4"||Q==="int4",Ei=(Q)=>Q==="float32"||Q==="float16"||Q==="int32"||Q==="int64"||Q==="uint32"||Q==="uint64"||Q==="int8"||Q==="uint8"||Q==="bool"||Q==="uint4"||Q==="int4",Vu=(Q)=>{switch(Q){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw Error(`unsupported data location: ${Q}`)}}}),no,Gu=$(()=>{gi(),no=async(Q)=>{if(typeof Q=="string"){let J=await fetch(Q);if(!J.ok)throw Error(`failed to load external data file: ${Q}`);let G=J.headers.get("Content-Length"),H=G?parseInt(G,10):0;if(H<1073741824)return new Uint8Array(await J.arrayBuffer());{if(!J.body)throw Error(`failed to load external data file: ${Q}, no response body.`);let K=J.body.getReader(),z;try{z=new ArrayBuffer(H)}catch(F){if(F instanceof RangeError){let D=Math.ceil(H/65536);z=new WebAssembly.Memory({initial:D,maximum:D}).buffer}else throw F}let q=0;for(;;){let{done:F,value:D}=await K.read();if(F)break;let V=D.byteLength;new Uint8Array(z,q,V).set(D),q+=V}return new Uint8Array(z,0,H)}}else return Q instanceof Blob?new Uint8Array(await Q.arrayBuffer()):Q instanceof Uint8Array?Q:new Uint8Array(Q)}}),MS,BS,Xm,Zm,Ci,FS,ie,gn=$(()=>{X(),MS=["V","I","W","E","F"],BS=(Q,J)=>{console.log(`[${MS[Q]},${new Date().toISOString()}]${J}`)},Ci=(Q,J)=>{Xm=Q,Zm=J},FS=(Q,J)=>{let G=to(Q),H=to(Xm);G>=H&&BS(G,typeof J=="function"?J():J)},ie=(...Q)=>{Zm&&FS(...Q)}}),Uu,bn,S,sr,Di,Jm,Qm,ee=$(()=>{Uu=class{static calcMatMulShape(Q,J){return Q[1]!==J[0]?void 0:[Q[0],J[1]]}},bn=class{static calcShape(Q,J,G=!1){let H=Q.length,K=J.length;if(H===0)return J;if(K===0)return Q;let z=Math.max(Q.length,J.length),q=Array(z);if(G){if(H<2||K<2)return;let F=Uu.calcMatMulShape([Q[H-2],Q[H-1]],[J[K-2],J[K-1]]);if(F===void 0)return;[q[z-2],q[z-1]]=F}for(let F=G?3:1;F<=z;F++){let D=H-F<0?1:Q[H-F],V=K-F<0?1:J[K-F];if(D!==V&&D>1&&V>1)return;let O=Math.max(D,V);if(D&&V)q[z-F]=Math.max(D,V);else{if(O>1)return;q[z-F]=0}}return q}static isValidBroadcast(Q,J){let G=Q.length,H=J.length;if(G>H)return!1;for(let K=1;K<=G;K++)if(Q[G-K]!==1&&Q[G-K]!==J[H-K])return!1;return!0}},S=class Q{static size(J){return Q.getSizeFromDimensionRange(J,0,J.length)}static convertShape(J,G=4){let H=J.length;if(H===0)return[];let K=Array(H),z=H-1;for(;z>=0;){if(J[z]%G===0){K[z]=J[z]/G;break}if(G%J[z]!==0)throw Error("cannot convert shape");K[z]=1,G/=J[z],z--}for(z--;z>=0;z--)K[z]=J[z];return K}static sizeFromDimension(J,G){if(G<0||G>J.length)throw Error(`invalid dimension of ${G} for sizeFromDimension as Tensor has ${J.length} dimensions.`);return Q.getSizeFromDimensionRange(J,G,J.length)}static sizeToDimension(J,G){if(G<0||G>J.length)throw Error(`invalid dimension of ${G} for sizeToDimension as Tensor has ${J.length} dimensions.`);return Q.getSizeFromDimensionRange(J,0,G)}static getSizeFromDimensionRange(J,G,H){let K=1;for(let z=G;z<H;z++){if(J[z]<0)throw Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");K*=Number(J[z])}return K}static computeStrides(J){let G=J.length;if(G===0)return[];if(G===1)return[1];let H=Array(G);H[G-1]=1,H[G-2]=J[G-1];for(let K=G-3;K>=0;--K)H[K]=H[K+1]*J[K+1];return H}static normalizeAxis(J,G){if(J<-G&&J>=G)throw Error("unsupported axis for this operation.");return J<0?J+G:J}static normalizeAxes(J,G){return J.map((H)=>this.normalizeAxis(H,G??J.length))}static sortBasedOnPerm(J,G){return G?G.map((H)=>J[H]):J.slice().reverse()}static padShape(J,G){let H=J.length;return J.map((K,z)=>K+G[z]+G[z+H])}static areEqual(J,G){return J.length!==G.length?!1:J.every((H,K)=>H===G[K])}},sr=class Q{static adjustPoolAttributes(J,G,H,K,z,q){if(!J&&H.length!==G.length-2)throw Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(J)for(let F=0;F<G.length-2;F++)F>=H.length?H.push(G[F+2]):H[F]=G[F+2];for(let F=0;F<H.length;F++)if(F<K.length){if(K[F]<0)throw Error("strides should be greater than or equal to 1")}else K.push(1);for(let F=0;F<H.length;F++)if(F<z.length){if(z[F]<0)throw Error("dilations should be greater than or equal to 1")}else z.push(1);for(let F=0;F<H.length*2;F++)if(F<q.length){if(q[F]<0)throw Error("pad should be greater than or equal to 1")}else q.push(0);for(let F=0;F<H.length;F++){if(H[F]<=0)throw Error("kernel shapes need to be greater than 0");if(q[F]>=H[F]||q[F+H.length]>=H[F])throw Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(J,G,H,K,z,q,F){if(F){if(z.length!==2*(J.length-2))throw Error("length of pads should be twice the length of data dimensions");if(G.length!==J.length-2)throw Error("length of strides should be the length of data dimensions");if(K.length!==J.length-2)throw Error("length of kernel shapes should be the length of data dimensions");for(let D=0;D<J.length-2;D++)Q.adjustPadAndReturnShape(J[D+(q?1:2)],G[D],H[D],K[D],z,D,D+J.length-2,F)}}static computePoolOutputShape(J,G,H,K,z,q,F){if(G.length<=0)throw Error("input shape must be of size greater than 0");let D=[G[0],G[1]];return Q.computeShapeHelper(J,G,D,H,K,z,q,F),D}static computeConvOutputShape(J,G,H,K,z,q,F){if(J.length<=0||G.length<=0)throw Error("invalid input tensor dims or invalid filter tensor dims");let D=[J[0],G[0]];return Q.computeShapeHelper(!1,J,D,H,K,z,q,F),D}static computeShapeHelper(J,G,H,K,z,q,F,D){if(J)for(let V=0;V<G.length-2;V++)H.push(1);else for(let V=0;V<G.length-2;V++)H.push(Q.adjustPadAndReturnShape(G[V+2],K[V],z[V],q[V],F,V,V+G.length-2,D))}static adjustPadAndReturnShape(J,G,H,K,z,q,F,D){let V=H*(K-1)+1;if(D&&D!=="NOTSET")switch(D){case"VALID":return z[q]=0,z[F]=0,Math.floor((J-V)/G+1);case"SAME_LOWER":case"SAME_UPPER":if(H!==1)throw Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let O=((J+G-1)/G-1)*G+K-J;return z[q]=Math.floor(D==="SAME_LOWER"?(O+1)/2:O/2),z[F]=O-z[q],Math.floor((J+O-K)/G+1)}default:throw Error("Unsupported AutoPad type")}else return Math.floor((J+z[q]+z[F]-V)/G+1)}},Di=class{static getShapeOfGemmResult(Q,J,G,H,K){if(Q.length!==2||G.length!==2)throw Error("shape need to be of size 2");let z,q,F;J?(z=Q[1],q=Q[0]):(z=Q[0],q=Q[1]);let D=-1;if(H?(F=G[0],D=1):(F=G[1],D=0),G[D]!==q)throw Error("dimension mismatch");if(z<=0||F<=0||q<=0)throw Error("invalid shape specified");if(K&&!bn.isValidBroadcast(K,[z,F]))throw Error("gemm: invalid bias shape for broadcast");return[z,F,q]}},Jm=-340282346638528860000000000000000000000,Qm=340282346638528860000000000000000000000}),ki,Wu=$(()=>{X(),ki=(Q,J)=>new($r(J))(Q)}),eg,qu,tg,VS,Ym,GS,ng,Li,Ri,Hu,rg,og=$(()=>{X(),gn(),eg=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qu=(Q,J)=>{if(J==="int32")return Q;let G=eg.get(J);if(!G)throw Error(`WebNN backend does not support data type: ${J}`);let H=G/8;if(Q.byteLength%H!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${H}.`);let K=Q.byteLength/H,z=new($r(J))(Q.buffer,Q.byteOffset,K);switch(J){case"int64":case"uint64":{let q=new Int32Array(K);for(let F=0;F<K;F++){let D=z[F];if(D>2147483647n||D<-2147483648n)throw Error("Can not convert int64 data to int32 - value out of range.");q[F]=Number(D)}return new Uint8Array(q.buffer)}case"int8":case"uint8":case"uint32":{if(J==="uint32"&&z.some((F)=>F>2147483647))throw Error("Can not convert uint32 data to int32 - value out of range.");let q=Int32Array.from(z,Number);return new Uint8Array(q.buffer)}default:throw Error(`Unsupported data conversion from ${J} to 'int32'`)}},tg=(Q,J)=>{if(J==="int32")return Q;if(Q.byteLength%4!==0)throw Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let G=Q.byteLength/4,H=new Int32Array(Q.buffer,Q.byteOffset,G);switch(J){case"int64":{let K=BigInt64Array.from(H,BigInt);return new Uint8Array(K.buffer)}case"uint64":{if(H.some((z)=>z<0))throw Error("Can not convert int32 data to uin64 - negative value found.");let K=BigUint64Array.from(H,BigInt);return new Uint8Array(K.buffer)}case"int8":{if(H.some((z)=>z<-128||z>127))throw Error("Can not convert int32 data to int8 - value out of range.");let K=Int8Array.from(H,Number);return new Uint8Array(K.buffer)}case"uint8":{if(H.some((K)=>K<0||K>255))throw Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(H,Number)}case"uint32":{if(H.some((z)=>z<0))throw Error("Can not convert int32 data to uint32 - negative value found.");let K=Uint32Array.from(H,Number);return new Uint8Array(K.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${J}`)}},VS=1,Ym=()=>VS++,GS=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),ng=(Q,J)=>{let G=eg.get(Q);if(!G)throw Error(`WebNN backend does not support data type: ${Q}`);return J.length>0?Math.ceil(J.reduce((H,K)=>H*K)*G/8):0},Li=class{constructor(Q){this.isDataConverted=!1;let{sessionId:J,context:G,tensor:H,dataType:K,shape:z,fallbackDataType:q}=Q;this.sessionId=J,this.mlContext=G,this.mlTensor=H,this.dataType=K,this.tensorShape=z,this.fallbackDataType=q}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return ng(this.dataType,this.tensorShape)}destroy(){ie("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(Q){this.mlContext.writeTensor(this.mlTensor,Q)}async read(Q){if(this.fallbackDataType){let J=await this.mlContext.readTensor(this.mlTensor),G=tg(new Uint8Array(J),this.dataType);if(Q){(Q instanceof ArrayBuffer?new Uint8Array(Q):new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)).set(G);return}else return G.buffer}else return Q?this.mlContext.readTensor(this.mlTensor,Q):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(Q,J,G){return this.mlContext===Q&&this.dataType===J&&this.tensorShape.length===G.length&&this.tensorShape.every((H,K)=>H===G[K])}setIsDataConverted(Q){this.isDataConverted=Q}},Ri=class{constructor(Q,J){this.tensorManager=Q,this.wrapper=J}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(Q,J,G,H){let K=this.tensorManager.getMLContext(Q),z=this.tensorManager.getMLOpSupportLimits(Q),q;if(!z?.input.dataTypes.includes(J)){if(q=GS.get(J),!q||z?.input.dataTypes.includes(q))throw Error(`WebNN backend does not support data type: ${J}`);ie("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${J} to ${q}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(K,J,G))return this.wrapper.tensor;if(H){if(this.wrapper.byteLength!==ng(J,G))throw Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let F=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(Q,J,G,F,!0,!0,q),H&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(Q){let J=Q;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")J=qu(Q,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(Q.byteLength===this.wrapper.byteLength){this.wrapper.write(J);return}else ie("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(J):this.activeUpload=new Uint8Array(J)}async download(Q){if(this.activeUpload){let J=this.wrapper?.isDataConverted?tg(this.activeUpload,this.wrapper?.type):this.activeUpload;if(Q){Q instanceof ArrayBuffer?new Uint8Array(Q).set(J):new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength).set(J);return}else return J.buffer}if(!this.wrapper)throw Error("Tensor has not been created.");return Q?this.wrapper.read(Q):this.wrapper.read()}},Hu=class{constructor(Q){this.backend=Q,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(Q){let J=this.backend.getMLContext(Q);if(!J)throw Error("MLContext not found for session.");return J}getMLOpSupportLimits(Q){return this.backend.getMLOpSupportLimits(Q)}reserveTensorId(){let Q=Ym();return this.tensorTrackersById.set(Q,new Ri(this)),Q}releaseTensorId(Q){let J=this.tensorTrackersById.get(Q);J&&(this.tensorTrackersById.delete(Q),J.tensorWrapper&&this.releaseTensor(J.tensorWrapper))}async ensureTensor(Q,J,G,H,K){ie("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${J}, dataType: ${G}, shape: ${H}, copyOld: ${K}}`);let z=this.tensorTrackersById.get(J);if(!z)throw Error("Tensor not found.");return z.ensureTensor(Q,G,H,K)}upload(Q,J){let G=this.tensorTrackersById.get(Q);if(!G)throw Error("Tensor not found.");G.upload(J)}async download(Q,J){ie("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${Q}, dstBuffer: ${J?.byteLength}}`);let G=this.tensorTrackersById.get(Q);if(!G)throw Error("Tensor not found.");return G.download(J)}releaseTensorsForSession(Q){for(let J of this.freeTensors)J.sessionId===Q&&J.destroy();this.freeTensors=this.freeTensors.filter((J)=>J.sessionId!==Q)}registerTensor(Q,J,G,H){let K=this.getMLContext(Q),z=Ym(),q=new Li({sessionId:Q,context:K,tensor:J,dataType:G,shape:H});return this.tensorTrackersById.set(z,new Ri(this,q)),this.externalTensors.add(q),z}async getCachedTensor(Q,J,G,H,K,z,q){let F=this.getMLContext(Q);for(let[V,O]of this.freeTensors.entries())if(O.canReuseTensor(F,J,G)){ie("verbose",()=>`[WebNN] Reusing tensor {dataType: ${J}, ${q?`fallbackDataType: ${q},`:""} shape: ${G}`);let P=this.freeTensors.splice(V,1)[0];return P.sessionId=Q,P}ie("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${J}, ${q?`fallbackDataType: ${q},`:""} shape: ${G}}`);let D=await F.createTensor({dataType:q??J,shape:G,dimensions:G,usage:H,writable:K,readable:z});return new Li({sessionId:Q,context:F,tensor:D,dataType:J,shape:G,fallbackDataType:q})}releaseTensor(Q){this.externalTensors.has(Q)&&this.externalTensors.delete(Q),this.freeTensors.push(Q)}},rg=(...Q)=>new Hu(...Q)}),Ni,US,zi,ig=$(()=>{X(),Bn(),Wu(),og(),gn(),Ni=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),US=(Q,J)=>{if(Q===J)return!0;if(Q===void 0||J===void 0)return!1;let G=Object.keys(Q).sort(),H=Object.keys(J).sort();return G.length===H.length&&G.every((K,z)=>K===H[z]&&Q[K]===J[K])},zi=class{constructor(Q){this.tensorManager=rg(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Ci(Q.logLevel,!!Q.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error("No active session");return this.activeSessionId}onRunStart(Q){ie("verbose",()=>`[WebNN] onRunStart {sessionId: ${Q}}`),this.activeSessionId=Q}onRunEnd(Q){ie("verbose",()=>`[WebNN] onRunEnd {sessionId: ${Q}}`);let J=this.temporarySessionTensorIds.get(Q);if(J){for(let G of J)ie("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${G}}`),this.tensorManager.releaseTensorId(G);this.temporarySessionTensorIds.delete(Q),this.activeSessionId=void 0}}async createMLContext(Q){if(Q instanceof GPUDevice){let G=this.mlContextCache.findIndex((H)=>H.gpuDevice===Q);if(G!==-1)return this.mlContextCache[G].mlContext;{let H=await navigator.ml.createContext(Q);return this.mlContextCache.push({gpuDevice:Q,mlContext:H}),H}}else if(Q===void 0){let G=this.mlContextCache.findIndex((H)=>H.options===void 0&&H.gpuDevice===void 0);if(G!==-1)return this.mlContextCache[G].mlContext;{let H=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:H}),H}}let J=this.mlContextCache.findIndex((G)=>US(G.options,Q));if(J!==-1)return this.mlContextCache[J].mlContext;{let G=await navigator.ml.createContext(Q);return this.mlContextCache.push({options:Q,mlContext:G}),G}}registerMLContext(Q,J){this.mlContextBySessionId.set(Q,J);let G=this.sessionIdsByMLContext.get(J);G||(G=new Set,this.sessionIdsByMLContext.set(J,G)),G.add(Q),this.mlOpSupportLimitsBySessionId.has(Q)||this.mlOpSupportLimitsBySessionId.set(Q,J.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(Q,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(Q,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(Q){this.sessionGraphInputs.delete(Q),this.sessionGraphOutputs.delete(Q);let J=this.mlContextBySessionId.get(Q);if(!J)return;this.tensorManager.releaseTensorsForSession(Q),this.mlContextBySessionId.delete(Q),this.mlOpSupportLimitsBySessionId.delete(Q);let G=this.sessionIdsByMLContext.get(J);if(G.delete(Q),G.size===0){this.sessionIdsByMLContext.delete(J);let H=this.mlContextCache.findIndex((K)=>K.mlContext===J);H!==-1&&this.mlContextCache.splice(H,1)}}getMLContext(Q){return this.mlContextBySessionId.get(Q)}getMLOpSupportLimits(Q){return this.mlOpSupportLimitsBySessionId.get(Q)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(Q){ie("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${Q}}`),this.tensorManager.releaseTensorId(Q)}async ensureTensor(Q,J,G,H,K){let z=Ni.get(G);if(!z)throw Error(`Unsupported ONNX data type: ${G}`);return this.tensorManager.ensureTensor(Q??this.currentSessionId,J,z,H,K)}async createTemporaryTensor(Q,J,G){ie("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${J}, shape: ${G}}`);let H=Ni.get(J);if(!H)throw Error(`Unsupported ONNX data type: ${J}`);let K=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(Q,K,H,G,!1);let z=this.temporarySessionTensorIds.get(Q);return z?z.push(K):this.temporarySessionTensorIds.set(Q,[K]),K}uploadTensor(Q,J){if(!we().shouldTransferToMLTensor)throw Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");ie("verbose",()=>`[WebNN] uploadTensor {tensorId: ${Q}, data: ${J.byteLength}}`),this.tensorManager.upload(Q,J)}async downloadTensor(Q,J){return this.tensorManager.download(Q,J)}createMLTensorDownloader(Q,J){return async()=>{let G=await this.tensorManager.download(Q);return ki(G,J)}}registerMLTensor(Q,J,G,H){let K=Ni.get(G);if(!K)throw Error(`Unsupported ONNX data type: ${G}`);let z=this.tensorManager.registerTensor(Q,J,K,H);return ie("verbose",()=>`[WebNN] registerMLTensor {tensor: ${J}, dataType: ${K}, dimensions: ${H}} -> {tensorId: ${z}}`),z}registerMLConstant(Q,J,G,H,K,z,q=!1){if(!z)throw Error("External mounted files are not available.");let F=Q;Q.startsWith("./")&&(F=Q.substring(2));let D=z.get(F);if(!D)throw Error(`File with name ${F} not found in preloaded files.`);if(J+G>D.byteLength)throw Error("Out of bounds: data offset and length exceed the external file data size.");let V=D.slice(J,J+G).buffer,O;switch(K.dataType){case"float32":O=new Float32Array(V);break;case"float16":O=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(V):new Uint16Array(V);break;case"int32":O=new Int32Array(V);break;case"uint32":O=new Uint32Array(V);break;case"int64":if(q){let P=qu(new Uint8Array(V),"int64");O=new Int32Array(P.buffer),K.dataType="int32"}else O=new BigInt64Array(V);break;case"uint64":O=new BigUint64Array(V);break;case"int8":O=new Int8Array(V);break;case"int4":case"uint4":case"uint8":O=new Uint8Array(V);break;default:throw Error(`Unsupported data type: ${K.dataType} in creating WebNN Constant from external data.`)}return ie("verbose",()=>`[WebNN] registerMLConstant {dataType: ${K.dataType}, shape: ${K.shape}}} ${q?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),H.constant(K,O)}registerGraphInput(Q){this.temporaryGraphInputs.push(Q)}registerGraphOutput(Q){this.temporaryGraphOutputs.push(Q)}isGraphInput(Q,J){let G=this.sessionGraphInputs.get(Q);return G?G.includes(J):!1}isGraphOutput(Q,J){let G=this.sessionGraphOutputs.get(Q);return G?G.includes(J):!1}isGraphInputOutputTypeSupported(Q,J,G=!0){let H=Ni.get(Fn(J)),K=this.mlOpSupportLimitsBySessionId.get(Q);return typeof H>"u"?!1:G?!!K?.input.dataTypes.includes(H):!!K?.output.dataTypes.includes(H)}flush(){}}}),Mi=$(()=>{}),ag,ju,Ku,WS,HS,sg,Zu,Xu,lg,cg=$(()=>{gn(),Mi(),ag=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]]),ju=[],Ku=(Q)=>Math.ceil(Number(Q)/16)*16,WS=(Q)=>{for(let J=0;J<ju.length;J++){let G=ju[J];if(Q<=G)return G}return Math.ceil(Q/16)*16},HS=1,sg=()=>HS++,Zu=async(Q,J,G,H)=>{let K=Ku(G),z=Q.device.createBuffer({size:K,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let q=Q.getCommandEncoder();Q.endComputePass(),q.copyBufferToBuffer(J,0,z,0,K),Q.flush(),await z.mapAsync(GPUMapMode.READ);let F=z.getMappedRange();if(H){let D=H();return D.set(new Uint8Array(F,0,G)),D}else return new Uint8Array(F.slice(0,G))}finally{z.destroy()}},Xu=class{constructor(Q){this.backend=Q,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[J]of ag)ju.push(J),this.freeBuffers.set(J,[]),this.freeUniformBuffers.set(J,[]);this.sessionCount=0}upload(Q,J){let{buffer:G,byteOffset:H,byteLength:K}=J,z=Ku(K),q=this.storageCache.get(Q);if(!q)throw Error("gpu data for uploading does not exist");if(Number(q.originalSize)!==K)throw Error(`inconsistent data size. gpu data size=${q.originalSize}, data size=${K}`);let F=this.backend.device.createBuffer({mappedAtCreation:!0,size:z,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),D=F.getMappedRange();new Uint8Array(D).set(new Uint8Array(G,H,K)),F.unmap();let V=this.backend.device.createCommandEncoder();V.copyBufferToBuffer(F,0,q.gpuData.buffer,0,z),this.backend.device.queue.submit([V.finish()]),F.destroy(),ie("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${Q})`)}memcpy(Q,J){let G=this.storageCache.get(Q);if(!G)throw Error("source gpu data for memcpy does not exist");let H=this.storageCache.get(J);if(!H)throw Error("destination gpu data for memcpy does not exist");if(G.originalSize!==H.originalSize)throw Error("inconsistent source and destination gpu data size");let K=Ku(G.originalSize),z=this.backend.getCommandEncoder();this.backend.endComputePass(),z.copyBufferToBuffer(G.gpuData.buffer,0,H.gpuData.buffer,0,K)}registerExternalBuffer(Q,J,G){let H;if(G){if(H=G[0],Q===G[1])return ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${J}) => id=${H}, buffer is the same, skip.`),H;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw Error(`Registering a different external buffer under graph capture mode is not supported yet.
Please use the previous external buffer!`)}else H=sg();return this.storageCache.set(H,{gpuData:{id:H,type:0,buffer:Q},originalSize:J}),ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${J}) => id=${H}, registered.`),H}unregisterExternalBuffer(Q){Q!==void 0&&(this.storageCache.delete(Q),ie("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${Q}`))}create(Q,J=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let G=WS(Q),H,K=(J&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,z=(J&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(K||z){let F=(K?this.freeBuffers:this.freeUniformBuffers).get(G);F?F.length>0?H=F.pop():H=this.backend.device.createBuffer({size:G,usage:J}):H=this.backend.device.createBuffer({size:G,usage:J})}else H=this.backend.device.createBuffer({size:G,usage:J});let q={id:sg(),type:0,buffer:H};return this.storageCache.set(q.id,{gpuData:q,originalSize:Number(Q)}),ie("verbose",()=>`[WebGPU] GpuDataManager.create(size=${Q}) => id=${q.id}`),q}get(Q){return this.storageCache.get(Q)?.gpuData}release(Q){let J=typeof Q=="bigint"?Number(Q):Q,G=this.storageCache.get(J);if(!G){if(this.storageCache.size===0)return 0;throw Error("releasing data does not exist")}return ie("verbose",()=>`[WebGPU] GpuDataManager.release(id=${J}), gpuDataId=${G.gpuData.id}`),this.storageCache.delete(J),this.buffersPending.push(G.gpuData.buffer),G.originalSize}async download(Q,J){let G=this.storageCache.get(Number(Q));if(!G)throw Error("data does not exist");await Zu(this.backend,G.gpuData.buffer,G.originalSize,J)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let Q of this.buffersPending){let J=ag.get(Q.size);if((Q.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let G=this.freeBuffers.get(Q.size)||[];J===void 0||G.length>=J?Q.destroy():G.push(Q)}else if((Q.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let G=this.freeUniformBuffers.get(Q.size)||[];J===void 0||G.length>=J?Q.destroy():G.push(Q)}else Q.destroy()}this.buffersPending=[]}else{let Q=this.capturedPendingBuffers.get(this.backend.currentSessionId);Q||(Q=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,Q));for(let J of this.buffersPending)Q.push(J);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach((Q)=>{Q.forEach((J)=>{J.destroy()})}),this.freeUniformBuffers.forEach((Q)=>{Q.forEach((J)=>{J.destroy()})}),this.storageCache.forEach((Q)=>{Q.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach((Q)=>{Q.forEach((J)=>{J.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(Q){let J=this.capturedPendingBuffers.get(Q);J&&(J.forEach((G)=>{G.destroy()}),this.capturedPendingBuffers.delete(Q)),this.sessionCount-=1,this.sessionCount===0&&(ie("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach((G)=>{G.gpuData.buffer.destroy()}),this.storageCache=new Map)}},lg=(...Q)=>new Xu(...Q)}),Ju,Z,ke=$(()=>{Ju=class{constructor(Q){Object.assign(this,Q)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map((Q)=>`${this[Q]}`).join(";")),this.key}},Z=(Q)=>new Ju(Q)}),ur,Yu,ve,Ve,k,he,el,lr,At,B,Bi,A,C,dg,Fi,Qu,pg,ne=$(()=>{X(),ee(),ur=64,Yu=(Q,J)=>{if(J===3)throw Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(Q)){case 10:return J>1?`vec${J}<f16>`:"f16";case 1:return J>1?`vec${J}<f32>`:"f32";case 6:return J>1?`vec${J}<i32>`:"i32";case 12:return J>1?`vec${J}<u32>`:"u32";case 7:if(J>1)throw Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(J>1)throw Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(J!==4)throw Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw Error(`Unknown data type: ${Q}`)}},ve=(Q,J=1)=>{let G=Yu(Q,J);return typeof G=="string"?G:G[0]},Ve=(Q,J=1)=>{let G=Yu(Q,J);return typeof G=="string"?G:G[1]},k=(...Q)=>{let J=[];return Q.forEach((G)=>{G.length!==0&&J.push({type:12,data:G},{type:12,data:S.computeStrides(G)})}),J},he=(Q)=>Q%4===0?4:Q%2===0?2:1,el=(Q="f32",J,G="0")=>!J||J===1?`${Q}(${G})`:`vec${J}<${Q}>(${G})`,lr=(Q,J,G)=>Q==="f32"?G:J===1?`f32(${G})`:`vec${J}<f32>(${G})`,At=(Q,J)=>J===4?`(${Q}.x + ${Q}.y + ${Q}.z + ${Q}.w)`:J===2?`(${Q}.x + ${Q}.y)`:J===3?`(${Q}.x + ${Q}.y + ${Q}.z)`:Q,B=(Q,J,G,H)=>Q.startsWith("uniforms.")&&G>4?typeof J=="string"?H==="f16"?`${Q}[(${J}) / 8][(${J}) % 8 / 4][(${J}) % 8 % 4]`:`${Q}[(${J}) / 4][(${J}) % 4]`:H==="f16"?`${Q}[${Math.floor(J/8)}][${Math.floor(J%8/4)}][${J%8%4}]`:`${Q}[${Math.floor(J/4)}][${J%4}]`:G>1?`${Q}[${J}]`:Q,Bi=(Q,J,G,H,K)=>{let z=typeof G=="number",q=z?G:G.length,F=[...Array(q).keys()],D=q<2?"u32":q<=4?`vec${q}<u32>`:`array<u32, ${q}>`,V=Yu(J,K),O=typeof V=="string"?V:V[1],P=typeof V=="string"?V:V[0],N={indices:D,value:O,storage:P,tensor:J},I=(m0)=>typeof m0=="string"?m0:`${m0}u`,R={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},w=z?"uniforms.":"",E=`${w}${Q}_shape`,T=`${w}${Q}_strides`,y="";for(let m0=0;m0<q-1;m0++)y+=`
let dim${m0} = current / ${B(T,m0,q)};
let rest${m0} = current % ${B(T,m0,q)};
indices[${m0}] = dim${m0};
current = rest${m0};
`;y+=`indices[${q-1}] = current;`;let x=q<2?"":`
fn o2i_${Q}(offset: u32) -> ${N.indices} {
var indices: ${N.indices};
var current = offset;
${y}
return indices;
}`,b=(m0)=>(R.offsetToIndices=!0,q<2?m0:`o2i_${Q}(${m0})`),g=[];if(q>=2)for(let m0=q-1;m0>=0;m0--)g.push(`${B(T,m0,q)} * (indices[${m0}])`);let l=q<2?"":`
fn i2o_${Q}(indices: ${N.indices}) -> u32 {
return ${g.join("+")};
}`,_=(m0)=>(R.indicesToOffset=!0,q<2?m0:`i2o_${Q}(${m0})`),a=(...m0)=>q===0?"0u":`${N.indices}(${m0.map(I).join(",")})`,r=(m0,ZQ)=>q<2?`${m0}`:`${B(m0,ZQ,q)}`,f0=(m0,ZQ,LQ)=>q<2?`${m0}=${LQ};`:`${B(m0,ZQ,q)}=${LQ};`,t={},p0=(m0,ZQ)=>{R.broadcastedIndicesToOffset=!0;let LQ=`${ZQ.name}broadcastedIndicesTo${Q}Offset`;if(LQ in t)return`${LQ}(${m0})`;let h0=[];for(let pQ=q-1;pQ>=0;pQ--){let iQ=ZQ.indicesGet("outputIndices",pQ+ZQ.rank-q);h0.push(`${r(T,pQ)} * (${iQ} % ${r(E,pQ)})`)}return t[LQ]=`fn ${LQ}(outputIndices: ${ZQ.type.indices}) -> u32 {
return ${h0.length>0?h0.join("+"):"0u"};
}`,`${LQ}(${m0})`},u0=(m0,ZQ)=>(()=>{if(N.storage===N.value)return`${Q}[${m0}]=${ZQ};`;if(N.storage==="vec2<u32>"&&N.value==="i32")return`${Q}[${m0}]=vec2<u32>(u32(${ZQ}), select(0u, 0xFFFFFFFFu, ${ZQ} < 0));`;if(N.storage==="vec2<u32>"&&N.value==="u32")return`${Q}[${m0}]=vec2<u32>(u32(${ZQ}), 0u);`;if(N.storage==="u32"&&N.value==="vec4<bool>")return`${Q}[${m0}]=dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(${ZQ}));`;throw Error(`not supported combination of storage type ${N.storage} and value type ${N.value} yet`)})(),d=(m0)=>(()=>{if(N.storage===N.value)return`${Q}[${m0}]`;if(N.storage==="vec2<u32>"&&N.value==="i32")return`i32(${Q}[${m0}].x)`;if(N.storage==="vec2<u32>"&&N.value==="u32")return`u32(${Q}[${m0}].x)`;if(N.storage==="u32"&&N.value==="vec4<bool>")return`vec4<bool>(bool(${Q}[${m0}] & 0xFFu), bool(${Q}[${m0}] & 0xFF00u), bool(${Q}[${m0}] & 0xFF0000u), bool(${Q}[${m0}] & 0xFF000000u))`;throw Error(`not supported combination of storage type ${N.storage} and value type ${N.value} yet`)})(),n=q<2?"":`
fn get_${Q}ByIndices(indices: ${N.indices}) -> ${O} {
return ${d(`i2o_${Q}(indices)`)};
}`,c0=q<2?"":(()=>{let m0=F.map((LQ)=>`d${LQ}: u32`).join(", "),ZQ=F.map((LQ)=>`d${LQ}`).join(", ");return`
fn get_${Q}(${m0}) -> ${O} {
return get_${Q}ByIndices(${a(ZQ)});
}`})(),WQ=(...m0)=>{if(m0.length!==q)throw Error(`indices length must be ${q}`);let ZQ=m0.map(I).join(",");return q===0?d("0u"):q===1?d(ZQ[0]):(R.get=!0,R.getByIndices=!0,R.indicesToOffset=!0,`get_${Q}(${ZQ})`)},R0=(m0)=>q<2?d(m0):(R.getByIndices=!0,R.indicesToOffset=!0,`get_${Q}ByIndices(${m0})`),l0=q<2?"":`
fn set_${Q}ByIndices(indices: ${N.indices}, value: ${O}) {
${u0(`i2o_${Q}(indices)`,"value")}
}`,d0=q<2?"":(()=>{let m0=F.map((LQ)=>`d${LQ}: u32`).join(", "),ZQ=F.map((LQ)=>`d${LQ}`).join(", ");return`
fn set_${Q}(${m0}, value: ${O}) {
set_${Q}ByIndices(${a(ZQ)}, value);
}`})();return{impl:()=>{let m0=[],ZQ=!1;return R.offsetToIndices&&(m0.push(x),ZQ=!0),R.indicesToOffset&&(m0.push(l),ZQ=!0),R.broadcastedIndicesToOffset&&(Object.values(t).forEach((LQ)=>m0.push(LQ)),ZQ=!0),R.set&&(m0.push(d0),ZQ=!0),R.setByIndices&&(m0.push(l0),ZQ=!0),R.get&&(m0.push(c0),ZQ=!0),R.getByIndices&&(m0.push(n),ZQ=!0),!z&&ZQ&&m0.unshift(`const ${E} = ${N.indices}(${G.join(",")});`,`const ${T} = ${N.indices}(${S.computeStrides(G).join(",")});`),m0.join(`
`)},type:N,offsetToIndices:b,indicesToOffset:_,broadcastedIndicesToOffset:p0,indices:a,indicesGet:r,indicesSet:f0,set:(...m0)=>{if(m0.length!==q+1)throw Error(`indices length must be ${q}`);let ZQ=m0[q];if(typeof ZQ!="string")throw Error("value must be string");let LQ=m0.slice(0,q).map(I).join(",");return q===0?u0("0u",ZQ):q===1?u0(LQ[0],ZQ):(R.set=!0,R.setByIndices=!0,R.indicesToOffset=!0,`set_${Q}(${LQ}, ${ZQ})`)},setByOffset:u0,setByIndices:(m0,ZQ)=>q<2?u0(m0,ZQ):(R.setByIndices=!0,R.indicesToOffset=!0,`set_${Q}ByIndices(${m0}, ${ZQ});`),get:WQ,getByOffset:d,getByIndices:R0,usage:H,name:Q,strides:T,shape:E,rank:q}},A=(Q,J,G,H=1)=>Bi(Q,J,G,"input",H),C=(Q,J,G,H=1)=>Bi(Q,J,G,"output",H),dg=(Q,J,G)=>Bi(Q,J,G,"atomicOutput",1),Fi=(Q,J,G,H=1)=>Bi(Q,J,G,"internal",H),Qu=class{constructor(Q,J){this.normalizedDispatchGroup=Q,this.limits=J,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(Q){return`if (global_idx >= ${typeof Q=="number"?`${Q}u`:Q}) { return; }`}mainStart(Q=ur){let J=typeof Q=="number"?Q:Q[0],G=typeof Q=="number"?1:Q[1],H=typeof Q=="number"?1:Q[2];if(J>this.limits.maxComputeWorkgroupSizeX||G>this.limits.maxComputeWorkgroupSizeY||H>this.limits.maxComputeWorkgroupSizeZ)throw Error(`workgroup size [${J}, ${G}, ${H}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(J*G*H>this.limits.maxComputeInvocationsPerWorkgroup)throw Error(`workgroup size [${J}, ${G}, ${H}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let K=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,z=K?`@builtin(global_invocation_id) global_id : vec3<u32>,
@builtin(workgroup_id) workgroup_id : vec3<u32>,
@builtin(local_invocation_index) local_idx : 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>`,q=K?`let global_idx = global_id.x;
let workgroup_index = workgroup_id.x;`:`let workgroup_index = workgroup_id.z * num_workgroups[0] * num_workgroups[1] +
workgroup_id.y * num_workgroups[0] + workgroup_id.x;
let global_idx = workgroup_index * ${J*G*H}u + local_idx;`;return`@compute @workgroup_size(${J}, ${G}, ${H})
fn main(${z}) {
${q}
`}appendVariableUniforms(Q){Q.rank!==0&&(Q.shape.startsWith("uniforms.")&&this.uniforms.push({name:Q.shape.replace("uniforms.",""),type:"u32",length:Q.rank}),Q.strides.startsWith("uniforms.")&&this.uniforms.push({name:Q.strides.replace("uniforms.",""),type:"u32",length:Q.rank}))}declareVariable(Q,J){if(Q.usage==="internal")throw Error("cannot use internal variable with declareVariable(). use registerInternalVariables() instead.");this.variables.push(Q),this.appendVariableUniforms(Q);let G=Q.usage==="input"?"read":"read_write",H=Q.usage==="atomicOutput"?"atomic<i32>":Q.type.storage;return`@group(0) @binding(${J}) var<storage, ${G}> ${Q.name}: array<${H}>;`}declareVariables(...Q){return Q.map((J)=>this.declareVariable(J,this.variableIndex++)).join(`
`)}registerInternalVariable(Q){if(Q.usage!=="internal")throw Error("cannot use input or output variable with registerInternalVariable(). use declareVariables() instead.");this.internalVariables.push(Q),this.appendVariableUniforms(Q)}registerInternalVariables(...Q){return Q.forEach((J)=>this.registerInternalVariable(J)),this}registerUniform(Q,J,G=1){return this.uniforms.push({name:Q,type:J,length:G}),this}registerUniforms(Q){return this.uniforms=this.uniforms.concat(Q),this}uniformDeclaration(){if(this.uniforms.length===0)return"";let Q=[];for(let{name:J,type:G,length:H}of this.uniforms)if(H&&H>4)G==="f16"?Q.push(`@align(16) ${J}:array<mat2x4<${G}>, ${Math.ceil(H/8)}>`):Q.push(`${J}:array<vec4<${G}>, ${Math.ceil(H/4)}>`);else{let K=H==null||H===1?G:`vec${H}<${G}>`;Q.push(`${J}:${K}`)}return`
struct Uniforms { ${Q.join(", ")} };
@group(0) @binding(${this.variableIndex}) var<uniform> uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map((Q)=>Q.impl()).join(`
`)+this.internalVariables.map((Q)=>Q.impl()).join(`
`)}get variablesInfo(){if(this.uniforms.length===0)return;let Q=(J)=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(J)];return this.uniforms.map((J)=>[Q(J.type),J.length??1])}},pg=(Q,J)=>new Qu(Q,J)}),qS,fg,jS,KS,XS,ZS,Ge,hg,mg,Pn=$(()=>{X(),ee(),ke(),ne(),qS=(Q,J)=>{if(!Q||Q.length!==1)throw Error("Transpose requires 1 input.");if(J.length!==0&&J.length!==Q[0].dims.length)throw Error(`perm size ${J.length} does not match input rank ${Q[0].dims.length}`)},fg=(Q,J)=>J.length!==0?J:[...Array(Q).keys()].reverse(),jS=(Q,J)=>S.sortBasedOnPerm(Q,fg(Q.length,J)),KS=(Q,J,G,H)=>{let K=`fn perm(i: ${H.type.indices}) -> ${G.type.indices} {
var a: ${G.type.indices};`;for(let z=0;z<J;++z)K+=`a[${Q[z]}]=i[${z}];`;return K+="return a;}"},XS=(Q,J)=>{let G=[],H=[];for(let K=0;K<Q.length;++K)Q[K]!==1&&G.push(Q[K]),Q[J[K]]!==1&&H.push(J[K]);return{newShape:G,newPerm:H}},ZS=(Q,J)=>{let G=0;for(let H=0;H<Q.length;++H)if(J[Q[H]]!==1){if(Q[H]<G)return!1;G=Q[H]}return!0},Ge=(Q,J)=>{let G=Q.dataType,H=Q.dims.length,K=fg(H,J),z=jS(Q.dims,K),q=Q.dims,F=z,D=H<2||ZS(K,Q.dims),V;if(D)return V=(R)=>{let w=A("input",G,q,4),E=C("output",G,F,4);return`
${R.registerUniform("output_size","u32").declareVariables(w,E)}
${R.mainStart()}
${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
output[global_idx] = input[global_idx];
}`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let R=S.size(z);return{outputs:[{dims:z,dataType:Q.dataType}],dispatchGroup:{x:Math.ceil(R/64/4)},programUniforms:[{type:12,data:Math.ceil(R/4)}]}},getShaderSource:V};let{newShape:O,newPerm:P}=XS(Q.dims,K),N=S.areEqual(P,[2,3,1]),I=S.areEqual(P,[3,1,2]);if(O.length===2||N||I){q=N?[O[0],O[1]*O[2]]:I?[O[0]*O[1],O[2]]:O,F=[q[1],q[0]];let R=16;return V=(w)=>{let E=A("a",G,q.length),T=C("output",G,F.length);return`
${w.registerUniform("output_size","u32").declareVariables(E,T)}
var<workgroup> tile : array<array<${T.type.value}, ${R+1}>, ${R}>;
${w.mainStart([R,R,1])}
let stride = (uniforms.output_shape[1] - 1) / ${R} + 1;
let workgroup_id_x = workgroup_index % stride;
let workgroup_id_y = workgroup_index / stride;
let input_col = workgroup_id_y * ${R}u + local_id.x;
let input_row = workgroup_id_x * ${R}u + local_id.y;
if (input_row < uniforms.a_shape[0] && input_col < uniforms.a_shape[1]) {
tile[local_id.y][local_id.x] = ${E.getByIndices(`${E.type.indices}(input_row, input_col)`)};
}
workgroupBarrier();
let output_col = workgroup_id_x * ${R}u + local_id.x;
let output_row = workgroup_id_y * ${R}u + local_id.y;
if (output_row < uniforms.output_shape[0] && output_col < uniforms.output_shape[1]) {
${T.setByIndices(`${T.type.indices}(output_row, output_col)`,"tile[local_id.x][local_id.y]")}
}
}`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let w=S.size(z);return{outputs:[{dims:z,dataType:Q.dataType}],dispatchGroup:{x:Math.ceil(F[1]/R),y:Math.ceil(F[0]/R)},programUniforms:[{type:12,data:w},...k(q,F)]}},getShaderSource:V}}return V=(R)=>{let w=A("a",G,q.length),E=C("output",G,F.length);return`
${R.registerUniform("output_size","u32").declareVariables(w,E)}
${KS(K,H,w,E)}
${R.mainStart()}
${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let indices = ${E.offsetToIndices("global_idx")};
let aIndices = perm(indices);
${E.setByOffset("global_idx",w.getByIndices("aIndices"))}
}`},{name:"Transpose",shaderCache:{hint:`${J}`,inputDependencies:["rank"]},getRunData:()=>{let R=S.size(z);return{outputs:[{dims:z,dataType:Q.dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...k(q,F)]}},getShaderSource:V}},hg=(Q,J)=>{qS(Q.inputs,J.perm),Q.compute(Ge(Q.inputs[0],J.perm))},mg=(Q)=>Z({perm:Q.perm})}),JS,QS,YS,e1,t1,n1,r1,o1,i1,a1,yn,gg,bg,yg,_g,xg,wg,Tg,vg,Ig,Sg,$g=$(()=>{X(),ee(),ne(),Vi(),Pn(),JS={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"},QS={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"},YS={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},e1={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},t1=(Q,J)=>{let G=[];for(let H=J-Q;H<J;++H)G.push(H);return G},n1=(Q,J)=>{let G=[],H=Q.length;for(let z=0;z<H;z++)J.indexOf(z)===-1&&G.push(Q[z]);let K=J.map((z)=>Q[z]);return[G,K]},r1=(Q,J)=>{let G=Q.length+J.length,H=[],K=0;for(let z=0;z<G;z++)J.indexOf(z)===-1?H.push(Q[K++]):H.push(1);return H},o1=(Q,J)=>{for(let G=0;G<Q.length;++G)if(Q[Q.length-G-1]!==J-1-G)return!1;return!0},i1=(Q,J)=>{let G=[];if(!o1(Q,J)){for(let H=0;H<J;++H)Q.indexOf(H)===-1&&G.push(H);Q.forEach((H)=>G.push(H))}return G},a1=(Q,J,G,H,K,z,q)=>{let F=G[0].dims,D=S.size(z),V=S.size(q),O=A("_A",G[0].dataType,F),P=C("output",K,z),N=64;D===1&&(N=256);let I=`
var<workgroup> aBestValues : array<f32, ${N}>;
`,R=(w)=>`
${w.registerUniform("reduceSize","u32").declareVariables(O,P)}
${I}
fn DIV_CEIL(a : u32, b : u32) -> u32 {
return ((a - 1u) / b + 1u);
}
${w.mainStart(N)}
let outputIndex = global_idx / ${N};
let offset = outputIndex * uniforms.reduceSize;
var bestValue = f32(${YS[H]});
let Length = uniforms.reduceSize;
for (var k = local_idx; k < Length; k = k + ${N}) {
let candidate = f32(${O.getByOffset("offset + k")});
bestValue = ${JS[H]};
}
aBestValues[local_idx] = bestValue;
workgroupBarrier();
var reduceSize = min(Length, ${N}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 = ${QS[H]};
aBestValues[local_idx] = bestValue;
}
reduceSize = interval;
workgroupBarrier();
}
if (local_idx == 0u) {
${P.setByOffset("outputIndex",`${H==="mean"?`${P.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${P.type.storage}(${e1[H]})`}`)};
}
}`;return{name:Q,shaderCache:{hint:`${J};${N}`,inputDependencies:["type"]},getShaderSource:R,getRunData:()=>({outputs:[{dims:z,dataType:K}],dispatchGroup:{x:D},programUniforms:[{type:12,data:V}]})}},yn=(Q,J,G,H)=>{let K=Q.inputs.length===1?G:tl(Q.inputs,G),z=K.axes;z.length===0&&!K.noopWithEmptyAxes&&(z=Q.inputs[0].dims.map((I,R)=>R));let q=S.normalizeAxes(z,Q.inputs[0].dims.length),F=q,D=Q.inputs[0],V=i1(F,Q.inputs[0].dims.length);V.length>0&&(D=Q.compute(Ge(Q.inputs[0],V),{inputs:[0],outputs:[-1]})[0],F=t1(F.length,D.dims.length));let[O,P]=n1(D.dims,F),N=O;K.keepDims&&(N=r1(O,q)),Q.compute(a1(J,K.cacheKey,[D],H,Q.inputs[0].dataType,N,P),{inputs:[D]})},gg=(Q,J)=>{yn(Q,"ReduceMeanShared",J,"mean")},bg=(Q,J)=>{yn(Q,"ReduceL1Shared",J,"l1")},yg=(Q,J)=>{yn(Q,"ReduceL2Shared",J,"l2")},_g=(Q,J)=>{yn(Q,"ReduceLogSumExpShared",J,"logSumExp")},xg=(Q,J)=>{yn(Q,"ReduceMaxShared",J,"max")},wg=(Q,J)=>{yn(Q,"ReduceMinShared",J,"min")},Tg=(Q,J)=>{yn(Q,"ReduceProdShared",J,"prod")},vg=(Q,J)=>{yn(Q,"ReduceSumShared",J,"sum")},Ig=(Q,J)=>{yn(Q,"ReduceSumSquareShared",J,"sumSquare")},Sg=(Q,J)=>{yn(Q,"ReduceLogSumShared",J,"logSum")}}),_n,s1,Gi,tl,xn,u1,l1,c1,d1,p1,f1,h1,m1,g1,b1,wn,Ag,Pg,Og,Eg,Cg,Dg,kg,Lg,Rg,Ng,Vi=$(()=>{X(),ee(),ke(),ne(),$g(),_n=(Q)=>{if(!Q||Q.length===0||Q.length>2)throw Error("Reduce op requires 1 or 2 inputs.");if(Q.length===2&&Q[1].dims.length!==1)throw Error("Invalid axes input dims.")},s1=(Q)=>["","",`var value = ${Q.getByIndices("input_indices")};`,""],Gi=(Q,J,G,H,K,z,q=!1,F=!1)=>{let D=[],V=G[0].dims,O=V.length,P=S.normalizeAxes(K,O),N=!F&&P.length===0;V.forEach((w,E)=>{N||P.indexOf(E)>=0?q&&D.push(1):D.push(w)});let I=D.length,R=S.size(D);return{name:Q,shaderCache:J,getShaderSource:(w)=>{let E=[],T=A("_A",G[0].dataType,O),y=C("output",z,I),x=H(T,y,P),b=x[2];for(let g=0,l=0;g<O;g++)N||P.indexOf(g)>=0?(q&&l++,b=`for(var j${g}: u32 = 0; j${g} < ${V[g]}; j${g}++) {
${x[2].includes("last_index")?`let last_index = j${g};`:""}
${T.indicesSet("input_indices",g,`j${g}`)}
${b}
}`):(E.push(`${T.indicesSet("input_indices",g,y.indicesGet("output_indices",l))};`),l++);return`
${w.registerUniform("output_size","u32").declareVariables(T,y)}
${w.mainStart()}
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
var input_indices: ${T.type.indices};
let output_indices = ${y.offsetToIndices("global_idx")};
${E.join(`
`)}
${x[0]} // init ops for reduce max/min
${x[1]}
${b}
${x[3]}
${x.length===4?y.setByOffset("global_idx","value"):x.slice(4).join(`
`)}
}`},getRunData:()=>({outputs:[{dims:D,dataType:z}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:[{type:12,data:R},...k(V,D)]})}},tl=(Q,J)=>{let G=[];return Q[1].dims[0]>0&&Q[1].getBigInt64Array().forEach((H)=>G.push(Number(H))),Z({axes:G,keepDims:J.keepDims,noopWithEmptyAxes:J.noopWithEmptyAxes})},xn=(Q,J,G,H)=>{let K=Q.inputs,z=K.length===1?G:tl(K,G);Q.compute(Gi(J,{hint:z.cacheKey,inputDependencies:["rank"]},[K[0]],z.noopWithEmptyAxes&&z.axes.length===0?s1:H,z.axes,K[0].dataType,z.keepDims,z.noopWithEmptyAxes),{inputs:[0]})},u1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceLogSum",J,(G,H)=>[`var value = ${H.type.storage}(0);`,"",`value += ${G.getByIndices("input_indices")};`,"value = log(value);"])},l1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceL1",J,(G,H)=>[`var value = ${H.type.storage}(0);`,"",`value += abs(${G.getByIndices("input_indices")});`,""])},c1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceL2",J,(G,H)=>[`var t = ${H.type.value}(0); var value = ${H.type.value}(0);`,"",`t = ${G.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},d1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceLogSumExp",J,(G,H)=>[`var value = ${H.type.storage}(0);`,"",`value += exp(${G.getByIndices("input_indices")});`,"value = log(value);"])},p1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceMax",J,(G,H,K)=>{let z=[];for(let q=0;q<G.rank;q++)(K.indexOf(q)>=0||K.length===0)&&z.push(G.indicesSet("input_indices",q,0));return[`${z.join(`
`)}`,`var value = ${G.getByIndices("input_indices")};`,`value = max(value, ${G.getByIndices("input_indices")});`,""]})},f1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceMean",J,(G,H,K)=>{let z=1;for(let q=0;q<G.rank;q++)(K.indexOf(q)>=0||K.length===0)&&(z*=Q.inputs[0].dims[q]);return["var sum = f32(0);","",`sum += f32(${G.getByIndices("input_indices")});`,`let value = ${H.type.value}(sum / ${z});`]})},h1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceMin",J,(G,H,K)=>{let z=[];for(let q=0;q<G.rank;q++)(K.indexOf(q)>=0||K.length===0)&&z.push(`input_indices[${q}] = 0;`);return[`${z.join(`
`)}`,`var value = ${G.getByIndices("input_indices")};`,`value = min(value, ${G.getByIndices("input_indices")});`,""]})},m1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceProd",J,(G,H)=>[`var value = ${H.type.storage}(1);`,"",`value *= ${G.getByIndices("input_indices")};`,""])},g1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceSum",J,(G,H)=>[`var value = ${H.type.storage}(0);`,"",`value += ${G.getByIndices("input_indices")};`,""])},b1=(Q,J)=>{_n(Q.inputs),xn(Q,"ReduceSumSquare",J,(G,H)=>[`var t = ${H.type.value}(0); var value = ${H.type.value}(0);`,"",`t = ${G.getByIndices("input_indices")}; value += t * t;`,""])},wn=(Q,J,G)=>{if(J.length===0)return G;let H=1,K=1;for(let z=0;z<J.length;z++)J.indexOf(z)===-1?H*=Q[z]:K*=Q[z];return K<32&&H>1024},Ag=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?f1(Q,J):gg(Q,J)},Pg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?l1(Q,J):bg(Q,J)},Og=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?c1(Q,J):yg(Q,J)},Eg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?d1(Q,J):_g(Q,J)},Cg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?p1(Q,J):xg(Q,J)},Dg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?h1(Q,J):wg(Q,J)},kg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?m1(Q,J):Tg(Q,J)},Lg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?g1(Q,J):vg(Q,J)},Rg=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?b1(Q,J):Ig(Q,J)},Ng=(Q,J)=>{wn(Q.inputs[0].dims,J.axes,J.noopWithEmptyAxes)?u1(Q,J):Sg(Q,J)}}),zg,Mg,Bg,nl,Fg=$(()=>{X(),ke(),Vi(),zg=(Q)=>{if(!Q||Q.length===0||Q.length>2)throw Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(Q[0].dataType!==1)throw Error("Invalid input type.")},Mg=(Q,J)=>{zg(Q.inputs);let G=(H,K,z)=>{let q=[];for(let F=0;F<H.rank;F++)(z.indexOf(F)>=0||z.length===0)&&q.push(`input_indices[${F}] = 0;`);return[`${q.join(`
`)}`,`var value = ${H.getByIndices("input_indices")};
var best_index : i32 = 0;`,`if (${H.getByIndices("input_indices")} ${J.selectLastIndex>0?"<=":"<"} value) {
value = ${H.getByIndices("input_indices")};
best_index = i32(last_index);
}`,"",K.setByOffset("global_idx","best_index")]};Q.compute(Gi("ArgMin",{hint:J.cacheKey,inputDependencies:["rank"]},[Q.inputs[0]],G,[J.axis],7,J.keepDims),{inputs:[0]})},Bg=(Q,J)=>{zg(Q.inputs);let G=(H,K,z)=>{let q=[];for(let F=0;F<H.rank;F++)(z.indexOf(F)>=0||z.length===0)&&q.push(`input_indices[${F}] = 0;`);return[`${q.join(`
`)}`,`var value = ${H.getByIndices("input_indices")};
var best_index : i32 = 0;`,`if (${H.getByIndices("input_indices")} ${J.selectLastIndex>0?">=":">"} value) {
value = ${H.getByIndices("input_indices")};
best_index = i32(last_index);
}`,"",K.setByOffset("global_idx","best_index")]};Q.compute(Gi("argMax",{hint:J.cacheKey,inputDependencies:["rank"]},[Q.inputs[0]],G,[J.axis],7,J.keepDims),{inputs:[0]})},nl=(Q)=>Z(Q)}),y1,rl,_1,x1,w1,Ar,T1,Vg,Ui=$(()=>{X(),ee(),Mi(),ne(),y1=(Q,J)=>{let G=Q[0],H=Q[1],K=Q[2],z=Q[3],q=Q[4],F=Q[5];if(q&&F)throw Error("Attention cannot have both past and attention_bias");if(G.dims.length!==3)throw Error('Input "input" must have 3 dimensions');let D=G.dims[0],V=G.dims[1],O=G.dims[2];if(K.dims.length!==1)throw Error('Input "bias" is expected to have 1 dimensions');if(H.dims.length!==2)throw Error('Input "weights" is expected to have 2 dimensions');if(H.dims[0]!==O)throw Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(K.dims[0]!==H.dims[1])throw Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let P=K.dims[0]/3,N=P,I=N;if(J.qkvHiddenSizes.length>0){if(J.qkvHiddenSizes.length!==3)throw Error("qkv_hidden_sizes attribute should have 3 elements");for(let x of J.qkvHiddenSizes)if(x%J.numHeads!==0)throw Error("qkv_hidden_sizes should be divisible by num_heads");P=J.qkvHiddenSizes[0],N=J.qkvHiddenSizes[1],I=J.qkvHiddenSizes[2]}let R=V;if(P!==N)throw Error("qkv_hidden_sizes first element should be same as the second");if(K.dims[0]!==P+N+I)throw Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let w=0;if(q){if(N!==I)throw Error('Input "past" expect k_hidden_size == v_hidden_size');if(q.dims.length!==5)throw Error('Input "past" must have 5 dimensions');if(q.dims[0]!==2)throw Error('Input "past" first dimension must be 2');if(q.dims[1]!==D)throw Error('Input "past" second dimension must be batch_size');if(q.dims[2]!==J.numHeads)throw Error('Input "past" third dimension must be num_heads');if(q.dims[4]!==N/J.numHeads)throw Error('Input "past" fifth dimension must be k_hidden_size / num_heads');J.pastPresentShareBuffer||(w=q.dims[3])}let E=R+w,T=-1,y=0;if(z)throw Error("Mask not supported");if(q)throw Error("past is not supported");if(F){if(F.dims.length!==4)throw Error('Input "attention_bias" must have 4 dimensions');if(F.dims[0]!==D||F.dims[1]!==J.numHeads||F.dims[2]!==V||F.dims[3]!==E)throw Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:D,sequenceLength:V,pastSequenceLength:w,kvSequenceLength:R,totalSequenceLength:E,maxSequenceLength:T,inputHiddenSize:O,hiddenSize:P,vHiddenSize:I,headSize:Math.floor(P/J.numHeads),vHeadSize:Math.floor(I/J.numHeads),numHeads:J.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:J.maskFilterValue,maskType:y,scale:J.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},rl=(Q,J,G)=>J&&Q?`
let total_sequence_length_input = u32(${J.getByOffset("0")});
let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length);
let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input;
let is_first_prompt: bool = is_subsequent_prompt == false && sequence_length == total_sequence_length_input;
total_sequence_length = u32(${Q?.getByOffset("batchIdx")}) + 1;
var past_sequence_length: u32 = 0;
if (is_first_prompt == false) {
past_sequence_length = total_sequence_length - sequence_length;
}
`:`
${G?"let past_sequence_length = uniforms.past_sequence_length":""};
let present_sequence_length = total_sequence_length;
`,_1=(Q,J,G,H,K,z,q,F)=>{let D=he(q?1:z),V=64,O=z/D;O<V&&(V=32);let P=Math.ceil(z/D/V),N=[{type:12,data:J},{type:12,data:G},{type:12,data:H},{type:12,data:K},{type:12,data:O},{type:12,data:P}],I=ve(Q.dataType,D),R=Ve(1,D),w=["type"];q&&w.push("type"),F&&w.push("type");let E=(T)=>{let y=C("x",Q.dataType,Q.dims,D),x=[y],b=q?A("seq_lens",q.dataType,q.dims):void 0;b&&x.push(b);let g=F?A("total_sequence_length_input",F.dataType,F.dims):void 0;g&&x.push(g);let l=Ve(Q.dataType),_=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return`
var<workgroup> thread_max: array<f32, ${V}>;
var<workgroup> thread_sum: array<f32, ${V}>;
${T.registerUniforms(_).declareVariables(...x)}
${T.mainStart([V,1,1])}
let batchIdx = workgroup_id.z / uniforms.num_heads;
let headIdx = workgroup_id.z % uniforms.num_heads;
let sequence_length = uniforms.sequence_length;
var total_sequence_length = uniforms.total_sequence_length;
${rl(b,g,!1)}
let local_offset = local_idx * uniforms.elements_per_thread;
let offset = (global_idx / ${V}) * uniforms.total_sequence_length + local_offset;
let seq_causal_length = ${q?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"};
var thread_max_vector = ${R}(-3.4028234663852886e+38f);
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
thread_max_vector = max(${R}(x[offset + i]), thread_max_vector);
}
thread_max[local_idx] = ${(()=>{switch(D){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 Error(`Unsupported components: ${D}`)}})()};
workgroupBarrier();
var max_value = f32(-3.4028234663852886e+38f);
for (var i = 0u; i < ${V}; i++) {
max_value = max(thread_max[i], max_value);
}
var sum_vector = ${R}(0);
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
sum_vector += exp(${R}(x[offset + i]) - max_value);
}
thread_sum[local_idx] = ${(()=>{switch(D){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 Error(`Unsupported components: ${D}`)}})()};
workgroupBarrier();
var sum: f32 = 0;
for (var i = 0u; i < ${V}; i++) {
sum += thread_sum[i];
}
if (sum == 0) {
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
x[offset + i] = ${y.type.value}(${l}(1.0) / ${l}(seq_causal_length));
}
} else {
for (var i: u32 = 0; i < uniforms.elements_per_thread && i + local_offset < seq_causal_length; i++) {
var f32input = ${R}(x[offset + i]);
x[offset + i] = ${y.type.value}(exp(f32input - max_value) / sum);
}
}
${q?`
for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) {
x[offset + total_seq_id] = ${y.type.value}(${l}(0));
}`:""};
}`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${V};${I};${D}`,inputDependencies:w},getShaderSource:E,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:K,z:J*G},programUniforms:N})}},x1=(Q,J,G,H,K,z,q,F,D)=>{let V=q+z.kvSequenceLength,O=[z.batchSize,z.numHeads,z.sequenceLength,V],P=Q>1&&H,N=z.kvNumHeads?z.kvNumHeads:z.numHeads,I=P?[z.batchSize,N,V,z.headSize]:void 0,R=z.nReps?z.nReps:1,w=z.scale===0?1/Math.sqrt(z.headSize):z.scale,E=he(z.headSize),T=z.headSize/E,y=12,x={x:Math.ceil(V/y),y:Math.ceil(z.sequenceLength/y),z:z.batchSize*z.numHeads},b=[{type:12,data:z.sequenceLength},{type:12,data:T},{type:12,data:V},{type:12,data:z.numHeads},{type:12,data:z.headSize},{type:1,data:w},{type:12,data:q},{type:12,data:z.kvSequenceLength},{type:12,data:R}],g=P&&H&&S.size(H.dims)>0,l=["type","type"];g&&l.push("type"),K&&l.push("type"),F&&l.push("type"),D&&l.push("type");let _=[{dims:O,dataType:J.dataType,gpuDataType:0}];P&&_.push({dims:I,dataType:J.dataType,gpuDataType:0});let a=(r)=>{let f0=A("q",J.dataType,J.dims,E),t=A("key",G.dataType,G.dims,E),p0=[f0,t];if(g){let l0=A("past_key",H.dataType,H.dims,E);p0.push(l0)}K&&p0.push(A("attention_bias",K.dataType,K.dims));let u0=F?A("seq_lens",F.dataType,F.dims):void 0;u0&&p0.push(u0);let d=D?A("total_sequence_length_input",D.dataType,D.dims):void 0;d&&p0.push(d);let n=C("output",J.dataType,O),c0=[n];P&&c0.push(C("present_key",J.dataType,I,E));let WQ=Ve(1,E),R0=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
const TILE_SIZE = ${y}u;
var<workgroup> tileQ: array<${f0.type.storage}, ${y*y}>;
var<workgroup> tileK: array<${f0.type.storage}, ${y*y}>;
${r.registerUniforms(R0).declareVariables(...p0,...c0)}
${r.mainStart([y,y,1])}
// x holds the N and y holds the M
let headIdx = workgroup_id.z % uniforms.num_heads;
let kvHeadIdx = ${R===1?"headIdx":"headIdx / uniforms.n_reps"};
let kv_num_heads = ${R===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
let batchIdx = workgroup_id.z / uniforms.num_heads;
let m = workgroup_id.y * TILE_SIZE;
let n = workgroup_id.x * TILE_SIZE;
let sequence_length = uniforms.M;
var total_sequence_length = uniforms.N;
${rl(u0,d,!0)}
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx;
let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
${g&&P?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""};
let kOffset = absKvHeadIdx * uniforms.kv_sequence_length * uniforms.K;
${P?"let presentKeyOffset = absKvHeadIdx * uniforms.N * uniforms.K;":""}
var value = ${WQ}(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;
${g&&P?`
if (n + local_id.y < past_sequence_length) {
tileK[idx] = past_key[pastKeyOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
} else if (n + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
tileK[idx] = key[kOffset + (n + local_id.y - past_sequence_length) * uniforms.K + w + local_id.x];
}`:`
if (n + local_id.y < uniforms.kv_sequence_length) {
tileK[idx] = key[kOffset + (n + local_id.y) * uniforms.K + w + local_id.x];
}`}
${P?`if (n + local_id.y < present_sequence_length) {
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 += ${WQ}(tileQ[TILE_SIZE * local_id.y + k] * tileK[TILE_SIZE * local_id.x + k]);
}
workgroupBarrier();
}
if (global_id.y < uniforms.M && global_id.x < total_sequence_length) {
let headOffset = workgroup_id.z * uniforms.M * uniforms.N;
let outputIdx = headOffset + global_id.y * uniforms.N + global_id.x;
var sum: f32 = ${(()=>{switch(E){case 1:return"value";case 2:return"value.x + value.y";case 4:return"value.x + value.y + value.z + value.w";default:throw Error(`Unsupported components: ${E}`)}})()};
output[outputIdx] = ${n.type.value} (sum * uniforms.alpha) + ${K?"attention_bias[outputIdx]":"0.0"};
}
}`};return{name:"AttentionProbs",shaderCache:{hint:`${E};${K!==void 0};${H!==void 0};${Q}`,inputDependencies:l},getRunData:()=>({outputs:_,dispatchGroup:x,programUniforms:b}),getShaderSource:a}},w1=(Q,J,G,H,K,z,q=void 0,F=void 0)=>{let D=z+K.kvSequenceLength,V=K.nReps?K.nReps:1,O=K.vHiddenSize*V,P=Q>1&&H,N=K.kvNumHeads?K.kvNumHeads:K.numHeads,I=P?[K.batchSize,N,D,K.headSize]:void 0,R=[K.batchSize,K.sequenceLength,O],w=12,E={x:Math.ceil(K.vHeadSize/w),y:Math.ceil(K.sequenceLength/w),z:K.batchSize*K.numHeads},T=[{type:12,data:K.sequenceLength},{type:12,data:D},{type:12,data:K.vHeadSize},{type:12,data:K.numHeads},{type:12,data:K.headSize},{type:12,data:O},{type:12,data:z},{type:12,data:K.kvSequenceLength},{type:12,data:V}],y=P&&H&&S.size(H.dims)>0,x=["type","type"];y&&x.push("type"),q&&x.push("type"),F&&x.push("type");let b=[{dims:R,dataType:J.dataType,gpuDataType:0}];P&&b.push({dims:I,dataType:J.dataType,gpuDataType:0});let g=(l)=>{let _=A("probs",J.dataType,J.dims),a=A("v",G.dataType,G.dims),r=[_,a];y&&r.push(A("past_value",H.dataType,H.dims));let f0=q?A("seq_lens",q.dataType,q.dims):void 0;q&&r.push(f0);let t=F?A("total_sequence_length_input",F.dataType,F.dims):void 0;F&&r.push(t);let p0=[C("output",J.dataType,R)];P&&p0.push(C("present_value",J.dataType,I));let u0=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return`
const TILE_SIZE = ${w}u;
var<workgroup> tileQ: array<${_.type.value}, ${w*w}>;
var<workgroup> tileV: array<${_.type.value}, ${w*w}>;
${l.registerUniforms(u0).declareVariables(...r,...p0)}
${l.mainStart([w,w,1])}
let headIdx = workgroup_id.z % uniforms.num_heads;
let batchIdx = workgroup_id.z / uniforms.num_heads;
let kvHeadIdx = ${V===1?"headIdx":"headIdx / uniforms.n_reps"};
let kv_num_heads = ${V===1?"uniforms.num_heads":"uniforms.num_heads / uniforms.n_reps"};
let m = global_id.y;
let n = global_id.x;
let sequence_length = uniforms.M;
var total_sequence_length = uniforms.K;
${rl(f0,t,!0)}
let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K;
let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch
${y&&P?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""};
let vOffset = absKvHeadIdx * uniforms.N * uniforms.kv_sequence_length + n;
${P?"let presentValueOffset = absKvHeadIdx * uniforms.N * uniforms.K + n;":""}
var value = ${_.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;
${y&&P?`
if (w + local_id.y < past_sequence_length) {
tileV[idx] = past_value[pastValueOffset + (w + local_id.y) * uniforms.N];
} else if (w + local_id.y - past_sequence_length < uniforms.kv_sequence_length) {
tileV[idx] = v[vOffset + (w + local_id.y - past_sequence_length) * uniforms.N];
}
`:`
if (w + local_id.y < uniforms.kv_sequence_length) {
tileV[idx] = v[vOffset + (w + local_id.y) * uniforms.N];
}`}
${P?`
if (w + local_id.y < present_sequence_length) {
present_value[presentValueOffset + (w + local_id.y) * uniforms.N] = tileV[idx];
}`:""}
}
workgroupBarrier();
for (var k: u32 = 0u; k < TILE_SIZE && w+k < total_sequence_length; k++) {
value += tileQ[TILE_SIZE * local_id.y + k] * tileV[TILE_SIZE * k + local_id.x];
}
workgroupBarrier();
}
// we need to transpose output from BNSH_v to BSND_v
if (m < uniforms.M && n < uniforms.N) {
let outputIdx = batchIdx * uniforms.M * uniforms.v_hidden_size + m * uniforms.v_hidden_size
+ headIdx * uniforms.N + n;
output[outputIdx] = value;
}
}`};return{name:"AttentionScore",shaderCache:{hint:`${H!==void 0};${Q}`,inputDependencies:x},getRunData:()=>({outputs:b,dispatchGroup:E,programUniforms:T}),getShaderSource:g}},Ar=(Q,J,G,H,K,z,q,F,D,V,O=void 0,P=void 0)=>{let N=Math.min(Q.outputCount,1+(q?1:0)+(F?1:0)),I=N>1?q:void 0,R=N>1?F:void 0,w=N>1?V.pastSequenceLength:0,E=w+V.kvSequenceLength,T=D&&S.size(D.dims)>0?D:void 0,y=[J,G];I&&S.size(I.dims)>0&&y.push(I),T&&y.push(T),O&&y.push(O),P&&y.push(P);let x=Q.compute(x1(N,J,G,I,T,V,w,O,P),{inputs:y,outputs:N>1?[-1,1]:[-1]})[0];Q.compute(_1(x,V.batchSize,V.numHeads,w,V.sequenceLength,E,O,P),{inputs:O&&P?[x,O,P]:[x],outputs:[]});let b=[x,H];R&&S.size(R.dims)>0&&b.push(R),O&&b.push(O),P&&b.push(P),Q.compute(w1(N,x,H,R,V,w,O,P),{inputs:b,outputs:N>1?[0,2]:[0]})},T1=(Q,J)=>{let G=[J.batchSize,J.numHeads,J.sequenceLength,J.headSize],H=J.sequenceLength,K=J.inputHiddenSize,z=J.headSize,q=12,F={x:Math.ceil(J.headSize/q),y:Math.ceil(J.sequenceLength/q),z:J.batchSize*J.numHeads},D=[Q.inputs[0],Q.inputs[1],Q.inputs[2]],V=[{type:12,data:H},{type:12,data:K},{type:12,data:z},{type:12,data:J.numHeads},{type:12,data:J.headSize},{type:12,data:J.hiddenSize},{type:12,data:J.hiddenSize+J.hiddenSize+J.vHiddenSize}],O=(P)=>{let N=C("output_q",D[0].dataType,G),I=C("output_k",D[0].dataType,G),R=C("output_v",D[0].dataType,G),w=A("input",D[0].dataType,D[0].dims),E=A("weight",D[1].dataType,D[1].dims),T=A("bias",D[2].dataType,D[2].dims),y=w.type.storage,x=[{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 = ${q}u;
var<workgroup> tileInput: array<${y}, ${q*q}>;
var<workgroup> tileWeightQ: array<${y}, ${q*q}>;
var<workgroup> tileWeightK: array<${y}, ${q*q}>;
var<workgroup> tileWeightV: array<${y}, ${q*q}>;
${P.registerUniforms(x).declareVariables(w,E,T,N,I,R)}
${P.mainStart([q,q,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 = ${y}(0);
var valueK = ${y}(0);
var valueV = ${y}(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 Q.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:G,dataType:Q.inputs[0].dataType,gpuDataType:0},{dims:G,dataType:Q.inputs[0].dataType,gpuDataType:0},{dims:G,dataType:Q.inputs[0].dataType,gpuDataType:0}],dispatchGroup:F,programUniforms:V}),getShaderSource:O},{inputs:D,outputs:[-1,-1,-1]})},Vg=(Q,J)=>{let G=y1(Q.inputs,J),[H,K,z]=T1(Q,G);return Ar(Q,H,K,z,Q.inputs[4],void 0,void 0,void 0,Q.inputs[5],G)}}),v1,I1,S1,Gg,Ug=$(()=>{qe(),X(),ee(),ke(),ne(),v1=(Q,J)=>{if(!Q||Q.length!==5)throw Error("BatchNormalization requires 5 inputs");let G=(H,K,z)=>{let q=K.length;if(q!==H.length)throw Error(`${z}: num dimensions != ${q}`);K.forEach((F,D)=>{if(F!==H[D])throw Error(`${z}: dim[${D}] do not match`)})};if(Q[0].dims.length>1){let H=J.format==="NHWC"?J.spatial?Q[0].dims.slice(-1):Q[0].dims.slice(-1).concat(Q[0].dims.slice(1,Q[0].dims.length-1)):Q[0].dims.slice(1,J.spatial?2:void 0);G(Q[1].dims,H,"Invalid input scale"),G(Q[2].dims,H,"Invalid input B"),G(Q[3].dims,H,"Invalid input mean"),G(Q[4].dims,H,"Invalid input var")}else G(Q[1].dims,[1],"Invalid input scale"),G(Q[2].dims,[1],"Invalid input B"),G(Q[3].dims,[1],"Invalid input mean"),G(Q[4].dims,[1],"Invalid input var")},I1=(Q,J)=>{let{epsilon:G,spatial:H,format:K}=J,z=Q[0].dims,q=H?he(z[z.length-1]):1,F=K==="NHWC"&&z.length>1?q:1,D=S.size(z)/q,V=H,O=V?z.length:z,P=A("x",Q[0].dataType,Q[0].dims,q),N=A("scale",Q[1].dataType,Q[1].dims,F),I=A("bias",Q[2].dataType,Q[2].dims,F),R=A("inputMean",Q[3].dataType,Q[3].dims,F),w=A("inputVar",Q[4].dataType,Q[4].dims,F),E=C("y",Q[0].dataType,O,q),T=()=>{let x="";if(H)x=`let cOffset = ${z.length===1?"0u":K==="NHWC"?`outputIndices[${z.length-1}] / ${q}`:"outputIndices[1]"};`;else if(K==="NCHW")x=`
${E.indicesSet("outputIndices","0","0")}
let cOffset = ${E.indicesToOffset("outputIndices")};`;else{x=`var cIndices = ${N.type.indices}(0);
cIndices[0] = outputIndices[${z.length-1}];`;for(let b=1;b<N.rank;b++)x+=`cIndices[${b}] = outputIndices[${b}];`;x+=`let cOffset = ${N.indicesToOffset("cIndices")};`}return x},y=(x)=>`
const epsilon = ${G};
${x.registerUniform("outputSize","u32").declareVariables(P,N,I,R,w,E)}
${x.mainStart()}
${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var outputIndices = ${E.offsetToIndices(`global_idx * ${q}`)};
${T()}
let scale = ${N.getByOffset("cOffset")};
let bias = ${I.getByOffset("cOffset")};
let inputMean = ${R.getByOffset("cOffset")};
let inputVar = ${w.getByOffset("cOffset")};
let x = ${P.getByOffset("global_idx")};
let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias;
${E.setByOffset("global_idx","value")}
}`;return{name:"BatchNormalization",shaderCache:{hint:`${J.epsilon}_${J.format}_${H}_${q}`,inputDependencies:V?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:Q[0].dims,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:V?[{type:12,data:D},...k(z)]:[{type:12,data:D}]})}},S1=(Q)=>Z(Q),Gg=(Q,J)=>{let{inputs:G,outputCount:H}=Q,K=S1({...J,outputCount:H});if(Y.webgpu.validateInputContent&&v1(G,K),J.trainingMode)throw Error("BatchNormalization trainingMode is not supported yet.");Q.compute(I1(G,K))}}),$1,A1,Wg,Hg=$(()=>{ee(),ne(),$1=(Q)=>{if(Q[0].dims.length!==3)throw Error("input should have 3 dimensions");if(![320,640,1280].includes(Q[0].dims[2]))throw Error("number of channels should be 320, 640 or 1280");if(Q[1].dims.length!==1)throw Error("bias is expected to have 1 dimensions");if(Q[0].dims[2]!==Q[1].dims[0])throw Error("last dimension of input and bias are not the same")},A1=(Q)=>{let J=Q[0].dims,G=Q[0].dims[2],H=S.size(J)/4,K=Q[0].dataType,z=A("input",K,J,4),q=A("bias",K,[G],4),F=A("residual",K,J,4),D=C("output",K,J,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:J,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(H/64)}}),getShaderSource:(V)=>`
const channels = ${G}u / 4;
${V.declareVariables(z,q,F,D)}
${V.mainStart()}
${V.guardAgainstOutOfBoundsWorkgroupSizes(H)}
let value = ${z.getByOffset("global_idx")}
+ ${q.getByOffset("global_idx % channels")} + ${F.getByOffset("global_idx")};
${D.setByOffset("global_idx","value")}
}`}},Wg=(Q)=>{$1(Q.inputs),Q.compute(A1(Q.inputs))}}),P1,be,qg,jg,Kg,Xg,Zg,Jg,Qg,Yg,eb,O1,tb,nb,rb,ob,ro,ib,Wi,ab,sb,ub,lb,cb,db,pb,fb,hb,mb,gb,bb,yb,_b,xb,wb,Tb,vb,ol,il,Ib,Sb,$b,E1,C1,Ab,Hi=$(()=>{X(),ee(),ke(),ne(),P1=(Q,J,G,H,K,z,q)=>{let F=Math.ceil(J/4),D="";typeof K=="string"?D=`${K}(a)`:D=K("a");let V=A("inputData",G,[F],4),O=C("outputData",H,[F],4),P=[{name:"vec_size",type:"u32"}];return q&&P.push(...q),`
${Q.registerUniforms(P).declareVariables(V,O)}
${z??""}
${Q.mainStart()}
${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
let a = ${V.getByOffset("global_idx")};
${O.setByOffset("global_idx",D)}
}`},be=(Q,J,G,H,K,z=Q.dataType,q,F)=>{let D=[{type:12,data:Math.ceil(S.size(Q.dims)/4)}];return q&&D.push(...q),{name:J,shaderCache:{hint:K,inputDependencies:["type"]},getShaderSource:(V)=>P1(V,S.size(Q.dims),Q.dataType,z,G,H,F),getRunData:(V)=>({outputs:[{dims:Q.dims,dataType:z}],dispatchGroup:{x:Math.ceil(S.size(V[0].dims)/64/4)},programUniforms:D})}},qg=(Q)=>{Q.compute(be(Q.inputs[0],"Abs","abs"))},jg=(Q)=>{Q.compute(be(Q.inputs[0],"Acos","acos"))},Kg=(Q)=>{Q.compute(be(Q.inputs[0],"Acosh","acosh"))},Xg=(Q)=>{Q.compute(be(Q.inputs[0],"Asin","asin"))},Zg=(Q)=>{Q.compute(be(Q.inputs[0],"Asinh","asinh"))},Jg=(Q)=>{Q.compute(be(Q.inputs[0],"Atan","atan"))},Qg=(Q)=>{Q.compute(be(Q.inputs[0],"Atanh","atanh"))},Yg=(Q)=>Z(Q),eb=(Q,J)=>{let G;switch(J.to){case 10:G="vec4<f16>";break;case 1:G="vec4<f32>";break;case 12:G="vec4<u32>";break;case 6:G="vec4<i32>";break;case 9:G="vec4<bool>";break;default:throw RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${J.to}`)}Q.compute(be(Q.inputs[0],"Cast",G,void 0,J.cacheKey,J.to))},O1=(Q)=>{let J,G,H=Q.length>=2&&Q[1].data!==0,K=Q.length>=3&&Q[2].data!==0;switch(Q[0].dataType){case 1:J=H?Q[1].getFloat32Array()[0]:-340282346638528860000000000000000000000,G=K?Q[2].getFloat32Array()[0]:340282346638528860000000000000000000000;break;case 10:J=H?Q[1].getUint16Array()[0]:64511,G=K?Q[2].getUint16Array()[0]:31743;break;default:throw Error("Unsupport data type")}return Z({min:J,max:G})},tb=(Q,J)=>{let G=J||O1(Q.inputs),H=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"Clip",(K)=>`clamp(${K}, vec4<${H}>(uniforms.min), vec4<${H}>(uniforms.max))`,void 0,G.cacheKey,void 0,[{type:Q.inputs[0].dataType,data:G.min},{type:Q.inputs[0].dataType,data:G.max}],[{name:"min",type:H},{name:"max",type:H}]),{inputs:[0]})},nb=(Q)=>{Q.compute(be(Q.inputs[0],"Ceil","ceil"))},rb=(Q)=>{Q.compute(be(Q.inputs[0],"Cos","cos"))},ob=(Q)=>{Q.compute(be(Q.inputs[0],"Cosh","cosh"))},ro=(Q)=>Z(Q),ib=(Q,J)=>{let G=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"Elu",(H)=>`elu_vf32(${H})`,`
const elu_alpha_ = ${G}(${J.alpha});
fn elu_f32(a: ${G}) -> ${G} {
return select((exp(a) - 1.0) * elu_alpha_, a, a >= 0.0);
}
fn elu_vf32(v: vec4<${G}>) -> vec4<${G}> {
return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w));
}`,J.cacheKey))},Wi=(Q="f32")=>`
const r0: ${Q} = 0.3275911;
const r1: ${Q} = 0.254829592;
const r2: ${Q} = -0.284496736;
const r3: ${Q} = 1.421413741;
const r4: ${Q} = -1.453152027;
const r5: ${Q} = 1.061405429;
fn erf_vf32(v: vec4<${Q}>) -> vec4<${Q}> {
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));
}`,ab=(Q)=>{let J=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"Erf",(G)=>`erf_vf32(${G})`,Wi(J)))},sb=(Q)=>{Q.compute(be(Q.inputs[0],"Exp","exp"))},ub=(Q)=>{Q.compute(be(Q.inputs[0],"Floor","floor"))},lb=(Q)=>{let J=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"Gelu",(G)=>`0.5 * ${G} * (1.0 + erf_vf32(${G} * 0.7071067811865475))`,Wi(J)))},cb=(Q,J)=>{let G=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"LeakyRelu",(H)=>`select(leaky_relu_alpha_ * ${H}, ${H}, ${H} >= vec4<${G}>(0.0))`,`const leaky_relu_alpha_ = ${G}(${J.alpha});`,J.cacheKey))},db=(Q)=>{Q.compute(be(Q.inputs[0],"Not",(J)=>`!${J}`))},pb=(Q)=>{Q.compute(be(Q.inputs[0],"Neg",(J)=>`-${J}`))},fb=(Q)=>{Q.compute(be(Q.inputs[0],"Reciprocal",(J)=>`1.0/${J}`))},hb=(Q)=>{let J=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"Relu",(G)=>`select(vec4<${J}>(0.0), ${G}, ${G} > vec4<${J}>(0.0))`))},mb=(Q)=>{Q.compute(be(Q.inputs[0],"Sigmoid",(J)=>`(1.0 / (1.0 + exp(-${J})))`))},gb=(Q)=>Z(Q),bb=(Q,J)=>{let G=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"HardSigmoid",(H)=>`max(vec4<${G}>(0.0), min(vec4<${G}>(1.0), ${J.alpha} * ${H} + vec4<${G}>(${J.beta})))`,void 0,J.cacheKey))},yb=(Q)=>{Q.compute(be(Q.inputs[0],"Sin","sin"))},_b=(Q)=>{Q.compute(be(Q.inputs[0],"Sinh","sinh"))},xb=(Q)=>{Q.compute(be(Q.inputs[0],"Sqrt","sqrt"))},wb=(Q)=>{Q.compute(be(Q.inputs[0],"Tan","tan"))},Tb=(Q)=>`sign(${Q}) * (1 - exp(-2 * abs(${Q}))) / (1 + exp(-2 * abs(${Q})))`,vb=(Q)=>{Q.compute(be(Q.inputs[0],"Tanh",Tb))},ol=(Q="f32")=>`
const fast_gelu_a: ${Q} = 0.5;
const fast_gelu_b: ${Q} = 0.7978845608028654;
const fast_gelu_c: ${Q} = 0.035677408136300125;
fn tanh_v(v: vec4<${Q}>) -> vec4<${Q}> {
return ${Tb("v")};
}
`,il=(Q)=>`(fast_gelu_a + fast_gelu_a * tanh_v(${Q} * (fast_gelu_c * ${Q} * ${Q} + fast_gelu_b))) * ${Q}`,Ib=(Q)=>{let J=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"FastGelu",il,ol(J),void 0,Q.inputs[0].dataType))},Sb=(Q,J)=>{let G=Ve(Q.inputs[0].dataType);return Q.compute(be(Q.inputs[0],"ThresholdedRelu",(H)=>`select(vec4<${G}>(0.0), ${H}, ${H} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${G}>(${J.alpha});`,J.cacheKey)),0},$b=(Q)=>{Q.compute(be(Q.inputs[0],"Log","log"))},E1=(Q,J)=>`
const alpha = vec4<${Q}>(${J});
const one = ${Q}(1.0);
const zero = ${Q}(0.0);
fn quick_gelu_impl(x: vec4<${Q}>) -> vec4<${Q}> {
let v = x *alpha;
var x1 : vec4<${Q}>;
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;
}
`,C1=(Q)=>`quick_gelu_impl(${Q})`,Ab=(Q,J)=>{let G=Ve(Q.inputs[0].dataType);Q.compute(be(Q.inputs[0],"QuickGelu",C1,E1(G,J.alpha),J.cacheKey,Q.inputs[0].dataType))}}),D1,k1,Ob,Eb=$(()=>{ee(),ne(),Hi(),D1=(Q)=>{if(Q[0].dims.length!==3)throw Error("input should have 3 dimensions");if(![2560,5120,10240].includes(Q[0].dims[2]))throw Error("hidden state should be 2560, 5120 or 10240");if(Q[1].dims.length!==1)throw Error("bias is expected to have 1 dimensions");if(Q[0].dims[2]!==Q[1].dims[0])throw Error("last dimension of input and bias are not the same")},k1=(Q)=>{let J=Q[0].dims.slice();J[2]=J[2]/2;let G=A("input",Q[0].dataType,Q[0].dims,4),H=A("bias",Q[0].dataType,[Q[0].dims[2]],4),K=C("output",Q[0].dataType,J,4),z=S.size(J)/4,q=ve(Q[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:J,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(z/64)}}),getShaderSource:(F)=>`
const M_SQRT2 = sqrt(2.0);
const halfChannels = ${Q[0].dims[2]/4/2}u;
${F.declareVariables(G,H,K)}
${Wi(q)}
${F.mainStart()}
${F.guardAgainstOutOfBoundsWorkgroupSizes(z)}
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);
${K.setByOffset("global_idx","valueLeft * geluRight")}
}`}},Ob=(Q)=>{D1(Q.inputs),Q.compute(k1(Q.inputs))}}),L1,R1,Tn,Cb,Db,kb,Lb,Rb,Nb,zb,Mb,Bb,Fb,Vb=$(()=>{X(),ee(),ne(),L1=(Q,J,G,H,K,z,q,F,D,V,O,P)=>{let N,I;typeof F=="string"?N=I=(y,x)=>`${F}((${y}),(${x}))`:typeof F=="function"?N=I=F:(N=F.scalar,I=F.vector);let R=C("outputData",O,H.length,4),w=A("aData",D,J.length,4),E=A("bData",V,G.length,4),T;if(K)if(z){let y=S.size(J)===1,x=S.size(G)===1,b=J.length>0&&J[J.length-1]%4===0,g=G.length>0&&G[G.length-1]%4===0;y||x?T=R.setByOffset("global_idx",I(y?`${w.type.value}(${w.getByOffset("0")}.x)`:w.getByOffset("global_idx"),x?`${E.type.value}(${E.getByOffset("0")}.x)`:E.getByOffset("global_idx"))):T=`
let outputIndices = ${R.offsetToIndices("global_idx * 4u")};
let offsetA = ${w.broadcastedIndicesToOffset("outputIndices",R)};
let offsetB = ${E.broadcastedIndicesToOffset("outputIndices",R)};
${R.setByOffset("global_idx",I(q||b?w.getByOffset("offsetA / 4u"):`${w.type.value}(${w.getByOffset("offsetA / 4u")}[offsetA % 4u])`,q||g?E.getByOffset("offsetB / 4u"):`${E.type.value}(${E.getByOffset("offsetB / 4u")}[offsetB % 4u])`))}
`}else T=R.setByOffset("global_idx",I(w.getByOffset("global_idx"),E.getByOffset("global_idx")));else{if(!z)throw Error("no necessary to use scalar implementation for element-wise binary op implementation.");let y=(x,b,g="")=>{let l=`aData[indexA${b}][componentA${b}]`,_=`bData[indexB${b}][componentB${b}]`;return`
let outputIndices${b} = ${R.offsetToIndices(`global_idx * 4u + ${b}u`)};
let offsetA${b} = ${w.broadcastedIndicesToOffset(`outputIndices${b}`,R)};
let offsetB${b} = ${E.broadcastedIndicesToOffset(`outputIndices${b}`,R)};
let indexA${b} = offsetA${b} / 4u;
let indexB${b} = offsetB${b} / 4u;
let componentA${b} = offsetA${b} % 4u;
let componentB${b} = offsetB${b} % 4u;
${x}[${b}] = ${g}(${N(l,_)});
`};O===9?T=`
var data = vec4<u32>(0);
${y("data",0,"u32")}
${y("data",1,"u32")}
${y("data",2,"u32")}
${y("data",3,"u32")}
outputData[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:T=`
${y("outputData[global_idx]",0)}
${y("outputData[global_idx]",1)}
${y("outputData[global_idx]",2)}
${y("outputData[global_idx]",3)}
`}return`
${Q.registerUniform("vec_size","u32").declareVariables(w,E,R)}
${P??""}
${Q.mainStart()}
${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
${T}
}`},R1=(Q,J,G,H,K,z,q=G.dataType)=>{let F=G.dims.map(Number),D=H.dims.map(Number),V=!S.areEqual(F,D),O=F,P=S.size(F),N=!1,I=!1,R=[V];if(V){let w=bn.calcShape(F,D,!1);if(!w)throw Error("Can't perform binary op on the given tensors");O=w.slice(),P=S.size(O);let E=S.size(F)===1,T=S.size(D)===1,y=F.length>0&&F[F.length-1]%4===0,x=D.length>0&&D[D.length-1]%4===0;R.push(E),R.push(T),R.push(y),R.push(x);let b=1;for(let g=1;g<O.length;g++){let l=F[F.length-g],_=D[D.length-g];if(l===_)b*=l;else break}b%4===0?(I=!0,N=!0):(E||T||y||x)&&(N=!0)}else N=!0;return R.push(N),{name:Q,shaderCache:{hint:J+R.map((w)=>w.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:(w)=>L1(w,F,D,O,N,V,I,K,G.dataType,H.dataType,q,z),getRunData:()=>({outputs:[{dims:O,dataType:q}],dispatchGroup:{x:Math.ceil(P/64/4)},programUniforms:[{type:12,data:Math.ceil(S.size(O)/4)},...k(F,D,O)]})}},Tn=(Q,J,G,H,K,z)=>{Q.compute(R1(J,K??"",Q.inputs[0],Q.inputs[1],G,H,z))},Cb=(Q)=>{Tn(Q,"Add",(J,G)=>`${J}+${G}`)},Db=(Q)=>{Tn(Q,"Div",(J,G)=>`${J}/${G}`)},kb=(Q)=>{Tn(Q,"Equal",{scalar:(J,G)=>`u32(${J}==${G})`,vector:(J,G)=>`vec4<u32>(${J}==${G})`},void 0,void 0,9)},Lb=(Q)=>{Tn(Q,"Mul",(J,G)=>`${J}*${G}`)},Rb=(Q)=>{let J=A("input",Q.inputs[0].dataType,Q.inputs[0].dims).type.value;Tn(Q,"Pow",{scalar:(G,H)=>`pow_custom(${G},${H})`,vector:(G,H)=>`pow_vector_custom(${G},${H})`},`
fn pow_custom(a : ${J}, b : ${J}) -> ${J} {
if (b == ${J}(0.0)) {
return ${J}(1.0);
} else if (a < ${J}(0.0) && f32(b) != floor(f32(b))) {
return ${J}(pow(f32(a), f32(b))); // NaN
}
return select(sign(a), ${J}(1.0), round(f32(abs(b) % ${J}(2.0))) != 1.0) * ${J}(${J==="i32"?"round":""}(pow(f32(abs(a)), f32(b))));
}
fn pow_vector_custom(a : vec4<${J}>, b : vec4<${J}>) -> vec4<${J}> {
// TODO: implement vectorized pow
return vec4<${J}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
}
`)},Nb=(Q)=>{Tn(Q,"Sub",(J,G)=>`${J}-${G}`)},zb=(Q)=>{Tn(Q,"Greater",{scalar:(J,G)=>`u32(${J}>${G})`,vector:(J,G)=>`vec4<u32>(${J}>${G})`},void 0,void 0,9)},Mb=(Q)=>{Tn(Q,"Less",{scalar:(J,G)=>`u32(${J}<${G})`,vector:(J,G)=>`vec4<u32>(${J}<${G})`},void 0,void 0,9)},Bb=(Q)=>{Tn(Q,"GreaterOrEqual",{scalar:(J,G)=>`u32(${J}>=${G})`,vector:(J,G)=>`vec4<u32>(${J}>=${G})`},void 0,void 0,9)},Fb=(Q)=>{Tn(Q,"LessOrEqual",{scalar:(J,G)=>`u32(${J}<=${G})`,vector:(J,G)=>`vec4<u32>(${J}<=${G})`},void 0,void 0,9)}}),z1,M1,B1,F1,Gb,Ub,Wb=$(()=>{X(),ee(),ke(),ne(),z1=(Q,J)=>{if(!Q||Q.length<1)throw Error("too few inputs");let G=0,H=Q[G],K=H.dataType,z=H.dims.length;Q.forEach((q,F)=>{if(F!==G){if(q.dataType!==K)throw Error("input tensors should be one type");if(q.dims.length!==z)throw Error("input tensors should have the same shape");q.dims.forEach((D,V)=>{if(V!==J&&D!==H.dims[V])throw Error("non concat dimensions must match")})}})},M1=(Q,J)=>`
fn calculateInputIndex(index: u32) -> u32 {
let sizeInConcatAxis = array<u32, ${Q}u>(${J});
for (var i: u32 = 0u; i < ${Q}; i += 1u ) {
if (index < sizeInConcatAxis[i]) {
return i;
}
}
return ${Q}u;
}`,B1=(Q,J)=>{let G=Q.length,H=[];for(let K=0;K<G;++K){let z=J.setByOffset("global_idx",Q[K].getByIndices("indices"));G===1?H.push(z):K===0?H.push(`if (inputIndex == ${K}u) { ${z} }`):K===G-1?H.push(`else { ${z} }`):H.push(`else if (inputIndex == ${K}) { ${z} }`)}return H.join(`
`)},F1=(Q,J,G,H)=>{let K=S.size(G),z=Array(Q.length),q=Array(Q.length),F=0,D=[],V=[],O=[{type:12,data:K}];for(let w=0;w<Q.length;++w)F+=Q[w].dims[J],z[w]=F,V.push(Q[w].dims.length),q[w]=A(`input${w}`,H,V[w]),D.push("rank"),O.push({type:12,data:z[w]});for(let w=0;w<Q.length;++w)O.push(...k(Q[w].dims));O.push(...k(G));let P=C("output",H,G.length),N=P.indicesGet("indices",J),I=Array.from(Array(z.length).keys()).map((w)=>`uniforms.sizeInConcatAxis${w}`).join(","),R=(w)=>`
${(()=>{w.registerUniform("outputSize","u32");for(let E=0;E<Q.length;E++)w.registerUniform(`sizeInConcatAxis${E}`,"u32");return w.declareVariables(...q,P)})()}
${M1(z.length,I)}
${w.mainStart()}
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var indices = ${P.offsetToIndices("global_idx")};
let inputIndex = calculateInputIndex(${N});
if (inputIndex != 0u) {
let sizeInConcatAxis = array<u32, ${z.length}u>(${I});
${N} -= sizeInConcatAxis[inputIndex - 1u];
}
${B1(q,P)}
}`;return{name:"Concat",shaderCache:{hint:`${J}`,inputDependencies:D},getRunData:()=>({outputs:[{dims:G,dataType:H}],dispatchGroup:{x:Math.ceil(K/64)},programUniforms:O}),getShaderSource:R}},Gb=(Q,J)=>{let G=Q.inputs,H=G[0].dims,K=S.normalizeAxis(J.axis,H.length);z1(G,K);let z=H.slice();z[K]=G.reduce((F,D)=>F+(D.dims.length>K?D.dims[K]:0),0);let q=G.filter((F)=>S.size(F.dims)>0);Q.compute(F1(q,K,z,G[0].dataType),{inputs:q})},Ub=(Q)=>Z({axis:Q.axis})}),Pt,Ot,Et,qi,Gn=$(()=>{X(),ee(),Pt=(Q,J,G="f32")=>{switch(Q.activation){case"Relu":return`value = max(value, ${J}(0.0));`;case"Sigmoid":return`value = (${J}(1.0) / (${J}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${J}(${G}(uniforms.clip_min)), ${J}(${G}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${J}(0.0), min(${J}(1.0), ${G}(uniforms.alpha) * value + ${G}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${G}(uniforms.alpha) * value, value, value >= ${J}(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 Error(`Unsupported activation ${Q.activation}`)}},Ot=(Q,J)=>{Q.activation==="Clip"?J.push({type:1,data:Q.clipMax},{type:1,data:Q.clipMin}):Q.activation==="HardSigmoid"?J.push({type:1,data:Q.alpha},{type:1,data:Q.beta}):Q.activation==="LeakyRelu"&&J.push({type:1,data:Q.alpha})},Et=(Q,J)=>{Q.activation==="Clip"?J.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):Q.activation==="HardSigmoid"?J.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):Q.activation==="LeakyRelu"&&J.push({name:"alpha",type:"f32"})},qi=(Q)=>{let J=Q?.activation||"";if(J==="HardSigmoid"){let[G,H]=Q?.activation_params||[0.2,0.5];return{activation:J,alpha:G,beta:H}}else if(J==="Clip"){let[G,H]=Q?.activation_params||[Jm,Qm];return{activation:J,clipMax:H,clipMin:G}}else if(J==="LeakyRelu"){let[G]=Q?.activation_params||[0.01];return{activation:J,alpha:G}}return{activation:J}}}),Be,Hb,ji=$(()=>{Be=(Q,J)=>{switch(Q){case 1:return J;case 2:return`vec2<${J}>`;case 3:return`vec3<${J}>`;case 4:return`vec4<${J}>`;default:throw Error(`${Q}-component is not supported.`)}},Hb=(Q)=>`
${Q?"value = value + getBiasByOutputCoords(coords);":""}
`}),qb,jb=$(()=>{qb=(Q)=>`
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(${Q}.x), i32(${Q}.y), i32(${Q}.z), 1));
}
`}),oo,Ki,Xi=$(()=>{X(),ee(),ne(),Gn(),oo=(Q,J,G,H,K)=>{let z=H-G;return`
${Array.from({length:G}).map((q,F)=>`
if (${B(J.shape,F,J.rank)} != 1) {
${J.indicesSet(Q,F,B(K,F+z,H))}
} else {
${J.indicesSet(Q,F,0)}
}`).join("")}
`},Ki=(Q,J,G,H,K=!1,z)=>{let q=Q[0].dims,F=Q[1].dims,D=q[q.length-2],V=F[F.length-1],O=q[q.length-1],P=he(V),N=he(O),I=he(D),R=S.size(G)/P/I,w=Q.length>2,E=H?H.slice(0,-2):G.slice(0,-2),T=[S.size(E),D,V],y=[{type:12,data:R},{type:12,data:D},{type:12,data:V},{type:12,data:O}];Ot(J,y),y.push(...k(E,q,F)),w&&y.push(...k(Q[2].dims)),y.push(...k(T));let x=(b)=>{let g=Fi("batch_dims",Q[0].dataType,E.length),l=A("a",Q[0].dataType,q.length,N),_=A("b",Q[1].dataType,F.length,P),a=C("output",Q[0].dataType,T.length,P),r=ve(a.type.tensor),f0=Pt(J,a.type.value,r),t=[l,_],p0="";if(w){let n=K?P:1;t.push(A("bias",Q[2].dataType,Q[2].dims.length,n)),p0=`${K?`value += bias[col / ${n}];`:`value += ${a.type.value}(bias[row + i]);`}`}let u0=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Et(J,u0);let d=()=>{let n=`var a_data: ${l.type.value};`;for(let c0=0;c0<N;c0++)n+=`
let b_data${c0} = b[(b_offset + (k + ${c0}) * uniforms.N + col) / ${P}];`;for(let c0=0;c0<I;c0++){n+=`a_data = a[(a_offset + (row + ${c0}) * uniforms.K + k) / ${N}];`;for(let WQ=0;WQ<N;WQ++)n+=`
values[${c0}] = fma(${_.type.value}(a_data${N===1?"":`[${WQ}]`}), b_data${WQ}, values[${c0}]);
`}return n};return`
${b.registerUniforms(u0).registerInternalVariables(g).declareVariables(...t,a)}
${b.mainStart()}
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let col = (global_idx % (uniforms.N / ${P})) * ${P};
var index1 = global_idx / (uniforms.N / ${P});
let stride1 = uniforms.M / ${I};
let row = (index1 % stride1) * ${I};
let batch = index1 / stride1;
${G.length===2?"":`let batch_indices = ${g.offsetToIndices("batch")};`}
var a_indices: ${l.type.indices};
${oo("a_indices",l,l.rank-2,g.rank,"batch_indices")}
${l.indicesSet("a_indices",l.rank-2,0)}
${l.indicesSet("a_indices",l.rank-1,0)}
let a_offset = ${l.indicesToOffset("a_indices")};
var b_indices: ${_.type.indices};
${oo("b_indices",_,_.rank-2,g.rank,"batch_indices")}
${_.indicesSet("b_indices",_.rank-2,0)}
${_.indicesSet("b_indices",_.rank-1,0)}
let b_offset = ${_.indicesToOffset("b_indices")};
var values: array<${a.type.value}, ${I}>;
for (var k: u32 = 0u; k < uniforms.K; k = k + ${N}) {
${d()}
}
for (var i = 0u; i < ${I}u; i++) {
var value = values[i];
${p0}
${f0}
let cur_indices = ${a.type.indices}(batch, row + i, col);
let offset = ${a.indicesToOffset("cur_indices")};
${a.setByOffset(`offset / ${P}`,"value")};
}
}
`};return{name:"MatMulNaive",shaderCache:{hint:`${J.activation};${P};${N};${I};${K}`,inputDependencies:w?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:z?z(G):G,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(R/64)},programUniforms:y}),getShaderSource:x}}}),V1,G1,al,Kb,U1,sl,W1,io,Zi=$(()=>{X(),ee(),ne(),Gn(),Xi(),ji(),V1=(Q,J)=>Q?`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
kStart + inputRow,
globalRowStart / innerElementSize + inputCol${J?", batchIndices":""});
`:`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
globalRow + innerRow,
kStart / innerElementSize + inputCol${J?", batchIndices":""});
`,G1=(Q,J)=>Q?`
let ACached0 = mm_Asub[k * innerElementSize][localRow];
let ACached1 = mm_Asub[k * innerElementSize + 1][localRow];
let ACached2 = mm_Asub[k * innerElementSize + 2][localRow];
${J===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];
${J===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];
${J===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
}`,al=(Q,J,G="f32",H,K=!1,z=32,q=!1,F=32)=>{let D=J[1]*Q[1],V=J[0]*Q[0],O=K?D:z,P=K?z:D,N=O/J[0],I=z/J[1];if(!((K&&N===4&&Q[1]===4||!K&&(N===3||N===4))&&O%J[0]===0&&z%J[1]===0&&Q[0]===4))throw Error(`If transposeA ${K} is true, innerElementSize ${N} and workPerThread[1] ${Q[1]} must be 4.
Otherwise, innerElementSize ${N} must be 3 or 4.
tileAWidth ${O} must be divisible by workgroupSize[0]${J[0]}. tileInner ${z} must be divisible by workgroupSize[1] ${J[1]}. colPerThread ${Q[0]} must be 4.`);return`
var<workgroup> mm_Asub: array<array<vec${N}<${G}>, ${O/N}>, ${P}>;
var<workgroup> mm_Bsub: array<array<vec4<${G}>, ${V/Q[0]}>, ${z}>;
const rowPerThread = ${Q[1]};
const colPerThread = ${Q[0]};
const innerElementSize = ${N};
const tileInner = ${z};
@compute @workgroup_size(${J[0]}, ${J[1]}, ${J[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 = ${q?"0":"i32(globalId.z)"};
${H?`let batchIndices = ${H.offsetToIndices("u32(batch)")};`:""}
let globalRowStart = i32(workgroupId.y) * ${D};
let num_tiles = ${q?`${Math.ceil(F/z)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
var kStart = ${q?`i32(globalId.z) * ${F}`:"0"};
var acc: array<vec4<${G}>, rowPerThread>;
// Loop over shared dimension.
let tileRowB = localRow * ${I};
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;
${V1(K,H)}
}
// Load one tile of B into local memory.
for (var innerRow = 0; innerRow < ${I}; innerRow = innerRow + 1) {
let inputRow = tileRowB + innerRow;
let inputCol = tileCol;
mm_Bsub[inputRow][inputCol] = mm_readB(batch, kStart + inputRow, globalCol${H?", 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];
${N===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"}
${G1(K,N)}
}
workgroupBarrier();
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
}
}`},Kb=(Q,J)=>Q?`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
kStart + inputRow,
globalRowStart + inputCol${J?", batchIndices":""});
`:`
mm_Asub[inputRow][inputCol] = mm_readA(batch,
globalRowStart + inputRow,
kStart + inputCol${J?", batchIndices":""});
`,U1=(Q)=>Q?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",sl=(Q,J,G="f32",H,K=!1,z=32,q=!1,F=32,D=!1)=>{let V=Q[1]*J[1],O=Q[0]*J[0],P=K?V:z,N=K?z:V;if(!(N%J[1]===0&&P%J[0]===0&&z%J[1]===0))throw Error(`tileAHight ${N} must be divisible by workgroupSize[1]${J[1]}, tileAWidth ${P} must be divisible by workgroupSize[0]${J[0]}, tileInner ${z} must be divisible by workgroupSize[1]${J[1]}`);let I=N/J[1],R=P/J[0],w=z/J[1],E=D?`
let localRow = i32(localId.y);
let localCol = i32(localId.x);
let globalRowStart = i32(workgroupId.y) * ${V};
let globalColStart = i32(workgroupId.x) * ${O};
// 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 < ${N}; inputRow = inputRow + ${J[1]}) {
for (var inputCol = localCol; inputCol < ${P}; inputCol = inputCol + ${J[0]}) {
${Kb(K,H)}
}
}
// Load one tile of B into local memory.
for (var inputRow = localRow; inputRow < ${z}; inputRow = inputRow + ${J[1]}) {
for (var inputCol = localCol; inputCol < ${O}; inputCol = inputCol + ${J[0]}) {
mm_Bsub[inputRow][inputCol] = mm_readB(batch,
kStart + inputRow,
globalColStart + inputCol${H?", batchIndices":""});
}
}
kStart = kStart + tileInner;
workgroupBarrier();
// Compute acc values for a single thread.
var BCached : array<${G}, 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 * ${J[0]}];
}
for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
let ACached = ${K?`mm_Asub[k][localRow + innerRow * ${J[1]}];`:`mm_Asub[localRow + innerRow * ${J[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 * ${J[1]};
for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) {
let gCol = globalColStart + localCol + innerCol * ${J[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) * ${V};
let tileRowA = i32(localId.y) * ${I};
let tileColA = i32(localId.x) * ${R};
let tileRowB = i32(localId.y) * ${w};
// 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 < ${I}; innerRow = innerRow + 1) {
for (var innerCol = 0; innerCol < ${R}; innerCol = innerCol + 1) {
let inputRow = tileRowA + innerRow;
let inputCol = tileColA + innerCol;
${Kb(K,H)}
}
}
// Load one tile of B into local memory.
for (var innerRow = 0; innerRow < ${w}; 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${H?", batchIndices":""});
}
}
kStart = kStart + tileInner;
workgroupBarrier();
// Compute acc values for a single thread.
var BCached : array<${G}, 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) {
${U1(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) {
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<${G}, ${P}>, ${N}>;
var<workgroup> mm_Bsub : array<array<${G}, ${O}>, ${z}>;
const rowPerThread = ${Q[1]};
const colPerThread = ${Q[0]};
const tileInner = ${z};
@compute @workgroup_size(${J[0]}, ${J[1]}, ${J[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 = ${q?"0":"i32(globalId.z)"};
${H?`let batchIndices = ${H.offsetToIndices("u32(batch)")};`:""}
let num_tiles = ${q?`${Math.ceil(F/z)}`:"(uniforms.dim_inner - 1) / tileInner + 1"};
var kStart = ${q?`i32(globalId.z) * ${F}`:"0"};
var acc : array<array<${G}, colPerThread>, rowPerThread>;
${E}
}
`},W1=(Q,J,G,H,K=!1)=>{let[z,q,F,D]=H,V=ve(H[0].type.tensor);return`
fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${z.type.indices}) -> ${Be(Q,V)} {
var value = ${Be(Q,V)}(0.0);
let col = colIn * ${Q};
if(row < uniforms.dim_a_outer && col < uniforms.dim_inner)
{
var aIndices: ${q.type.indices};
${oo("aIndices",q,q.rank-2,z.rank,"batchIndices")}
${q.indicesSet("aIndices",q.rank-2,"u32(row)")}
${q.indicesSet("aIndices",q.rank-1,"u32(colIn)")}
value = ${q.getByIndices("aIndices")};
}
return value;
}
fn mm_readB(batch: i32, row: i32, colIn: i32, batchIndices: ${z.type.indices}) -> ${Be(Q,V)} {
var value = ${Be(Q,V)}(0.0);
let col = colIn * ${Q};
if(row < uniforms.dim_inner && col < uniforms.dim_b_outer)
{
var bIndices: ${F.type.indices};
${oo("bIndices",F,F.rank-2,z.rank,"batchIndices")}
${F.indicesSet("bIndices",F.rank-2,"u32(row)")}
${F.indicesSet("bIndices",F.rank-1,"u32(colIn)")}
value = ${F.getByIndices("bIndices")};
}
return value;
}
fn mm_write(batch: i32, row: i32, colIn: i32, valueIn: ${Be(Q,V)}) {
let col = colIn * ${Q};
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer) {
var value = valueIn;
let coords = vec3<i32>(batch, row, colIn);
${J?`value = value + ${K?"bias[colIn]":`${Be(Q,V)}(bias[row])`};`:""}
${G}
${D.setByIndices("vec3<u32>(coords)","value")}
}
}
`},io=(Q,J,G,H,K=!1,z)=>{let q=Q[0].dims,F=Q[1].dims,D=q.slice(0,-2),V=F.slice(0,-2),O=H?H.slice(0,-2):G.slice(0,-2),P=S.size(O),N=q[q.length-2],I=q[q.length-1],R=F[F.length-1],w=I%4===0&&R%4===0,E=N<=8?[4,1,1]:[4,4,1],T=[8,8,1],y=[Math.ceil(R/T[0]/E[0]),Math.ceil(N/T[1]/E[1]),Math.ceil(P/T[2]/E[2])],x=w?4:1,b=[...D,N,I/x],g=b.length,l=[...V,I,R/x],_=l.length,a=[P,N,R/x],r=[{type:6,data:N},{type:6,data:R},{type:6,data:I}];Ot(J,r),r.push(...k(O,b,l));let f0=["rank","rank"],t=Q.length>2;t&&(r.push(...k(Q[2].dims)),f0.push("rank")),r.push(...k(a));let p0=(u0)=>{let d=O.length,n=Fi("batchDims",Q[0].dataType,d,1),c0=ve(Q[0].dataType),WQ=A("a",Q[0].dataType,g,x),R0=A("b",Q[1].dataType,_,x),l0=C("result",Q[0].dataType,a.length,x),d0=[WQ,R0];if(t){let pQ=K?x:1;d0.push(A("bias",Q[2].dataType,Q[2].dims.length,pQ))}let m0=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Et(J,m0);let ZQ=ve(l0.type.tensor),LQ=Pt(J,l0.type.value,ZQ),h0=W1(x,t,LQ,[n,WQ,R0,l0],K);return`
${u0.registerUniforms(m0).registerInternalVariables(n).declareVariables(...d0,l0)}
${h0}
${w?al(E,T,c0,n):sl(E,T,c0,n)}
`};return{name:"MatMul",shaderCache:{hint:`${E};${J.activation};${w};${K}`,inputDependencies:f0},getRunData:()=>({outputs:[{dims:z?z(G):G,dataType:Q[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:r}),getShaderSource:p0}}}),H1,Xb,Zb=$(()=>{X(),gn(),ne(),Gn(),ji(),jb(),Zi(),H1=(Q,J,G,H,K=!1,z,q=4,F=4,D=4,V="f32")=>{let O=(r)=>{switch(r){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${V}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw Error(`innerElementSize ${r} is not supported.`)}},P=(r)=>{switch(r){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 Error(`innerElementSize ${r} is not supported.`)}},N=Q?`
let coord = vec4<i32>(batch, xRow, xCol, xCh);
`:`
let coord = vec4<i32>(batch, xCh, xRow, xCol);
`,I=Q?`
let coords = vec4<i32>(
batch,
row / outWidth,
row % outWidth,
col);
`:`
let coords = vec4<i32>(
batch,
row,
col / outWidth,
col % outWidth);
`,R=Q?"i32(uniforms.x_shape[1])":"i32(uniforms.x_shape[2])",w=Q?"i32(uniforms.x_shape[2])":"i32(uniforms.x_shape[3])",E=Q?"row":"col",T=Q?"col":"row",y=`
let inChannels = i32(uniforms.w_shape[2]);
let outWidth = ${Q?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
let outRow = ${E} / outWidth;
let outCol = ${E} % outWidth;
let WRow = ${T} / (i32(uniforms.w_shape[1]) * inChannels);
let WCol = ${T} / 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 = ${T} % inChannels;
var resData = ${Be(q,V)}(0.0);
// The bounds checking is always needed since we use it to pad zero for
// the 'same' padding type.
if (xRow >= 0 && xRow < ${R} && xCol >= 0 && xCol < ${w}) {
${N}
let xIndex = getIndexFromCoords4D(coord, vec4<i32>(uniforms.x_shape));
${O(q)}
}
return resData;`,x=Q?J&&H?`
let col = colIn * ${q};
${y}`:`
let col = colIn * ${q};
if (row < uniforms.dim_a_outer && col < uniforms.dim_inner) {
${y}
}
return ${Be(q,V)}(0.0);`:H&&G?`
let col = colIn * ${q};
${y}`:`
let col = colIn * ${q};
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
${y}
}
return ${Be(q,V)}(0.0);`,b=Q?H&&G?P(F):`
let col = colIn * ${F};
if (row < uniforms.dim_inner && col < uniforms.dim_b_outer) {
${P(F)}
}
return ${Be(F,V)}(0.0);`:`
let col = colIn * ${F};
if (row < uniforms.dim_inner && col < uniforms.dim_a_outer) {
${P(F)}
}
return ${Be(F,V)}(0.0);`,g=Be(D,V),l=Q?Be(q,V):Be(F,V),_=Q?Be(F,V):Be(q,V),a=Pt(z,g,V);return`
fn mm_readA(batch: i32, row : i32, colIn : i32) -> ${l} {
${Q?x:b}
}
fn mm_readB(batch: i32, row : i32, colIn : i32) -> ${_} {
${Q?b:x}
}
fn mm_write(batch: i32, row : i32, colIn : i32, valueIn : ${g}) {
let col = colIn * ${D};
if (row < uniforms.dim_a_outer && col < uniforms.dim_b_outer)
{
var value = valueIn;
let outWidth = ${Q?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"};
${I}
${Hb(K)}
${a}
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value);
}
}`},Xb=(Q,J,G,H,K,z,q,F,D)=>{let V=J.format==="NHWC",O=V?Q[0].dims[3]:Q[0].dims[1],P=G[0],N=V?G[2]:G[3],I=V?G[1]:G[2],R=V?G[3]:G[1],w=V&&(O%4===0||O%3===0)&&R%4===0,E=V?R:N*I,T=V?N*I:R,y=[8,8,1],x=H<=8?[4,1,1]:[4,4,1],b=[Math.ceil(E/y[0]/x[0]),Math.ceil(T/y[1]/x[1]),Math.ceil(P/y[2]/x[2])];ie("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${b}`);let g=w?V&&O%4!==0?3:4:1,l=y[1]*x[1],_=y[0]*x[0],a=Math.max(y[0]*g,y[1]),r=H%l===0,f0=K%_===0,t=z%a===0,p0=w?[g,4,4]:[1,1,1],u0=[{type:6,data:H},{type:6,data:K},{type:6,data:z},{type:6,data:[J.pads[0],J.pads[1]]},{type:6,data:J.strides},{type:6,data:J.dilations}];Ot(J,u0),u0.push(...k(Q[0].dims,Q[1].dims));let d=["rank","rank"];q&&(u0.push(...k(Q[2].dims)),d.push("rank")),u0.push(...k(G));let n=(c0)=>{let WQ=[{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}];Et(J,WQ);let R0=w?4:1,l0=ve(Q[0].dataType),d0=`
fn setOutputAtIndex(flatIndex : i32, value : ${w?`vec4<${l0}>`:l0}) {
result[flatIndex] = ${w?`vec4<${l0}>`:l0}(value);
}
fn setOutputAtCoords(d0 : i32, d1 : i32, d2 : i32, d3 : i32, value : ${w?`vec4<${l0}>`:l0}) {
let flatIndex = getOutputIndexFromCoords(vec4<i32>(d0, d1, d2, d3));
setOutputAtIndex(flatIndex ${w?"/ 4":""}, value);
}`,m0=A("x",Q[0].dataType,Q[0].dims.length,g===3?1:g),ZQ=A("w",Q[1].dataType,Q[1].dims.length,R0),LQ=[m0,ZQ],h0=C("result",Q[0].dataType,G.length,R0);if(q){let pQ=A("bias",Q[2].dataType,Q[2].dims.length,R0);LQ.push(pQ),d0+=`
fn getBiasByOutputCoords(coords : vec4<i32>) -> ${w?`vec4<${l0}>`:l0} {
return bias[coords.${V?"w":"y"}${w?"/ 4":""}];
}`}return`
${qb("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 };
${c0.registerUniforms(WQ).declareVariables(...LQ,h0)}
${d0}
${H1(V,r,f0,t,q,J,p0[0],p0[1],p0[2],l0)}
${w?al(x,y,l0,void 0,!V,a):sl(x,y,l0,void 0,!V,a,!1,void 0,F)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${J.cacheKey};${g};${w};${r};${f0};${t};${l};${_};${a}`,inputDependencies:d},getRunData:()=>({outputs:[{dims:D?D(G):G,dataType:Q[0].dataType}],dispatchGroup:{x:b[0],y:b[1],z:b[2]},programUniforms:u0}),getShaderSource:n}}}),q1,Jb,Ji,j1,Qb,K1,Yb,ey,ty=$(()=>{X(),gn(),ee(),ne(),Gn(),ji(),q1=(Q)=>{let J=1;for(let G=0;G<Q.length;G++)J*=Q[G];return J},Jb=(Q)=>typeof Q=="number"?[Q,Q,Q]:Q,Ji=(Q,J)=>J<=1?Q:Q+(Q-1)*(J-1),j1=(Q,J,G,H=1)=>{let K=Ji(J,H);return Math.floor((Q[0]*(G-1)-G+K)/2)},Qb=(Q,J,G,H,K)=>{K==null&&(K=j1(Q,J[0],H[0]));let z=[0,0,0,G];for(let q=0;q<3;q++)Q[q]+2*K>=J[q]&&(z[q]=Math.trunc((Q[q]-J[q]+2*K)/H[q]+1));return z},K1=(Q,J,G,H,K,z,q,F,D,V)=>{let O,P,N,I;if(Q==="VALID"&&(Q=0),typeof Q=="number"){O={top:Q,bottom:Q,left:Q,right:Q,front:Q,back:Q};let R=Qb([J,G,H,1],[F,D,V],1,[K,z,q],Q);P=R[0],N=R[1],I=R[2]}else if(Array.isArray(Q)){if(!Q.every((w,E,T)=>w===T[0]))throw Error(`Unsupported padding parameter: ${Q}`);O={top:Q[0],bottom:Q[1],left:Q[2],right:Q[3],front:Q[4],back:Q[5]};let R=Qb([J,G,H,1],[F,D,V],1,[K,z,q],Q[0]);P=R[0],N=R[1],I=R[2]}else if(Q==="SAME_UPPER"){P=Math.ceil(J/K),N=Math.ceil(G/z),I=Math.ceil(H/q);let R=(P-1)*K+F-J,w=(N-1)*z+D-G,E=(I-1)*q+V-H,T=Math.floor(R/2),y=R-T,x=Math.floor(w/2),b=w-x,g=Math.floor(E/2),l=E-g;O={top:x,bottom:b,left:g,right:l,front:T,back:y}}else throw Error(`Unknown padding parameter: ${Q}`);return{padInfo:O,outDepth:P,outHeight:N,outWidth:I}},Yb=(Q,J,G,H,K,z=!1,q="channelsLast")=>{let F,D,V,O,P;if(q==="channelsLast")[F,D,V,O,P]=Q;else if(q==="channelsFirst")[F,P,D,V,O]=Q;else throw Error(`Unknown dataFormat ${q}`);let[N,,I,R,w]=J,[E,T,y]=Jb(G),[x,b,g]=Jb(H),l=Ji(I,x),_=Ji(R,b),a=Ji(w,g),{padInfo:r,outDepth:f0,outHeight:t,outWidth:p0}=K1(K,D,V,O,E,T,y,l,_,a),u0=z?N*P:N,d=[0,0,0,0,0];return q==="channelsFirst"?d=[F,u0,f0,t,p0]:q==="channelsLast"&&(d=[F,f0,t,p0,u0]),{batchSize:F,dataFormat:q,inDepth:D,inHeight:V,inWidth:O,inChannels:P,outDepth:f0,outHeight:t,outWidth:p0,outChannels:u0,padInfo:r,strideDepth:E,strideHeight:T,strideWidth:y,filterDepth:I,filterHeight:R,filterWidth:w,effectiveFilterDepth:l,effectiveFilterHeight:_,effectiveFilterWidth:a,dilationDepth:x,dilationHeight:b,dilationWidth:g,inShape:Q,outShape:d,filterShape:J}},ey=(Q,J,G,H,K,z)=>{let q=z==="channelsLast",F=q?Q[0].dims[3]:Q[0].dims[1],D=!1,V=[64,1,1],O={x:G.map((y,x)=>x)},P=[Math.ceil(q1(O.x.map((y)=>G[y]))/V[0]),1,1];ie("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${P}`);let N=D?q&&F%4!==0?3:4:1,I=S.size(G),R=[{type:12,data:I},{type:12,data:H},{type:12,data:K},{type:12,data:J.strides},{type:12,data:J.dilations}];Ot(J,R),R.push(...k(Q[0].dims,Q[1].dims));let w=["rank","rank"],E=Q.length===3;E&&(R.push(...k(Q[2].dims)),w.push("rank")),R.push(...k(G));let T=(y)=>{let x=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:H.length},{name:"pads",type:"u32",length:K.length},{name:"strides",type:"u32",length:J.strides.length},{name:"dilations",type:"u32",length:J.dilations.length}];Et(J,x);let b=D?4:1,g=ve(Q[0].dataType),l=A("x",Q[0].dataType,Q[0].dims.length,N===3?1:N),_=A("W",Q[1].dataType,Q[1].dims.length,b),a=[l,_],r=C("result",Q[0].dataType,G.length,b),f0="";if(E){let u0=A("bias",Q[2].dataType,Q[2].dims.length,b);a.push(u0),f0+=`
fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${D?`vec4<${g}>`:g} {
return bias[${q?B("coords",4,5):B("coords",1,5)}${D?"/ 4":""}];
}`}let t=Be(N,g),p0=Pt(J,t,g);return`
${f0}
fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 {
let aIndices = array<u32, 5>(d0, d1, d2, d3, d4);
return ${l.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 ${_.getByIndices("aIndices")};
}
${y.registerUniforms(x).declareVariables(...a,r)}
${y.mainStart()}
${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let coords = ${r.offsetToIndices("global_idx")};
let batch = ${B("coords",0,l.rank)};
let d2 = ${q?B("coords",l.rank-1,l.rank):B("coords",1,l.rank)};
let xFRCCorner = vec3<u32>(${q?B("coords",1,l.rank):B("coords",2,l.rank)},
${q?B("coords",2,l.rank):B("coords",3,l.rank)},
${q?B("coords",3,l.rank):B("coords",4,l.rank)}) * uniforms.strides - uniforms.pads;
let xFCorner = xFRCCorner.x;
let xRCorner = xFRCCorner.y;
let xCCorner = xFRCCorner.z;
let xShapeY = ${q?B("uniforms.x_shape",1,l.rank):B("uniforms.x_shape",2,l.rank)};
let xShapeZ = ${q?B("uniforms.x_shape",2,l.rank):B("uniforms.x_shape",3,l.rank)};
let xShapeW = ${q?B("uniforms.x_shape",3,l.rank):B("uniforms.x_shape",4,l.rank)};
let xShapeU = ${q?B("uniforms.x_shape",4,l.rank):B("uniforms.x_shape",1,l.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) {
${q?`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) {
${q?`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) {
${q?`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) {
${q?`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);
}
}
}
}
${E?"value = value + getBiasByOutputCoords(coords)":""};
${p0}
result[global_idx] = f32(value);
}`};return{name:"Conv3DNaive",shaderCache:{hint:`${J.cacheKey};${q};${N};${E}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:G,dataType:Q[0].dataType}],dispatchGroup:{x:P[0],y:P[1],z:P[2]},programUniforms:R}),getShaderSource:T}}}),ny,ry,oy=$(()=>{X(),ee(),ne(),Gn(),ny=(Q,J,G,H)=>{let K=Q.length>2,z=K?"value += b[output_channel];":"",q=Q[0].dims,F=Q[1].dims,D=J.format==="NHWC",V=D?G[3]:G[1],O=V/J.group,P=D&&O>=4?he(V):1,N=S.size(G)/P,I=[{type:12,data:N},{type:12,data:J.dilations},{type:12,data:[J.strides[0],J.strides[1]]},{type:12,data:[J.pads[0],J.pads[1]]},{type:12,data:O}];Ot(J,I),I.push(...k(q,[F[0],F[1],F[2],F[3]/P]));let R=K?["rank","rank","rank"]:["rank","rank"];I.push(...k([G[0],G[1],G[2],G[3]/P]));let w=(E)=>{let T=C("output",Q[0].dataType,G.length,P),y=ve(T.type.tensor),x=Pt(J,T.type.value,y),b=A("x",Q[0].dataType,q.length),g=A("w",Q[1].dataType,F.length,P),l=[b,g];K&&l.push(A("b",Q[2].dataType,Q[2].dims,P));let _=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:J.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];Et(J,_);let a=D?`
for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) {
let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0];
if (xHeight < 0u || xHeight >= uniforms.x_shape[1]) {
continue;
}
for (var wWidth: u32 = 0u; wWidth < uniforms.w_shape[1]; wWidth++) {
let xWidth = xRCCorner.y + wWidth * uniforms.dilations[1];
if (xWidth < 0u || xWidth >= uniforms.x_shape[2]) {
continue;
}
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[2]; wInChannel++) {
let input_channel = in_channel_offset + wInChannel;
let xVal = ${b.get("batch","xHeight","xWidth","input_channel")};
let wVal = ${g.get("wHeight","wWidth","wInChannel","output_channel")};
value += xVal * wVal;
}
}
}
`:`
for (var wInChannel: u32 = 0u; wInChannel < uniforms.w_shape[1]; wInChannel++) {
let input_channel = in_channel_offset + 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[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[3]) {
continue;
}
let xVal = ${b.get("batch","input_channel","xHeight","xWidth")};
let wVal = ${g.get("output_channel","wInChannel","wHeight","wWidth")};
value += xVal * wVal;
}
}
}
`;return`
${E.registerUniforms(_).declareVariables(...l,T)}
${E.mainStart()}
${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let outputIndices = ${T.offsetToIndices("global_idx")};
let batch: u32 = outputIndices[0];
let output_channel: u32 = outputIndices[${D?3:1}];
let xRCCorner: vec2<u32> = vec2<u32>(outputIndices[${D?1:2}], outputIndices[${D?2:3}]) * uniforms.strides - uniforms.pads;
let group_id: u32 = output_channel * ${P} / uniforms.output_channels_per_group;
var in_channel_offset = group_id * uniforms.w_shape[${D?2:1}];
var value: ${T.type.value} = ${T.type.value}(0);
${a}
${z}
${x}
${T.setByOffset("global_idx","value")}
}`};return{name:"GroupedConv",shaderCache:{hint:`${J.cacheKey}_${P}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:H?H(G):G,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:I}),getShaderSource:w}},ry=(Q,J,G,H)=>{let K=Q.length>2,z=he(G[3]),q=he(G[2]),F=S.size(G)/z/q,D=[Q[0].dims[0],Q[0].dims[1],Q[0].dims[2],Q[0].dims[3]/z],V=[Q[1].dims[0],Q[1].dims[1],Q[1].dims[2],Q[1].dims[3]/z],O=[G[0],G[1],G[2],G[3]/z],P=[{type:12,data:F},{type:6,data:[J.strides[0],J.strides[1]]},{type:6,data:[J.pads[0],J.pads[1]]}];Ot(J,P),P.push(...k(D,V,O));let N=(q-1)*J.strides[1]+V[1],I=(R)=>{let w=C("output",Q[0].dataType,O.length,z),E=ve(w.type.tensor),T=Pt(J,w.type.value,E),y=A("x",Q[0].dataType,D.length,z),x=A("w",Q[1].dataType,V.length,z),b=[y,x];K&&b.push(A("b",Q[2].dataType,Q[2].dims,z));let g=K?"value += b[output_channel];":"",l=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return Et(J,l),`
${R.registerUniforms(l).declareVariables(...b,w)}
${R.mainStart()}
${R.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] / ${q}u;
let col = (index1 % width1) * ${q}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<${y.type.value}, ${N}>;
var values: array<${w.type.value}, ${q}>;
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 < ${V[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 < ${N}; i++) {
let x_width = x_corner.y + i;
if (x_width >= 0 && u32(x_width) < uniforms.x_shape[2]) {
x_vals[i] = ${y.get("batch","u32(x_height)","u32(x_width)","input_channel")};
} else {
x_vals[i] = ${y.type.value}(0);
}
}
for (var w_width: u32 = 0u; w_width < ${V[1]}; w_width++) {
let w_val = ${x.get("w_height","w_width","0","output_channel")};
for (var i = 0u; i < ${q}u; i++) {
values[i] = fma(x_vals[i * u32(uniforms.strides[1]) + w_width], w_val, values[i]);
}
}
}
}
for (var i = 0u; i < ${q}u; i++) {
var value = values[i];
${g}
${T}
${w.set("batch","row","col + i","output_channel","value")};
}
}`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${J.cacheKey};${z};${q};${N};${V[0]};${V[1]}`,inputDependencies:K?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:H?H(G):G,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:P}),getShaderSource:I}}}),X1,ul,Z1,ll,cl,iy,J1,Q1,dl,ay=$(()=>{ee(),Zb(),ty(),Zi(),oy(),Gn(),Xi(),Pn(),X1=(Q,J,G,H,K,z)=>{let q=Q[0],F=Q.slice(z?1:2,z?3:4),D=F.length,V=J[0],O=J.slice(2).map((N,I)=>N+(N-1)*(G[I]-1)),P=F.map((N,I)=>N+H[I]+H[I+D]).map((N,I)=>Math.floor((N-O[I]+K[I])/K[I]));return P.splice(0,0,q),P.splice(z?3:1,0,V),P},ul=[2,3,1,0],Z1=(Q,J)=>{if(!Q||Q.length!==2&&Q.length!==3)throw Error("Conv requires 2 or 3 inputs");if(Q[0].dims.length>5)throw Error("greater than 5D is not supported");if(Q[0].dims.length!==Q[1].dims.length)throw Error("filter does not have same dimension as input");let G=Q[0].dims[J.format==="NHWC"?Q[0].dims.length-1:1],H=Q[1].dims[1]*J.group;if(G!==H)throw Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(Q.length===3&&(Q[2].dims.length!==1||Q[1].dims[0]!==Q[2].dims[0]))throw Error("invalid bias");let K=Q[0].dims.length-2;if(J.dilations.length!==K)throw Error(`dilations should be ${K}D`);if(J.strides.length!==K)throw Error(`strides should be ${K}D`);if(J.pads.length!==K*2)throw Error(`pads should be ${K*2}D`);if(J.kernelShape.length!==0&&J.kernelShape.length!==Q[1].dims.length-2)throw Error("invalid kernel shape")},ll=(Q,J)=>{let G=Q.kernelShape.slice();G.length<J[1].dims.length-2&&G.push(...Array(J[1].dims.length-2-G.length).fill(0));for(let z=2;z<J[1].dims.length;++z)G[z-2]===0&&(G[z-2]=J[1].dims[z]);let H=Q.pads.slice();sr.adjustPadsBasedOnAutoPad(J[0].dims,Q.strides,Q.dilations,G,H,Q.format==="NHWC",Q.autoPad);let K=Object.assign({},Q);return Object.assign(K,{kernelShape:G,pads:H}),K},cl=(Q)=>{let J=qi(Q),G=Q.format,H=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][Q.auto_pad],K=Q.dilations,z=Q.group,q=Q.kernel_shape,F=Q.pads,D=Q.strides,V=Q.w_is_const();return{autoPad:H,format:G,dilations:K,group:z,kernelShape:q,pads:F,strides:D,wIsConst:V,...J,cacheKey:`${Q.format};${J.activation};`}},iy=(Q,J,G,H)=>{let K=G.format==="NHWC",z=X1(J[0].dims,J[1].dims,G.dilations,G.pads,G.strides,K);if(G.group!==1){let l=[J[0]];if(K){let _=Q.kernelCustomData.wT??Q.compute(Ge(J[1],ul),{inputs:[1],outputs:[G.wIsConst?-2:-1]})[0];G.wIsConst&&!Q.kernelCustomData.wT&&(Q.kernelCustomData.wT=_),l.push(_)}else l.push(J[1]);J.length===3&&l.push(J[2]),!Q.adapterInfo.isArchitecture("ampere")&&K&&J[1].dims[0]===G.group&&J[1].dims[1]===1&&G.dilations[0]===1&&G.dilations[1]===1?Q.compute(ry(l,G,z,H),{inputs:l}):Q.compute(ny(l,G,z,H),{inputs:l});return}let q=J.length===3,F=J[0].dims[K?1:2],D=J[0].dims[K?2:3],V=J[0].dims[K?3:1],O=J[1].dims[2],P=J[1].dims[3],N=z[K?1:2],I=z[K?2:3],R=z[K?3:1],w=K&&O===F&&P===D&&G.pads[0]===0&&G.pads[1]===0;if(w||O===1&&P===1&&G.dilations[0]===1&&G.dilations[1]===1&&G.strides[0]===1&&G.strides[1]===1&&G.pads[0]===0&&G.pads[1]===0){let l=z[0],_,a,r,f0=[];if(K){let u0=Q.kernelCustomData.wT??Q.compute(Ge(J[1],ul),{inputs:[1],outputs:[G.wIsConst?-2:-1]})[0];if(G.wIsConst&&!Q.kernelCustomData.wT&&(Q.kernelCustomData.wT=u0),w){let d=F*D*V;_=J[0].reshape([1,l,d]),a=u0.reshape([1,d,R]),r=[1,l,R]}else _=J[0].reshape([l,F*D,V]),a=u0.reshape([1,V,R]),r=[l,N*I,R];f0.push(_),f0.push(a)}else _=J[0].reshape([l,V,F*D]),a=J[1].reshape([1,R,V]),r=[l,R,N*I],f0.push(a),f0.push(_);q&&f0.push(J[2]);let t=r[2],p0=f0[0].dims[f0[0].dims.length-1];t<8&&p0<8?Q.compute(Ki(f0,G,z,r,K,H),{inputs:f0}):Q.compute(io(f0,G,z,r,K,H),{inputs:f0});return}let E=!0,T=Q.kernelCustomData.wT??Q.compute(Ge(J[1],ul),{inputs:[1],outputs:[G.wIsConst?-2:-1]})[0];G.wIsConst&&!Q.kernelCustomData.wT&&(Q.kernelCustomData.wT=T);let y=[J[0],T];q&&y.push(J[2]);let x=K?N*I:R,b=K?R:N*I,g=O*P*V;Q.compute(Xb(y,G,z,x,b,g,q,E,H),{inputs:y})},J1=(Q,J)=>{let G=J.format==="NHWC",H=[Q.inputs[0].reshape(G?[Q.inputs[0].dims[0],1,Q.inputs[0].dims[1],Q.inputs[0].dims[2]]:[Q.inputs[0].dims[0],Q.inputs[0].dims[1],1,Q.inputs[0].dims[2]]),Q.inputs[1].reshape([Q.inputs[1].dims[0],Q.inputs[1].dims[1],1,Q.inputs[1].dims[2]])];Q.inputs.length===3&&H.push(Q.inputs[2]);let K=[0,J.pads[0],0,J.pads[1]],z=[1].concat(J.strides),q=[1].concat(J.dilations),F=[1].concat(J.kernelShape),D=ll({...J,pads:K,strides:z,dilations:q,kernelShape:F},H);iy(Q,H,D,(V)=>G?[V[0],V[2],V[3]]:[V[0],V[1],V[3]])},Q1=(Q,J,G)=>{let H=G.format==="NHWC"?"channelsLast":"channelsFirst",K=ll(G,J),z=G.autoPad==="NOTSET"?G.pads:G.autoPad,q=Yb(J[0].dims,J[1].dims,G.strides,G.dilations,z,!1,H);Q.compute(ey(J,K,q.outShape,[q.filterDepth,q.filterHeight,q.filterWidth],[q.padInfo.front,q.padInfo.top,q.padInfo.left],H))},dl=(Q,J)=>{if(Z1(Q.inputs,J),Q.inputs[0].dims.length===3)J1(Q,J);else if(Q.inputs[0].dims.length===5)Q1(Q,Q.inputs,J);else{let G=ll(J,Q.inputs);iy(Q,Q.inputs,G)}}}),sy,uy=$(()=>{X(),gn(),ee(),ne(),sy=(Q,J,G)=>{let H=Q.length>2,K=J.outputShape,z=J.format==="NHWC",q=J.group,F=Q[1].dims,D=F[2]/q,V=F[3],O=z?he(D):1,P=z&&V===1&&D>=4,N=P?Math.floor(D/4)*4:Math.floor(D/O)*O,I=D-N,R=z?he(V):1,w=z?V===1?O:R:1,E=S.size(K)/R,T=[Math.ceil(E/64),1,1];ie("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${T}`);let y=["rank","rank"],x=[J.strides[0],J.strides[1]],b=[J.kernelShape[z?1:2],J.kernelShape[z?2:3]],g=[J.dilations[0],J.dilations[1]],l=[b[0]+(J.dilations[0]<=1?0:(J.kernelShape[z?1:2]-1)*(J.dilations[0]-1)),b[1]+(J.dilations[1]<=1?0:(J.kernelShape[z?2:3]-1)*(J.dilations[1]-1))],_=[l[0]-1-Math.floor((J.pads[0]+J.pads[2])/2),l[1]-1-Math.floor((J.pads[1]+J.pads[3])/2)],a=[{type:12,data:E},{type:12,data:x},{type:12,data:b},{type:12,data:g},{type:12,data:l},{type:6,data:_},{type:12,data:N},{type:12,data:D},{type:12,data:V},...k(Q[0].dims,Q[1].dims)];H&&(a.push(...k(Q[2].dims)),y.push("rank")),a.push(...k(K));let r=(f0)=>{let t=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:x.length},{name:"filter_dims",type:"u32",length:b.length},{name:"dilations",type:"u32",length:b.length},{name:"effective_filter_dims",type:"u32",length:l.length},{name:"pads",type:"i32",length:_.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],p0=ve(Q[0].dataType),u0=z?1:2,d=z?2:3,n=z?3:1,c0=A("W",Q[1].dataType,Q[1].dims.length,w),WQ=A("Dy",Q[0].dataType,Q[0].dims.length,O),R0=[WQ,c0];H&&R0.push(A("bias",Q[2].dataType,[K[n]].length,R));let l0=C("result",Q[0].dataType,K.length,R),d0=()=>{let LQ="";if(P)O===4?LQ+=`
let xValue = ${WQ.getByOffset("x_offset")};
let wValue = ${c0.getByOffset("w_offset")};
dotProd = dotProd + dot(xValue, wValue);
x_offset += 1u;
w_offset += 1u;`:O===2?LQ+=`
dotProd = dotProd + dot(vec4<${p0}>(${WQ.getByOffset("x_offset")}, ${WQ.getByOffset("x_offset + 1u")}), vec4<${p0}>(${c0.getByOffset("w_offset")}, ${c0.getByOffset("w_offset + 1u")}));
x_offset += 2u;
w_offset += 2u;`:O===1&&(LQ+=`
dotProd = dotProd + dot(vec4<${p0}>(${WQ.getByOffset("x_offset")}, ${WQ.getByOffset("x_offset + 1u")}, ${WQ.getByOffset("x_offset + 2u")}, ${WQ.getByOffset("x_offset + 3u")}), vec4<${p0}>(${c0.getByOffset("w_offset")}, ${c0.getByOffset("w_offset + 1u")}, ${c0.getByOffset("w_offset + 2u")}, ${c0.getByOffset("w_offset + 3u")}));
x_offset += 4u;
w_offset += 4u;`);else if(LQ+=`
let xValue = ${z?WQ.getByOffset(`${WQ.indicesToOffset(`${WQ.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${O}`):WQ.get("batch","inputChannel","idyR","idyC")};
`,O===1)LQ+=`
let w_offset = ${c0.indicesToOffset(`${c0.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel, wOutChannel)`)};
let wValue = ${c0.getByOffset(`w_offset / ${w}`)};
dotProd = dotProd + xValue * wValue;`;else for(let h0=0;h0<O;h0++)LQ+=`
let wValue${h0} = ${c0.getByOffset(`${c0.indicesToOffset(`${c0.type.indices}(u32(wRPerm), u32(wCPerm), inputChannel + ${h0}, wOutChannel)`)} / ${w}`)};
dotProd = dotProd + xValue[${h0}] * wValue${h0};`;return LQ},m0=()=>{if(I===0)return"";if(!P)throw Error(`packInputAs4 ${P} is not true.`);let LQ="";if(O===1){LQ+="dotProd = dotProd";for(let h0=0;h0<I;h0++)LQ+=`
+ ${WQ.getByOffset(`x_offset + ${h0}`)} * ${c0.getByOffset(`w_offset + ${h0}`)}`;LQ+=";"}else if(O===2){if(I!==2)throw Error(`Invalid inputChannelsRemainder ${I}.`);LQ+=`
let xValue = ${WQ.getByOffset("x_offset")};
let wValue = ${c0.getByOffset("w_offset")};
dotProd = dotProd + dot(xValue, wValue);`}return LQ},ZQ=`
let outputIndices = ${l0.offsetToIndices(`global_idx * ${R}`)};
let batch = ${l0.indicesGet("outputIndices",0)};
let d1 = ${l0.indicesGet("outputIndices",n)};
let r = ${l0.indicesGet("outputIndices",u0)};
let c = ${l0.indicesGet("outputIndices",d)};
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 = ${l0.type.value}(0.0);
var wR: u32 = 0;
if (uniforms.dilations.x == 1) {
// Minimum wR >= 0 that satisfies (dyRCorner + wR) % (uniforms.strides.x) == 0
wR = u32(((dyRCorner + i32(uniforms.strides.x) - 1) / i32(uniforms.strides.x)) * i32(uniforms.strides.x) - dyRCorner);
}
for (; wR < uniforms.effective_filter_dims.x; wR = wR + 1) {
if (wR % uniforms.dilations.x != 0) {
continue;
}
let dyR = (${p0}(dyRCorner) + ${p0}(wR)) / ${p0}(uniforms.strides[0]);
let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x;
if (dyR < 0.0 || dyR >= ${p0}(uniforms.Dy_shape[${u0}]) || fract(dyR) > 0.0 ||
wRPerm < 0) {
continue;
}
let idyR: u32 = u32(dyR);
var wC: u32 = 0;
if (uniforms.dilations.y == 1) {
// Minimum wC >= 0 that satisfies (dyCCorner + wC) % (uniforms.strides.y) == 0
wC = u32(((dyCCorner + i32(uniforms.strides.y) - 1) / i32(uniforms.strides.y)) * i32(uniforms.strides.y) - dyCCorner);
}
for (; wC < uniforms.effective_filter_dims.y; wC = wC + 1) {
if (wC % uniforms.dilations.y != 0) {
continue;
}
let dyC = (${p0}(dyCCorner) + ${p0}(wC)) / ${p0}(uniforms.strides.y);
let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y;
if (dyC < 0.0 || dyC >= ${p0}(uniforms.Dy_shape[${d}]) ||
fract(dyC) > 0.0 || wCPerm < 0) {
continue;
}
let idyC: u32 = u32(dyC);
var inputChannel = groupId * uniforms.input_channels_per_group;
${P?`
var x_offset = ${WQ.indicesToOffset(`${WQ.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${O};
var w_offset = ${c0.indicesToOffset(`${c0.type.indices}(wRPerm, wCPerm, inputChannel, wOutChannel)`)} / ${w};
`:""}
for (var d2: u32 = 0; d2 < uniforms.input_channels_per_group_int; d2 = d2 + ${P?4:O}) {
${d0()}
inputChannel = inputChannel + ${P?4:O};
}
${m0()}
wC = wC + uniforms.strides.y - 1;
}
wR = wR + uniforms.strides[0] - 1;
}
let value = dotProd${H?` + bias[d1 / ${R}]`:""};
${l0.setByOffset("global_idx","value")};
`;return`
${f0.registerUniforms(t).declareVariables(...R0,l0)}
${f0.mainStart()}
${f0.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
${ZQ}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${J.cacheKey};${O}${w}${R}${P}${I}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:T[0],y:T[1],z:T[2]},outputs:[{dims:G?G(K):K,dataType:Q[0].dataType}],programUniforms:a}),getShaderSource:r}}}),Y1,e$,t$,ly,cy,n$,dy,r$,py,fy=$(()=>{uy(),Gn(),Pn(),Y1=(Q,J,G,H,K,z)=>(Q-1)*J+G+(H-1)*K+1-z,e$=(Q,J,G,H,K)=>{let z=Math.floor(Q/2);J==="SAME_UPPER"?(G[H]=z,G[K]=Q-z):J==="SAME_LOWER"&&(G[H]=Q-z,G[K]=z)},t$=(Q,J,G,H,K,z,q,F,D,V)=>{let O=Q.length-2,P=V.length===0;D.length<O&&D.push(...Array(O-D.length).fill(0));let N=Q[0],I=J[F?3:1]*K;for(let R=0,w=Q.length-O-(F?1:0);R<O;++R,++w){let E=Q[w],T=P?E*q[R]:V[R],y=Y1(E,q[R],z[R],J[w],G[R],T);e$(y,H,z,R,R+O),P&&V.push(q[R]*(E-1)+D[R]+(J[w]-1)*G[R]+1-z[R]-z[R+O])}V.splice(0,0,N),V.splice(F?3:1,0,I)},ly=(Q,J)=>{let G=Q.kernelShape.slice();if(Q.kernelShape.length===0||Q.kernelShape.reduce((P,N)=>P*N,1)===0){G.length=0;for(let P=2;P<J[1].dims.length;++P)G.push(J[1].dims[P])}let H=Q.format==="NHWC";G.splice(0,0,J[1].dims[0]),G.splice(H?3:1,0,J[1].dims[1]);let K=Q.pads.slice(),z=Q.outputShape.slice(),q=Q.outputPadding.slice(),F=J[0].dims,D=Q.dilations.slice();if(D.reduce((P,N)=>P+N,0)===0){let P=J[0].dims.length-2;D=Array(P).fill(1)}let V=Q.strides.slice();if(V.reduce((P,N)=>P+N,0)===0){let P=J[0].dims.length-2;V=Array(P).fill(1)}t$(F,G,D,Q.autoPad,Q.group,K,V,H,q,z);let O=Object.assign({},Q);return Object.assign(O,{kernelShape:G,pads:K,outputPadding:q,outputShape:z,dilations:D,strides:V}),O},cy=(Q)=>{let J=qi(Q),G=Q.format,H=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof Q.autoPad>"u"?0:Q.autoPad],K=Q.dilations,z=Q.group??1,q=Q.kernelShape,F=Q.pads,D=Q.strides,V=Q.wIsConst(),O=Q.outputPadding,P=Q.outputShape;return{autoPad:H,format:G,dilations:K,group:z,kernelShape:q,outputPadding:O,outputShape:P,pads:F,strides:D,wIsConst:V,...J,cacheKey:`${Q.format};${J.activation};`}},n$=(Q,J)=>{if(!Q||Q.length!==2&&Q.length!==3)throw Error("Conv requires 2 or 3 inputs");if(Q[0].dims.length!==4&&Q[0].dims.length!==3)throw Error("currently only support 2-dimensional conv");if(Q[0].dims.length!==Q[1].dims.length)throw Error("filter does not have same dimension as input");let G=Q[0].dims[J.format==="NHWC"?Q[0].dims.length-1:1],H=Q[1].dims[0];if(G!==H)throw Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let K=Q[1].dims[1]*J.group;if(Q.length===3&&(Q[2].dims.length!==1||Q[2].dims[0]!==K))throw Error("invalid bias");let z=Q[0].dims.length-2;if(J.dilations.reduce((q,F)=>q+F,0)>0&&J.dilations.length!==z)throw Error(`dilations should be ${z}D`);if(J.strides.reduce((q,F)=>q+F,0)>0&&J.strides.length!==z)throw Error(`strides should be ${z}D`);if(J.pads.reduce((q,F)=>q+F,0)>0&&J.pads.length!==z*2)throw Error(`pads should be ${z*2}D`);if(J.outputPadding.length!==z&&J.outputPadding.length!==0)throw Error(`output_padding should be ${z}D`);if(J.kernelShape.reduce((q,F)=>q+F,0)>0&&J.kernelShape.length!==0&&J.kernelShape.length!==Q[1].dims.length-2)throw Error("invalid kernel shape");if(J.outputShape.length!==0&&J.outputShape.length!==Q[0].dims.length-2)throw Error("invalid output shape")},dy=(Q,J,G,H)=>{let K=Q.kernelCustomData.wT??Q.compute(Ge(J[1],[2,3,0,1]),{inputs:[1],outputs:[G.wIsConst?-2:-1]})[0];G.wIsConst&&!Q.kernelCustomData.wT&&(Q.kernelCustomData.wT=K);let z=[J[0],K];J.length===3&&z.push(J[2]),Q.compute(sy(z,G,H),{inputs:z})},r$=(Q,J)=>{let G=J.format==="NHWC",H=[Q.inputs[0].reshape(G?[Q.inputs[0].dims[0],1,Q.inputs[0].dims[1],Q.inputs[0].dims[2]]:[Q.inputs[0].dims[0],Q.inputs[0].dims[1],1,Q.inputs[0].dims[2]]),Q.inputs[1].reshape([Q.inputs[1].dims[0],Q.inputs[1].dims[1],1,Q.inputs[1].dims[2]])];Q.inputs.length===3&&H.push(Q.inputs[2]);let K=J.kernelShape;(K.length===0||K[0]===0)&&(K=[Q.inputs[1].dims[2]]);let z=J.dilations;(z.length===0||z[0]===0)&&(z=[1]);let q=J.strides;(q.length===0||q[0]===0)&&(q=[1]);let F=J.pads;F.length===0&&(F=[0,0]),F=[0,F[0],0,F[1]],q=[1].concat(q),z=[1].concat(z),K=[1].concat(K);let D=J.outputPadding;D=[0].concat(D);let V=ly({...J,pads:F,strides:q,dilations:z,kernelShape:K,outputPadding:D},H);dy(Q,H,V,(O)=>G?[O[0],O[2],O[3]]:[O[0],O[1],O[3]])},py=(Q,J)=>{if(n$(Q.inputs,J),Q.inputs[0].dims.length===3)r$(Q,J);else{let G=ly(J,Q.inputs);dy(Q,Q.inputs,G)}}}),o$,hy,my,gy=$(()=>{X(),ee(),ke(),ne(),o$=(Q,J,G,H)=>{let K=S.size(J),z=J.length,q=A("input",Q,z),F=C("output",Q,z),D=G.dataType===6?G.getInt32Array()[0]:Number(G.getBigInt64Array()[0]),V=S.normalizeAxis(D,z),O=(P)=>{let N=` i32(${q.indicesGet("inputIndices","uniforms.axis")}) `,I=B("uniforms.input_shape","uniforms.axis",z),R=H.reverse?N+(H.exclusive?" + 1":""):"0",w=H.reverse?I:N+(H.exclusive?"":" + 1");return`
${P.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(q,F)}
${P.mainStart()}
${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var inputIndices = ${F.offsetToIndices("global_idx")};
var sum = ${F.type.value}(0);
let first : i32 = ${R};
let last : i32 = ${w};
for (var i : i32 = first; i < last; i++) {
${q.indicesSet("inputIndices","uniforms.axis","u32(i)")};
sum = sum + ${q.getByIndices("inputIndices")};
}
${F.setByOffset("global_idx","sum")};
}`};return{name:"CumSum",shaderCache:{hint:H.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:J,dataType:Q}],dispatchGroup:{x:Math.ceil(K/64)},programUniforms:[{type:12,data:K},{type:12,data:V},...k(J,J)]}),getShaderSource:O}},hy=(Q,J)=>{let G=Q.inputs[0].dims,H=Q.inputs[0].dataType,K=Q.inputs[1];Q.compute(o$(H,G,K,J),{inputs:[0]})},my=(Q)=>{let J=Q.exclusive===1,G=Q.reverse===1;return Z({exclusive:J,reverse:G})}}),i$,a$,s$,by,yy,_y=$(()=>{X(),ee(),ke(),ne(),i$=(Q)=>{if(!Q||Q.length!==1)throw Error("DepthToSpace requires 1 input.");if(Q[0].dims.length!==4)throw Error("DepthToSpace requires 4D input.")},a$=(Q,J,G,H)=>{let K=[];K.push(`fn perm(i: ${H.type.indices}) -> ${G.type.indices} {
var a: ${G.type.indices};`);for(let z=0;z<J;++z)K.push(G.indicesSet("a",Q[z],`i[${z}]`));return K.push("return a;}"),K.join(`
`)},s$=(Q,J)=>{let G,H,K,z,q,F,D=J.format==="NHWC",V=J.blocksize,O=J.mode==="DCR";D?([G,H,K,z]=Q.dims,q=O?[G,H,K,V,V,z/V**2]:[G,H,K,z/V**2,V,V],F=O?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([G,H,K,z]=[Q.dims[0],Q.dims[2],Q.dims[3],Q.dims[1]],q=O?[G,V,V,z/V**2,H,K]:[G,z/V**2,V,V,H,K],F=O?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let P=Q.reshape(q),N=P.dims.length,I=Q.dataType,R=A("a",I,N),w=C("output",I,N),E=(T)=>`
${T.registerUniform("output_size","u32").declareVariables(R,w)}
${a$(F,N,R,w)}
${T.mainStart()}
${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let indices = ${w.offsetToIndices("global_idx")};
let aIndices = perm(indices);
${w.setByOffset("global_idx",R.getByIndices("aIndices"))}
}`;return{name:"DepthToSpace",shaderCache:{hint:`${Q.dims};${J.blocksize};${J.mode}`,inputDependencies:["rank"]},getRunData:(T)=>{let y=D?[G,H*V,K*V,z/V**2]:[G,z/V**2,H*V,K*V],x=S.size(y),b=P.dims,g=S.sortBasedOnPerm(b,F);return{outputs:[{dims:y,dataType:T[0].dataType}],dispatchGroup:{x:Math.ceil(x/64)},programUniforms:[{type:12,data:x},...k(b,g)]}},getShaderSource:E}},by=(Q,J)=>{i$(Q.inputs),Q.compute(s$(Q.inputs[0],J))},yy=(Q)=>Z({blocksize:Q.blocksize,mode:Q.mode,format:Q.format})}),pl,Qi,xy,u$,l$,fl,hl,wy,c$,Ty,vy,Iy=$(()=>{X(),ee(),ke(),ne(),pl="[a-zA-Z]|\\.\\.\\.",Qi="("+pl+")+",xy="^"+Qi+"$",u$="("+Qi+",)*"+Qi,l$="^"+u$+"$",fl=class{constructor(Q=-1){this.symbolToIndices=new Map,this.inputIndex=Q}addSymbol(Q,J){let G=this.symbolToIndices.get(Q);G===void 0?G=[J]:G.push(J),this.symbolToIndices.set(Q,G)}},hl=class{constructor(Q,J){this.equation=J,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=[],this.outputDims=[];let[G,H]=J.includes("->")?J.split("->",2):[J,""];if(!G.match(RegExp(l$)))throw Error("Invalid LHS term");if(G.split(",").forEach((K,z)=>{let q=Q[z].dims.slice();if(!K.match(RegExp(xy)))throw Error("Invalid LHS term");let F=this.processTerm(K,!0,q,z);this.lhs.push(F)}),H==="")H+=[...this.symbolToInfo.entries()].filter(([K,z])=>z.count===1||K==="...").map(([K])=>K).join("");else if(!H.match(RegExp(Qi)))throw Error("Invalid RHS");H.match(RegExp(pl,"g"))?.forEach((K)=>{if(K==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let z=this.symbolToInfo.get(K);if(z===void 0)throw Error("Invalid RHS symbol");this.outputDims.push(z.dimValue)}}),this.rhs=this.processTerm(H,!1,this.outputDims)}addSymbol(Q,J,G){let H=this.symbolToInfo.get(Q);if(H!==void 0){if(H.dimValue!==J&&H.count!==1)throw Error("Dimension mismatch");H.count++,H.inputIndices.push(G)}else H={count:1,dimValue:J,inputIndices:[G]};this.symbolToInfo.set(Q,H)}processTerm(Q,J,G,H=-1){let K=G.length,z=!1,q=[],F=0;if(!Q.match(RegExp(xy))&&!J&&Q!=="")throw Error("Invalid LHS term");let D=Q.match(RegExp(pl,"g")),V=new fl(H);return D?.forEach((O,P)=>{if(O==="..."){if(z)throw Error("Only one ellipsis is allowed per input term");z=!0;let N=K-D.length+1;if(N<0)throw Error("Ellipsis out of bounds");if(q=G.slice(F,F+N),this.hasEllipsis){if(this.ellipsisDims.length!==q.length||this.ellipsisDims.toString()!==q.toString())throw Error("Ellipsis dimensions mismatch")}else if(J)this.hasEllipsis=!0,this.ellipsisDims=q;else throw Error("Ellipsis must be specified in the LHS");for(let I=0;I<q.length;I++){let R=String.fromCharCode(48+I);V.addSymbol(R,P+I),this.addSymbol(R,G[F++],H)}}else V.addSymbol(O,P+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(O,G[F++],H)}),V}},wy=(Q)=>Q+"_max",c$=(Q,J,G,H)=>{let K=Q.map((V)=>V.length).map((V,O)=>A(`input${O}`,J,V)),z=S.size(H),q=C("output",J,H.length),F=[...G.symbolToInfo.keys()].filter((V)=>!G.rhs.symbolToIndices.has(V)),D=(V)=>{let O=[],P="var prod = 1.0;",N="var sum = 0.0;",I="sum += prod;",R=[],w=[],E=[],T=[],y=G.symbolToInfo.size===G.rhs.symbolToIndices.size;G.symbolToInfo.forEach((b,g)=>{if(G.rhs.symbolToIndices.has(g)){let l=G.rhs.symbolToIndices.get(g)?.[0];l!==void 0&&G.lhs.forEach((_,a)=>{if(b.inputIndices.includes(a)){let r=_.symbolToIndices.get(g);if(r===void 0)throw Error("Invalid symbol error");r.forEach((f0)=>{O.push(`${K[a].indicesSet(`input${a}Indices`,f0,q.indicesGet("outputIndices",l))}`)})}})}else G.lhs.forEach((l,_)=>{if(b.inputIndices.includes(_)){let a=l.symbolToIndices.get(g);if(a===void 0)throw Error("Invalid symbol error");a.forEach((r)=>{R.push(`${K[_].indicesSet(`input${_}Indices`,r,`${g}`)}`)}),T.push(`prod *= ${K[_].getByIndices(`input${_}Indices`)};`)}}),w.push(`for(var ${g}: u32 = 0; ${g} < uniforms.${wy(g)}; ${g}++) {`),E.push("}")});let x=y?[...O,`let sum = ${K.map((b,g)=>b.getByIndices(`input${g}Indices`)).join(" * ")};`]:[...O,N,...w,...R,P,...T,I,...E];return`
${V.registerUniforms(F.map((b)=>({name:`${wy(b)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...K,q)}
${V.mainStart()}
${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
var outputIndices = ${q.offsetToIndices("global_idx")};
${K.map((b,g)=>`var input${g}Indices: ${K[g].type.indices};`).join(`
`)}
${x.join(`
`)};
${q.setByOffset("global_idx","sum")};
}`};return{name:"Einsum",shaderCache:{hint:G.equation,inputDependencies:Q.map(()=>"rank")},getRunData:()=>{let V=F.filter((P)=>G.symbolToInfo.has(P)).map((P)=>({type:12,data:G.symbolToInfo.get(P)?.dimValue||0}));V.push({type:12,data:z});let O=Q.map((P,N)=>[...k(P)]).reduce((P,N)=>P.concat(N),V);return O.push(...k(H)),{outputs:[{dims:H,dataType:J}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:O}},getShaderSource:D}},Ty=(Q,J)=>{let G=new hl(Q.inputs,J.equation),H=G.outputDims,K=Q.inputs.map((z,q)=>z.dims);Q.compute(c$(K,Q.inputs[0].dataType,G,H))},vy=(Q)=>{let J=Q.equation.replace(/\s+/g,"");return Z({equation:J})}}),d$,Sy,p$,f$,$y,Ay=$(()=>{X(),ee(),ne(),d$=(Q)=>{if(!Q||Q.length!==2)throw Error("Expand requires 2 input.");let J=Q[0].dims,G=Array.from(Q[1].getBigInt64Array(),Number),H=G.length<J.length?0:G.length-J.length,K=J.length<G.length?0:J.length-G.length;for(;H<G.length&&K<J.length;++H,++K)if(G[H]!==J[K]&&G[H]!==1&&J[K]!==1)throw Error("Expand requires shape to be broadcastable to input")},Sy=(Q,J)=>{let G=Q.length-J.length,H=[];for(let K=0;K<G;++K)H.push(Q[K]);for(let K=0;K<J.length;++K)H.push(J[K]===1?Q[K+G]:J[K]);return H},p$=(Q,J)=>Q.length>J.length?Sy(Q,J):Sy(J,Q),f$=(Q)=>{let J=Q[0].dims,G=Array.from(Q[1].getBigInt64Array(),Number),H=p$(J,G),K=Q[0].dataType,z=K===9||S.size(J)===1,q=K===9||J.length>0&&J[J.length-1]%4===0?4:1,F=z||H.length>0&&H[H.length-1]%4===0?4:1,D=Math.ceil(S.size(H)/F),V=(P)=>{let N=A("input",K,J.length,q),I=C("output",K,H.length,F),R;if(K===9){let w=(E,T,y="")=>`
let outputIndices${T} = ${I.offsetToIndices(`outputOffset + ${T}u`)};
let offset${T} = ${N.broadcastedIndicesToOffset(`outputIndices${T}`,I)};
let index${T} = offset${T} / 4u;
let component${T} = offset${T} % 4u;
${E}[${T}] = ${y}(${N.getByOffset(`index${T}`)}[component${T}]);
`;R=`
let outputOffset = global_idx * ${F};
var data = vec4<u32>(0);
${w("data",0,"u32")}
${w("data",1,"u32")}
${w("data",2,"u32")}
${w("data",3,"u32")}
${I.setByOffset("global_idx","data")}
}`}else R=`
let outputIndices = ${I.offsetToIndices(`global_idx * ${F}`)};
let inputOffset = ${N.broadcastedIndicesToOffset("outputIndices",I)};
let data = ${I.type.value}(${N.getByOffset(`inputOffset / ${q}`)});
${I.setByOffset("global_idx","data")}
}`;return`
${P.registerUniform("vec_size","u32").declareVariables(N,I)}
${P.mainStart()}
${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
${R}`},O=[{type:12,data:D},...k(J,H)];return{name:"Expand",shaderCache:{hint:`${H.length};${q}${F}`,inputDependencies:["rank"]},getShaderSource:V,getRunData:()=>({outputs:[{dims:H,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:O})}},$y=(Q)=>{d$(Q.inputs),Q.compute(f$(Q.inputs),{inputs:[0]})}}),h$,Py,Oy=$(()=>{X(),ee(),ne(),Hi(),h$=(Q)=>{let J=Q[0].dataType,G=S.size(Q[0].dims),H=S.size(Q[1].dims),K=H%4===0,z=(q)=>{let F=A("x",J,[1],4),D=A("bias",J,[1],4),V=C("y",J,[1],4),O=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],P=(I)=>`
let bias${I}_offset: u32 = (global_idx * 4 + ${I}) % uniforms.bias_size;
let bias${I} = ${D.getByOffset(`bias${I}_offset / 4`)}[bias${I}_offset % 4];`,N=K?`
let bias = ${D.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${P(0)}${P(1)}${P(2)}${P(3)}
let bias = ${F.type.value}(bias0, bias1, bias2, bias3);`;return`${q.registerUniforms(O).declareVariables(F,D,V)}
${ol(Ve(J))}
${q.mainStart(ur)}
${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
let x = ${F.getByOffset("global_idx")};
${N}
let x_in = x + bias;
${V.setByOffset("global_idx",il("x_in"))}
}`};return{name:"FastGeluWithBias",shaderCache:{hint:`${K}`,inputDependencies:["type","type"]},getShaderSource:z,getRunData:(q)=>({outputs:[{dims:q[0].dims,dataType:q[0].dataType}],programUniforms:[{type:12,data:Math.ceil(G/4)},{type:12,data:H}],dispatchGroup:{x:Math.ceil(G/ur/4)}})}},Py=(Q)=>{Q.inputs.length<2||S.size(Q.inputs[1].dims)===0?Ib(Q):Q.compute(h$(Q.inputs))}}),m$,g$,Ey,Cy,Dy=$(()=>{X(),ee(),ke(),ne(),m$=(Q)=>{if(!Q||Q.length!==2)throw Error("Gather requires 2 inputs.")},g$=(Q,J)=>{let G=Q[0].dims,H=Q[1].dims,K=G.length,z=S.normalizeAxis(J.axis,K),q=G.slice(0);q.splice(z,1,...H);let F=G[z],D=Q[0].dataType===9?4:1,V=Math.ceil(S.size(q)/D),O=[{type:12,data:V},{type:6,data:F},{type:12,data:z},...k(Q[0].dims,Q[1].dims,q)],P=(N)=>{let I=A("data",Q[0].dataType,Q[0].dims.length,D),R=A("inputIndices",Q[1].dataType,Q[1].dims.length),w=C("output",Q[0].dataType,q.length,D),E=(y)=>{let x=H.length,b=`var indicesIndices${y} = ${R.type.indices}(0);`;for(let g=0;g<x;g++)b+=`${x>1?`indicesIndices${y}[${g}]`:`indicesIndices${y}`} = ${q.length>1?`outputIndices${y}[uniforms.axis + ${g}]`:`outputIndices${y}`};`;b+=`
var idx${y} = ${R.getByIndices(`indicesIndices${y}`)};
if (idx${y} < 0) {
idx${y} = idx${y} + uniforms.axisDimLimit;
}
var dataIndices${y} : ${I.type.indices};
`;for(let g=0,l=0;g<K;g++)g===z?(b+=`${K>1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = u32(idx${y});`,l+=x):(b+=`${K>1?`dataIndices${y}[${g}]`:`dataIndices${y}`} = ${q.length>1?`outputIndices${y}[${l}]`:`outputIndices${y}`};`,l++);return b},T;if(Q[0].dataType===9){let y=(x,b,g="")=>`
let outputIndices${b} = ${w.offsetToIndices(`outputOffset + ${b}u`)};
${E(b)};
let offset${b} = ${I.indicesToOffset(`dataIndices${b}`)};
let index${b} = offset${b} / 4u;
let component${b} = offset${b} % 4u;
${x}[${b}] = ${g}(${I.getByOffset(`index${b}`)}[component${b}]);
`;T=`
let outputOffset = global_idx * ${D};
var value = vec4<u32>(0);
${y("value",0,"u32")}
${y("value",1,"u32")}
${y("value",2,"u32")}
${y("value",3,"u32")}
${w.setByOffset("global_idx","value")}
`}else T=`
let outputIndices = ${w.offsetToIndices("global_idx")};
${E("")};
let value = ${I.getByIndices("dataIndices")};
${w.setByOffset("global_idx","value")};
`;return`
${N.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(I,R,w)}
${N.mainStart()}
${N.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
${T}
}`};return{name:"Gather",shaderCache:{hint:J.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:q,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(V/64)},programUniforms:O}),getShaderSource:P}},Ey=(Q)=>Z({axis:Q.axis}),Cy=(Q,J)=>{let G=Q.inputs;m$(G),Q.compute(g$(Q.inputs,J))}}),b$,ky,Ly,Ry=$(()=>{X(),ee(),ne(),b$=(Q,J,G,H,K,z,q,F,D)=>{let V=[{type:12,data:z},{type:12,data:H},{type:12,data:K},{type:12,data:G},{type:12,data:q},{type:12,data:F},{type:12,data:D}],O=[z];V.push(...k(J.dims,O));let P=(N)=>{let I=A("indices_data",J.dataType,J.dims.length),R=C("input_slice_offsets_data",12,1,1),w=[I,R],E=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:K.length},{name:"sizes_from_slice_dims_data",type:"u32",length:G.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return`
${N.registerUniforms(E).declareVariables(...w)}
${N.mainStart()}
${N.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let batch_idx = global_idx / uniforms.num_slices_per_batch;
let base_offset = batch_idx * uniforms.input_batch_stride;
let slice_indices_base_offset = global_idx * uniforms.num_slice_dims;
var relative_slice_offset = 0;
for (var dim_idx = 0u; dim_idx < uniforms.num_slice_dims; dim_idx ++) {
var index = i32(indices_data[dim_idx + slice_indices_base_offset].x);
let input_dim_idx = uniforms.batch_dims + dim_idx;
if (index < 0) {
${K.length===1?"index += i32(uniforms.input_dims);":"index += i32(uniforms.input_dims[input_dim_idx]);"}
}
${G.length===1?"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data);":"relative_slice_offset += index * i32(uniforms.sizes_from_slice_dims_data[dim_idx]);"}
}
input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset);
}`};return Q.compute({name:"computeSliceOffsets",shaderCache:{hint:`${K.length}_${G.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:O,dataType:Q.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:V}),getShaderSource:P},{inputs:[J],outputs:[-1]})[0]},ky=(Q,J)=>{let G=Q.inputs,H=G[0].dims,K=G[0].dataType,z=G[1].dims,q=z[z.length-1],F=S.sizeToDimension(z,z.length-1),D=S.sizeFromDimension(H,J.batchDims+q),V=S.sizeToDimension(H,J.batchDims),O=S.sizeFromDimension(H,J.batchDims),P=F/V,N=Array(q),I=D;for(let b=0;b<q;++b)N[q-1-b]=I,I*=H[J.batchDims+q-1-b];let R=b$(Q,G[1],N,J.batchDims,H,F,P,O,q),w=J.batchDims+q;if(w>H.length)throw Error("last dimension of indices must not be larger than rank of input tensor");let E=z.slice(0,-1).concat(H.slice(w)),T=S.size(E),y=[{type:12,data:T},{type:12,data:D},...k(G[0].dims,R.dims,E)],x=(b)=>{let g=A("data",G[0].dataType,G[0].dims.length),l=A("slice_offsets",12,R.dims.length),_=C("output",G[0].dataType,E.length);return`
${b.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(g,l,_)}
${b.mainStart()}
${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let slice_offset = slice_offsets[global_idx / uniforms.slice_size];
output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size];
}`};Q.compute({name:"GatherND",shaderCache:{hint:J.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:E,dataType:K}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:y}),getShaderSource:x},{inputs:[G[0],R]})},Ly=(Q)=>({batchDims:Q.batch_dims,cacheKey:""})}),y$,_$,Ny,zy,My=$(()=>{X(),ee(),ke(),ne(),y$=(Q,J)=>{if(Q.length<3||Q.length>4)throw Error("GatherBlockQuantized requires 3 or 4 inputs.");let G=S.normalizeAxis(J.quantizeAxis,Q[0].dims.length),H=J.blockSize,K=Q[0],z=Q[2],q=Q.length===4?Q[3]:void 0;if(z.dims.length!==K.dims.length||!K.dims.map((F,D)=>D===G?Math.ceil(F/H)===z.dims[D]:F===z.dims[D]).reduce((F,D)=>F&&D,!0))throw Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(q){if(q.dataType!==K.dataType)throw Error("Zero point must have the same data type as the input tensor.");if(q.dims.length!==z.dims.length||!q.dims.map((F,D)=>F===z.dims[D]).reduce((F,D)=>F&&D,!0))throw Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},_$=(Q,J)=>{let G=Q[0].dims,H=Q[1].dims,K=G.length,z=S.normalizeAxis(J.gatherAxis,K),q=S.normalizeAxis(J.quantizeAxis,K),F=G.slice(0);F.splice(z,1,...H);let D=S.size(F),V=Q[2].dataType,O=Q[0].dataType===22,P=[{type:12,data:D},{type:12,data:q},{type:12,data:z},{type:12,data:J.blockSize},...k(...Q.map((I,R)=>I.dims),F)],N=(I)=>{let R=A("data",Q[0].dataType,Q[0].dims.length),w=A("inputIndices",Q[1].dataType,Q[1].dims.length),E=A("scales",Q[2].dataType,Q[2].dims.length),T=Q.length>3?A("zeroPoint",Q[3].dataType,Q[3].dims.length):void 0,y=C("output",V,F.length),x=[R,w,E];T&&x.push(T);let b=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return`
${I.registerUniforms(b).declareVariables(...x,y)}
${I.mainStart()}
let output_indices = ${y.offsetToIndices("global_idx")};
var indices_indices = ${w.type.indices}(0);
${H.length>1?`
for (var i: u32 = 0; i < ${H.length}; i++) {
let index = ${y.indicesGet("output_indices","uniforms.gather_axis + i")};
${w.indicesSet("indices_indices","i","index")};
}`:`indices_indices = ${y.indicesGet("output_indices","uniforms.gather_axis")};`};
var data_indices = ${R.type.indices}(0);
for (var i: u32 = 0; i < uniforms.gather_axis; i++) {
let index = ${y.indicesGet("output_indices","i")};
${R.indicesSet("data_indices","i","index")};
}
var index_from_indices = ${w.getByIndices("indices_indices")};
if (index_from_indices < 0) {
index_from_indices += ${G[z]};
}
${R.indicesSet("data_indices","uniforms.gather_axis","u32(index_from_indices)")};
for (var i = uniforms.gather_axis + 1; i < ${F.length}; i++) {
let index = ${y.indicesGet("output_indices",`i + ${H.length} - 1`)};
${R.indicesSet("data_indices","i","index")};
}
let data_offset = ${R.indicesToOffset("data_indices")};
let data_index = data_offset % 8;
// Convert 4-bit packed data to 8-bit packed data.
let packed_4bit_quantized_data = ${R.getByOffset("data_offset / 8")};
let packed_8bit_quantized_data = (packed_4bit_quantized_data >> (4 * (data_index % 2))) & 0x0f0f0f0f;
let quantized_data_vec = ${O?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_quantized_data));
let quantized_data = quantized_data_vec[data_index / 2];
var scale_indices = data_indices;
let quantize_axis_index = ${E.indicesGet("data_indices","uniforms.quantize_axis")} / uniforms.block_size;
${E.indicesSet("scale_indices","uniforms.quantize_axis","quantize_axis_index")};
var scale = ${E.getByIndices("scale_indices")};
${T?`
let zero_point_indices = scale_indices;
let zero_point_offset = ${T.indicesToOffset("zero_point_indices")};
let zero_point_index = zero_point_offset % 8;
let packed_4bit_zero_points = ${T.getByOffset("zero_point_offset / 8")};
let packed_8bit_zero_points = (packed_4bit_zero_points >> (4 * (zero_point_index % 2))) & 0x0f0f0f0f;
let zero_point_vec = ${O?"unpack4xI8":"unpack4xU8"}(u32(packed_8bit_zero_points));
let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"};
let dequantized_data = ${Ve(V)}(quantized_data - zero_point) * scale;
${y.setByOffset("global_idx","dequantized_data")};
}`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${J.cacheKey};${Q.filter((I,R)=>R!==1).map((I)=>I.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:Q.length},(I,R)=>"rank")},getRunData:()=>({outputs:[{dims:F,dataType:V}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:P}),getShaderSource:N}},Ny=(Q,J)=>{let G=Q.inputs;y$(G,J),Q.compute(_$(Q.inputs,J))},zy=(Q)=>Z({blockSize:Q.blockSize,gatherAxis:Q.gatherAxis,quantizeAxis:Q.quantizeAxis})}),x$,w$,By,Fy,Vy=$(()=>{X(),ee(),ke(),ne(),x$=(Q)=>{if(!Q||Q.length!==2)throw Error("GatherElements requires 2 inputs.");if(Q[0].dims.length<1)throw Error("GatherElements requires that the data input be rank >= 1.");if(Q[0].dims.length!==Q[1].dims.length)throw Error(`GatherElements requires that the data input and
indices input tensors be of same rank.`)},w$=(Q,J)=>{let G=Q[0].dims,H=Q[0].dataType,K=G.length,z=Q[1].dims,q=Q[1].dataType,F=S.normalizeAxis(J.axis,K),D=G[F],V=z.slice(0),O=S.size(V),P=A("input",H,K),N=A("indicesInput",q,z.length),I=C("output",H,V.length),R=[{type:12,data:O},{type:6,data:D},{type:12,data:F}];return R.push(...k(G,z,V)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:V,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:R}),getShaderSource:(w)=>`
${w.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(P,N,I)}
${w.mainStart()}
${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let outputIndices = ${I.offsetToIndices("global_idx")};
var idx = ${N.getByOffset("global_idx")};
if (idx < 0) {
idx = idx + uniforms.axisDimLimit;
}
var inputIndices = ${P.type.indices}(outputIndices);
${P.indicesSet("inputIndices","uniforms.axis","u32(idx)")};
let value = ${P.getByIndices("inputIndices")};
${I.setByOffset("global_idx","value")};
}`}},By=(Q)=>Z({axis:Q.axis}),Fy=(Q,J)=>{let G=Q.inputs;x$(G),Q.compute(w$(Q.inputs,J))}}),T$,v$,Gy,Uy,Wy=$(()=>{X(),ee(),ne(),T$=(Q)=>{if(!Q)throw Error("Input is missing");if(Q.length<2||Q.length>3)throw Error("Invaid input number.");if(Q.length===3&&Q[2].dims.length>2)throw Error("Invalid input shape of C");if(Q[0].dataType!==Q[1].dataType||Q.length===3&&Q[0].dataType!==Q[2].dataType)throw Error("Input types are mismatched")},v$=(Q,J)=>{let G=Q[0].dims.slice(),H=Q[1].dims.slice(),[K,z,q]=Di.getShapeOfGemmResult(G,J.transA,H,J.transB,Q.length===3?Q[2].dims:void 0),F=[K,z];if(!F)throw Error("Can't use gemm on the given tensors");let D=16,V=Math.ceil(z/D),O=Math.ceil(K/D),P=!0,N=S.size(F),I=[{type:12,data:P?V:N},{type:12,data:K},{type:12,data:z},{type:12,data:q},{type:1,data:J.alpha},{type:1,data:J.beta}],R=["type","type"];Q.length===3&&(I.push(...k(Q[2].dims)),R.push("rank")),I.push(...k(F));let w=(T)=>{let y="";J.transA&&J.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":J.transA&&!J.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!J.transA&&J.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!J.transA&&!J.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let x=J.alpha===1?"":"value *= uniforms.alpha;",b=A("a",Q[0].dataType,Q[0].dims),g=A("b",Q[1].dataType,Q[1].dims),l=b.type.value,_=null,a=[b,g];Q.length===3&&(_=A("c",Q[2].dataType,Q[2].dims.length),a.push(_));let r=C("output",Q[0].dataType,F.length);a.push(r);let f0=[{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`
${T.registerUniforms(f0).declareVariables(...a)}
${T.mainStart()}
${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let m = global_idx / uniforms.N;
let n = global_idx % uniforms.N;
var value = ${l}(0);
for (var k: u32 = 0u; k < uniforms.K; k++) {
${y}
}
${x}
${_!=null?`let cOffset = ${_.broadcastedIndicesToOffset("vec2(m, n)",r)}; value += ${l}(uniforms.beta) * ${_.getByOffset("cOffset")};`:""}
output[global_idx] = value;
}`},E=(T)=>{let y=A("a",Q[0].dataType,Q[0].dims),x=A("b",Q[1].dataType,Q[1].dims),b=null,g=[y,x];Q.length===3&&(b=A("c",Q[2].dataType,Q[2].dims.length),g.push(b));let l=C("output",Q[0].dataType,F.length);g.push(l);let _=[{name:"num_tile_n",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"},{name:"alpha",type:"f32"},{name:"beta",type:"f32"}],a="",r="";J.transA&&J.transB?(r=`
var col = tile_row_start + local_id.x;
var row = k_start + local_id.y;
if (col < uniforms.M && row < uniforms.K) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = k_start + local_id.x;
row = tile_col_start + local_id.y;
if (col < uniforms.K && row < uniforms.N) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
} else {
tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
}
`,a="value += tile_a[k][local_id.y] * tile_b[local_id.x][k];"):J.transA&&!J.transB?(r=`
var col = tile_row_start + local_id.x;
var row = k_start + local_id.y;
if (col < uniforms.M && row < uniforms.K) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.M + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = tile_col_start + local_id.x;
row = k_start + local_id.y;
if (col < uniforms.N && row < uniforms.K) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
} else {
tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
}
`,a="value += tile_a[k][local_id.y] * tile_b[k][local_id.x];"):!J.transA&&J.transB?(r=`
var col = k_start + local_id.x;
var row = tile_row_start + local_id.y;
if (col < uniforms.K && row < uniforms.M) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = k_start + local_id.x;
row = tile_col_start + local_id.y;
if (col < uniforms.K && row < uniforms.N) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.K + col];
} else {
tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
}
`,a="value += tile_a[local_id.y][k] * tile_b[local_id.x][k];"):!J.transA&&!J.transB&&(r=`
var col = k_start + local_id.x;
var row = tile_row_start + local_id.y;
if (col < uniforms.K && row < uniforms.M) {
tile_a[local_id.y][local_id.x] = a[row * uniforms.K + col];
} else {
tile_a[local_id.y][local_id.x] = ${y.type.value}(0);
}
col = tile_col_start + local_id.x;
row = k_start + local_id.y;
if (col < uniforms.N && row < uniforms.K) {
tile_b[local_id.y][local_id.x] = b[row * uniforms.N + col];
} else {
tile_b[local_id.y][local_id.x] = ${x.type.value}(0);
}
`,a="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let f0=J.alpha===1?"":"value *= uniforms.alpha;";return`
${T.registerUniforms(_).declareVariables(...g)}
var<workgroup> tile_a: array<array<${y.type.storage}, ${D}>, ${D}>;
var<workgroup> tile_b: array<array<${x.type.storage}, ${D}>, ${D}>;
${T.mainStart([D,D,1])}
let tile_col_start = (workgroup_index % uniforms.num_tile_n) * ${D};
let tile_row_start = (workgroup_index / uniforms.num_tile_n) * ${D};
let num_tiles = (uniforms.K - 1) / ${D} + 1;
var k_start = 0u;
var value = ${l.type.value}(0);
for (var t: u32 = 0u; t < num_tiles; t++) {
${r}
k_start = k_start + ${D};
workgroupBarrier();
for (var k: u32 = 0u; k < ${D}; k++) {
${a}
}
workgroupBarrier();
}
${f0}
let m = tile_row_start + local_id.y;
let n = tile_col_start + local_id.x;
${b!=null?`let cOffset = ${b.broadcastedIndicesToOffset("vec2(m, n)",l)}; value += ${l.type.value}(uniforms.beta) * ${b.getByOffset("cOffset")};`:""}
if (m < uniforms.M && n < uniforms.N) {
output[m * uniforms.N + n] = value;
}
}`};return P?{name:"GemmShared",shaderCache:{hint:`${J.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:F,dataType:Q[0].dataType}],dispatchGroup:{x:V*O},programUniforms:I}),getShaderSource:E}:{name:"Gemm",shaderCache:{hint:`${J.cacheKey}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:F,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:I}),getShaderSource:w}},Gy=(Q)=>{let{transA:J,transB:G,alpha:H,beta:K}=Q;return{transA:J,transB:G,alpha:H,beta:K,cacheKey:`${Q.transA};${Q.transB};${Q.alpha===1}`}},Uy=(Q,J)=>{T$(Q.inputs),Q.compute(v$(Q.inputs,J))}}),On,Un,Pr,Or,I$,S$,$$,A$,P$,O$,E$,C$,Hy,qy,jy=$(()=>{X(),ee(),ke(),ne(),[On,Un,Pr,Or]=[0,1,2,3],I$=(Q)=>{if(Q[0].dims.length!==4)throw Error("only 4-D tensor is supported.");if(Q[0].dims.length!==Q[1].dims.length)throw Error("input dimensions must be equal to grid dimensions");if(Q[0].dims.length-2!==Q[1].dims[Q[1].dims.length-1])throw Error(`last dimension of grid must be equal to ${Q[0].dims.length-2}`);if(Q[0].dims[0]!==Q[1].dims[0])throw Error("grid batch size must match input batch size")},S$=`
fn gs_get_cubic_coeffs(x: f32) -> vec4<f32> {
let cubic_alpha = -0.75f;
let x_abs = abs(x);
var coeffs: vec4<f32>;
coeffs[0] = (((cubic_alpha * (x_abs + 1) - 5 * cubic_alpha) * (x_abs + 1) + 8 * cubic_alpha) * (x_abs + 1) - 4 * cubic_alpha);
coeffs[1] = (((cubic_alpha + 2) * x_abs - (cubic_alpha + 3)) * x_abs * x_abs + 1);
coeffs[2] = (((cubic_alpha + 2) * (1 - x_abs) - (cubic_alpha + 3)) * (1 - x_abs) * (1 - x_abs) + 1);
coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha);
return coeffs;
}
`,$$=(Q)=>`
fn gs_bicubic_interpolate(p: mat4x4<${Q}>, x: f32, y: f32) -> ${Q} {
var v: vec4<f32>;
var coeffs = gs_get_cubic_coeffs(x);
for (var i = 0; i < 4; i++) {
v[i] = coeffs[0] * p[i][0] + coeffs[1] * p[i][1] + coeffs[2] * p[i][2] + coeffs[3] * p[i][3];
}
coeffs = gs_get_cubic_coeffs(y);
let pixel = ${Q}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]);
return pixel;
}
`,A$=(Q)=>`
fn gs_denormalize(n: f32, length: i32) -> f32 {
${Q.alignCorners===0?`
// alignCorners: false => [-1, 1] to [-0.5, length - 0.5]
return ((n + 1.0) * f32(length) - 1.0) / 2.0;
`:`
// alignCorners: true => [-1, 1] to [0, length - 1]
return (n + 1.0) / 2.0 * (f32(length - 1));
`}
}
`,P$=(Q)=>`
${Q.paddingMode==="reflection"?`
fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 {
var dx = 0.0;
var fx = f32(x);
let range = x_max - x_min;
if (fx < x_min) {
dx = x_min - fx;
let n = u32(dx / range);
let r = dx - f32(n) * range;
if (n % 2 == 0) {
fx = x_min + r;
} else {
fx = x_max - r;
}
} else if (fx > x_max) {
dx = fx - x_max;
let n = u32(dx / range);
let r = dx - f32(n) * range;
if (n % 2 == 0) {
fx = x_max - r;
} else {
fx = x_min + r;
}
}
return u32(fx);
}`:""}
`,O$=(Q,J,G)=>`
fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4<f32>) -> ${J} {
var pixel = ${J}(0);
var indices = vec4<u32>(0);
indices[${On}] = batch;
indices[${Un}] = channel;`+(()=>{switch(G.paddingMode){case"zeros":return`
if (r >= 0 && r < H && c >=0 && c < W) {
indices[${Pr}] = u32(r);
indices[${Or}] = u32(c);
} else {
return ${J}(0);
}
`;case"border":return`
indices[${Pr}] = u32(clamp(r, 0, H - 1));
indices[${Or}] = u32(clamp(c, 0, W - 1));
`;case"reflection":return`
indices[${Pr}] = gs_reflect(r, border[1], border[3]);
indices[${Or}] = gs_reflect(c, border[0], border[2]);
`;default:throw Error(`padding mode ${G.paddingMode} is not supported`)}})()+`
return ${Q.getByIndices("indices")};
}
`,E$=(Q,J,G)=>(()=>{switch(G.mode){case"nearest":return`
let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${On}], indices[${Un}], border);
`;case"bilinear":return`
let x1 = i32(floor(x));
let y1 = i32(floor(y));
let x2 = x1 + 1;
let y2 = y1 + 1;
let p11 = pixel_at_grid(y1, x1, H_in, W_in, indices[${On}], indices[${Un}], border);
let p12 = pixel_at_grid(y1, x2, H_in, W_in, indices[${On}], indices[${Un}], border);
let p21 = pixel_at_grid(y2, x1, H_in, W_in, indices[${On}], indices[${Un}], border);
let p22 = pixel_at_grid(y2, x2, H_in, W_in, indices[${On}], indices[${Un}], border);
let dx2 = ${J}(f32(x2) - x);
let dx1 = ${J}(x - f32(x1));
let dy2 = ${J}(f32(y2) - y);
let dy1 = ${J}(y - f32(y1));
let result = dy2 * (dx2 * p11 + dx1 * p12) + dy1 * (dx2 * p21 + dx1 * p22);
`;case"bicubic":return`
let x0 = i32(floor(x)) - 1;
let y0 = i32(floor(y)) - 1;
var p: mat4x4<${J}>;
for (var h = 0; h < 4; h++) {
for (var w = 0; w < 4; w++) {
p[h][w] = pixel_at_grid(h + y0, w + x0, H_in, W_in, indices[${On}], indices[${Un}], border);
}
}
let dx = x - f32(x0 + 1);
let dy = y - f32(y0 + 1);
let result = gs_bicubic_interpolate(p, dx, dy);
`;default:throw Error(`mode ${G.mode} is not supported`)}})()+`${Q.setByOffset("global_idx","result")}`,C$=(Q,J)=>{let G=A("x",Q[0].dataType,Q[0].dims.length),H=[Q[1].dims[0],Q[1].dims[1],Q[1].dims[2]],K=A("grid",Q[1].dataType,H.length,2),z=[Q[0].dims[0],Q[0].dims[1],Q[1].dims[1],Q[1].dims[2]];J.format==="NHWC"&&(z=[Q[0].dims[0],Q[1].dims[1],Q[1].dims[2],Q[0].dims[3]],[On,Un,Pr,Or]=[0,3,1,2]);let q=C("output",Q[0].dataType,z.length),F=G.type.value,D=S.size(z),V=[{type:12,data:D},...k(Q[0].dims,H,z)],O=(P)=>`
${P.registerUniform("output_size","u32").declareVariables(G,K,q)}
${S$}
${$$(F)}
${A$(J)}
${P$(J)}
${O$(G,F,J)}
${P.mainStart()}
${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let H_in = i32(uniforms.x_shape[${Pr}]);
let W_in = i32(uniforms.x_shape[${Or}]);
${J.alignCorners===0?`
let x_min = -0.5;
let x_max = f32(W_in) - 0.5;
let y_min = -0.5;
let y_max = f32(H_in) - 0.5;
`:`
let x_min = 0.0;
let x_max = f32(W_in) - 1.0;
let y_min = 0.0;
let y_max = f32(H_in) - 1.0;
`};
let border = vec4<f32>(x_min, y_min, x_max, y_max);
let indices = ${q.offsetToIndices("global_idx")};
var grid_indices = vec3<u32>(indices[${On}], indices[${Pr}], indices[${Or}]);
let nxy = ${K.getByIndices("grid_indices")};
var x = gs_denormalize(f32(nxy[0]), W_in);
var y = gs_denormalize(f32(nxy[1]), H_in);
${E$(q,F,J)}
}`;return{name:"GridSample",shaderCache:{hint:`${J.cacheKey}`,inputDependencies:["type","type"]},getRunData:(P)=>{let N=S.size(z);return{outputs:[{dims:z,dataType:P[0].dataType}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:V}},getShaderSource:O}},Hy=(Q,J)=>{I$(Q.inputs),Q.compute(C$(Q.inputs,J))},qy=(Q)=>Z({alignCorners:Q.align_corners,mode:Q.mode,paddingMode:Q.padding_mode,format:Q.format})}),at,L$,Xy,Ky,R$,ao,Zy,ml=$(()=>{X(),ee(),ke(),Mi(),Ui(),ne(),Pn(),at=(Q,J)=>Q.length>J&&Q[J].dims.length>0?Q[J]:void 0,L$=(Q,J)=>{let G=Q[0],H=at(Q,1),K=at(Q,2),z=at(Q,3),q=at(Q,4),F=at(Q,5),D=at(Q,6),V=at(Q,7);if(G.dims.length!==3&&G.dims.length!==5)throw Error("Input query is expected to have 3 or 5 dimensions");let O=G.dims[0],P=G.dims[1],N=G.dims.length===3?G.dims[2]:J.numHeads*G.dims[4],I=P,R=0,w=0,E=Math.floor(N/J.numHeads);if(D&&V&&S.size(D.dims)&&S.size(V.dims)){if(D.dims.length!==4)throw Error('Input "past_key" is expected to have 4 dimensions');if(D.dims[0]!==O||D.dims[1]!==J.numHeads||D.dims[3]!==E)throw Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(V.dims[0]!==O||V.dims[1]!==J.numHeads||V.dims[3]!==E)throw Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(D.dims[2]!==V.dims[2])throw Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(V.dims.length!==4)throw Error('Input "past_value" is expected to have 4 dimensions');R=D.dims[2],w=D.dims[2]}else if(D&&S.size(D.dims)||V&&S.size(V.dims))throw Error('Input "past_key" and "past_value" shall be both present or both absent');let T;if(H&&S.size(H.dims)>0){if(G.dims.length!==3)throw Error('Input "query" is expected to have 3 dimensions when key is given');if(H.dims.length<3||H.dims.length>5)throw Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(G.dims[0]!==H.dims[0])throw Error('Input "query" and "key" shall have same dim 0 (batch size)');if(H.dims.length===3){if(H.dims[2]!==G.dims[2])throw Error('Input "query" and "key" shall have same dim 2 (hidden_size)');T=2,I=H.dims[1]}else if(H.dims.length===5){if(H.dims[2]!==J.numHeads||H.dims[3]!==2||H.dims[4]!==E)throw Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(K)throw Error('Expect "value" be none when "key" has packed kv format.');T=5,I=H.dims[1]}else{if(H.dims[1]!==J.numHeads||H.dims[3]!==E)throw Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');T=0,I=H.dims[2]}}else{if(G.dims.length!==5)throw Error('Input "query" is expected to have 5 dimensions when key is empty');if(G.dims[2]!==J.numHeads||G.dims[3]!==3)throw Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');T=3}if(z&&S.size(z.dims)>0){if(z.dims.length!==1)throw Error('Input "bias" is expected to have 1 dimension');if(H&&H.dims.length===5&&H.dims[3]===2)throw Error("bias is not allowed for packed kv.")}let y=R+I,x=0;if(q&&S.size(q.dims)>0){x=8;let _=q.dims;throw _.length===1?_[0]===O?x=1:_[0]===3*O+2&&(x=3):_.length===2&&_[0]===O&&_[1]===y&&(x=5),x===8?Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):Error("Mask not supported")}let b=!1,g=N;if(K&&S.size(K.dims)>0){if(K.dims.length!==3&&K.dims.length!==4)throw Error('Input "value" is expected to have 3 or 4 dimensions');if(G.dims[0]!==K.dims[0])throw Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(K.dims.length===3){if(I!==K.dims[1])throw Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');g=K.dims[2]}else{if(I!==K.dims[2])throw Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');g=K.dims[1]*K.dims[3],b=!0}}let l=!1;if(q&&S.size(q.dims)>0)throw Error("Key padding mask is not supported");if(F&&S.size(F.dims)>0){if(F.dims.length!==4)throw Error('Input "attention_bias" is expected to have 4 dimensions');if(F.dims[0]!==O||F.dims[1]!==J.numHeads||F.dims[2]!==P||F.dims[3]!==y)throw Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:O,sequenceLength:P,pastSequenceLength:R,kvSequenceLength:I,totalSequenceLength:y,maxSequenceLength:w,inputHiddenSize:0,hiddenSize:N,vHiddenSize:g,headSize:E,vHeadSize:Math.floor(g/J.numHeads),numHeads:J.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:J.maskFilterValue,maskType:x,scale:J.scale,broadcastResPosBias:l,passPastInKv:b,qkvFormat:T}},Xy=(Q)=>Z({...Q}),Ky=Z({perm:[0,2,1,3]}),R$=(Q,J,G,H,K,z,q)=>{let F=[H,K,z],D=S.size(F),V=[{type:12,data:D},{type:12,data:q},{type:12,data:z}],O=(P)=>{let N=C("qkv_with_bias",J.dataType,F),I=A("qkv",J.dataType,F),R=A("bias",G.dataType,F),w=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
${P.registerUniforms(w).declareVariables(I,R,N)}
${P.mainStart()}
${P.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 Q.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:F,dataType:J.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:V}),getShaderSource:O},{inputs:[J,G],outputs:[-1]})[0]},ao=(Q,J,G,H,K,z,q,F)=>{let D=z;if(q&&S.size(q.dims)>0){if(H===1)throw Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return D=R$(Q,z,q,J,H,G*K,F),D=D.reshape([J,H,G,K]),G===1||H===1?D:Q.compute(Ge(D,Ky.perm),{inputs:[D],outputs:[-1]})[0]}else return z.dims.length===3&&(D=z.reshape([J,H,G,K])),G===1||H===1?D:Q.compute(Ge(D,Ky.perm),{inputs:[D],outputs:[-1]})[0]},Zy=(Q,J)=>{let G=L$(Q.inputs,J),H=Q.inputs[0],K=at(Q.inputs,1),z=at(Q.inputs,2),q=at(Q.inputs,3),F=at(Q.inputs,4),D=at(Q.inputs,5),V=at(Q.inputs,6),O=at(Q.inputs,7);if(H.dims.length===5)throw Error("Packed QKV is not implemented");if(K?.dims.length===5)throw Error("Packed KV is not implemented");let P=K&&z&&K.dims.length===4&&z.dims.length===4,N=ao(Q,G.batchSize,G.numHeads,G.sequenceLength,G.headSize,H,q,0);if(P)return Ar(Q,N,K,z,F,void 0,V,O,D,G);if(!K||!z)throw Error("key and value must be provided");let I=ao(Q,G.batchSize,G.numHeads,G.kvSequenceLength,G.headSize,K,q,G.hiddenSize),R=ao(Q,G.batchSize,G.numHeads,G.kvSequenceLength,G.vHeadSize,z,q,2*G.hiddenSize);Ar(Q,N,I,R,F,void 0,V,O,D,G)}}),N$,z$,M$,B$,gl,Jy,Qy,bl=$(()=>{X(),ee(),ke(),ne(),N$=(Q)=>{if(!Q||Q.length<1)throw Error("too few inputs")},z$=(Q,J)=>{let G=[],H=J.numOutputs;return Q[1].dims[0]>0&&(Q[1].getBigInt64Array().forEach((K)=>G.push(Number(K))),H=G.length),Z({numOutputs:H,axis:J.axis,splitSizes:G})},M$=(Q)=>`
fn calculateOutputIndex(index: u32) -> u32 {
for (var i: u32 = 0u; i < ${Q}u; i += 1u ) {
if (index < ${B("uniforms.size_in_split_axis","i",Q)}) {
return i;
}
}
return ${Q}u;
}`,B$=(Q)=>{let J=Q.length,G=[];for(let H=0;H<J;++H){let K=Q[H].setByIndices("indices","input[global_idx]");J===1?G.push(K):H===0?G.push(`if (output_number == ${H}u) { ${K} }`):H===J-1?G.push(`else { ${K} }`):G.push(`else if (output_number == ${H}) { ${K} }`)}return`
fn writeBufferData(output_number: u32, indices: ${Q[0].type.indices}, global_idx: u32) {
${G.join(`
`)}
}`},gl=(Q,J)=>{let G=Q[0].dims,H=S.size(G),K=Q[0].dataType,z=S.normalizeAxis(J.axis,G.length),q=Array(J.numOutputs),F=A("input",K,G.length),D=Array(J.numOutputs),V=[],O=[],P=0,N=[{type:12,data:H}];for(let R=0;R<J.numOutputs;R++){P+=J.splitSizes[R],D[R]=P;let w=G.slice();w[z]=J.splitSizes[R],O.push(w),q[R]=C(`output${R}`,K,w.length),V.push({dims:O[R],dataType:Q[0].dataType})}N.push({type:12,data:D},...k(G,...O));let I=(R)=>`
${R.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",D.length).declareVariables(F,...q)}
${M$(D.length)}
${B$(q)}
${R.mainStart()}
${R.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")}
var indices = ${F.offsetToIndices("global_idx")};
var index = ${F.indicesGet("indices",z)};
let output_number = calculateOutputIndex(index);
if (output_number != 0) {
index -= ${B("uniforms.size_in_split_axis","output_number - 1u",D.length)};
${F.indicesSet("indices",z,"index")};
}
writeBufferData(output_number, indices, global_idx);
}`;return{name:"Split",shaderCache:{hint:J.cacheKey,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:V,dispatchGroup:{x:Math.ceil(H/64)},programUniforms:N})}},Jy=(Q,J)=>{N$(Q.inputs);let G=Q.inputs.length===1?J:z$(Q.inputs,J);Q.compute(gl(Q.inputs,G),{inputs:[0]})},Qy=(Q)=>{let{axis:J,splitSizes:G}=Q,H=Q.numOutputs<0?G.length:Q.numOutputs;if(H!==G.length)throw Error("numOutputs and splitSizes length must be equal");return Z({axis:J,numOutputs:H,splitSizes:G})}}),F$,Yi,Yy,yl=$(()=>{X(),ee(),ke(),ne(),F$=(Q,J)=>{let[G,H,K,z]=Q,{numHeads:q,rotaryEmbeddingDim:F}=J;if(G.dims.length!==3&&G.dims.length!==4)throw Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${G.dims.length}`);if(!S.areEqual(H.dims,[])&&!S.areEqual(H.dims,[1])&&H.dims.length!==2)throw Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${H.dims.length}`);if(K.dims.length!==2)throw Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${K.dims.length}`);if(z.dims.length!==2)throw Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${z.dims.length}`);if(!S.areEqual(K.dims,z.dims))throw Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(F>0&&q===0)throw Error("num_heads must be provided if rotary_embedding_dim is specified");let D=G.dims[0],V=G.dims[G.dims.length-2],O=K.dims[0],P=S.sizeFromDimension(G.dims,1)/V,N=F===0?K.dims[1]*2:P/q;if(F>N)throw Error("rotary_embedding_dim must be less than or equal to head_size");if(H.dims.length===2){if(D!==H.dims[0])throw Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${H.dims[0]}`);if(V!==H.dims[1])throw Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${H.dims[1]}`)}if(V>O)throw Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(N/2!==K.dims[1]&&F/2!==K.dims[1])throw Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${K.dims[1]}`)},Yi=(Q,J)=>{let{interleaved:G,numHeads:H,rotaryEmbeddingDim:K,scale:z}=J,q=Q[0].dims[0],F=S.sizeFromDimension(Q[0].dims,1),D=Q[0].dims[Q[0].dims.length-2],V=F/D,O=Q[2].dims[1],P=K===0?O*2:V/H,N=[q,D,V/P,P-O],I=S.computeStrides(N),R=[{type:1,data:z},{type:12,data:N},{type:12,data:I},...Q[0].dims.length===3?[{type:12,data:[F,V,P,1]}]:[],...Q[0].dims.length===4?[{type:12,data:[F,P,D*P,1]}]:[],...k(Q[0].dims,Q[1].dims,Q[2].dims,Q[3].dims,Q[0].dims)],w=(E)=>{let T=A("input",Q[0].dataType,Q[0].dims.length),y=A("position_ids",Q[1].dataType,Q[1].dims.length),x=A("cos_cache",Q[2].dataType,Q[2].dims.length),b=A("sin_cache",Q[3].dataType,Q[3].dims.length),g=C("output",Q[0].dataType,Q[0].dims.length);return E.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:N.length},{name:"global_strides",type:"u32",length:I.length},{name:"input_output_strides",type:"u32",length:I.length}]),`
${E.declareVariables(T,y,x,b,g)}
${E.mainStart(ur)}
let half_rotary_emb_dim = uniforms.${x.name}_shape[1];
let bsnh = global_idx / uniforms.global_strides % uniforms.global_shape;
let size = uniforms.global_shape[0] * uniforms.global_strides[0];
${E.guardAgainstOutOfBoundsWorkgroupSizes("size")}
if (bsnh[3] < half_rotary_emb_dim) {
let position_ids_idx =
${y.broadcastedIndicesToOffset("bsnh.xy",C("",y.type.tensor,2))};
let position_id =
u32(${y.getByOffset("position_ids_idx")}) + select(0, bsnh[1], position_ids_idx == 0);
let i = dot(bsnh, uniforms.input_output_strides) + select(0, bsnh[3], ${G});
let j = i + select(half_rotary_emb_dim, 1, ${G});
let re = ${T.getByOffset("i")} * ${x.get("position_id","bsnh[3]")} -
${T.getByOffset("j")} * ${b.get("position_id","bsnh[3]")};
${g.setByOffset("i","re")}
let im = ${T.getByOffset("i")} * ${b.get("position_id","bsnh[3]")} +
${T.getByOffset("j")} * ${x.get("position_id","bsnh[3]")};
${g.setByOffset("j","im")}
} else {
let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
${g.setByOffset("k",T.getByOffset("k"))}
}
}`};return{name:"RotaryEmbedding",shaderCache:{hint:Z({interleaved:G}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:Q[0].dims,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(S.size(N)/ur)},programUniforms:R})}},Yy=(Q,J)=>{F$(Q.inputs,J),Q.compute(Yi(Q.inputs,J))}}),V$,G$,e_,U$,t_,n_=$(()=>{ke(),X(),Ui(),ml(),bl(),Pn(),yl(),ne(),V$=(Q,J)=>{if(J.doRotary&&Q.length<=7)throw Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let G=Q[0],H=Q[1],K=Q[2],z=Q[3],q=Q[4];if(J.doRotary!==0&&Q.length<=7)throw Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(J.localWindowSize!==-1)throw Error("Local attention is not supported");if(J.softcap!==0)throw Error("Softcap is not supported");if(J.rotaryInterleaved!==0)throw Error("Rotary interleaved is not supported");if(J.smoothSoftmax)throw Error("Smooth softmax is not supported");if(G.dims.length!==3&&G.dims.length!==5)throw Error("Input query is expected to have 3 or 5 dimensions");let F=!1,D=G.dims[0],V=G.dims[1],O=G.dims.length===3?F?G.dims[2]/3:G.dims[2]:J.numHeads*G.dims[4],P=V,N=0,I=!H||H.dims.length===0,R=Math.floor(I?O/(J.numHeads+2*J.kvNumHeads):O/J.numHeads);I&&(O=R*J.numHeads);let w=z&&z.dims.length!==0,E=q&&q.dims.length!==0;if(w&&z.dims.length===4&&z.dims[0]===D&&z.dims[1]!==J.kvNumHeads&&z.dims[2]===J.kvNumHeads&&z.dims[3]===R)throw Error("BSNH pastKey/pastValue is not supported");if(w&&E){if(z.dims.length!==4)throw Error('Input "past_key" is expected to have 4 dimensions');if(q.dims.length!==4)throw Error('Input "past_value" is expected to have 4 dimensions');N=z.dims[2]}else if(w||E)throw Error('Input "past_key" and "past_value" shall be both present or both absent');let T=1;if(H&&H.dims.length>0){if(G.dims.length!==3)throw Error('Input "query" is expected to have 3 dimensions when key is given');if(H.dims.length<3||H.dims.length>5)throw Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(G.dims[0]!==H.dims[0])throw Error('Input "query" and "key" shall have same dim 0 (batch size)');if(H.dims.length===3){if(G.dims[2]%H.dims[2]!==0)throw Error('Dimension 2 of "query" should be a multiple of "key"');P=H.dims[1]}else if(H.dims.length===5){if(H.dims[2]!==J.numHeads||H.dims[3]!==2||H.dims[4]!==R)throw Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(K)throw Error('Expect "value" be none when "key" has packed kv format.');P=H.dims[1]}else{if(H.dims[1]!==J.numHeads||H.dims[3]!==R)throw Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');P=H.dims[2]}}else{if(G.dims.length!==3&&G.dims.length!==5)throw Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(G.dims.length===5&&(G.dims[2]!==J.numHeads||G.dims[3]!==3))throw Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');T=3}let y=0,x=!1,b=J.kvNumHeads?R*J.kvNumHeads:O;if(K&&K.dims.length>0){if(K.dims.length!==3&&K.dims.length!==4)throw Error('Input "value" is expected to have 3 or 4 dimensions');if(G.dims[0]!==K.dims[0])throw Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(K.dims.length===3){if(P!==K.dims[1])throw Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');b=K.dims[2]}else{if(P!==K.dims[2])throw Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');b=K.dims[1]*K.dims[3],x=!0}}let g=Q.length>4?Q[5]:void 0;if(g){if(g.dims.length===0)throw Error("seqlens_k must be at least 1D, got scalar.");let l=g.dims.reduce((_,a)=>_*a,1);if(l!==D)throw Error(`seqlens_k must have batch_size (${D}) elements, got ${l}.`);for(let _=0;_<g.dims.length;_++)if(g.dims[_]!==1&&g.dims[_]!==D)throw Error(`seqlens_k has unexpected shape. Each dimension must be 1 or batch_size (${D}), got dims[${_}] = ${g.dims[_]}.`)}return{batchSize:D,sequenceLength:V,pastSequenceLength:N,kvSequenceLength:P,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:O,vHiddenSize:b,headSize:R,vHeadSize:Math.floor(b/J.kvNumHeads),numHeads:J.numHeads,kvNumHeads:J.kvNumHeads,nReps:J.numHeads/J.kvNumHeads,pastPresentShareBuffer:!1,maskType:y,scale:J.scale,broadcastResPosBias:!1,passPastInKv:x,qkvFormat:T}},G$=Z({perm:[0,2,1,3]}),e_=(Q,J,G)=>{let H=J,K=G.kvNumHeads;return J.dims.length===3&&G.kvSequenceLength!==0&&(H=J.reshape([G.batchSize,G.kvSequenceLength,K,G.headSize]),H=Q.compute(Ge(H,G$.perm),{inputs:[H],outputs:[-1]})[0]),H},U$=(Q,J,G,H)=>{let K=7,z=["type","type"],q=[Q*J],F=Q*J,D=[{type:12,data:F},{type:12,data:J},{type:12,data:Q}],V=(O)=>{let P=A("seq_lens",G.dataType,G.dims),N=A("total_seq_lens",H.dataType,H.dims),I=C("pos_ids",K,q),R=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
${O.registerUniforms(R).declareVariables(P,N,I)}
${O.mainStart()}
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let total_sequence_length = u32(${N.getByOffset("0")});
let is_subsequent_prompt = uniforms.sequence_length > 1 && uniforms.sequence_length != total_sequence_length;
let is_first_prompt = !is_subsequent_prompt && uniforms.sequence_length == total_sequence_length;
let batch_idx = global_idx / uniforms.sequence_length;
let sequence_idx = i32(global_idx % uniforms.sequence_length);
var pos_id: i32 = 0;
let seqlen = ${P.getByOffset("batch_idx")};
let total_seqlen = seqlen + 1;
if (is_first_prompt) {
if (sequence_idx < total_seqlen) {
pos_id = sequence_idx;
} else {
pos_id = 1;
}
${I.setByOffset("global_idx","pos_id")}
} else if (is_subsequent_prompt) {
let past_seqlen = total_seqlen - i32(uniforms.sequence_length);
if (past_seqlen + sequence_idx < total_seqlen) {
pos_id = past_seqlen + sequence_idx;
} else {
pos_id = 1;
}
${I.setByOffset("global_idx","pos_id")}
} else if (global_idx < uniforms.batch_size) {
${I.setByOffset("global_idx","seqlen")}
};
}
`};return{name:"GeneratePositionIds",shaderCache:{hint:`${Q};${J}`,inputDependencies:z},getRunData:()=>({outputs:[{dims:q,dataType:K}],dispatchGroup:{x:Math.ceil(F/64)},programUniforms:D}),getShaderSource:V}},t_=(Q,J)=>{let G=V$(Q.inputs,J);if(Q.inputs[0].dims.length===5)throw Error("Packed QKV is not implemented");if(Q.inputs[1]?.dims.length===5)throw Error("Packed KV is not implemented");let H=Q.inputs[0],K=Q.inputs[1]&&Q.inputs[1].dims.length>0?Q.inputs[1]:void 0,z=Q.inputs[2]&&Q.inputs[2].dims.length>0?Q.inputs[2]:void 0,q=Q.inputs[3]&&Q.inputs[3].dims.length!==0?Q.inputs[3]:void 0,F=Q.inputs[4]&&Q.inputs[4].dims.length!==0?Q.inputs[4]:void 0,D=Q.inputs.length>4?Q.inputs[5]:void 0,V=Q.inputs.length>5?Q.inputs[6]:void 0,O=G.kvNumHeads?G.kvNumHeads:G.numHeads,P=Z({axis:2,numOutputs:3,splitSizes:[G.numHeads*G.headSize,O*G.headSize,O*G.headSize]}),[N,I,R]=!K&&!z?Q.compute(gl([H],P),{inputs:[H],outputs:[-1,-1,-1]}):[H,K,z],w,E;if(J.doRotary){let b=Q.compute(U$(G.batchSize,G.sequenceLength,D,V),{inputs:[D,V],outputs:[-1]})[0],g=Q.inputs[7],l=Q.inputs[8],_=Z({interleaved:J.rotaryInterleaved!==0,numHeads:G.numHeads,rotaryEmbeddingDim:0,scale:J.scale}),a=[N,b,g,l],r=[-1];w=Q.compute(Yi(a,_),{inputs:a,outputs:r})[0],a.splice(0,1,I);let f0=Z({interleaved:J.rotaryInterleaved!==0,numHeads:G.kvNumHeads,rotaryEmbeddingDim:0,scale:J.scale});E=Q.compute(Yi(a,f0),{inputs:a,outputs:r})[0]}let T=ao(Q,G.batchSize,G.numHeads,G.sequenceLength,G.headSize,J.doRotary?w:N,void 0,0),y=e_(Q,J.doRotary?E:I,G),x=e_(Q,R,G);Ar(Q,T,y,x,void 0,void 0,q,F,void 0,G,D,V)}}),r_,W$,H$,o_,i_=$(()=>{X(),ee(),Pn(),ne(),r_=(Q,J,G,H,K,z,q,F)=>{let D=he(z),V=D===1?"f32":`vec${D}f`,O=D===1?"vec2f":`mat2x${D}f`,P=K*q,N=64;P===1&&(N=256);let I=[K,q,z/D],R=[K,q,2],w=["rank","type","type"],E=[];E.push(...k(I,R));let T=(y)=>{let x=A("x",J.dataType,3,D),b=A("scale",G.dataType,G.dims),g=A("bias",H.dataType,H.dims),l=C("output",1,3,2),_=[x,b,g,l];return`
var<workgroup> workgroup_shared : array<${O}, ${N}>;
const workgroup_size = ${N}u;
${y.declareVariables(..._)}
${y.mainStart(N)}
let batch = workgroup_index / uniforms.x_shape[1];
let channel = workgroup_index % uniforms.x_shape[1];
let hight = uniforms.x_shape[2];
// initialize workgroup memory
var sum = ${V}(0);
var squared_sum = ${V}(0);
for (var h = local_idx; h < hight; h += workgroup_size) {
let value = ${V}(${x.get("batch","channel","h")});
sum += value;
squared_sum += value * value;
}
workgroup_shared[local_idx] = ${O}(sum, squared_sum);
workgroupBarrier();
for (var currSize = workgroup_size >> 1; currSize > 0; currSize = currSize >> 1) {
if (local_idx < currSize) {
workgroup_shared[local_idx] = workgroup_shared[local_idx] + workgroup_shared[local_idx + currSize];
}
workgroupBarrier();
}
if (local_idx == 0) {
let sum_final = ${At("workgroup_shared[0][0]",D)} / f32(hight * ${D});
let squared_sum_final = ${At("workgroup_shared[0][1]",D)} / f32(hight * ${D});
let inv_std_dev = inverseSqrt(squared_sum_final - sum_final * sum_final + f32(${F}));
let channel_scale = inv_std_dev * f32(scale[channel]);
let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
output[workgroup_index] = vec2f(channel_scale, channel_shift);
}
}`};return Q.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${D};${F};${N}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:R,dataType:1}],dispatchGroup:{x:P},programUniforms:E}),getShaderSource:T},{inputs:[J,G,H],outputs:[-1]})[0]},W$=(Q,J,G)=>{let H=J[0].dims,K=H,z=2,q=H[0],F=H[1],D=S.sizeFromDimension(H,z),V=he(D),O=S.size(K)/V,P=r_(Q,J[0],J[1],J[2],q,D,F,G.epsilon),N=[q,F,D/V],I=[q,F],R=["type","none"],w=(E)=>{let T=A("x",J[0].dataType,N.length,V),y=A("scale_shift",1,I.length,2),x=C("output",J[0].dataType,N.length,V),b=[T,y,x];return`
${E.registerUniform("output_size","u32").declareVariables(...b)}
${E.mainStart()}
${E.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let outputIndices = ${x.offsetToIndices("global_idx")};
let batch = outputIndices[0];
let channel = outputIndices[1];
let scale_shift = ${y.getByIndices("vec2<u32>(batch, channel)")};
let value = ${T.getByOffset("global_idx")} * ${x.type.value}(scale_shift.x) + ${x.type.value}(scale_shift.y);
${x.setByOffset("global_idx","value")};
}`};Q.compute({name:"InstanceNormalization",shaderCache:{hint:`${V}`,inputDependencies:R},getRunData:()=>({outputs:[{dims:K,dataType:J[0].dataType}],dispatchGroup:{x:Math.ceil(O/64)},programUniforms:[{type:12,data:O},...k(N,I,N)]}),getShaderSource:w},{inputs:[J[0],P]})},H$=(Q,J,G)=>{let H=J[0].dims,K=H,z=H[0],q=H[H.length-1],F=S.sizeFromDimension(H,1)/q,D=he(q),V=S.size(K)/D,O=[{type:12,data:F},{type:12,data:Math.floor(q/D)}],P=["type","type"],N=!1,I=[0,H.length-1];for(let T=0;T<H.length-2;T++)N=N||H[T+1]!==1,I.push(T+1);N=N&&H[H.length-1]!==1;let R=N?Q.compute(Ge(Q.inputs[0],I),{inputs:[Q.inputs[0]],outputs:[-1]})[0]:Q.inputs[0].reshape(Array.from({length:H.length},(T,y)=>H[I[y]])),w=r_(Q,R,J[1],J[2],z,F,q,G.epsilon),E=(T)=>{let y=ve(J[0].dataType),x=D===1?"vec2f":`mat${D}x2f`,b=(_)=>{let a=_===0?"x":"y",r=D===1?"f32":`vec${D}f`;switch(D){case 1:return`${y}(${r}(scale.${a}))`;case 2:return`vec2<${y}>(${r}(scale[0].${a}, scale[1].${a}))`;case 4:return`vec4<${y}>(${r}(scale[0].${a}, scale[1].${a}, scale[2].${a}, scale[3].${a}))`;default:throw Error(`Not supported compoents ${D}`)}},g=A("input",J[0].dataType,J[0].dims,D),l=C("output",J[0].dataType,K,D);return`
@group(0) @binding(0) var<storage, read> input : array<${g.type.storage}>;
@group(0) @binding(1) var<storage, read> scale_input : array<${x}>;
@group(0) @binding(2) var<storage, read_write> output : array<${l.type.storage}>;
struct Uniforms {H: u32, C : u32};
@group(0) @binding(3) var<uniform> uniforms: Uniforms;
${T.mainStart()}
let current_image_number = global_idx / (uniforms.C * uniforms.H);
let current_channel_number = global_idx % uniforms.C;
let scale_offset = current_image_number * uniforms.C + current_channel_number;
let scale = scale_input[scale_offset];
output[global_idx] = fma(input[global_idx], ${b(0)}, ${b(1)});
}`};Q.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${D}`,inputDependencies:P},getRunData:()=>({outputs:[{dims:K,dataType:J[0].dataType}],dispatchGroup:{x:Math.ceil(V/64)},programUniforms:O}),getShaderSource:E},{inputs:[J[0],w]})},o_=(Q,J)=>{J.format==="NHWC"?H$(Q,Q.inputs,J):W$(Q,Q.inputs,J)}}),q$,j$,a_,s_=$(()=>{X(),ee(),ne(),q$=(Q)=>{if(!Q||Q.length<2)throw Error("layerNorm requires at least 2 inputs.")},j$=(Q,J,G)=>{let H=J.simplified,K=Q[0].dims,z=Q[1],q=!H&&Q[2],F=K,D=S.normalizeAxis(J.axis,K.length),V=S.sizeToDimension(K,D),O=S.sizeFromDimension(K,D),P=S.size(z.dims),N=q?S.size(q.dims):0;if(P!==O||q&&N!==O)throw Error(`Size of X.shape()[axis:] == ${O}.
Size of scale and bias (if provided) must match this.
Got scale size of ${P} and bias size of ${N}`);let I=[];for(let g=0;g<K.length;++g)g<D?I.push(K[g]):I.push(1);let R=he(O),w=["type","type"],E=[{type:12,data:V},{type:1,data:O},{type:12,data:Math.floor(O/R)},{type:1,data:J.epsilon}];q&&w.push("type");let T=G>1,y=G>2,x=(g)=>{let l=ve(Q[0].dataType),_=[A("x",Q[0].dataType,Q[0].dims,R),A("scale",z.dataType,z.dims,R)];q&&_.push(A("bias",q.dataType,q.dims,R)),_.push(C("output",Q[0].dataType,F,R)),T&&_.push(C("mean_data_output",1,I)),y&&_.push(C("inv_std_output",1,I));let a=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return`
${g.registerUniforms(a).declareVariables(..._)}
${g.mainStart()}
${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")}
let offset = global_idx * uniforms.norm_size_vectorized;
var mean_vector = ${el("f32",R)};
var mean_square_vector = ${el("f32",R)};
for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) {
let value = ${lr(l,R,"x[h + offset]")};
mean_vector += value;
mean_square_vector += value * value;
}
let mean = ${At("mean_vector",R)} / uniforms.norm_size;
let inv_std_dev = inverseSqrt(${At("mean_square_vector",R)} / uniforms.norm_size ${H?"":"- mean * mean"} + uniforms.epsilon);
for (var j: u32 = 0; j < uniforms.norm_size_vectorized; j++) {
let f32input = ${lr(l,R,"x[j + offset]")};
let f32scale = ${lr(l,R,"scale[j]")};
output[j + offset] = ${_[0].type.value}((f32input ${H?"":"- mean"}) * inv_std_dev * f32scale
${q?`+ ${lr(l,R,"bias[j]")}`:""}
);
}
${T?"mean_data_output[global_idx] = mean":""};
${y?"inv_std_output[global_idx] = inv_std_dev":""};
}`},b=[{dims:F,dataType:Q[0].dataType}];return T&&b.push({dims:I,dataType:1}),y&&b.push({dims:I,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${R};${G};${H}`,inputDependencies:w},getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(V/64)},programUniforms:E}),getShaderSource:x}},a_=(Q,J)=>{q$(Q.inputs),Q.compute(j$(Q.inputs,J,Q.outputCount))}}),K$,u_,l_=$(()=>{ee(),Xi(),Zi(),K$=(Q)=>{if(!Q||Q.length!==2)throw Error("MatMul requires 2 inputs.");if(Q[0].dims[Q[0].dims.length-1]!==Q[1].dims[Q[1].dims.length-2])throw Error("shared dimension does not match.")},u_=(Q)=>{K$(Q.inputs);let J=bn.calcShape(Q.inputs[0].dims,Q.inputs[1].dims,!0);if(!J)throw Error("Can't use matmul on the given tensors");let G=J[J.length-1],H=Q.inputs[0].dims[Q.inputs[0].dims.length-1];if(G<8&&H<8)Q.compute(Ki(Q.inputs,{activation:""},J));else{let K=J[J.length-2],z=S.size(Q.inputs[0].dims.slice(0,-2)),q=S.size(Q.inputs[1].dims.slice(0,-2));if(z!==1&&K===1&&q===1){let F=Q.inputs[0].reshape([1,z,H]),D=Q.inputs[1].reshape([1,H,G]),V=[1,z,G],O=[F,D];Q.compute(io(O,{activation:""},J,V),{inputs:O})}else Q.compute(io(Q.inputs,{activation:""},J))}}}),X$,Z$,J$,c_,d_,p_=$(()=>{X(),ee(),ke(),ne(),X$=(Q,J)=>{if(Q.length<3||Q.length>4)throw Error("MatMulNBits requires 3 or 4 inputs");let G=Q[0],H=G.dims.length;if(G.dims[H-1]!==J.k)throw Error("The last dim of input shape does not match the k value");let K=Math.floor((J.k+J.blockSize-1)/J.blockSize),z=J.blockSize/8*J.bits,q=Q[1];if(!S.areEqual(q.dims,[J.n,K,z]))throw Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let F=Q[2].dims;if(S.size(F)!==J.n*K)throw Error("scales input size error.");if(Q.length===4){let D=Q[3].dims,V=J.n*(J.bits===8?K:Math.floor((K*J.bits+7)/8));if(S.size(D)!==V)throw Error("zeroPoints input size error.")}},Z$=(Q,J)=>{let G=Q[0].dims,H=G.length,K=G[H-2],z=J.k,q=J.n,F=G.slice(0,H-2),D=S.size(F),V=Q[1].dims[2]/4,O=Q[0].dataType,P=he(J.k),N=he(V),I=he(q),R=F.concat([K,q]),w=K>1&&q/I%2===0?2:1,E=S.size(R)/I/w,T=64,y=[],x=[D,K,z/P],b=S.convertShape(Q[1].dims).slice();b.splice(-1,1,V/N),y.push(...k(x)),y.push(...k(b)),y.push(...k(Q[2].dims)),Q.length===4&&y.push(...k(S.convertShape(Q[3].dims)));let g=[D,K,q/I];y.push(...k(g));let l=(_)=>{let a=x.length,r=A("a",Q[0].dataType,a,P),f0=A("b",12,b.length,N),t=A("scales",Q[2].dataType,Q[2].dims.length),p0=[r,f0,t],u0=Q.length===4?A("zero_points",12,Q[3].dims.length):void 0;u0&&p0.push(u0);let d=g.length,n=C("output",Q[0].dataType,d,I),c0=ve(Q[0].dataType),WQ=(()=>{switch(P){case 1:return`array<${c0}, 8>`;case 2:return`mat4x2<${c0}>`;case 4:return`mat2x4<${c0}>`;default:throw Error(`${P}-component is not supported.`)}})(),R0=Math.floor(32/J.bits),l0=Math.floor(R0/8),d0=()=>{let LQ="";for(let h0=0;h0<l0;h0++){let pQ=h0*J.bits*4,iQ=pQ+J.bits;LQ+=`
// reuse a data (pass ${h0})
var input_offset${h0>0?h0:""} = ${h0===0?r.indicesToOffset(`${r.type.indices}(batch, row, word_offset)`):"input_offset"};
var a_data${h0>0?h0:""}: ${WQ};
for (var j${h0>0?h0:""}: u32 = 0; j${h0>0?h0:""} < ${8/P}; j${h0>0?h0:""}++) {
a_data${h0>0?h0:""}[j${h0>0?h0:""}] = ${r.getByOffset(`input_offset${h0>0?h0:""}`)};
input_offset${h0>0?h0:""}++;
}
`;for(let mQ=0;mQ<I*w;mQ++)LQ+=`
b_value = ${N===1?`b${mQ}_data`:`b${mQ}_data[i]`};
${J.bits===2?`{
let half_word = b_value >> ${h0*16}u;
let byte_lo = half_word & 0xFFu;
let byte_hi = (half_word >> 8u) & 0xFFu;
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
b_value_lower = unpack4xU8(spread_word & b_mask);
b_value_upper = unpack4xU8((spread_word >> 2u) & b_mask);
}`:`b_value_lower = unpack4xU8((b_value >> ${pQ}u) & b_mask);
b_value_upper = unpack4xU8((b_value >> ${iQ}u) & b_mask);`}
b_quantized_values = ${WQ}(${Array.from({length:4},(AQ,MQ)=>`${c0}(b_value_lower[${MQ}]), ${c0}(b_value_upper[${MQ}])`).join(", ")});
b_dequantized_values = ${P===1?`${WQ}(${Array.from({length:8},(AQ,MQ)=>`(b_quantized_values[${MQ}] - ${u0?`zero_point${mQ}`:"zero_point"}) * scale${mQ}`).join(", ")});`:`(b_quantized_values - ${WQ}(${Array(8).fill(`${u0?`zero_point${mQ}`:"zero_point"}`).join(",")})) * scale${mQ};`};
workgroup_shared[local_id.x * ${w} + ${Math.floor(mQ/I)}]${I>1?`[${mQ%I}]`:""} += ${Array.from({length:8/P},(AQ,MQ)=>`${P===1?`a_data${h0>0?h0:""}[${MQ}] * b_dequantized_values[${MQ}]`:`dot(a_data${h0>0?h0:""}[${MQ}], b_dequantized_values[${MQ}])`}`).join(" + ")};
`}return LQ},m0=()=>{let LQ=`
var col_index = col * ${I};
${u0?`
let zero_point_values_per_byte: u32 = ${Math.floor(8/J.bits)}u;
let zero_point_bytes_per_col = (nBlocksPerCol + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
var zero_point_byte_count: u32;
var zero_point_word_index: u32;
var zero_point_byte_offset: u32;
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
var zero_point_bits_offset: u32;
var zero_point_word: u32;`:`
// The default zero point is ${Math.pow(2,J.bits-1)} for unsigned ${J.bits}-bit quantization.
let zero_point = ${c0}(${Math.pow(2,J.bits-1).toFixed(1)});`}
`;for(let h0=0;h0<I*w;h0++)LQ+=`
let scale${h0} = ${t.getByOffset("col_index * nBlocksPerCol + block")};
${u0?`
zero_point_byte_count = col_index * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
zero_point_word_index = zero_point_byte_count >> 0x2u;
zero_point_byte_offset = zero_point_byte_count & 0x3u;
zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${J.bits}u);
zero_point_word = ${u0.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
let zero_point${h0} = ${c0}((zero_point_word) & ${J.bits===2?"0x3u":"0xFu"});`:""}
col_index += 1;`;return LQ},ZQ=()=>{let LQ=`col_index = col * ${I};`;for(let h0=0;h0<I*w;h0++)LQ+=`
let b${h0}_data = ${f0.getByIndices(`${f0.type.indices}(col_index, block, word)`)};
col_index += 1;`;return LQ+=`
var b_value: u32;
let b_mask: u32 = ${J.bits===2?"0x03030303u":"0x0F0F0F0Fu"};
var b_value_lower: vec4<u32>;
var b_value_upper: vec4<u32>;
var b_quantized_values: ${WQ};
var b_dequantized_values: ${WQ};`,LQ};return`
var<workgroup> workgroup_shared: array<${n.type.value}, ${w*T}>;
${_.declareVariables(...p0,n)}
${_.mainStart([T,1,1])}
let output_indices = ${n.offsetToIndices(`(global_idx / ${T}) * ${w}`)};
let col = output_indices[2];
let row = output_indices[1];
let batch = output_indices[0];
let nBlocksPerCol = uniforms.b_shape[1];
for (var block = local_id.x; block < nBlocksPerCol; block += ${T}) {
//process one block
var word_offset: u32 = block * ${J.blockSize/P};
${m0()}
for (var word: u32 = 0; word < ${V}; word += ${N}) {
${ZQ()}
for (var i: u32 = 0; i < ${N}; i++) {
${d0()}
word_offset += ${R0/P};
}
}
}
workgroupBarrier();
if (local_id.x < ${w}) {
var output_value: ${n.type.value} = ${n.type.value}(0);
var workgroup_shared_offset: u32 = local_id.x;
for (var b: u32 = 0u; b < ${T}u; b++) {
output_value += workgroup_shared[workgroup_shared_offset];
workgroup_shared_offset += ${w};
}
${n.setByIndices(`${n.type.indices}(batch, row, col + local_id.x)`,"output_value")};
}
}`};return{name:"MatMulNBits",shaderCache:{hint:`${J.blockSize};${J.bits};${P};${N};${I};${w};${T}`,inputDependencies:Array(Q.length).fill("rank")},getRunData:()=>({outputs:[{dims:R,dataType:O}],dispatchGroup:{x:E},programUniforms:y}),getShaderSource:l}},J$=(Q,J)=>{let G=Q[0].dims,H=G.length,K=G[H-2],z=J.k,q=J.n,F=G.slice(0,H-2),D=S.size(F),V=Q[1].dims[2]/4,O=Q[0].dataType,P=he(J.k),N=he(V),I=F.concat([K,q]),R=128,w=q%8===0?8:q%4===0?4:1,E=R/w,T=Math.floor(32/J.bits),y=E*N*T,x=y/P,b=y/J.blockSize,g=S.size(I)/w,l=[],_=[D,K,z/P],a=S.convertShape(Q[1].dims).slice();a.splice(-1,1,V/N),l.push(...k(_)),l.push(...k(a)),l.push(...k(Q[2].dims)),Q.length===4&&l.push(...k(S.convertShape(Q[3].dims)));let r=[D,K,q];l.push(...k(r));let f0=(t)=>{let p0=_.length,u0=A("a",Q[0].dataType,p0,P),d=A("b",12,a.length,N),n=A("scales",Q[2].dataType,Q[2].dims.length),c0=[u0,d,n],WQ=Q.length===4?A("zero_points",12,Q[3].dims.length):void 0;WQ&&c0.push(WQ);let R0=r.length,l0=C("output",Q[0].dataType,R0),d0=ve(Q[0].dataType),m0=()=>{switch(P){case 1:return`
let a_data0 = vec4<${d0}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]);
let a_data1 = vec4<${d0}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return`
let a_data0 = vec4<${d0}>(sub_a[word_offset], sub_a[word_offset + 1]);
let a_data1 = vec4<${d0}>(sub_a[word_offset + 2], sub_a[word_offset + 3]);`;case 4:return`
let a_data0 = sub_a[word_offset];
let a_data1 = sub_a[word_offset + 1];`;default:throw Error(`${P}-component is not supported.`)}};return`
var<workgroup> sub_a: array<${u0.type.value}, ${x}>;
var<workgroup> inter_results: array<array<${l0.type.value}, ${E}>, ${w}>;
${t.declareVariables(...c0,l0)}
${t.mainStart([E,w,1])}
let output_indices = ${l0.offsetToIndices(`workgroup_index * ${w}`)};
let col = output_indices[2];
let row = output_indices[1];
let batch = output_indices[0];
let n_blocks_per_col = uniforms.b_shape[1];
let num_tiles = (n_blocks_per_col - 1) / ${b} + 1;
// Loop over shared dimension.
for (var tile: u32 = 0; tile < num_tiles; tile += 1) {
let a_col_start = tile * ${x};
// load one tile A data into shared memory.
for (var a_offset = local_idx; a_offset < ${x}; a_offset += ${R})
{
let a_col = a_col_start + a_offset;
if (a_col < uniforms.a_shape[2])
{
sub_a[a_offset] = ${u0.getByIndices(`${u0.type.indices}(batch, row, a_col)`)};
} else {
sub_a[a_offset] = ${u0.type.value}(0);
}
}
workgroupBarrier();
// each thread process one block
let b_row = col + local_id.y;
let block = tile * ${b} + local_id.x;
${WQ?`
let zero_point_values_per_byte: u32 = ${Math.floor(8/J.bits)}u;
let zero_point_bytes_per_col = (n_blocks_per_col + zero_point_values_per_byte - 1u) / zero_point_values_per_byte;
let zero_point_byte_count = b_row * zero_point_bytes_per_col + (block / zero_point_values_per_byte);
let zero_point_word_index = zero_point_byte_count >> 0x2u;
let zero_point_byte_offset = zero_point_byte_count & 0x3u;
let zero_point_sub_offset: u32 = block % zero_point_values_per_byte;
let zero_point_bits_offset = (zero_point_byte_offset << 3) + (zero_point_sub_offset * ${J.bits}u);
let zero_point_word = ${WQ.getByOffset("zero_point_word_index")} >> zero_point_bits_offset;
let zero_point = ${d0}((zero_point_word) & ${J.bits===2?"0x3u":"0xFu"});`:`
// The default zero point is ${Math.pow(2,J.bits-1)} for unsigned ${J.bits}-bit quantization.
let zero_point = ${d0}(${Math.pow(2,J.bits-1).toFixed(1)});`}
let scale = ${n.getByOffset("b_row * n_blocks_per_col + block")};
let b_data = ${d.getByIndices(`${d.type.indices}(b_row, block, 0)`)};
var word_offset = local_id.x * ${J.blockSize/P};
for (var i: u32 = 0; i < ${N}; i++) {
let b_value = ${N===1?"b_data":"b_data[i]"};
${(()=>{let ZQ=Math.floor(T/8),LQ="";for(let h0=0;h0<ZQ;h0++){let pQ=h0*J.bits*4,iQ=pQ+J.bits;LQ+=`
${m0()}
{${J.bits===2?`
let half_word = b_value >> ${h0*16}u;
let byte_lo = half_word & 0xFFu;
let byte_hi = (half_word >> 8u) & 0xFFu;
let spread_word = (byte_lo & 0xFu) | ((byte_lo >> 4u) << 8u) | ((byte_hi & 0xFu) << 16u) | ((byte_hi >> 4u) << 24u);
let b_value_lower = unpack4xU8(spread_word & 0x03030303u);
let b_value_upper = unpack4xU8((spread_word >> 2u) & 0x03030303u);`:`
let b_value_lower = unpack4xU8((b_value >> ${pQ}u) & 0x0F0F0F0Fu);
let b_value_upper = unpack4xU8((b_value >> ${iQ}u) & 0x0F0F0F0Fu);`}
let b_quantized_values = mat2x4<${d0}>(${Array.from({length:4},(mQ,AQ)=>`${d0}(b_value_lower[${AQ}]), ${d0}(b_value_upper[${AQ}])`).join(", ")});
let b_dequantized_values = (b_quantized_values - mat2x4<${d0}>(${Array(8).fill("zero_point").join(",")})) * scale;
inter_results[local_id.y][local_id.x] += ${Array.from({length:2},(mQ,AQ)=>`${`dot(a_data${AQ}, b_dequantized_values[${AQ}])`}`).join(" + ")};
}
word_offset += ${8/P};`}return LQ})()}
}
workgroupBarrier();
}
if (local_idx < ${w}) {
var output_value: ${l0.type.value} = ${l0.type.value}(0);
for (var b = 0u; b < ${E}; b++) {
output_value += inter_results[local_idx][b];
}
if (col + local_idx < uniforms.output_shape[2])
{
${l0.setByIndices(`${l0.type.indices}(batch, row, col + local_idx)`,"output_value")}
}
}
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${J.blockSize};${P};${N};${E};${w}`,inputDependencies:Array(Q.length).fill("rank")},getRunData:()=>({outputs:[{dims:I,dataType:O}],dispatchGroup:{x:g},programUniforms:l}),getShaderSource:f0}},c_=(Q,J)=>{X$(Q.inputs,J),J.blockSize===32&&Q.adapterInfo.isVendor("intel")&&Q.adapterInfo.isArchitecture("gen-12lp")?Q.compute(J$(Q.inputs,J)):Q.compute(Z$(Q.inputs,J))},d_=(Q)=>Z(Q)}),Q$,Y$,eA,tA,nA,rA,oA,iA,f_,h_=$(()=>{X(),ee(),ne(),Q$=(Q)=>{if(!Q||Q.length<1)throw Error("Too few inputs");if(Q[0].dataType!==1&&Q[0].dataType!==10)throw Error("Input type must be float or float16.");if(Q.length>=2){let J=Q[0].dims.length*2===Q[1].dims[0];if(Q.length===4&&(J=Q[3].dims[0]*2===Q[1].dims[0]),!J)throw Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},Y$=(Q,J,G)=>{let H="";for(let K=J-1;K>=0;--K)H+=`
k = i32(${Q.indicesGet("indices",K)}) - ${B("uniforms.pads",K,G)};
if (k < 0) {
break;
}
if (k >= i32(${B("uniforms.x_shape",K,J)})) {
break;
}
offset += k * i32(${B("uniforms.x_strides",K,J)});
`;return`
value = ${Q.type.value}(uniforms.constant_value);
for (var i = 0; i < 1; i++) {
var offset = 0;
var k = 0;
${H}
value = x[offset];
}
`},eA=(Q,J,G)=>{let H="";for(let K=J-1;K>=0;--K)H+=`
k = i32(${Q.indicesGet("indices",K)}) - ${B("uniforms.pads",K,G)};
if (k < 0) {
k = -k;
}
{
let _2n_1 = 2 * (i32(${B("uniforms.x_shape",K,J)}) - 1);
k = k % _2n_1;
if(k >= i32(${B("uniforms.x_shape",K,J)})) {
k = _2n_1 - k;
}
}
offset += k * i32(${B("uniforms.x_strides",K,J)});
`;return`
var offset = 0;
var k = 0;
${H}
value = x[offset];
`},tA=(Q,J,G)=>{let H="";for(let K=J-1;K>=0;--K)H+=`
k = i32(${Q.indicesGet("indices",K)}) - ${B("uniforms.pads",K,G)};
if (k < 0) {
k = 0;
}
if (k >= i32(${B("uniforms.x_shape",K,J)})) {
k = i32(${B("uniforms.x_shape",K,J)}) - 1;
}
offset += k * i32(${B("uniforms.x_strides",K,J)});
`;return`
var offset = 0;
var k = 0;
${H}
value = x[offset];
`},nA=(Q,J,G)=>{let H="";for(let K=J-1;K>=0;--K)H+=`
k = i32(${Q.indicesGet("indices",K)}) - ${B("uniforms.pads",K,G)};
if (k < 0) {
k += i32(${B("uniforms.x_shape",K,J)}]);
}
if (k >= i32(${B("uniforms.x_shape",K,J)})) {
k -= i32(${B("uniforms.x_shape",K,J)});
}
offset += k * i32(${B("uniforms.x_strides",K,J)});
`;return`
var offset = 0;
var k = 0;
${H}
value = x[offset];
`},rA=(Q,J,G)=>{switch(G.mode){case 0:return Y$(Q,J,G.pads.length);case 1:return eA(Q,J,G.pads.length);case 2:return tA(Q,J,G.pads.length);case 3:return nA(Q,J,G.pads.length);default:throw Error("Invalid mode")}},oA=(Q,J)=>{let G=S.padShape(Q[0].dims.slice(),J.pads),H=Q[0].dims,K=S.size(G),z=[{type:12,data:K},{type:6,data:J.pads}],q=Q.length>=3&&Q[2].data;J.mode===0&&z.push({type:q?Q[2].dataType:1,data:J.value}),z.push(...k(Q[0].dims,G));let F=["rank"],D=(V)=>{let O=C("output",Q[0].dataType,G.length),P=A("x",Q[0].dataType,H.length),N=P.type.value,I=rA(O,H.length,J),R=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:J.pads.length}];return J.mode===0&&R.push({name:"constant_value",type:q?N:"f32"}),`
${V.registerUniforms(R).declareVariables(P,O)}
${V.mainStart()}
${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let indices = ${O.offsetToIndices("global_idx")};
var value = ${N}(0);
${I}
output[global_idx] = value;
}`};return{name:"Pad",shaderCache:{hint:`${J.mode}${q}`,inputDependencies:F},getRunData:()=>({outputs:[{dims:G,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(S.size(G)/64)},programUniforms:z}),getShaderSource:D}},iA=(Q,J)=>{if(Q.length>1){let G=Q[1].getBigInt64Array(),H=Q.length>=3&&Q[2].data?Q[2].dataType===10?Q[2].getUint16Array()[0]:Q[2].getFloat32Array()[0]:0,K=Q[0].dims.length,z=new Int32Array(2*K).fill(0);if(Q.length>=4){let F=Q[3].getBigInt64Array();for(let D=0;D<F.length;D++)z[Number(F[D])]=Number(G[D]),z[Number(F[D])+K]=Number(G[D+F.length])}else G.forEach((F,D)=>z[Number(D)]=Number(F));let q=[];return z.forEach((F)=>q.push(F)),{mode:J.mode,value:H,pads:q}}else return J},f_=(Q,J)=>{Q$(Q.inputs);let G=iA(Q.inputs,J);Q.compute(oA(Q.inputs,G),{inputs:[0]})}}),ea,m_,g_,b_,y_,aA,sA,__,x_,w_,T_,v_,I_,S_,$_,A_,P_,O_,E_,C_=$(()=>{qe(),X(),ee(),ne(),ea=(Q)=>{if(Y.webgpu.validateInputContent&&(!Q||Q.length!==1))throw Error("Pool ops requires 1 input.")},m_=(Q,J,G)=>{let H=J.format==="NHWC",K=Q.dims.slice();H&&K.splice(1,0,K.pop());let z=Object.hasOwnProperty.call(J,"dilations"),q=J.kernelShape.slice(),F=J.strides.slice(),D=z?J.dilations.slice():[],V=J.pads.slice();sr.adjustPoolAttributes(G,K,q,F,D,V);let O=sr.computePoolOutputShape(G,K,F,D,q,V,J.autoPad),P=Object.assign({},J);z?Object.assign(P,{kernelShape:q,strides:F,pads:V,dilations:D,cacheKey:J.cacheKey}):Object.assign(P,{kernelShape:q,strides:F,pads:V,cacheKey:J.cacheKey});let N=O.slice();return N.push(N.splice(1,1)[0]),[P,H?N:O]},g_=(Q,J)=>{let G=J.format==="NHWC",H=S.size(Q),K=S.size(J.kernelShape),z=[{type:12,data:H},{type:12,data:K}],q=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(J.kernelShape.length<=2){let F=J.kernelShape[J.kernelShape.length-1],D=J.strides[J.strides.length-1],V=J.pads[J.pads.length/2-1],O=J.pads[J.pads.length-1],P=!!(V+O);z.push({type:12,data:F},{type:12,data:D},{type:12,data:V},{type:12,data:O}),q.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let N=!1;if(J.kernelShape.length===2){let I=J.kernelShape[J.kernelShape.length-2],R=J.strides[J.strides.length-2],w=J.pads[J.pads.length/2-2],E=J.pads[J.pads.length-2];N=!!(w+E),z.push({type:12,data:I},{type:12,data:R},{type:12,data:w},{type:12,data:E}),q.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[z,q,!0,P,N]}else{if(G)throw Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let F=S.computeStrides(J.kernelShape);z.push({type:12,data:F},{type:12,data:J.pads},{type:12,data:J.strides}),q.push({name:"kernelStrides",type:"u32",length:F.length},{name:"pads",type:"u32",length:J.pads.length},{name:"strides",type:"u32",length:J.strides.length});let D=J.pads.reduce((V,O)=>V+O);return[z,q,!!D,!1,!1]}},b_=(Q,J,G,H,K,z,q,F,D,V,O,P)=>{let N=K.format==="NHWC",I=J.type.value,R=C("output",J.type.tensor,H);if(K.kernelShape.length<=2){let w="",E="",T="",y=G-(N?2:1);if(O?w=`
for (var i: u32 = 0u; i < uniforms.kw; i++) {
xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i;
if (xIndices[${y}] < 0 || xIndices[${y}]
>= uniforms.x_shape[${y}]) {
pad++;
continue;
}
let x_val = x[${J.indicesToOffset("xIndices")}];
${z}
}`:w=`
for (var i: u32 = 0u; i < uniforms.kw; i++) {
xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i;
let x_val = x[${J.indicesToOffset("xIndices")}];
${z}
}`,K.kernelShape.length===2){let x=G-(N?3:2);P?E=`
for (var j: u32 = 0u; j < uniforms.kh; j++) {
xIndices[${x}] = indices[${x}] * uniforms.sh - uniforms.phStart + j;
if (xIndices[${x}] < 0 || xIndices[${x}] >= uniforms.x_shape[${x}]) {
pad += i32(uniforms.kw);
continue;
}
`:E=`
for (var j: u32 = 0u; j < uniforms.kh; j++) {
xIndices[${x}] = indices[${x}] * uniforms.sh - uniforms.phStart + j;
`,T=`
}
`}return`
${Q.registerUniforms(D).declareVariables(J,R)}
${Q.mainStart()}
${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let indices = ${R.offsetToIndices("global_idx")};
var xIndices = ${R.offsetToIndices("global_idx")};
var value = ${I}(${F});
var pad = 0;
${E}
${w}
${T}
${q}
output[global_idx] = value;
}`}else{if(N)throw Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let w=K.kernelShape.length,E=K.pads.length,T="";return V?T=`
if (xIndices[j] >= uniforms.x_shape[j]) {
pad++;
isPad = true;
break;
}
}
if (!isPad) {
let x_val = x[${J.indicesToOffset("xIndices")}];
${z}
}`:T=`
}
let x_val = x[${J.indicesToOffset("xIndices")}];
${z}
`,`
${Q.registerUniforms(D).declareVariables(J,R)}
${Q.mainStart()}
${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let indices = ${R.offsetToIndices("global_idx")};
var xIndices = ${R.offsetToIndices("global_idx")};
var offsets: array<u32, ${w}>;
var value = ${I}(${F});
var pad = 0;
var isPad = false;
for (var i: u32 = 0u; i < uniforms.kernelSize; i++) {
var offset = i;
for (var j = 0u; j < ${w-1}u; j++) {
offsets[j] = offset / ${B("uniforms.kernelStrides","j",w)};
offset -= offsets[j] * ${B("uniforms.kernelStrides","j",w)};
}
offsets[${w-1}] = offset;
isPad = false;
for (var j = ${G-w}u; j < ${G}u; j++) {
xIndices[j] = indices[j] * ${B("uniforms.strides",`j - ${G-w}u`,w)}
+ offsets[j - ${G-w}u] - ${B("uniforms.pads","j - 2u",E)};
${T}
}
${q}
output[global_idx] = value;
}`}},y_=(Q)=>`${Q.format};${Q.ceilMode};${Q.autoPad};${Q.kernelShape.length}`,aA=(Q)=>`${y_(Q)};${Q.countIncludePad}`,sA=(Q)=>`${y_(Q)};${Q.storageOrder};${Q.dilations}`,__=(Q)=>({format:Q.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][Q.auto_pad],ceilMode:Q.ceil_mode,kernelShape:Q.kernel_shape,strides:Q.strides,pads:Q.pads}),x_=(Q,J,G,H)=>{let[K,z]=m_(J,H,G),q=A("x",J.dataType,J.dims.length),F=q.type.value,D="value += x_val;",V="";K.countIncludePad?V+=`value /= ${F}(uniforms.kernelSize);`:V+=`value /= ${F}(i32(uniforms.kernelSize) - pad);`;let[O,P,N,I,R]=g_(z,K);O.push(...k(J.dims,z));let w=["rank"];return{name:Q,shaderCache:{hint:`${H.cacheKey};${N};${I};${R}`,inputDependencies:w},getRunData:()=>({outputs:[{dims:z,dataType:J.dataType}],dispatchGroup:{x:Math.ceil(S.size(z)/64)},programUniforms:O}),getShaderSource:(E)=>b_(E,q,J.dims.length,z.length,K,D,V,0,P,N,I,R)}},w_=(Q)=>{let J=Q.count_include_pad!==0,G=__(Q);if(G.ceilMode!==0)throw Error("using ceil() in shape computation is not yet supported for AveragePool");let H={countIncludePad:J,...G,cacheKey:""};return{...H,cacheKey:aA(H)}},T_=(Q,J)=>{ea(Q.inputs),Q.compute(x_("AveragePool",Q.inputs[0],!1,J))},v_={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},I_=(Q)=>{let J=Q.format;return{format:J,...v_,cacheKey:J}},S_=(Q,J)=>{ea(Q.inputs),Q.compute(x_("GlobalAveragePool",Q.inputs[0],!0,J))},$_=(Q,J,G,H)=>{let[K,z]=m_(J,H,G),q=`
value = max(x_val, value);
`,F="",D=A("x",J.dataType,J.dims.length),V=["rank"],[O,P,N,I,R]=g_(z,K);return O.push(...k(J.dims,z)),{name:Q,shaderCache:{hint:`${H.cacheKey};${N};${I};${R}`,inputDependencies:V},getRunData:()=>({outputs:[{dims:z,dataType:J.dataType}],dispatchGroup:{x:Math.ceil(S.size(z)/64)},programUniforms:O}),getShaderSource:(w)=>b_(w,D,J.dims.length,z.length,K,q,F,J.dataType===10?-65504:-1e5,P,N,I,R)}},A_=(Q,J)=>{ea(Q.inputs),Q.compute($_("MaxPool",Q.inputs[0],!1,J))},P_=(Q)=>{let{storage_order:J,dilations:G}=Q,H=__(Q);if(J!==0)throw Error("column major storage order is not yet supported for MaxPool");if(H.ceilMode!==0)throw Error("using ceil() in shape computation is not yet supported for MaxPool");let K={storageOrder:J,dilations:G,...H,cacheKey:""};return{...K,cacheKey:sA(K)}},O_=(Q)=>{let J=Q.format;return{format:J,...v_,cacheKey:J}},E_=(Q,J)=>{ea(Q.inputs),Q.compute($_("GlobalMaxPool",Q.inputs[0],!0,J))}}),lA,cA,D_,k_,L_=$(()=>{X(),ee(),ke(),ne(),lA=(Q,J)=>{if(Q.length<2||Q.length>3)throw Error("DequantizeLinear requires 2 or 3 inputs.");if(Q.length===3&&Q[1].dims===Q[2].dims)throw Error("x-scale and x-zero-point must have the same shape.");if(Q.length===3&&Q[0].dataType!==Q[2].dataType)throw Error("x and x-zero-point must have the same data type.");if(Q[1].dims.length!==0&&Q[1].dims.length!==1&&Q[1].dims.length!==Q[0].dims.length)throw Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(Q.length>2){if(Q[0].dataType!==Q[2].dataType)throw Error("x and x-zero-point must have the same data type.");if(Q[1].dims.length!==Q[2].dims.length)throw Error("scale and zero-point inputs must have the same rank.");if(!Q[1].dims.map((G,H)=>G===Q[2].dims[H]).reduce((G,H)=>G&&H,!0))throw Error("scale and zero-point inputs must have the same shape.")}if(J.blockSize>0){if(Q[1].dims.length===0||Q[1].dims.length===1&&Q[1].dims[0]===1)throw Error("blockSize must be set only for block quantization.");if(!Q[1].dims.map((K,z)=>z===J.axis||K===Q[0].dims[z]).reduce((K,z)=>K&&z,!0))throw Error("For block qunatization, scale input shape to match the input shape except for the axis");if(Q[1].dims.length!==Q[0].dims.length)throw Error("For block qunatization the scale input rank must be the same as the x rank.");let G=Q[0].dims[J.axis],H=Q[1].dims[J.axis];if(J.blockSize<Math.ceil(G/H)||J.blockSize>Math.ceil(G/(H-1)-1))throw Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},cA=(Q,J)=>{let G=S.normalizeAxis(J.axis,Q[0].dims.length),H=Q[0].dataType,K=H===3,z=Q[0].dims,q=Q[1].dataType,F=S.size(z),D=H===3||H===2,V=D?[Math.ceil(S.size(Q[0].dims)/4)]:Q[0].dims,O=Q[1].dims,P=Q.length>2?Q[2]:void 0,N=P?D?[Math.ceil(S.size(P.dims)/4)]:P.dims:void 0,I=O.length===0||O.length===1&&O[0]===1,R=I===!1&&O.length===1,w=he(F),E=I&&(!D||w===4),T=E?w:1,y=E&&!D?w:1,x=A("input",D?12:H,V.length,y),b=A("scale",q,O.length),g=P?A("zero_point",D?12:H,N.length):void 0,l=C("output",q,z.length,T),_=[x,b];g&&_.push(g);let a=[V,O];P&&a.push(N);let r=[{type:12,data:F/T},{type:12,data:G},{type:12,data:J.blockSize},...k(...a,z)],f0=(t)=>{let p0=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
${t.registerUniforms(p0).declareVariables(..._,l)}
${t.mainStart()}
${t.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let output_indices = ${l.offsetToIndices("global_idx")};
// Set input x
${D?`
let input = ${x.getByOffset("global_idx / 4")};
let x_vec = ${K?"unpack4xI8(input)":"unpack4xU8(input)"};
let x_value = ${T===1?"x_vec[global_idx % 4]":"x_vec"};`:`let x_value = ${x.getByOffset("global_idx")};`};
// Set scale input
${I?`let scale_value= ${b.getByOffset("0")}`:R?`
let scale_index = ${l.indicesGet("output_indices","uniforms.axis")};
let scale_value= ${b.getByOffset("scale_index")};`:`
var scale_indices: ${b.type.indices} = output_indices;
let index = ${b.indicesGet("scale_indices","uniforms.axis")} / uniforms.block_size;
${b.indicesSet("scale_indices","uniforms.axis","index")};
let scale_value= ${b.getByIndices("scale_indices")};`};
// Set zero-point input
${g?I?D?`
let zero_point_input = ${g.getByOffset("0")};
let zero_point_vec = ${K?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
let zero_point_value= zero_point_vec[0]`:`let zero_point_value = ${g.getByOffset("0")}`:R?D?`
let zero_point_index = ${l.indicesGet("output_indices","uniforms.axis")};
let zero_point_input = ${g.getByOffset("zero_point_index / 4")};
let zero_point_vec = ${K?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
let zero_point_value = zero_point_vec[zero_point_index % 4]`:`
let zero_point_index = ${l.indicesGet("output_indices","uniforms.axis")};
let zero_point_value = ${g.getByOffset("zero_point_index")};`:D?`
let zero_point_offset = ${b.indicesToOffset("scale_indices")};
let zero_point_input = ${g.getByOffset("zero_point_offset / 4")};
let zero_point_vec = ${K?"unpack4xI8(zero_point_input)":"unpack4xU8(zero_point_input)"};
let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${g.getByIndices("scale_indices")};`:`let zero_point_value = ${D?K?"i32":"u32":x.type.value}(0);`};
// Compute and write output
${l.setByOffset("global_idx",`${l.type.value}(x_value - zero_point_value) * scale_value`)};
}`};return{name:"DequantizeLinear",shaderCache:{hint:J.cacheKey,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getShaderSource:f0,getRunData:()=>({outputs:[{dims:z,dataType:q}],dispatchGroup:{x:Math.ceil(F/T/64),y:1,z:1},programUniforms:r})}},D_=(Q,J)=>{lA(Q.inputs,J),Q.compute(cA(Q.inputs,J))},k_=(Q)=>Z({axis:Q.axis,blockSize:Q.blockSize})}),dA,pA,R_,N_=$(()=>{qe(),X(),ne(),dA=(Q,J,G)=>{let H=Q===J,K=Q<J&&G<0,z=Q>J&&G>0;if(H||K||z)throw Error("Range these inputs' contents are invalid.")},pA=(Q,J,G,H)=>{let K=Math.abs(Math.ceil((J-Q)/G)),z=[K],q=K,F=[{type:12,data:q},{type:H,data:Q},{type:H,data:G},...k(z)],D=(V)=>{let O=C("output",H,z.length),P=O.type.value,N=[{name:"outputSize",type:"u32"},{name:"start",type:P},{name:"delta",type:P}];return`
${V.registerUniforms(N).declareVariables(O)}
${V.mainStart()}
${V.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
output[global_idx] = uniforms.start + ${P}(global_idx) * uniforms.delta;
}`};return{name:"Range",shaderCache:{hint:`${H}`},getShaderSource:D,getRunData:()=>({outputs:[{dims:z,dataType:H}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:F})}},R_=(Q)=>{let J=0,G=0,H=0;Q.inputs[0].dataType===6?(J=Q.inputs[0].getInt32Array()[0],G=Q.inputs[1].getInt32Array()[0],H=Q.inputs[2].getInt32Array()[0]):Q.inputs[0].dataType===1&&(J=Q.inputs[0].getFloat32Array()[0],G=Q.inputs[1].getFloat32Array()[0],H=Q.inputs[2].getFloat32Array()[0]),Y.webgpu.validateInputContent&&dA(J,G,H),Q.compute(pA(J,G,H,Q.inputs[0].dataType),{inputs:[]})}}),fA,hA,z_,M_,B_=$(()=>{X(),ee(),ke(),ne(),fA=(Q,J,G,H)=>{if(Q!=="none"&&H!=="i32"&&H!=="u32"&&H!=="f32")throw Error(`Input ${H} is not supported with reduction ${Q}.`);let K=`{
var oldValue = 0;
loop {
let newValueF32 =`,z=`;
let newValue = bitcast<i32>(newValueF32);
let res = atomicCompareExchangeWeak(&${J}, oldValue, newValue);
if res.exchanged {
break;
}
oldValue = res.old_value;
}
}`;switch(Q){case"none":return`${J}=${G};`;case"add":return H==="i32"||H==="u32"?`atomicAdd(&${J}, bitcast<${H}>(${G}));`:`
${K}bitcast<${H}>(oldValue) + (${G})${z}`;case"max":return H==="i32"||H==="u32"?`atomicMax(&${J}, bitcast<${H}>(${G}));`:`
${K}max(bitcast<f32>(oldValue), (${G}))${z}`;case"min":return H==="i32"||H==="u32"?`atomicMin(&${J}, bitcast<${H}>(${G}));`:`${K}min(bitcast<${H}>(oldValue), (${G}))${z}`;case"mul":return`${K}(bitcast<${H}>(oldValue) * (${G}))${z}`;default:throw Error(`Reduction ${Q} is not supported.`)}},hA=(Q,J)=>{let G=Q[0].dims,H=Q[1].dims,K=G,z=1,q=Math.ceil(S.sizeToDimension(H,H.length-1)/z),F=H[H.length-1],D=S.sizeFromDimension(G,F),V=[{type:12,data:q},{type:12,data:F},{type:12,data:D},...k(Q[1].dims,Q[2].dims,K)],O=(P)=>{let N=A("indices",Q[1].dataType,Q[1].dims.length),I=A("updates",Q[2].dataType,Q[2].dims.length,z),R=J.reduction!=="none"&&J.reduction!==""?dg("output",Q[0].dataType,K.length):C("output",Q[0].dataType,K.length,z);return`
${P.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(N,I,R)}
${P.mainStart()}
${P.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
var data_offset = 0u;
let indices_start = uniforms.last_index_dimension * global_idx;
let indices_end = indices_start + uniforms.last_index_dimension;
for (var i = indices_start; i < indices_end; i++) {
var index = i32(indices[i].x);
${Q[0].dims.length===1?`
let element_count_dim = uniforms.output_strides;
let dim_value = uniforms.output_shape;`:`
let element_count_dim = uniforms.output_strides[i - indices_start];
let dim_value = uniforms.output_shape[i - indices_start];`}
if (index >= 0) {
if (index >= i32(dim_value)) {
index = i32(dim_value - 1);
}
} else {
if (index < -i32(dim_value)) {
index = 0;
} else {
index += i32(dim_value);
}
}
data_offset += u32((u32(index) * element_count_dim));
}
for (var i = 0u; i < uniforms.num_updates_elements; i++) {
let value = updates[uniforms.num_updates_elements * global_idx + i];
${fA(J.reduction,"output[data_offset + i]","value",R.type.value)}
}
}`};return{name:"ScatterND",shaderCache:{hint:`${J.cacheKey}_${J.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:K,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(q/64)},programUniforms:V}),getShaderSource:O}},z_=(Q)=>Z({reduction:Q.reduction}),M_=(Q,J)=>{Q.compute(hA(Q.inputs,J),{inputs:[Q.inputs[1],Q.inputs[2]],outputs:[]})}}),mA,gA,bA,F_,yA,_A,xA,wA,TA,vA,IA,SA,V_,$A,AA,PA,OA,EA,G_,U_,W_=$(()=>{X(),ee(),ke(),ne(),mA=(Q,J)=>{if(Q.every((G)=>G>0||(()=>{throw Error("Resize requires scales input values to be positive")})),Q.length>0){if(J.mode==="linear"){if(!(Q.length===2||Q.length===3||Q.length===4&&Q[0]===1&&Q[1]===1||Q.length===4&&Q[0]===1&&Q[3]===1||Q.length===5&&Q[0]===1&&Q[1]===1))throw 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(J.mode==="cubic"&&!(Q.length===2||Q.length===4&&Q[0]===1&&Q[1]===1||Q.length===4&&Q[0]===1&&Q[3]===1))throw Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},gA=(Q,J,G)=>{J.every((K)=>K>=0&&K<G||(()=>{throw Error("Resize requires axes input values to be positive and less than rank")}));let H=Array(G).fill(1);return J.forEach((K,z)=>H[K]=Q[z]),H},bA=(Q,J,G,H,K,z)=>{let[q,F,D]=G>10?[1,2,3]:[-1,Q.length>1?1:-1,-1],V=Q[0].dims.length;if(q>0&&Q.length>q&&Q[q].dims.length>0)Q[q].getFloat32Array().forEach((O)=>z.push(O));else if(J.coordinateTransformMode==="tf_crop_and_resize")throw Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(F>0&&Q.length>F&&Q[F].dims.length===1&&Q[F].dims[0]>0){if(Q[F].getFloat32Array().forEach((O)=>H.push(O)),H.length!==0&&H.length!==V&&G>=18&&H.length!==J.axes.length)throw Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");mA(H,J),J.axes.length>0&&gA(H,J.axes,V).forEach((O,P)=>H[P]=O)}if(D>0&&Q.length>D&&Q[D].dims.length===1&&Q[D].dims[0]>0&&(Q[D].getBigInt64Array().forEach((O)=>K.push(Number(O))),K.length!==0&&K.length!==V&&G>=18&&K.length!==J.axes.length))throw Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(J.axes.length>0){if(H.length!==0&&H.length!==J.axes.length)throw Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(K.length!==0&&K.length!==J.axes.length)throw Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof H<"u"&&typeof K<"u"&&H.length>0&&K.length>V)throw Error("Resize requires only of scales or sizes to be specified")},F_=(Q,J,G,H)=>`
// 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 big = (${Q}) * (${J});
let whole = ${H}(big / (${G}));
let fract = ${H}(big % (${G})) / ${H}(${G});
return whole + fract;
`,yA=(Q,J)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32,
lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${J} { `+(()=>{switch(Q){case"asymmetric":return`
if (xScale < 1.0 || floor(xScale) != xScale) {
return ${J}(xResized) / ${J}(xScale);
} else {
${F_("xResized","lengthOriginal","lengthResized",J)}
}
`;case"pytorch_half_pixel":return`if (lengthResized > 1) {
return (${J}(xResized) + 0.5) / ${J}(xScale) - 0.5;
} else {
return 0.0;
}`;case"tf_half_pixel_for_nn":return`return (${J}(xResized) + 0.5) / ${J}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
return 0.0;
} else {
${F_("xResized","lengthOriginal - 1","lengthResized - 1",J)}
}`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
return ${J}(roiStart) * ${J}(lengthOriginal - 1) +
(${J}(xResized) * ${J}(roiEnd - roiStart) * ${J}(lengthOriginal - 1)) /
${J}(lengthResized - 1);
} else {
return 0.5 * ${J}(roiStart + roiEnd) * ${J}(lengthOriginal - 1);
}`;case"half_pixel_symmetric":return`const outputWidth = ${J}xScale * ${J}(lengthResized);
const adjustment = ${J}(lengthResized) / outputWidth;
const center = ${J}(lengthOriginal) / 2;
const offset = center * (1 - adjustment);
return offset + ((${J}(xResized) + 0.5) / ${J}(xScale)) - 0.5;`;case"half_pixel":return`return ((${J}(xResized) + 0.5) / ${J}(xScale)) - 0.5;`;default:throw Error(`Coordinate transform mode ${Q} is not supported`)}})()+"}",_A=(Q,J,G)=>`fn getNearestPixelFromOriginal(xOriginal: ${G}, isDownSample: bool) -> ${G} {`+(()=>{switch(Q){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(J<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw Error(`Nearest mode ${Q} is not supported`)}})()+"}",xA=(Q,J,G)=>{let H=Array(G).fill(0).concat(Array(G).fill(1)),K=Q.length===0?H:Q.slice();return J.length>0?(J.forEach((z,q)=>{H[z]=K[q],H[q+G]=K[J.length+q]}),H):K},wA=(Q,J,G,H)=>{let K=[];if(G.length>0)if(H.length>0){if(Q.forEach((z)=>K.push(z)),Math.max(...H)>Q.length)throw Error("axes is out of bound");H.forEach((z,q)=>K[z]=G[q])}else G.forEach((z)=>K.push(z));else{if(J.length===0)throw Error("Resize requires either scales or sizes.");K=Q.map((z,q)=>Math.round(z*J[q]))}return K},TA=(Q,J,G)=>{let H=(()=>{switch(G.keepAspectRatioPolicy){case"not_larger":return G.axes.length>0?Math.min(...G.axes.map((z)=>J[z]),Number.MAX_VALUE):Math.min(...J,Number.MAX_VALUE);case"not_smaller":return G.axes.length>0?Math.max(...G.axes.map((z)=>J[z]),Number.MIN_VALUE):Math.max(...J,Number.MIN_VALUE);default:throw Error(`Keep aspect ratio policy ${G.keepAspectRatioPolicy} is not supported`)}})();J.fill(1,0,J.length);let K=Q.slice();return G.axes.length>0?(G.axes.forEach((z)=>J[z]=H),G.axes.forEach((z)=>K[z]=Math.round(Q[z]*J[z]))):(J.fill(H,0,J.length),K.forEach((z,q)=>K[q]=Math.round(z*J[q]))),K},vA=(Q,J,G,H,K)=>`
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${Q.type.indices}) -> array<${Q.type.value}, ${G.length}> {
var original_indices: array<${Q.type.value}, ${G.length}>;
for (var i:u32 = 0; i < ${G.length}; i++) {
var output_index = ${Q.indicesGet("output_indices","i")};
var scale = ${B("uniforms.scales","i",H)};
var roi_low = ${B("uniforms.roi","i",K)};
var roi_hi = ${B("uniforms.roi",`i + ${J.length}`,K)};
if (scale == 1.0) {
original_indices[i] = ${Q.type.value}(output_index);
} else {
var input_shape_i = ${B("uniforms.input_shape","i",J.length)};
var output_shape_i = ${B("uniforms.output_shape","i",G.length)};
original_indices[i] = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
input_shape_i, roi_low, roi_hi);
}
}
return original_indices;
}`,IA=(Q,J,G,H,K,z,q)=>`
fn calculateInputIndicesFromOutputIndices(output_indices: ${J.type.indices}) -> ${Q.type.indices} {
var input_indices: ${Q.type.indices};
for (var i:u32 = 0; i < ${H.length}; i++) {
var output_index = ${J.indicesGet("output_indices","i")};
var input_index: u32;
var scale = ${B("uniforms.scales","i",K)};
if (scale == 1.0) {
input_index = output_index;
} else {
var roi_low = ${B("uniforms.roi","i",z)};
var roi_hi = ${B("uniforms.roi",`i + ${G.length}`,z)};
var input_shape_i = ${B("uniforms.input_shape","i",G.length)};
var output_shape_i = ${B("uniforms.output_shape","i",H.length)};
var original_idx = getOriginalCoordinateFromResizedCoordinate(output_index, scale, output_shape_i,
input_shape_i, roi_low, roi_hi);
if (!${q} || (original_idx >= 0 && original_idx < ${J.type.value}(input_shape_i))) {
if (original_idx < 0) {
input_index = 0;
} else if (original_idx > ${J.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);
}
}
${Q.indicesSet("input_indices","i","input_index")}
}
return input_indices;
}`,SA=(Q,J)=>`
fn checkInputIndices(input_indices: ${Q.type.indices}) -> bool {
for (var i:u32 = 0; i < ${J.length}; i++) {
var input_index = ${Q.indicesGet("input_indices","i")};
if (input_index < 0 || input_index >= ${B("uniforms.input_shape","i",J.length)}) {
return false;
}
}
return true;
}`,V_=(Q,J,G,H)=>Q.rank>H?`
${Q.indicesSet("input_indices",J,"channel")};
${Q.indicesSet("input_indices",G,"batch")};
`:"",$A=(Q,J,G,H,K)=>{let[z,q,F,D]=G.length===2?[-1,0,1,-1]:[0,2,3,1],V=Q.type.value;return`
fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${V} {
var input_indices: ${Q.type.indices};
${Q.indicesSet("input_indices",q,`max(0, min(row, ${G[q]} - 1))`)};
${Q.indicesSet("input_indices",F,`max(0, min(col, ${G[F]} - 1))`)};
${V_(Q,D,z,2)}
return ${Q.getByIndices("input_indices")};
}
fn bilinearInterpolation(output_indices: ${J.type.indices}) -> ${V} {
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
var row:${V} = originalIndices[${q}];
var col:${V} = originalIndices[${F}];
${H?`if (row < 0 || row > (${G[q]} - 1) || col < 0 || col > (${G[F]} - 1)) {
return ${K};
}`:""};
row = max(0, min(row, ${G[q]} - 1));
col = max(0, min(col, ${G[F]} - 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 = ${G.length>2?`u32(originalIndices[${D}])`:"0"};
var batch: u32 = ${G.length>2?`u32(originalIndices[${z}])`:"0"};
var x11: ${V} = getInputValue(batch, channel, row1, col1);
var x12: ${V} = getInputValue(batch, channel, row1, col2);
var x21: ${V} = getInputValue(batch, channel, row2, col1);
var x22: ${V} = getInputValue(batch, channel, row2, col2);
var dx1: ${V} = abs(row - ${V}(row1));
var dx2: ${V} = abs(${V}(row2) - row);
var dy1: ${V} = abs(col - ${V}(col1));
var dy2: ${V} = abs(${V}(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);
}`},AA=(Q,J,G,H,K,z,q,F,D,V)=>{let O=G.length===2,P=!0,[N,I]=O?[0,1]:P?[2,3]:[1,2],R=Q.type.value,w=(E)=>{let T=E===N?"row":"col";return`
fn ${T}CubicInterpolation(input_indices: ${Q.type.indices}, output_indices: ${J.type.indices}) -> ${R} {
var output_index = ${J.indicesGet("output_indices",E)};
var originalIdx: ${R} = getOriginalCoordinateFromResizedCoordinate(output_index, ${K[E]},
${H[E]}, ${G[E]}, ${z[E]}, ${z[E]} + ${G.length});
var fractOriginalIdx: ${R} = originalIdx - floor(originalIdx);
var coefs = getCubicInterpolationCoefs(fractOriginalIdx);
if (${F} && (originalIdx < 0 || originalIdx > (${G[E]} - 1))) {
return ${D};
}
var data: array<${R}, 4> = array<${R}, 4>(0.0, 0.0, 0.0, 0.0);
for (var i: i32 = -1; i < 3; i++) {
var ${T}: ${R} = originalIdx + ${R}(i);
if (${T} < 0 || ${T} >= ${G[E]}) {
${V?`coefs[i + 1] = 0.0;
continue;`:F?`return ${D};`:`${T} = max(0, min(${T}, ${G[E]} - 1));`};
}
var input_indices_copy: ${Q.type.indices} = input_indices;
${Q.indicesSet("input_indices_copy",E,`u32(${T})`)};
data[i + 1] = ${E===N?Q.getByIndices("input_indices_copy"):"rowCubicInterpolation(input_indices_copy, output_indices)"};
}
return cubicInterpolation1D(data, coefs);
}`};return`
${w(N)};
${w(I)};
fn getCubicInterpolationCoefs(s: ${R}) -> array<${R}, 4> {
var absS = abs(s);
var coeffs: array<${R}, 4> = array<${R}, 4>(0.0, 0.0, 0.0, 0.0);
var oneMinusAbsS: ${R} = 1.0 - absS;
var twoMinusAbsS: ${R} = 2.0 - absS;
var onePlusAbsS: ${R} = 1.0 + absS;
coeffs[0] = ((${q} * onePlusAbsS - 5 * ${q}) * onePlusAbsS + 8 * ${q}) * onePlusAbsS - 4 * ${q};
coeffs[1] = ((${q} + 2) * absS - (${q} + 3)) * absS * absS + 1;
coeffs[2] = ((${q} + 2) * oneMinusAbsS - (${q} + 3)) * oneMinusAbsS * oneMinusAbsS + 1;
coeffs[3] = ((${q} * twoMinusAbsS - 5 * ${q}) * twoMinusAbsS + 8 * ${q}) * twoMinusAbsS - 4 * ${q};
return coeffs;
}
fn cubicInterpolation1D(x: array<${R}, 4>, coefs: array<${R}, 4>) -> ${R} {
var coefsSum: ${R} = 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: ${J.type.indices}) -> ${R} {
var input_indices: ${Q.type.indices} = output_indices;
return colCubicInterpolation(input_indices, output_indices);
}
`},PA=(Q,J,G,H,K)=>{let[z,q,F,D,V]=G.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],O=Q.type.value;return`
fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${O} {
var input_indices: ${Q.type.indices};
${Q.indicesSet("input_indices",q,`max(0, min(depth, ${G[q]} - 1))`)};
${Q.indicesSet("input_indices",F,`max(0, min(height, ${G[F]} - 1))`)};
${Q.indicesSet("input_indices",D,`max(0, min(width, ${G[D]} - 1))`)};
${V_(Q,V,z,3)}
return ${Q.getByIndices("input_indices")};
}
fn trilinearInterpolation(output_indices: ${J.type.indices}) -> ${O} {
var originalIndices = calculateOriginalIndicesFromOutputIndices(output_indices);
var depth:${O} = originalIndices[${q}];
var height:${O} = originalIndices[${F}];
var width:${O} = originalIndices[${D}];
${H?`if (depth < 0 || depth > (${G[q]} - 1) || height < 0 || height > (${G[F]} - 1) || width < 0 || (width > ${G[D]} - 1)) {
return ${K};
}`:""};
depth = max(0, min(depth, ${G[q]} - 1));
height = max(0, min(height, ${G[F]} - 1));
width = max(0, min(width, ${G[D]} - 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 = ${G.length>3?`u32(originalIndices[${V}])`:"0"};
var batch: u32 = ${G.length>3?`u32(originalIndices[${z}])`:"0"};
var x111: ${O} = getInputValue(batch, channel, depth1, height1, width1);
var x112: ${O} = getInputValue(batch, channel, depth1, height1, width2);
var x121: ${O} = getInputValue(batch, channel, depth1, height2, width1);
var x122: ${O} = getInputValue(batch, channel, depth1, height2, width2);
var x211: ${O} = getInputValue(batch, channel, depth2, height1, width1);
var x212: ${O} = getInputValue(batch, channel, depth2, height1, width2);
var x221: ${O} = getInputValue(batch, channel, depth2, height2, width1);
var x222: ${O} = getInputValue(batch, channel, depth2, height2, width2);
var dx1: ${O} = abs(depth - ${O}(depth1));
var dx2: ${O} = abs(${O}(depth2) - depth);
var dy1: ${O} = abs(height - ${O}(height1));
var dy2: ${O} = abs(${O}(height2) - height);
var dz1: ${O} = abs(width - ${O}(width1));
var dz2: ${O} = abs(${O}(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);
}`},OA=(Q,J,G,H,K,z)=>{let q=Q.dims,F=xA(z,J.axes,q.length),D=wA(q,H,K,J.axes),V=H.slice();H.length===0&&(V=q.map((y,x)=>y===0?1:D[x]/y),J.keepAspectRatioPolicy!=="stretch"&&(D=TA(q,V,J)));let O=C("output",Q.dataType,D.length),P=A("input",Q.dataType,q.length),N=S.size(D),I=q.length===D.length&&q.every((y,x)=>y===D[x]),R=J.coordinateTransformMode==="tf_crop_and_resize",w=J.extrapolationValue,E=P.type.value,T=(y)=>`
${I?"":`
${yA(J.coordinateTransformMode,E)};
${(()=>{switch(J.mode){case"nearest":return`
${SA(P,q)};
${_A(J.nearestMode,G,E)};
${IA(P,O,q,D,V.length,F.length,R)};
`;case"linear":return`
${vA(O,q,D,V.length,F.length)};
${(()=>{if(q.length===2||q.length===4)return`${$A(P,O,q,R,w)}`;if(q.length===3||q.length===5)return`${PA(P,O,q,R,w)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()};
`;case"cubic":return`
${(()=>{if(q.length===2||q.length===4)return`${AA(P,O,q,D,V,F,J.cubicCoeffA,R,J.extrapolationValue,J.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()};
`;default:throw Error("Invalid resize mode")}})()};
`}
${y.registerUniform("output_size","u32").registerUniform("scales","f32",V.length).registerUniform("roi","f32",F.length).declareVariables(P,O)}
${y.mainStart()}
${y.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
${I?"output[global_idx] = input[global_idx];":`
let output_indices = ${O.offsetToIndices("global_idx")};
var input_indices: ${P.type.indices};
${(()=>{switch(J.mode){case"nearest":return`input_indices = calculateInputIndicesFromOutputIndices(output_indices);
if (checkInputIndices(input_indices)) {
output[global_idx] = ${P.getByIndices("input_indices")};
} else {
output[global_idx] = ${J.extrapolationValue};
}`;case"linear":return`output[global_idx] = ${q.length===2||q.length===4?"bilinearInterpolation":"trilinearInterpolation"}(output_indices);`;case"cubic":return"output[global_idx] = bicubicInterpolation(output_indices);";default:throw Error(`Unsupported resize mode: ${J.mode}`)}})()};
`}
}`;return{name:"Resize",shaderCache:{hint:`${J.cacheKey}|${G}|${V.length>0?J.mode==="cubic"?V:V.length:""}|${K.length>0?K:""}|${F.length>0?F:""}|${I}|${J.mode==="nearest"?q.length:q}`,inputDependencies:["rank"]},getShaderSource:T,getRunData:()=>({outputs:[{dims:D,dataType:Q.dataType}],dispatchGroup:{x:Math.ceil(N/64)},programUniforms:[{type:12,data:N},{type:1,data:V},{type:1,data:F},...k(q,D)]})}},EA=(Q)=>{let J=Q.customDataBuffer;return new Uint32Array(J,J.byteOffset,1)[0]},G_=(Q,J)=>{let G=[],H=[],K=[],z=EA(Q);if(J.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");bA(Q.inputs,J,z,G,H,K),Q.compute(OA(Q.inputs[0],J,z,G,H,K),{inputs:[0]})},U_=(Q)=>{let{antialias:J,axes:G,coordinateTransformMode:H,cubicCoeffA:K}=Q,z=Q.excludeOutside!==0,q=Q.extrapolationValue,F=Q.keepAspectRatioPolicy,D=Q.mode,V=Q.nearestMode===""?"simple":Q.nearestMode;return Z({antialias:J,axes:G,coordinateTransformMode:H,cubicCoeffA:K,excludeOutside:z,extrapolationValue:q,keepAspectRatioPolicy:F,mode:D,nearestMode:V})}}),CA,DA,H_,q_=$(()=>{X(),ee(),ne(),CA=(Q)=>{if(!Q||Q.length<3)throw Error("layerNorm requires at least 3 inputs.");let J=Q[0],G=Q[1],H=Q[2];if(J.dataType!==G.dataType||J.dataType!==H.dataType)throw Error("All inputs must have the same data type");if(J.dims.length!==3&&J.dims.length!==2)throw Error("Input must be 2D or 3D");if(G.dims.length!==3&&G.dims.length!==2)throw Error("Skip must be 2D or 3D");let K=J.dims[J.dims.length-1],z=J.dims[J.dims.length-2];if(G.dims[G.dims.length-1]!==K)throw Error("Skip must have the same hidden size as input");if(G.dims[G.dims.length-2]!==z)throw Error("Skip must have the same sequence length as input");if(H.dims.length!==1)throw Error("Gamma must be 1D");if(H.dims[H.dims.length-1]!==K)throw Error("Gamma must have the same hidden size as input");if(Q.length>3){let q=Q[3];if(q.dims.length!==1)throw Error("Beta must be 1D");if(q.dims[q.dims.length-1]!==K)throw Error("Beta must have the same hidden size as input")}if(Q.length>4){let q=Q[4];if(q.dims.length!==1)throw Error("Bias must be 1D");if(q.dims[q.dims.length-1]!==K)throw Error("Bias must have the same hidden size as input")}},DA=(Q,J,G,H)=>{let K=J.simplified,z=Q[0].dims,q=S.size(z),F=z,D=q,V=z.slice(-1)[0],O=H?z.slice(0,-1).concat(1):[],P=!K&&Q.length>3,N=Q.length>4,I=H&&G>1,R=H&&G>2,w=G>3,E=64,T=he(V),y=[{type:12,data:D},{type:12,data:T},{type:12,data:V},{type:1,data:J.epsilon}],x=(g)=>{let l=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],_=[A("x",Q[0].dataType,Q[0].dims,T),A("skip",Q[1].dataType,Q[1].dims,T),A("gamma",Q[2].dataType,Q[2].dims,T)];P&&_.push(A("beta",Q[3].dataType,Q[3].dims,T)),N&&_.push(A("bias",Q[4].dataType,Q[4].dims,T)),_.push(C("output",Q[0].dataType,F,T)),I&&_.push(C("mean_output",1,O)),R&&_.push(C("inv_std_output",1,O)),w&&_.push(C("input_skip_bias_sum",Q[0].dataType,F,T));let a=ve(Q[0].dataType),r=ve(1,T);return`
${g.registerUniforms(l).declareVariables(..._)}
var<workgroup> sum_shared : array<${r}, ${E}>;
var<workgroup> sum_squared_shared : array<${r}, ${E}>;
${g.mainStart([E,1,1])}
let ix = local_id.x;
let iy = global_id.x / ${E};
let hidden_size_vectorized: u32 = uniforms.hidden_size / uniforms.components;
var stride = hidden_size_vectorized / ${E};
let offset = ix * stride + iy * hidden_size_vectorized;
let offset1d = stride * ix;
if (ix == ${E-1}) {
stride = hidden_size_vectorized - stride * ix;
}
for (var i: u32 = 0; i < stride; i++) {
let skip_value = skip[offset + i];
let bias_value = ${N?"bias[offset1d + i]":a+"(0.0)"};
let input_value = x[offset + i];
let value = input_value + skip_value + bias_value;
${w?"input_skip_bias_sum[offset + i] = value;":""}
output[offset + i] = value;
let f32_value = ${lr(a,T,"value")};
sum_shared[ix] += f32_value;
sum_squared_shared[ix] += f32_value * f32_value;
}
workgroupBarrier();
var reduce_size : u32 = ${E};
for (var curr_size = reduce_size >> 1; curr_size > 0; curr_size = reduce_size >> 1) {
reduce_size = curr_size + (reduce_size & 1);
if (ix < curr_size) {
sum_shared[ix] += sum_shared[ix + reduce_size];
sum_squared_shared[ix] += sum_squared_shared[ix + reduce_size];
}
workgroupBarrier();
}
let sum = sum_shared[0];
let square_sum = sum_squared_shared[0];
let mean = ${At("sum",T)} / f32(uniforms.hidden_size);
let inv_std_dev = inverseSqrt(${At("square_sum",T)} / f32(uniforms.hidden_size) ${K?"":"- mean * mean"} + uniforms.epsilon);
${I?"mean_output[global_idx] = mean;":""}
${R?"inv_std_output[global_idx] = inv_std_dev;":""}
for (var i: u32 = 0; i < stride; i++) {
output[offset + i] = (output[offset + i] ${K?"":`- ${a}(mean)`}) *
${a}(inv_std_dev) * gamma[offset1d + i]
${P?"+ beta[offset1d + i]":""};
}
}`},b=[{dims:F,dataType:Q[0].dataType}];return G>1&&b.push({dims:O,dataType:1}),G>2&&b.push({dims:O,dataType:1}),G>3&&b.push({dims:z,dataType:Q[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${T};${I};${R};${w}`,inputDependencies:Q.map((g,l)=>"type")},getShaderSource:x,getRunData:()=>({outputs:b,dispatchGroup:{x:Math.ceil(D/V)},programUniforms:y})}},H_=(Q,J)=>{CA(Q.inputs);let G=[0];Q.outputCount>1&&G.push(-3),Q.outputCount>2&&G.push(-3),Q.outputCount>3&&G.push(3),Q.compute(DA(Q.inputs,J,Q.outputCount,!1),{outputs:G})}}),kA,ta,LA,j_,RA,NA,K_,X_,Z_=$(()=>{X(),ee(),ke(),ne(),kA=(Q,J)=>{if(!Q||Q.length<1)throw Error("too few inputs");if(J.axes.length!==0){if(J.axes.length!==J.starts.length||J.axes.length!==J.ends.length)throw Error("axes, starts and ends must have the same length")}else if(J.starts.length!==J.ends.length)throw Error("starts and ends must have the same length");Q.slice(1).forEach((G,H)=>{if(Q[H+1].dataType!==6&&Q[H+1].dataType!==7)throw Error(`Input ${H} must be an array of int32 or int64`)})},ta=(Q,J)=>{let G=[];if(Q.length>J)if(Q[J].dataType===7)Q[J].getBigInt64Array().forEach((H)=>G.push(Number(H)));else if(Q[J].dataType===6)Q[J].getInt32Array().forEach((H)=>G.push(Number(H)));else throw Error(`Input ${J} must be an array of int32 or int64`);return G},LA=(Q,J)=>{if(Q.length>1){let G=ta(Q,1),H=ta(Q,2),K=ta(Q,3);return K.length===0&&(K=[...Array(Q[0].dims.length).keys()]),Z({starts:G,ends:H,axes:K})}else return J},j_=(Q,J,G,H,K)=>{let z=Q;return Q<0&&(z+=G[H[J]]),K[J]<0?Math.max(0,Math.min(z,G[H[J]]-1)):Math.max(0,Math.min(z,G[H[J]]))},RA=(Q,J,G)=>`fn calculateInputIndices(output_indices: ${J.type.indices}) -> ${Q.type.indices} {
var input_indices: ${Q.type.indices};
var carry = 0u;
for (var i = ${G.length-1}; i >= 0; i--) {
let input_shape_i = ${B("uniforms.input_shape","i",G.length)};
let steps_i = ${B("uniforms.steps","i",G.length)};
let signs_i = ${B("uniforms.signs","i",G.length)};
let starts_i = ${B("uniforms.starts","i",G.length)};
var output_index = ${J.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;
}
${Q.indicesSet("input_indices","i","input_index")};
}
return input_indices;
}`,NA=(Q,J)=>{let G=Q[0].dims,H=S.size(G),K=J.axes.length>0?S.normalizeAxes(J.axes,G.length):[...Array(G.length).keys()],z=ta(Q,4);z.forEach((T)=>T!==0||(()=>{throw Error("step cannot be 0")})),z.length===0&&(z=Array(K.length).fill(1));let q=J.starts.map((T,y)=>j_(T,y,G,K,z)),F=J.ends.map((T,y)=>j_(T,y,G,K,z));if(K.length!==q.length||K.length!==F.length)throw Error("start, ends and axes should have the same number of elements");if(K.length!==G.length)for(let T=0;T<G.length;++T)K.includes(T)||(q.splice(T,0,0),F.splice(T,0,G[T]),z.splice(T,0,1));let D=z.map((T)=>Math.sign(T));z.forEach((T,y,x)=>{if(T<0){let b=(F[y]-q[y])/T,g=q[y],l=g+b*z[y];q[y]=l,F[y]=g,x[y]=-T}});let V=G.slice(0);K.forEach((T,y)=>{V[T]=Math.ceil((F[T]-q[T])/z[T])});let O={dims:V,dataType:Q[0].dataType},P=C("output",Q[0].dataType,V.length),N=A("input",Q[0].dataType,Q[0].dims.length),I=S.size(V),R=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:q.length},{name:"signs",type:"i32",length:D.length},{name:"steps",type:"u32",length:z.length}],w=[{type:12,data:I},{type:12,data:q},{type:6,data:D},{type:12,data:z},...k(Q[0].dims,V)],E=(T)=>`
${T.registerUniforms(R).declareVariables(N,P)}
${RA(N,P,G)}
${T.mainStart()}
${T.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
let output_indices = ${P.offsetToIndices("global_idx")};
let input_indices = calculateInputIndices(output_indices);
${P.setByOffset("global_idx",N.getByIndices("input_indices"))}
}`;return{name:"Slice",shaderCache:{hint:`${D.length}_${q.length}_${z.length}`,inputDependencies:["rank"]},getShaderSource:E,getRunData:()=>({outputs:[O],dispatchGroup:{x:Math.ceil(H/64)},programUniforms:w})}},K_=(Q,J)=>{kA(Q.inputs,J);let G=LA(Q.inputs,J);Q.compute(NA(Q.inputs,G),{inputs:[0]})},X_=(Q)=>{let{starts:J,ends:G,axes:H}=Q;return Z({starts:J,ends:G,axes:H})}}),zA,MA,J_,Q_,Y_=$(()=>{X(),ee(),ke(),Pn(),ne(),zA=(Q)=>{if(!Q||Q.length!==1)throw Error("Softmax op requires 1 input.")},MA=(Q,J)=>{let G=Q.inputs[0],H=G.dims,K=S.size(H),z=H.length,q=S.normalizeAxis(J.axis,z),F=q<H.length-1,D,V=[];F?(V=Array.from({length:z},(_,a)=>a),V[q]=z-1,V[z-1]=q,D=Q.compute(Ge(G,V),{inputs:[G],outputs:[-1]})[0]):D=G;let O=D.dims,P=O[z-1],N=K/P,I=he(P),R=P/I,w=64;N===1&&(w=256);let E=(_,a)=>a===4?`max(max(${_}.x, ${_}.y), max(${_}.z, ${_}.w))`:a===2?`max(${_}.x, ${_}.y)`:a===3?`max(max(${_}.x, ${_}.y), ${_}.z)`:_,T=A("x",D.dataType,D.dims,I),y=C("result",D.dataType,D.dims,I),x=T.type.value,b=ve(D.dataType)==="f32"?`var threadMax = ${x}(-3.4028234663852886e+38f);`:`var threadMax = ${x}(-65504.0h);`,g=(_)=>`
var<workgroup> rowMaxShared : ${x};
var<workgroup> rowSumShared : ${x};
var<workgroup> threadShared : array<${x}, ${w}>;
fn getValue(row: i32, col: i32, row_stride: i32) -> ${x} {
let index = row * row_stride + col;
return x[index];
}
fn setValue(row: i32, col: i32, row_stride: i32, value: ${x}) {
let index = row * row_stride + col;
result[index] = value;
}
${_.registerUniform("packedCols","i32").declareVariables(T,y)}
${_.mainStart(w)}
let gindex = i32(global_idx);
let lindex = i32(local_idx);
const wg = ${w};
let row = gindex / wg;
let cols = uniforms.packedCols;
let row_stride : i32 = uniforms.packedCols;
// find the rows max
${b}
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 = ${x}(${E("threadShared[0]",I)});
}
workgroupBarrier();
// find the rows sum
var threadSum = ${x}(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 = ${x}(${At("threadShared[0]",I)});
}
workgroupBarrier();
// calculate final value for each element in the row
for (var col = lindex; col < cols; col += wg) {
var value = exp(getValue(row, col, row_stride) - rowMaxShared) / rowSumShared;
// max operation protects against NaN since all values should be >=0
value = max(value, ${x}(0.0));
setValue(row, col, row_stride, value);
}
}`,l=Q.compute({name:"Softmax",shaderCache:{hint:`${I};${w}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:O,dataType:D.dataType}],dispatchGroup:{x:N},programUniforms:[{type:6,data:R}]}),getShaderSource:g},{inputs:[D],outputs:[F?-1:0]})[0];F&&Q.compute(Ge(l,V),{inputs:[l]})},J_=(Q,J)=>{zA(Q.inputs),MA(Q,J)},Q_=(Q)=>Z({axis:Q.axis})}),ex,BA,FA,VA,tx,nx=$(()=>{X(),ee(),ne(),ex=(Q)=>Array.from(Q.getBigInt64Array(),Number),BA=(Q)=>{if(!Q||Q.length!==2)throw Error("Tile requires 2 inputs.");if(Q[0].dataType!==1&&Q[0].dataType!==10&&Q[0].dataType!==6&&Q[0].dataType!==12)throw Error("Tile only support float, float16, int32, and uint32 data types");if(Q[1].dataType!==7)throw Error("Tile `repeats` input should be of int64 data type");if(Q[1].dims.length!==1)throw Error("Tile `repeats` input should be 1-D");if(ex(Q[1]).length!==Q[0].dims.length)throw Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},FA=(Q,J)=>{let G=[];for(let H=0;H<Q.length;++H)G.push(Q[H]*J[H]);return G},VA=(Q,J)=>{let G=Q[0].dims,H=J??ex(Q[1]),K=FA(G,H),z=S.size(K),q=Q[0].dataType,F=A("input",q,G.length),D=C("output",q,K.length),V=(O)=>`
const inputShape = ${F.indices(...G)};
${O.registerUniform("output_size","u32").declareVariables(F,D)}
${O.mainStart()}
${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
let output_indices = ${D.offsetToIndices("global_idx")};
var input_indices: ${F.type.indices};
for (var i = 0; i < ${G.length}; i++) {
let input_dim_i = ${F.indicesGet("uniforms.input_shape","i")};
let input_dim_value = ${D.indicesGet("output_indices","i")} % input_dim_i;
${F.indicesSet("input_indices","i","input_dim_value")}
}
${D.setByOffset("global_idx",F.getByIndices("input_indices"))}
}`;return{name:"Tile",shaderCache:{hint:`${H}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:K,dataType:Q[0].dataType}],dispatchGroup:{x:Math.ceil(z/64)},programUniforms:[{type:12,data:z},...k(Q[0].dims,K)]}),getShaderSource:V}},tx=(Q)=>{BA(Q.inputs),Q.compute(VA(Q.inputs),{inputs:[0]})}}),GA,UA,rx,ox=$(()=>{X(),ee(),ne(),GA=(Q,J,G,H,K)=>{let z=C("output_data",K,G.length,4),q=A("a_data",J[1].dataType,J[1].dims.length,4),F=A("b_data",J[2].dataType,J[2].dims.length,4),D=A("c_data",J[0].dataType,J[0].dims.length,4),V,O=(P,N,I)=>`select(${N}, ${P}, ${I})`;if(!H)V=z.setByOffset("global_idx",O(q.getByOffset("global_idx"),F.getByOffset("global_idx"),D.getByOffset("global_idx")));else{let P=(N,I,R="")=>{let w=`a_data[index_a${I}][component_a${I}]`,E=`b_data[index_b${I}][component_b${I}]`,T=`bool(c_data[index_c${I}] & (0xffu << (component_c${I} * 8)))`;return`
let output_indices${I} = ${z.offsetToIndices(`global_idx * 4u + ${I}u`)};
let offset_a${I} = ${q.broadcastedIndicesToOffset(`output_indices${I}`,z)};
let offset_b${I} = ${F.broadcastedIndicesToOffset(`output_indices${I}`,z)};
let offset_c${I} = ${D.broadcastedIndicesToOffset(`output_indices${I}`,z)};
let index_a${I} = offset_a${I} / 4u;
let index_b${I} = offset_b${I} / 4u;
let index_c${I} = offset_c${I} / 4u;
let component_a${I} = offset_a${I} % 4u;
let component_b${I} = offset_b${I} % 4u;
let component_c${I} = offset_c${I} % 4u;
${N}[${I}] = ${R}(${O(w,E,T)});
`};K===9?V=`
var data = vec4<u32>(0);
${P("data",0,"u32")}
${P("data",1,"u32")}
${P("data",2,"u32")}
${P("data",3,"u32")}
output_data[global_idx] = dot(vec4<u32>(0x1, 0x100, 0x10000, 0x1000000), vec4<u32>(data));`:V=`
${P("output_data[global_idx]",0)}
${P("output_data[global_idx]",1)}
${P("output_data[global_idx]",2)}
${P("output_data[global_idx]",3)}
`}return`
${Q.registerUniform("vec_size","u32").declareVariables(D,q,F,z)}
${Q.mainStart()}
${Q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
${V}
}`},UA=(Q)=>{let J=Q[1].dims,G=Q[2].dims,H=Q[0].dims,K=Q[1].dataType,z=!(S.areEqual(J,G)&&S.areEqual(G,H)),q=J,F=S.size(J);if(z){let V=bn.calcShape(bn.calcShape(J,G,!1),H,!1);if(!V)throw Error("Can't perform where op on the given tensors");q=V,F=S.size(q)}let D=Math.ceil(F/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:(V)=>GA(V,Q,q,z,K),getRunData:()=>({outputs:[{dims:q,dataType:K}],dispatchGroup:{x:Math.ceil(F/64/4)},programUniforms:[{type:12,data:D},...k(H,J,G,q)]})}},rx=(Q)=>{Q.compute(UA(Q.inputs))}}),ix,ax=$(()=>{Fg(),Ui(),Ug(),Hg(),Eb(),Vb(),Wb(),ay(),fy(),gy(),_y(),Iy(),Ay(),Oy(),Dy(),Ry(),My(),Vy(),Wy(),jy(),n_(),i_(),s_(),l_(),p_(),ml(),h_(),C_(),L_(),N_(),B_(),Vi(),W_(),yl(),q_(),Z_(),Y_(),bl(),nx(),Pn(),Hi(),ox(),ix=new Map([["Abs",[qg]],["Acos",[jg]],["Acosh",[Kg]],["Add",[Cb]],["ArgMax",[Bg,nl]],["ArgMin",[Mg,nl]],["Asin",[Xg]],["Asinh",[Zg]],["Atan",[Jg]],["Atanh",[Qg]],["Attention",[Vg]],["AveragePool",[T_,w_]],["BatchNormalization",[Gg]],["BiasAdd",[Wg]],["BiasSplitGelu",[Ob]],["Cast",[eb,Yg]],["Ceil",[nb]],["Clip",[tb]],["Concat",[Gb,Ub]],["Conv",[dl,cl]],["ConvTranspose",[py,cy]],["Cos",[rb]],["Cosh",[ob]],["CumSum",[hy,my]],["DepthToSpace",[by,yy]],["DequantizeLinear",[D_,k_]],["Div",[Db]],["Einsum",[Ty,vy]],["Elu",[ib,ro]],["Equal",[kb]],["Erf",[ab]],["Exp",[sb]],["Expand",[$y]],["FastGelu",[Py]],["Floor",[ub]],["FusedConv",[dl,cl]],["Gather",[Cy,Ey]],["GatherElements",[Fy,By]],["GatherBlockQuantized",[Ny,zy]],["GatherND",[ky,Ly]],["Gelu",[lb]],["Gemm",[Uy,Gy]],["GlobalAveragePool",[S_,I_]],["GlobalMaxPool",[E_,O_]],["Greater",[zb]],["GreaterOrEqual",[Bb]],["GridSample",[Hy,qy]],["GroupQueryAttention",[t_]],["HardSigmoid",[bb,gb]],["InstanceNormalization",[o_]],["LayerNormalization",[a_]],["LeakyRelu",[cb,ro]],["Less",[Mb]],["LessOrEqual",[Fb]],["Log",[$b]],["MatMul",[u_]],["MatMulNBits",[c_,d_]],["MaxPool",[A_,P_]],["Mul",[Lb]],["MultiHeadAttention",[Zy,Xy]],["Neg",[pb]],["Not",[db]],["Pad",[f_]],["Pow",[Rb]],["QuickGelu",[Ab,ro]],["Range",[R_]],["Reciprocal",[fb]],["ReduceMin",[Dg]],["ReduceMean",[Ag]],["ReduceMax",[Cg]],["ReduceSum",[Lg]],["ReduceProd",[kg]],["ReduceL1",[Pg]],["ReduceL2",[Og]],["ReduceLogSum",[Ng]],["ReduceLogSumExp",[Eg]],["ReduceSumSquare",[Rg]],["Relu",[hb]],["Resize",[G_,U_]],["RotaryEmbedding",[Yy]],["ScatterND",[M_,z_]],["Sigmoid",[mb]],["Sin",[yb]],["Sinh",[_b]],["Slice",[K_,X_]],["SkipLayerNormalization",[H_]],["Split",[Jy,Qy]],["Sqrt",[xb]],["Softmax",[J_,Q_]],["Sub",[Nb]],["Tan",[wb]],["Tanh",[vb]],["ThresholdedRelu",[Sb,ro]],["Tile",[tx]],["Transpose",[hg,mg]],["Where",[rx]]])}),na,sx=$(()=>{qe(),gn(),ne(),na=class{constructor(Q){this.backend=Q,this.repo=new Map,this.attributesBound=!1}getArtifact(Q){return this.repo.get(Q)}setArtifact(Q,J){this.repo.set(Q,J)}run(Q,J,G,H,K){tt(Q.programInfo.name);let z=this.backend.device,q=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let F=[];for(let V of J)F.push({binding:F.length,resource:{buffer:V.buffer}});for(let V of G)F.push({binding:F.length,resource:{buffer:V.buffer}});K&&F.push({binding:F.length,resource:K});let D=z.createBindGroup({layout:Q.computePipeline.getBindGroupLayout(0),entries:F,label:Q.programInfo.name});if(this.backend.sessionStatus==="capturing"){let V={kernelId:this.backend.currentKernelId,computePipeline:Q.computePipeline,bindGroup:D,dispatchGroup:H};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(V)}q.setPipeline(Q.computePipeline),q.setBindGroup(0,D),q.dispatchWorkgroups(...H),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(),Je(Q.programInfo.name)}dispose(){}build(Q,J){tt(Q.name);let G=this.backend.device,H=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach((V)=>{G.features.has(V.feature)&&H.push(`enable ${V.extension};`)});let K=pg(J,this.backend.device.limits),z=Q.getShaderSource(K),q=`${H.join(`
`)}
${K.additionalImplementations}
${z}`,F=G.createShaderModule({code:q,label:Q.name});ie("verbose",()=>`[WebGPU] ${Q.name} shader code: ${q}`);let D=G.createComputePipeline({compute:{module:F,entryPoint:"main"},layout:"auto",label:Q.name});return Je(Q.name),{programInfo:Q,computePipeline:D,uniformVariablesInfo:K.variablesInfo}}normalizeDispatchGroupSize(Q){let J=typeof Q=="number"?Q:Q.x,G=typeof Q=="number"?1:Q.y||1,H=typeof Q=="number"?1:Q.z||1,K=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(J<=K&&G<=K&&H<=K)return[J,G,H];let z=J*G*H,q=Math.ceil(Math.sqrt(z));if(q>K){if(q=Math.ceil(Math.cbrt(z)),q>K)throw Error("Total dispatch size exceeds WebGPU maximum.");return[q,q,q]}else return[q,q,1]}}}),ux={};Wn(ux,{WebGpuBackend:()=>xl});var WA,HA,_l,xl,lx=$(()=>{qe(),X(),gn(),Wu(),cg(),ax(),sx(),WA=(Q,J)=>{if(J.length!==Q.length)throw Error(`inputDependencies length ${J.length} is not equal to inputTensors length ${Q.length}.`);let G=[];for(let H=0;H<Q.length;++H){let K=Q[H].dataType;switch(J[H]){case"none":{G.push("");break}case"type":{G.push(`${K}`);break}case"rank":{let z=Q[H].dims.length;G.push(`${K};${z}`);break}case"dims":{let z=Q[H].dims.join(",");G.push(`${K};${z}`);break}default:throw Error(`unsupported input dependency: ${J[H]}`)}}return G.join("|")},HA=(Q,J,G)=>{let H=Q.name;return Q.shaderCache?.hint&&(H+="["+Q.shaderCache.hint+"]"),H+=":"+G+`:${WA(J,Q.shaderCache?.inputDependencies??Array(J.length).fill("dims"))}`,H},_l=class{constructor(Q){Q&&(this.architecture=Q.architecture,this.vendor=Q.vendor)}isArchitecture(Q){return this.architecture===Q}isVendor(Q){return this.vendor===Q}},xl=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 Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let Q=this.kernelCustomData.get(this.currentKernelId);return Q||(Q={},this.kernelCustomData.set(this.currentKernelId,Q)),Q}async initialize(Q,J){this.env=Q;let G=[],H={requiredLimits:{maxComputeWorkgroupStorageSize:J.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:J.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:J.limits.maxStorageBufferBindingSize,maxBufferSize:J.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:J.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:J.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:J.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:J.limits.maxComputeWorkgroupSizeZ},requiredFeatures:G},K=(z)=>J.features.has(z)&&G.push(z)&&!0;K("chromium-experimental-timestamp-query-inside-passes")||K("timestamp-query"),K("shader-f16"),K("subgroups"),this.device=await J.requestDevice(H),this.adapterInfo=new _l(J.info||await J.requestAdapterInfo()),this.gpuDataManager=lg(this),this.programManager=new na(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ci(Q.logLevel,!!Q.debug),this.device.onuncapturederror=(z)=>{z.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${z.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:J,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let Q=this.getCommandEncoder(),J={};this.queryType==="at-passes"&&(J.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=Q.beginComputePass(J)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;tt(),this.endComputePass();let Q;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),Q=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(Q,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,Q,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&Q.mapAsync(GPUMapMode.READ).then(()=>{let J=new BigUint64Array(Q.getMappedRange()),G=this.pendingQueries.get(Q);for(let H=0;H<J.length/2;H++){let K=G[H],z=K.kernelId,q=this.kernels.get(z),F=q.kernelType,D=q.kernelName,V=K.programName,O=K.inputTensorViews,P=K.outputTensorViews,N=J[H*2],I=J[H*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=N);let R=Number(N-this.queryTimeBase),w=Number(I-this.queryTimeBase);if(!Number.isSafeInteger(R)||!Number.isSafeInteger(w))throw RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:O.map((E)=>({dims:E.dims,dataType:mn(E.dataType)})),outputsMetadata:P.map((E)=>({dims:E.dims,dataType:mn(E.dataType)})),kernelId:z,kernelType:F,kernelName:D,programName:V,startTime:R,endTime:w});else{let E="";O.forEach((y,x)=>{E+=`input[${x}]: [${y.dims}] | ${mn(y.dataType)}, `});let T="";P.forEach((y,x)=>{T+=`output[${x}]: [${y.dims}] | ${mn(y.dataType)}, `}),console.log(`[profiling] kernel "${z}|${F}|${D}|${V}" ${E}${T}start time: ${R} ns, execution time: ${w-R} ns`)}kr("GPU",`${V}::${N}::${I}`)}Q.unmap(),this.pendingQueries.delete(Q)}),Je()}run(Q,J,G,H,K,z){tt(Q.name);let q=[];for(let y=0;y<J.length;++y){let x=J[y].data;if(x===0)continue;let b=this.gpuDataManager.get(x);if(!b)throw Error(`no GPU data for input: ${x}`);q.push(b)}let{outputs:F,dispatchGroup:D,programUniforms:V}=Q.getRunData(J),O=G.length===0?F.map((y,x)=>x):G;if(O.length!==F.length)throw Error(`Output size ${O.length} must be equal to ${F.length}.`);let P=[],N=[];for(let y=0;y<F.length;++y){if(!Number.isInteger(O[y])||O[y]<-3||O[y]>=z)throw Error(`Invalid output index: ${O[y]}`);if(O[y]===-3)continue;let x=O[y]===-1,b=O[y]===-2,g=x||b?K(F[y].dataType,F[y].dims):H(O[y],F[y].dataType,F[y].dims);if(P.push(g),g.data===0)continue;let l=this.gpuDataManager.get(g.data);if(!l)throw Error(`no GPU data for output: ${g.data}`);if(x&&this.temporaryData.push(l),b){let _=this.kernelPersistentData.get(this.currentKernelId);_||(_=[],this.kernelPersistentData.set(this.currentKernelId,_)),_.push(l)}N.push(l)}if(q.length!==J.length||N.length!==P.length){if(N.length===0)return Je(Q.name),P;throw Error(`Program ${Q.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let I;if(V){let y=0,x=[];V.forEach((_)=>{let a=typeof _.data=="number"?[_.data]:_.data;if(a.length===0)return;let r=_.type===10?2:4,f0,t;_.type===10?(t=a.length>4?16:a.length>2?8:a.length*r,f0=a.length>4?16:r*a.length):(t=a.length<=2?a.length*r:16,f0=16),y=Math.ceil(y/t)*t,x.push(y);let p0=_.type===10?8:4;y+=a.length>4?Math.ceil(a.length/p0)*f0:a.length*r});let b=16;y=Math.ceil(y/b)*b;let g=new ArrayBuffer(y);V.forEach((_,a)=>{let r=x[a],f0=typeof _.data=="number"?[_.data]:_.data;if(_.type===6)new Int32Array(g,r,f0.length).set(f0);else if(_.type===12)new Uint32Array(g,r,f0.length).set(f0);else if(_.type===10)new Uint16Array(g,r,f0.length).set(f0);else if(_.type===1)new Float32Array(g,r,f0.length).set(f0);else throw Error(`Unsupported uniform type: ${mn(_.type)}`)});let l=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(l.buffer,0,g,0,y),this.gpuDataManager.release(l.id),I={offset:0,size:y,buffer:l.buffer}}let R=this.programManager.normalizeDispatchGroupSize(D),w=R[1]===1&&R[2]===1,E=HA(Q,J,w),T=this.programManager.getArtifact(E);if(T||(T=this.programManager.build(Q,R),this.programManager.setArtifact(E,T),ie("info",()=>`[artifact] key: ${E}, programName: ${Q.name}`)),V&&T.uniformVariablesInfo){if(V.length!==T.uniformVariablesInfo.length)throw Error(`Uniform variables count mismatch: expect ${T.uniformVariablesInfo.length}, got ${V.length} in program "${T.programInfo.name}".`);for(let y=0;y<V.length;y++){let x=V[y],b=x.type,g=typeof x.data=="number"?1:x.data.length,[l,_]=T.uniformVariablesInfo[y];if(b!==l||g!==_)throw Error(`Uniform variable ${y} mismatch: expect type ${l} with size ${_}, got type ${b} with size ${g} in program "${T.programInfo.name}".`)}}if(ie("info",()=>`[ProgramManager] run "${Q.name}" (key=${E}) with ${R[0]}x${R[1]}x${R[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:T.programInfo.name,inputTensorViews:J,outputTensorViews:P};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(T,q,N,R,I),Je(Q.name),P}upload(Q,J){this.gpuDataManager.upload(Q,J)}memcpy(Q,J){this.gpuDataManager.memcpy(Q,J)}async download(Q,J){await this.gpuDataManager.download(Q,J)}alloc(Q){return this.gpuDataManager.create(Q).id}free(Q){return this.gpuDataManager.release(Q)}createKernel(Q,J,G,H){let K=ix.get(Q);if(!K)throw Error(`kernel not implemented: ${Q}`);let z={kernelType:Q,kernelName:H,kernelEntry:K[0],attributes:[K[1],G]};this.kernels.set(J,z)}releaseKernel(Q){let J=this.kernelPersistentData.get(Q);if(J){for(let G of J)this.gpuDataManager.release(G.id);this.kernelPersistentData.delete(Q)}this.kernelCustomData.delete(Q),this.kernels.delete(Q)}computeKernel(Q,J,G){let H=this.kernels.get(Q);if(!H)throw Error(`kernel not created: ${Q}`);let{kernelType:K,kernelName:z,kernelEntry:q,attributes:F}=H;if(this.currentKernelId!==null)throw Error(`kernel "[${K}] ${z}" is not allowed to be called recursively`);this.currentKernelId=Q,F[0]&&(F[1]=F[0](F[1]),F[0]=void 0),ie("info",()=>`[WebGPU] Start to run kernel "[${K}] ${z}"...`);let D=this.env.debug;this.temporaryData=[];try{return D&&this.device.pushErrorScope("validation"),q(J,F[1]),0}catch(V){return G.push(Promise.resolve(`[WebGPU] Kernel "[${K}] ${z}" failed. ${V}`)),1}finally{D&&G.push(this.device.popErrorScope().then((V)=>V?`GPU validation error for kernel "[${K}] ${z}": ${V.message}`:null));for(let V of this.temporaryData)this.gpuDataManager.release(V.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(Q,J,G,H){let K=this.sessionExternalDataMapping.get(Q);K||(K=new Map,this.sessionExternalDataMapping.set(Q,K));let z=K.get(J),q=this.gpuDataManager.registerExternalBuffer(G,H,z);return K.set(J,[q,G]),q}unregisterBuffers(Q){let J=this.sessionExternalDataMapping.get(Q);J&&(J.forEach((G)=>this.gpuDataManager.unregisterExternalBuffer(G[0])),this.sessionExternalDataMapping.delete(Q))}getBuffer(Q){let J=this.gpuDataManager.get(Q);if(!J)throw Error(`no GPU data for buffer: ${Q}`);return J.buffer}createDownloader(Q,J,G){return async()=>{let H=await Zu(this,Q,J);return ki(H.buffer,G)}}writeTimestamp(Q){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,Q)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.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(){ie("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(){ie("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){ie("info","replay"),this.sessionStatus="replaying";let Q=this.capturedCommandList.get(this.currentSessionId),J=this.capturedPendingKernels.get(this.currentSessionId),G=Q.length;this.pendingKernels=[];for(let H=0;H<G;H++){let K=this.getComputePassEncoder(),z=Q[H];this.writeTimestamp(this.pendingDispatchNumber*2),K.setPipeline(z.computePipeline),K.setBindGroup(0,z.bindGroup),K.dispatchWorkgroups(...z.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(J[H]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(Q){this.unregisterBuffers(Q),this.capturedCommandList.has(Q)&&this.capturedCommandList.delete(Q),this.capturedPendingKernels.has(Q)&&this.capturedPendingKernels.delete(Q),this.gpuDataManager.onReleaseSession(Q)}onRunStart(Q){this.currentSessionId=Q,this.setQueryType()}}}),cx={};Wn(cx,{init:()=>qA});var so,wl,qA,dx=$(()=>{X(),gn(),ee(),ig(),so=class Q{constructor(J,G,H,K){this.module=J,this.dataType=G,this.data=H,this.dims=K}getFloat32Array(){if(this.dataType!==1)throw Error("Invalid data type");let J=S.size(this.dims);return J===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,J)}getBigInt64Array(){if(this.dataType!==7)throw Error("Invalid data type");let J=S.size(this.dims);return J===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,J)}getInt32Array(){if(this.dataType!==6)throw Error("Invalid data type");let J=S.size(this.dims);return J===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,J)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw Error("Invalid data type");let J=S.size(this.dims);return J===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,J)}reshape(J){if(S.size(J)!==S.size(this.dims))throw Error("Invalid new shape");return new Q(this.module,this.dataType,this.data,J)}},wl=class{constructor(Q,J,G){this.module=Q,this.backend=J,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=J.adapterInfo;let H=Q.PTR_SIZE,K=G/Q.PTR_SIZE,z=H===4?"i32":"i64";this.opKernelContext=Number(Q.getValue(H*K++,z));let q=Number(Q.getValue(H*K++,z));this.outputCount=Number(Q.getValue(H*K++,z)),this.customDataOffset=Number(Q.getValue(H*K++,"*")),this.customDataSize=Number(Q.getValue(H*K++,z));let F=[];for(let D=0;D<q;D++){let V=Number(Q.getValue(H*K++,z)),O=Number(Q.getValue(H*K++,"*")),P=Number(Q.getValue(H*K++,z)),N=[];for(let I=0;I<P;I++)N.push(Number(Q.getValue(H*K++,z)));F.push(new so(Q,V,O,N))}this.inputs=F}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(Q,J){let G=J?.inputs?.map((q)=>typeof q=="number"?this.inputs[q]:q)??this.inputs,H=J?.outputs??[],K=(q,F,D)=>new so(this.module,F,this.output(q,D),D),z=(q,F)=>{let D=Vn(q,F);if(!D)throw Error(`Unsupported data type: ${q}`);let V=D>0?this.backend.gpuDataManager.create(D).id:0;return new so(this.module,q,V,F)};return this.backend.run(Q,G,H,K,z,this.outputCount)}output(Q,J){let G=this.module.stackSave();try{let H=this.module.PTR_SIZE,K=H===4?"i32":"i64",z=this.module.stackAlloc((1+J.length)*H);this.module.setValue(z,J.length,K);for(let q=0;q<J.length;q++)this.module.setValue(z+H*(q+1),J[q],K);return this.module._JsepOutput(this.opKernelContext,Q,z)}catch(H){throw Error(`Failed to generate kernel's output[${Q}] with dims [${J}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${H}`)}finally{this.module.stackRestore(G)}}},qA=async(Q,J,G,H)=>{let K=J.jsepInit;if(!K)throw Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(Q==="webgpu"){let z=(lx(),pr(ux)).WebGpuBackend,q=new z;await q.initialize(G,H),K("webgpu",[q,(F)=>q.alloc(Number(F)),(F)=>q.free(F),(F,D,V,O=!1)=>{if(O)ie("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(F)}, dst=${Number(D)}, size=${Number(V)}`),q.memcpy(Number(F),Number(D));else{ie("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(F)}, gpuDataId=${Number(D)}, size=${Number(V)}`);let P=J.HEAPU8.subarray(Number(F>>>0),Number(F>>>0)+Number(V));q.upload(Number(D),P)}},async(F,D,V)=>{ie("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${F}, dataOffset=${D}, size=${V}`),await q.download(Number(F),()=>J.HEAPU8.subarray(Number(D)>>>0,Number(D+V)>>>0))},(F,D,V)=>q.createKernel(F,Number(D),V,J.UTF8ToString(J._JsepGetNodeName(Number(D)))),(F)=>q.releaseKernel(F),(F,D,V,O)=>{ie("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${V}, kernel=${F}, contextDataOffset=${D}`);let P=new wl(J,q,Number(D));return q.computeKernel(Number(F),P,O)},()=>q.captureBegin(),()=>q.captureEnd(),()=>q.replay()])}else{let z=new zi(G);K("webnn",[z,()=>z.reserveTensorId(),(q)=>z.releaseTensorId(q),async(q,F,D,V,O)=>z.ensureTensor(q,F,D,V,O),(q,F)=>{z.uploadTensor(q,F)},async(q,F)=>z.downloadTensor(q,F),(q,F)=>z.registerMLContext(q,F),!!G.trace])}}}),jA,_i,xi,cr,KA,px,Yr,wi,Ti,fx,vi,Ii,Si,zu=$(()=>{qe(),qm(),Km(),X(),Bn(),Pi(),Gu(),jA=(Q,J)=>{we()._OrtInit(Q,J)!==0&&fe("Can't initialize onnxruntime.")},_i=async(Q)=>{jA(Q.wasm.numThreads,to(Q.logLevel))},xi=async(Q,J)=>{we().asyncInit?.();let G=Q.webgpu.adapter;if(J==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw Error("WebGPU is not supported in current environment");if(G){if(typeof G.limits!="object"||typeof G.features!="object"||typeof G.requestDevice!="function")throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let H=Q.webgpu.powerPreference;if(H!==void 0&&H!=="low-power"&&H!=="high-performance")throw Error(`Invalid powerPreference setting: "${H}"`);let K=Q.webgpu.forceFallbackAdapter;if(K!==void 0&&typeof K!="boolean")throw Error(`Invalid forceFallbackAdapter setting: "${K}"`);if(G=await navigator.gpu.requestAdapter({powerPreference:H,forceFallbackAdapter:K}),!G)throw Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(J==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw Error("WebNN is not supported in current environment");{let H=(dx(),pr(cx)).init;J==="webgpu"&&await H("webgpu",we(),Q,G),J==="webnn"&&await H("webnn",we(),Q)}},cr=new Map,KA=(Q)=>{let J=we(),G=J.stackSave();try{let H=J.PTR_SIZE,K=J.stackAlloc(2*H);J._OrtGetInputOutputCount(Q,K,K+H)!==0&&fe("Can't get session input/output count.");let z=H===4?"i32":"i64";return[Number(J.getValue(K,z)),Number(J.getValue(K+H,z))]}finally{J.stackRestore(G)}},px=(Q,J)=>{let G=we(),H=G.stackSave(),K=0;try{let z=G.PTR_SIZE,q=G.stackAlloc(2*z);G._OrtGetInputOutputMetadata(Q,J,q,q+z)!==0&&fe("Can't get session input/output metadata.");let F=Number(G.getValue(q,"*"));K=Number(G.getValue(q+z,"*"));let D=G.HEAP32[K/4];if(D===0)return[F,0];let V=G.HEAPU32[K/4+1],O=[];for(let P=0;P<V;P++){let N=Number(G.getValue(K+8+P*z,"*"));O.push(N!==0?G.UTF8ToString(N):Number(G.getValue(K+8+(P+V)*z,"*")))}return[F,D,O]}finally{G.stackRestore(H),K!==0&&G._OrtFree(K)}},Yr=(Q)=>{let J=we(),G=J._malloc(Q.byteLength);if(G===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${Q.byteLength}.`);return J.HEAPU8.set(Q,G),[G,Q.byteLength]},wi=async(Q,J)=>{let G,H,K=we();Array.isArray(Q)?[G,H]=Q:Q.buffer===K.HEAPU8.buffer?[G,H]=[Q.byteOffset,Q.byteLength]:[G,H]=Yr(Q);let z=0,q=0,F=0,D=[],V=[],O=[];try{if([q,D]=await jm(J),J?.externalData&&K.mountExternalData){let b=[];for(let g of J.externalData){let l=typeof g=="string"?g:g.path;b.push(no(typeof g=="string"?g:g.data).then((_)=>{K.mountExternalData(l,_)}))}await Promise.all(b)}for(let b of J?.executionProviders??[])if((typeof b=="string"?b:b.name)==="webnn"){if(K.shouldTransferToMLTensor=!1,typeof b!="string"){let g=b,l=g?.context,_=g?.gpuDevice,a=g?.deviceType,r=g?.powerPreference;l?K.currentContext=l:_?K.currentContext=await K.webnnCreateMLContext(_):K.currentContext=await K.webnnCreateMLContext({deviceType:a,powerPreference:r})}else K.currentContext=await K.webnnCreateMLContext();break}z=await K._OrtCreateSession(G,H,q),K.webgpuOnCreateSession?.(z),z===0&&fe("Can't create a session."),K.jsepOnCreateSession?.(),K.currentContext&&(K.webnnRegisterMLContext(z,K.currentContext),K.currentContext=void 0,K.shouldTransferToMLTensor=!0);let[P,N]=KA(z),I=!!J?.enableGraphCapture,R=[],w=[],E=[],T=[],y=[];for(let b=0;b<P;b++){let[g,l,_]=px(z,b);g===0&&fe("Can't get an input name."),V.push(g);let a=K.UTF8ToString(g);R.push(a),E.push(l===0?{name:a,isTensor:!1}:{name:a,isTensor:!0,type:mn(l),shape:_})}for(let b=0;b<N;b++){let[g,l,_]=px(z,b+P);g===0&&fe("Can't get an output name."),O.push(g);let a=K.UTF8ToString(g);w.push(a),T.push(l===0?{name:a,isTensor:!1}:{name:a,isTensor:!0,type:mn(l),shape:_});{if(I&&J?.preferredOutputLocation===void 0){y.push("gpu-buffer");continue}let r=typeof J?.preferredOutputLocation=="string"?J.preferredOutputLocation:J?.preferredOutputLocation?.[a]??"cpu",f0=K.webnnIsGraphOutput;if(r==="cpu"&&f0&&f0(z,a)){y.push("ml-tensor-cpu-output");continue}if(r!=="cpu"&&r!=="cpu-pinned"&&r!=="gpu-buffer"&&r!=="ml-tensor")throw Error(`Not supported preferred output location: ${r}.`);if(I&&r!=="gpu-buffer")throw Error(`Not supported preferred output location: ${r}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);y.push(r)}}let x=null;return y.some((b)=>b==="gpu-buffer"||b==="ml-tensor"||b==="ml-tensor-cpu-output")&&(F=K._OrtCreateBinding(z),F===0&&fe("Can't create IO binding."),x={handle:F,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map((b)=>b==="ml-tensor-cpu-output"?"ml-tensor":b).map((b)=>Vu(b))}),cr.set(z,[z,V,O,x,I,!1]),[z,R,w,E,T]}catch(P){throw V.forEach((N)=>K._OrtFree(N)),O.forEach((N)=>K._OrtFree(N)),F!==0&&K._OrtReleaseBinding(F)!==0&&fe("Can't release IO binding."),z!==0&&K._OrtReleaseSession(z)!==0&&fe("Can't release session."),P}finally{K._free(G),q!==0&&K._OrtReleaseSessionOptions(q)!==0&&fe("Can't release session options."),D.forEach((P)=>K._free(P)),K.unmountExternalData?.()}},Ti=(Q)=>{let J=we(),G=cr.get(Q);if(!G)throw Error(`cannot release session. invalid session id: ${Q}`);let[H,K,z,q,F]=G;q&&(F&&J._OrtClearBoundOutputs(q.handle)!==0&&fe("Can't clear bound outputs."),J._OrtReleaseBinding(q.handle)!==0&&fe("Can't release IO binding.")),J.jsepOnReleaseSession?.(Q),J.webnnOnReleaseSession?.(Q),J.webgpuOnReleaseSession?.(Q),K.forEach((D)=>J._OrtFree(D)),z.forEach((D)=>J._OrtFree(D)),J._OrtReleaseSession(H)!==0&&fe("Can't release session."),cr.delete(Q)},fx=async(Q,J,G,H,K,z,q=!1)=>{if(!Q){J.push(0);return}let F=we(),D=F.PTR_SIZE,V=Q[0],O=Q[1],P=Q[3],N=P,I,R;if(V==="string"&&(P==="gpu-buffer"||P==="ml-tensor"))throw Error("String tensor is not supported on GPU.");if(q&&P!=="gpu-buffer")throw Error(`External buffer must be provided for input/output index ${z} when enableGraphCapture is true.`);if(P==="gpu-buffer"){let T=Q[2].gpuBuffer;R=Vn(Fn(V),O);{let y=F.jsepRegisterBuffer;if(!y)throw Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');I=y(H,z,T,R)}}else if(P==="ml-tensor"){let T=Q[2].mlTensor;R=Vn(Fn(V),O);let y=F.webnnRegisterMLTensor;if(!y)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');I=y(H,T,Fn(V),O)}else{let T=Q[2];if(Array.isArray(T)){R=D*T.length,I=F._malloc(R),G.push(I);for(let y=0;y<T.length;y++){if(typeof T[y]!="string")throw TypeError(`tensor data at index ${y} is not a string`);F.setValue(I+y*D,lt(T[y],G),"*")}}else{let{webnnIsGraphInput:y,webnnIsGraphOutput:x}=F;if(V!=="string"&&y&&x){let b=F.UTF8ToString(K);if(y(H,b)||x(H,b)){let g=Fn(V);R=Vn(g,O),N="ml-tensor";let{webnnCreateTemporaryTensor:l,webnnUploadTensor:_}=F;if(!l||!_)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');let a=await l(H,g,O);_(a,new Uint8Array(T.buffer,T.byteOffset,T.byteLength)),I=a}else R=T.byteLength,I=F._malloc(R),G.push(I),F.HEAPU8.set(new Uint8Array(T.buffer,T.byteOffset,R),I)}else R=T.byteLength,I=F._malloc(R),G.push(I),F.HEAPU8.set(new Uint8Array(T.buffer,T.byteOffset,R),I)}}let w=F.stackSave(),E=F.stackAlloc(4*O.length);try{O.forEach((y,x)=>F.setValue(E+x*D,y,D===4?"i32":"i64"));let T=F._OrtCreateTensor(Fn(V),I,R,E,O.length,Vu(N));T===0&&fe(`Can't create tensor for input/output. session=${H}, index=${z}.`),J.push(T)}finally{F.stackRestore(w)}},vi=async(Q,J,G,H,K,z)=>{let q=we(),F=q.PTR_SIZE,D=cr.get(Q);if(!D)throw Error(`cannot run inference. invalid session id: ${Q}`);let V=D[0],O=D[1],P=D[2],N=D[3],I=D[4],R=D[5],w=J.length,E=H.length,T=0,y=[],x=[],b=[],g=[],l=[],_=q.stackSave(),a=q.stackAlloc(w*F),r=q.stackAlloc(w*F),f0=q.stackAlloc(E*F),t=q.stackAlloc(E*F);try{[T,y]=Hm(z),In("wasm prepareInputOutputTensor");for(let n=0;n<w;n++)await fx(G[n],x,g,Q,O[J[n]],J[n],I);for(let n=0;n<E;n++)await fx(K[n],b,g,Q,P[H[n]],w+H[n],I);Sn("wasm prepareInputOutputTensor");for(let n=0;n<w;n++)q.setValue(a+n*F,x[n],"*"),q.setValue(r+n*F,O[J[n]],"*");for(let n=0;n<E;n++)q.setValue(f0+n*F,b[n],"*"),q.setValue(t+n*F,P[H[n]],"*");if(N&&!R){let{handle:n,outputPreferredLocations:c0,outputPreferredLocationsEncoded:WQ}=N;if(O.length!==w)throw Error(`input count from feeds (${w}) is expected to be always equal to model's input count (${O.length}).`);In("wasm bindInputsOutputs");for(let R0=0;R0<w;R0++){let l0=J[R0];await q._OrtBindInput(n,O[l0],x[R0])!==0&&fe(`Can't bind input[${R0}] for session=${Q}.`)}for(let R0=0;R0<E;R0++){let l0=H[R0];K[R0]?.[3]?(l.push(b[R0]),q._OrtBindOutput(n,P[l0],b[R0],0)!==0&&fe(`Can't bind pre-allocated output[${R0}] for session=${Q}.`)):q._OrtBindOutput(n,P[l0],0,WQ[l0])!==0&&fe(`Can't bind output[${R0}] to ${c0[R0]} for session=${Q}.`)}Sn("wasm bindInputsOutputs"),cr.set(Q,[V,O,P,N,I,!0])}q.jsepOnRunStart?.(V),q.webnnOnRunStart?.(V);let p0;N?p0=await q._OrtRunWithBinding(V,N.handle,E,f0,T):p0=await q._OrtRun(V,r,a,w,t,E,f0,T),p0!==0&&fe("failed to call OrtRun().");let u0=[],d=[];In("wasm ProcessOutputTensor");for(let n=0;n<E;n++){let c0=Number(q.getValue(f0+n*F,"*"));if(c0===b[n]||l.includes(b[n])){u0.push(K[n]),c0!==b[n]&&q._OrtReleaseTensor(c0)!==0&&fe("Can't release tensor.");continue}let WQ=q.stackSave(),R0=q.stackAlloc(4*F),l0=!1,d0,m0=0;try{q._OrtGetTensorData(c0,R0,R0+F,R0+2*F,R0+3*F)!==0&&fe(`Can't access output tensor data on index ${n}.`);let ZQ=F===4?"i32":"i64",LQ=Number(q.getValue(R0,ZQ));m0=q.getValue(R0+F,"*");let h0=q.getValue(R0+F*2,"*"),pQ=Number(q.getValue(R0+F*3,ZQ)),iQ=[];for(let MQ=0;MQ<pQ;MQ++)iQ.push(Number(q.getValue(h0+MQ*F,ZQ)));q._OrtFree(h0)!==0&&fe("Can't free memory for tensor dims.");let mQ=iQ.reduce((MQ,DQ)=>MQ*DQ,1);d0=mn(LQ);let AQ=N?.outputPreferredLocations[H[n]];if(d0==="string"){if(AQ==="gpu-buffer"||AQ==="ml-tensor")throw Error("String tensor is not supported on GPU.");let MQ=[];for(let DQ=0;DQ<mQ;DQ++){let bQ=q.getValue(m0+DQ*F,"*"),j8=q.getValue(m0+(DQ+1)*F,"*"),tQ=DQ===mQ-1?void 0:j8-bQ;MQ.push(q.UTF8ToString(bQ,tQ))}u0.push([d0,iQ,MQ,"cpu"])}else if(AQ==="gpu-buffer"&&mQ>0){let MQ=q.jsepGetBuffer;if(!MQ)throw Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let DQ=MQ(m0),bQ=Vn(LQ,mQ);if(bQ===void 0||!Oi(d0))throw Error(`Unsupported data type: ${d0}`);l0=!0,u0.push([d0,iQ,{gpuBuffer:DQ,download:q.jsepCreateDownloader(DQ,bQ,d0),dispose:()=>{q._OrtReleaseTensor(c0)!==0&&fe("Can't release tensor.")}},"gpu-buffer"])}else if(AQ==="ml-tensor"&&mQ>0){let{webnnEnsureTensor:MQ,webnnIsGraphInputOutputTypeSupported:DQ}=q;if(!MQ||!DQ)throw Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Vn(LQ,mQ)===void 0||!Ei(d0))throw Error(`Unsupported data type: ${d0}`);if(!DQ(Q,d0,!1))throw Error(`preferredLocation "ml-tensor" for ${d0} output is not supported by current WebNN Context.`);let bQ=await MQ(Q,m0,LQ,iQ,!1);l0=!0,u0.push([d0,iQ,{mlTensor:bQ,download:q.webnnCreateMLTensorDownloader(m0,d0),dispose:()=>{q.webnnReleaseTensorId(m0),q._OrtReleaseTensor(c0)}},"ml-tensor"])}else if(AQ==="ml-tensor-cpu-output"&&mQ>0){let MQ=q.webnnCreateMLTensorDownloader(m0,d0)(),DQ=u0.length;l0=!0,d.push((async()=>{let bQ=[DQ,await MQ];return q.webnnReleaseTensorId(m0),q._OrtReleaseTensor(c0),bQ})()),u0.push([d0,iQ,[],"cpu"])}else{let MQ=$r(d0),DQ=new MQ(mQ);new Uint8Array(DQ.buffer,DQ.byteOffset,DQ.byteLength).set(q.HEAPU8.subarray(m0,m0+DQ.byteLength)),u0.push([d0,iQ,DQ,"cpu"])}}finally{q.stackRestore(WQ),d0==="string"&&m0&&q._free(m0),l0||q._OrtReleaseTensor(c0)}}N&&!I&&(q._OrtClearBoundOutputs(N.handle)!==0&&fe("Can't clear bound outputs."),cr.set(Q,[V,O,P,N,I,!1]));for(let[n,c0]of await Promise.all(d))u0[n][2]=c0;return Sn("wasm ProcessOutputTensor"),u0}finally{q.webnnOnRunEnd?.(V),q.stackRestore(_),x.forEach((p0)=>q._OrtReleaseTensor(p0)),b.forEach((p0)=>q._OrtReleaseTensor(p0)),g.forEach((p0)=>q._free(p0)),T!==0&&q._OrtReleaseRunOptions(T),y.forEach((p0)=>q._free(p0))}},Ii=(Q)=>{let J=we(),G=cr.get(Q);if(!G)throw Error("invalid session id");let H=G[0],K=J._OrtEndProfiling(H);K===0&&fe("Can't get an profile file name."),J._OrtFree(K)},Si=(Q)=>{let J=[];for(let G of Q){let H=G[2];!Array.isArray(H)&&"buffer"in H&&J.push(H.buffer)}return J}}),dr,_t,uo,oa,ia,ra,Tl,vl,Er,Cr,ZA,hx,mx,gx,bx,yx,_x,xx,Il=$(()=>{qe(),zu(),Bn(),bi(),dr=()=>!!Y.wasm.proxy&&typeof document<"u",uo=!1,oa=!1,ia=!1,vl=new Map,Er=(Q,J)=>{let G=vl.get(Q);G?G.push(J):vl.set(Q,[J])},Cr=()=>{if(uo||!oa||ia||!_t)throw Error("worker not ready")},ZA=(Q)=>{switch(Q.data.type){case"init-wasm":uo=!1,Q.data.err?(ia=!0,Tl[1](Q.data.err)):(oa=!0,Tl[0]()),ra&&(URL.revokeObjectURL(ra),ra=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let J=vl.get(Q.data.type);Q.data.err?J.shift()[1](Q.data.err):J.shift()[0](Q.data.out);break}default:}},hx=async()=>{if(!oa){if(uo)throw Error("multiple calls to 'initWasm()' detected.");if(ia)throw Error("previous call to 'initWasm()' failed.");if(uo=!0,dr())return new Promise((Q,J)=>{_t?.terminate(),Gm().then(([G,H])=>{try{_t=H,_t.onerror=(z)=>J(z),_t.onmessage=ZA,Tl=[Q,J];let K={type:"init-wasm",in:Y};if(!K.in.wasm.wasmPaths&&G){let z=$i();z&&(K.in.wasm.wasmPaths=z)}_t.postMessage(K),ra=G}catch(K){J(K)}},J)});try{await yi(Y.wasm),await _i(Y),oa=!0}catch(Q){throw ia=!0,Q}finally{uo=!1}}},mx=async(Q)=>{if(dr())return Cr(),new Promise((J,G)=>{Er("init-ep",[J,G]);let H={type:"init-ep",in:{epName:Q,env:Y}};_t.postMessage(H)});await xi(Y,Q)},gx=async(Q)=>dr()?(Cr(),new Promise((J,G)=>{Er("copy-from",[J,G]);let H={type:"copy-from",in:{buffer:Q}};_t.postMessage(H,[Q.buffer])})):Yr(Q),bx=async(Q,J)=>{if(dr()){if(J?.preferredOutputLocation)throw Error('session option "preferredOutputLocation" is not supported for proxy.');return Cr(),new Promise((G,H)=>{Er("create",[G,H]);let K={type:"create",in:{model:Q,options:{...J}}},z=[];Q instanceof Uint8Array&&z.push(Q.buffer),_t.postMessage(K,z)})}else return wi(Q,J)},yx=async(Q)=>{if(dr())return Cr(),new Promise((J,G)=>{Er("release",[J,G]);let H={type:"release",in:Q};_t.postMessage(H)});Ti(Q)},_x=async(Q,J,G,H,K,z)=>{if(dr()){if(G.some((q)=>q[3]!=="cpu"))throw Error("input tensor on GPU is not supported for proxy.");if(K.some((q)=>q))throw Error("pre-allocated output tensor is not supported for proxy.");return Cr(),new Promise((q,F)=>{Er("run",[q,F]);let D=G,V={type:"run",in:{sessionId:Q,inputIndices:J,inputs:D,outputIndices:H,options:z}};_t.postMessage(V,Si(D))})}else return vi(Q,J,G,H,K,z)},xx=async(Q)=>{if(dr())return Cr(),new Promise((J,G)=>{Er("end-profiling",[J,G]);let H={type:"end-profiling",in:Q};_t.postMessage(H)});Ii(Q)}}),wx,JA,aa,Tx=$(()=>{qe(),Il(),X(),gi(),Gu(),wx=(Q,J)=>{switch(Q.location){case"cpu":return[Q.type,Q.dims,Q.data,"cpu"];case"gpu-buffer":return[Q.type,Q.dims,{gpuBuffer:Q.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Q.type,Q.dims,{mlTensor:Q.mlTensor},"ml-tensor"];default:throw Error(`invalid data location: ${Q.location} for ${J()}`)}},JA=(Q)=>{switch(Q[3]){case"cpu":return new et(Q[0],Q[2],Q[1]);case"gpu-buffer":{let J=Q[0];if(!Oi(J))throw Error(`not supported data type: ${J} for deserializing GPU tensor`);let{gpuBuffer:G,download:H,dispose:K}=Q[2];return et.fromGpuBuffer(G,{dataType:J,dims:Q[1],download:H,dispose:K})}case"ml-tensor":{let J=Q[0];if(!Ei(J))throw Error(`not supported data type: ${J} for deserializing MLTensor tensor`);let{mlTensor:G,download:H,dispose:K}=Q[2];return et.fromMLTensor(G,{dataType:J,dims:Q[1],download:H,dispose:K})}default:throw Error(`invalid data location: ${Q[3]}`)}},aa=class{async fetchModelAndCopyToWasmMemory(Q){return gx(await no(Q))}async loadModel(Q,J){tt();let G;typeof Q=="string"?G=await this.fetchModelAndCopyToWasmMemory(Q):G=Q,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await bx(G,J),Je()}async dispose(){return yx(this.sessionId)}async run(Q,J,G){tt();let H=[],K=[];Object.entries(Q).forEach((P)=>{let N=P[0],I=P[1],R=this.inputNames.indexOf(N);if(R===-1)throw Error(`invalid input '${N}'`);H.push(I),K.push(R)});let z=[],q=[];Object.entries(J).forEach((P)=>{let N=P[0],I=P[1],R=this.outputNames.indexOf(N);if(R===-1)throw Error(`invalid output '${N}'`);z.push(I),q.push(R)});let F=H.map((P,N)=>wx(P,()=>`input "${this.inputNames[K[N]]}"`)),D=z.map((P,N)=>P?wx(P,()=>`output "${this.outputNames[q[N]]}"`):null),V=await _x(this.sessionId,K,F,q,D,G),O={};for(let P=0;P<V.length;P++)O[this.outputNames[q[P]]]=z[P]??JA(V[P]);return Je(),O}startProfiling(){}endProfiling(){xx(this.sessionId)}}}),Ix={};Wn(Ix,{OnnxruntimeWebAssemblyBackend:()=>sa,initializeFlags:()=>vx,wasmBackend:()=>QA});var vx,sa,QA,Sx=$(()=>{qe(),Il(),Tx(),vx=()=>{(typeof Y.wasm.initTimeout!="number"||Y.wasm.initTimeout<0)&&(Y.wasm.initTimeout=0);let Q=Y.wasm.simd;if(typeof Q!="boolean"&&Q!==void 0&&Q!=="fixed"&&Q!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Q}". Reset it to \`false\` and ignore SIMD feature checking.`),Y.wasm.simd=!1),typeof Y.wasm.proxy!="boolean"&&(Y.wasm.proxy=!1),typeof Y.wasm.trace!="boolean"&&(Y.wasm.trace=!1),typeof Y.wasm.numThreads!="number"||!Number.isInteger(Y.wasm.numThreads)||Y.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Y.wasm.numThreads=1;else{let J=typeof navigator>"u"?ua("node:os").cpus().length:navigator.hardwareConcurrency;Y.wasm.numThreads=Math.min(4,Math.ceil((J||1)/2))}},sa=class{async init(Q){vx(),await hx(),await mx(Q)}async createInferenceSessionHandler(Q,J){let G=new aa;return await G.loadModel(Q,J),G}},QA=new sa}),eP={};Wn(eP,{InferenceSession:()=>Zl,TRACE:()=>kr,TRACE_EVENT_BEGIN:()=>In,TRACE_EVENT_END:()=>Sn,TRACE_FUNC_BEGIN:()=>tt,TRACE_FUNC_END:()=>Je,Tensor:()=>et,default:()=>YA,env:()=>Y,registerBackend:()=>vn}),qe(),qe(),qe();var nc="1.26.0",YA=ha;{let Q=(Lm(),pr(km)).onnxjsBackend;vn("webgl",Q,-10)}{let Q=(Sx(),pr(Ix)).wasmBackend;vn("webgpu",Q,5),vn("webnn",Q,5),vn("cpu",Q,10),vn("wasm",Q,10)}return Object.defineProperty(Y.versions,"web",{value:nc,enumerable:!0}),pr(eP)})();/*! Bundled license information:
long/index.js:
(**
* @license
* Copyright 2009 The Closure Library Authors
* Copyright 2020 Daniel Wirtz / The long.js Authors.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*)
*/typeof O60=="object"&&typeof cC=="object"&&(cC.exports=SBQ)});var cj0=i((hK8,dj0)=>{dj0.exports=lj0()});var HC0=i((Tz8,WC0)=>{WC0.exports={}});var DIQ={};UD(DIQ,{default:()=>DX0});module.exports=Dk0(DIQ);var Xw=require("obsidian"),yS0=K7(sE(),1);var rE=50,fH=30,tE=1,eE=300;function $40(Q){if(Q===void 0||!Number.isFinite(Q)||Q<=0)return;return Math.max(1,Math.min(300,Math.round(Q)))}var q40=/\b(delete|remove|uninstall|trash|clean(?:up)?|purge|drop|reset|clear|wipe)\b/i;function Pq(Q,J){if(q40.test(Q))return!0;if(J&&q40.test(J))return!0;return!1}function QT(Q=60000,J=30){let G=[];function H(K){let z=K-Q,q=G[0];while(q!==void 0&&q<=z)G.shift(),q=G[0]}return{record(K=Date.now()){G.push(K),H(K)},countInLastMinute(K=Date.now()){return H(K),G.length},isSoftLimitExceeded(K=Date.now()){return H(K),G.length>J}}}function XT(Q){if(!Q)return[];return Q.split(/[,\n]/).map((J)=>J.trim()).filter((J)=>J.length>0)}function JT(Q){return Q.map((J)=>J.trim()).filter((J)=>J.length>0).join(", ")}function jO(Q,J){return[...Q??[],J].slice(-50)}function U40(Q){if(/[",\r\n]/.test(Q))return'"'+Q.replace(/"/g,'""')+'"';return Q}function Z40(Q){let G=[["timestamp","commandId","decision","reason"].map(U40).join(",")];for(let H of Q)G.push([H.timestamp,H.commandId,H.decision,H.reason??""].map(U40).join(","));return G.join(`\r
`)+`\r
`}function F40(Q=new Date){return`mcp-tools-audit-${Q.toISOString().slice(0,10)}.csv`}function YT(Q,J,G){if(!J)return{decision:"deny",reason:"MCP command execution is disabled in plugin settings. Enable 'Command execution' in the MCP Tools settings to allow the agent to run commands."};if(!G||G.length===0)return{decision:"deny",reason:`Command '${Q}' is not in the user's allowlist. Add it in MCP Tools settings → Command execution → Allowlist to authorize it.`};if(!G.includes(Q))return{decision:"deny",reason:`Command '${Q}' is not in the user's allowlist. Add it in MCP Tools settings → Command execution → Allowlist to authorize it.`};return{decision:"allow"}}function GT(Q){let J=new Map;for(let H of Q){let K=H.id.indexOf(":"),z=K>0?H.id.slice(0,K):"other",q=J.get(z);if(q)q.push(H);else J.set(z,[H])}let G=new Map;for(let H of[...J.keys()].sort()){let K=J.get(H);K.sort((z,q)=>z.id.localeCompare(q.id)),G.set(H,K)}return G}function WT(Q,J){if(!J)return{live:[...Q],stale:[]};let G=[],H=[];for(let K of Q)if(J[K])G.push(K);else H.push(K);return{live:G,stale:H}}var z30=require("obsidian");var UQ=!1;var QW=Array.isArray,M40=Array.prototype.indexOf,U4=Array.prototype.includes,UK=Array.from,HT=Object.keys,BX=Object.defineProperty,wJ=Object.getOwnPropertyDescriptor,CO=Object.getOwnPropertyDescriptors,BT=Object.prototype,L40=Array.prototype,mH=Object.getPrototypeOf,AT=Object.isExtensible;var XW=()=>{};function O40(Q){return Q()}function $K(Q){for(var J=0;J<Q.length;J++)Q[J]()}function IO(){var Q,J,G=new Promise((H,K)=>{Q=H,J=K});return{promise:G,resolve:Q,reject:J}}function KT(Q,J){if(Array.isArray(Q))return Q;if(J===void 0||!(Symbol.iterator in Q))return Array.from(Q);let G=[];for(let H of Q)if(G.push(H),G.length===J)break;return G}var D9=2,JW=4,aW=8,uH=16777216,AX=16,l7=32,EJ=64,ZK=128,KX=512,Q9=1024,X9=2048,z7=4096,P7=8192,o9=16384,HJ=32768,FK=33554432,SJ=65536,$4=131072,zT=262144,YW=524288,VT=1048576,GG=33554432,tJ=65536,pH=2097152,eJ=4194304,IY=8388608,T7=Symbol("$state"),Nq=Symbol("legacy props"),P40=Symbol(""),RO=Symbol("proxy path"),wO=Symbol("attributes"),jq=Symbol("class"),Cq=Symbol("style"),Iq=Symbol("text"),Z4=Symbol("form reset"),qT=Symbol("hmr anchor"),F4=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},EO=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");var lH=3,RY=8;function N40(Q){if(UQ){let J=Error(`invariant_violation
An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: "${Q}"
https://svelte.dev/e/invariant_violation`);throw J.name="Svelte error",J}else throw Error("https://svelte.dev/e/invariant_violation")}function Rq(Q){if(UQ){let J=Error(`lifecycle_outside_component
\`${Q}(...)\` can only be used during component initialisation
https://svelte.dev/e/lifecycle_outside_component`);throw J.name="Svelte error",J}else throw Error("https://svelte.dev/e/lifecycle_outside_component")}function C40(){if(UQ){let Q=Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/async_derived_orphan")}function UT(){if(UQ){let Q=Error("bind_invalid_checkbox_value\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\nhttps://svelte.dev/e/bind_invalid_checkbox_value");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function I40(){if(UQ){let Q=Error(`derived_references_self
A derived value cannot reference itself recursively
https://svelte.dev/e/derived_references_self`);throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/derived_references_self")}function $T(Q,J,G){if(UQ){let H=Error(`each_key_duplicate
${G?`Keyed each block has duplicate key \`${G}\` at indexes ${Q} and ${J}`:`Keyed each block has duplicate key at indexes ${Q} and ${J}`}
https://svelte.dev/e/each_key_duplicate`);throw H.name="Svelte error",H}else throw Error("https://svelte.dev/e/each_key_duplicate")}function R40(Q,J,G){if(UQ){let H=Error(`each_key_volatile
Keyed each block has key that is not idempotent — the key for item at index ${Q} was \`${J}\` but is now \`${G}\`. Keys must be the same each time for a given item
https://svelte.dev/e/each_key_volatile`);throw H.name="Svelte error",H}else throw Error("https://svelte.dev/e/each_key_volatile")}function w40(Q){if(UQ){let J=Error(`effect_in_teardown
\`${Q}\` cannot be used inside an effect cleanup function
https://svelte.dev/e/effect_in_teardown`);throw J.name="Svelte error",J}else throw Error("https://svelte.dev/e/effect_in_teardown")}function E40(){if(UQ){let Q=Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/effect_in_unowned_derived")}function S40(Q){if(UQ){let J=Error(`effect_orphan
\`${Q}\` can only be used inside an effect (e.g. during component initialisation)
https://svelte.dev/e/effect_orphan`);throw J.name="Svelte error",J}else throw Error("https://svelte.dev/e/effect_orphan")}function T40(){if(UQ){let Q=Error(`effect_update_depth_exceeded
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
https://svelte.dev/e/effect_update_depth_exceeded`);throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/effect_update_depth_exceeded")}function k40(){if(UQ){let Q=Error(`hydration_failed
Failed to hydrate the application
https://svelte.dev/e/hydration_failed`);throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/hydration_failed")}function y40(Q){if(UQ){let J=Error(`props_invalid_value
Cannot do \`bind:${Q}={undefined}\` when \`${Q}\` has a fallback value
https://svelte.dev/e/props_invalid_value`);throw J.name="Svelte error",J}else throw Error("https://svelte.dev/e/props_invalid_value")}function v40(Q){if(UQ){let J=Error(`rune_outside_svelte
The \`${Q}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
https://svelte.dev/e/rune_outside_svelte`);throw J.name="Svelte error",J}else throw Error("https://svelte.dev/e/rune_outside_svelte")}function x40(){if(UQ){let Q=Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/state_descriptors_fixed")}function b40(){if(UQ){let Q=Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/state_prototype_fixed")}function g40(){if(UQ){let Q=Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/state_unsafe_mutation")}function h40(){if(UQ){let Q=Error("svelte_boundary_reset_onerror\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");throw Q.name="Svelte error",Q}else throw Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}var _40=1,f40=2,ZT=4,m40=8,u40=16,p40=1,l40=2,d40=4,c40=8,i40=16;var o40=1,n40=2;var DK="[",D4="[!",FT="[?",dH="]",sW={};var z9=Symbol("uninitialized"),wY=Symbol("filename"),a40=Symbol("hmr"),SO="http://www.w3.org/1999/xhtml";var GW="font-weight: bold",WW="font-weight: normal";function s40(Q){if(UQ)console.warn(`%c[svelte] await_reactivity_loss
%cDetected reactivity loss when reading \`${Q}\`. This happens when state is read in an async function after an earlier \`await\`
https://svelte.dev/e/await_reactivity_loss`,GW,WW);else console.warn("https://svelte.dev/e/await_reactivity_loss")}function r40(Q,J){if(UQ)console.warn(`%c[svelte] await_waterfall
%cAn async derived, \`${Q}\` (${J}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app
https://svelte.dev/e/await_waterfall`,GW,WW);else console.warn("https://svelte.dev/e/await_waterfall")}function t40(){if(UQ)console.warn(`%c[svelte] derived_inert
%cReading a derived belonging to a now-destroyed effect may result in stale values
https://svelte.dev/e/derived_inert`,GW,WW);else console.warn("https://svelte.dev/e/derived_inert")}function e40(Q,J,G){if(UQ)console.warn(`%c[svelte] hydration_attribute_changed
%cThe \`${Q}\` attribute on \`${J}\` changed its value between server and client renders. The client value, \`${G}\`, will be ignored in favour of the server value
https://svelte.dev/e/hydration_attribute_changed`,GW,WW);else console.warn("https://svelte.dev/e/hydration_attribute_changed")}function cH(Q){if(UQ)console.warn(`%c[svelte] hydration_mismatch
%c${Q?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${Q}`:"Hydration failed because the initial UI does not match what was rendered on the server"}
https://svelte.dev/e/hydration_mismatch`,GW,WW);else console.warn("https://svelte.dev/e/hydration_mismatch")}function QH0(){if(UQ)console.warn(`%c[svelte] lifecycle_double_unmount
%cTried to unmount a component that was not mounted
https://svelte.dev/e/lifecycle_double_unmount`,GW,WW);else console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function XH0(){if(UQ)console.warn("%c[svelte] select_multiple_invalid_value\n%cThe `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\nhttps://svelte.dev/e/select_multiple_invalid_value",GW,WW);else console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function TO(Q){if(UQ)console.warn(`%c[svelte] state_proxy_equality_mismatch
%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${Q}\` will produce unexpected results
https://svelte.dev/e/state_proxy_equality_mismatch`,GW,WW);else console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function JH0(){if(UQ)console.warn(`%c[svelte] state_proxy_unmount
%cTried to unmount a state proxy, rather than a component
https://svelte.dev/e/state_proxy_unmount`,GW,WW);else console.warn("https://svelte.dev/e/state_proxy_unmount")}function YH0(){if(UQ)console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",GW,WW);else console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}var eQ=!1;function k7(Q){eQ=Q}var y8;function J9(Q){if(Q===null)throw cH(),sW;return y8=Q}function yX(){return J9(d7(y8))}function YQ(Q){if(!eQ)return;if(d7(y8)!==null)throw cH(),sW;y8=Q}function v9(Q=1){if(eQ){var J=Q,G=y8;while(J--)G=d7(G);y8=G}}function HW(Q=!0){var J=0,G=y8;while(!0){if(G.nodeType===RY){var H=G.data;if(H===dH){if(J===0)return G;J-=1}else if(H===DK||H===D4||H[0]==="["&&!isNaN(Number(H.slice(1))))J+=1}var K=d7(G);if(Q)G.remove();G=K}}function wq(Q){if(!Q||Q.nodeType!==RY)throw cH(),sW;return Q.data}function kO(Q){return Q===this.v}function DT(Q,J){return Q!=Q?J==J:Q!==J||Q!==null&&typeof Q==="object"||typeof Q==="function"}function yO(Q){return!DT(Q,this.v)}var V7=!1,BW=!1,WG=!1;function GH0(){BW=!0}var Eq=null;function vX(Q,J){return Q.label=J,xO(Q.v,J),Q}function xO(Q,J){return Q?.[RO]?.(J),Q}function HG(Q){let J=Error(),G=kn0();if(G.length===0)return null;return G.unshift(`
`),BX(J,"stack",{value:G.join(`
`)}),BX(J,"name",{value:Q}),J}function kn0(){let Q=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let J=Error().stack;if(Error.stackTraceLimit=Q,!J)return[];let G=J.split(`
`),H=[];for(let K=0;K<G.length;K++){let z=G[K],q=z.replaceAll("\\","/");if(z.trim()==="Error")continue;if(z.includes("validate_each_keys"))return[];if(q.includes("svelte/src/internal")||q.includes("node_modules/.vite"))continue;H.push(z)}return H}function HH0(Q,J){if(!UQ)throw Error("invariant(...) was not guarded by if (DEV)");if(!Q)N40(J)}var d8=null;function rW(Q){d8=Q}var AW=null;function MK(Q){AW=Q}var BG=null;function bO(Q){BG=Q}function c7(Q,J=!1,G){if(d8={p:d8,i:!1,c:null,e:null,s:Q,x:null,r:aQ,l:BW&&!J?{s:null,u:null,$:[]}:null},UQ)d8.function=G,BG=G}function i7(Q){var J=d8,G=J.e;if(G!==null){J.e=null;for(var H of G)MT(H)}if(Q!==void 0)J.x=Q;if(J.i=!0,d8=J.p,UQ)BG=d8?.function??null;return Q??{}}function KW(){return!BW||d8!==null&&d8.l===null}var iH=[];function BH0(){var Q=iH;iH=[],$K(Q)}function y7(Q){if(iH.length===0&&!oH){var J=iH;queueMicrotask(()=>{if(J===iH)BH0()})}iH.push(Q)}function AH0(){while(iH.length>0)BH0()}var LT=new WeakMap;function gO(Q){var J=aQ;if(J===null)return P8.f|=IY,Q;if(UQ&&Q instanceof Error&&!LT.has(Q))LT.set(Q,yn0(Q,J));if((J.f&HJ)===0&&(J.f&JW)===0){if(UQ&&!J.parent&&Q instanceof Error)KH0(Q);throw Q}AG(Q,J)}function AG(Q,J){if(J!==null&&(J.f&o9)!==0)return;while(J!==null){if((J.f&ZK)!==0){if((J.f&HJ)===0)throw Q;try{J.b.error(Q);return}catch(G){Q=G}}J=J.parent}if(UQ&&Q instanceof Error)KH0(Q);throw Q}function yn0(Q,J){let G=wJ(Q,"message");if(G&&!G.configurable)return;var H=Sq?" ":"\t",K=`
${H}in ${J.fn?.name||"<unknown>"}`,z=J.ctx;while(z!==null)K+=`
${H}in ${z.function?.[wY].split("/").pop()}`,z=z.p;return{message:Q.message+`
${K}
`,stack:Q.stack?.split(`
`).filter((q)=>!q.includes("svelte/src/internal")).join(`
`)}}function KH0(Q){let J=LT.get(Q);if(J)BX(Q,"message",{value:J.message}),BX(Q,"stack",{value:J.stack})}var vn0=~(X9|z7|Q9);function Y9(Q,J){Q.f=Q.f&vn0|J}function LK(Q){if((Q.f&KX)!==0||Q.deps===null)Y9(Q,Q9);else Y9(Q,z7)}function zH0(Q){if(Q===null)return;for(let J of Q){if((J.f&D9)===0||(J.f&tJ)===0)continue;J.f^=tJ,zH0(J.deps)}}function hO(Q,J,G){if((Q.f&X9)!==0)J.add(Q);else if((Q.f&z7)!==0)G.add(Q);zH0(Q.deps),Y9(Q,Q9)}var VH0=!1,_O=!1,cSQ=Symbol("unmounted");function OT(Q){var J=_O;try{return _O=!1,[Q(),_O]}finally{_O=J}}function qH0(Q){let J=0,G=xX(0),H;if(UQ)vX(G,"createSubscriber version");return()=>{if(M4())c(G),q7(()=>{if(J===0)H=FQ(()=>Q(()=>nH(G)));return J+=1,()=>{y7(()=>{if(J-=1,J===0)H?.(),H=void 0,nH(G)})}})}}var bn0=SJ|YW;function PT(Q,J,G,H){new NT(Q,J,G,H)}class NT{parent;is_pending=!1;transform_error;#X;#Q=eQ?y8:null;#J;#B;#W;#H=null;#Y=null;#A=null;#G=null;#$=0;#z=0;#V=!1;#q=new Set;#F=new Set;#K=null;#L=qH0(()=>{if(this.#K=xX(this.#$),UQ)vX(this.#K,"$effect.pending()");return()=>{this.#K=null}});constructor(Q,J,G,H){if(this.#X=Q,this.#J=J,this.#B=(K)=>{var z=aQ;z.b=this,z.f|=ZK,G(K)},this.parent=aQ.b,this.transform_error=H??this.parent?.transform_error??((K)=>K),this.#W=QY(()=>{if(eQ){let K=this.#Q;yX();let z=K.data===D4;if(K.data.startsWith(FT)){let F=JSON.parse(K.data.slice(FT.length));this.#O(F)}else if(z)this.#N();else this.#D()}else this.#P()},bn0),eQ)this.#X=y8}#D(){try{this.#H=v7(()=>this.#B(this.#X))}catch(Q){this.error(Q)}}#O(Q){let J=this.#J.failed;if(!J)return;this.#A=v7(()=>{J(this.#X,()=>Q,()=>()=>{})})}#N(){let Q=this.#J.pending;if(!Q)return;this.is_pending=!0,this.#Y=v7(()=>Q(this.#X)),y7(()=>{var J=this.#G=document.createDocumentFragment(),G=$7();if(J.append(G),this.#H=this.#M(()=>{return v7(()=>this.#B(G))}),this.#z===0)this.#X.before(J),this.#G=null,zW(this.#Y,()=>{this.#Y=null}),this.#U(z8)})}#P(){try{if(this.is_pending=this.has_pending_snippet(),this.#z=0,this.#$=0,this.#H=v7(()=>{this.#B(this.#X)}),this.#z>0){var Q=this.#G=document.createDocumentFragment();OK(this.#H,Q);let J=this.#J.pending;this.#Y=v7(()=>J(this.#X))}else this.#U(z8)}catch(J){this.error(J)}}#U(Q){this.is_pending=!1,Q.transfer_effects(this.#q,this.#F)}defer_effect(Q){hO(Q,this.#q,this.#F)}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!this.#J.pending}#M(Q){var J=aQ,G=P8,H=d8;U7(this.#W),x7(this.#W),rW(this.#W.ctx);try{return qX.ensure(),Q()}catch(K){return gO(K),null}finally{U7(J),x7(G),rW(H)}}#Z(Q,J){if(!this.has_pending_snippet()){if(this.parent)this.parent.#Z(Q,J);return}if(this.#z+=Q,this.#z===0){if(this.#U(J),this.#Y)zW(this.#Y,()=>{this.#Y=null});if(this.#G)this.#X.before(this.#G),this.#G=null}}update_pending_count(Q,J){if(this.#Z(Q,J),this.#$+=Q,!this.#K||this.#V)return;this.#V=!0,y7(()=>{if(this.#V=!1,this.#K)KG(this.#K,this.#$)})}get_effect_pending(){return this.#L(),c(this.#K)}error(Q){if(!this.#J.onerror&&!this.#J.failed)throw Q;if(z8?.is_fork){if(this.#H)z8.skip_effect(this.#H);if(this.#Y)z8.skip_effect(this.#Y);if(this.#A)z8.skip_effect(this.#A);z8.oncommit(()=>{this.#j(Q)})}else this.#j(Q)}#j(Q){if(this.#H)N1(this.#H),this.#H=null;if(this.#Y)N1(this.#Y),this.#Y=null;if(this.#A)N1(this.#A),this.#A=null;if(eQ)J9(this.#Q),v9(),J9(HW());var J=this.#J.onerror;let G=this.#J.failed;var H=!1,K=!1;let z=()=>{if(H){YH0();return}if(H=!0,K)h40();if(this.#A!==null)zW(this.#A,()=>{this.#A=null});this.#M(()=>{this.#P()})},q=(F)=>{try{K=!0,J?.(F,z),K=!1}catch(D){AG(D,this.#W&&this.#W.parent)}if(G)this.#A=this.#M(()=>{try{return v7(()=>{var D=aQ;D.b=this,D.f|=ZK,G(this.#X,()=>F,()=>z)})}catch(D){return AG(D,this.#W.parent),null}})};y7(()=>{var F;try{F=this.transform_error(Q)}catch(D){AG(D,this.#W&&this.#W.parent);return}if(F!==null&&typeof F==="object"&&typeof F.then==="function")F.then(q,(D)=>AG(D,this.#W&&this.#W.parent));else q(F)})}}function fO(Q,J,G,H){let K=KW()?tW:VW;var z=Q.filter((I)=>!I.settled),q=J.map(K);if(UQ)q.forEach((I,R)=>{I.label=J[R].toString().replace("() => ","").replaceAll("$.eager(() => ","$state.eager(").replace(/\$\.get\((.+?)\)/g,(w,E)=>E)});if(G.length===0&&z.length===0){H(q);return}var F=aQ,D=UH0(),V=z.length===1?z[0].promise:z.length>1?Promise.all(z.map((I)=>I.promise)):null;function O(I){if((F.f&o9)!==0)return;D();try{H([...q,...I])}catch(R){AG(R,F)}PK()}var P=jT();if(G.length===0){V.then(()=>O([])).finally(P);return}function N(){Promise.all(G.map((I)=>IT(I))).then(O).catch((I)=>AG(I,F)).finally(P)}if(V)V.then(()=>{D(),N(),PK()});else N()}function UH0(){var Q=aQ,J=P8,G=d8,H=z8;if(UQ)var K=AW;return function(q=!0){if(U7(Q),x7(J),rW(G),q&&(Q.f&o9)===0)H?.activate(),H?.apply();if(UQ)CT(null),MK(K)}}function PK(Q=!0){if(U7(null),x7(null),rW(null),Q)z8?.deactivate();if(UQ)CT(null),MK(null)}function jT(){var Q=aQ,J=Q.b,G=z8,H=!!J?.is_rendered();return J?.update_pending_count(1,G),G.increment(H,Q),()=>{J?.update_pending_count(-1,G),G.decrement(H,Q)}}var TJ=null;function CT(Q){TJ=Q}var Tq=new Set;function tW(Q){var J=D9|X9;if(aQ!==null)aQ.f|=YW;let G={ctx:d8,deps:null,effects:null,equals:kO,f:J,fn:Q,reactions:null,rv:0,v:z9,wv:0,parent:aQ,ac:null};if(UQ&&WG)G.created=HG("created at");return G}var NK=Symbol("obsolete");function IT(Q,J,G){let H=aQ;if(H===null)C40();var K=void 0,z=xX(z9);if(UQ)z.label=J??Q.toString();var q=!P8,F=new Set;if(FH0(()=>{var D=aQ;if(UQ)TJ={effect:D,effect_deps:new Set,warned:!1};var V=IO();K=V.promise;try{Promise.resolve(Q()).then(V.resolve,(I)=>{if(I!==F4)V.reject(I)}).finally(PK)}catch(I){V.reject(I),PK()}if(UQ){if(TJ){if(D.deps!==null)for(let I=0;I<BJ;I+=1)TJ.effect_deps.add(D.deps[I]);if(n7!==null)for(let I=0;I<n7.length;I+=1)TJ.effect_deps.add(n7[I])}TJ=null}var O=z8;if(q){if((D.f&HJ)!==0)var P=jT();if(H.b?.is_rendered())O.async_deriveds.get(D)?.reject(NK);else for(let I of F.values())I.reject(NK);F.add(V),O.async_deriveds.set(D,V)}let N=(I,R=void 0)=>{if(UQ)TJ=null;if(P?.(),F.delete(V),R===NK)return;if(O.activate(),R)z.f|=IY,KG(z,R);else{if((z.f&IY)!==0)z.f^=IY;if(UQ&&G!==void 0&&!z.equals(I))Tq.add(z),setTimeout(()=>{if(Tq.has(z)&&(D.f&o9)===0)r40(z.label,G),Tq.delete(z)});KG(z,I)}O.deactivate()};V.promise.then(N,(I)=>N(null,I||"unknown"))}),o7(()=>{for(let D of F)D.reject(NK)}),UQ)z.f|=eJ;return new Promise((D)=>{function V(O){function P(){if(O===K)D(z);else V(K)}O.then(P,P)}V(K)})}function sH(Q){let J=tW(Q);if(!V7)pO(J);return J}function VW(Q){let J=tW(Q);return J.equals=yO,J}function $H0(Q){var J=Q.effects;if(J!==null){Q.effects=null;for(var G=0;G<J.length;G+=1)N1(J[G])}}var RT=[];function kq(Q){var J,G=aQ,H=Q.parent;if(!XY&&H!==null&&Q.v!==z9&&(H.f&(o9|P7))!==0)return t40(),Q.v;if(U7(H),UQ){let K=rH;mO(new Set);try{if(U4.call(RT,Q))I40();RT.push(Q),Q.f&=~tJ,$H0(Q),J=uO(Q)}finally{U7(G),mO(K),RT.pop()}}else try{Q.f&=~tJ,$H0(Q),J=uO(Q)}finally{U7(G)}return J}function wT(Q){var J=kq(Q);if(!Q.equals(J)){if(Q.wv=jK(),!z8?.is_fork||Q.deps===null){if(z8!==null)z8.capture(Q,J,!0),qW?.capture(Q,J,!0);else Q.v=J;if(Q.deps===null){Y9(Q,Q9);return}}}if(XY)return;if(a7!==null){if(M4()||z8?.is_fork)a7.set(Q,J)}else LK(Q)}function ZH0(Q){if(Q.effects===null)return;for(let J of Q.effects)if(J.teardown||J.ac){if(J.teardown?.(),J.ac?.abort(F4),J.fn!==null)J.teardown=XW;J.ac=null,tH(J,0),yq(J)}}function ET(Q){if(Q.effects===null)return;for(let J of Q.effects)if(J.teardown&&J.fn!==null)zG(J)}var lO=null,CK=null,z8=null,qW=null,a7=null,kT=null,oH=!1,ST=!1,eH=null,vq=null,DH0=0,TT=new Set,_n0=1;class qX{id=_n0++;#X=!1;linked=!0;#Q=null;#J=null;async_deriveds=new Map;current=new Map;previous=new Map;#B=new Set;#W=new Set;#H=0;#Y=new Map;#A=null;#G=[];#$=[];#z=new Set;#V=new Set;#q=new Map;#F=new Set;is_fork=!1;#K=!1;constructor(){if(CK===null)lO=CK=this;else CK.#J=this,this.#Q=CK;CK=this}#L(){if(this.is_fork)return!0;for(let G of this.#Y.keys()){var Q=G,J=!1;while(Q.parent!==null){if(this.#q.has(Q)){J=!0;break}Q=Q.parent}if(!J)return!0}return!1}skip_effect(Q){if(!this.#q.has(Q))this.#q.set(Q,{d:[],m:[]});this.#F.delete(Q)}unskip_effect(Q,J=(G)=>this.schedule(G)){var G=this.#q.get(Q);if(G){this.#q.delete(Q);for(var H of G.d)Y9(H,X9),J(H);for(H of G.m)Y9(H,z7),J(H)}this.#F.add(Q)}#D(){if(this.#X=!0,DH0++>1000)this.#Z(),fn0();if(UQ)for(let F of this.current.keys())TT.add(F);for(let F of this.#z)this.#V.delete(F),Y9(F,X9),this.schedule(F);for(let F of this.#V)Y9(F,z7),this.schedule(F);let Q=this.#G;this.#G=[],this.apply();var J=eH=[],G=[],H=vq=[];for(let F of Q)try{this.#O(F,J,G)}catch(D){if(PH0(F),!this.#L())this.discard();throw D}if(z8=null,H.length>0){var K=qX.ensure();for(let F of H)K.schedule(F)}if(eH=null,vq=null,this.#L()){this.#U(G),this.#U(J);for(let[F,D]of this.#q)OH0(F,D);if(H.length>0)z8.#D();return}let z=this.#N();if(z){this.#U(G),this.#U(J),z.#P(this);return}this.#z.clear(),this.#V.clear();for(let F of this.#B)F(this);this.#B.clear(),qW=this,MH0(G),MH0(J),qW=null,this.#A?.resolve();var q=z8;if(this.#H===0&&(this.#G.length===0||q!==null)){if(this.#Z(),V7)this.#M(),z8=q}if(this.#G.length>0)if(q!==null){let F=q;F.#G.push(...this.#G.filter((D)=>!F.#G.includes(D)))}else q=this;if(q!==null)q.#D()}#O(Q,J,G){Q.f^=Q9;var H=Q.first;while(H!==null){var K=H.f,z=(K&(l7|EJ))!==0,q=z&&(K&Q9)!==0,F=q||(K&P7)!==0||this.#q.has(H);if(!F&&H.fn!==null){if(z)H.f^=Q9;else if((K&JW)!==0)J.push(H);else if(V7&&(K&(aW|uH))!==0)G.push(H);else if(Q5(H)){if((K&AX)!==0)this.#V.add(H);zG(H)}var D=H.first;if(D!==null){H=D;continue}}while(H!==null){var V=H.next;if(V!==null){H=V;break}H=H.parent}}}#N(){var Q=this.#Q;while(Q!==null){if(!Q.is_fork){for(let[J,[,G]]of this.current)if(Q.current.has(J)&&!G)return Q}Q=Q.#Q}return null}#P(Q){for(let[G,H]of Q.current){if(!this.previous.has(G)&&Q.previous.has(G))this.previous.set(G,Q.previous.get(G));this.current.set(G,H)}for(let[G,H]of Q.async_deriveds){let K=this.async_deriveds.get(G);if(K)H.promise.then(K.resolve).catch(K.reject)}Q.async_deriveds.clear(),this.transfer_effects(Q.#z,Q.#V);let J=(G)=>{var H=G.reactions;if(H===null)return;for(let q of H){var K=q.f;if((K&D9)!==0)J(q);else{var z=q;if(K&(eJ|AX)&&!this.async_deriveds.has(z))this.#V.delete(z),Y9(z,X9),this.schedule(z)}}};for(let G of this.current.keys())J(G);this.oncommit(()=>Q.discard()),Q.#Z(),z8=this,this.#D()}#U(Q){for(var J=0;J<Q.length;J+=1)hO(Q[J],this.#z,this.#V)}capture(Q,J,G=!1){if(Q.v!==z9&&!this.previous.has(Q))this.previous.set(Q,Q.v);if((Q.f&IY)===0)this.current.set(Q,[J,G]),a7?.set(Q,J);if(!this.is_fork)Q.v=J}activate(){z8=this}deactivate(){z8=null,a7=null}flush(){try{if(UQ)TT.clear();ST=!0,z8=this,this.#D()}finally{if(DH0=0,kT=null,eH=null,vq=null,ST=!1,z8=null,a7=null,eW.clear(),UQ)for(let Q of TT)Q.updated=null}}discard(){for(let Q of this.#W)Q(this);this.#W.clear();for(let Q of this.async_deriveds.values())Q.reject(NK);this.#Z(),this.#A?.resolve()}register_created_effect(Q){this.#$.push(Q)}#M(){for(let O=lO;O!==null;O=O.#J){var Q=O.id<this.id,J=[];for(let[P,[N,I]]of this.current){if(O.current.has(P)){var G=O.current.get(P)[0];if(Q&&N!==G)O.current.set(P,[N,I]);else continue}J.push(P)}if(Q)for(let[P,N]of this.async_deriveds){let I=O.async_deriveds.get(P);if(I)N.promise.then(I.resolve).catch(I.reject)}var H=[...O.current.keys()].filter((P)=>!O.current.get(P)[1]);if(!O.#X||H.length===0)continue;var K=H.filter((P)=>!this.current.has(P));if(K.length===0){if(Q)O.discard()}else if(J.length>0){if(UQ&&!O.#K)HH0(O.#G.length===0,"Batch has scheduled roots");if(Q)for(let P of this.#F)O.unskip_effect(P,(N)=>{if((N.f&(AX|eJ))!==0)O.schedule(N);else O.#U([N])});O.activate();var z=new Set,q=new Map;for(var F of J)LH0(F,K,z,q);q=new Map;var D=[...O.current].filter(([P,N])=>{let I=this.current.get(P);if(!I)return!0;return I[0]!==N[0]||I[1]!==N[1]}).map(([P])=>P);if(D.length>0){for(let P of this.#$)if((P.f&(o9|P7|$4))===0&&yT(P,D,q))if((P.f&(eJ|AX))!==0)Y9(P,X9),O.schedule(P);else O.#z.add(P)}if(O.#G.length>0&&!O.#K){O.apply();for(var V of O.#G)O.#O(V,[],[]);O.#G=[]}O.deactivate()}}}increment(Q,J){if(this.#H+=1,Q){let G=this.#Y.get(J)??0;this.#Y.set(J,G+1)}}decrement(Q,J){if(this.#H-=1,Q){let G=this.#Y.get(J)??0;if(G===1)this.#Y.delete(J);else this.#Y.set(J,G-1)}if(this.#K)return;this.#K=!0,y7(()=>{if(this.#K=!1,this.linked)this.flush()})}transfer_effects(Q,J){for(let G of Q)this.#z.add(G);for(let G of J)this.#V.add(G);Q.clear(),J.clear()}oncommit(Q){this.#B.add(Q)}ondiscard(Q){this.#W.add(Q)}settled(){return(this.#A??=IO()).promise}static ensure(){if(z8===null){let Q=z8=new qX;if(!ST&&!oH)y7(()=>{if(!Q.#X)Q.flush()})}return z8}apply(){if(!V7||!this.is_fork&&this.#Q===null&&this.#J===null){a7=null;return}a7=new Map;for(let[J,[G]]of this.current)a7.set(J,G);for(let J=lO;J!==null;J=J.#J){if(J===this||J.is_fork)continue;var Q=!1;if(J.id<this.id)for(let[G,[,H]]of J.current){if(H)continue;if(this.current.has(G)){Q=!0;break}}if(!Q){for(let[G,H]of J.previous)if(!a7.has(G))a7.set(G,H)}}}schedule(Q){if(kT=Q,Q.b?.is_pending&&(Q.f&(JW|aW|uH))!==0&&(Q.f&HJ)===0){Q.b.defer_effect(Q);return}var J=Q;while(J.parent!==null){J=J.parent;var G=J.f;if(eH!==null&&J===aQ){if(V7)return;if((P8===null||(P8.f&D9)===0)&&!VH0)return}if((G&(EJ|l7))!==0){if((G&Q9)===0)return;J.f^=Q9}}this.#G.push(J)}#Z(){if(!this.linked)return;var Q=this.#Q,J=this.#J;if(Q===null)lO=J;else Q.#J=J;if(J===null)CK=Q;else J.#Q=Q;this.linked=!1}}function Q3(Q){var J=oH;oH=!0;try{var G;if(Q){if(z8!==null&&!z8.is_fork)z8.flush();G=Q()}while(!0){if(AH0(),z8===null)return G;z8.flush()}}finally{oH=J}}function fn0(){if(UQ){var Q=new Map;for(let G of z8.current.keys())for(let[H,K]of G.updated??[]){var J=Q.get(H);if(!J)J={error:K.error,count:0},Q.set(H,J);J.count+=K.count}for(let G of Q.values())if(G.error)console.error(G.error)}try{T40()}catch(G){if(UQ)BX(G,"stack",{value:""});AG(G,kT)}}var EY=null;function MH0(Q){var J=Q.length;if(J===0)return;var G=0;while(G<J){var H=Q[G++];if((H.f&(o9|P7))===0&&Q5(H)){if(EY=new Set,zG(H),H.deps===null&&H.first===null&&H.nodes===null&&H.teardown===null&&H.ac===null)vT(H);if(EY?.size>0){eW.clear();for(let K of EY){if((K.f&(o9|P7))!==0)continue;let z=[K],q=K.parent;while(q!==null){if(EY.has(q))EY.delete(q),z.push(q);q=q.parent}for(let F=z.length-1;F>=0;F--){let D=z[F];if((D.f&(o9|P7))!==0)continue;zG(D)}}EY.clear()}}}EY=null}function LH0(Q,J,G,H){if(G.has(Q))return;if(G.add(Q),Q.reactions!==null)for(let K of Q.reactions){let z=K.f;if((z&D9)!==0)LH0(K,J,G,H);else if((z&(eJ|AX))!==0&&(z&X9)===0&&yT(K,J,H))Y9(K,X9),xq(K)}}function yT(Q,J,G){let H=G.get(Q);if(H!==void 0)return H;if(Q.deps!==null)for(let K of Q.deps){if(U4.call(J,K))return!0;if((K.f&D9)!==0&&yT(K,J,G))return G.set(K,!0),!0}return G.set(Q,!1),!1}function xq(Q){z8.schedule(Q)}function OH0(Q,J){if((Q.f&l7)!==0&&(Q.f&Q9)!==0)return;if((Q.f&X9)!==0)J.d.push(Q);else if((Q.f&z7)!==0)J.m.push(Q);Y9(Q,Q9);var G=Q.first;while(G!==null)OH0(G,J),G=G.next}function PH0(Q){Y9(Q,Q9);var J=Q.first;while(J!==null)PH0(J),J=J.next}var rH=new Set,eW=new Map;function mO(Q){rH=Q}var xT=!1;function jH0(){xT=!0}function xX(Q,J){var G={f:0,v:Q,reactions:null,equals:kO,rv:0,wv:0};if(UQ&&WG)G.created=J??HG("created at"),G.updated=null,G.set_during_effect=!1,G.trace=null;return G}function UW(Q,J){let G=xX(Q,J);return pO(G),G}function dQ(Q,J=!1,G=!0){let H=xX(Q);if(!J)H.equals=yO;if(BW&&G&&d8!==null&&d8.l!==null)(d8.l.s??=[]).push(H);return H}function qQ(Q,J,G=!1){if(P8!==null&&(!AJ||(P8.f&$4)!==0)&&KW()&&(P8.f&(D9|AX|eJ|$4))!==0&&(VG===null||!VG.has(Q)))g40();let H=G?X5(J):J;if(UQ)xO(H,Q.label);return KG(Q,H,vq)}function KG(Q,J,G=null){if(!Q.equals(J)){eW.set(Q,XY?J:Q.v);var H=qX.ensure();if(H.capture(Q,J),UQ){if(WG||aQ!==null){Q.updated??=new Map;let K=(Q.updated.get("")?.count??0)+1;if(Q.updated.set("",{error:null,count:K}),WG||K>5){let z=HG("updated at");if(z!==null){let q=Q.updated.get(z.stack);if(!q)q={error:z,count:0},Q.updated.set(z.stack,q);q.count++}}}if(aQ!==null)Q.set_during_effect=!0}if((Q.f&D9)!==0){let K=Q;if((Q.f&X9)!==0)kq(K);if(a7===null)LK(K)}if(Q.wv=jK(),CH0(Q,X9,G),KW()&&aQ!==null&&(aQ.f&Q9)!==0&&(aQ.f&(l7|EJ))===0)if(JY===null)IH0([Q]);else JY.push(Q);if(!H.is_fork&&rH.size>0&&!xT)dO()}return J}function dO(){xT=!1;for(let Q of rH){if((Q.f&Q9)!==0)Y9(Q,z7);let J;try{J=Q5(Q)}catch{J=!0}if(J)zG(Q)}rH.clear()}function nH(Q){qQ(Q,Q.v+1)}function CH0(Q,J,G){var H=Q.reactions;if(H===null)return;var K=KW(),z=H.length;for(var q=0;q<z;q++){var F=H[q],D=F.f;if(!K&&F===aQ)continue;var V=(D&X9)===0;if(V)Y9(F,J);if((D&$4)!==0)rH.add(F);else if((D&D9)!==0){var O=F;if(a7?.delete(O),(D&tJ)===0){if(D&KX&&(aQ===null||(aQ.f&pH)===0))F.f|=tJ;CH0(O,z7,G)}}else if(V){var P=F;if((D&AX)!==0&&EY!==null)EY.add(P);if(G!==null)G.push(P);else xq(P)}}}var un0=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function X5(Q){if(typeof Q!=="object"||Q===null||T7 in Q)return Q;let J=mH(Q);if(J!==BT&&J!==L40)return Q;var G=new Map,H=QW(Q),K=UW(0),z=UQ&&WG?HG("created at"):null,q=L4,F=(P)=>{if(L4===q)return P();var N=P8,I=L4;x7(null),bT(q);var R=P();return x7(N),bT(I),R};if(H){if(G.set("length",UW(Q.length,z)),UQ)Q=ln0(Q)}var D="";let V=!1;function O(P){if(V)return;V=!0,D=P,vX(K,`${D} version`);for(let[N,I]of G)vX(I,X3(D,N));V=!1}return new Proxy(Q,{defineProperty(P,N,I){if(!("value"in I)||I.configurable===!1||I.enumerable===!1||I.writable===!1)x40();var R=G.get(N);if(R===void 0)F(()=>{var w=UW(I.value,z);if(G.set(N,w),UQ&&typeof N==="string")vX(w,X3(D,N));return w});else qQ(R,I.value,!0);return!0},deleteProperty(P,N){var I=G.get(N);if(I===void 0){if(N in P){let R=F(()=>UW(z9,z));if(G.set(N,R),nH(K),UQ)vX(R,X3(D,N))}}else qQ(I,z9),nH(K);return!0},get(P,N,I){if(N===T7)return Q;if(UQ&&N===RO)return O;var R=G.get(N),w=N in P;if(R===void 0&&(!w||wJ(P,N)?.writable))R=F(()=>{var T=X5(w?P[N]:z9),y=UW(T,z);if(UQ)vX(y,X3(D,N));return y}),G.set(N,R);if(R!==void 0){var E=c(R);return E===z9?void 0:E}return Reflect.get(P,N,I)},getOwnPropertyDescriptor(P,N){var I=Reflect.getOwnPropertyDescriptor(P,N);if(I&&"value"in I){var R=G.get(N);if(R)I.value=c(R)}else if(I===void 0){var w=G.get(N),E=w?.v;if(w!==void 0&&E!==z9)return{enumerable:!0,configurable:!0,value:E,writable:!0}}return I},has(P,N){if(N===T7)return!0;var I=G.get(N),R=I!==void 0&&I.v!==z9||Reflect.has(P,N);if(I!==void 0||aQ!==null&&(!R||wJ(P,N)?.writable)){if(I===void 0)I=F(()=>{var E=R?X5(P[N]):z9,T=UW(E,z);if(UQ)vX(T,X3(D,N));return T}),G.set(N,I);var w=c(I);if(w===z9)return!1}return R},set(P,N,I,R){var w=G.get(N),E=N in P;if(H&&N==="length")for(var T=I;T<w.v;T+=1){var y=G.get(T+"");if(y!==void 0)qQ(y,z9);else if(T in P){if(y=F(()=>UW(z9,z)),G.set(T+"",y),UQ)vX(y,X3(D,T))}}if(w===void 0){if(!E||wJ(P,N)?.writable){if(w=F(()=>UW(void 0,z)),UQ)vX(w,X3(D,N));qQ(w,X5(I)),G.set(N,w)}}else{E=w.v!==z9;var x=F(()=>X5(I));qQ(w,x)}var b=Reflect.getOwnPropertyDescriptor(P,N);if(b?.set)b.set.call(R,I);if(!E){if(H&&typeof N==="string"){var g=G.get("length"),l=Number(N);if(Number.isInteger(l)&&l>=g.v)qQ(g,l+1)}nH(K)}return!0},ownKeys(P){c(K);var N=Reflect.ownKeys(P).filter((w)=>{var E=G.get(w);return E===void 0||E.v!==z9});for(var[I,R]of G)if(R.v!==z9&&!(I in P))N.push(I);return N},setPrototypeOf(){b40()}})}function X3(Q,J){if(typeof J==="symbol")return`${Q}[Symbol(${J.description??""})]`;if(un0.test(J))return`${Q}.${J}`;return/^\d+$/.test(J)?`${Q}[${J}]`:`${Q}['${J}']`}function IK(Q){try{if(Q!==null&&typeof Q==="object"&&T7 in Q)return Q[T7]}catch{}return Q}function gT(Q,J){return Object.is(IK(Q),IK(J))}var pn0=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function ln0(Q){return new Proxy(Q,{get(J,G,H){var K=Reflect.get(J,G,H);if(!pn0.has(G))return K;return function(...z){jH0();var q=K.apply(this,z);return dO(),q}}})}function RH0(){let{prototype:Q,__svelte_cleanup:J}=Array;if(J)J();let{indexOf:G,lastIndexOf:H,includes:K}=Q;Q.indexOf=function(z,q){let F=G.call(this,z,q);if(F===-1){for(let D=q??0;D<this.length;D+=1)if(IK(this[D])===z){TO("array.indexOf(...)");break}}return F},Q.lastIndexOf=function(z,q){let F=H.call(this,z,q??this.length-1);if(F===-1){for(let D=0;D<=(q??this.length-1);D+=1)if(IK(this[D])===z){TO("array.lastIndexOf(...)");break}}return F},Q.includes=function(z,q){let F=K.call(this,z,q);if(!F){for(let D=0;D<this.length;D+=1)if(IK(this[D])===z){TO("array.includes(...)");break}}return F},Array.__svelte_cleanup=()=>{Q.indexOf=G,Q.lastIndexOf=H,Q.includes=K}}var hT,wH0,Sq,EH0,SH0;function cO(){if(hT!==void 0)return;hT=window,wH0=document,Sq=/Firefox/.test(navigator.userAgent);var Q=Element.prototype,J=Node.prototype,G=Text.prototype;if(EH0=wJ(J,"firstChild").get,SH0=wJ(J,"nextSibling").get,AT(Q))Q[jq]=void 0,Q[wO]=null,Q[Cq]=void 0,Q.__e=void 0;if(AT(G))G[Iq]=void 0;if(UQ)Q.__svelte_meta=null,RH0()}function $7(Q=""){return document.createTextNode(Q)}function UX(Q){return EH0.call(Q)}function d7(Q){return SH0.call(Q)}function GQ(Q,J){if(!eQ)return UX(Q);var G=UX(y8);if(G===null)G=y8.appendChild($7());else if(J&&G.nodeType!==lH){var H=$7();return G?.before(H),J9(H),H}if(J)bq(G);return J9(G),G}function $X(Q,J=!1){if(!eQ){var G=UX(Q);if(G instanceof Comment&&G.data==="")return d7(G);return G}if(J){if(y8?.nodeType!==lH){var H=$7();return y8?.before(H),J9(H),H}bq(y8)}return y8}function VQ(Q,J=1,G=!1){let H=eQ?y8:Q;var K;while(J--)K=H,H=d7(H);if(!eQ)return H;if(G){if(H?.nodeType!==lH){var z=$7();if(H===null)K?.after(z);else H.before(z);return J9(z),z}bq(H)}return J9(H),H}function RK(Q){Q.textContent=""}function iO(){if(!V7)return!1;if(EY!==null)return!1;var Q=aQ.f;return(Q&HJ)!==0}function $W(Q,J,G){if(J==null||J===SO)return G?document.createElement(Q,{is:G}):document.createElement(Q);return G?document.createElementNS(J,Q,{is:G}):document.createElementNS(J,Q)}function bq(Q){if(Q.nodeValue.length<65536)return;let J=Q.nextSibling;while(J!==null&&J.nodeType===lH)J.remove(),Q.nodeValue+=J.nodeValue,J=Q.nextSibling}function _T(Q){if(eQ&&UX(Q)!==null)RK(Q)}var TH0=!1;function oO(){if(!TH0)TH0=!0,document.addEventListener("reset",(Q)=>{Promise.resolve().then(()=>{if(!Q.defaultPrevented)for(let J of Q.target.elements)J[Z4]?.()})},{capture:!0})}function J5(Q){var J=P8,G=aQ;x7(null),U7(null);try{return Q()}finally{x7(J),U7(G)}}function gq(Q,J,G,H=G){Q.addEventListener(J,()=>J5(G));let K=Q[Z4];if(K)Q[Z4]=()=>{K(),H(!0)};else Q[Z4]=()=>H(!0);oO()}function mT(Q){if(aQ===null){if(P8===null)S40(Q);E40()}if(XY)w40(Q)}function dn0(Q,J){var G=J.last;if(G===null)J.last=J.first=Q;else G.next=Q,Q.prev=G,J.last=Q}function qG(Q,J){var G=aQ;if(UQ)while(G!==null&&(G.f&$4)!==0)G=G.parent;if(G!==null&&(G.f&P7)!==0)Q|=P7;var H={ctx:d8,deps:null,nodes:null,f:Q|X9|KX,first:null,fn:J,last:null,next:null,parent:G,b:G&&G.b,prev:null,teardown:null,wv:0,ac:null};if(UQ)H.component_function=BG;z8?.register_created_effect(H);var K=H;if((Q&JW)!==0)if(eH!==null)eH.push(H);else qX.ensure().schedule(H);else if(J!==null){try{zG(H)}catch(q){throw N1(H),q}if(K.deps===null&&K.teardown===null&&K.nodes===null&&K.first===K.last&&(K.f&YW)===0){if(K=K.first,(Q&AX)!==0&&(Q&SJ)!==0&&K!==null)K.f|=SJ}}if(K!==null){if(K.parent=G,G!==null)dn0(K,G);if(P8!==null&&(P8.f&D9)!==0&&(Q&EJ)===0){var z=P8;(z.effects??=[]).push(K)}}return H}function M4(){return P8!==null&&!AJ}function o7(Q){let J=qG(aW,null);return Y9(J,Q9),J.teardown=Q,J}function wK(Q){if(mT("$effect"),UQ)BX(Q,"name",{value:"$effect"});var J=aQ.f,G=!P8&&(J&l7)!==0&&d8!==null&&!d8.i;if(G){var H=d8;(H.e??=[]).push(Q)}else return MT(Q)}function MT(Q){return qG(JW|VT,Q)}function hq(Q){if(mT("$effect.pre"),UQ)BX(Q,"name",{value:"$effect.pre"});return qG(aW|VT,Q)}function uT(Q){qX.ensure();let J=qG(EJ|YW,Q);return()=>{N1(J)}}function kH0(Q){qX.ensure();let J=qG(EJ|YW,Q);return(G={})=>{return new Promise((H)=>{if(G.outro)zW(J,()=>{N1(J),H(void 0)});else N1(J),H(void 0)})}}function KJ(Q){return qG(JW,Q)}function YY(Q,J){var G=d8,H={effect:null,ran:!1,deps:Q};G.l.$.push(H),H.effect=q7(()=>{if(Q(),H.ran)return;H.ran=!0;var K=aQ;try{U7(K.parent),FQ(J)}finally{U7(K)}})}function J3(){var Q=d8;q7(()=>{for(var J of Q.l.$){J.deps();var G=J.effect;if((G.f&Q9)!==0&&G.deps!==null)Y9(G,z7);if(Q5(G))zG(G);J.ran=!1}})}function FH0(Q){return qG(eJ|YW,Q)}function q7(Q,J=0){return qG(aW|J,Q)}function C8(Q,J=[],G=[],H=[]){fO(H,J,G,(K)=>{qG(aW,()=>{Q(...K.map(c))})})}function QY(Q,J=0){var G=qG(AX|J,Q);if(UQ)G.dev_stack=AW;return G}function v7(Q){return qG(l7|YW,Q)}function pT(Q){var J=Q.teardown;if(J!==null){let G=XY,H=P8;fT(!0),x7(null);try{J.call(null)}finally{fT(G),x7(H)}}}function yq(Q,J=!1){var G=Q.first;Q.first=Q.last=null;while(G!==null){let K=G.ac;if(K!==null)J5(()=>{K.abort(F4)});var H=G.next;if((G.f&EJ)!==0)G.parent=null;else N1(G,J);G=H}}function yH0(Q){var J=Q.first;while(J!==null){var G=J.next;if((J.f&l7)===0)N1(J);J=G}}function N1(Q,J=!0){var G=!1;if((J||(Q.f&zT)!==0)&&Q.nodes!==null&&Q.nodes.end!==null)vH0(Q.nodes.start,Q.nodes.end),G=!0;Q.f|=FK,yq(Q,J&&!G),tH(Q,0);var H=Q.nodes&&Q.nodes.t;if(H!==null)for(let z of H)z.stop();pT(Q),Q.f^=FK,Q.f|=o9;var K=Q.parent;if(K!==null&&K.first!==null)vT(Q);if(UQ)Q.component_function=null;Q.next=Q.prev=Q.teardown=Q.ctx=Q.deps=Q.fn=Q.nodes=Q.ac=Q.b=null}function vH0(Q,J){while(Q!==null){var G=Q===J?null:d7(Q);Q.remove(),Q=G}}function vT(Q){var{parent:J,prev:G,next:H}=Q;if(G!==null)G.next=H;if(H!==null)H.prev=G;if(J!==null){if(J.first===Q)J.first=H;if(J.last===Q)J.last=G}}function zW(Q,J,G=!0){var H=[];xH0(Q,H,!0);var K=()=>{if(G)N1(Q);if(J)J()},z=H.length;if(z>0){var q=()=>--z||K();for(var F of H)F.out(q)}else K()}function xH0(Q,J,G){if((Q.f&P7)!==0)return;Q.f^=P7;var H=Q.nodes&&Q.nodes.t;if(H!==null){for(let F of H)if(F.is_global||G)J.push(F)}var K=Q.first;while(K!==null){var z=K.next;if((K.f&EJ)===0){var q=(K.f&SJ)!==0||(K.f&l7)!==0&&(Q.f&AX)!==0;xH0(K,J,q?G:!1)}K=z}}function EK(Q){bH0(Q,!0)}function bH0(Q,J){if((Q.f&P7)===0)return;if(Q.f^=P7,(Q.f&Q9)===0)Y9(Q,X9),qX.ensure().schedule(Q);var G=Q.first;while(G!==null){var H=G.next,K=(G.f&SJ)!==0||(G.f&l7)!==0;bH0(G,K?J:!1),G=H}var z=Q.nodes&&Q.nodes.t;if(z!==null){for(let q of z)if(q.is_global||J)q.in()}}function OK(Q,J){if(!Q.nodes)return;var G=Q.nodes.start,H=Q.nodes.end;while(G!==null){var K=G===H?null:d7(G);J.append(G),G=K}}var gH0=null;var nO=!1,XY=!1;function fT(Q){XY=Q}var P8=null,AJ=!1;function x7(Q){P8=Q}var aQ=null;function U7(Q){aQ=Q}var VG=null;function pO(Q){if(P8!==null&&(!V7||(P8.f&D9)!==0))(VG??=new Set).add(Q)}var n7=null,BJ=0,JY=null;function IH0(Q){JY=Q}var hH0=1,Y3=0,L4=Y3;function bT(Q){L4=Q}function jK(){return++hH0}function Q5(Q){var J=Q.f;if((J&X9)!==0)return!0;if(J&D9)Q.f&=~tJ;if((J&z7)!==0){var G=Q.deps,H=G.length;for(var K=0;K<H;K++){var z=G[K];if(Q5(z))wT(z);if(z.wv>Q.wv)return!0}if((J&KX)!==0&&a7===null)Y9(Q,Q9)}return!1}function _H0(Q,J,G=!0){var H=Q.reactions;if(H===null)return;if(!V7&&VG!==null&&VG.has(Q))return;for(var K=0;K<H.length;K++){var z=H[K];if((z.f&D9)!==0)_H0(z,J,!1);else if(J===z){if(G)Y9(z,X9);else if((z.f&Q9)!==0)Y9(z,z7);xq(z)}}}function uO(Q){var J=n7,G=BJ,H=JY,K=P8,z=VG,q=d8,F=AJ,D=L4,V=Q.f;if(n7=null,BJ=0,JY=null,P8=(V&(l7|EJ))===0?Q:null,VG=null,rW(Q.ctx),AJ=!1,L4=++Y3,Q.ac!==null)J5(()=>{Q.ac.abort(F4)}),Q.ac=null;try{Q.f|=pH;var O=Q.fn,P=O();Q.f|=HJ;var N=Q.deps,I=z8?.is_fork;if(n7!==null){var R;if(!I)tH(Q,BJ);if(N!==null&&BJ>0){N.length=BJ+n7.length;for(R=0;R<n7.length;R++)N[BJ+R]=n7[R]}else Q.deps=N=n7;if(M4()&&(Q.f&KX)!==0)for(R=BJ;R<N.length;R++)(N[R].reactions??=[]).push(Q)}else if(!I&&N!==null&&BJ<N.length)tH(Q,BJ),N.length=BJ;if(KW()&&JY!==null&&!AJ&&N!==null&&(Q.f&(D9|z7|X9))===0)for(R=0;R<JY.length;R++)_H0(JY[R],Q);if(K!==null&&K!==Q){if(Y3++,K.deps!==null)for(let w=0;w<G;w+=1)K.deps[w].rv=Y3;if(J!==null)for(let w of J)w.rv=Y3;if(JY!==null)if(H===null)H=JY;else H.push(...JY)}if((Q.f&IY)!==0)Q.f^=IY;return P}catch(w){return gO(w)}finally{Q.f^=pH,n7=J,BJ=G,JY=H,P8=K,VG=z,rW(q),AJ=F,L4=D}}function cn0(Q,J){let G=J.reactions;if(G!==null){var H=M40.call(G,Q);if(H!==-1){var K=G.length-1;if(K===0)G=J.reactions=null;else G[H]=G[K],G.pop()}}if(G===null&&(J.f&D9)!==0&&(n7===null||!U4.call(n7,J))){var z=J;if((z.f&KX)!==0)z.f^=KX,z.f&=~tJ;if(z.v!==z9)LK(z);ZH0(z),tH(z,0)}}function tH(Q,J){var G=Q.deps;if(G===null)return;for(var H=J;H<G.length;H++)cn0(Q,G[H])}function zG(Q){var J=Q.f;if((J&o9)!==0)return;Y9(Q,Q9);var G=aQ,H=nO;if(aQ=Q,nO=!0,UQ){var K=BG;bO(Q.component_function);var z=AW;MK(Q.dev_stack??AW)}try{if((J&(AX|uH))!==0)yH0(Q);else yq(Q);pT(Q);var q=uO(Q);if(Q.teardown=typeof q==="function"?q:null,Q.wv=hH0,UQ&&WG&&(Q.f&X9)!==0&&Q.deps!==null){for(var F of Q.deps)if(F.set_during_effect)F.wv=jK(),F.set_during_effect=!1}}finally{if(nO=H,aQ=G,UQ)bO(K),MK(z)}}async function aH(){if(V7)return new Promise((Q)=>{requestAnimationFrame(()=>Q()),setTimeout(()=>Q())});await Promise.resolve(),Q3()}function c(Q){var J=Q.f,G=(J&D9)!==0;if(gH0?.add(Q),P8!==null&&!AJ){var H=aQ!==null&&(aQ.f&o9)!==0;if(!H&&(VG===null||!VG.has(Q))){var K=P8.deps;if((P8.f&pH)!==0){if(Q.rv<Y3)if(Q.rv=Y3,n7===null&&K!==null&&K[BJ]===Q)BJ++;else if(n7===null)n7=[Q];else n7.push(Q)}else{if(P8.deps??=[],!U4.call(P8.deps,Q))P8.deps.push(Q);var z=Q.reactions;if(z===null)Q.reactions=[P8];else if(!U4.call(z,P8))z.push(P8)}}}if(UQ){if(!AJ&&TJ&&z8===null&&qW===null&&!TJ.warned&&(TJ.effect.f&pH)===0&&!TJ.effect_deps.has(Q)){TJ.warned=!0,s40(Q.label);var q=HG("traced at");if(q)console.warn(q)}if(Tq.delete(Q),WG&&!AJ&&Eq!==null&&P8!==null&&Eq.reaction===P8){if(Q.trace)Q.trace();else if(q=HG("traced at"),q){var F=Eq.entries.get(Q);if(F===void 0)F={traces:[]},Eq.entries.set(Q,F);var D=F.traces[F.traces.length-1];if(q.stack!==D?.stack)F.traces.push(q)}}}if(XY&&eW.has(Q))return eW.get(Q);if(G){var V=Q;if(XY){var O=V.v;if((V.f&Q9)===0&&V.reactions!==null||mH0(V))O=kq(V);return eW.set(V,O),O}var P=(V.f&KX)===0&&!AJ&&P8!==null&&(nO||(P8.f&KX)!==0),N=(V.f&HJ)===0;if(Q5(V)){if(P)V.f|=KX;wT(V)}if(P&&!N)ET(V),fH0(V)}if(a7?.has(Q))return a7.get(Q);if((Q.f&IY)!==0)throw Q.v;return Q.v}function fH0(Q){if(Q.f|=KX,Q.deps===null)return;for(let J of Q.deps)if((J.reactions??=[]).push(Q),(J.f&D9)!==0&&(J.f&KX)===0)ET(J),fH0(J)}function mH0(Q){if(Q.v===z9)return!0;if(Q.deps===null)return!1;for(let J of Q.deps){if(eW.has(J))return!0;if((J.f&D9)!==0&&mH0(J))return!0}return!1}function kJ(Q){return Q&&c(Q)}function FQ(Q){var J=AJ;try{return AJ=!0,Q()}finally{AJ=J}}function yJ(Q){if(typeof Q!=="object"||!Q||Q instanceof EventTarget)return;if(T7 in Q)aO(Q);else if(!Array.isArray(Q))for(let J in Q){let G=Q[J];if(typeof G==="object"&&G&&T7 in G)aO(G)}}function aO(Q,J=new Set){if(typeof Q==="object"&&Q!==null&&!(Q instanceof EventTarget)&&!J.has(Q)){if(J.add(Q),Q instanceof Date)Q.getTime();for(let H in Q)try{aO(Q[H],J)}catch(K){}let G=mH(Q);if(G!==Object.prototype&&G!==Array.prototype&&G!==Map.prototype&&G!==Set.prototype&&G!==Date.prototype){let H=CO(G);for(let K in H){let z=H[K].get;if(z)try{z.call(Q)}catch(q){}}}}}var on0=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"];var fyQ=[...on0,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var nn0=["touchstart","touchmove"];function uH0(Q){return nn0.includes(Q)}var an0=["$state","$state.raw","$derived","$derived.by"],myQ=[...an0,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];var lH0=new Map;function dH0(Q,J){var G=lH0.get(Q);if(!G)G=new Set,lH0.set(Q,G);G.add(J)}var SK=Symbol("events"),lT=new Set,sO=new Set;function oH0(Q,J,G,H={}){function K(z){if(!H.capture)tO.call(J,z);if(!z.cancelBubble)return J5(()=>{return G?.call(this,z)})}if(Q.startsWith("pointer")||Q.startsWith("touch")||Q==="wheel")y7(()=>{J.addEventListener(Q,K,H)});else J.addEventListener(Q,K,H);return K}function N8(Q,J,G,H,K){var z={capture:H,passive:K},q=oH0(Q,J,G,z);if(J===document.body||J===window||J===document||J instanceof HTMLMediaElement)o7(()=>{J.removeEventListener(Q,q,z)})}function TK(Q,J,G){(J[SK]??={})[Q]=G}function rO(Q){for(var J=0;J<Q.length;J++)lT.add(Q[J]);for(var G of sO)G(Q)}var iH0=null;function tO(Q){var J=this,G=J.ownerDocument,H=Q.type,K=Q.composedPath?.()||[],z=K[0]||Q.target;iH0=Q;var q=0,F=iH0===Q&&Q[SK];if(F){var D=K.indexOf(F);if(D!==-1&&(J===document||J===window)){Q[SK]=J;return}var V=K.indexOf(J);if(V===-1)return;if(D<=V)q=D}if(z=K[q]||Q.target,z===J)return;BX(Q,"currentTarget",{configurable:!0,get(){return z||G}});var O=P8,P=aQ;x7(null),U7(null);try{var N,I=[];while(z!==null){if(z===J)break;try{var R=z[SK]?.[H];if(R!=null&&(!z.disabled||Q.target===z))R.call(z,Q)}catch(w){if(N)I.push(w);else N=w}if(Q.cancelBubble)break;q++,z=q<K.length?K[q]:null}if(N){for(let w of I)queueMicrotask(()=>{throw w});throw N}}finally{Q[SK]=J,delete Q.currentTarget,x7(O),U7(P)}}var rn0=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy("svelte-trusted-html",{createHTML:(Q)=>{return Q}});function nH0(Q){return rn0?.createHTML(Q)??Q}function dT(Q){var J=$W("template");return J.innerHTML=nH0(Q.replaceAll("<!>","<!---->")),J.content}function GY(Q,J){var G=aQ;if(G.nodes===null)G.nodes={start:Q,end:J,a:null,t:null}}function oQ(Q,J){var G=(J&o40)!==0,H=(J&n40)!==0,K,z=!Q.startsWith("<!>");return()=>{if(eQ)return GY(y8,null),y8;if(K===void 0){if(K=dT(z?Q:"<!>"+Q),!G)K=UX(K)}var q=H||Sq?document.importNode(K,!0):K.cloneNode(!0);if(G){var F=UX(q),D=q.lastChild;GY(F,D)}else GY(q,q);return q}}function Y5(Q=""){if(!eQ){var J=$7(Q+"");return GY(J,J),J}var G=y8;if(G.nodeType!==lH)G.before(G=$7()),J9(G);else bq(G);return GY(G,G),G}function _q(){if(eQ)return GY(y8,null),y8;var Q=document.createDocumentFragment(),J=document.createComment(""),G=$7();return Q.append(J,G),GY(J,G),Q}function TQ(Q,J){if(eQ){var G=aQ;if((G.f&HJ)===0||G.nodes.end===null)G.nodes.end=y8;yX();return}if(Q===null)return;Q.before(J)}var iT=!0;function q8(Q,J){var G=J==null?"":typeof J==="object"?`${J}`:J;if(G!==(Q[Iq]??=Q.nodeValue))Q[Iq]=G,Q.nodeValue=`${G}`}function O4(Q,J){return aH0(Q,J)}function nT(Q,J){cO(),J.intro=J.intro??!1;let G=J.target,H=eQ,K=y8;try{var z=UX(G);while(z&&(z.nodeType!==RY||z.data!==DK))z=d7(z);if(!z)throw sW;k7(!0),J9(z);let q=aH0(Q,{...J,anchor:z});return k7(!1),q}catch(q){if(q instanceof Error&&q.message.split(`
`).some((F)=>F.startsWith("https://svelte.dev/e/")))throw q;if(q!==sW)console.warn("Failed to hydrate: ",q);if(J.recover===!1)k40();return cO(),RK(G),k7(!1),O4(Q,J)}finally{k7(H),J9(K)}}var eO=new Map;function aH0(Q,{target:J,anchor:G,props:H={},events:K,context:z,intro:q=!0,transformError:F}){cO();var D=void 0,V=kH0(()=>{var O=G??J.appendChild($7());PT(O,{pending:()=>{}},(I)=>{c7({});var R=d8;if(z)R.c=z;if(K)H.$$events=K;if(eQ)GY(I,null);if(iT=q,D=Q(I,H)||{},iT=!0,eQ){if(aQ.nodes.end=y8,y8===null||y8.nodeType!==RY||y8.data!==dH)throw cH(),sW}i7()},F);var P=new Set,N=(I)=>{for(var R=0;R<I.length;R++){var w=I[R];if(P.has(w))continue;P.add(w);var E=uH0(w);for(let x of[J,document]){var T=eO.get(x);if(T===void 0)T=new Map,eO.set(x,T);var y=T.get(w);if(y===void 0)x.addEventListener(w,tO,{passive:E}),T.set(w,1);else T.set(w,y+1)}}};return N(UK(lT)),sO.add(N),()=>{for(var I of P)for(let E of[J,document]){var R=eO.get(E),w=R.get(I);if(--w==0){if(E.removeEventListener(I,tO),R.delete(I),R.size===0)eO.delete(E)}else R.set(I,w)}if(sO.delete(N),O!==G)O.parentNode?.removeChild(O)}});return oT.set(D,V),D}var oT=new WeakMap;function G3(Q,J){let G=oT.get(Q);if(G)return oT.delete(Q),G(J);if(UQ)if(T7 in Q)JH0();else QH0();return Promise.resolve()}class P4{anchor;#X=new Map;#Q=new Map;#J=new Map;#B=new Set;#W=!0;constructor(Q,J=!0){this.anchor=Q,this.#W=J}#H=(Q)=>{if(!this.#X.has(Q))return;var J=this.#X.get(Q),G=this.#Q.get(J);if(G)EK(G),this.#B.delete(J);else{var H=this.#J.get(J);if(H){if(EK(H.effect),this.#Q.set(J,H.effect),this.#J.delete(J),UQ)H.fragment.lastChild[qT]=this.anchor;H.fragment.lastChild.remove(),this.anchor.before(H.fragment),G=H.effect}}for(let[K,z]of this.#X){if(this.#X.delete(K),K===Q)break;let q=this.#J.get(z);if(q)N1(q.effect),this.#J.delete(z)}for(let[K,z]of this.#Q){if(K===J||this.#B.has(K))continue;let q=()=>{if(Array.from(this.#X.values()).includes(K)){var D=document.createDocumentFragment();OK(z,D),D.append($7()),this.#J.set(K,{effect:z,fragment:D})}else N1(z);this.#B.delete(K),this.#Q.delete(K)};if(this.#W||!G)this.#B.add(K),zW(z,q,!1);else q()}};#Y=(Q)=>{this.#X.delete(Q);let J=Array.from(this.#X.values());for(let[G,H]of this.#J)if(!J.includes(G))N1(H.effect),this.#J.delete(G)};ensure(Q,J){var G=z8,H=iO();if(J&&!this.#Q.has(Q)&&!this.#J.has(Q))if(H){var K=document.createDocumentFragment(),z=$7();K.append(z),this.#J.set(Q,{effect:v7(()=>J(z)),fragment:K})}else this.#Q.set(Q,v7(()=>J(this.anchor)));if(this.#X.set(G,Q),H){for(let[q,F]of this.#Q)if(q===Q)G.unskip_effect(F);else G.skip_effect(F);for(let[q,F]of this.#J)if(q===Q)G.unskip_effect(F.effect);else G.skip_effect(F.effect);G.oncommit(this.#H),G.ondiscard(this.#Y)}else{if(eQ)this.anchor=y8;this.#H(G)}}}function m8(Q,J,G=!1){var H;if(eQ)H=y8,yX();var K=new P4(Q),z=G?SJ:0;function q(F,D){if(eQ){var V=wq(H);if(F!==parseInt(V.substring(1))){var O=HW();J9(O),K.anchor=O,k7(!1),K.ensure(F,D),k7(!0);return}}K.ensure(F,D)}QY(()=>{var F=!1;if(J((D,V=0)=>{F=!0,q(V,D)}),!F)q(-1,null)},z)}var dxQ=Symbol("NaN");function Xa0(Q,J,G){var H=[],K=J.length,z,q=J.length;for(var F=0;F<K;F++){let P=J[F];zW(P,()=>{if(z){if(z.pending.delete(P),z.done.add(P),z.pending.size===0){var N=Q.outrogroups;if(aT(Q,UK(z.done)),N.delete(z),N.size===0)Q.outrogroups=null}}else q-=1},!1)}if(q===0){var D=H.length===0&&G!==null;if(D){var V=G,O=V.parentNode;RK(O),O.append(V),Q.items.clear()}aT(Q,J,!D)}else z={pending:new Set(J),done:new Set},(Q.outrogroups??=new Set).add(z)}function aT(Q,J,G=!0){var H;if(Q.pending.size>0){H=new Set;for(let q of Q.pending.values())for(let F of q)H.add(Q.items.get(F).e)}for(var K=0;K<J.length;K++){var z=J[K];if(H?.has(z)){z.f|=GG;let q=document.createDocumentFragment();OK(z,q)}else N1(J[K],G)}}var sH0;function WY(Q,J,G,H,K,z=null){var q=Q,F=new Map,D=(J&ZT)!==0;if(D){var V=Q;q=eQ?J9(UX(V)):V.appendChild($7())}if(eQ)yX();var O=null,P=VW(()=>{var x=G();return QW(x)?x:x==null?[]:UK(x)});if(UQ)vX(P,"{#each ...}");var N,I=new Map,R=!0;function w(x){if((y.effect.f&o9)!==0)return;if(y.pending.delete(x),y.fallback=O,Ja0(y,N,q,J,H),O!==null)if(N.length===0)if((O.f&GG)===0)EK(O);else O.f^=GG,mq(O,null,q);else zW(O,()=>{O=null})}function E(x){y.pending.delete(x)}var T=QY(()=>{N=c(P);var x=N.length;let b=!1;if(eQ){var g=wq(q)===D4;if(g!==(x===0))q=HW(),J9(q),k7(!1),b=!0}var l=new Set,_=z8,a=iO();for(var r=0;r<x;r+=1){if(eQ&&y8.nodeType===RY&&y8.data===dH)q=y8,b=!0,k7(!1);var f0=N[r],t=H(f0,r);if(UQ){var p0=H(f0,r);if(t!==p0)R40(String(r),String(t),String(p0))}var u0=R?null:F.get(t);if(u0){if(u0.v)KG(u0.v,f0);if(u0.i)KG(u0.i,r);if(a)_.unskip_effect(u0.e)}else{if(u0=Ya0(F,R?q:sH0??=$7(),f0,t,r,K,J,G),!R)u0.e.f|=GG;F.set(t,u0)}l.add(t)}if(x===0&&z&&!O)if(R)O=v7(()=>z(q));else O=v7(()=>z(sH0??=$7())),O.f|=GG;if(x>l.size)if(UQ)Ga0(N,H);else $T("","","");if(eQ&&x>0)J9(HW());if(!R)if(I.set(_,l),a){for(let[d,n]of F)if(!l.has(d))_.skip_effect(n.e);_.oncommit(w),_.ondiscard(E)}else w(_);if(b)k7(!0);c(P)}),y={effect:T,flags:J,items:F,pending:I,outrogroups:null,fallback:O};if(R=!1,eQ)q=y8}function fq(Q){while(Q!==null&&(Q.f&l7)===0)Q=Q.next;return Q}function Ja0(Q,J,G,H,K){var z=(H&m40)!==0,q=J.length,F=Q.items,D=fq(Q.effect.first),V,O=null,P,N=[],I=[],R,w,E,T;if(z){for(T=0;T<q;T+=1)if(R=J[T],w=K(R,T),E=F.get(w).e,(E.f&GG)===0)E.nodes?.a?.measure(),(P??=new Set).add(E)}for(T=0;T<q;T+=1){if(R=J[T],w=K(R,T),E=F.get(w).e,Q.outrogroups!==null)for(let f0 of Q.outrogroups)f0.pending.delete(E),f0.done.delete(E);if((E.f&P7)!==0){if(EK(E),z)E.nodes?.a?.unfix(),(P??=new Set).delete(E)}if((E.f&GG)!==0)if(E.f^=GG,E===D)mq(E,null,G);else{var y=O?O.next:D;if(E===Q.effect.last)Q.effect.last=E.prev;if(E.prev)E.prev.next=E.next;if(E.next)E.next.prev=E.prev;N4(Q,O,E),N4(Q,E,y),mq(E,y,G),O=E,N=[],I=[],D=fq(O.next);continue}if(E!==D){if(V!==void 0&&V.has(E)){if(N.length<I.length){var x=I[0],b;O=x.prev;var g=N[0],l=N[N.length-1];for(b=0;b<N.length;b+=1)mq(N[b],x,G);for(b=0;b<I.length;b+=1)V.delete(I[b]);N4(Q,g.prev,l.next),N4(Q,O,g),N4(Q,l,x),D=x,O=l,T-=1,N=[],I=[]}else V.delete(E),mq(E,D,G),N4(Q,E.prev,E.next),N4(Q,E,O===null?Q.effect.first:O.next),N4(Q,O,E),O=E;continue}N=[],I=[];while(D!==null&&D!==E)(V??=new Set).add(D),I.push(D),D=fq(D.next);if(D===null)continue}if((E.f&GG)===0)N.push(E);O=E,D=fq(E.next)}if(Q.outrogroups!==null){for(let f0 of Q.outrogroups)if(f0.pending.size===0)aT(Q,UK(f0.done)),Q.outrogroups?.delete(f0);if(Q.outrogroups.size===0)Q.outrogroups=null}if(D!==null||V!==void 0){var _=[];if(V!==void 0){for(E of V)if((E.f&P7)===0)_.push(E)}while(D!==null){if((D.f&P7)===0&&D!==Q.fallback)_.push(D);D=fq(D.next)}var a=_.length;if(a>0){var r=(H&ZT)!==0&&q===0?G:null;if(z){for(T=0;T<a;T+=1)_[T].nodes?.a?.measure();for(T=0;T<a;T+=1)_[T].nodes?.a?.fix()}Xa0(Q,_,r)}}if(z)y7(()=>{if(P===void 0)return;for(E of P)E.nodes?.a?.apply()})}function Ya0(Q,J,G,H,K,z,q,F){var D=(q&_40)!==0?(q&u40)===0?dQ(G,!1,!1):xX(G):null,V=(q&f40)!==0?xX(K):null;if(UQ&&D)D.trace=()=>{F()[V?.v??K]};return{v:D,i:V,e:v7(()=>{return z(J,D??G,V??K,F),()=>{Q.delete(H)}})}}function mq(Q,J,G){if(!Q.nodes)return;var H=Q.nodes.start,K=Q.nodes.end,z=J&&(J.f&GG)===0?J.nodes.start:G;while(H!==null){var q=d7(H);if(z.before(H),H===K)return;H=q}}function N4(Q,J,G){if(J===null)Q.effect.first=G;else J.next=G;if(G===null)Q.effect.last=J;else G.prev=J}function Ga0(Q,J){let G=new Map,H=Q.length;for(let K=0;K<H;K++){let z=J(Q[K],K);if(G.has(z)){let q=String(G.get(z)),F=String(K),D=String(z);if(D.startsWith("[object "))D=null;$T(q,F,D)}G.set(z,K)}}function bX(Q,J){KJ(()=>{var G=Q.getRootNode(),H=G.host?G:G.head??G.ownerDocument.head;if(!H.querySelector("#"+J.hash)){let K=$W("style");if(K.id=J.hash,K.textContent=J.code,H.appendChild(K),UQ)dH0(J.hash,K)}})}var rH0=[...`
\r\f \v\uFEFF`];function eH0(Q,J,G){var H=Q==null?"":""+Q;if(J)H=H?H+" "+J:J;if(G){for(var K of Object.keys(G))if(G[K])H=H?H+" "+K:K;else if(H.length){var z=K.length,q=0;while((q=H.indexOf(K,q))>=0){var F=q+z;if((q===0||rH0.includes(H[q-1]))&&(F===H.length||rH0.includes(H[F])))H=(q===0?"":H.substring(0,q))+H.substring(F+1);else q=F}}}return H===""?null:H}function tH0(Q,J=!1){var G=J?" !important;":";",H="";for(var K of Object.keys(Q)){var z=Q[K];if(z!=null&&z!=="")H+=" "+K+": "+z+G}return H}function sT(Q){if(Q[0]!=="-"||Q[1]!=="-")return Q.toLowerCase();return Q}function Q30(Q,J){if(J){var G="",H,K;if(Array.isArray(J))H=J[0],K=J[1];else H=J;if(Q){Q=String(Q).replaceAll(/\s*\/\*.*?\*\/\s*/g,"").trim();var z=!1,q=0,F=!1,D=[];if(H)D.push(...Object.keys(H).map(sT));if(K)D.push(...Object.keys(K).map(sT));var V=0,O=-1;let w=Q.length;for(var P=0;P<w;P++){var N=Q[P];if(F){if(N==="/"&&Q[P-1]==="*")F=!1}else if(z){if(z===N)z=!1}else if(N==="/"&&Q[P+1]==="*")F=!0;else if(N==='"'||N==="'")z=N;else if(N==="(")q++;else if(N===")")q--;if(!F&&z===!1&&q===0){if(N===":"&&O===-1)O=P;else if(N===";"||P===w-1){if(O!==-1){var I=sT(Q.substring(V,O).trim());if(!D.includes(I)){if(N!==";")P++;var R=Q.substring(V,P).trim();G+=" "+R+";"}}V=P+1,O=-1}}}}if(H)G+=tH0(H);if(K)G+=tH0(K,!0);return G=G.trim(),G===""?null:G}return Q==null?null:String(Q)}function ZW(Q,J,G,H,K,z){var q=Q[jq];if(eQ||q!==G||q===void 0){var F=eH0(G,H,z);if(!eQ||F!==Q.getAttribute("class"))if(F==null)Q.removeAttribute("class");else if(J)Q.className=F;else Q.setAttribute("class",F);Q[jq]=G}else if(z&&K!==z)for(var D in z){var V=!!z[D];if(K==null||V!==!!K[D])Q.classList.toggle(D,V)}return z}function rT(Q,J={},G,H){for(var K in G){var z=G[K];if(J[K]!==z)if(G[K]==null)Q.style.removeProperty(K);else Q.style.setProperty(K,z,H)}}function QP(Q,J,G,H){var K=Q[Cq];if(eQ||K!==J){var z=Q30(J,H);if(!eQ||z!==Q.getAttribute("style"))if(z==null)Q.removeAttribute("style");else Q.style.cssText=z;Q[Cq]=J}else if(H)if(Array.isArray(H))rT(Q,G?.[0],H[0]),rT(Q,G?.[1],H[1],"important");else rT(Q,G,H);return H}function XP(Q,J,G=!1){if(Q.multiple){if(J==null)return;if(!QW(J))return XH0();for(var H of Q.options)H.selected=J.includes(uq(H));return}for(H of Q.options){var K=uq(H);if(gT(K,J)){H.selected=!0;return}}if(!G||J!==void 0)Q.selectedIndex=-1}function tT(Q){var J=new MutationObserver(()=>{XP(Q,Q.__value)});J.observe(Q,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]}),o7(()=>{J.disconnect()})}function eT(Q,J,G=J){var H=new WeakSet,K=!0;gq(Q,"change",(z)=>{var q=z?"[selected]":":checked",F;if(Q.multiple)F=[].map.call(Q.querySelectorAll(q),uq);else{var D=Q.querySelector(q)??Q.querySelector("option:not([disabled])");F=D&&uq(D)}if(G(F),Q.__value=F,z8!==null)H.add(z8)}),KJ(()=>{var z=J();if(Q===document.activeElement){var q=V7?qW:z8;if(H.has(q))return}if(XP(Q,z,K),K&&z===void 0){var F=Q.querySelector(":checked");if(F!==null)z=uq(F),G(z)}Q.__value=z,K=!1}),tT(Q)}function uq(Q){if("__value"in Q)return Q.__value;else return Q.value}var qa0=Symbol("class"),Ua0=Symbol("style"),$a0=Symbol("is custom element"),Za0=Symbol("is html"),Fa0=EO?"link":"LINK";var Da0=EO?"progress":"PROGRESS";function j9(Q){if(!eQ)return;var J=!1,G=()=>{if(J)return;if(J=!0,Q.hasAttribute("value")){var H=Q.value;N9(Q,"value",null),Q.value=H}if(Q.hasAttribute("checked")){var K=Q.checked;N9(Q,"checked",null),Q.checked=K}};Q[Z4]=G,y7(G),oO()}function Xk(Q,J){var G=Jk(Q);if(G.value===(G.value=J??void 0)||Q.value===J&&(J!==0||Q.nodeName!==Da0))return;Q.value=J??""}function N7(Q,J){var G=Jk(Q);if(G.checked===(G.checked=J??void 0))return;Q.checked=J}function N9(Q,J,G,H){var K=Jk(Q);if(eQ){if(K[J]=Q.getAttribute(J),J==="src"||J==="srcset"||J==="href"&&Q.nodeName===Fa0){if(!H)La0(Q,J,G??"");return}}if(K[J]===(K[J]=G))return;if(J==="loading")Q[P40]=G;if(G==null)Q.removeAttribute(J);else if(typeof G!=="string"&&Ma0(Q).includes(J))Q[J]=G;else Q.setAttribute(J,G)}function Jk(Q){return Q[wO]??={[$a0]:Q.nodeName.includes("-"),[Za0]:Q.namespaceURI===SO}}var X30=new Map;function Ma0(Q){var J=Q.getAttribute("is")||Q.nodeName,G=X30.get(J);if(G)return G;X30.set(J,G=[]);var H,K=Q,z=Element.prototype;while(z!==K){H=CO(K);for(var q in H)if(H[q].set&&q!=="innerHTML"&&q!=="textContent"&&q!=="innerText")G.push(q);K=mH(K)}return G}function La0(Q,J,G){if(!UQ)return;if(J==="srcset"&&Oa0(Q,G))return;if(Qk(Q.getAttribute(J)??"",G))return;e40(J,Q.outerHTML.replace(Q.innerHTML,Q.innerHTML&&"..."),String(G))}function Qk(Q,J){if(Q===J)return!0;return new URL(Q,document.baseURI).href===new URL(J,document.baseURI).href}function J30(Q){return Q.split(",").map((J)=>J.trim().split(" ").filter(Boolean))}function Oa0(Q,J){var G=J30(Q.srcset),H=J30(J);return H.length===G.length&&H.every(([K,z],q)=>z===G[q][1]&&(Qk(G[q][0],K)||Qk(K,G[q][0])))}function pq(Q,J,G=J){var H=new WeakSet;if(gq(Q,"input",async(K)=>{if(UQ&&Q.type==="checkbox")UT();var z=K?Q.defaultValue:Q.value;if(z=Yk(Q)?Gk(z):z,G(z),z8!==null)H.add(z8);if(await aH(),z!==(z=J())){var{selectionStart:q,selectionEnd:F}=Q,D=Q.value.length;if(Q.value=z??"",F!==null){var V=Q.value.length;if(q===F&&F===D&&V>D)Q.selectionStart=V,Q.selectionEnd=V;else Q.selectionStart=q,Q.selectionEnd=Math.min(F,V)}}}),eQ&&Q.defaultValue!==Q.value||FQ(J)==null&&Q.value){if(G(Yk(Q)?Gk(Q.value):Q.value),z8!==null)H.add(z8)}q7(()=>{if(UQ&&Q.type==="checkbox")UT();var K=J();if(Q===document.activeElement){var z=V7?qW:z8;if(H.has(z))return}if(Yk(Q)&&K===Gk(Q.value))return;if(Q.type==="date"&&!K&&!Q.value)return;if(K!==Q.value)Q.value=K??""})}function Wk(Q,J,G=J){if(gq(Q,"change",(H)=>{var K=H?Q.defaultChecked:Q.checked;G(K)}),eQ&&Q.defaultChecked!==Q.checked||FQ(J)==null)G(Q.checked);q7(()=>{var H=J();Q.checked=Boolean(H)})}function Yk(Q){var J=Q.type;return J==="number"||J==="range"}function Gk(Q){return Q===""?null:+Q}class G30{#X=new WeakMap;#Q;#J;static entries=new WeakMap;constructor(Q){this.#J=Q}observe(Q,J){var G=this.#X.get(Q)||new Set;return G.add(J),this.#X.set(Q,G),this.#B().observe(Q,this.#J),()=>{var H=this.#X.get(Q);if(H.delete(J),H.size===0)this.#X.delete(Q),this.#Q.unobserve(Q)}}#B(){return this.#Q??(this.#Q=new ResizeObserver((Q)=>{for(var J of Q){G30.entries.set(J.target,J);for(var G of this.#X.get(J.target)||[])G(J)}}))}}function Hk(Q,J){return Q===J||Q?.[T7]===J}function Bk(Q={},J,G,H){var K=d8.r,z=aQ;return KJ(()=>{var q,F;return q7(()=>{q=F,F=H?.()||[],FQ(()=>{if(!Hk(G(...F),Q)){if(J(Q,...F),q&&Hk(G(...q),Q))J(null,...q)}})}),()=>{let D=z;while(D!==K&&D.parent!==null&&D.parent.f&FK)D=D.parent;let V=()=>{if(F&&Hk(G(...F),Q))J(null,...F)},O=D.teardown;D.teardown=()=>{V(),O?.()}}}),Q}function vJ(Q=!1){let J=d8,G=J.l.u;if(!G)return;let H=()=>yJ(J.s);if(Q){let K=0,z={},q=tW(()=>{let F=!1,D=J.s;for(let V in D)if(D[V]!==z[V])z[V]=D[V],F=!0;if(F)K++;return K});H=()=>c(q)}if(G.b.length)hq(()=>{W30(J,H),$K(G.b)});if(wK(()=>{let K=FQ(()=>G.m.map(O40));return()=>{for(let z of K)if(typeof z==="function")z()}}),G.a.length)wK(()=>{W30(J,H),$K(G.a)})}function W30(Q,J){if(Q.l.s)for(let G of Q.l.s)c(G);J()}function gX(Q,J,G,H){var K=!BW||(G&l40)!==0,z=(G&c40)!==0,q=(G&i40)!==0,F=H,D=!0,V=void 0,O=()=>{if(q&&K)return V??=tW(H),c(V);if(D)D=!1,F=q?FQ(H):H;return F};let P;if(z){var N=T7 in Q||Nq in Q;P=wJ(Q,J)?.set??(N&&J in Q?(b)=>Q[J]=b:void 0)}var I,R=!1;if(z)[I,R]=OT(()=>Q[J]);else I=Q[J];if(I===void 0&&H!==void 0){if(I=O(),P){if(K)y40(J);P(I)}}var w;if(K)w=()=>{var b=Q[J];if(b===void 0)return O();return D=!0,b};else w=()=>{var b=Q[J];if(b!==void 0)F=void 0;return b===void 0?F:b};if(K&&(G&d40)===0)return w;if(P){var E=Q.$$legacy;return function(b,g){if(arguments.length>0){if(!K||!g||E||R)P(g?w():b);return b}return w()}}var T=!1,y=((G&p40)!==0?tW:VW)(()=>{return T=!1,w()});if(UQ)y.label=J;if(z)c(y);var x=aQ;return function(b,g){if(arguments.length>0){let l=g?c(y):K&&z?X5(b):b;if(qQ(y,l),T=!0,F!==void 0)F=l;return b}if(XY&&T||(x.f&o9)!==0)return y.v;return c(y)}}function H30(Q){return new B30(Q)}class B30{#X;#Q;constructor(Q){var J=new Map,G=(K,z)=>{var q=dQ(z,!1,!1);return J.set(K,q),q};let H=new Proxy({...Q.props||{},$$events:{}},{get(K,z){return c(J.get(z)??G(z,Reflect.get(K,z)))},has(K,z){if(z===Nq)return!0;return c(J.get(z)??G(z,Reflect.get(K,z))),Reflect.has(K,z)},set(K,z,q){return qQ(J.get(z)??G(z,q),q),Reflect.set(K,z,q)}});if(this.#Q=(Q.hydrate?nT:O4)(Q.component,{target:Q.target,anchor:Q.anchor,props:H,context:Q.context,intro:Q.intro??!1,recover:Q.recover,transformError:Q.transformError}),!V7&&(!Q?.props?.$$host||Q.sync===!1))Q3();this.#X=H.$$events;for(let K of Object.keys(this.#Q)){if(K==="$set"||K==="$destroy"||K==="$on")continue;BX(this,K,{get(){return this.#Q[K]},set(z){this.#Q[K]=z},enumerable:!0})}this.#Q.$set=(K)=>{Object.assign(H,K)},this.#Q.$destroy=()=>{G3(this.#Q)}}$set(Q){this.#Q.$set(Q)}$on(Q,J){this.#X[Q]=this.#X[Q]||[];let G=(...H)=>J.call(this,...H);return this.#X[Q].push(G),()=>{this.#X[Q]=this.#X[Q].filter((H)=>H!==G)}}$destroy(){this.#Q.$destroy()}}var Ea0;if(typeof HTMLElement==="function")Ea0=class extends HTMLElement{$$ctor;$$s;$$c;$$cn=!1;$$d={};$$r=!1;$$p_d={};$$l={};$$l_u=new Map;$$me;$$shadowRoot=null;constructor(Q,J,G){super();if(this.$$ctor=Q,this.$$s=J,G)this.$$shadowRoot=this.attachShadow(G)}addEventListener(Q,J,G){if(this.$$l[Q]=this.$$l[Q]||[],this.$$l[Q].push(J),this.$$c){let H=this.$$c.$on(Q,J);this.$$l_u.set(J,H)}super.addEventListener(Q,J,G)}removeEventListener(Q,J,G){if(super.removeEventListener(Q,J,G),this.$$c){let H=this.$$l_u.get(J);if(H)H(),this.$$l_u.delete(J)}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let Q=function(H){return(K)=>{let z=$W("slot");if(H!=="default")z.name=H;TQ(K,z)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let J={},G=Sa0(this);for(let H of this.$$s)if(H in G)if(H==="default"&&!this.$$d.children)this.$$d.children=Q(H),J.default=!0;else J[H]=Q(H);for(let H of this.attributes){let K=this.$$g_p(H.name);if(!(K in this.$$d))this.$$d[K]=Ak(K,H.value,this.$$p_d,"toProp")}for(let H in this.$$p_d)if(!(H in this.$$d)&&this[H]!==void 0)this.$$d[H]=this[H],delete this[H];this.$$c=H30({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:J,$$host:this}}),this.$$me=uT(()=>{q7(()=>{this.$$r=!0;for(let H of HT(this.$$c)){if(!this.$$p_d[H]?.reflect)continue;this.$$d[H]=this.$$c[H];let K=Ak(H,this.$$d[H],this.$$p_d,"toAttribute");if(K==null)this.removeAttribute(this.$$p_d[H].attribute||H);else this.setAttribute(this.$$p_d[H].attribute||H,K)}this.$$r=!1})});for(let H in this.$$l)for(let K of this.$$l[H]){let z=this.$$c.$on(H,K);this.$$l_u.set(K,z)}this.$$l={}}}attributeChangedCallback(Q,J,G){if(this.$$r)return;Q=this.$$g_p(Q),this.$$d[Q]=Ak(Q,G,this.$$p_d,"toProp"),this.$$c?.$set({[Q]:this.$$d[Q]})}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{if(!this.$$cn&&this.$$c)this.$$c.$destroy(),this.$$me(),this.$$c=void 0})}$$g_p(Q){return HT(this.$$p_d).find((J)=>this.$$p_d[J].attribute===Q||!this.$$p_d[J].attribute&&J.toLowerCase()===Q)||Q}};function Ak(Q,J,G,H){let K=G[Q]?.type;if(J=K==="Boolean"&&typeof J!=="boolean"?J!=null:J,!H||!G[Q])return J;else if(H==="toAttribute")switch(K){case"Object":case"Array":return J==null?null:JSON.stringify(J);case"Boolean":return J?"":null;case"Number":return J==null?null:J;default:return J}else switch(K){case"Object":case"Array":return J&&JSON.parse(J);case"Boolean":return J;case"Number":return J!=null?+J:J;default:return J}}function Sa0(Q){let J={};return Q.childNodes.forEach((G)=>{J[G.slot||"default"]=!0}),J}if(UQ){let Q=function(J){if(!(J in globalThis)){let G;Object.defineProperty(globalThis,J,{configurable:!0,get:()=>{if(G!==void 0)return G;v40(J)},set:(H)=>{G=H}})}};Q("$state"),Q("$effect"),Q("$derived"),Q("$inspect"),Q("$props"),Q("$bindable")}function SY(Q){if(d8===null)Rq("onMount");if(BW&&d8.l!==null)Ta0(d8).m.push(Q);else wK(()=>{let J=FQ(Q);if(typeof J==="function")return J})}function A30(Q){if(d8===null)Rq("onDestroy");SY(()=>()=>FQ(Q))}function Ta0(Q){var J=Q.l;return J.u??={a:[],b:[],m:[]}}var K30="5";if(typeof window<"u")((window.__svelte??={}).v??=new Set).add(K30);var ka0=oQ('<div class="cmd-name svelte-1wvc3jg"> </div>'),ya0=oQ(`<div class="warning destructive-warning svelte-1wvc3jg">⚠️ <strong>This command may be destructive.</strong> Its id or
human name contains a word that often indicates data deletion,
reset, or cleanup. <em>Allow always</em> is disabled for
commands like this — if you trust it, use <em>Allow once</em> and inspect the result before granting persistent access.</div>`),va0=oQ(`<div class="warning rate-warning svelte-1wvc3jg">⚠️ The agent has requested <strong> </strong> command
executions in the last minute. This may indicate a runaway loop
or an unintended batch — pause and verify that this call is
expected before continuing.</div>`),xa0=oQ(`<div><h2 class="svelte-1wvc3jg">Run Obsidian command?</h2> <p class="intro svelte-1wvc3jg">The MCP agent is requesting permission to execute an Obsidian
command on your behalf.</p> <div class="command-info svelte-1wvc3jg"><code class="cmd-id svelte-1wvc3jg"> </code> <!></div> <!> <!> <div class="hint svelte-1wvc3jg"><strong>Allow once</strong>: run this invocation only; the command
is not added to your allowlist. <strong>Allow always</strong>: run this invocation and add <code class="svelte-1wvc3jg"> </code> to your allowlist so future calls skip
this prompt. <strong>Deny</strong>: reject this call; the agent receives a
permission-denied error.</div> <div class="buttons svelte-1wvc3jg"><button type="button" class="cmd-perm-btn cmd-perm-deny svelte-1wvc3jg">Deny</button> <button type="button" class="cmd-perm-btn cmd-perm-once svelte-1wvc3jg">Allow once</button> <button type="button" class="cmd-perm-btn cmd-perm-always mod-cta svelte-1wvc3jg">Allow always</button></div></div>`),ba0={hash:"svelte-1wvc3jg",code:".permission-prompt.svelte-1wvc3jg {max-width:560px;}.permission-prompt.svelte-1wvc3jg h2:where(.svelte-1wvc3jg) {margin-top:0;margin-bottom:0.5em;}.permission-prompt.destructive.svelte-1wvc3jg h2:where(.svelte-1wvc3jg) {color:var(--text-error, #c04848);}.intro.svelte-1wvc3jg {color:var(--text-muted);margin-bottom:0.75em;}.command-info.svelte-1wvc3jg {padding:0.6em 0.8em;background:var(--background-secondary);border-radius:4px;margin-bottom:0.75em;}.cmd-id.svelte-1wvc3jg {font-family:var(--font-monospace);font-size:0.95em;word-break:break-all;}.cmd-name.svelte-1wvc3jg {color:var(--text-muted);font-size:0.85em;margin-top:0.3em;}.warning.svelte-1wvc3jg {padding:0.6em 0.8em;border-left:3px solid var(--text-warning, #e1a800);background:var(--background-secondary);border-radius:4px;font-size:0.88em;margin-bottom:0.75em;}.destructive-warning.svelte-1wvc3jg {border-left-color:var(--text-error, #c04848);}.hint.svelte-1wvc3jg {color:var(--text-muted);font-size:0.83em;margin-bottom:1em;line-height:1.45;}.hint.svelte-1wvc3jg code:where(.svelte-1wvc3jg) {font-family:var(--font-monospace);font-size:0.85em;}.buttons.svelte-1wvc3jg {display:flex;gap:0.5em;justify-content:flex-end;flex-wrap:wrap;}.cmd-perm-btn.svelte-1wvc3jg {min-width:110px;}.cmd-perm-btn.mod-cta.svelte-1wvc3jg {background:var(--interactive-accent);color:var(--text-on-accent);}.cmd-perm-btn.mod-cta.svelte-1wvc3jg:disabled {background:var(--background-modifier-border);color:var(--text-muted);cursor:not-allowed;}"};function Kk(Q,J){c7(J,!0),bX(Q,ba0);var G=xa0();let H;var K=VQ(GQ(G),4),z=GQ(K),q=GQ(z,!0);YQ(z);var F=VQ(z,2);{var D=(b)=>{var g=ka0(),l=GQ(g,!0);YQ(g),C8(()=>q8(l,J.commandName)),TQ(b,g)};m8(F,(b)=>{if(J.commandName)b(D)})}YQ(K);var V=VQ(K,2);{var O=(b)=>{var g=ya0();TQ(b,g)};m8(V,(b)=>{if(J.isDestructive)b(O)})}var P=VQ(V,2);{var N=(b)=>{var g=va0(),l=VQ(GQ(g)),_=GQ(l,!0);YQ(l),v9(),YQ(g),C8(()=>q8(_,J.rateCount)),TQ(b,g)};m8(P,(b)=>{if(J.showRateWarning)b(N)})}var I=VQ(P,2),R=VQ(GQ(I),4),w=GQ(R,!0);YQ(R),v9(3),YQ(I);var E=VQ(I,2),T=GQ(E),y=VQ(T,2),x=VQ(y,2);YQ(E),YQ(G),C8(()=>{H=ZW(G,1,"permission-prompt svelte-1wvc3jg",null,H,{destructive:J.isDestructive}),q8(q,J.commandId),q8(w,J.commandId),x.disabled=J.isDestructive,N9(x,"title",J.isDestructive?"Disabled for potentially destructive commands — use Allow once if you are sure":void 0)}),TK("click",T,()=>J.onDecision("deny")),TK("click",y,()=>J.onDecision("allow-once")),TK("click",x,()=>J.onDecision("allow-always")),TQ(Q,G),i7()}rO(["click"]);class YP extends z30.Modal{opts;component;resolved=!1;resolveFn;constructor(Q,J){super(Q);this.opts=J}waitForDecision(){return new Promise((Q)=>{this.resolveFn=Q})}handleDecision=(Q)=>{if(this.resolved)return;this.resolved=!0,this.resolveFn?.(Q),this.close()};onOpen(){this.component=O4(Kk,{target:this.contentEl,props:{commandId:this.opts.commandId,commandName:this.opts.commandName,isDestructive:this.opts.isDestructive,showRateWarning:this.opts.showRateWarning,rateCount:this.opts.rateCount,onDecision:this.handleDecision}})}onClose(){if(!this.resolved)this.resolved=!0,this.resolveFn?.("deny");if(this.component)G3(this.component),this.component=void 0;this.contentEl.empty()}}var V30="commandPermissions",ga0=30000,ha0=(Q,J)=>new YP(Q,J),_a0=QT();async function q30(Q,J){let G=Q.rateCounter??_a0,H=Q.modalFactory??ha0,K=Q.timeoutMs??ga0,z=J.trim();G.record();let q;if(await Q.store.updateSlice(V30,(T)=>{let y=T??{},x=YT(z,y.enabled,y.allowlist),b=(y.allowlist??[]).includes(z);if(y.enabled===!0&&x.decision==="deny"&&!b)return q={kind:"needs-modal",softRateLimit:y.softRateLimit??fH},y;let l={timestamp:new Date().toISOString(),commandId:z,decision:x.decision,...x.reason?{reason:x.reason}:{}};return q={kind:"done",outcome:x.decision,reason:x.reason},{...y,recentInvocations:jO(y.recentInvocations,l)}}),q.kind==="done")return{outcome:q.outcome,reason:q.reason};let F=Q.app.commands?.commands?.[z]?.name,D=Pq(z,F),V=G.countInLastMinute(),O=V>q.softRateLimit,P=H(Q.app,{commandId:z,commandName:F,isDestructive:D,showRateWarning:O,rateCount:V});P.open();let N,I=await Promise.race([P.waitForDecision().then((T)=>({kind:"decided",decision:T})),new Promise((T)=>{N=window.setTimeout(()=>T({kind:"timeout"}),K)})]);if(N)window.clearTimeout(N);if(I.kind==="timeout")P.close();let R,w,E=!1;if(I.kind==="timeout")R="deny",w=`User did not respond within ${K/1000} seconds.`;else{let T=I.decision;if(T==="deny")R="deny",w=`User denied permission for command '${z}' via the confirmation modal.`;else if(R="allow",T==="allow-always")E=!0}return await Q.store.updateSlice(V30,(T)=>{let y=T??{},x={timestamp:new Date().toISOString(),commandId:z,decision:R,...w?{reason:w}:{}},b=E&&!(y.allowlist??[]).includes(z)?[...y.allowlist??[],z]:void 0;return{...y,...b!==void 0?{allowlist:b}:{},recentInvocations:jO(y.recentInvocations,x)}}),{outcome:R,reason:w}}var kK=(Q)=>Array.isArray(Q)?Q:[Q],U30=(Q,J)=>{let G=[[],[]];for(let H of Q)if(J(H))G[0].push(H);else G[1].push(H);return G},GP=Array,W5=(Q,J)=>Q.includes(J);var D6=(Q,J,G)=>{if(Q===void 0)return J===void 0?[]:Array.isArray(J)?J:[J];if(G?.prepend)if(Array.isArray(J))Q.unshift(...J);else Q.unshift(J);else if(Array.isArray(J))Q.push(...J);else Q.push(J);return Q},j4=(Q,J)=>{if(J===void 0||J===null)return Q??[];if(Q===void 0||Q===null)return kK(J);return Q.concat(J)};var H5=(Q,J,G)=>{if(Q===void 0)return Array.isArray(J)?J:[J];let H=G?.isEqual??((K,z)=>K===z);return kK(J).forEach((K)=>{if(!Q.some((z)=>H(z,K)))Q.push(K)}),Q},WP=(Q,J)=>Q.reduce((G,H)=>{let K=H[J];return G[K]=D6(G[K],H),G},{}),yK=(Q,J,G)=>Q.length===J.length&&Q.every(G?.isEqual?(H,K)=>G.isEqual(H,J[K]):(H,K)=>H===J[K]);var xJ=(Q,J)=>zJ(Q)===J,zJ=(Q)=>{let J=typeof Q;return J==="object"?Q===null?"null":"object":J==="function"?"object":J},TY={boolean:"boolean",null:"null",undefined:"undefined",bigint:"a bigint",number:"a number",object:"an object",string:"a string",symbol:"a symbol"},$30={...TY,function:"a function"};var r8=(Q,J)=>{let G=Array.isArray(Q),H=Object.entries(Q).flatMap((z,q)=>{let F=G?J(q,z[1]):J(...z,q);return Array.isArray(F[0])||F.length===0?F:[F]}),K=Object.fromEntries(H);return typeof H[0]?.[0]==="number"?Object.values(K):K};var zk=Object.entries;var ZX=(Q,J)=>(Q in J);class Vk{constructor(Q){Object.assign(this,Q)}}var Z30=class{};class lq extends Z30{}var fa0=(Q,J)=>{let G={},H={},K;for(K in Q)if(K in J)G[K]=Q[K];else H[K]=Q[K];return[G,H]};var F30=(Q,J)=>fa0(Q,J)[1],UG=(Q)=>Object.keys(Q).length===0,dq=(Q)=>[...Object.entries(Q),...Object.getOwnPropertySymbols(Q).map((J)=>[J,Q[J]])],D30=(Q,J)=>Object.defineProperties(Q,Object.getOwnPropertyDescriptors(J));var W3=Symbol("represents an uninitialized value");var qk={Array,Boolean,Date,Error,Function,Map,Number,Promise,RegExp,Set,String,WeakMap,WeakSet},Uk=globalThis.File??Blob,$k={ArrayBuffer,Blob,File:Uk,FormData,Headers,Request,Response,URL},ma0={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array},H3={...qk,...$k,...ma0,String,Number,Boolean},cq=(Q)=>{let J=Object.getPrototypeOf(Q);while(J?.constructor&&(!ZX(J.constructor.name,H3)||!(Q instanceof H3[J.constructor.name])))J=Object.getPrototypeOf(J);let G=J?.constructor?.name;if(G===void 0||G==="Object")return;return G},iq=(Q)=>typeof Q==="object"&&Q!==null?cq(Q)??"object":zJ(Q);var V9=Array.isArray,ua0={Array:"an array",Function:"a function",Date:"a Date",RegExp:"a RegExp",Error:"an Error",Map:"a Map",Set:"a Set",String:"a String object",Number:"a Number object",Boolean:"a Boolean object",Promise:"a Promise",WeakMap:"a WeakMap",WeakSet:"a WeakSet"},pa0={ArrayBuffer:"an ArrayBuffer instance",Blob:"a Blob instance",File:"a File instance",FormData:"a FormData instance",Headers:"a Headers instance",Request:"a Request instance",Response:"a Response instance",URL:"a URL instance"},la0={Int8Array:"an Int8Array",Uint8Array:"a Uint8Array",Uint8ClampedArray:"a Uint8ClampedArray",Int16Array:"an Int16Array",Uint16Array:"a Uint16Array",Int32Array:"an Int32Array",Uint32Array:"a Uint32Array",Float32Array:"a Float32Array",Float64Array:"a Float64Array",BigInt64Array:"a BigInt64Array",BigUint64Array:"a BigUint64Array"},M30={...ua0,...pa0,...la0},oq=(Q)=>{let J=Object(Q).name??null;return J&&ZX(J,H3)&&H3[J]===Q?J:null};var Zk=(Q,J)=>{let G=Q.prototype;while(G!==null){if(G===J.prototype)return!0;G=Object.getPrototypeOf(G)}return!1};var L30=(Q)=>O30(Q,new Map),O30=(Q,J)=>{if(typeof Q!=="object"||Q===null)return Q;if(J?.has(Q))return J.get(Q);let G=oq(Q.constructor);if(G==="Date")return new Date(Q.getTime());if(G&&G!=="Array")return Q;let H=Array.isArray(Q)?Q.slice():Object.create(Object.getPrototypeOf(Q)),K=Object.getOwnPropertyDescriptors(Q);if(J){J.set(Q,H);for(let z in K)K[z].value=O30(K[z].value,J)}return Object.defineProperties(H,K),H};class P30 extends Error{}var i6=(Q)=>B3(Q,P30),B3=(Q,J=Error)=>{throw new J(Q)};class HP extends Error{name="ParseError"}var zQ=(Q)=>B3(Q,HP),vK=(Q)=>` ${Q}`;var da0=(Q)=>{let J=W3;return()=>J===W3?J=Q():J},C4=(Q)=>typeof Q==="function"&&Q.length===0;var N30=class extends Function{constructor(...Q){let J=Q.slice(0,-1),G=Q.at(-1);try{super(...J,G)}catch(H){return i6(`Encountered an unexpected error while compiling your definition:
Message: ${H}
Source: (${Q.slice(0,-1)}) => {
${Q.at(-1)}
}`)}}};class I4{constructor(Q,...[J]){return Object.assign(Object.setPrototypeOf(Q.bind(J?.bind??this),this.constructor.prototype),J?.attach)}}var j30=da0(()=>{try{return Function("return false")()}catch{return!0}});var C30=vK("arkInferred");var YdQ=vK("args");class hX{constructor(){}}var I30=(Q)=>Q[0].toUpperCase()+Q.slice(1);var Fk=(Q)=>new RegExp(ca0(Q),typeof Q==="string"?"":Q.flags);var ca0=(Q)=>{return`^(?:${typeof Q==="string"?Q:Q.source})$`};var B5={negativeLookahead:(Q)=>`(?!${Q})`,nonCapturingGroup:(Q)=>`(?:${Q})`},nq="\\",R4={" ":1,"\n":1,"\t":1};var ia0=/^-0\.?0*$/.source,w30=/[1-9]\d*/.source,oa0=/\.\d+/.source,na0=/\.\d*[1-9]/.source,E30=(Q)=>Fk(B5.negativeLookahead(ia0)+B5.nonCapturingGroup("-?"+B5.nonCapturingGroup(B5.nonCapturingGroup("0|"+w30)+B5.nonCapturingGroup(Q.decimalPattern)+"?")+(Q.allowDecimalOnly?"":"|"+Q.decimalPattern)+"?")),R30=E30({decimalPattern:na0,allowDecimalOnly:!1}),aa0=R30.test.bind(R30),S30=E30({decimalPattern:oa0,allowDecimalOnly:!0}),sa0=/^-?\d*\.?\d*$/,ra0=(Q)=>Q.length!==0&&sa0.test(Q),aq=Fk(B5.negativeLookahead("^-0$")+"-?"+B5.nonCapturingGroup(B5.nonCapturingGroup("0|"+w30))),ta0=aq.test.bind(aq),Dk=/^-?\d+$/,ea0=Dk.test.bind(Dk),T30={number:"a number",bigint:"a bigint",integer:"an integer"},k30=(Q,J)=>`'${Q}' was parsed as ${T30[J]} but could not be narrowed to a literal value. Avoid unnecessary leading or trailing zeros and other abnormal notation`,Qs0=(Q,J)=>J==="number"?aa0(Q):ta0(Q),Xs0=(Q,J)=>J==="number"?Number(Q):Number.parseInt(Q),Js0=(Q,J)=>J==="number"?ra0(Q):ea0(Q),y30=(Q,J)=>Mk(Q,"number",J),v30=(Q,J)=>Mk(Q,"number",{...J,strict:!0}),x30=(Q,J)=>Mk(Q,"integer",J),Mk=(Q,J,G)=>{let H=Xs0(Q,J);if(!Number.isNaN(H)){if(Js0(Q,J)){if(G?.strict)return Qs0(Q,J)?H:zQ(k30(Q,J));return H}}return G?.errorOnFail?zQ(G?.errorOnFail===!0?`Failed to parse ${T30[J]} from '${Q}'`:G?.errorOnFail):void 0},b30=(Q)=>{if(Q[Q.length-1]!=="n")return;let J=Q.slice(0,-1),G;try{G=BigInt(J)}catch{return}if(aq.test(J))return G;if(Dk.test(J))return zQ(k30(Q,"bigint"))};var Ys0="0.30.0",Gs0={version:Ys0,filename:"mcp-tools-for-obsidian.ts",FileConstructor:Uk},A3=Gs0,g30=new WeakMap,Lk=Object.create(null),sq=(Q)=>{let J=g30.get(Q);if(J)return J;let G=Ws0(Q);if(Lk[G])G=`${G}${Lk[G]++}`;else Lk[G]=1;return A3[G]=Q,g30.set(Q,G),G},xK=(Q)=>/^[a-zA-Z_$][a-zA-Z_$0-9]*$/.test(Q),Ws0=(Q)=>{switch(typeof Q){case"object":{if(Q===null)break;let J=cq(Q)??"object";return J[0].toLowerCase()+J.slice(1)}case"function":return xK(Q.name)?Q.name:"fn";case"symbol":return Q.description&&xK(Q.description)?Q.description:"symbol"}return i6(`Unexpected attempt to register serializable value of type ${zJ(Q)}`)};var BP=(Q)=>typeof Q==="string"?JSON.stringify(Q):typeof Q==="bigint"?`${Q}n`:`${Q}`;var h30=(Q,J={})=>rq(Q,{onUndefined:"$ark.undefined",onBigInt:(G)=>`$ark.bigint-${G}`,...J},[]);var n8=(Q,J)=>{switch(zJ(Q)){case"object":let G=Q,H=G.constructor.name;return H==="Object"||H==="Array"?JSON.stringify(rq(G,AP,[]),null,J):G instanceof Date?K3(G):typeof G.expression==="string"?G.expression:H;case"symbol":return AP.onSymbol(Q);default:return BP(Q)}},AP={onCycle:()=>"(cycle)",onSymbol:(Q)=>`Symbol(${sq(Q)})`,onFunction:(Q)=>`Function(${sq(Q)})`},rq=(Q,J,G)=>{switch(zJ(Q)){case"object":{let H=Q;if("toJSON"in H&&typeof H.toJSON==="function")return H.toJSON();if(typeof H==="function")return AP.onFunction(H);if(G.includes(H))return"(cycle)";let K=[...G,H];if(Array.isArray(H))return H.map((q)=>rq(q,J,K));if(H instanceof Date)return H.toDateString();let z={};for(let q in H)z[q]=rq(H[q],J,K);for(let q of Object.getOwnPropertySymbols(H))z[J.onSymbol?.(q)??q.toString()]=rq(H[q],J,K);return z}case"symbol":return AP.onSymbol(Q);case"bigint":return J.onBigInt?.(Q)??`${Q}n`;case"undefined":return J.onUndefined??"undefined";default:return Q}},K3=(Q)=>{let J=Q.getFullYear(),G=Q.getMonth(),H=Q.getDate(),K=Q.getHours(),z=Q.getMinutes(),q=Q.getSeconds(),F=Q.getMilliseconds();if(G===0&&H===1&&K===0&&z===0&&q===0&&F===0)return`${J}`;let D=`${Hs0[G]} ${H}, ${J}`;if(K===0&&z===0&&q===0&&F===0)return D;let V=Q.toLocaleTimeString(),O=V.endsWith(" AM")||V.endsWith(" PM")?V.slice(-3):"";if(O)V=V.slice(0,-O.length);if(F)V+=`.${As0(F,3)}`;else if(Bs0.test(V))V=V.slice(0,-3);return`${V+O}, ${D}`},Hs0=["January","February","March","April","May","June","July","August","September","October","November","December"],Bs0=/:\d\d:00$/,As0=(Q,J)=>String(Q).padStart(J,"0");var _30=(Q,J,...[G])=>{let H=G?.stringifySymbol??n8,K=Q;switch(typeof J){case"string":K=xK(J)?Q===""?J:`${Q}.${J}`:`${Q}[${JSON.stringify(J)}]`;break;case"number":K=`${Q}[${J}]`;break;case"symbol":K=`${Q}[${H(J)}]`;break;default:if(G?.stringifyNonKey)K=`${Q}[${G.stringifyNonKey(J)}]`;else zQ(`${n8(J)} must be a PropertyKey or stringifyNonKey must be passed to options`)}return K},z3=(Q,...J)=>Q.reduce((G,H)=>_30(G,H,...J),"");class V3 extends GP{cache={};constructor(...Q){super();this.push(...Q)}stringify(){if(this.cache.stringify)return this.cache.stringify;return this.cache.stringify=z3(this)}stringifyAncestors(){if(this.cache.stringifyAncestors)return this.cache.stringifyAncestors;let Q="",J=[Q];return this.forEach((G)=>{Q=_30(Q,G),J.push(Q)}),this.cache.stringifyAncestors=J}}class Ok{chars;i;def;constructor(Q){this.def=Q,this.chars=[...Q],this.i=0}shift(){return this.chars[this.i++]??""}get lookahead(){return this.chars[this.i]??""}get nextLookahead(){return this.chars[this.i+1]??""}get length(){return this.chars.length}shiftUntil(Q){let J="";while(this.lookahead){if(Q(this,J))if(J[J.length-1]===nq)J=J.slice(0,-1);else break;J+=this.shift()}return J}shiftUntilLookahead(Q){return typeof Q==="string"?this.shiftUntil((J)=>J.lookahead===Q):this.shiftUntil((J)=>(J.lookahead in Q))}shiftUntilNonWhitespace(){return this.shiftUntil(()=>!(this.lookahead in R4))}jumpToIndex(Q){this.i=Q<0?this.length+Q:Q}jumpForward(Q){this.i+=Q}get location(){return this.i}get unscanned(){return this.chars.slice(this.i,this.length).join("")}get scanned(){return this.chars.slice(0,this.i).join("")}sliceChars(Q,J){return this.chars.slice(Q,J).join("")}lookaheadIs(Q){return this.lookahead===Q}lookaheadIsIn(Q){return this.lookahead in Q}}var TdQ=Symbol("implementedTraits");var Pk="$ark",Nk=2;while(Pk in globalThis)Pk=`$ark${Nk++}`;var f30=Pk;globalThis[f30]=A3;var NQ=A3;if(Nk!==2){let Q=globalThis,J=[Q.$ark];for(let K=2;K<Nk;K++)if(Q[`$ark${K}`])J.push(Q[`$ark${K}`]);console.warn("Multiple @ark registries detected. This can lead to unexpected behavior.");let G=WP(J,"filename"),H=Object.keys(G);for(let K of H)if(G[K].length>1)console.warn(`File ${K} was initialized multiple times, likely due to being imported from both CJS and ESM contexts.`);if(H.length>1)console.warn("Registries were initialized at the following paths:"+H.map((K)=>` ${K} (@ark/util version ${G[K][0].version})`).join(`
`))}var Ks0=(Q)=>`${f30}.${Q}`,j7=(Q)=>Ks0(sq(Q));class KP extends lq{argNames;body="";constructor(...Q){super();this.argNames=Q;for(let J of Q){if(J in this)throw Error(`Arg name '${J}' would overwrite an existing property on FunctionBody`);this[J]=J}}indentation=0;indent(){return this.indentation+=4,this}dedent(){return this.indentation-=4,this}prop(Q,J=!1){return jk(Q,J)}index(Q,J=!1){return m30(`${Q}`,J)}line(Q){return this.body+=`${" ".repeat(this.indentation)}${Q}
`,this}const(Q,J){return this.line(`const ${Q} = ${J}`),this}let(Q,J){return this.line(`let ${Q} = ${J}`)}set(Q,J){return this.line(`${Q} = ${J}`)}if(Q,J){return this.block(`if (${Q})`,J)}elseIf(Q,J){return this.block(`else if (${Q})`,J)}else(Q){return this.block("else",Q)}for(Q,J,G=0){return this.block(`for (let i = ${G}; ${Q}; i++)`,J)}forIn(Q,J){return this.block(`for (const k in ${Q})`,J)}block(Q,J,G=""){return this.line(`${Q} {`),this.indent(),J(this),this.dedent(),this.line(`}${G}`)}return(Q=""){return this.line(`return ${Q}`)}write(Q="anonymous"){return`${Q}(${this.argNames.join(", ")}) {
${this.body}}`}compile(){return new N30(...this.argNames,this.body)}}var A5=(Q)=>xJ(Q,"object")||typeof Q==="symbol"?j7(Q):BP(Q),jk=(Q,J=!1)=>{if(typeof Q==="string"&&xK(Q))return`${J?"?":""}.${Q}`;return m30(zs0(Q),J)},zs0=(Q)=>typeof Q==="symbol"?j7(Q):JSON.stringify(Q),m30=(Q,J=!1)=>`${J?"?.":""}[${Q}]`;class zP extends KP{path=[];discriminants=[];traversalKind;constructor(Q){super("data","ctx");this.traversalKind=Q}invoke(Q,J){let G=J?.arg??this.data,H=typeof Q==="string"?!0:this.requiresContextFor(Q),K=typeof Q==="string"?Q:Q.id;if(H)return`${this.referenceToId(K,J)}(${G}, ${this.ctx})`;return`${this.referenceToId(K,J)}(${G})`}referenceToId(Q,J){let G=J?.kind??this.traversalKind,H=`this.${Q}${G}`;return J?.bind?`${H}.bind(${J?.bind})`:H}requiresContextFor(Q){return this.traversalKind==="Apply"||Q.allowsRequiresContext}initializeErrorCount(){return this.const("errorCount","ctx.currentErrorCount")}returnIfFail(){return this.if("ctx.currentErrorCount > errorCount",()=>this.return())}returnIfFailFast(){return this.if("ctx.failFast && ctx.currentErrorCount > errorCount",()=>this.return())}traverseKey(Q,J,G){let H=this.requiresContextFor(G);if(H)this.line(`${this.ctx}.path.push(${Q})`);if(this.check(G,{arg:J}),H)this.line(`${this.ctx}.path.pop()`);return this}check(Q,J){return this.traversalKind==="Allows"?this.if(`!${this.invoke(Q,J)}`,()=>this.return(!1)):this.line(this.invoke(Q,J))}}var VP=(Q)=>r8(Q,(J,G)=>[J,V9(G)?[...G]:G]),bJ=vK("arkKind"),Q8=(Q,J)=>Q?.[bJ]===J,C9=(Q)=>Q8(Q,"root")||Q8(Q,"constraint");var u30=["unit","proto","domain"],bK=["required","optional","index","sequence"],Ck=["pattern","divisor","exactLength","max","min","maxLength","minLength","before","after"],qP=[...Ck,...bK,"structure","predicate"],gK=["alias","union","morph","unit","intersection","proto","domain"],Vs0=[...gK,...qP],UP=r8(qP,(Q,J)=>[J,1]),p30=r8([...bK,"undeclared"],(Q,J)=>[J,1]),l30=r8(Vs0,(Q,J)=>[J,Q]),hK=(Q)=>typeof Q==="string"&&(Q in l30);var _K=(Q)=>l30[Q],$P=(Q)=>gK.slice(_K(Q)+1),qcQ=[...$P("union"),"alias"],UcQ=[...$P("morph"),"alias"],K5=(Q)=>{if(typeof Q==="string"||typeof Q==="boolean"||Q===null)return Q;if(typeof Q==="number"){if(Number.isNaN(Q))return"NaN";if(Q===Number.POSITIVE_INFINITY)return"Infinity";if(Q===Number.NEGATIVE_INFINITY)return"-Infinity";return Q}return A5(Q)},w4=(Q)=>{let J="{ ";for(let[G,H]of Object.entries(Q))J+=`${G}: ${A5(H)}, `;return J+" }"},u8=(Q)=>{let J=Q;if(J.hasAssociatedError)J.defaults.expected??=(G)=>("description"in G)?G.description:J.defaults.description(G),J.defaults.actual??=(G)=>n8(G),J.defaults.problem??=(G)=>`must be ${G.expected}${G.actual?` (was ${G.actual})`:""}`,J.defaults.message??=(G)=>{if(G.path.length===0)return G.problem;let H=`${G.propString} ${G.problem}`;if(H[0]==="[")return`value at ${H}`;return H};return J};NQ.config??={};var qs0=(Q,J)=>{let G={...Q},H;for(H in J)G[H]=hK(H)?{...Q[H],...J[H]}:J[H];return G},d30=(Q,J)=>{if(!J)return Q;return qs0(Q,J)},c30=(Q)=>d30(d30(NQ.defaultConfig,NQ.config),Q);class q3 extends lq{[bJ]="error";path;data;nodeConfig;input;constructor(Q,J){super();this.input=Q,D30(this,Q);let G=J.data;if(Q.code==="union")Q.errors=Q.errors.flatMap((H)=>H.hasCode("union")?H.errors:H);this.nodeConfig=J.config[this.code],this.path=Q.relativePath?new V3(...J.path,...Q.relativePath):Q.path?new V3(...Q.path):new V3(...J.path),this.data="data"in Q?Q.data:G}hasCode(Q){return this.code===Q}get propString(){return z3(this.path)}get expected(){return this.input.expected??this.nodeConfig.expected?.(this.input)}get actual(){return this.input.actual??this.nodeConfig.actual?.(this.data)}get problem(){return this.input.problem??this.nodeConfig.problem(this)}get message(){return this.input.message??this.nodeConfig.message(this)}toString(){return this.message}throw(){throw this}}class gJ extends GP{ctx;constructor(Q){super();this.ctx=Q}byPath=Object.create(null);byAncestorPath=Object.create(null);count=0;mutable=this;add(Q){if(this.includes(Q))return;this._add(Q)}affectsPath(Q){if(this.length===0)return!1;return Q.stringifyAncestors().some((J)=>(J in this.byPath))||Q.stringify()in this.byAncestorPath}_add(Q){let J=this.byPath[Q.propString];if(J){let G=new q3({code:"intersection",errors:J.hasCode("intersection")?[...J.errors,Q]:[J,Q]},this.ctx),H=this.indexOf(J);this.mutable[H===-1?this.length:H]=G,this.byPath[Q.propString]=G,this.addAncestorPaths(Q)}else this.byPath[Q.propString]=Q,this.addAncestorPaths(Q),this.mutable.push(Q);this.count++}addAncestorPaths(Q){Q.path.stringifyAncestors().forEach((J)=>{this.byAncestorPath[J]=D6(this.byAncestorPath[J],Q)})}merge(Q){Q.forEach((J)=>{if(this.includes(J))return;this._add(new q3({...J,path:[...this.ctx.path,...J.path]},this.ctx))})}get summary(){return this.toString()}get message(){return this.toString()}get issues(){return this}toString(){return this.join(`
`)}throw(){throw AggregateError(this,this.message)}}class ZP{path=[];queuedMorphs=[];errors=new gJ(this);branches=[];seen={};root;config;constructor(Q,J){this.root=Q,this.config=J}get currentBranch(){return this.branches.at(-1)}queueMorphs(Q){let J={path:new V3(...this.path),morphs:Q};if(this.currentBranch)this.currentBranch.queuedMorphs.push(J);else this.queuedMorphs.push(J)}finalize(){if(!this.queuedMorphs.length)return this.hasError()?this.errors:this.root;if(typeof this.root==="object"&&this.root!==null&&this.config.clone)this.root=this.config.clone(this.root);return this.applyQueuedMorphs(),this.hasError()?this.errors:this.root}applyQueuedMorphs(){while(this.queuedMorphs.length){let Q=this.queuedMorphs;this.queuedMorphs=[];for(let{path:J,morphs:G}of Q){if(this.errors.affectsPath(J))continue;this.applyMorphsAtPath(J,G)}}}applyMorphsAtPath(Q,J){let G=Q.at(-1),H;if(G!==void 0){H=this.root;for(let K=0;K<Q.length-1;K++)H=H[Q[K]]}this.path=[...Q];for(let K of J){let z=C9(K),q=K(H===void 0?this.root:H[G],this);if(q instanceof q3){this.errors.add(q);break}if(q instanceof gJ){if(!z)this.errors.merge(q);break}if(H===void 0)this.root=q;else H[G]=q;this.applyQueuedMorphs()}}get currentErrorCount(){return this.currentBranch?this.currentBranch.error?1:0:this.errors.count}hasError(){return this.currentErrorCount!==0}get failFast(){return this.branches.length!==0}error(Q){let J=typeof Q==="object"?Q.code?Q:{...Q,code:"predicate"}:{code:"predicate",expected:Q},G=new q3(J,this);if(this.currentBranch)this.currentBranch.error=G;else this.errors.add(G);return G}get data(){let Q=this.root;for(let J of this.path)Q=Q?.[J];return Q}reject(Q){return this.error(Q),!1}mustBe(Q){return this.error(Q),!1}pushBranch(){this.branches.push({error:void 0,queuedMorphs:[]})}popBranch(){return this.branches.pop()}}var hJ=(Q,J,G)=>{if(!G)return J();G.path.push(Q);let H=J();return G.path.pop(),H};class tq extends I4{attachments;$;constructor(Q,J){super((G,H)=>{if(!this.includesMorph&&!this.allowsRequiresContext&&this.allows(G))return G;if(H)return this.traverseApply(G,H),H.hasError()?H.errors:H.data;let K=new ZP(G,this.$.resolvedConfig);return this.traverseApply(G,K),K.finalize()},{attach:Q});this.attachments=Q,this.$=J}withMeta(Q){return this.$.node(this.kind,{...this.inner,meta:typeof Q==="function"?Q({...this.meta}):Q})}includesMorph=this.kind==="morph"||this.hasKind("optional")&&this.hasDefault()||this.hasKind("sequence")&&this.defaultablesLength!==0||this.hasKind("structure")&&this.undeclared==="delete"||this.children.some((Q)=>Q.includesMorph);hasContextualPredicate=this.hasKind("predicate")&&this.inner.predicate.length!==1||this.children.some((Q)=>Q.hasContextualPredicate);isCyclic=this.kind==="alias"||this.children.some((Q)=>Q.isCyclic);allowsRequiresContext=this.hasContextualPredicate||this.isCyclic;referencesById=this.children.reduce((Q,J)=>Object.assign(Q,J.referencesById),{[this.id]:this});cacheGetter(Q,J){return Object.defineProperty(this,Q,{value:J}),J}get description(){let Q=this.$?.resolvedConfig[this.kind].description??NQ.config[this.kind]?.description??NQ.defaultConfig[this.kind].description;return this.cacheGetter("description",this.meta?.description??Q(this))}get references(){return Object.values(this.referencesById)}get shallowReferences(){return this.cacheGetter("shallowReferences",this.hasKind("structure")?[this,...this.children]:this.children.reduce((Q,J)=>Zs0(Q,J.shallowReferences),[this]))}get shallowMorphs(){return this.cacheGetter("shallowMorphs",this.shallowReferences.filter((Q)=>Q.hasKind("morph")).sort((Q,J)=>Q.expression<J.expression?-1:1))}get flatRefs(){return this.cacheGetter("flatRefs",this.children.reduce((Q,J)=>fK(Q,J.flatRefs),[]).sort((Q,J)=>Q.path.length>J.path.length?1:Q.path.length<J.path.length?-1:Q.propString>J.propString?1:Q.propString<J.propString?-1:Q.node.expression<J.node.expression?-1:1))}precedence=_K(this.kind);precompilation;allows=(Q)=>{if(this.allowsRequiresContext)return this.traverseAllows(Q,new ZP(Q,this.$.resolvedConfig));return this.traverseAllows(Q)};traverse(Q){return this(Q)}get in(){return this.cacheGetter("in",this.getIo("in"))}get out(){return this.cacheGetter("out",this.getIo("out"))}getIo(Q){if(!this.includesMorph)return this;let J={};for(let[G,H]of this.innerEntries){let K=this.impl.keys[G];if(K.reduceIo)K.reduceIo(Q,J,H);else if(K.child){let z=H;J[G]=V9(z)?z.map((q)=>q[Q]):z[Q]}else J[G]=H}return this.$.node(this.kind,J)}toJSON(){return this.json}toString(){return this.expression}equals(Q){let J=C9(Q)?Q:this.$.parseDefinition(Q);return this.innerHash===J.innerHash}ifEquals(Q){return this.equals(Q)?this:void 0}hasKind(Q){return this.kind===Q}assertHasKind(Q){if(this.kind!==Q)B3(`${this.kind} node was not of asserted kind ${Q}`);return this}hasKindIn(...Q){return Q.includes(this.kind)}assertHasKindIn(...Q){if(!W5(Q,this.kind))B3(`${this.kind} node was not one of asserted kinds ${Q}`);return this}isBasis(){return W5(u30,this.kind)}isConstraint(){return W5(qP,this.kind)}isStructural(){return W5(bK,this.kind)}isRefinement(){return W5(Ck,this.kind)}isRoot(){return W5(gK,this.kind)}isUnknown(){return this.hasKind("intersection")&&this.children.length===0}isNever(){return this.hasKind("union")&&this.children.length===0}hasUnit(Q){return this.hasKind("unit")&&this.allows(Q)}hasOpenIntersection(){return this.impl.intersectionIsOpen}get nestableExpression(){return this.expression}firstReference(Q){return this.references.find((J)=>J!==this&&Q(J))}firstReferenceOrThrow(Q){return this.firstReference(Q)??B3(`${this.id} had no references matching predicate ${Q}`)}firstReferenceOfKind(Q){return this.firstReference((J)=>J.hasKind(Q))}firstReferenceOfKindOrThrow(Q){return this.firstReference((J)=>J.kind===Q)??B3(`${this.id} had no ${Q} references`)}transform(Q,J){return this._transform(Q,{...J,seen:{},path:[],parseOptions:{prereduced:J?.prereduced??!1},undeclaredKeyHandling:void 0})}_transform(Q,J){let G=J.bindScope??this.$;if(J.seen[this.id])return this.$.lazilyResolve(J.seen[this.id]);if(J.shouldTransform?.(this,J)===!1)return this;let H;if(J.seen[this.id]=()=>H,this.hasKind("structure")&&this.undeclared!==J.undeclaredKeyHandling)J={...J,undeclaredKeyHandling:this.undeclared};let K=r8(this.inner,(q,F)=>{if(!this.impl.keys[q].child)return[q,F];let D=F;if(!V9(D)){let O=D._transform(Q,J);return O?[q,O]:[]}if(D.length===0)return[q,F];let V=D.flatMap((O)=>{return O._transform(Q,J)??[]});return V.length?[q,V]:[]});delete J.seen[this.id];let z=Q(this.kind,K,J);if(z===null)return null;if(C9(z))return H=z;if(UG(z)&&!UG(this.inner))return null;if((this.kind==="required"||this.kind==="optional"||this.kind==="index")&&!("value"in z))return J.undeclaredKeyHandling?{...z,value:NQ.intrinsic.unknown}:null;if(this.kind==="morph")z.in??=NQ.intrinsic.unknown;return H=G.node(this.kind,z,J.parseOptions)}configureShallowDescendants(Q){return this.$.finalize(this.transform((J,G)=>({...G,meta:Q}),{shouldTransform:(J)=>J.kind!=="structure"}))}}var Us0=(Q)=>z3(Q,{stringifyNonKey:(J)=>J.expression}),$G=(Q,J)=>({path:Q,node:J,propString:Us0(Q)}),$s0=(Q,J)=>Q.propString===J.propString&&Q.node.equals(J.node),fK=(Q,J)=>H5(Q,J,{isEqual:$s0}),Zs0=(Q,J)=>H5(Q,J,{isEqual:(G,H)=>G.equals(H)});class _Q extends Array{static init(Q,J,G,H){return new _Q({kind:Q,l:J,r:G,path:H?.path??[],optional:H?.optional??!1})}add(Q,J,G,H){return this.push({kind:Q,l:J,r:G,path:H?.path??[],optional:H?.optional??!1}),this}describeReasons(){if(this.length===1){let{path:Q,l:J,r:G}=this[0],H=z3(Q);return Rk(`Intersection${H&&` at ${H}`} of ${i30(J,G)}`)}return`The following intersections result in unsatisfiable types:
• ${this.map(({path:Q,l:J,r:G})=>`${Q}: ${i30(J,G)}`).join(`
• `)}`}throw(){return zQ(this.describeReasons())}invert(){return this.map((Q)=>({...Q,l:Q.r,r:Q.l}))}withPrefixKey(Q,J){return this.map((G)=>({...G,path:[Q,...G.path],optional:G.optional||J==="optional"}))}toNeverIfDisjoint(){return NQ.intrinsic.never}}var i30=(Q,J)=>`${Ik(Q)} and ${Ik(J)}`,Ik=(Q)=>C9(Q)?Q.expression:V9(Q)?Q.map(Ik).join(" | ")||"never":String(Q),Rk=(Q)=>`${Q} results in an unsatisfiable type`;var mK={},HY=(Q,J,G)=>M9(Q,J,{$:G,invert:!1,pipe:!1}),Ek=(Q,J,G)=>M9(Q,J,{$:G,invert:!1,pipe:!0}),M9=(Q,J,G)=>{let H=G.pipe?"|>":"&",K=`${Q.hash}${H}${J.hash}`;if(mK[K]!==void 0)return mK[K];if(!G.pipe){let F=`${J.hash}${H}${Q.hash}`;if(mK[F]!==void 0){let D=mK[F],V=D instanceof _Q?D.invert():D;return mK[K]=V,V}}let z=!G.pipe||!Q.includesMorph&&!J.includesMorph;if(z&&Q.equals(J))return Q;let q=z?wk(Q,J,G):Q.hasKindIn(...gK)?Fs0(Q,J,G):wk(Q,J,G);if(C9(q)){if(Q.equals(q))q=Q;else if(J.equals(q))q=J}return mK[K]=q,q},wk=(Q,J,G)=>{let H=Q.precedence<J.precedence?Q.kind:J.kind,K=Q.impl.intersections[J.kind]??J.impl.intersections[Q.kind];if(K===void 0)return null;else if(H===Q.kind)return K(Q,J,G);else{let z=K(J,Q,{...G,invert:!G.invert});if(z instanceof _Q)z=z.invert();return z}},Fs0=(Q,J,G)=>Q.includesMorph||J.includesMorph?G.invert?o30(J,Q,G):o30(Q,J,G):wk(Q,J,G),o30=(Q,J,G)=>Q.distribute((H)=>Ds0(H,J,G),(H)=>{let K=H.filter(C9);if(K.length===0)return _Q.init("union",Q.branches,J.branches);if(K.length<Q.branches.length||!Q.branches.every((F,D)=>F.in.equals(K[D].in)))return G.$.parseSchema(K);let z;if(K.length===1){let F=K[0];if(!z)return F;return G.$.node("morph",{...F.inner,in:F.in.withMeta(z)})}let q={branches:K};if(z)q.meta=z;return G.$.parseSchema(q)}),Ds0=(Q,J,G)=>{if(Q.hasKind("morph")){let K=[...Q.morphs];if(Q.lastMorphIfNode){let z=M9(Q.lastMorphIfNode,J,G);if(z instanceof _Q)return z;K[K.length-1]=z}else K.push(J);return G.$.node("morph",{morphs:K,in:Q.inner.in})}if(J.hasKind("morph")){let K=M9(Q,J.in,G);if(K instanceof _Q)return K;return G.$.node("morph",{morphs:[J],in:K})}return G.$.node("morph",{morphs:[J],in:Q})};class kY extends tq{constructor(Q,J){super(Q,J);Object.defineProperty(this,bJ,{value:"constraint",enumerable:!1})}impliedSiblings;intersect(Q){return HY(this,Q,this.$)}}class z5 extends kY{traverseApply=(Q,J)=>{if(!this.traverseAllows(Q,J))J.error(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`${Q.ctx}.error(${this.compiledErrorContext})`))}get errorContext(){return{code:this.kind,description:this.description,...this.inner}}get compiledErrorContext(){return w4(this.errorContext)}}var _X=(Q)=>(J,G)=>{if(V9(J)){if(J.length===0)return;let K=J.map((z)=>G.$.node(Q,z));if(Q==="predicate")return K;return K.sort((z,q)=>z.hash<q.hash?-1:1)}let H=G.$.node(Q,J);return H.hasOpenIntersection()?[H]:H},uK=(Q)=>{let J=Q.r.shift();if(!J){let H=Q.l.length===0&&Q.kind==="structure"?NQ.intrinsic.unknown.internal:Q.ctx.$.node(Q.kind,Object.assign(Q.baseInner,Ms0(Q.l)),{prereduced:!0});for(let K of Q.roots){if(H instanceof _Q)return H;H=M9(K,H,Q.ctx)}return H}let G=!1;for(let H=0;H<Q.l.length;H++){let K=M9(Q.l[H],J,Q.ctx);if(K===null)continue;if(K instanceof _Q)return K;if(!G){if(K.isRoot())return Q.roots.push(K),Q.l.splice(H),uK(Q);Q.l[H]=K,G=!0}else if(!Q.l.includes(K))return i6(`Unexpectedly encountered multiple distinct intersection results for refinement ${K}`)}if(!G)Q.l.push(J);if(Q.kind==="intersection")J.impliedSiblings?.forEach((H)=>H5(Q.r,H));return uK(Q)},pK=(Q)=>{return Object.entries(Q).flatMap(([G,H])=>(G in UP)?H:[]).sort((G,H)=>G.precedence<H.precedence?-1:G.precedence>H.precedence?1:G.kind==="predicate"&&H.kind==="predicate"?0:G.hash<H.hash?-1:1)},Ms0=(Q)=>{let J={};for(let G of Q)if(G.hasOpenIntersection())J[G.kind]=D6(J[G.kind],G);else{if(J[G.kind])return i6(`Unexpected intersection of closed refinements of kind ${G.kind}`);J[G.kind]=G}return J},n30=(...Q)=>zQ(a30(...Q)),a30=(Q,J,G)=>`${I30(Q)} operand must be ${J.description} (was ${G.exclude(J).description})`;var s30=(Q,J,G)=>new E4(Q,J,G,G,null);class FP extends I4{}class E4 extends I4{[bJ]="generic";paramDefs;bodyDef;$;arg$;baseInstantiation;hkt;description;constructor(Q,J,G,H,K){super((...z)=>{let q=r8(this.names,(F,D)=>{let V=this.arg$.parse(z[F]);if(!V.extends(this.constraints[F]))zQ(Ls0(D,this.constraints[F].expression,V.expression));return[D,V]});if(this.defIsLazy()){let F=this.bodyDef(q);return this.$.parse(F)}return this.$.parse(J,{args:q})});this.paramDefs=Q,this.bodyDef=J,this.$=G,this.arg$=H,this.hkt=K,this.description=K?new K().description??`a generic type for ${K.constructor.name}`:"a generic type",this.baseInstantiation=this(...this.constraints)}defIsLazy(){return this.bodyDef instanceof FP}cacheGetter(Q,J){return Object.defineProperty(this,Q,{value:J}),J}get json(){return this.cacheGetter("json",{params:this.params.map((Q)=>Q[1].isUnknown()?Q[0]:[Q[0],Q[1].json]),body:h30(this.bodyDef)})}get params(){return this.cacheGetter("params",this.paramDefs.map((Q)=>typeof Q==="string"?[Q,NQ.intrinsic.unknown]:[Q[0],this.$.parse(Q[1])]))}get names(){return this.cacheGetter("names",this.params.map((Q)=>Q[0]))}get constraints(){return this.cacheGetter("constraints",this.params.map((Q)=>Q[1]))}get internal(){return this}get referencesById(){return this.baseInstantiation.internal.referencesById}get references(){return this.baseInstantiation.internal.references}}var Ls0=(Q,J,G)=>`${Q} must be assignable to ${J} (was ${G})`;var x9=(Q)=>{let J=typeof Q==="string"?{description:Q}:Q,G=`${J.description} is not convertible to JSON Schema`;if(J.reason)G+=` because ${J.reason}`;return G},r30=(Q)=>x9({description:`Morph ${Q}`,reason:"it represents a transformation, while JSON Schema only allows validation. Consider creating a Schema from one of its endpoints using `.in` or `.out`."}),t30=(Q)=>x9({description:Q,reason:"cyclic types are not yet convertible to JSON Schema. If this feature is important to you, please add your feedback at https://github.com/arktypeio/arktype/issues/1087"}),S4=(Q,J)=>i6(`Unexpected JSON Schema input for ${Q}: ${n8(J)}`);var Os0=u8({kind:"predicate",hasAssociatedError:!0,collapsibleKey:"predicate",keys:{predicate:{}},normalize:(Q)=>typeof Q==="function"?{predicate:Q}:Q,defaults:{description:(Q)=>`valid according to ${Q.predicate.name||"an anonymous predicate"}`},intersectionIsOpen:!0,intersections:{predicate:()=>null}});class e30 extends kY{serializedPredicate=j7(this.predicate);compiledCondition=`${this.serializedPredicate}(data, ctx)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=null;expression=this.serializedPredicate;traverseAllows=this.predicate;errorContext={code:"predicate",description:this.description};compiledErrorContext=w4(this.errorContext);traverseApply=(Q,J)=>{if(!this.predicate(Q,J)&&!J.hasError())J.error(this.errorContext)};compile(Q){if(Q.traversalKind==="Allows"){Q.return(this.compiledCondition);return}Q.if(`${this.compiledNegation} && !ctx.hasError()`,()=>Q.line(`ctx.error(${this.compiledErrorContext})`))}reduceJsonSchema(){return zQ(x9({description:`Predicate ${this.expression}`}))}}var Sk={implementation:Os0,Node:e30};var Ps0=u8({kind:"divisor",collapsibleKey:"rule",keys:{rule:{}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>Q.rule===1?"an integer":`a multiple of ${Q.rule}`},intersections:{divisor:(Q,J,G)=>G.$.node("divisor",{rule:Math.abs(Q.rule*J.rule/Ns0(Q.rule,J.rule))})}});class QB0 extends z5{traverseAllows=(Q)=>Q%this.rule===0;compiledCondition=`data % ${this.rule} === 0`;compiledNegation=`data % ${this.rule} !== 0`;impliedBasis=NQ.intrinsic.number.internal;expression=`% ${this.rule}`;reduceJsonSchema(Q){if(Q.type="integer",this.rule===1)return Q;return Q.multipleOf=this.rule,Q}}var Tk={implementation:Ps0,Node:QB0};var Ns0=(Q,J)=>{let G,H=Q,K=J;while(K!==0)G=K,K=H%K,H=G;return H};class BY extends z5{boundOperandKind=Rs0[this.kind];compiledActual=this.boundOperandKind==="value"?"data":this.boundOperandKind==="length"?"data.length":"data.valueOf()";comparator=ws0(this.kind,this.exclusive);numericLimit=this.rule.valueOf();expression=`${this.comparator} ${this.rule}`;compiledCondition=`${this.compiledActual} ${this.comparator} ${this.numericLimit}`;compiledNegation=`${this.compiledActual} ${js0[this.comparator]} ${this.numericLimit}`;stringLimit=this.boundOperandKind==="date"?Es0(this.numericLimit):`${this.numericLimit}`;limitKind=this.comparator["0"]==="<"?"upper":"lower";isStricterThan(Q){return(this.limitKind==="upper"?this.numericLimit<Q.numericLimit:this.numericLimit>Q.numericLimit)||this.numericLimit===Q.numericLimit&&this.exclusive===!0&&!Q.exclusive}overlapsRange(Q){if(this.isStricterThan(Q))return!1;if(this.numericLimit===Q.numericLimit&&(this.exclusive||Q.exclusive))return!1;return!0}overlapIsUnit(Q){return this.numericLimit===Q.numericLimit&&!this.exclusive&&!Q.exclusive}}var js0={"<":">=","<=":">",">":"<=",">=":"<"},Cs0={min:"max",minLength:"maxLength",after:"before"},DP={parse:(Q)=>Q||void 0},MP=(Q)=>(J)=>{if(typeof J==="number")return{rule:J};let{exclusive:G,...H}=J;return G?{...H,rule:Q==="minLength"?H.rule+1:H.rule-1}:H},LP=(Q)=>(J)=>{if(typeof J==="number"||typeof J==="string"||J instanceof Date)return{rule:J};let{exclusive:G,...H}=J;if(!G)return H;let K=typeof H.rule==="number"?H.rule:typeof H.rule==="string"?new Date(H.rule).valueOf():H.rule.valueOf();return G?{...H,rule:Q==="after"?K+1:K-1}:H},OP=(Q)=>typeof Q==="string"||typeof Q==="number"?new Date(Q):Q,Is0=(Q,J)=>`${Q} bound must be a positive integer (was ${J})`,lK=(Q)=>(J)=>{if(!Number.isInteger(J)||J<0)zQ(Is0(Q,J));return J},Rs0={min:"value",max:"value",minLength:"length",maxLength:"length",after:"date",before:"date"},ws0=(Q,J)=>`${ZX(Q,Cs0)?">":"<"}${J?"":"="}`,Es0=(Q)=>typeof Q==="string"?Q:new Date(Q).toLocaleString(),XB0=(Q)=>`Bounded expression ${Q} must be exactly one of number, string, Array, or Date`;var Ss0=u8({kind:"after",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:OP,serialize:(Q)=>Q.toISOString()}},normalize:LP("after"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or later`,actual:K3},intersections:{after:(Q,J)=>Q.isStricterThan(J)?Q:J}});class JB0 extends BY{impliedBasis=NQ.intrinsic.Date.internal;collapsibleLimitString=K3(this.rule);traverseAllows=(Q)=>Q>=this.rule;reduceJsonSchema(){return zQ(x9("Date instance"))}}var kk={implementation:Ss0,Node:JB0};var Ts0=u8({kind:"before",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:OP,serialize:(Q)=>Q.toISOString()}},normalize:LP("before"),defaults:{description:(Q)=>`${Q.collapsibleLimitString} or earlier`,actual:K3},intersections:{before:(Q,J)=>Q.isStricterThan(J)?Q:J,after:(Q,J,G)=>Q.overlapsRange(J)?Q.overlapIsUnit(J)?G.$.node("unit",{unit:Q.rule}):null:_Q.init("range",Q,J)}});class YB0 extends BY{collapsibleLimitString=K3(this.rule);traverseAllows=(Q)=>Q<=this.rule;impliedBasis=NQ.intrinsic.Date.internal;reduceJsonSchema(){return zQ(x9("Date instance"))}}var yk={implementation:Ts0,Node:YB0};var ks0=u8({kind:"exactLength",collapsibleKey:"rule",keys:{rule:{parse:lK("exactLength")}},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,hasAssociatedError:!0,defaults:{description:(Q)=>`exactly length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{exactLength:(Q,J,G)=>_Q.init("unit",G.$.node("unit",{unit:Q.rule}),G.$.node("unit",{unit:J.rule}),{path:["length"]}),minLength:(Q,J)=>Q.rule>=J.rule?Q:_Q.init("range",Q,J),maxLength:(Q,J)=>Q.rule<=J.rule?Q:_Q.init("range",Q,J)}});class GB0 extends z5{traverseAllows=(Q)=>Q.length===this.rule;compiledCondition=`data.length === ${this.rule}`;compiledNegation=`data.length !== ${this.rule}`;impliedBasis=NQ.intrinsic.lengthBoundable.internal;expression=`== ${this.rule}`;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q.maxLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q.maxItems=this.rule,Q;default:return S4("exactLength",Q)}}}var vk={implementation:ks0,Node:GB0};var ys0=u8({kind:"max",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:DP},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>`${Q.exclusive?"less than":"at most"} ${Q.rule}`},intersections:{max:(Q,J)=>Q.isStricterThan(J)?Q:J,min:(Q,J,G)=>Q.overlapsRange(J)?Q.overlapIsUnit(J)?G.$.node("unit",{unit:Q.rule}):null:_Q.init("range",Q,J)}});class WB0 extends BY{impliedBasis=NQ.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q<this.rule:(Q)=>Q<=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMaximum=this.rule;else Q.maximum=this.rule;return Q}}var xk={implementation:ys0,Node:WB0};var vs0=u8({kind:"maxLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:lK("maxLength")}},reduce:(Q,J)=>Q.rule===0?J.node("exactLength",Q):void 0,normalize:MP("maxLength"),defaults:{description:(Q)=>`at most length ${Q.rule}`,actual:(Q)=>`${Q.length}`},intersections:{maxLength:(Q,J)=>Q.isStricterThan(J)?Q:J,minLength:(Q,J,G)=>Q.overlapsRange(J)?Q.overlapIsUnit(J)?G.$.node("exactLength",{rule:Q.rule}):null:_Q.init("range",Q,J)}});class HB0 extends BY{impliedBasis=NQ.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length<=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.maxLength=this.rule,Q;case"array":return Q.maxItems=this.rule,Q;default:return S4("maxLength",Q)}}}var bk={implementation:vs0,Node:HB0};var xs0=u8({kind:"min",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{},exclusive:DP},normalize:(Q)=>typeof Q==="number"?{rule:Q}:Q,defaults:{description:(Q)=>`${Q.exclusive?"more than":"at least"} ${Q.rule}`},intersections:{min:(Q,J)=>Q.isStricterThan(J)?Q:J}});class BB0 extends BY{impliedBasis=NQ.intrinsic.number.internal;traverseAllows=this.exclusive?(Q)=>Q>this.rule:(Q)=>Q>=this.rule;reduceJsonSchema(Q){if(this.exclusive)Q.exclusiveMinimum=this.rule;else Q.minimum=this.rule;return Q}}var gk={implementation:xs0,Node:BB0};var bs0=u8({kind:"minLength",collapsibleKey:"rule",hasAssociatedError:!0,keys:{rule:{parse:lK("minLength")}},reduce:(Q)=>Q.rule===0?NQ.intrinsic.unknown:void 0,normalize:MP("minLength"),defaults:{description:(Q)=>Q.rule===1?"non-empty":`at least length ${Q.rule}`,actual:(Q)=>Q.length===0?"":`${Q.length}`},intersections:{minLength:(Q,J)=>Q.isStricterThan(J)?Q:J}});class AB0 extends BY{impliedBasis=NQ.intrinsic.lengthBoundable.internal;traverseAllows=(Q)=>Q.length>=this.rule;reduceJsonSchema(Q){switch(Q.type){case"string":return Q.minLength=this.rule,Q;case"array":return Q.minItems=this.rule,Q;default:return S4("minLength",Q)}}}var hk={implementation:bs0,Node:AB0};var KB0={min:gk.implementation,max:xk.implementation,minLength:hk.implementation,maxLength:bk.implementation,exactLength:vk.implementation,after:kk.implementation,before:yk.implementation},zB0={min:gk.Node,max:xk.Node,minLength:hk.Node,maxLength:bk.Node,exactLength:vk.Node,after:kk.Node,before:yk.Node};var gs0=u8({kind:"pattern",collapsibleKey:"rule",keys:{rule:{},flags:{}},normalize:(Q)=>typeof Q==="string"?{rule:Q}:Q instanceof RegExp?Q.flags?{rule:Q.source,flags:Q.flags}:{rule:Q.source}:Q,hasAssociatedError:!0,intersectionIsOpen:!0,defaults:{description:(Q)=>`matched by ${Q.rule}`},intersections:{pattern:()=>null}});class VB0 extends z5{instance=new RegExp(this.rule,this.flags);expression=`${this.instance}`;traverseAllows=this.instance.test.bind(this.instance);compiledCondition=`${this.expression}.test(data)`;compiledNegation=`!${this.compiledCondition}`;impliedBasis=NQ.intrinsic.string.internal;reduceJsonSchema(Q){if(Q.pattern)return zQ(x9(`Intersection of patterns ${Q.pattern} & ${this.rule}`));return Q.pattern=this.rule,Q}}var _k={implementation:gs0,Node:VB0};var eq=(Q,J)=>{let G=hs0(Q);if(J&&!J.includes(G))return zQ(`Root of kind ${G} should be one of ${J}`);return G},hs0=(Q)=>{if(Q8(Q,"root"))return Q.kind;if(typeof Q==="string")return Q[0]==="$"?"alias":"domain";if(typeof Q==="function")return"proto";if(typeof Q!=="object"||Q===null)return zQ(qB0(Q));if("morphs"in Q)return"morph";if("branches"in Q||V9(Q))return"union";if("unit"in Q)return"unit";if("reference"in Q)return"alias";let J=Object.keys(Q);if(J.length===0||J.some((G)=>(G in UP)))return"intersection";if("proto"in Q)return"proto";if("domain"in Q)return"domain";return zQ(qB0(Q))},qB0=(Q)=>`${n8(Q)} is not a valid type schema`,UB0={},_s0=(Q)=>V9(Q)?Q.map((J)=>J.collapsibleJson):Q.collapsibleJson,VJ={};NQ.nodesByRegisteredId=VJ;var fk=(Q)=>{return UB0[Q]??=0,`${Q}${++UB0[Q]}`},mk=(Q)=>{let J=dK[Q.kind],G={},{meta:H,...K}=Q.def,z=H===void 0?{}:typeof H==="string"?{description:H}:H,q=zk(K).sort(([D],[V])=>hK(D)?hK(V)?_K(D)-_K(V):1:hK(V)?-1:D<V?-1:1).filter(([D,V])=>{if(D.startsWith("meta.")){let O=D.slice(5);return z[O]=V,!1}return!0});for(let D of q){let V=D[0],O=J.keys[V];if(!O)return zQ(`Key ${V} is not valid on ${Q.kind} schema`);let P=O.parse?O.parse(D[1],Q):D[1];if(P!==W3&&(P!==void 0||O.preserveUndefined))G[V]=P}if(J.reduce&&!Q.prereduced){let D=J.reduce(G,Q.$);if(D){if(D instanceof _Q)return D.throw();return fs0(D,z)}}return uk(Q.id,Q.kind,G,z,Q.$)},uk=(Q,J,G,H,K,z)=>{let q=dK[J],F=zk(G),D=[],V={};if(F.forEach(([T,y])=>{let x=q.keys[T],b=x.serialize??(x.child?_s0:K5);if(V[T]=b(y),x.child===!0){let g=y;if(V9(g))D.push(...g);else D.push(g)}else if(typeof x.child==="function")D.push(...x.child(y))}),q.finalizeInnerJson)V=q.finalizeInnerJson(V);let O={...V},P={};if(!UG(H))P=r8(H,(T,y)=>[T,T==="examples"?y:K5(y)]),O.meta=PP(P,"description",!0);V=PP(V,q.collapsibleKey,!1);let N=JSON.stringify({kind:J,...V});O=PP(O,q.collapsibleKey,!1);let I=PP(O,q.collapsibleKey,!0),R=JSON.stringify({kind:J,...O});if(K.nodesByHash[R]&&!z)return K.nodesByHash[R];let w={id:Q,kind:J,impl:q,inner:G,innerEntries:F,innerJson:V,innerHash:N,meta:H,metaJson:P,json:O,hash:R,collapsibleJson:I,children:D};for(let T in G)if(T!=="in"&&T!=="out")w[T]=G[T];let E=new ZB0[J](w,K);return K.nodesByHash[R]=E},$B0=(Q,J)=>{if(Q.id===J)return Q;if(C9(VJ[J]))i6(`Unexpected attempt to overwrite node id ${J}`);return uk(J,Q.kind,Q.inner,Q.meta,Q.$,!0)},fs0=(Q,J,G)=>{if(G&&C9(VJ[G]))i6(`Unexpected attempt to overwrite node id ${G}`);return uk(G??fk(J.alias??Q.kind),Q.kind,Q.inner,J,Q.$)},PP=(Q,J,G)=>{let H=Object.keys(Q);if(H.length===1&&H[0]===J){let K=Q[J];if(G)return K;if(xJ(K,"object")&&(Object.keys(K).length===1||Array.isArray(K)))return K}return Q};var QU=(Q,J,G)=>{if(Q.key!==J.key)return null;let H=Q.key,K=M9(Q.value,J.value,G),z=Q.required||J.required?"required":"optional";if(K instanceof _Q)if(z==="optional")K=NQ.intrinsic.never.internal;else return K.withPrefixKey(Q.key,Q.required&&J.required?"required":"optional");if(z==="required")return G.$.node("required",{key:H,value:K});let q=Q.hasDefault()?J.hasDefault()?Q.default===J.default?Q.default:zQ(pk(Q.default,J.default)):Q.default:J.hasDefault()?J.default:W3;return G.$.node("optional",{key:H,value:K,default:q})};class XU extends kY{required=this.kind==="required";optional=this.kind==="optional";impliedBasis=NQ.intrinsic.object.internal;serializedKey=A5(this.key);compiledKey=typeof this.key==="string"?this.key:this.serializedKey;get flatRefs(){return D6(this.value.flatRefs.map((Q)=>$G([this.key,...Q.path],Q.node)),$G([this.key],this.value))}_transform(Q,J){J.path.push(this.key);let G=super._transform(Q,J);return J.path.pop(),G}hasDefault(){return"default"in this.inner}traverseAllows=(Q,J)=>{if(this.key in Q)return hJ(this.key,()=>this.value.traverseAllows(Q[this.key],J),J);return this.optional};traverseApply=(Q,J)=>{if(this.key in Q)hJ(this.key,()=>this.value.traverseApply(Q[this.key],J),J);else if(this.hasKind("required"))J.error(this.errorContext);else if(this.hasDefault())J.queueMorphs(this.defaultValueMorphs)};compile(Q){if(Q.if(`${this.serializedKey} in data`,()=>Q.traverseKey(this.serializedKey,`data${Q.prop(this.key)}`,this.value)),this.hasKind("required"))Q.else(()=>{if(Q.traversalKind==="Apply")return Q.line(`ctx.error(${this.compiledErrorContext})`);else return Q.return(!1)});else if(Q.traversalKind==="Apply"&&this.hasDefault())Q.else(()=>Q.line(`ctx.queueMorphs(${this.defaultValueMorphsReference})`));if(Q.traversalKind==="Allows")Q.return(!0)}}var pk=(Q,J)=>`Invalid intersection of default values ${n8(Q)} & ${n8(J)}`;var ms0=u8({kind:"optional",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,J)=>J.$.parseSchema(Q)},default:{preserveUndefined:!0}},normalize:(Q)=>Q,defaults:{description:(Q)=>`${Q.compiledKey}?: ${Q.value.description}`},intersections:{optional:QU}});class FB0 extends XU{constructor(...Q){super(...Q);if("default"in this.inner)YU(this.value,this.inner.default,this.key)}get outProp(){if(!this.hasDefault())return this;let{default:Q,...J}=this.inner;return this.cacheGetter("outProp",this.$.node("required",J,{prereduced:!0}))}expression=this.hasDefault()?`${this.compiledKey}: ${this.value.expression} = ${n8(this.inner.default)}`:`${this.compiledKey}?: ${this.value.expression}`;defaultValueMorphs=this.hasDefault()?lk(this.key,this.value,this.default):[];defaultValueMorphsReference=j7(this.defaultValueMorphs)}var JU={implementation:ms0,Node:FB0},lk=(Q,J,G)=>{if(typeof G==="function")return[J.includesMorph?(K,z)=>{return hJ(Q,()=>J(K[Q]=G(),z),z),K}:(K)=>{return K[Q]=G(),K}];let H=J.includesMorph?J.assert(G):G;return[xJ(H,"object")?(K,z)=>{return hJ(Q,()=>J(K[Q]=G,z),z),K}:(K)=>{return K[Q]=H,K}]},YU=(Q,J,G)=>{let H=C4(J);if(xJ(J,"object")&&!H)zQ(us0(G));let K=Q.in(H?J():J);if(K instanceof gJ){if(G!==null)K.forEach((q)=>q.path.unshift(G));let z=G===null?`Default ${K.message}`:`Default for ${K.message}`;zQ(z)}return J},us0=(Q)=>{return`Non-primitive default ${Q===null?"":typeof Q==="number"?`for value at [${Q}] `:`for ${A5(Q)} `}must be specified as a function like () => ({my: 'object'})`};class yY extends tq{constructor(Q,J){super(Q,J);Object.defineProperty(this,bJ,{value:"root",enumerable:!1})}assert=(Q)=>{let J=this.traverse(Q);return J instanceof gJ?J.throw():J};get internal(){return this}get "~standard"(){return{vendor:"arktype",version:1,validate:(Q)=>{let J=this(Q);if(J instanceof gJ)return J;return{value:J}}}}as(){return this}brand(Q){if(Q==="")return zQ(ps0);return this}brandAttributes(){return this}unbrandAttributes(){return this}readonly(){return this}branches=this.hasKind("union")?this.inner.branches:[this];distribute(Q,J){let G=this.branches.map(Q);return J?.(G)??G}toJsonSchema(){let Q=this.innerToJsonSchema();return Object.assign(Q,this.metaJson)}intersect(Q){let J=this.$.parseDefinition(Q),G=this.rawIntersect(J);if(G instanceof _Q)return G;return this.$.finalize(G)}rawIntersect(Q){return HY(this,Q,this.$)}toNeverIfDisjoint(){return this}and(Q){let J=this.intersect(Q);return J instanceof _Q?J.throw():J}rawAnd(Q){let J=this.rawIntersect(Q);return J instanceof _Q?J.throw():J}or(Q){let J=this.$.parseDefinition(Q);return this.$.finalize(this.rawOr(J))}rawOr(Q){let J=[...this.branches,...Q.branches];return this.$.node("union",J)}map(Q){return this.$.schema(this.applyStructuralOperation("map",[Q]))}pick(...Q){return this.$.schema(this.applyStructuralOperation("pick",Q))}omit(...Q){return this.$.schema(this.applyStructuralOperation("omit",Q))}required(){return this.$.schema(this.applyStructuralOperation("required",[]))}partial(){return this.$.schema(this.applyStructuralOperation("partial",[]))}_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.applyStructuralOperation("keyof",[]).reduce((J,G)=>J.intersect(G).toNeverIfDisjoint(),NQ.intrinsic.unknown.internal);if(Q.branches.length===0)zQ(Rk(`keyof ${this.expression}`));return this._keyof=this.$.finalize(Q)}get props(){if(this.branches.length!==1)return zQ(ls0(this.expression));return[...this.applyStructuralOperation("props",[])[0]]}merge(Q){let J=this.$.parseDefinition(Q);return this.$.schema(J.distribute((G)=>this.applyStructuralOperation("merge",[DB0(G)??zQ(MB0("merge",G.expression))])))}applyStructuralOperation(Q,J){return this.distribute((G)=>{if(G.equals(NQ.intrinsic.object)&&Q!=="merge")return G;let H=DB0(G);if(!H)zQ(MB0(Q,G.expression));if(Q==="keyof")return H.keyof();if(Q==="get")return H.get(...J);if(Q==="props")return H.props;let K=Q==="required"?"require":Q==="partial"?"optionalize":Q;return this.$.node("intersection",{...G.inner,structure:H[K](...J)})})}get(...Q){if(Q[0]===void 0)return this;return this.$.schema(this.applyStructuralOperation("get",Q))}extract(Q){let J=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((G)=>G.extends(J)))}exclude(Q){let J=this.$.parseDefinition(Q);return this.$.schema(this.branches.filter((G)=>!G.extends(J)))}array(){return this.$.schema({proto:Array,sequence:this},{prereduced:!0})}overlaps(Q){return!(this.intersect(Q)instanceof _Q)}extends(Q){let J=this.intersect(Q);return!(J instanceof _Q)&&this.equals(J)}ifExtends(Q){return this.extends(Q)?this:void 0}subsumes(Q){return this.$.parseDefinition(Q).extends(this)}configure(Q){return this.configureShallowDescendants(Q)}describe(Q){return this.configure({description:Q})}optional(){return[this,"?"]}default(Q){return YU(this,Q,null),[this,"=",Q]}from(Q){return this.assert(Q)}_pipe(...Q){return Q.reduce((J,G)=>J.pipeOnce(G),this)}tryPipe(...Q){return Q.reduce((J,G)=>J.pipeOnce(Q8(G,"root")?G:(H,K)=>{try{return G(H,K)}catch(z){return K.error({code:"predicate",predicate:G,actual:`aborted due to error:
${z}
`})}}),this)}pipe=Object.assign(this._pipe.bind(this),{try:this.tryPipe.bind(this)});to(Q){return this.$.finalize(this.toNode(this.$.parseDefinition(Q)))}toNode(Q){let J=Ek(this,Q,this.$);if(J instanceof _Q)return J.throw();return J}pipeOnce(Q){if(Q8(Q,"root"))return this.toNode(Q);return this.distribute((J)=>J.hasKind("morph")?this.$.node("morph",{in:J.inner.in,morphs:[...J.morphs,Q]}):this.$.node("morph",{in:J,morphs:[Q]}),this.$.parseSchema)}get flatMorphs(){return this.cacheGetter("flatMorphs",this.flatRefs.reduce((Q,J)=>fK(Q,J.node.hasKind("union")?J.node.branches.filter((G)=>G.hasKind("morph")).map((G)=>({path:J.path,propString:J.propString,node:G})):J.node.hasKind("morph")?J:[]),[]))}narrow(Q){return this.constrainOut("predicate",Q)}constrain(Q,J){return this._constrain("root",Q,J)}constrainIn(Q,J){return this._constrain("in",Q,J)}constrainOut(Q,J){return this._constrain("out",Q,J)}_constrain(Q,J,G){let H=this.$.node(J,G);if(H.isRoot())return H.isUnknown()?this:i6(`Unexpected constraint node ${H}`);let K=Q==="root"?this:this[Q];if(K.hasKind("morph")||H.impliedBasis&&!K.extends(H.impliedBasis))return n30(J,H.impliedBasis,this);let z=this.$.node("intersection",{[H.kind]:H}),q=Q==="out"?Ek(this,z,this.$):HY(this,z,this.$);if(q instanceof _Q)q.throw();return this.$.finalize(q)}onUndeclaredKey(Q){let J=typeof Q==="string"?Q:Q.rule,G=typeof Q==="string"?!1:Q.deep;return this.$.finalize(this.transform((H,K)=>H==="structure"?J==="ignore"?F30(K,{undeclared:1}):{...K,undeclared:J}:K,G?void 0:{shouldTransform:(H)=>!W5(bK,H.kind)}))}onDeepUndeclaredKey(Q){return this.onUndeclaredKey({rule:Q,deep:!0})}satisfying(Q){return this.constrain("predicate",Q)}divisibleBy(Q){return this.constrain("divisor",Q)}matching(Q){return this.constrain("pattern",Q)}atLeast(Q){return this.constrain("min",Q)}atMost(Q){return this.constrain("max",Q)}moreThan(Q){return this.constrain("min",cK(Q))}lessThan(Q){return this.constrain("max",cK(Q))}atLeastLength(Q){return this.constrain("minLength",Q)}atMostLength(Q){return this.constrain("maxLength",Q)}moreThanLength(Q){return this.constrain("minLength",cK(Q))}lessThanLength(Q){return this.constrain("maxLength",cK(Q))}exactlyLength(Q){return this.constrain("exactLength",Q)}atOrAfter(Q){return this.constrain("after",Q)}atOrBefore(Q){return this.constrain("before",Q)}laterThan(Q){return this.constrain("after",cK(Q))}earlierThan(Q){return this.constrain("before",cK(Q))}}var ps0="Expected a non-empty brand name after #",cK=(Q)=>typeof Q==="object"&&!(Q instanceof Date)?{...Q,exclusive:!0}:{rule:Q,exclusive:!0},GU=(Q,J)=>Q8(J,"root")?Q8(Q,"root")?Q.extends(J):J.allows(Q):Q8(Q,"root")?Q.hasUnit(J):J===Q,DB0=(Q)=>{if(Q.hasKind("morph"))return null;if(Q.hasKind("intersection"))return Q.inner.structure??(Q.basis?.domain==="object"?Q.$.bindReference(NQ.intrinsic.emptyStructure):null);if(Q.isBasis()&&Q.domain==="object")return Q.$.bindReference(NQ.intrinsic.emptyStructure);return null},ls0=(Q)=>`Props cannot be extracted from a union. Use .distribute to extract props from each branch instead. Received:
${Q}`,MB0=(Q,J)=>`${Q} operand must be an object (was ${J})`;var FW=(Q,J)=>r8($P(Q),(G,H)=>[H,J]);var ds0=(Q)=>typeof Q==="string"?{reference:Q}:Q,LB0=(Q)=>Q instanceof _Q?NQ.intrinsic.never.internal:Q,cs0=u8({kind:"alias",hasAssociatedError:!1,collapsibleKey:"reference",keys:{reference:{serialize:(Q)=>Q.startsWith("$")?Q:`$ark.${Q}`},resolve:{}},normalize:ds0,defaults:{description:(Q)=>Q.reference},intersections:{alias:(Q,J,G)=>G.$.lazilyResolve(()=>LB0(M9(Q.resolution,J.resolution,G)),`${Q.reference}${G.pipe?"=>":"&"}${J.reference}`),...FW("alias",(Q,J,G)=>{if(J.isUnknown())return Q;if(J.isNever())return J;return G.$.lazilyResolve(()=>LB0(M9(Q.resolution,J,G)),`${Q.reference}${G.pipe?"=>":"&"}${J.id}`)})}});class OB0 extends yY{expression=this.reference;structure=void 0;get resolution(){let Q=this._resolve();return VJ[this.id]=Q}_resolve(){if(this.resolve)return this.resolve();if(this.reference[0]==="$")return this.$.resolveRoot(this.reference.slice(1));let Q=this.reference,J=VJ[Q],G=[];while(Q8(J,"context")){if(G.includes(J.id))return zQ(is0(J.id,G));G.push(J.id),J=VJ[J.id]}if(!Q8(J,"root"))return i6(`Unexpected resolution for reference ${this.reference}
Seen: [${G.join("->")}]
Resolution: ${n8(J)}`);return J}get resolutionId(){if(this.reference.includes("&")||this.reference.includes("=>"))return this.resolution.id;if(this.reference[0]!=="$")return this.reference;let Q=this.reference.slice(1),J=this.$.resolutions[Q];if(typeof J==="string")return J;if(Q8(J,"root"))return J.id;return i6(`Unexpected resolution for reference ${this.reference}: ${n8(J)}`)}get shortDescription(){return TY.object}innerToJsonSchema(){return zQ(t30(this.expression))}traverseAllows=(Q,J)=>{let G=J.seen[this.reference];if(G?.includes(Q))return!0;return J.seen[this.reference]=D6(G,Q),this.resolution.traverseAllows(Q,J)};traverseApply=(Q,J)=>{let G=J.seen[this.reference];if(G?.includes(Q))return;J.seen[this.reference]=D6(G,Q),this.resolution.traverseApply(Q,J)};compile(Q){let J=this.resolutionId;Q.if(`ctx.seen.${J} && ctx.seen.${J}.includes(data)`,()=>Q.return(!0)),Q.if(`!ctx.seen.${J}`,()=>Q.line(`ctx.seen.${J} = []`)),Q.line(`ctx.seen.${J}.push(data)`),Q.return(Q.invoke(J))}}var is0=(Q,J)=>`Alias '${Q}' has a shallow resolution cycle: ${[...J,Q].join("->")}`,WU={implementation:cs0,Node:OB0};class U3 extends yY{traverseApply=(Q,J)=>{if(!this.traverseAllows(Q,J))J.error(this.errorContext)};get errorContext(){return{code:this.kind,description:this.description,...this.inner}}get compiledErrorContext(){return w4(this.errorContext)}compile(Q){if(Q.traversalKind==="Allows")Q.return(this.compiledCondition);else Q.if(this.compiledNegation,()=>Q.line(`${Q.ctx}.error(${this.compiledErrorContext})`))}}var os0=u8({kind:"domain",hasAssociatedError:!0,collapsibleKey:"domain",keys:{domain:{}},normalize:(Q)=>typeof Q==="string"?{domain:Q}:Q,defaults:{description:(Q)=>TY[Q.domain],actual:(Q)=>TY[zJ(Q)]},intersections:{domain:(Q,J)=>_Q.init("domain",Q,J)}});class PB0 extends U3{traverseAllows=(Q)=>zJ(Q)===this.domain;compiledCondition=this.domain==="object"?'((typeof data === "object" && data !== null) || typeof data === "function")':`typeof data === "${this.domain}"`;compiledNegation=this.domain==="object"?'((typeof data !== "object" || data === null) && typeof data !== "function")':`typeof data !== "${this.domain}"`;expression=this.domain;get shortDescription(){return TY[this.domain]}innerToJsonSchema(){if(this.domain==="bigint"||this.domain==="symbol")return zQ(x9(this.domain));return{type:this.domain}}}var dk={implementation:os0,Node:PB0};var ns0=u8({kind:"intersection",hasAssociatedError:!0,normalize:(Q)=>{if(C9(Q))return Q;let{structure:J,...G}=Q,H=!!J,K=J??{},z=r8(G,(q,F)=>{if(ZX(q,p30)){if(H)zQ(`Flattened structure key ${q} cannot be specified alongside a root 'structure' key.`);return K[q]=F,[]}return[q,F]});if(Q8(K,"constraint")||!UG(K))z.structure=K;return z},finalizeInnerJson:({structure:Q,...J})=>xJ(Q,"object")?{...Q,...J}:J,keys:{domain:{child:!0,parse:(Q,J)=>J.$.node("domain",Q)},proto:{child:!0,parse:(Q,J)=>J.$.node("proto",Q)},structure:{child:!0,parse:(Q,J)=>J.$.node("structure",Q),serialize:(Q)=>{if(!Q.sequence?.minLength)return Q.collapsibleJson;let{sequence:J,...G}=Q.collapsibleJson,{minVariadicLength:H,...K}=J,z=K.variadic&&Object.keys(K).length===1?K.variadic:K;return{...G,sequence:z}}},divisor:{child:!0,parse:_X("divisor")},max:{child:!0,parse:_X("max")},min:{child:!0,parse:_X("min")},maxLength:{child:!0,parse:_X("maxLength")},minLength:{child:!0,parse:_X("minLength")},exactLength:{child:!0,parse:_X("exactLength")},before:{child:!0,parse:_X("before")},after:{child:!0,parse:_X("after")},pattern:{child:!0,parse:_X("pattern")},predicate:{child:!0,parse:_X("predicate")}},reduce:(Q,J)=>NP({},Q,{$:J,invert:!1,pipe:!1}),defaults:{description:(Q)=>Q.children.length===0?"unknown":Q.structure?.description??Q.children.map((J)=>J.description).join(" and "),expected:(Q)=>` • ${Q.errors.map((J)=>J.expected).join(`
• `)}`,problem:(Q)=>`(${Q.actual}) must be...
${Q.expected}`},intersections:{intersection:(Q,J,G)=>NP(Q,J,G),...FW("intersection",(Q,J,G)=>{if(Q.children.length===0)return J;let{domain:H,proto:K,...z}=Q.inner,q=K??H,F=q?M9(q,J,G):J;return F instanceof _Q?F:Q?.basis?.equals(F)?Q:Q.$.node("intersection",{...z,[F.kind]:F},{prereduced:!0})})}});class NB0 extends yY{basis=this.domain??this.proto??null;refinements=this.children.filter((Q)=>Q.isRefinement());get expression(){let Q=this.structure?.expression||`${this.basis?this.basis.nestableExpression+" ":""}${this.refinements.join(" & ")}`||"unknown";if(Q==="Array == 0")Q="[]";return this.cacheGetter("expression",Q)}get shortDescription(){return this.basis?.shortDescription??"present"}innerToJsonSchema(){return this.children.reduce((Q,J)=>J.isBasis()?J.toJsonSchema():J.reduceJsonSchema(Q),{})}traverseAllows=(Q,J)=>this.children.every((G)=>G.traverseAllows(Q,J));traverseApply=(Q,J)=>{let G=J.currentErrorCount;if(this.basis){if(this.basis.traverseApply(Q,J),J.currentErrorCount>G)return}if(this.refinements.length){for(let H=0;H<this.refinements.length-1;H++)if(this.refinements[H].traverseApply(Q,J),J.failFast&&J.currentErrorCount>G)return;if(this.refinements.at(-1).traverseApply(Q,J),J.currentErrorCount>G)return}if(this.structure){if(this.structure.traverseApply(Q,J),J.currentErrorCount>G)return}if(this.predicate){for(let H=0;H<this.predicate.length-1;H++)if(this.predicate[H].traverseApply(Q,J),J.failFast&&J.currentErrorCount>G)return;this.predicate.at(-1).traverseApply(Q,J)}};compile(Q){if(Q.traversalKind==="Allows"){this.children.forEach((J)=>Q.check(J)),Q.return(!0);return}if(Q.initializeErrorCount(),this.basis){if(Q.check(this.basis),this.children.length>1)Q.returnIfFail()}if(this.refinements.length){for(let J=0;J<this.refinements.length-1;J++)Q.check(this.refinements[J]),Q.returnIfFailFast();if(Q.check(this.refinements.at(-1)),this.structure||this.predicate)Q.returnIfFail()}if(this.structure){if(Q.check(this.structure),this.predicate)Q.returnIfFail()}if(this.predicate){for(let J=0;J<this.predicate.length-1;J++)Q.check(this.predicate[J]),Q.returnIfFail();Q.check(this.predicate.at(-1))}}}var ck={implementation:ns0,Node:NB0},NP=(Q,J,G)=>{if(Q8(Q,"root")&&Q.hasKind("intersection"))return NP(Q.inner,J,G);if(Q8(J,"root")&&J.hasKind("intersection"))return NP(Q,J.inner,G);let H={},K=Q.proto??Q.domain,z=J.proto??J.domain,q=K?z?M9(K,z,G):K:z;if(q instanceof _Q)return q;if(q)H[q.kind]=q;return uK({kind:"intersection",baseInner:H,l:pK(Q),r:pK(J),roots:[],ctx:G})};var as0=u8({kind:"morph",hasAssociatedError:!1,keys:{in:{child:!0,parse:(Q,J)=>J.$.parseSchema(Q)},morphs:{parse:kK,serialize:(Q)=>Q.map((J)=>Q8(J,"root")?J.json:j7(J))},declaredIn:{child:!1,serialize:(Q)=>Q.json},declaredOut:{child:!1,serialize:(Q)=>Q.json}},normalize:(Q)=>Q,defaults:{description:(Q)=>`a morph from ${Q.in.description} to ${Q.out?.description??"unknown"}`},intersections:{morph:(Q,J,G)=>{if(!Q.hasEqualMorphs(J))return zQ(ss0(Q.expression,J.expression));let H=M9(Q.in,J.in,G);if(H instanceof _Q)return H;let K={morphs:Q.morphs};if(Q.declaredIn||J.declaredIn){let z=M9(Q.in,J.in,G);if(z instanceof _Q)return z.throw();else K.declaredIn=z}if(Q.declaredOut||J.declaredOut){let z=M9(Q.out,J.out,G);if(z instanceof _Q)return z.throw();else K.declaredOut=z}return H.distribute((z)=>G.$.node("morph",{...K,in:z}),G.$.parseSchema)},...FW("morph",(Q,J,G)=>{let H=Q.inner.in?M9(Q.inner.in,J,G):J;return H instanceof _Q?H:H.equals(Q.inner.in)?Q:G.$.node("morph",{...Q.inner,in:H})})}});class jB0 extends yY{serializedMorphs=this.morphs.map(j7);compiledMorphs=`[${this.serializedMorphs}]`;lastMorph=this.inner.morphs.at(-1);lastMorphIfNode=Q8(this.lastMorph,"root")?this.lastMorph:void 0;introspectableIn=this.inner.in;introspectableOut=this.lastMorphIfNode?Object.assign(this.referencesById,this.lastMorphIfNode.referencesById)&&this.lastMorphIfNode.out:void 0;get in(){return this.declaredIn??this.inner.in?.in??NQ.intrinsic.unknown.internal}get out(){return this.declaredOut??this.introspectableOut??NQ.intrinsic.unknown.internal}declareIn(Q){return this.$.node("morph",{...this.inner,declaredIn:Q})}declareOut(Q){return this.$.node("morph",{...this.inner,declaredOut:Q})}expression=`(In: ${this.in.expression}) => Out<${this.out.expression}>`;get shortDescription(){return this.in.shortDescription}innerToJsonSchema(){return zQ(r30(this.expression))}compile(Q){if(Q.traversalKind==="Allows"){if(!this.introspectableIn)return;Q.return(Q.invoke(this.introspectableIn));return}if(this.introspectableIn)Q.line(Q.invoke(this.introspectableIn));Q.line(`ctx.queueMorphs(${this.compiledMorphs})`)}traverseAllows=(Q,J)=>!this.introspectableIn||this.introspectableIn.traverseAllows(Q,J);traverseApply=(Q,J)=>{if(this.introspectableIn)this.introspectableIn.traverseApply(Q,J);J.queueMorphs(this.morphs)};hasEqualMorphs(Q){return yK(this.morphs,Q.morphs,{isEqual:(J,G)=>J===G||Q8(J,"root")&&Q8(G,"root")&&J.equals(G)})}}var ik={implementation:as0,Node:jB0},ss0=(Q,J)=>`The intersection of distinct morphs at a single path is indeterminate:
Left: ${Q}
Right: ${J}`;var rs0=u8({kind:"proto",hasAssociatedError:!0,collapsibleKey:"proto",keys:{proto:{serialize:(Q)=>oq(Q)??K5(Q)}},normalize:(Q)=>typeof Q==="string"?{proto:H3[Q]}:typeof Q==="function"?C9(Q)?Q:{proto:Q}:typeof Q.proto==="string"?{...Q,proto:H3[Q.proto]}:Q,defaults:{description:(Q)=>Q.builtinName?M30[Q.builtinName]:`an instance of ${Q.proto.name}`,actual:(Q)=>iq(Q)},intersections:{proto:(Q,J)=>Zk(Q.proto,J.proto)?Q:Zk(J.proto,Q.proto)?J:_Q.init("proto",Q,J),domain:(Q,J)=>J.domain==="object"?Q:_Q.init("domain",NQ.intrinsic.object.internal,J)}});class CB0 extends U3{builtinName=oq(this.proto);serializedConstructor=this.json.proto;compiledCondition=`data instanceof ${this.serializedConstructor}`;compiledNegation=`!(${this.compiledCondition})`;innerToJsonSchema(){switch(this.builtinName){case"Array":return{type:"array"};default:return zQ(x9(this.description))}}traverseAllows=(Q)=>Q instanceof this.proto;expression=this.proto.name;domain="object";get shortDescription(){return this.description}}var ok={implementation:rs0,Node:CB0};var ts0=u8({kind:"union",hasAssociatedError:!0,collapsibleKey:"branches",keys:{ordered:{},branches:{child:!0,parse:(Q,J)=>{let G=[];if(Q.forEach((H)=>{(Q8(H,"root")?H.branches:J.$.parseSchema(H).branches).forEach((z)=>{if(z.hasKind("morph")){let q=G.findIndex((F)=>F.hasKind("morph")&&F.hasEqualMorphs(z));if(q===-1)G.push(z);else{let F=G[q];G[q]=J.$.node("morph",{...F.inner,in:F.in.rawOr(z.in)})}}else G.push(z)})}),!J.def.ordered)G.sort((H,K)=>H.hash<K.hash?-1:1);return G}}},normalize:(Q)=>V9(Q)?{branches:Q}:Q,reduce:(Q,J)=>{let G=Gr0(Q);if(G.length===1)return G[0];if(G.length===Q.branches.length)return;return J.node("union",{...Q,branches:G},{prereduced:!0})},defaults:{description:(Q)=>Q.distribute((J)=>J.description,iK),expected:(Q)=>{let J=WP(Q.errors,"propString"),G=Object.entries(J).map(([H,K])=>{let z=[];K.forEach((D)=>H5(z,D.expected));let q=iK(z),F=K.every((D)=>D.actual===K[0].actual)?K[0].actual:n8(K[0].data);return`${H&&`${H} `}must be ${q}${F&&` (was ${F})`}`});return iK(G)},problem:(Q)=>Q.expected,message:(Q)=>Q.problem},intersections:{union:(Q,J,G)=>{if(Q.isNever!==J.isNever)return _Q.init("presence",Q,J);let H;if(Q.ordered){if(J.ordered)zQ(Ar0(Q.expression,J.expression));if(H=nk(J.branches,Q.branches,G),H instanceof _Q)H.invert()}else H=nk(Q.branches,J.branches,G);if(H instanceof _Q)return H;return G.$.parseSchema(Q.ordered||J.ordered?{branches:H,ordered:!0}:{branches:H})},...FW("union",(Q,J,G)=>{let H=nk(Q.branches,[J],G);if(H instanceof _Q)return H;if(H.length===1)return H[0];return G.$.parseSchema(Q.ordered?{branches:H,ordered:!0}:{branches:H})})}});class IB0 extends yY{isBoolean=this.branches.length===2&&this.branches[0].hasUnit(!1)&&this.branches[1].hasUnit(!0);get branchGroups(){let Q=[],J=-1;return this.branches.forEach((G)=>{if(G.hasKind("unit")&&G.domain==="boolean"){if(J===-1)J=Q.length,Q.push(G);else Q[J]=NQ.intrinsic.boolean;return}Q.push(G)}),Q}unitBranches=this.branches.filter((Q)=>Q.in.hasKind("unit"));discriminant=this.discriminate();discriminantJson=this.discriminant?Xr0(this.discriminant):null;expression=this.distribute((Q)=>Q.nestableExpression,Yr0);get shortDescription(){return this.distribute((Q)=>Q.shortDescription,iK)}innerToJsonSchema(){return{anyOf:this.branchGroups.map((Q)=>Q.equals(NQ.intrinsic.boolean)?{type:"boolean"}:Q.toJsonSchema())}}traverseAllows=(Q,J)=>this.branches.some((G)=>G.traverseAllows(Q,J));traverseApply=(Q,J)=>{let G=[];for(let H=0;H<this.branches.length;H++){if(J.pushBranch(),this.branches[H].traverseApply(Q,J),!J.hasError()){if(this.branches[H].includesMorph)return J.queuedMorphs.push(...J.popBranch().queuedMorphs);return J.popBranch()}G.push(J.popBranch().error)}J.error({code:"union",errors:G})};compile(Q){if(!this.discriminant||this.unitBranches.length===this.branches.length&&this.branches.length===2)return this.compileIndiscriminable(Q);let J=this.discriminant.optionallyChainedPropString;if(this.discriminant.kind==="domain")J=`typeof ${J} === "object" ? ${J} === null ? "null" : "object" : typeof ${J} === "function" ? "object" : typeof ${J}`;let G=this.discriminant.cases,H=Object.keys(G);if(Q.block(`switch(${J})`,()=>{for(let D in G){let V=G[D],O=D==="default"?D:`case ${D}`;Q.line(`${O}: return ${V===!0?V:Q.invoke(V)}`)}return Q}),Q.traversalKind==="Allows"){Q.return(!1);return}let K=iK(this.discriminant.kind==="domain"?H.map((D)=>{let V=D.slice(1,-1);return V==="function"?TY.object:TY[V]}):H),z=this.discriminant.path.map((D)=>typeof D==="string"?JSON.stringify(D):j7(D)),q=JSON.stringify(K),F=this.discriminant.kind==="domain"?`${es0}[${J}]`:`${Qr0}(${J})`;Q.line(`ctx.error({
expected: ${q},
actual: ${F},
relativePath: [${z}]
})`)}compileIndiscriminable(Q){if(Q.traversalKind==="Apply")Q.const("errors","[]"),this.branches.forEach((J)=>Q.line("ctx.pushBranch()").line(Q.invoke(J)).if("!ctx.hasError()",()=>Q.return(J.includesMorph?"ctx.queuedMorphs.push(...ctx.popBranch().queuedMorphs)":"ctx.popBranch()")).line("errors.push(ctx.popBranch().error)")),Q.line('ctx.error({ code: "union", errors })');else this.branches.forEach((J)=>Q.if(`${Q.invoke(J)}`,()=>Q.return(!0))),Q.return(!1)}get nestableExpression(){return this.isBoolean?"boolean":`(${this.expression})`}discriminate(){if(this.branches.length<2)return null;if(this.unitBranches.length===this.branches.length){let z=r8(this.unitBranches,(q,F)=>[`${F.in.serializedValue}`,F.hasKind("morph")?F:!0]);return{kind:"unit",path:[],optionallyChainedPropString:"data",cases:z}}let Q=[];for(let z=0;z<this.branches.length-1;z++){let q=this.branches[z];for(let F=z+1;F<this.branches.length;F++){let D=this.branches[F],V=HY(q.in,D.in,q.$);if(!(V instanceof _Q))continue;for(let O of V){if(!O.kind||O.optional)continue;let P,N;if(O.kind==="domain"){let{l:R,r:w}=O;P=`"${typeof R==="string"?R:R.domain}"`,N=`"${typeof w==="string"?w:w.domain}"`}else if(O.kind==="unit")P=O.l.serializedValue,N=O.r.serializedValue;else continue;let I=Q.find((R)=>yK(R.path,O.path)&&R.kind===O.kind);if(!I)Q.push({kind:O.kind,cases:{[P]:[q],[N]:[D]},path:O.path});else I.cases[P]=H5(I.cases[P],q),I.cases[N]=H5(I.cases[N],D)}}}let J=Q.sort((z,q)=>Object.keys(z.cases).length-Object.keys(q.cases).length).at(-1);if(!J)return null;let G=[...this.branches],H={kind:J.kind,path:J.path,optionallyChainedPropString:RB0(J.path)},K=r8(J.cases,(z,q)=>{let F=[];G=G.filter((V)=>!q.includes(V));for(let V of q){let O=Hr0(V,H);if(O===null)return[z,!0];F.push(O)}let D=F.length===1?F[0]:this.$.node("union",F);return Object.assign(this.referencesById,D.referencesById),[z,D]});if(G.length)K.default=this.$.node("union",G,{prereduced:!0}),Object.assign(this.referencesById,K.default.referencesById);return Object.assign(H,{cases:K})}}var RB0=(Q)=>Q.reduce((J,G)=>J+jk(G,!0),"data"),es0=j7($30),Qr0=j7(n8),ak={implementation:ts0,Node:IB0},Xr0=(Q)=>({kind:Q.kind,path:Q.path.map((J)=>typeof J==="string"?J:A5(J)),cases:r8(Q.cases,(J,G)=>[J,G===!0?G:G.hasKind("union")&&G.discriminantJson?G.discriminantJson:G.json])}),Jr0={delimiter:" | ",finalDelimiter:" | "},Yr0=(Q)=>iK(Q,Jr0),iK=(Q,J)=>{let G=J?.delimiter??", ",H=J?.finalDelimiter??" or ";if(Q.length===0)return"never";if(Q.length===1)return Q[0];if(Q.length===2&&Q[0]==="false"&&Q[1]==="true"||Q[0]==="true"&&Q[1]==="false")return"boolean";let K={},z=Q.filter((F)=>K[F]?!1:K[F]=!0),q=z.pop();return`${z.join(G)}${z.length?H:""}${q}`},nk=(Q,J,G)=>{let H=J.map(()=>[]);for(let z=0;z<Q.length;z++){let q={};for(let F=0;F<J.length;F++){if(H[F]===null)continue;if(Q[z].equals(J[F])){H[F]=null,q={};break}let D=M9(Q[z],J[F],G);if(D instanceof _Q)continue;if(D.equals(Q[z])){H[F].push(Q[z]),q={};break}if(D.equals(J[F]))H[F]=null;else q[F]=D}for(let F in q)H[F][z]=q[F]}let K=H.flatMap((z,q)=>z?.flatMap((F)=>F.branches)??J[q]);return K.length===0?_Q.init("union",Q,J):K},Gr0=({branches:Q,ordered:J})=>{if(Q.length<2)return Q;let G=Q.map(()=>!0);for(let H=0;H<Q.length;H++)for(let K=H+1;K<Q.length&&G[H]&&G[K];K++){if(Q[H].equals(Q[K])){G[K]=!1;continue}let z=HY(Q[H].in,Q[K].in,Q[0].$);if(z instanceof _Q)continue;if(!J)Wr0(Q[H],Q[K]);if(z.equals(Q[H].in))G[H]=!!J;else if(z.equals(Q[K].in))G[K]=!1}return Q.filter((H,K)=>G[K])},Wr0=(Q,J)=>{if((Q.includesMorph||J.includesMorph)&&(!yK(Q.shallowMorphs,J.shallowMorphs,{isEqual:(G,H)=>G.hasEqualMorphs(H)})||!yK(Q.flatMorphs,J.flatMorphs,{isEqual:(G,H)=>G.propString===H.propString&&G.node.hasEqualMorphs(H.node)})))zQ(Br0(Q.expression,J.expression))},Hr0=(Q,J)=>Q.transform((G,H)=>{if(G==="domain"||G==="unit")return null;return H},{shouldTransform:(G,H)=>{let K=RB0(H.path);if(!J.optionallyChainedPropString.startsWith(K))return!1;if(G.hasKind("domain")&&G.domain==="object")return!0;if((G.hasKind("domain")||J.kind==="unit")&&K===J.optionallyChainedPropString)return!0;return G.children.length!==0&&G.kind!=="index"}}),Br0=(Q,J)=>`An unordered union of a type including a morph and a type with overlapping input is indeterminate:
Left: ${Q}
Right: ${J}`,Ar0=(Q,J)=>`The intersection of two ordered unions is indeterminate:
Left: ${Q}
Right: ${J}`;var Kr0=u8({kind:"unit",hasAssociatedError:!0,keys:{unit:{preserveUndefined:!0,serialize:(Q)=>Q instanceof Date?Q.toISOString():K5(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>n8(Q.unit),problem:({expected:Q,actual:J})=>`${Q===J?`must be reference equal to ${Q} (serialized to the same value)`:`must be ${Q} (was ${J})`}`},intersections:{unit:(Q,J)=>_Q.init("unit",Q,J),...FW("unit",(Q,J)=>{if(J.allows(Q.unit))return Q;let G=J.hasKind("intersection")?J.basis:J;if(G){let H=G.hasKind("domain")?G:NQ.intrinsic.object;if(Q.domain!==H.domain){let K=Q.domain==="undefined"||Q.domain==="null"||Q.domain==="boolean"?Q.domain:NQ.intrinsic[Q.domain];return _Q.init("domain",K,H)}}return _Q.init("assignability",Q,J.hasKind("intersection")?J.children.find((H)=>!H.allows(Q.unit)):J)})}});class EB0 extends U3{compiledValue=this.json.unit;serializedValue=typeof this.unit==="string"||this.unit instanceof Date?JSON.stringify(this.compiledValue):`${this.compiledValue}`;compiledCondition=wB0(this.unit,this.serializedValue);compiledNegation=wB0(this.unit,this.serializedValue,"negated");expression=n8(this.unit);domain=zJ(this.unit);get shortDescription(){return this.domain==="object"?TY.object:this.description}innerToJsonSchema(){return NQ.intrinsic.jsonPrimitive.allows(this.unit)?{const:this.unit}:zQ(x9(this.shortDescription))}traverseAllows=this.unit instanceof Date?(Q)=>Q instanceof Date&&Q.toISOString()===this.compiledValue:Number.isNaN(this.unit)?(Q)=>Number.isNaN(Q):(Q)=>Q===this.unit}var sk={implementation:Kr0,Node:EB0},wB0=(Q,J,G)=>{if(Q instanceof Date){let H=`data instanceof Date && data.toISOString() === ${J}`;return G?`!(${H})`:H}if(Number.isNaN(Q))return`${G?"!":""}Number.isNaN(data)`;return`data ${G?"!":"="}== ${J}`};var zr0=u8({kind:"index",hasAssociatedError:!1,intersectionIsOpen:!0,keys:{signature:{child:!0,parse:(Q,J)=>{let G=J.$.parseSchema(Q);if(!G.extends(NQ.intrinsic.key))return zQ(qr0(G.expression));let H=G.branches.filter((K)=>K.hasKind("unit"));if(H.length)return zQ(Vr0(H.map((K)=>n8(K.unit))));return G}},value:{child:!0,parse:(Q,J)=>J.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`[${Q.signature.expression}]: ${Q.value.description}`},intersections:{index:(Q,J,G)=>{if(Q.signature.equals(J.signature)){let H=M9(Q.value,J.value,G),K=H instanceof _Q?NQ.intrinsic.never.internal:H;return G.$.node("index",{signature:Q.signature,value:K})}if(Q.signature.extends(J.signature)&&Q.value.subsumes(J.value))return J;if(J.signature.extends(Q.signature)&&J.value.subsumes(Q.value))return Q;return null}}});class SB0 extends kY{impliedBasis=NQ.intrinsic.object.internal;expression=`[${this.signature.expression}]: ${this.value.expression}`;traverseAllows=(Q,J)=>dq(Q).every((G)=>{if(this.signature.traverseAllows(G[0],J))return hJ(G[0],()=>this.value.traverseAllows(G[1],J),J);return!0});traverseApply=(Q,J)=>dq(Q).forEach((G)=>{if(this.signature.traverseAllows(G[0],J))hJ(G[0],()=>this.value.traverseApply(G[1],J),J)});_transform(Q,J){J.path.push(this.signature);let G=super._transform(Q,J);return J.path.pop(),G}get flatRefs(){return D6(this.value.flatRefs.map((Q)=>$G([this.signature,...Q.path],Q.node)),$G([this.signature],this.value))}compile(){}}var rk={implementation:zr0,Node:SB0},Vr0=(Q)=>`Index keys ${Q.join(", ")} should be specified as named props.`,qr0=(Q)=>`Indexed key definition '${Q}' must be a string or symbol`;var Ur0=u8({kind:"required",hasAssociatedError:!0,intersectionIsOpen:!0,keys:{key:{},value:{child:!0,parse:(Q,J)=>J.$.parseSchema(Q)}},normalize:(Q)=>Q,defaults:{description:(Q)=>`${Q.compiledKey}: ${Q.value.description}`,expected:(Q)=>Q.missingValueDescription,actual:()=>"missing"},intersections:{required:QU,optional:QU}});class TB0 extends XU{expression=`${this.compiledKey}: ${this.value.expression}`;errorContext=Object.freeze({code:"required",missingValueDescription:this.value.shortDescription,relativePath:[this.key]});compiledErrorContext=w4(this.errorContext)}var tk={implementation:Ur0,Node:TB0};var $r0=u8({kind:"sequence",hasAssociatedError:!1,collapsibleKey:"variadic",keys:{prefix:{child:!0,parse:(Q,J)=>{if(Q.length===0)return;return Q.map((G)=>J.$.parseSchema(G))}},optionals:{child:!0,parse:(Q,J)=>{if(Q.length===0)return;return Q.map((G)=>J.$.parseSchema(G))}},defaultables:{child:(Q)=>Q.map((J)=>J[0]),parse:(Q,J)=>{if(Q.length===0)return;return Q.map((G)=>{let H=J.$.parseSchema(G[0]);return YU(H,G[1],null),[H,G[1]]})},serialize:(Q)=>Q.map((J)=>[J[0].collapsibleJson,K5(J[1])])},variadic:{child:!0,parse:(Q,J)=>J.$.parseSchema(Q,J)},minVariadicLength:{parse:(Q)=>Q===0?void 0:Q},postfix:{child:!0,parse:(Q,J)=>{if(Q.length===0)return;return Q.map((G)=>J.$.parseSchema(G))}}},normalize:(Q)=>{if(typeof Q==="string")return{variadic:Q};if("variadic"in Q||"prefix"in Q||"defaultables"in Q||"optionals"in Q||"postfix"in Q||"minVariadicLength"in Q){if(Q.postfix?.length){if(!Q.variadic)return zQ(Fr0);if(Q.optionals?.length||Q.defaultables?.length)return zQ(Av)}if(Q.minVariadicLength&&!Q.variadic)return zQ("minVariadicLength may not be specified without a variadic element");return Q}return{variadic:Q}},reduce:(Q,J)=>{let G=Q.minVariadicLength??0,H=Q.prefix?.slice()??[],K=Q.defaultables?.slice()??[],z=Q.optionals?.slice()??[],q=Q.postfix?.slice()??[];if(Q.variadic){while(z.at(-1)?.equals(Q.variadic))z.pop();if(z.length===0&&K.length===0)while(H.at(-1)?.equals(Q.variadic))H.pop(),G++;while(q[0]?.equals(Q.variadic))q.shift(),G++}else if(z.length===0&&K.length===0)H.push(...q.splice(0));if(G!==Q.minVariadicLength||Q.prefix&&Q.prefix.length!==H.length)return J.node("sequence",{...Q,prefix:H,defaultables:K,optionals:z,postfix:q,minVariadicLength:G},{prereduced:!0})},defaults:{description:(Q)=>{if(Q.isVariadicOnly)return`${Q.variadic.nestableExpression}[]`;return`[${Q.tuple.map((G)=>G.kind==="defaultables"?`${G.node.nestableExpression} = ${n8(G.default)}`:G.kind==="optionals"?`${G.node.nestableExpression}?`:G.kind==="variadic"?`...${G.node.nestableExpression}[]`:G.node.expression).join(", ")}]`}},intersections:{sequence:(Q,J,G)=>{let H=HU({l:Q.tuple,r:J.tuple,disjoint:new _Q,result:[],fixedVariants:[],ctx:G}),K=H.disjoint.length===0?[H,...H.fixedVariants]:H.fixedVariants;return K.length===0?H.disjoint:K.length===1?G.$.node("sequence",kB0(K[0].result)):G.$.node("union",K.map((z)=>({proto:Array,sequence:kB0(z.result)})))}}});class yB0 extends kY{impliedBasis=NQ.intrinsic.Array.internal;tuple=Zr0(this.inner);prefixLength=this.prefix?.length??0;defaultablesLength=this.defaultables?.length??0;optionalsLength=this.optionals?.length??0;postfixLength=this.postfix?.length??0;prevariadic=this.tuple.filter((Q)=>Q.kind==="prefix"||Q.kind==="defaultables"||Q.kind==="optionals");variadicOrPostfix=j4(this.variadic&&[this.variadic],this.postfix);isVariadicOnly=this.prevariadic.length+this.postfixLength===0;minVariadicLength=this.inner.minVariadicLength??0;minLength=this.prefixLength+this.minVariadicLength+this.postfixLength;minLengthNode=this.minLength===0?null:this.$.node("minLength",this.minLength);maxLength=this.variadic?null:this.tuple.length;maxLengthNode=this.maxLength===null?null:this.$.node("maxLength",this.maxLength);impliedSiblings=this.minLengthNode?this.maxLengthNode?[this.minLengthNode,this.maxLengthNode]:[this.minLengthNode]:this.maxLengthNode?[this.maxLengthNode]:[];defaultValueMorphs=this.defaultables?.map(([Q,J],G)=>lk(this.prefixLength+G,Q,J))??[];defaultValueMorphsReference=j7(this.defaultValueMorphs);elementAtIndex(Q,J){if(J<this.prevariadic.length)return this.tuple[J];let G=Q.length-this.postfixLength;if(J>=G)return{kind:"postfix",node:this.postfix[J-G]};return{kind:"variadic",node:this.variadic??i6(`Unexpected attempt to access index ${J} on ${this}`)}}traverseAllows=(Q,J)=>{for(let G=0;G<Q.length;G++)if(!this.elementAtIndex(Q,G).node.traverseAllows(Q[G],J))return!1;return!0};traverseApply=(Q,J)=>{let G=0;for(;G<Q.length;G++)hJ(G,()=>this.elementAtIndex(Q,G).node.traverseApply(Q[G],J),J);for(;G<this.prefixLength+this.defaultablesLength;G++)J.queueMorphs(this.defaultValueMorphs[G-this.prefixLength])};get flatRefs(){let Q=[];return fK(Q,this.prevariadic.flatMap((J,G)=>D6(J.node.flatRefs.map((H)=>$G([`${G}`,...H.path],H.node)),$G([`${G}`],J.node)))),fK(Q,this.variadicOrPostfix.flatMap((J)=>D6(J.flatRefs.map((G)=>$G([NQ.intrinsic.nonNegativeIntegerString.internal,...G.path],G.node)),$G([NQ.intrinsic.nonNegativeIntegerString.internal],J)))),Q}get element(){return this.cacheGetter("element",this.$.node("union",this.children))}compile(Q){if(this.prefix?.forEach((J,G)=>Q.traverseKey(`${G}`,`data[${G}]`,J)),this.defaultables?.forEach((J,G)=>{let H=`${G+this.prefixLength}`;Q.if(`${H} >= ${Q.data}.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return(`ctx.queueMorphs(${this.defaultValueMorphsReference}[${G}])`)),Q.traverseKey(H,`data[${H}]`,J[0])}),this.optionals?.forEach((J,G)=>{let H=`${G+this.prefixLength+this.defaultablesLength}`;Q.if(`${H} >= ${Q.data}.length`,()=>Q.traversalKind==="Allows"?Q.return(!0):Q.return()),Q.traverseKey(H,`data[${H}]`,J)}),this.variadic){if(this.postfix)Q.const("firstPostfixIndex",`${Q.data}.length${this.postfix?`- ${this.postfix.length}`:""}`);Q.for(`i < ${this.postfix?"firstPostfixIndex":"data.length"}`,()=>Q.traverseKey("i","data[i]",this.variadic),this.prevariadic.length),this.postfix?.forEach((J,G)=>{let H=`firstPostfixIndex + ${G}`;Q.traverseKey(H,`data[${H}]`,J)})}if(Q.traversalKind==="Allows")Q.return(!0)}_transform(Q,J){J.path.push(NQ.intrinsic.nonNegativeIntegerString.internal);let G=super._transform(Q,J);return J.path.pop(),G}expression=this.description;reduceJsonSchema(Q){if(this.prefix)Q.prefixItems=this.prefix.map((J)=>J.toJsonSchema());if(this.optionals)zQ(x9(`Optional tuple element${this.optionalsLength>1?"s":""} ${this.optionals.join(", ")}`));if(this.variadic){if(Q.items=this.variadic?.toJsonSchema(),this.minLength)Q.minItems=this.minLength;if(this.maxLength)Q.maxItems=this.maxLength}else Q.items=!1,delete Q.minItems,delete Q.maxItems;if(this.postfix)zQ(x9(`Postfix tuple element${this.postfixLength>1?"s":""} ${this.postfix.join(", ")}`));return Q}}var ek={implementation:$r0,Node:yB0},Zr0=(Q)=>{let J=[];if(Q.prefix?.forEach((G)=>J.push({kind:"prefix",node:G})),Q.defaultables?.forEach(([G,H])=>J.push({kind:"defaultables",node:G,default:H})),Q.optionals?.forEach((G)=>J.push({kind:"optionals",node:G})),Q.variadic)J.push({kind:"variadic",node:Q.variadic});return Q.postfix?.forEach((G)=>J.push({kind:"postfix",node:G})),J},kB0=(Q)=>Q.reduce((J,G)=>{if(G.kind==="variadic")J.variadic=G.node;else if(G.kind==="defaultables")J.defaultables=D6(J.defaultables,[[G.node,G.default]]);else J[G.kind]=D6(J[G.kind],G.node);return J},{}),Av="A postfix required element cannot follow an optional or defaultable element",Fr0="A postfix element requires a variadic element",HU=(Q)=>{let[J,...G]=Q.l,[H,...K]=Q.r;if(!J||!H)return Q;let z=G.at(-1)?.kind==="postfix",q=K.at(-1)?.kind==="postfix",F=J.kind==="prefix"||H.kind==="prefix"?"prefix":J.kind==="postfix"||H.kind==="postfix"?"postfix":J.kind==="variadic"&&H.kind==="variadic"?"variadic":z||q?"prefix":J.kind==="defaultables"||H.kind==="defaultables"?"defaultables":"optionals";if(J.kind==="prefix"&&H.kind==="variadic"&&q){let P=HU({...Q,fixedVariants:[],r:K.map((N)=>({...N,kind:"prefix"}))});if(P.disjoint.length===0)Q.fixedVariants.push(P)}else if(H.kind==="prefix"&&J.kind==="variadic"&&z){let P=HU({...Q,fixedVariants:[],l:G.map((N)=>({...N,kind:"prefix"}))});if(P.disjoint.length===0)Q.fixedVariants.push(P)}let D=M9(J.node,H.node,Q.ctx);if(D instanceof _Q)if(F==="prefix"||F==="postfix")Q.disjoint.push(...D.withPrefixKey(F==="prefix"?`${Q.result.length}`:`-${G.length+1}`,"required")),Q.result=[...Q.result,{kind:F,node:NQ.intrinsic.never.internal}];else if(F==="optionals"||F==="defaultables")return Q;else return HU({...Q,fixedVariants:[],l:G.map((P)=>({...P,kind:"prefix"})),r:G.map((P)=>({...P,kind:"prefix"}))});else if(F==="defaultables"){if(J.kind==="defaultables"&&H.kind==="defaultables"&&J.default!==H.default)zQ(pk(J.default,H.default));Q.result=[...Q.result,{kind:F,node:D,default:J.kind==="defaultables"?J.default:H.kind==="defaultables"?H.default:i6(`Unexpected defaultable intersection from ${J.kind} and ${H.kind} elements.`)}]}else Q.result=[...Q.result,{kind:F,node:D}];let V=Q.l.length,O=Q.r.length;if(J.kind!=="variadic"||V>=O&&(H.kind==="variadic"||O===1))Q.l=G;if(H.kind!=="variadic"||O>=V&&(J.kind==="variadic"||V===1))Q.r=K;return HU(Q)};var $v="^(?:0|[1-9]\\d*)$",Dr0=new RegExp($v),vB0=j7(Dr0);var bB0=(Q)=>(J)=>{if(J.props.length||J.index){let G=J.index?.map(String)??[];if(J.props.forEach((K)=>G.push(K[Q])),J.undeclared)G.push(`+ (undeclared): ${J.undeclared}`);let H=`{ ${G.join(", ")} }`;return J.sequence?`${H} & ${J.sequence.description}`:H}return J.sequence?.description??"{}"},Mr0=bB0("description"),Lr0=bB0("expression"),Or0=u8({kind:"structure",hasAssociatedError:!1,normalize:(Q,J)=>{if(!Q.undeclared&&J.resolvedConfig.onUndeclaredKey!=="ignore")return{...Q,undeclared:J.resolvedConfig.onUndeclaredKey};return Q},keys:{required:{child:!0,parse:_X("required"),reduceIo:(Q,J,G)=>{J.required=D6(J.required,G.map((H)=>H[Q]));return}},optional:{child:!0,parse:_X("optional"),reduceIo:(Q,J,G)=>{if(Q==="in"){J.optional=G.map((H)=>H.in);return}G.forEach((H)=>J[H.outProp.kind]=D6(J[H.outProp.kind],H.outProp.out))}},index:{child:!0,parse:_X("index")},sequence:{child:!0,parse:_X("sequence")},undeclared:{parse:(Q)=>Q==="ignore"?void 0:Q}},defaults:{description:Mr0},intersections:{structure:(Q,J,G)=>{let H={...Q.inner},K={...J.inner},z=new _Q;if(Q.undeclared){let D=Q.keyof();if(J.requiredKeys.forEach((V)=>{if(!D.allows(V))z.add("presence",NQ.intrinsic.never.internal,J.propsByKey[V].value,{path:[V]})}),K.optional)K.optional=K.optional.filter((V)=>D.allows(V.key));if(K.index)K.index=K.index.flatMap((V)=>{if(V.signature.extends(D))return V;let O=HY(D,V.signature,G.$);if(O instanceof _Q)return[];let P=jP(O,V.value,G.$);if(P.required)K.required=j4(K.required,P.required);if(P.optional)K.optional=j4(K.optional,P.optional);return P.index??[]})}if(J.undeclared){let D=J.keyof();if(Q.requiredKeys.forEach((V)=>{if(!D.allows(V))z.add("presence",Q.propsByKey[V].value,NQ.intrinsic.never.internal,{path:[V]})}),H.optional)H.optional=H.optional.filter((V)=>D.allows(V.key));if(H.index)H.index=H.index.flatMap((V)=>{if(V.signature.extends(D))return V;let O=HY(D,V.signature,G.$);if(O instanceof _Q)return[];let P=jP(O,V.value,G.$);if(P.required)H.required=j4(H.required,P.required);if(P.optional)H.optional=j4(H.optional,P.optional);return P.index??[]})}let q={};if(Q.undeclared||J.undeclared)q.undeclared=Q.undeclared==="reject"||J.undeclared==="reject"?"reject":"delete";let F=uK({kind:"structure",baseInner:q,l:pK(H),r:pK(K),roots:[],ctx:G});if(F instanceof _Q)z.push(...F);if(z.length)return z;return F}}});class gB0 extends kY{impliedBasis=NQ.intrinsic.object.internal;impliedSiblings=this.children.flatMap((Q)=>Q.impliedSiblings??[]);props=j4(this.required,this.optional);propsByKey=r8(this.props,(Q,J)=>[J.key,J]);propsByKeyReference=j7(this.propsByKey);expression=Lr0(this);requiredKeys=this.required?.map((Q)=>Q.key)??[];optionalKeys=this.optional?.map((Q)=>Q.key)??[];literalKeys=[...this.requiredKeys,...this.optionalKeys];_keyof;keyof(){if(this._keyof)return this._keyof;let Q=this.$.units(this.literalKeys).branches;return this.index?.forEach(({signature:J})=>{Q=Q.concat(J.branches)}),this._keyof=this.$.node("union",Q)}map(Q){return this.$.node("structure",this.props.flatMap(Q).reduce((J,G)=>{let H=this.propsByKey[G.key];if(C9(G)){if(G.kind!=="required"&&G.kind!=="optional")return zQ(`Map result must have kind "required" or "optional" (was ${G.kind})`);return J[G.kind]=D6(J[G.kind],G),J}let K=G.kind??H?.kind??"required",z=r8(G,(q,F)=>(q in JU.implementation.keys)?[q,F]:[]);return J[K]=D6(J[K],this.$.node(K,z)),J},{}))}assertHasKeys(Q){let J=Q.filter((G)=>!GU(G,this.keyof()));if(J.length)return zQ(xB0(this.expression,J))}get(Q,...J){let G,H=!1,K=Pr0(Q);if((typeof K==="string"||typeof K==="symbol")&&this.propsByKey[K])G=this.propsByKey[K].value,H=this.propsByKey[K].required;if(this.index?.forEach((q)=>{if(GU(K,q.signature))G=G?.and(q.value)??q.value}),this.sequence&&GU(K,NQ.intrinsic.nonNegativeIntegerString))if(Q8(K,"root")){if(this.sequence.variadic)G=G?.and(this.sequence.element)??this.sequence.element}else{let q=Number.parseInt(K);if(q<this.sequence.prevariadic.length){let F=this.sequence.prevariadic[q].node;G=G?.and(F)??F,H||=q<this.sequence.prefixLength}else if(this.sequence.variadic){let F=this.$.node("union",this.sequence.variadicOrPostfix);G=G?.and(F)??F}}if(!G){if(this.sequence?.variadic&&Q8(K,"root")&&K.extends(NQ.intrinsic.number))return zQ(Nr0(K.expression,this.sequence.expression));return zQ(xB0(this.expression,[K]))}let z=G.get(...J);return H?z:z.or(NQ.intrinsic.undefined)}exhaustive=this.undeclared!==void 0||this.index!==void 0;pick(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("pick",Q))}omit(...Q){return this.assertHasKeys(Q),this.$.node("structure",this.filterKeys("omit",Q))}optionalize(){let{required:Q,...J}=this.inner;return this.$.node("structure",{...J,optional:this.props.map((G)=>G.hasKind("required")?this.$.node("optional",G.inner):G)})}require(){let{optional:Q,...J}=this.inner;return this.$.node("structure",{...J,required:this.props.map((G)=>G.hasKind("optional")?{key:G.key,value:G.value}:G)})}merge(Q){let J=this.filterKeys("omit",[Q.keyof()]);if(Q.required)J.required=D6(J.required,Q.required);if(Q.optional)J.optional=D6(J.optional,Q.optional);if(Q.index)J.index=D6(J.index,Q.index);if(Q.sequence)J.sequence=Q.sequence;if(Q.undeclared)J.undeclared=Q.undeclared;else delete J.undeclared;return this.$.node("structure",J)}filterKeys(Q,J){let G=VP(this.inner),H=(K)=>{let z=J.some((q)=>GU(K,q));return Q==="pick"?z:!z};if(G.required)G.required=G.required.filter((K)=>H(K.key));if(G.optional)G.optional=G.optional.filter((K)=>H(K.key));if(G.index)G.index=G.index.filter((K)=>H(K.signature));return G}traverseAllows=(Q,J)=>this._traverse("Allows",Q,J);traverseApply=(Q,J)=>this._traverse("Apply",Q,J);_traverse=(Q,J,G)=>{let H=G?.currentErrorCount??0;for(let z=0;z<this.props.length;z++)if(Q==="Allows"){if(!this.props[z].traverseAllows(J,G))return!1}else if(this.props[z].traverseApply(J,G),G.failFast&&G.currentErrorCount>H)return!1;if(this.sequence){if(Q==="Allows"){if(!this.sequence.traverseAllows(J,G))return!1}else if(this.sequence.traverseApply(J,G),G.failFast&&G.currentErrorCount>H)return!1}if(!this.exhaustive)return!0;let K=Object.keys(J);K.push(...Object.getOwnPropertySymbols(J));for(let z=0;z<K.length;z++){let q=K[z],F=!1;if(this.index){for(let D of this.index)if(D.signature.traverseAllows(q,G)){if(Q==="Allows"){if(!hJ(q,()=>D.value.traverseAllows(J[q],G),G))return!1}else if(hJ(q,()=>D.value.traverseApply(J[q],G),G),G.failFast&&G.currentErrorCount>H)return!1;F=!0}}if(this.undeclared){if(F||=q in this.propsByKey,F||=this.sequence!==void 0&&typeof q==="string"&&NQ.intrinsic.nonNegativeIntegerString.allows(q),!F){if(Q==="Allows")return!1;if(this.undeclared==="reject")G.error({expected:"removed",actual:"",relativePath:[q]});else G.queueMorphs([(D)=>{return delete D[q],D}]);if(G.failFast)return!1}}}return!0};compile(Q){if(Q.traversalKind==="Apply")Q.initializeErrorCount();if(this.props.forEach((J)=>{if(Q.check(J),Q.traversalKind==="Apply")Q.returnIfFailFast()}),this.sequence){if(Q.check(this.sequence),Q.traversalKind==="Apply")Q.returnIfFailFast()}if(this.exhaustive)Q.const("keys","Object.keys(data)"),Q.line("keys.push(...Object.getOwnPropertySymbols(data))"),Q.for("i < keys.length",()=>this.compileExhaustiveEntry(Q));if(Q.traversalKind==="Allows")Q.return(!0)}compileExhaustiveEntry(Q){if(Q.const("k","keys[i]"),this.undeclared)Q.let("matched",!1);if(this.index?.forEach((J)=>{Q.if(`${Q.invoke(J.signature,{arg:"k",kind:"Allows"})}`,()=>{if(Q.traverseKey("k","data[k]",J.value),this.undeclared)Q.set("matched",!0);return Q})}),this.undeclared){if(this.props?.length!==0)Q.line(`matched ||= k in ${this.propsByKeyReference}`);if(this.sequence)Q.line(`matched ||= typeof k === "string" && ${vB0}.test(k)`);Q.if("!matched",()=>{if(Q.traversalKind==="Allows")return Q.return(!1);return this.undeclared==="reject"?Q.line('ctx.error({ expected: "removed", actual: "", relativePath: [k] })').if("ctx.failFast",()=>Q.return()):Q.line("ctx.queueMorphs([data => { delete data[k]; return data }])")})}return Q}reduceJsonSchema(Q){switch(Q.type){case"object":return this.reduceObjectJsonSchema(Q);case"array":if(this.props.length||this.index)zQ(x9(`Additional properties on array ${this.expression}`));return this.sequence?.reduceJsonSchema(Q)??Q;default:return S4("structure",Q)}}reduceObjectJsonSchema(Q){if(this.props.length){if(Q.properties={},this.props.forEach((J)=>{if(typeof J.key==="symbol")return zQ(x9(`Sybolic key ${J.serializedKey}`));Q.properties[J.key]=J.value.toJsonSchema()}),this.requiredKeys.length)Q.required=this.requiredKeys}if(this.index?.forEach((J)=>{if(J.signature.equals(NQ.intrinsic.string))return Q.additionalProperties=J.value.toJsonSchema();if(!J.signature.extends(NQ.intrinsic.string))return zQ(x9(`Symbolic index signature ${J.signature.exclude(NQ.intrinsic.string)}`));J.signature.branches.forEach((G)=>{if(!G.hasKind("intersection")||G.pattern?.length!==1)return zQ(x9(`Index signature ${G}`));Q.patternProperties??={},Q.patternProperties[G.pattern[0].rule]=J.value.toJsonSchema()})}),this.undeclared&&!Q.additionalProperties)Q.additionalProperties=!1;return Q}}var Ov={implementation:Or0,Node:gB0},Pr0=(Q)=>{if(Q8(Q,"root")&&Q.hasKind("unit"))Q=Q.unit;if(typeof Q==="number")Q=`${Q}`;return Q},Nr0=(Q,J)=>`${Q} is not allowed as an array index on ${J}. Use the 'nonNegativeIntegerString' keyword instead.`,jP=(Q,J,G)=>{let[H,K]=U30(Q.branches,(q)=>q.hasKind("unit"));if(!H.length)return{index:G.node("index",{signature:Q,value:J})};let z={};if(H.forEach((q)=>{let F=G.node("required",{key:q.unit,value:J});z[F.kind]=D6(z[F.kind],F)}),K.length)z.index=G.node("index",{signature:K,value:J});return z},jr0=(Q)=>Q8(Q,"root")?Q.expression:n8(Q),xB0=(Q,J)=>`Key${J.length===1?"":"s"} ${J.map(jr0).join(", ")} ${J.length===1?"does":"do"} not exist on ${Q}`;var dK={...KB0,alias:WU.implementation,domain:dk.implementation,unit:sk.implementation,proto:ok.implementation,union:ak.implementation,morph:ik.implementation,intersection:ck.implementation,divisor:Tk.implementation,pattern:_k.implementation,predicate:Sk.implementation,required:tk.implementation,optional:JU.implementation,index:rk.implementation,sequence:ek.implementation,structure:Ov.implementation};NQ.defaultConfig=Object.assign(r8(dK,(Q,J)=>[Q,J.defaults]),{jitless:j30(),clone:L30,onUndeclaredKey:"ignore"});var ZB0={...zB0,alias:WU.Node,domain:dk.Node,unit:sk.Node,proto:ok.Node,union:ak.Node,morph:ik.Node,intersection:ck.Node,divisor:Tk.Node,pattern:_k.Node,predicate:Sk.Node,required:tk.Node,optional:JU.Node,index:rk.Node,sequence:ek.Node,structure:Ov.Node};class $3 extends Vk{get[bJ](){return"module"}}var Pv=(Q,J)=>new $3(r8(Q,(G,H)=>[G,Q8(H,"module")?Pv(H,J):J.bindReference(H)]));var Cr0=(Q)=>V9(Q)?Q:("branches"in Q)&&V9(Q.branches)?Q.branches:void 0,Ir0=(Q,J)=>zQ(`Node of kind ${J} is not valid as a ${Q} definition`),hB0=(Q)=>`#${Q} duplicates public alias ${Q}`,_B0={};NQ.ambient??={};var fB0;class CP{config;resolvedConfig;id=`${Object.keys(_B0).length}$`;get[bJ](){return"scope"}referencesById={};references=[];resolutions={};json={};exportedNames=[];aliases={};resolved=!1;nodesByHash={};constructor(Q,J){this.config=J??{},this.resolvedConfig=c30(J),Object.entries(Q).map((H)=>this.preparseOwnAliasEntry(...H)).forEach(([H,K])=>{let z=H;if(H[0]==="#"){if(z=H.slice(1),z in this.aliases)zQ(hB0(z));this.aliases[z]=K}else{if(z in this.aliases)zQ(hB0(H));this.aliases[z]=K,this.exportedNames.push(z)}if(!Q8(K,"module")&&!Q8(K,"generic")&&!C4(K)){let q=this.preparseOwnDefinitionFormat(K,{alias:z});if(Q8(q,"root"))this.resolutions[z]=this.bindReference(q);else this.resolutions[z]=this.createParseContext(q).id}}),fB0??=this.node("union",{branches:["string","number","object","bigint","symbol",{unit:!0},{unit:!1},{unit:void 0},{unit:null}]},{prereduced:!0}),this.nodesByHash[fB0.hash]=this.node("intersection",{},{prereduced:!0}),_B0[this.id]=this}get internal(){return this}defineSchema(Q){return Q}generic=(...Q)=>{let J=this;return(G,H)=>new E4(Q,H?new FP(G):G,J,J,H??null)};units=(Q,J)=>{let G=[];for(let K of Q)if(!G.includes(K))G.push(K);let H=G.map((K)=>this.node("unit",{unit:K},J));return this.node("union",H,{...J,prereduced:!0})};lazyResolutions=[];lazilyResolve(Q,J){let G=this.node("alias",{reference:J??"synthetic",resolve:Q},{prereduced:!0});if(!this.resolved)this.lazyResolutions.push(G);return G}schema=(Q,J)=>this.finalize(this.parseSchema(Q,J));parseSchema=(Q,J)=>this.node(eq(Q),Q,J);preparseNode(Q,J,G){let H=typeof Q==="string"?Q:eq(J,Q);if(C9(J)&&J.kind===H)return J;if(H==="alias"&&!G?.prereduced){let{reference:q}=WU.implementation.normalize(J,this);if(q.startsWith("$")){let F=this.resolveRoot(q.slice(1));J=F,H=F.kind}}else if(H==="union"&&xJ(J,"object")){let q=Cr0(J);if(q?.length===1)J=q[0],H=eq(J)}let z=dK[H].normalize?.(J,this)??J;if(C9(z))return z.kind===H?z:Ir0(H,z.kind);return{...G,$:this,kind:H,def:z,prefix:G.alias??H}}bindReference(Q){let J=Q.$===this?Q:C9(Q)?new Q.constructor(Q.attachments,this):new E4(Q.params,Q.bodyDef,Q.$,this,Q.hkt);if(!this.resolved)Object.assign(this.referencesById,J.referencesById);return J}resolveRoot(Q){return this.maybeResolveRoot(Q)??zQ(wv(Q))}maybeResolveRoot(Q){let J=this.maybeResolve(Q);if(Q8(J,"generic"))return;return J}maybeResolveSubalias(Q){return Cv(this.aliases,Q)??Cv(this.ambient,Q)}get ambient(){return NQ.ambient}maybeResolve(Q){let J=this.resolutions[Q];if(J){if(typeof J!=="string")return J;let H=VJ[J];if(Q8(H,"root"))return this.resolutions[Q]=H;if(Q8(H,"context")){if(H.phase==="resolving")return this.node("alias",{reference:`$${Q}`},{prereduced:!0});if(H.phase==="resolved")return i6(`Unexpected resolved context for was uncached by its scope: ${n8(H)}`);H.phase="resolving";let K=this.bindReference(this.parseOwnDefinitionFormat(H.def,H));return H.phase="resolved",VJ[K.id]=K,VJ[H.id]=K,this.resolutions[Q]=K}return i6(`Unexpected nodesById entry for ${J}: ${n8(H)}`)}let G=this.aliases[Q]??this.ambient?.[Q];if(!G)return this.maybeResolveSubalias(Q);if(G=this.normalizeRootScopeValue(G),Q8(G,"generic"))return this.resolutions[Q]=this.bindReference(G);if(Q8(G,"module"))if(G.root)return this.resolutions[Q]=this.bindReference(G.root);else return zQ(lB0(Q));return this.resolutions[Q]=this.parse(G,{alias:Q})}createParseContext(Q){let J=Q.id??fk(Q.prefix);return VJ[J]=Object.assign(Q,{[bJ]:"context",$:this,id:J,phase:"unresolved"})}import(...Q){return new $3(r8(this.export(...Q),(J,G)=>[`#${J}`,G]))}precompilation;_exportedResolutions;_exports;export(...Q){if(!this._exports){this._exports={};for(let G of this.exportedNames){let H=this.aliases[G];this._exports[G]=Q8(H,"module")?Pv(H,this):mB0(this.maybeResolve(G))}if(this.lazyResolutions.forEach((G)=>G.resolution),this.resolvedConfig.ambient===!0)Object.assign(NQ.ambient,this._exports);else if(typeof this.resolvedConfig.ambient==="string")Object.assign(NQ.ambient,{[this.resolvedConfig.ambient]:new $3({...this._exports})});if(this._exportedResolutions=pB0(this,this._exports),Object.assign(this.json,uB0(this._exportedResolutions)),Object.assign(this.resolutions,this._exportedResolutions),this.references=Object.values(this.referencesById),!this.resolvedConfig.jitless)this.precompilation=cB0(this.references),dB0(this.references,this.precompilation);this.resolved=!0}let J=Q.length?Q:this.exportedNames;return new $3(r8(J,(G,H)=>[H,this._exports[H]]))}resolve(Q){return this.export()[Q]}node=(Q,J,G={})=>{let H=this.preparseNode(Q,J,G);if(C9(H))return this.bindReference(H);let K=this.createParseContext(H);return VJ[K.id]=this.bindReference(mk(K))};parse=(Q,J={})=>this.finalize(this.parseDefinition(Q,J));parseDefinition(Q,J={}){if(Q8(Q,"root"))return this.bindReference(Q);let G=this.preparseOwnDefinitionFormat(Q,J);if(Q8(G,"root"))return this.bindReference(G);let H=this.createParseContext(G);VJ[H.id]=H;let K=this.bindReference(this.parseOwnDefinitionFormat(Q,H));if(K.isCyclic)K=$B0(K,H.id);return VJ[H.id]=K,K}finalize(Q){if(mB0(Q),!Q.precompilation&&!this.resolvedConfig.jitless)wr0(Q.references);return Q}}class Iv extends CP{parseOwnDefinitionFormat(Q,J){return mk(J)}preparseOwnDefinitionFormat(Q,J){return this.preparseNode(eq(Q),Q,J)}preparseOwnAliasEntry(Q,J){return[Q,J]}normalizeRootScopeValue(Q){return Q}}var mB0=(Q)=>{return Q.references.filter((J)=>J.hasKind("alias")).forEach((J)=>{Object.assign(J.referencesById,J.resolution.referencesById),Q.references.forEach((G)=>{if(J.id in G.referencesById)Object.assign(G.referencesById,J.referencesById)})}),Q},uB0=(Q)=>r8(Q,(J,G)=>[J,Q8(G,"root")||Q8(G,"generic")?G.json:Q8(G,"module")?uB0(G):i6(`Unexpected resolution ${n8(G)}`)]),Cv=(Q,J)=>{let G=J.indexOf(".");if(G===-1)return;let H=J.slice(0,G),K=Q[H];if(K===void 0)return;if(!Q8(K,"module"))return zQ(Rr0(H));let z=J.slice(G+1),q=K[z];if(q===void 0)return Cv(K,z);if(Q8(q,"root")||Q8(q,"generic"))return q;if(Q8(q,"module"))return q.root??zQ(lB0(J));i6(`Unexpected resolution for alias '${J}': ${n8(q)}`)},IP=(Q,J)=>new Iv(Q,J),BU=new Iv({});var pB0=(Q,J)=>{let G={};for(let H in J){let K=J[H];if(Q8(K,"module")){let z=pB0(Q,K),q=r8(z,(F,D)=>[`${H}.${F}`,D]);Object.assign(G,q)}else if(Q8(K,"root")||Q8(K,"generic"))G[H]=K;else i6(`Unexpected scope resolution ${n8(K)}`)}return G},wv=(Q)=>`'${Q}' is unresolvable`,Rr0=(Q)=>`'${Q}' must reference a module to be accessed using dot syntax`,lB0=(Q)=>`Reference to submodule '${Q}' must specify an alias`,wr0=(Q)=>dB0(Q,cB0(Q)),dB0=(Q,J)=>{let G=Er0(J);for(let H of Q){if(H.precompilation)continue;if(H.traverseAllows=G[`${H.id}Allows`].bind(G),H.isRoot()&&!H.allowsRequiresContext)H.allows=H.traverseAllows;H.traverseApply=G[`${H.id}Apply`].bind(G),H.precompilation=J}},Er0=(Q)=>new KP().return(Q).compile()(),cB0=(Q)=>Q.reduce((J,G)=>{let H=new zP("Allows").indent();G.compile(H);let K=H.write(`${G.id}Allows`),z=new zP("Apply").indent();G.compile(z);let q=z.write(`${G.id}Apply`);return`${J}${K},
${q},
`},`{
`)+"}";BU.export();var{schema:G9,node:oK,defineSchema:CsQ,generic:vY}=BU;var iB0=IP({bigint:"bigint",boolean:[{unit:!1},{unit:!0}],false:{unit:!1},never:[],null:{unit:null},number:"number",object:"object",string:"string",symbol:"symbol",true:{unit:!0},unknown:{},undefined:{unit:void 0},Array,Date},{prereducedAliases:!0}).export();NQ.intrinsic={...iB0};var oB0=IP({integer:{domain:"number",divisor:1},lengthBoundable:["string",Array],key:["string","symbol"],nonNegativeIntegerString:{domain:"string",pattern:$v}},{prereducedAliases:!0}).export();Object.assign(NQ.intrinsic,oB0);var Sr0=IP({jsonPrimitive:["string","number",{unit:!0},{unit:!1},{unit:null}],jsonObject:{domain:"object",index:{signature:"string",value:"$jsonData"}},jsonArray:{proto:Array,sequence:"$jsonData"},jsonData:["$jsonPrimitive","$jsonObject","$jsonArray"],json:["$jsonObject","$jsonArray"]},{prereducedAliases:!0}).export(),_8={...iB0,...oB0,...Sr0,emptyStructure:oK("structure",{},{prereduced:!0})};NQ.intrinsic={..._8};var aB0=(Q)=>typeof Q==="string"&&Q[0]==="d"&&(Q[1]==="'"||Q[1]==='"')&&Q.at(-1)===Q[1],nB0=(Q)=>Q.toString()!=="Invalid Date",sB0=(Q)=>Q.slice(2,-1),Ev=(Q)=>`'${Q}' could not be parsed by the Date constructor`,rB0=(Q,J)=>Tr0(Q,J),Tr0=(Q,J)=>{let G=new Date(Q);if(nB0(G))return G;let H=y30(Q);if(H!==void 0){let K=new Date(H);if(nB0(K))return K}return J?zQ(J===!0?Ev(Q):J):void 0};var Sv=(Q,J)=>{let G=Q.scanner.shiftUntil(kr0[eB0[J]]);if(Q.scanner.lookahead==="")return Q.error(vr0(G,J));if(Q.scanner.shift(),J==="/"){try{new RegExp(G)}catch(H){zQ(String(H))}Q.root=Q.ctx.$.node("intersection",{domain:"string",pattern:G},{prereduced:!0})}else if(ZX(J,Tv))Q.root=Q.ctx.$.node("unit",{unit:G});else{let H=rB0(G,Ev(G));Q.root=Q.ctx.$.node("unit",{meta:G,unit:H})}},Tv={"'":1,'"':1},tB0={"/":1,"'":1,'"':1},eB0={"d'":"'",'d"':'"',"'":"'",'"':'"',"/":"/"},kr0={"'":(Q)=>Q.lookahead==="'",'"':(Q)=>Q.lookahead==='"',"/":(Q)=>Q.lookahead==="/"},yr0={'"':"double-quote","'":"single-quote","/":"forward slash"},vr0=(Q,J)=>`${J}${Q} requires a closing ${yr0[eB0[J]]}`;var QA0=(Q)=>`Private type references should not include '#'. Use '${Q}' instead.`,RP="Optional definitions like 'string?' are only valid as properties in an object or tuple",wP="Defaultable definitions like 'number = 0' are only valid as properties in an object or tuple";var XA0={">":!0,">=":!0},JA0={"<":!0,"<=":!0};var nK={"<":">",">":"<","<=":">=",">=":"<=","==":"=="},YA0=(Q)=>`Unmatched )${Q===""?"":` before ${Q}`}`,EP=(Q)=>`Missing ${Q}`,GA0=(Q,J)=>`Left bounds are only valid when paired with right bounds (try ...${J}${Q})`,SP=(Q)=>`Left-bounded expressions must specify their limits using < or <= (was ${Q})`,WA0=(Q,J,G,H)=>`An expression may have at most one left bound (parsed ${Q}${nK[J]}, ${G}${nK[H]})`;var HA0=(Q,J,G)=>BA0(Q,J,G,[]),BA0=(Q,J,G,H)=>{let K=G.parseUntilFinalizer();if(H.push(K.root),K.finalizer===">"){if(H.length!==J.params.length)return G.error(yv(Q,J.names,H.map((z)=>z.expression)));return H}if(K.finalizer===",")return BA0(Q,J,G,H);return K.error(EP(">"))},yv=(Q,J,G)=>`${Q}<${J.join(", ")}> requires exactly ${J.length} args (got ${G.length}${G.length===0?"":`: ${G.join(", ")}`})`;var vv=(Q)=>{let J=Q.scanner.shiftUntilNextTerminator();if(J==="keyof")Q.addPrefix("keyof");else Q.root=br0(Q,J)},xr0=(Q,J,G)=>{if(G.scanner.shiftUntilNonWhitespace(),G.scanner.shift()!=="<")return G.error(yv(Q,J.names,[]));let K=HA0(Q,J,G);return J(...K)},br0=(Q,J)=>gr0(Q,J)??hr0(Q,J)??Q.error(J===""?Q.scanner.lookahead==="#"?QA0(Q.shiftedByOne().scanner.shiftUntilNextTerminator()):xv(Q):wv(J)),gr0=(Q,J)=>{if(Q.ctx.args?.[J]){let H=Q.ctx.args[J];if(typeof H!=="string")return H;return Q.ctx.$.node("alias",{reference:H},{prereduced:!0})}let G=Q.ctx.$.maybeResolve(J);if(Q8(G,"root"))return G;if(G===void 0)return;if(Q8(G,"generic"))return xr0(J,G,Q);return zQ(`Unexpected resolution ${n8(G)}`)},hr0=(Q,J)=>{let G=v30(J);if(G!==void 0)return Q.ctx.$.node("unit",{unit:G});let H=b30(J);if(H!==void 0)return Q.ctx.$.node("unit",{unit:H})},xv=(Q)=>{let J=Q.previousOperator();return J?bv(J,Q.scanner.unscanned):_r0(Q.scanner.unscanned)},bv=(Q,J="")=>`Token '${Q}' requires a right operand${J?` before '${J}'`:""}`,_r0=(Q)=>`Expected an expression${Q?` before '${Q}'`:""}`;var gv=(Q)=>Q.scanner.lookahead===""?Q.error(xv(Q)):Q.scanner.lookahead==="("?Q.shiftedByOne().reduceGroupOpen():Q.scanner.lookaheadIsIn(tB0)?Sv(Q,Q.scanner.shift()):Q.scanner.lookaheadIsIn(R4)?gv(Q.shiftedByOne()):Q.scanner.lookahead==="d"?Q.scanner.nextLookahead in Tv?Sv(Q,`${Q.scanner.shift()}${Q.scanner.shift()}`):vv(Q):vv(Q);class V5 extends Ok{shiftUntilNextTerminator(){return this.shiftUntilNonWhitespace(),this.shiftUntil(()=>(this.lookahead in V5.terminatingChars))}static terminatingChars={"<":1,">":1,"=":1,"|":1,"&":1,")":1,"[":1,"%":1,",":1,":":1,"?":1,"#":1,...R4};static finalizingLookaheads={">":1,",":1,"":1,"=":1,"?":1};static lookaheadIsFinalizing=(Q,J)=>Q===">"?J[0]==="="?J[1]==="=":J.trimStart()===""||ZX(J.trimStart()[0],V5.terminatingChars):Q==="="?J[0]!=="=":Q===","||Q==="?"}var KA0=(Q,J)=>{let G=fr0(Q,J);if(Q.root.hasKind("unit")){if(typeof Q.root.unit==="number"){Q.reduceLeftBound(Q.root.unit,G),Q.unsetRoot();return}if(Q.root.unit instanceof Date){let H=`d'${Q.root.description??Q.root.unit.toISOString()}'`;Q.unsetRoot(),Q.reduceLeftBound(H,G);return}}return ur0(Q,G)},zA0={"<":1,">":1,"=":1},fr0=(Q,J)=>Q.scanner.lookaheadIs("=")?`${J}${Q.scanner.shift()}`:J;var AA0=(Q,J,G,H)=>{if(G.extends(NQ.intrinsic.number)){if(typeof J!=="number")return zQ(hv(Q,J,H));return Q==="=="?["min","max"]:Q[0]===">"?["min"]:["max"]}if(G.extends(NQ.intrinsic.lengthBoundable)){if(typeof J!=="number")return zQ(hv(Q,J,H));return Q==="=="?["exactLength"]:Q[0]===">"?["minLength"]:["maxLength"]}if(G.extends(NQ.intrinsic.Date))return Q==="=="?["after","before"]:Q[0]===">"?["after"]:["before"];return zQ(XB0(G.expression))},mr0=(Q)=>({rule:aB0(Q.limit)?sB0(Q.limit):Q.limit,exclusive:Q.comparator.length===1}),ur0=(Q,J)=>{let G=Q.unsetRoot(),H=Q.scanner.location;Q.parseOperand();let K=Q.unsetRoot(),z=Q.scanner.sliceChars(H,Q.scanner.location);if(Q.root=G,!K.hasKind("unit")||typeof K.unit!=="number"&&!(K.unit instanceof Date))return Q.error(hv(J,z,"right"));let q=K.unit,F=J.length===1,D=AA0(J,typeof q==="number"?q:z,G,"right");for(let O of D)Q.constrainRoot(O,J==="=="?{rule:q}:{rule:q,exclusive:F});if(!Q.branches.leftBound)return;if(!ZX(J,JA0))return Q.error(SP(J));let V=AA0(Q.branches.leftBound.comparator,Q.branches.leftBound.limit,G,"left");Q.constrainRoot(V[0],mr0(Q.branches.leftBound)),Q.branches.leftBound=null},hv=(Q,J,G)=>`Comparator ${G==="left"?nK[Q]:Q} must be ${G==="left"?"preceded":"followed"} by a corresponding literal (was ${J})`;var VA0=(Q)=>{Q.scanner.shiftUntilNonWhitespace();let J=Q.scanner.shiftUntilNextTerminator();Q.root=Q.root.brand(J)};var UA0=(Q)=>{let J=Q.scanner.shiftUntilNextTerminator(),G=x30(J,{errorOnFail:qA0(J)});if(G===0)Q.error(qA0(0));Q.root=Q.root.constrain("divisor",G)},qA0=(Q)=>`% operator must be followed by a non-zero integer literal (was ${Q})`;var _v=(Q)=>{let J=Q.scanner.shift();return J===""?Q.finalize(""):J==="["?Q.scanner.shift()==="]"?Q.setRoot(Q.root.array()):Q.error(pr0):J==="|"||J==="&"?Q.pushRootToBranch(J):J===")"?Q.finalizeGroup():V5.lookaheadIsFinalizing(J,Q.scanner.unscanned)?Q.finalize(J):ZX(J,zA0)?KA0(Q,J):J==="%"?UA0(Q):J==="#"?VA0(Q):(J in R4)?_v(Q):Q.error(TP(J))},TP=(Q,J="")=>`'${Q}' is not allowed here${J&&` (should be ${J})`}`,pr0="Missing expected ']'";var $A0=(Q)=>{let J=Q.unsetRoot();Q.parseOperand();let G=Q.unsetRoot();if(!G.hasKind("unit"))return Q.error(lr0(G.expression));let H=G.unit instanceof Date?()=>new Date(G.unit):G.unit;return[J,"=",H]},lr0=(Q)=>`Default value '${Q}' must a literal value`;var fv=(Q,J)=>{let G=J.$.maybeResolveRoot(Q);if(G)return G;let H=Q.endsWith("[]")?J.$.maybeResolveRoot(Q.slice(0,-2))?.array():void 0;if(H)return H;let K=new aK(new V5(Q),J),z=dr0(K);if(K.finalizer===">")zQ(TP(">"));return z},dr0=(Q)=>{Q.parseOperand();let J=AU(Q).root;if(!J)return i6(`Root was unexpectedly unset after parsing string '${Q.scanner.scanned}'`);if(Q.finalizer==="=")J=$A0(Q);else if(Q.finalizer==="?")J=[J,"?"];if(Q.scanner.shiftUntilNonWhitespace(),Q.scanner.lookahead)zQ(TP(Q.scanner.lookahead));return J},AU=(Q)=>{while(Q.finalizer===void 0)cr0(Q);return Q},cr0=(Q)=>Q.hasRoot()?Q.parseOperator():Q.parseOperand();class aK{root;branches={prefixes:[],leftBound:null,intersection:null,union:null};finalizer;groups=[];scanner;ctx;constructor(Q,J){this.scanner=Q,this.ctx=J}error(Q){return zQ(Q)}hasRoot(){return this.root!==void 0}setRoot(Q){this.root=Q}unsetRoot(){let Q=this.root;return this.root=void 0,Q}constrainRoot(...Q){this.root=this.root.constrain(Q[0],Q[1])}finalize(Q){if(this.groups.length)return this.error(EP(")"));this.finalizeBranches(),this.finalizer=Q}reduceLeftBound(Q,J){let G=nK[J];if(!ZX(G,XA0))return this.error(SP(J));if(this.branches.leftBound)return this.error(WA0(this.branches.leftBound.limit,this.branches.leftBound.comparator,Q,G));this.branches.leftBound={comparator:G,limit:Q}}finalizeBranches(){if(this.assertRangeUnset(),this.branches.union)this.pushRootToBranch("|"),this.root=this.branches.union;else if(this.branches.intersection)this.pushRootToBranch("&"),this.root=this.branches.intersection;else this.applyPrefixes()}finalizeGroup(){this.finalizeBranches();let Q=this.groups.pop();if(!Q)return this.error(YA0(this.scanner.unscanned));this.branches=Q}addPrefix(Q){this.branches.prefixes.push(Q)}applyPrefixes(){while(this.branches.prefixes.length){let Q=this.branches.prefixes.pop();this.root=Q==="keyof"?this.root.keyof():i6(`Unexpected prefix '${Q}'`)}}pushRootToBranch(Q){this.assertRangeUnset(),this.applyPrefixes();let J=this.root;if(this.branches.intersection=this.branches.intersection?.rawAnd(J)??J,Q==="|")this.branches.union=this.branches.union?.rawOr(this.branches.intersection)??this.branches.intersection,this.branches.intersection=null;this.root=void 0}parseUntilFinalizer(){return AU(new aK(this.scanner,this.ctx))}parseOperator(){return _v(this)}parseOperand(){return gv(this)}assertRangeUnset(){if(this.branches.leftBound)return this.error(GA0(this.branches.leftBound.limit,this.branches.leftBound.comparator))}reduceGroupOpen(){this.groups.push(this.branches),this.branches={prefixes:[],leftBound:null,union:null,intersection:null}}previousOperator(){return this.branches.leftBound?.comparator??this.branches.prefixes.at(-1)??(this.branches.intersection?"&":this.branches.union?"|":void 0)}shiftedByOne(){return this.scanner.shift(),this}}var ir0="An empty string is not a valid generic parameter name",kP=(Q,J,G)=>{Q.shiftUntilNonWhitespace();let H=Q.shiftUntilNextTerminator();if(H===""){if(Q.lookahead===""&&J.length)return J;return zQ(ir0)}return Q.shiftUntilNonWhitespace(),or0(Q,H,J,G)},ZA0="extends ",or0=(Q,J,G,H)=>{if(Q.shiftUntilNonWhitespace(),Q.unscanned.startsWith(ZA0))Q.jumpForward(ZA0.length);else{if(Q.lookahead===",")Q.shift();return G.push(J),kP(Q,G,H)}let K=AU(new aK(Q,H));return G.push([J,K.root]),kP(Q,G,H)};var yP=(Q,J)=>{if(V9(Q)){if(Q[1]==="=")return[J.$.parseOwnDefinitionFormat(Q[0],J),"=",Q[2]];if(Q[1]==="?")return[J.$.parseOwnDefinitionFormat(Q[0],J),"?"]}return vP(Q,J)},FA0="Only required keys may make their values optional, e.g. { [mySymbol]: ['number', '?'] }",DA0="Only required keys may specify default values, e.g. { value: 'number = 0' }";var MA0=(Q,J)=>{let G,H={},K=dq(Q);for(let[q,F]of K){let D=sr0(q);if(D.kind==="spread"){if(!UG(H))return zQ(ar0);let I=J.$.parseOwnDefinitionFormat(F,J);if(!I.hasKind("intersection")||!I.structure)return zQ(rr0(I.expression));G=I.structure;continue}if(D.kind==="undeclared"){if(F!=="reject"&&F!=="delete"&&F!=="ignore")zQ(nr0(F));H.undeclared=F;continue}let V=yP(F,J),O=D;if(D.kind==="required"){if(!V9(V))mv(H,"required",{key:D.normalized,value:V},J);else mv(H,"optional",V[1]==="="?{key:D.normalized,value:V[0],default:V[2]}:{key:D.normalized,value:V[0]},J);continue}if(V9(V)){if(V[1]==="?")zQ(FA0);if(V[1]==="=")zQ(DA0)}if(D.kind==="optional"){mv(H,"optional",{key:D.normalized,value:V},J);continue}let P=J.$.parseOwnDefinitionFormat(O.normalized,J),N=jP(P,V,J.$);if(N.index)H.index=D6(H.index,N.index);if(N.required)H.required=D6(H.required,N.required)}let z=J.$.node("structure",H);return J.$.parseSchema({domain:"object",structure:G?.merge(z)??z})},mv=(Q,J,G,H)=>{Q[J]=D6(Q[J],H.$.node(J,G))},nr0=(Q)=>`Value of '+' key must be 'reject', 'delete', or 'ignore' (was ${n8(Q)})`,ar0="Spread operator may only be used as the first key in an object",sr0=(Q)=>typeof Q==="symbol"?{kind:"required",normalized:Q}:Q.at(-1)==="?"?Q.at(-2)===nq?{kind:"required",normalized:`${Q.slice(0,-2)}?`}:{kind:"optional",normalized:Q.slice(0,-1)}:Q[0]==="["&&Q.at(-1)==="]"?{kind:"index",normalized:Q.slice(1,-1)}:Q[0]===nq&&Q[1]==="["&&Q.at(-1)==="]"?{kind:"required",normalized:Q.slice(1)}:Q==="..."?{kind:"spread"}:Q==="+"?{kind:"undeclared"}:{kind:"required",normalized:Q==="\\..."?"...":Q==="\\+"?"+":Q},rr0=(Q)=>`Spread operand must resolve to an object literal type (was ${Q})`;var PA0=(Q,J)=>Gt0(Q)?CA0[Q[0]](Q,J):Qt0(Q)?jA0[Q[1]](Q,J):null,tr0=(Q,J)=>J.$.parseOwnDefinitionFormat(Q[1],J).keyof(),LA0=(Q,J)=>{if(Q[2]===void 0)return zQ(bv(Q[1],""));let G=J.$.parseOwnDefinitionFormat(Q[0],J),H=J.$.parseOwnDefinitionFormat(Q[2],J);if(Q[1]==="|")return J.$.node("union",{branches:[G,H]});let K=HY(G,H,J.$);if(K instanceof _Q)return K.throw();return K},er0=(Q,J)=>J.$.parseOwnDefinitionFormat(Q[0],J).array(),Qt0=(Q)=>jA0[Q[1]]!==void 0,Xt0=(Q,J)=>{if(typeof Q[2]!=="function")return zQ(NA0("=>",Q[2]));return J.$.parseOwnDefinitionFormat(Q[0],J).pipe(Q[2])},NA0=(Q,J)=>`${Q===":"?"Narrow":"Morph"} expression requires a function following '${Q}' (was ${typeof J})`,Jt0=(Q,J)=>{if(typeof Q[2]!=="function")return zQ(NA0(":",Q[2]));return J.$.parseOwnDefinitionFormat(Q[0],J).constrain("predicate",Q[2])},Yt0=(Q,J)=>J.$.parseOwnDefinitionFormat(Q[0],J).configureShallowDescendants(Q[2]),jA0={"[]":er0,"|":LA0,"&":LA0,":":Jt0,"=>":Xt0,"@":Yt0,"=":()=>zQ(wP),"?":()=>zQ(RP)},CA0={keyof:tr0,instanceof:(Q,J)=>{if(typeof Q[1]!=="function")return zQ(OA0(iq(Q[1])));let G=Q.slice(1).map((H)=>typeof H==="function"?J.$.node("proto",{proto:H}):zQ(OA0(iq(H))));return G.length===1?G[0]:J.$.node("union",{branches:G})},"===":(Q,J)=>J.$.units(Q.slice(1))},Gt0=(Q)=>CA0[Q[0]]!==void 0,OA0=(Q)=>`Expected a constructor following 'instanceof' operator (was ${Q})`;var wA0=(Q,J)=>{let G=[{}],H=0;while(H<Q.length){let K=!1;if(Q[H]==="..."&&H<Q.length-1)K=!0,H++;let z=yP(Q[H],J),[q,F,D]=!V9(z)?[z]:z;if(H++,K){if(!q.extends(NQ.intrinsic.Array))return zQ(Bt0(q.expression));G=G.flatMap((V)=>q.distribute((O)=>Ht0(VP(V),O)))}else G=G.map((V)=>{if(F==="?")return EA0(V,q);if(F==="=")return Wt0(V,q,D);return uv(V,q)})}return J.$.parseSchema(G.map((K)=>UG(K)?{proto:Array,exactLength:0}:{proto:Array,sequence:K}))},uv=(Q,J)=>{if(Q.defaultables||Q.optionals)return zQ(Q.variadic?Av:At0);if(Q.variadic)Q.postfix=D6(Q.postfix,J);else Q.prefix=D6(Q.prefix,J);return Q},EA0=(Q,J)=>{if(Q.variadic)return zQ(SA0);return Q.optionals=D6(Q.optionals,J),Q},Wt0=(Q,J,G)=>{if(Q.variadic)return zQ(SA0);if(Q.optionals)return zQ(Kt0);return Q.defaultables=D6(Q.defaultables,[[J,G]]),Q},IA0=(Q,J)=>{if(Q.postfix)zQ(RA0);if(Q.variadic){if(!Q.variadic.equals(J))zQ(RA0)}else Q.variadic=J.internal;return Q},Ht0=(Q,J)=>{let G=J.firstReferenceOfKind("sequence");if(!G)return IA0(Q,NQ.intrinsic.unknown);if(G.prefix?.forEach((H)=>uv(Q,H)),G.optionals?.forEach((H)=>EA0(Q,H)),G.variadic)IA0(Q,G.variadic);return G.postfix?.forEach((H)=>uv(Q,H)),Q},Bt0=(Q)=>`Spread element must be an array (was ${Q})`,RA0="A tuple may have at most one variadic element",At0="A required element may not follow an optional element",SA0="An optional element may not follow a variadic element";var Kt0="A defaultable element may not follow an optional element without a default";var zt0={},vP=(Q,J)=>{if(typeof Q==="string"){if(J.args&&Object.keys(J.args).some((H)=>Q.includes(H)))return fv(Q,J);let G=zt0[J.$.id]??={};return G[Q]??=fv(Q,J)}return xJ(Q,"object")?Vt0(Q,J):zQ(pv(zJ(Q)))},Vt0=(Q,J)=>{let G=cq(Q);switch(G){case void 0:if(Q8(Q,"root"))return Q;return MA0(Q,J);case"Array":return qt0(Q,J);case"RegExp":return J.$.node("intersection",{domain:"string",pattern:Q},{prereduced:!0});case"Function":{let H=C4(Q)?Q():Q;if(Q8(H,"root"))return H;return zQ(pv("Function"))}default:return zQ(pv(G??n8(Q)))}},qt0=(Q,J)=>PA0(Q,J)??wA0(Q,J),pv=(Q)=>`Type definitions must be strings or objects (was ${Q})`;class lv extends I4{constructor(Q){let J=Object.assign({errors:gJ,hkt:hX,$:Q,raw:Q.parse,module:Q.constructor.module,scope:Q.constructor.scope,define:Q.define,generic:Q.generic,schema:Q.schema,keywords:Q.ambient,unit:Q.unit,enumerated:Q.enumerated,instanceOf:Q.instanceOf},Q.ambientAttachments);super((...G)=>{if(G.length===1)return Q.parse(G[0]);if(G.length===2&&typeof G[0]==="string"&&G[0][0]==="<"&&G[0].at(-1)===">"){let H=G[0].slice(1,-1),K=Q.parseGenericParams(H,{});return new E4(K,G[1],Q,Q,null)}return Q.parse(G)},{bind:Q,attach:J})}}var xP=NQ;class bP extends CP{cacheGetter(Q,J){return Object.defineProperty(this,Q,{value:J}),J}get ambientAttachments(){if(!xP.typeAttachments)return;return this.cacheGetter("ambientAttachments",r8(xP.typeAttachments,(Q,J)=>[Q,this.bindReference(J)]))}preparseOwnAliasEntry(Q,J){let G=Q.indexOf("<");if(G===-1)return[Q,J];if(Q.at(-1)!==">")zQ("'>' must be the last character of a generic declaration in a scope");let H=Q.slice(0,G),K=Q.slice(G+1,-1);return[H,()=>{let z=this.parseGenericParams(K,{alias:H});return s30(z,J,this)}]}parseGenericParams(Q,J){return kP(new V5(Q),[],this.createParseContext({...J,def:Q,prefix:"generic"}))}normalizeRootScopeValue(Q){if(C4(Q)&&!Q8(Q,"generic"))return Q();return Q}preparseOwnDefinitionFormat(Q,J){return{...J,def:Q,prefix:J.alias??"type"}}parseOwnDefinitionFormat(Q,J){if(!(J.alias&&(J.alias in this.aliases))&&!J.args)J.args={this:J.id};let H=vP(Q,J);if(V9(H)){if(H[1]==="=")return zQ(wP);if(H[1]==="?")return zQ(RP)}return H}unit=(Q)=>this.units([Q]);enumerated=(...Q)=>this.units(Q);instanceOf=(Q)=>this.node("proto",{proto:Q},{prereduced:!0});type=new lv(this);declare=()=>({type:this.type});define(Q){return Q}static scope=(Q,J={})=>new bP(Q,J);static module=(Q,J={})=>this.scope(Q,J).export()}var dv=Object.assign(bP.scope,{define:(Q)=>Q}),X6=bP;class TA0 extends hX{}var Ut0=vY(["base",_8.object],["props",_8.object])((Q)=>Q.base.merge(Q.props),TA0),cv=X6.module({Key:_8.key,Merge:Ut0});class kA0 extends hX{}var $t0=vY("element")((Q)=>{let J=Q.element.exclude(_8.Array),G=J.array();return J.rawOr(G).pipe(kK).distribute((H)=>H.assertHasKind("morph").declareOut(G),G9)},kA0),yA0=X6.module({root:_8.Array,readonly:"root",index:_8.nonNegativeIntegerString,liftFrom:$t0});var iv=G9(["string",A3.FileConstructor]),Zt0=iv.rawOr(iv.array()),vA0=G9({meta:"an object representing parsed form data",domain:"object",index:{signature:"string",value:Zt0}}),xA0=X6.module({root:["instanceof",FormData],value:iv,parsed:vA0,parse:G9({in:FormData,morphs:(Q)=>{let J={};for(let[G,H]of Q)if(G in J){let K=J[G];if(typeof K==="string"||K instanceof A3.FileConstructor)J[G]=[K,H];else K.push(H)}else J[G]=H;return J},declaredOut:vA0})});var bA0=X6.module({Int8:["instanceof",Int8Array],Uint8:["instanceof",Uint8Array],Uint8Clamped:["instanceof",Uint8ClampedArray],Int16:["instanceof",Int16Array],Uint16:["instanceof",Uint16Array],Int32:["instanceof",Int32Array],Uint32:["instanceof",Uint32Array],Float32:["instanceof",Float32Array],Float64:["instanceof",Float64Array],BigInt64:["instanceof",BigInt64Array],BigUint64:["instanceof",BigUint64Array]});var Ft0={Boolean:1,Number:1,String:1},gP=X6.module({...r8({...qk,...$k},(Q,J)=>(Q in Ft0)?[]:[Q,["instanceof",J]]),Array:yA0,TypedArray:bA0,FormData:xA0});var Dt0=G9({domain:{domain:"number",meta:"a number representing a Unix timestamp"},divisor:{rule:1,meta:"an integer representing a Unix timestamp"},min:{rule:-8640000000000000,meta:"a Unix timestamp after -8640000000000000"},max:{rule:8640000000000000,meta:"a Unix timestamp before 8640000000000000"},meta:"an integer representing a safe Unix timestamp"}),Mt0=G9({domain:"number",divisor:1}),hP=X6.module({root:_8.number,integer:Mt0,epoch:Dt0,safe:G9({domain:"number",min:Number.MIN_SAFE_INTEGER,max:Number.MAX_SAFE_INTEGER,predicate:{predicate:(Q)=>!Number.isNaN(Q),meta:"a safe number"}}),NaN:["===",Number.NaN],Infinity:["===",Number.POSITIVE_INFINITY],NegativeInfinity:["===",Number.NEGATIVE_INFINITY]});var b9=(Q,J)=>oK("intersection",{domain:"string",pattern:{rule:Q.source,flags:Q.flags,meta:J}}),gA0=b9(aq,"a well-formed integer string"),oA0=X6.module({root:gA0,parse:G9({in:gA0,morphs:(Q,J)=>{let G=Number.parseInt(Q);return Number.isSafeInteger(G)?G:J.error("an integer in the range Number.MIN_SAFE_INTEGER to Number.MAX_SAFE_INTEGER")},declaredOut:_8.integer})}),Lt0=X6.module({root:b9(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,"base64-encoded"),url:b9(/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2}(?:==|%3D%3D)?|[A-Za-z0-9_-]{3}(?:=|%3D)?)?$/,"base64url-encoded")}),hA0=b9(/^[A-Z].*$/,"capitalized"),Ot0=X6.module({root:G9({in:"string",morphs:(Q)=>Q.charAt(0).toUpperCase()+Q.slice(1),declaredOut:hA0}),preformatted:hA0}),Pt0=(Q)=>{let J=Q.replace(/[- ]+/g,""),G=0,H,K,z=!1;for(let q=J.length-1;q>=0;q--){if(H=J.substring(q,q+1),K=Number.parseInt(H,10),z)if(K*=2,K>=10)G+=K%10+1;else G+=K;else G+=K;z=!z}return!!(G%10===0?J:!1)},Nt0=/^(?:4[0-9]{12}(?:[0-9]{3,6})?|5[1-5][0-9]{14}|(222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|6(?:011|5[0-9][0-9])[0-9]{12,15}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11}|6[27][0-9]{14}|^(81[0-9]{14,17}))$/,jt0=G9({domain:"string",pattern:{meta:"a credit card number",rule:Nt0.source},predicate:{meta:"a credit card number",predicate:Pt0}});var Ct0=/^([+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T]((([01]\d|2[0-3])((:?)[0-5]\d)?|24:?00)([.,]\d+(?!:))?)?(\17[0-5]\d([.,]\d+)?)?([zZ]|([+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var It0=(Q)=>!Number.isNaN(new Date(Q).valueOf()),_A0=G9({domain:"string",predicate:{meta:"a parsable date",predicate:It0}}).assertHasKind("intersection"),fA0=oA0.root.internal.narrow((Q,J)=>{let G=Number.parseInt(Q),H=hP.epoch(G);if(H instanceof gJ)return J.errors.merge(H),!1;return!0}).withMeta({description:"an integer string representing a safe Unix timestamp"}).assertHasKind("intersection"),Rt0=X6.module({root:fA0,parse:G9({in:fA0,morphs:(Q)=>new Date(Q),declaredOut:_8.Date})}),mA0=b9(Ct0,"an ISO 8601 (YYYY-MM-DDTHH:mm:ss.sssZ) date").internal.assertHasKind("intersection"),wt0=X6.module({root:mA0,parse:G9({in:mA0,morphs:(Q)=>new Date(Q),declaredOut:_8.Date})}),Et0=X6.module({root:_A0,parse:G9({declaredIn:_A0,in:"string",morphs:(Q,J)=>{let G=new Date(Q);if(Number.isNaN(G.valueOf()))return J.error("a parsable date");return G},declaredOut:_8.Date}),iso:wt0,epoch:Rt0}),St0=b9(/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,"an email address"),uA0="(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])",T4=`(${uA0}[.]){3}${uA0}`,Tt0=new RegExp(`^${T4}$`),C7="(?:[0-9a-fA-F]{1,4})",kt0=new RegExp(`^((?:${C7}:){7}(?:${C7}|:)|(?:${C7}:){6}(?:${T4}|:${C7}|:)|(?:${C7}:){5}(?::${T4}|(:${C7}){1,2}|:)|(?:${C7}:){4}(?:(:${C7}){0,1}:${T4}|(:${C7}){1,3}|:)|(?:${C7}:){3}(?:(:${C7}){0,2}:${T4}|(:${C7}){1,4}|:)|(?:${C7}:){2}(?:(:${C7}){0,3}:${T4}|(:${C7}){1,5}|:)|(?:${C7}:){1}(?:(:${C7}){0,4}:${T4}|(:${C7}){1,6}|:)|(?::((?::${C7}){0,5}:${T4}|(?::${C7}){1,7}|:)))(%[0-9a-zA-Z.]{1,})?$`),yt0=X6.module({root:["v4 | v6","@","an IP address"],v4:b9(Tt0,"an IPv4 address"),v6:b9(kt0,"an IPv6 address")}),KU="a JSON string",nA0=(Q)=>{if(!(Q instanceof SyntaxError))throw Q;return`must be ${KU} (${Q})`},vt0=G9({domain:"string",predicate:{meta:KU,predicate:(Q,J)=>{try{return JSON.parse(Q),!0}catch(G){return J.reject({code:"predicate",expected:KU,problem:nA0(G)})}}}}),xt0=(Q,J)=>{if(Q.length===0)return J.error({code:"predicate",expected:KU,actual:"empty"});try{return JSON.parse(Q)}catch(G){return J.error({code:"predicate",expected:KU,problem:nA0(G)})}},bt0=X6.module({root:vt0,parse:G9({in:"string",morphs:xt0,declaredOut:_8.json})}),pA0=b9(/^[a-z]*$/,"only lowercase letters"),gt0=X6.module({root:G9({in:"string",morphs:(Q)=>Q.toLowerCase(),declaredOut:pA0}),preformatted:pA0}),aA0=["NFC","NFD","NFKC","NFKD"],zU=r8(aA0,(Q,J)=>[J,G9({domain:"string",predicate:(G)=>G.normalize(J)===G,meta:`${J}-normalized unicode`})]),_P=r8(aA0,(Q,J)=>[J,G9({in:"string",morphs:(G)=>G.normalize(J),declaredOut:zU[J]})]),ht0=X6.module({root:_P.NFC,preformatted:zU.NFC}),_t0=X6.module({root:_P.NFD,preformatted:zU.NFD}),ft0=X6.module({root:_P.NFKC,preformatted:zU.NFKC}),mt0=X6.module({root:_P.NFKD,preformatted:zU.NFKD}),ut0=X6.module({root:"NFC",NFC:ht0,NFD:_t0,NFKC:ft0,NFKD:mt0}),lA0=b9(S30,"a well-formed numeric string"),pt0=X6.module({root:lA0,parse:G9({in:lA0,morphs:(Q)=>Number.parseFloat(Q),declaredOut:_8.number})}),lt0=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/,dt0=b9(lt0,"a semantic version (see https://semver.org/)"),dA0=b9(/^\S.*\S$|^\S?$/,"trimmed"),ct0=X6.module({root:G9({in:"string",morphs:(Q)=>Q.trim(),declaredOut:dA0}),preformatted:dA0}),cA0=b9(/^[A-Z]*$/,"only uppercase letters"),it0=X6.module({root:G9({in:"string",morphs:(Q)=>Q.toUpperCase(),declaredOut:cA0}),preformatted:cA0}),ot0=(Q)=>{if(URL.canParse)return URL.canParse(Q);try{return new URL(Q),!0}catch{return!1}},iA0=G9({domain:"string",predicate:{meta:"a URL string",predicate:ot0}}),nt0=X6.module({root:iA0,parse:G9({declaredIn:iA0,in:"string",morphs:(Q,J)=>{try{return new URL(Q)}catch{return J.error("a URL string")}},declaredOut:G9(URL)})}),at0=X6.module({root:["versioned | nil | max","@","a UUID"],"#nil":"'00000000-0000-0000-0000-000000000000'","#max":"'ffffffff-ffff-ffff-ffff-ffffffffffff'","#versioned":/[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i,v1:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv1"),v2:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-2[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv2"),v3:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv3"),v4:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv4"),v5:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv5"),v6:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-6[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv6"),v7:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv7"),v8:b9(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,"a UUIDv8")}),sA0=X6.module({root:_8.string,alpha:b9(/^[A-Za-z]*$/,"only letters"),alphanumeric:b9(/^[A-Za-z\d]*$/,"only letters and digits 0-9"),base64:Lt0,capitalize:Ot0,creditCard:jt0,date:Et0,digits:b9(/^\d*$/,"only digits 0-9"),email:St0,integer:oA0,ip:yt0,json:bt0,lower:gt0,normalize:ut0,numeric:pt0,semver:dt0,trim:ct0,upper:it0,url:nt0,uuid:at0});var ov=X6.module({bigint:_8.bigint,boolean:_8.boolean,false:_8.false,never:_8.never,null:_8.null,number:_8.number,object:_8.object,string:_8.string,symbol:_8.symbol,true:_8.true,unknown:_8.unknown,undefined:_8.undefined}),rA0=X6.module({root:_8.unknown,any:_8.unknown}),st0=X6.module({root:_8.json,stringify:oK("morph",{in:_8.json,morphs:(Q)=>JSON.stringify(Q),declaredOut:_8.string})}),tA0=X6.module({root:_8.object,json:st0});class eA0 extends hX{description="a generic type that instantiates an object from a single index signature and corresponding value type"}var rt0=vY(["K",_8.key],"V")((Q)=>({domain:"object",index:{signature:Q.K,value:Q.V}}),eA0);class QK0 extends hX{}var tt0=vY(["T",_8.object],["K",_8.key])((Q)=>Q.T.pick(Q.K),QK0);class XK0 extends hX{}var et0=vY(["T",_8.object],["K",_8.key])((Q)=>Q.T.omit(Q.K),XK0);class JK0 extends hX{}var Qe0=vY(["T",_8.object])((Q)=>Q.T.partial(),JK0);class YK0 extends hX{}var Xe0=vY(["T",_8.object])((Q)=>Q.T.required(),YK0);class GK0 extends hX{}var Je0=vY("T","U")((Q)=>Q.T.exclude(Q.U),GK0);class WK0 extends hX{}var Ye0=vY("T","U")((Q)=>Q.T.extract(Q.U),WK0),nv=X6.module({Exclude:Je0,Extract:Ye0,Omit:et0,Partial:Qe0,Pick:tt0,Record:rt0,Required:Xe0});xP.typeAttachments={...ov,Key:cv.Key,Record:nv.Record,Array:gP.Array.root,Date:gP.Date};var Z3=dv({...ov,...nv,...gP,...cv,string:sA0,number:hP,object:tA0,unknown:rA0},{prereducedAliases:!0,ambient:!0}),Ge0=Z3.export(),e=Z3.type,We0=Z3.generic,meQ=Z3.schema,He0=Z3.define,Be0=Z3.declare;function fP(){let Q=Promise.resolve();return{async run(J){let G=Q,H;Q=new Promise((z)=>{H=z});try{return await G,await J()}finally{H()}}}}var xY=fP();var uP=require("fs"),HK0=require("fs/promises"),sK=require("os"),rK=require("path");function BK0(Q,J){switch(sK.platform()){case"darwin":return rK.resolve(sK.homedir(),"Library","Logs",Q,J);case"win32":return rK.resolve(sK.homedir(),"AppData","Local","Logs",Q,J);case"linux":return rK.resolve(sK.homedir(),".local","share","logs",Q,J);default:throw Error("Unsupported operating system")}}var Ae0=(Q)=>{if(!uP.existsSync(Q))uP.mkdirSync(Q,{recursive:!0})},av=["DEBUG","INFO","WARN","ERROR","FATAL"],Ke0=e.enumerated(...av),ze0=(Q,J,G)=>{let H=new Date().toISOString(),K=Object.keys(G).length?`
${JSON.stringify(G,null,2)}`:"";return`${H} [${Q.padEnd(5)}] ${JSON.stringify(J)}${K}
`},Ve0=e({appName:"string",filename:"string",level:Ke0}),mP=Ve0.pipe((Q)=>{let J=BK0(Q.appName,Q.filename),G=av.slice(av.indexOf(Q.level));return{...Q,levels:G,filename:J}});function AK0(Q){let J=mP.assert(Q),G={},H=[],K=(P,N,I)=>{if(!J.levels.includes(P))return;Ae0(rK.dirname(BK0(J.appName,J.filename))),H.push(HK0.appendFile(J.filename,ze0(P,N,{...G,...I??{}})))},O={debug:(P,N)=>K("DEBUG",P,N),info:(P,N)=>K("INFO",P,N),warn:(P,N)=>K("WARN",P,N),error:(P,N)=>K("ERROR",P,N),fatal:(P,N)=>K("FATAL",P,N),flush(){return Promise.all(H)},get config(){return{...J}},set config(P){J=mP.assert({...J,...P}),O.debug("Updated logger configuration",{config:J})},set meta(P){G=P}};return O}var KK0=e({"exclude_key?":e("string").describe("A single key to exclude."),"exclude_keys?":e("string[]").describe("An array of keys to exclude. If exclude_key is provided, it's added to this array."),"exclude_key_starts_with?":e("string").describe("Exclude keys starting with this string."),"exclude_key_starts_with_any?":e("string[]").describe("Exclude keys starting with any of these strings."),"exclude_key_includes?":e("string").describe("Exclude keys that include this string."),"key_ends_with?":e("string").describe("Include only keys ending with this string."),"key_starts_with?":e("string").describe("Include only keys starting with this string."),"key_starts_with_any?":e("string[]").describe("Include only keys starting with any of these strings."),"key_includes?":e("string").describe("Include only keys that include this string."),"limit?":e("number").describe("Limit the number of search results.")});var pP={};UD(pP,{RunMode:()=>VK0,FunctionsMode:()=>qK0});var VK0;((q)=>{q[q.CreateNewFromTemplate=0]="CreateNewFromTemplate";q[q.AppendActiveFile=1]="AppendActiveFile";q[q.OverwriteFile=2]="OverwriteFile";q[q.OverwriteActiveFile=3]="OverwriteActiveFile";q[q.DynamicProcessor=4]="DynamicProcessor";q[q.StartupTemplate=5]="StartupTemplate"})(VK0||={});var qK0;((G)=>{G[G.INTERNAL=0]="INTERNAL";G[G.USER_INTERNAL=1]="USER_INTERNAL"})(qK0||={});var qe0=e({name:"string","description?":"string","required?":"boolean"}),A08=e({name:"string","description?":e("string").describe("Description of the prompt"),"arguments?":qe0.array()}),Ue0=e("'mcp-tools-prompt'"),lP=e({tags:e("string[]").narrow((Q)=>Q.some((J)=>Ue0.allows(J))),"description?":e("string")}),$e0=e({type:"'MISSING_REQUIRED_ARG'|'INVALID_ARG_VALUE'",message:"string","argumentName?":"string"}),K08=e({content:"string","errors?":$e0.array()});var Ze0=e({query:e("string>0").describe("A search phrase for semantic search"),"filter?":{"folders?":e("string[]").describe('An array of folder names to include. For example, ["Public", "Work"]'),"excludeFolders?":e("string[]").describe('An array of folder names to exclude. For example, ["Private", "Archive"]'),"limit?":e("number>0").describe("The maximum number of results to return")}}),q08=e("string.json.parse").to(Ze0),U08=e({query:"string",filter:KK0});var Fe0=!0,UK0={appName:"Claude",filename:"obsidian-plugin-mcp-tools.log",level:"DEBUG"},{filename:N08}=mP.assert(UK0),SQ=Fe0?console:AK0(UK0);function sv(Q,J){if(Q===J)return!0;if(typeof Q!==typeof J)return!1;if(Q===null||J===null)return Q===J;if(Array.isArray(Q)||Array.isArray(J)){if(!Array.isArray(Q)||!Array.isArray(J)||Q.length!==J.length)return!1;return Q.every((G,H)=>sv(G,J[H]))}if(typeof Q==="object"&&typeof J==="object"){let G=Q,H=J,K=Object.keys(G),z=Object.keys(H);if(K.length!==z.length)return!1;return K.every((q)=>Object.prototype.hasOwnProperty.call(H,q)&&sv(G[q],H[q]))}return!1}class n9{plugin;mutex;constructor(Q,J=xY){this.plugin=Q;this.mutex=J}updateSlice(Q,J){return this.mutex.run(async()=>{let G=await this.plugin.loadData()??{},H=G[Q],K=J(H);if(K!==H)await this.plugin.saveData({...G,[Q]:K});return K})}loadSlice(Q,J){return this.mutex.run(async()=>{let G=await this.plugin.loadData()??{},H=G[Q],K={...J.defaults,...H&&typeof H==="object"?H:{}},z=K;if(J.schema){let q=J.schema(K);if(q instanceof e.errors)SQ.warn(`settings slice "${Q}" invalid, using defaults`,{summary:q.summary}),z=J.defaults;else z=q}if(!sv(H,z))await this.plugin.saveData({...G,[Q]:z});return z})}async readSlice(Q){return(await this.plugin.loadData())?.[Q]}}GH0();var ZG=require("obsidian");var rv=[{id:"editing",label:"Editing",description:"Common text-formatting and list commands",commandIds:["editor:toggle-bold","editor:toggle-italic","editor:toggle-strikethrough","editor:toggle-highlight","editor:toggle-code","editor:toggle-inline-math","editor:toggle-blockquote","editor:toggle-bullet-list","editor:toggle-numbered-list","editor:toggle-checklist-status","editor:toggle-comments","editor:insert-link","editor:insert-wikilink","editor:insert-embed","editor:insert-horizontal-rule","editor:insert-callout","editor:insert-tag"]},{id:"navigation",label:"Navigation",description:"Pane splits, tab navigation, graph view",commandIds:["app:go-back","app:go-forward","editor:focus-top","editor:focus-bottom","editor:focus-left","editor:focus-right","workspace:split-vertical","workspace:split-horizontal","workspace:close","workspace:next-tab","workspace:previous-tab","graph:open","graph:open-local"]},{id:"search",label:"Search",description:"Quick switcher, global search, file reveal",commandIds:["global-search:open","switcher:open","file-explorer:reveal-active-file"]}];function dP(Q,J){if(!J)return[];let G=new Set,H=[];for(let K of Q.commandIds){if(G.has(K))continue;if(J[K])G.add(K),H.push(K)}return H}function $K0(Q,J){let G=new Set(Q),H=[...Q];for(let K of J)if(!G.has(K))G.add(K),H.push(K);return H}var De0=oQ(`<p class="empty svelte-1arp3cq">No commands are allowed yet. Search or pick a preset below to
add some.</p>`),tv=oQ('<span class="destructive-badge svelte-1arp3cq" title="Destructive heuristic — this command can modify or remove data. Review carefully." aria-label="Destructive command">⚠</span>'),Me0=oQ('<li><!> <code class="svelte-1arp3cq"> </code> <button type="button" class="chip-remove svelte-1arp3cq">×</button></li>'),Le0=oQ('<ul class="chip-list svelte-1arp3cq" aria-label="Allowed commands"></ul>'),Oe0=oQ('<li class="chip stale-chip svelte-1arp3cq" title="Not registered in this vault"><code class="svelte-1arp3cq"> </code> <button type="button" class="chip-remove svelte-1arp3cq">×</button></li>'),Pe0=oQ(`<div class="stale-block svelte-1arp3cq"><div class="stale-header svelte-1arp3cq"><span class="stale-label svelte-1arp3cq"> </span> <span class="stale-hint svelte-1arp3cq">not currently registered in this vault — kept in case the
plugin is reinstalled</span> <button type="button" class="stale-remove-all svelte-1arp3cq"> </button></div> <ul class="chip-list stale-list svelte-1arp3cq" aria-label="Stale allowed commands"></ul></div>`),Ne0=oQ('<button type="button"> </button>'),je0=oQ('<li class="empty-row svelte-1arp3cq">No commands match your search.</li>'),ZK0=oQ('<li><label class="svelte-1arp3cq"><input type="checkbox"/> <!> <span class="cmd-meta svelte-1arp3cq"><code class="svelte-1arp3cq"> </code> <span class="cmd-name svelte-1arp3cq"> </span></span></label></li>'),Ce0=oQ('<ul class="search-results svelte-1arp3cq" aria-label="Search results"><!></ul>'),Ie0=oQ(`<p class="empty svelte-1arp3cq">No commands were found in the Obsidian command registry.
Try closing and reopening the settings tab.</p>`),Re0=oQ('<details class="namespace-group svelte-1arp3cq"><summary class="svelte-1arp3cq"><span class="namespace-label svelte-1arp3cq"> </span> <span class="namespace-counter svelte-1arp3cq"> </span></summary> <ul class="cmd-list svelte-1arp3cq"></ul></details>'),we0=oQ('<div class="namespace-list svelte-1arp3cq"></div>'),Ee0=oQ('<details class="browse-all svelte-1arp3cq"><summary class="svelte-1arp3cq"> </summary> <div class="browse-actions svelte-1arp3cq"><button type="button" class="refresh-registry" title="Re-snapshot the Obsidian command registry — useful after installing or uninstalling a plugin while this tab is open.">Refresh registry</button></div> <!></details>'),Se0=oQ('<section class="allowed-section svelte-1arp3cq" aria-labelledby="allowed-heading"><h4 id="allowed-heading" class="svelte-1arp3cq">Currently allowed <span class="counter svelte-1arp3cq"> </span></h4> <!> <!></section> <section class="add-section svelte-1arp3cq" aria-labelledby="add-heading"><h4 id="add-heading" class="svelte-1arp3cq">Add commands</h4> <input type="search" class="search svelte-1arp3cq" placeholder="Search by id or name (Enter adds first match)..." aria-label="Search available commands"/> <div class="presets-row svelte-1arp3cq" aria-label="Quick-add presets"><span class="presets-label svelte-1arp3cq">Quick start:</span> <!></div> <!></section>',1),Te0=oQ(`<p class="empty svelte-1arp3cq">No commands have been requested yet. When the agent calls <code>execute_obsidian_command</code>, each decision will be
logged here.</p>`),ke0=oQ('<div class="audit-reason svelte-1arp3cq"> </div>'),ye0=oQ('<li><div class="audit-header svelte-1arp3cq"><code class="svelte-1arp3cq"> </code> <span class="audit-decision svelte-1arp3cq"> </span> <span class="audit-time svelte-1arp3cq"> </span></div> <!></li>'),ve0=oQ('<div class="audit-actions svelte-1arp3cq"><button type="button">Export CSV</button></div> <ul class="audit-list svelte-1arp3cq"></ul>',1),xe0=oQ(`<div class="command-permissions-settings svelte-1arp3cq"><h3>Command execution</h3> <p class="description svelte-1arp3cq">Let the MCP agent run Obsidian commands (the entries you see in the
command palette). This feature is <strong>off by default</strong> — when enabled, only commands on the allowlist below are
authorized. Everything else is denied and logged. Changes apply
immediately; no client restart is required.</p> <label class="toggle-row svelte-1arp3cq"><input type="checkbox"/> Enable MCP command execution</label> <!> <details class="advanced svelte-1arp3cq"><summary class="svelte-1arp3cq">Advanced</summary> <div class="advanced-body svelte-1arp3cq"><label class="advanced-field svelte-1arp3cq"><span class="advanced-label svelte-1arp3cq">Soft rate-limit warning threshold <span class="hint svelte-1arp3cq"> </span></span> <input type="number" step="1" aria-label="Soft rate-limit warning threshold (commands per minute)" class="svelte-1arp3cq"/></label> <div class="advanced-field svelte-1arp3cq"><span class="advanced-label svelte-1arp3cq">Import / Export allowlist <span class="hint svelte-1arp3cq">For syncing the allowlist between vaults. Copy returns a
comma-separated list of command ids. Paste &amp; replace
overwrites the current allowlist (use with care).</span></span> <div class="import-export-actions svelte-1arp3cq"><button type="button">Copy as CSV</button></div> <textarea class="import-textarea svelte-1arp3cq" placeholder="Paste a CSV of command ids here..." rows="3" aria-label="Allowlist import buffer"></textarea> <div class="import-export-actions svelte-1arp3cq"><button type="button">Paste &amp; replace allowlist</button></div></div></div></details> <details class="audit-log svelte-1arp3cq"><summary class="svelte-1arp3cq"> </summary> <!></details></div>`),be0={hash:"svelte-1arp3cq",code:`.command-permissions-settings.svelte-1arp3cq {margin-top:2em;}.description.svelte-1arp3cq {color:var(--text-muted);font-size:0.9em;margin-bottom:0.75em;}.toggle-row.svelte-1arp3cq {display:flex;align-items:center;gap:0.5em;margin-bottom:1em;cursor:pointer;}.allowed-section.svelte-1arp3cq {margin:0.5em 0 1.2em;}.allowed-section.svelte-1arp3cq h4:where(.svelte-1arp3cq),
.add-section.svelte-1arp3cq h4:where(.svelte-1arp3cq) {margin:0 0 0.4em;font-size:0.95em;}.counter.svelte-1arp3cq {color:var(--text-muted);font-weight:normal;font-size:0.9em;}.chip-list.svelte-1arp3cq {list-style:none;margin:0;padding:0.5em 0.6em;display:flex;flex-wrap:wrap;gap:0.35em;background:var(--background-secondary);border-radius:4px;max-height:280px;overflow-y:auto;}.chip.svelte-1arp3cq {display:inline-flex;align-items:center;gap:0.2em;padding:0.15em 0.15em 0.15em 0.5em;background:var(--background-primary);border:1px solid var(--background-modifier-border);border-radius:999px;font-size:0.85em;}.chip.svelte-1arp3cq code:where(.svelte-1arp3cq) {font-family:var(--font-monospace);font-size:0.95em;}.chip-remove.svelte-1arp3cq {border:none;background:transparent;cursor:pointer;color:var(--text-muted);font-size:1.1em;line-height:1;padding:0 0.35em;border-radius:999px;}.chip-remove.svelte-1arp3cq:hover:not(:disabled) {color:var(--text-error, #c04848);background:var(--background-modifier-hover);}.destructive-badge.svelte-1arp3cq {color:var(--text-warning, #c08a3e);font-size:0.95em;cursor:help;line-height:1;}.chip-destructive.svelte-1arp3cq {border-color:var(--text-warning, #c08a3e);}.destructive-row.svelte-1arp3cq code:where(.svelte-1arp3cq) {color:var(--text-warning, #c08a3e);}.stale-block.svelte-1arp3cq {margin-top:0.6em;}.stale-header.svelte-1arp3cq {display:flex;flex-wrap:wrap;align-items:baseline;gap:0.5em;margin-bottom:0.3em;font-size:0.85em;}.stale-label.svelte-1arp3cq {font-weight:500;color:var(--text-muted);}.stale-hint.svelte-1arp3cq {color:var(--text-muted);font-size:0.85em;flex:1 1 auto;}.stale-list.svelte-1arp3cq {background:transparent;padding:0;}.stale-chip.svelte-1arp3cq {background:transparent;border-style:dashed;opacity:0.7;}.stale-chip.svelte-1arp3cq code:where(.svelte-1arp3cq) {font-style:italic;}.stale-remove-all.svelte-1arp3cq {flex-shrink:0;}.add-section.svelte-1arp3cq {margin:0.5em 0 1em;}.search.svelte-1arp3cq {width:100%;margin-bottom:0.5em;font-family:var(--font-monospace);font-size:0.9em;}.presets-row.svelte-1arp3cq {display:flex;flex-wrap:wrap;align-items:center;gap:0.4em;margin-bottom:0.6em;}.presets-label.svelte-1arp3cq {color:var(--text-muted);font-size:0.85em;margin-right:0.2em;}.search-results.svelte-1arp3cq,
.cmd-list.svelte-1arp3cq {list-style:none;margin:0;padding:0;border:1px solid var(--background-modifier-border);border-radius:4px;max-height:320px;overflow-y:auto;}.search-results.svelte-1arp3cq {margin-top:0.3em;}.cmd-row.svelte-1arp3cq {border-bottom:1px solid var(--background-modifier-border);}.cmd-row.svelte-1arp3cq:last-child {border-bottom:none;}.cmd-row.svelte-1arp3cq label:where(.svelte-1arp3cq) {display:flex;align-items:center;gap:0.5em;padding:0.3em 0.5em;cursor:pointer;}.cmd-meta.svelte-1arp3cq {display:flex;flex-direction:column;min-width:0;}.cmd-meta.svelte-1arp3cq code:where(.svelte-1arp3cq) {font-family:var(--font-monospace);font-size:0.85em;word-break:break-all;}.cmd-name.svelte-1arp3cq {color:var(--text-muted);font-size:0.8em;}.allowed-row.svelte-1arp3cq code:where(.svelte-1arp3cq) {color:var(--text-success, #2a7d2a);}.empty-row.svelte-1arp3cq {color:var(--text-muted);font-size:0.85em;padding:0.5em;text-align:center;}.browse-all.svelte-1arp3cq {margin-top:0.4em;}.browse-actions.svelte-1arp3cq {display:flex;justify-content:flex-end;margin:0.3em 0;}.namespace-list.svelte-1arp3cq {margin-top:0.3em;border:1px solid var(--background-modifier-border);border-radius:4px;max-height:420px;overflow-y:auto;}.namespace-group.svelte-1arp3cq {border-bottom:1px solid var(--background-modifier-border);margin:0;}.namespace-group.svelte-1arp3cq:last-child {border-bottom:none;}.namespace-group.svelte-1arp3cq summary:where(.svelte-1arp3cq) {padding:0.4em 0.6em;cursor:pointer;font-size:0.9em;background:var(--background-secondary);}.namespace-label.svelte-1arp3cq {font-family:var(--font-monospace);font-weight:500;}.namespace-counter.svelte-1arp3cq {color:var(--text-muted);font-size:0.85em;margin-left:0.4em;}.namespace-group.svelte-1arp3cq .cmd-list:where(.svelte-1arp3cq) {border:none;border-radius:0;max-height:none;}details.svelte-1arp3cq {margin-top:0.75em;}details.svelte-1arp3cq summary:where(.svelte-1arp3cq) {cursor:pointer;color:var(--text-muted);font-size:0.9em;}.empty.svelte-1arp3cq {color:var(--text-muted);font-size:0.85em;margin-top:0.5em;}.advanced-body.svelte-1arp3cq {padding:0.5em 0.25em 0.25em;display:flex;flex-direction:column;gap:1em;}.advanced-field.svelte-1arp3cq {display:flex;flex-direction:column;gap:0.3em;}.advanced-label.svelte-1arp3cq {font-size:0.9em;display:flex;flex-direction:column;gap:0.2em;}.hint.svelte-1arp3cq {color:var(--text-muted);font-size:0.85em;font-weight:normal;}.advanced-field.svelte-1arp3cq input[type="number"]:where(.svelte-1arp3cq) {width:8em;font-family:var(--font-monospace);}.import-textarea.svelte-1arp3cq {width:100%;font-family:var(--font-monospace);font-size:0.85em;resize:vertical;}.import-export-actions.svelte-1arp3cq {display:flex;gap:0.4em;}.audit-actions.svelte-1arp3cq {display:flex;justify-content:flex-end;margin:0.5em 0 0.25em 0;}.audit-list.svelte-1arp3cq {list-style:none;margin:0.5em 0 0 0;padding:0;max-height:320px;overflow-y:auto;}.audit-entry.svelte-1arp3cq {padding:0.4em 0.6em;margin-bottom:0.3em;border-left:3px solid var(--background-modifier-border);background:var(--background-secondary);border-radius:3px;font-size:0.85em;}.audit-allow.svelte-1arp3cq {border-left-color:var(--text-success, #2a7d2a);}.audit-deny.svelte-1arp3cq {border-left-color:var(--text-error, #c04848);}.audit-header.svelte-1arp3cq {display:flex;flex-wrap:wrap;align-items:baseline;gap:0.5em;}.audit-header.svelte-1arp3cq code:where(.svelte-1arp3cq) {font-family:var(--font-monospace);font-size:0.85em;word-break:break-all;}.audit-decision.svelte-1arp3cq {text-transform:uppercase;font-size:0.75em;font-weight:bold;color:var(--text-muted);}.audit-time.svelte-1arp3cq {color:var(--text-muted);font-size:0.75em;margin-left:auto;}.audit-reason.svelte-1arp3cq {margin-top:0.25em;color:var(--text-muted);font-size:0.8em;}`};function cP(Q,J){c7(J,!1),bX(Q,be0);let G=dQ(),H=dQ(),K=dQ(),z=dQ(),q=dQ(),F=dQ(),D=gX(J,"plugin",8),V=dQ(!1),O=dQ([]),P=dQ([]),N=dQ(""),I=dQ(!1),R=dQ(!1),w=dQ([]),E=dQ(void 0),T=dQ(""),y=dQ(null);SY(async()=>{var wQ,lQ,U8,P6,N6;let t9=await D().loadData(),F8=(wQ=t9===null||t9===void 0?void 0:t9.commandPermissions)!==null&&wQ!==void 0?wQ:{};qQ(V,(lQ=F8.enabled)!==null&&lQ!==void 0?lQ:!1),qQ(O,[...(U8=F8.allowlist)!==null&&U8!==void 0?U8:[]]),qQ(P,(P6=F8.recentInvocations)!==null&&P6!==void 0?P6:[]),qQ(N,F8.softRateLimit!==void 0?String(F8.softRateLimit):"");let SX=(N6=D().app.commands)===null||N6===void 0?void 0:N6.commands;if(SX)qQ(E,SX),qQ(w,Object.values(SX).map((B7)=>({id:B7.id,name:B7.name})).sort((B7,f8)=>B7.id.localeCompare(f8.id)));qQ(R,!0)});async function x(){qQ(I,!0);try{await xY.run(async()=>{var wQ,lQ;let U8=(wQ=await D().loadData())!==null&&wQ!==void 0?wQ:{},P6=(lQ=U8.commandPermissions)!==null&&lQ!==void 0?lQ:{},N6=String(c(N)!==null&&c(N)!==void 0?c(N):"").trim(),t9=N6===""?void 0:$40(Number(N6));U8.commandPermissions={...P6,enabled:c(V),allowlist:[...c(O)],softRateLimit:t9},await D().saveData(U8),qQ(N,t9!==void 0?String(t9):"")})}catch(wQ){let lQ=wQ instanceof Error?wQ.message:String(wQ);new ZG.Notice(`Failed to save command permissions: ${lQ}`)}finally{qQ(I,!1)}}function b(){x()}function g(){x()}function l(wQ){let lQ=c(O).filter((U8)=>U8!==wQ);if(lQ.length===c(O).length)return;qQ(O,lQ),x()}function _(wQ){if(c(O).includes(wQ))return;qQ(O,[...c(O),wQ]),x()}function a(wQ){if(c(G).has(wQ))l(wQ);else _(wQ)}function r(wQ){let lQ=dP(wQ,c(E));if(lQ.length===0){new ZG.Notice(`No '${wQ.label}' commands were found in this vault's registry.`);return}let U8=$K0(c(O),lQ),P6=U8.length-c(O).length;if(P6===0){new ZG.Notice(`All '${wQ.label}' commands are already in the allowlist.`);return}qQ(O,U8),x(),new ZG.Notice(`Added ${P6} '${wQ.label}' command${P6===1?"":"s"} to the allowlist.`)}async function f0(wQ){if(wQ.key!=="Enter")return;wQ.preventDefault();let lQ=c(K).find((U8)=>!c(G).has(U8.id));if(!lQ)return;_(lQ.id),qQ(T,""),await aH(),c(y)===null||c(y)===void 0||c(y).focus()}function t(wQ){let lQ=new Date(wQ);if(Number.isNaN(lQ.getTime()))return wQ;return lQ.toLocaleString()}function p0(wQ){let lQ=Z40(wQ),U8=new Blob(["\uFEFF"+lQ],{type:"text/csv;charset=utf-8"}),P6=URL.createObjectURL(U8),N6=document.createElement("a");N6.href=P6,N6.download=F40(),document.body.appendChild(N6),N6.click(),document.body.removeChild(N6),URL.revokeObjectURL(P6)}function u0(wQ){var lQ,U8;return(U8=(lQ=c(E)===null||c(E)===void 0?void 0:c(E)[wQ])===null||lQ===void 0?void 0:lQ.name)!==null&&U8!==void 0?U8:wQ}function d(wQ){var lQ;return Pq(wQ,(lQ=c(E)===null||c(E)===void 0?void 0:c(E)[wQ])===null||lQ===void 0?void 0:lQ.name)}async function n(){let wQ=JT(c(O));try{await navigator.clipboard.writeText(wQ),new ZG.Notice(`Copied ${c(O).length} command id${c(O).length===1?"":"s"} to clipboard.`)}catch(lQ){new ZG.Notice(`Allowlist (copy manually):
${wQ}`)}}function c0(){var wQ;let lQ=(wQ=D().app.commands)===null||wQ===void 0?void 0:wQ.commands;if(!lQ){new ZG.Notice("Could not access the Obsidian command registry.");return}qQ(E,lQ),qQ(w,Object.values(lQ).map((U8)=>({id:U8.id,name:U8.name})).sort((U8,P6)=>U8.id.localeCompare(P6.id))),new ZG.Notice(`Refreshed registry: ${c(w).length} commands found.`)}function WQ(){if(c(H).stale.length===0)return;let wQ=c(H).stale.length;qQ(O,c(H).live),x(),new ZG.Notice(`Removed ${wQ} stale command id${wQ===1?"":"s"} from the allowlist.`)}let R0=dQ("");function l0(){let wQ=XT(c(R0));qQ(O,wQ),x(),qQ(R0,""),new ZG.Notice(`Replaced allowlist with ${wQ.length} command id${wQ.length===1?"":"s"}.`)}YY(()=>c(O),()=>{qQ(G,new Set(c(O)))}),YY(()=>(WT,c(O),c(E)),()=>{qQ(H,WT(c(O),c(E)))}),YY(()=>(c(T),c(w)),()=>{qQ(K,(()=>{let wQ=c(T).trim().toLowerCase();if(!wQ)return[];return c(w).filter((lQ)=>lQ.id.toLowerCase().includes(wQ)||lQ.name.toLowerCase().includes(wQ))})())}),YY(()=>(GT,c(w)),()=>{qQ(z,GT(c(w)))}),YY(()=>(c(z),c(G)),()=>{qQ(q,(()=>{let wQ=new Map;for(let[lQ,U8]of c(z)){let P6=0;for(let N6 of U8)if(c(G).has(N6.id))P6++;wQ.set(lQ,P6)}return wQ})())}),YY(()=>(rv,dP,c(E)),()=>{qQ(F,rv.map((wQ)=>({preset:wQ,availableIds:dP(wQ,c(E))})))}),J3(),vJ();var d0=xe0(),m0=VQ(GQ(d0),4),ZQ=GQ(m0);j9(ZQ),v9(),YQ(m0);var LQ=VQ(m0,2);{var h0=(wQ)=>{var lQ=Se0(),U8=$X(lQ),P6=GQ(U8),N6=VQ(GQ(P6)),t9=GQ(N6);YQ(N6),YQ(P6);var F8=VQ(P6,2);{var SX=(j6)=>{var s8=De0();TQ(j6,s8)},B7=(j6)=>{var s8=Le0();WY(s8,5,()=>(c(H),FQ(()=>c(H).live)),(x6)=>x6,(x6,t6)=>{var M7=Me0();let Z9;var h8=GQ(M7);{var F6=($8)=>{var c6=tv();TQ($8,c6)},L7=sH(()=>(c(t6),FQ(()=>d(c(t6)))));m8(h8,($8)=>{if(c(L7))$8(F6)})}var C6=VQ(h8,2),A9=GQ(C6,!0);YQ(C6);var kQ=VQ(C6,2);YQ(M7),C8(($8,c6)=>{Z9=ZW(M7,1,"chip svelte-1arp3cq",null,Z9,$8),N9(M7,"title",c6),q8(A9,c(t6)),N9(kQ,"aria-label",`Remove ${c(t6)??""}`),N9(kQ,"title",`Remove ${c(t6)??""}`),kQ.disabled=c(I)},[()=>({"chip-destructive":d(c(t6))}),()=>(c(t6),FQ(()=>u0(c(t6))))]),N8("click",kQ,()=>l(c(t6))),TQ(x6,M7)}),YQ(s8),TQ(j6,s8)};m8(F8,(j6)=>{if(c(O),FQ(()=>c(O).length===0))j6(SX);else j6(B7,-1)})}var f8=VQ(F8,2);{var D8=(j6)=>{var s8=Pe0(),x6=GQ(s8),t6=GQ(x6),M7=GQ(t6);YQ(t6);var Z9=VQ(t6,4),h8=GQ(Z9);YQ(Z9),YQ(x6);var F6=VQ(x6,2);WY(F6,5,()=>(c(H),FQ(()=>c(H).stale)),(L7)=>L7,(L7,C6)=>{var A9=Oe0(),kQ=GQ(A9),$8=GQ(kQ,!0);YQ(kQ);var c6=VQ(kQ,2);YQ(A9),C8(()=>{q8($8,c(C6)),N9(c6,"aria-label",`Remove stale ${c(C6)??""}`),N9(c6,"title",`Remove ${c(C6)??""}`),c6.disabled=c(I)}),N8("click",c6,()=>l(c(C6))),TQ(L7,A9)}),YQ(F6),YQ(s8),C8(()=>{q8(M7,`Stale (${(c(H),FQ(()=>c(H).stale.length))??""})`),Z9.disabled=c(I),q8(h8,`Remove all ${(c(H),FQ(()=>c(H).stale.length))??""} stale`)}),N8("click",Z9,WQ),TQ(j6,s8)};m8(f8,(j6)=>{if(c(H),FQ(()=>c(H).stale.length>0))j6(D8)})}YQ(U8);var S6=VQ(U8,2),IQ=VQ(GQ(S6),2);j9(IQ),Bk(IQ,(j6)=>qQ(y,j6),()=>c(y));var rQ=VQ(IQ,2),l8=VQ(GQ(rQ),2);WY(l8,1,()=>c(F),(j6)=>j6.preset.id,(j6,s8)=>{var x6=Ne0(),t6=GQ(x6);YQ(x6),C8(()=>{x6.disabled=(c(I),c(s8),FQ(()=>c(I)||c(s8).availableIds.length===0)),N9(x6,"title",(c(s8),FQ(()=>c(s8).availableIds.length===0?"None of these commands exist in this vault":`${c(s8).preset.description} — adds ${c(s8).availableIds.length} command${c(s8).availableIds.length===1?"":"s"}`))),q8(t6,`+ ${(c(s8),FQ(()=>c(s8).preset.label))??""} (${(c(s8),FQ(()=>c(s8).availableIds.length))??""})`)}),N8("click",x6,()=>r(c(s8).preset)),TQ(j6,x6)}),YQ(rQ);var U6=VQ(rQ,2);{var G8=(j6)=>{var s8=Ce0(),x6=GQ(s8);{var t6=(Z9)=>{var h8=je0();TQ(Z9,h8)},M7=(Z9)=>{var h8=_q(),F6=$X(h8);WY(F6,1,()=>c(K),(L7)=>L7.id,(L7,C6)=>{var A9=ZK0();let kQ;var $8=GQ(A9),c6=GQ($8);j9(c6);var XJ=VQ(c6,2);{var YX=(A7)=>{var JJ=tv();TQ(A7,JJ)},LY=sH(()=>(c(C6),FQ(()=>d(c(C6).id))));m8(XJ,(A7)=>{if(c(LY))A7(YX)})}var sY=VQ(XJ,2),OY=GQ(sY),hW=GQ(OY,!0);YQ(OY);var pG=VQ(OY,2),MH=GQ(pG,!0);YQ(pG),YQ(sY),YQ($8),YQ(A9),C8((A7,JJ)=>{kQ=ZW(A9,1,"cmd-row svelte-1arp3cq",null,kQ,A7),N7(c6,JJ),c6.disabled=c(I),N9(c6,"aria-label",`Toggle ${(c(C6),FQ(()=>c(C6).id))??""}`),q8(hW,(c(C6),FQ(()=>c(C6).id))),q8(MH,(c(C6),FQ(()=>c(C6).name)))},[()=>({"allowed-row":c(G).has(c(C6).id),"destructive-row":d(c(C6).id)}),()=>(c(G),c(C6),FQ(()=>c(G).has(c(C6).id)))]),N8("change",c6,()=>a(c(C6).id)),TQ(L7,A9)}),TQ(Z9,h8)};m8(x6,(Z9)=>{if(c(K),FQ(()=>c(K).length===0))Z9(t6);else Z9(M7,-1)})}YQ(s8),TQ(j6,s8)},e9=sH(()=>(c(T),FQ(()=>c(T).trim().length>0))),TX=(j6)=>{var s8=Ee0(),x6=GQ(s8),t6=GQ(x6);YQ(x6);var M7=VQ(x6,2),Z9=GQ(M7);YQ(M7);var h8=VQ(M7,2);{var F6=(C6)=>{var A9=Ie0();TQ(C6,A9)},L7=(C6)=>{var A9=we0();WY(A9,5,()=>(c(z),FQ(()=>[...c(z)])),([kQ,$8])=>kQ,(kQ,$8)=>{var c6=sH(()=>KT(c($8),2));let XJ=()=>c(c6)[0],YX=()=>c(c6)[1];var LY=Re0(),sY=GQ(LY),OY=GQ(sY),hW=GQ(OY,!0);YQ(OY);var pG=VQ(OY,2),MH=GQ(pG);YQ(pG),YQ(sY);var A7=VQ(sY,2);WY(A7,5,YX,(JJ)=>JJ.id,(JJ,E7)=>{var u5=ZK0();let rY;var PJ=GQ(u5),tY=GQ(PJ);j9(tY);var ZB=VQ(tY,2);{var cV=(_W)=>{var NJ=tv();TQ(_W,NJ)},YJ=sH(()=>(c(E7),FQ(()=>d(c(E7).id))));m8(ZB,(_W)=>{if(c(YJ))_W(cV)})}var PY=VQ(ZB,2),lG=GQ(PY),m7=GQ(lG,!0);YQ(lG);var kX=VQ(lG,2),LH=GQ(kX,!0);YQ(kX),YQ(PY),YQ(PJ),YQ(u5),C8((_W,NJ)=>{rY=ZW(u5,1,"cmd-row svelte-1arp3cq",null,rY,_W),N7(tY,NJ),tY.disabled=c(I),N9(tY,"aria-label",`Toggle ${(c(E7),FQ(()=>c(E7).id))??""}`),q8(m7,(c(E7),FQ(()=>c(E7).id))),q8(LH,(c(E7),FQ(()=>c(E7).name)))},[()=>({"allowed-row":c(G).has(c(E7).id),"destructive-row":d(c(E7).id)}),()=>(c(G),c(E7),FQ(()=>c(G).has(c(E7).id)))]),N8("change",tY,()=>a(c(E7).id)),TQ(JJ,u5)}),YQ(A7),YQ(LY),C8((JJ)=>{q8(hW,XJ()),q8(MH,`(${JJ??""} / ${(YX(),FQ(()=>YX().length))??""})`)},[()=>(c(q),XJ(),FQ(()=>c(q).get(XJ())??0))]),TQ(kQ,LY)}),YQ(A9),TQ(C6,A9)};m8(h8,(C6)=>{if(c(w),FQ(()=>c(w).length===0))C6(F6);else C6(L7,-1)})}YQ(s8),C8(()=>{q8(t6,`Browse all ${(c(w),FQ(()=>c(w).length))??""} commands by category`),Z9.disabled=c(I)}),N8("click",Z9,c0),TQ(j6,s8)};m8(U6,(j6)=>{if(c(e9))j6(G8);else j6(TX,-1)})}YQ(S6),C8(()=>{q8(t9,`(${(c(H),FQ(()=>c(H).live.length))??""}${(c(H),FQ(()=>c(H).stale.length>0?`, ${c(H).stale.length} stale`:""))??""})`),IQ.disabled=c(I)}),pq(IQ,()=>c(T),(j6)=>qQ(T,j6)),N8("keydown",IQ,f0),TQ(wQ,lQ)};m8(LQ,(wQ)=>{if(c(R))wQ(h0)})}var pQ=VQ(LQ,2),iQ=VQ(GQ(pQ),2),mQ=GQ(iQ),AQ=GQ(mQ),MQ=VQ(GQ(AQ)),DQ=GQ(MQ);YQ(MQ),YQ(AQ);var bQ=VQ(AQ,2);j9(bQ),YQ(mQ);var j8=VQ(mQ,2),tQ=VQ(GQ(j8),2),K8=GQ(tQ);YQ(tQ);var k8=VQ(tQ,2);_T(k8);var d6=VQ(k8,2),r9=GQ(d6);YQ(d6),YQ(j8),YQ(iQ),YQ(pQ);var H7=VQ(pQ,2),LJ=GQ(H7),OJ=GQ(LJ);YQ(LJ);var w7=VQ(LJ,2);{var QJ=(wQ)=>{var lQ=Te0();TQ(wQ,lQ)},e8=(wQ)=>{var lQ=ve0(),U8=$X(lQ),P6=GQ(U8);YQ(U8);var N6=VQ(U8,2);WY(N6,7,()=>(c(P),FQ(()=>[...c(P)].reverse())),(t9,F8)=>t9.timestamp+":"+F8,(t9,F8)=>{var SX=ye0(),B7=GQ(SX),f8=GQ(B7),D8=GQ(f8,!0);YQ(f8);var S6=VQ(f8,2),IQ=GQ(S6,!0);YQ(S6);var rQ=VQ(S6,2),l8=GQ(rQ,!0);YQ(rQ),YQ(B7);var U6=VQ(B7,2);{var G8=(e9)=>{var TX=ke0(),j6=GQ(TX,!0);YQ(TX),C8(()=>q8(j6,(c(F8),FQ(()=>c(F8).reason)))),TQ(e9,TX)};m8(U6,(e9)=>{if(c(F8),FQ(()=>c(F8).reason))e9(G8)})}YQ(SX),C8((e9)=>{ZW(SX,1,`audit-entry audit-${(c(F8),FQ(()=>c(F8).decision))??""}`,"svelte-1arp3cq"),q8(D8,(c(F8),FQ(()=>c(F8).commandId))),q8(IQ,(c(F8),FQ(()=>c(F8).decision))),q8(l8,e9)},[()=>(c(F8),FQ(()=>t(c(F8).timestamp)))]),TQ(t9,SX)}),YQ(N6),N8("click",P6,()=>p0(c(P))),TQ(wQ,lQ)};m8(w7,(wQ)=>{if(c(P),FQ(()=>c(P).length===0))wQ(QJ);else wQ(e8,-1)})}YQ(H7),YQ(d0),C8((wQ,lQ)=>{ZQ.disabled=c(I),q8(DQ,`Commands per minute before the modal shows a "you're
invoking a lot of commands" warning. Leave blank to use
the default (${fH??""}). Range: ${tE??""}${eE??""}.
This is informational only — the MCP server's hard limit
of 100/min is compiled into the binary and is not
configurable from here.`),N9(bQ,"min",tE),N9(bQ,"max",eE),N9(bQ,"placeholder",wQ),bQ.disabled=c(I),K8.disabled=c(I),k8.disabled=c(I),r9.disabled=lQ,q8(OJ,`Recent invocations (${(c(P),FQ(()=>c(P).length))??""} / ${rE??""})`)},[()=>(yJ(fH),FQ(()=>String(fH))),()=>(c(I),c(R0),FQ(()=>c(I)||c(R0).trim().length===0))]),Wk(ZQ,()=>c(V),(wQ)=>qQ(V,wQ)),N8("change",ZQ,b),pq(bQ,()=>c(N),(wQ)=>qQ(N,wQ)),N8("change",bQ,g),N8("click",K8,n),pq(k8,()=>c(R0),(wQ)=>qQ(R0,wQ)),N8("click",r9,l0),TQ(Q,d0),i7()}var FK0=e({provider:'"native"|"smart-connections"|"auto"|"embedding-gemma"|"multilingual-e5-base"',indexingMode:'"live"|"low-power"',unloadModelWhenIdle:"boolean"}),iP={provider:"auto",indexingMode:"live",unloadModelWhenIdle:!1};class MK0{opts;constructor(Q){this.opts=Q}isReady(){return!0}async search(Q,J){let G=await this.opts.embedder.embed(Q),H=J.limit??10,K=[];for await(let z of this.opts.store.scan()){if(!ge0(z.filePath,J))continue;let q=he0(G,z.vector),F=K[K.length-1];if(K.length===H&&F&&q<=F.score)continue;let D=0,V=K.length;while(D<V){let O=D+V>>1,P=K[O];if(P&&P.score>=q)D=O+1;else V=O}if(K.splice(D,0,{record:z,score:q}),K.length>H)K.pop()}return Promise.all(K.map(async({record:z,score:q})=>({filePath:z.filePath,heading:z.heading,excerpt:await this.makeExcerpt(z),score:q})))}async makeExcerpt(Q){let J="";if(this.opts.excerptResolver)try{J=await this.opts.excerptResolver(Q.filePath,Q.offset,500)}catch{J=""}return _e0(J)}}function ge0(Q,J){if(J.folders&&J.folders.length>0){if(!J.folders.some((H)=>DK0(Q,H)))return!1}if(J.excludeFolders&&J.excludeFolders.length>0){if(J.excludeFolders.some((H)=>DK0(Q,H)))return!1}return!0}function DK0(Q,J){let G=J.endsWith("/")?J:J+"/";return Q===J||Q.startsWith(G)}function he0(Q,J){if(Q.length!==J.length)throw Error(`dot: dim mismatch ${Q.length} vs ${J.length}`);let G=0;for(let H=0;H<Q.length;H++)G+=Q[H]*J[H];return G}function _e0(Q){if(Q.length===0)return"(no preview)";if(Q.length<=500)return Q;let J=Q.lastIndexOf(" ",500);return(J>0?Q.slice(0,J):Q.slice(0,500))+"..."}function ev(Q){return new MK0(Q)}function fe0(Q){let J={};if(Q.folders&&Q.folders.length>0)J.key_starts_with_any=[...Q.folders];if(Q.excludeFolders&&Q.excludeFolders.length>0)J.exclude_key_starts_with_any=[...Q.excludeFolders];if(Q.limit!==void 0)J.limit=Q.limit;return J}function LK0(Q){return Q.smartSearch}class OK0 extends Error{constructor(){super("Smart Connections plugin is not installed or not yet loaded with an indexed vault. Install Smart Connections from Obsidian community plugins, let it index, then retry.");this.name="SmartConnectionsUnavailableError"}}class PK0{plugin;constructor(Q){this.plugin=Q}isReady(){return typeof LK0(this.plugin)?.search==="function"}async search(Q,J){let G=LK0(this.plugin);if(!G)throw new OK0;let H=fe0(J),K=await G.search(Q,H);return Promise.all(K.map(async(z)=>{let q=z.item.breadcrumbs??null,F=await z.item.read();return{filePath:z.item.path,heading:q,excerpt:me0(F),score:z.score}}))}}function me0(Q){if(Q.length===0)return"(no preview)";if(Q.length<=500)return Q;let J=Q.lastIndexOf(" ",500);return(J>0?Q.slice(0,J):Q.slice(0,500))+"..."}function NK0(Q){return new PK0(Q)}var jK0=["native-minilm-l6-v2","embedding-gemma-300m","multilingual-e5-base"];function Qx(Q){return typeof Q.smartSearch?.search==="function"}function ue0(Q){return{embed:async(J)=>{return(await Q.embed([J],"query"))[0]},embedBatch:async(J)=>Q.embed(J,"query"),unload:async()=>{},isLoaded:()=>!0}}function CK0(Q){let J=()=>ev({embedder:Q.embedder,store:Q.store,excerptResolver:Q.excerptResolver}),G=()=>NK0(Q.plugin),H=(K,z)=>ev({embedder:ue0(K),store:z,excerptResolver:Q.excerptResolver});return(K)=>{switch(K.provider){case"native":return J();case"smart-connections":return G();case"auto":return Qx(Q.plugin)?G():J();case"embedding-gemma":{let z=Q.embeddingProviders?.["embedding-gemma-300m"];if(!z||!Q.registry)return J();return H(z,Q.registry.storeFor("embedding-gemma-300m",768))}case"multilingual-e5-base":{let z=Q.embeddingProviders?.["multilingual-e5-base"];if(!z||!Q.registry)return J();return H(z,Q.registry.storeFor("multilingual-e5-base",768))}}}}var q5=require("obsidian");var pe0=oQ('<div class="file svelte-1wkmwym"> </div>'),le0=oQ('<div class="model-download svelte-1wkmwym" role="status"><div class="header svelte-1wkmwym"><span>Downloading embedding model…</span> <span class="pct svelte-1wkmwym"> </span></div> <div class="bar svelte-1wkmwym"><div class="fill svelte-1wkmwym"></div></div> <!></div>'),de0=oQ('<div class="model-download error svelte-1wkmwym" role="alert"><div class="header svelte-1wkmwym"><span>Model download failed</span> <button type="button" class="svelte-1wkmwym">Retry</button></div> <div class="message svelte-1wkmwym"> </div></div>'),ce0={hash:"svelte-1wkmwym",code:".model-download.svelte-1wkmwym {margin:0.75em 0;padding:0.6em 0.8em;border:1px solid var(--background-modifier-border);border-radius:4px;background:var(--background-secondary);font-size:0.9em;}.model-download.error.svelte-1wkmwym {border-color:var(--text-error);}.header.svelte-1wkmwym {display:flex;align-items:center;justify-content:space-between;margin-bottom:0.4em;}.pct.svelte-1wkmwym {font-variant-numeric:tabular-nums;color:var(--text-muted);}.bar.svelte-1wkmwym {width:100%;height:6px;background:var(--background-modifier-border);border-radius:3px;overflow:hidden;}.fill.svelte-1wkmwym {height:100%;background:var(--interactive-accent);transition:width 200ms linear;}.file.svelte-1wkmwym {margin-top:0.4em;color:var(--text-muted);font-family:var(--font-monospace);font-size:0.85em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.message.svelte-1wkmwym {color:var(--text-error);font-size:0.85em;}button.svelte-1wkmwym {font-size:0.85em;}"};function Xx(Q,J){c7(J,!1),bX(Q,ce0);let G=gX(J,"plugin",8),H=dQ({kind:"idle"}),K=null;SY(()=>{var O;let P=(O=G().semanticSearchState)===null||O===void 0?void 0:O.downloader;if(!P)return;K=P.subscribe((N)=>{qQ(H,N)})}),A30(()=>{K===null||K===void 0||K()});function z(){var O,P;(P=(O=G().semanticSearchState)===null||O===void 0?void 0:O.downloader)===null||P===void 0||P.retry()}vJ();var q=_q(),F=$X(q);{var D=(O)=>{var P=le0(),N=GQ(P),I=VQ(GQ(N),2),R=GQ(I);YQ(I),YQ(N);var w=VQ(N,2),E=GQ(w);YQ(w);var T=VQ(w,2);{var y=(x)=>{var b=pe0(),g=GQ(b,!0);YQ(b),C8(()=>{N9(b,"title",(c(H),FQ(()=>c(H).file))),q8(g,(c(H),FQ(()=>c(H).file)))}),TQ(x,b)};m8(T,(x)=>{if(c(H),FQ(()=>c(H).file))x(y)})}YQ(P),C8((x,b)=>{q8(R,`${x??""}%`),QP(E,`width: ${b??""}%`)},[()=>(c(H),FQ(()=>Math.round(c(H).progress))),()=>(c(H),FQ(()=>Math.max(2,Math.min(100,c(H).progress))))]),TQ(O,P)},V=(O)=>{var P=de0(),N=GQ(P),I=VQ(GQ(N),2);YQ(N);var R=VQ(N,2),w=GQ(R,!0);YQ(R),YQ(P),C8(()=>q8(w,(c(H),FQ(()=>c(H).message)))),N8("click",I,z),TQ(O,P)};m8(F,(O)=>{if(c(H),FQ(()=>c(H).kind==="downloading"))O(D);else if(c(H),FQ(()=>c(H).kind==="error"))O(V,1)})}TQ(Q,q),i7()}var ie0=oQ('<div class="banner info svelte-ndgp4c"> <button type="button" class="banner-action svelte-ndgp4c">Switch</button></div>'),oe0=oQ('<div class="banner warn svelte-ndgp4c"> <button type="button" class="banner-action svelte-ndgp4c">Rebuild now</button></div>'),ne0=oQ(`<fieldset class="svelte-ndgp4c"><legend class="svelte-ndgp4c">Indexing mode (native only)</legend> <label class="svelte-ndgp4c"><input type="radio" name="ss-mode" value="live"/> Live <span class="hint svelte-ndgp4c">responsive, recommended — re-embed on file change</span></label> <label class="svelte-ndgp4c"><input type="radio" name="ss-mode" value="low-power"/> Low-power <span class="hint svelte-ndgp4c">re-index every 5 min, saves battery</span></label></fieldset> <label class="checkbox svelte-ndgp4c"><input type="checkbox"/> Unload model when idle (60s) <span class="hint svelte-ndgp4c">frees ~150 MB of RAM after inactivity, next search reloads the model
(~1s); takes effect at the next plugin reload</span></label>`,1),ae0=oQ('<div class="error svelte-ndgp4c"> </div>'),se0=oQ(`<div class="semantic-search-settings svelte-ndgp4c"><h3>Semantic search</h3> <p class="description svelte-ndgp4c">Search notes by meaning, not just by keyword. Pick the embedding
backend that matches your setup.</p> <!> <!> <fieldset class="svelte-ndgp4c"><legend class="svelte-ndgp4c">Provider</legend> <label class="svelte-ndgp4c"><input type="radio" name="ss-provider" value="auto"/> Auto <span class="hint svelte-ndgp4c">use Smart Connections if installed, otherwise native</span></label> <label class="svelte-ndgp4c"><input type="radio" name="ss-provider" value="native"/> Native <span class="hint svelte-ndgp4c">Transformers.js + MiniLM-L6-v2, no external plugin required</span></label> <label class="svelte-ndgp4c"><input type="radio" name="ss-provider" value="smart-connections"/> Smart Connections plugin <span class="hint svelte-ndgp4c">requires the Smart Connections community plugin</span></label> <label class="svelte-ndgp4c"><input type="radio" name="ss-provider" value="embedding-gemma"/> EmbeddingGemma 300M <span class="hint svelte-ndgp4c">multilingual, 768d, 2K context (~190 MB download)</span></label> <label class="svelte-ndgp4c"><input type="radio" name="ss-provider" value="multilingual-e5-base"/> Multilingual E5 base <span class="hint svelte-ndgp4c">multilingual, 768d, 512 context (~100 MB download)</span></label></fieldset> <!> <!> <div class="status svelte-ndgp4c"><span> </span> <button type="button"> </button></div> <!></div>`),re0={hash:"svelte-ndgp4c",code:`.semantic-search-settings.svelte-ndgp4c {margin-top:2em;}.description.svelte-ndgp4c {color:var(--text-muted);font-size:0.9em;margin-bottom:0.5em;}fieldset.svelte-ndgp4c {border:1px solid var(--background-modifier-border);border-radius:4px;padding:0.5em 1em;margin:0 0 0.75em 0;}legend.svelte-ndgp4c {font-weight:600;font-size:0.9em;padding:0 0.4em;}fieldset.svelte-ndgp4c label:where(.svelte-ndgp4c),
label.checkbox.svelte-ndgp4c {display:block;margin:0.25em 0;cursor:pointer;}.hint.svelte-ndgp4c {color:var(--text-muted);font-size:0.85em;margin-left:0.4em;}.banner.svelte-ndgp4c {border-radius:4px;font-size:0.9em;margin-bottom:0.75em;padding:0.5em 0.75em;}.banner.info.svelte-ndgp4c {background:var(--background-modifier-info);color:var(--text-normal);}.banner.warn.svelte-ndgp4c {background:var(--background-modifier-error);color:var(--text-normal);}.banner-action.svelte-ndgp4c {margin-left:0.5em;}.status.svelte-ndgp4c {display:flex;align-items:center;justify-content:space-between;margin-top:1em;padding-top:0.75em;border-top:1px solid var(--background-modifier-border);font-size:0.9em;}.error.svelte-ndgp4c {color:var(--text-error);font-size:0.9em;margin-top:0.5em;}`};function oP(Q,J){c7(J,!1),bX(Q,re0);let G=gX(J,"plugin",8),H=dQ({...iP}),K=dQ(!1),z=dQ(!1),q=dQ(0),F=dQ(null),D=dQ(null),V=dQ(null),O={"embedding-gemma-300m":{label:"EmbeddingGemma 300M",size:"~190 MB",seconds:"510 min"},"multilingual-e5-base":{label:"Multilingual E5 base",size:"~100 MB",seconds:"35 min"}};SY(()=>{var AQ,MQ;let DQ=G().semanticSearchState;if(DQ)qQ(H,{...DQ.settings}),qQ(D,(AQ=DQ.pendingProvider)!==null&&AQ!==void 0?AQ:null),qQ(V,(MQ=DQ.autoSuggestProvider)!==null&&MQ!==void 0?MQ:null);P()});function P(){var AQ,MQ,DQ,bQ,j8,tQ,K8;let k8=G().semanticSearchState,d6=(AQ=k8===null||k8===void 0?void 0:k8.settings)===null||AQ===void 0?void 0:AQ.provider,r9=k8===null||k8===void 0?void 0:k8.registry,H7=(MQ=k8===null||k8===void 0?void 0:k8.probedCounts)!==null&&MQ!==void 0?MQ:{};if(d6==="embedding-gemma"&&r9)qQ(q,r9.storeFor("embedding-gemma-300m",768).size()||H7["embedding-gemma-300m"]||0);else if(d6==="multilingual-e5-base"&&r9)qQ(q,r9.storeFor("multilingual-e5-base",768).size()||H7["multilingual-e5-base"]||0);else qQ(q,((j8=(bQ=(DQ=k8===null||k8===void 0?void 0:k8.store)===null||DQ===void 0?void 0:DQ.size)===null||bQ===void 0?void 0:bQ.call(DQ))!==null&&j8!==void 0?j8:0)||H7["native-minilm-l6-v2"]||0);qQ(D,(tQ=k8===null||k8===void 0?void 0:k8.pendingProvider)!==null&&tQ!==void 0?tQ:null),qQ(V,(K8=k8===null||k8===void 0?void 0:k8.autoSuggestProvider)!==null&&K8!==void 0?K8:null)}async function N(AQ){var MQ;let DQ=G().semanticSearchState;if(!DQ){qQ(F,"Plugin not fully initialized — reload Obsidian.");return}qQ(K,!0),qQ(F,null);try{await IK0(G(),DQ,AQ),qQ(H,AQ),qQ(D,(MQ=DQ.pendingProvider)!==null&&MQ!==void 0?MQ:null)}catch(bQ){qQ(F,bQ instanceof Error?bQ.message:String(bQ))}finally{qQ(K,!1)}}async function I(AQ){await N({...c(H),provider:AQ})}async function R(AQ){await N({...c(H),indexingMode:AQ})}async function w(AQ){await N({...c(H),unloadModelWhenIdle:AQ})}async function E(){let AQ=G().semanticSearchState;if(!AQ||!c(D))return;if(AQ.startRebuildFor)AQ.startRebuildFor(c(D));else new q5.Notice("Rebuild not available yet — reload Obsidian.")}async function T(){let AQ=G().semanticSearchState;if(!AQ){new q5.Notice("Semantic index not available yet — reload Obsidian.");return}let MQ=c(H).provider==="embedding-gemma"?"embedding-gemma-300m":c(H).provider==="multilingual-e5-base"?"multilingual-e5-base":null;if(MQ){if(!AQ.startRebuildFor){new q5.Notice("Rebuild not available yet — reload Obsidian.");return}AQ.startRebuildFor(MQ),new q5.Notice("Rebuilding index in background…");return}if(c(H).provider==="smart-connections"){new q5.Notice("Smart Connections manages its own index.");return}let DQ=AQ.indexer;if(!DQ){new q5.Notice("Semantic index not available yet — reload Obsidian.");return}qQ(z,!0);try{await DQ.rebuildAll(),new q5.Notice("Semantic index rebuilt."),P()}catch(bQ){let j8=bQ instanceof Error?bQ.message:String(bQ);new q5.Notice(`Rebuild failed: ${j8}`)}finally{qQ(z,!1)}}vJ();var y=se0(),x=VQ(GQ(y),4);{var b=(AQ)=>{let MQ=VW(()=>(c(V),FQ(()=>O[c(V)])));var DQ=ie0(),bQ=GQ(DQ),j8=VQ(bQ);YQ(DQ),C8(()=>q8(bQ,`Your vault appears to contain non-English content.
${(yJ(c(MQ)),c(V),FQ(()=>c(MQ)?.label??c(V)))??""} may improve search quality. `)),N8("click",j8,()=>I(c(V)==="embedding-gemma-300m"?"embedding-gemma":"multilingual-e5-base")),TQ(AQ,DQ)};m8(x,(AQ)=>{if(c(V))AQ(b)})}var g=VQ(x,2);{var l=(AQ)=>{let MQ=VW(()=>(c(D),FQ(()=>O[c(D)])));var DQ=oe0(),bQ=GQ(DQ),j8=VQ(bQ);YQ(DQ),C8(()=>q8(bQ,`${(yJ(c(MQ)),c(D),FQ(()=>c(MQ)?.label??c(D)))??""} index is being built (${(yJ(c(MQ)),FQ(()=>c(MQ)?.size??""))??""}
download, ~${(yJ(c(MQ)),FQ(()=>c(MQ)?.seconds??""))??""}). `)),N8("click",j8,E),TQ(AQ,DQ)};m8(g,(AQ)=>{if(c(D))AQ(l)})}var _=VQ(g,2),a=VQ(GQ(_),2),r=GQ(a);j9(r),v9(2),YQ(a);var f0=VQ(a,2),t=GQ(f0);j9(t),v9(2),YQ(f0);var p0=VQ(f0,2),u0=GQ(p0);j9(u0),v9(2),YQ(p0);var d=VQ(p0,2),n=GQ(d);j9(n),v9(2),YQ(d);var c0=VQ(d,2),WQ=GQ(c0);j9(WQ),v9(2),YQ(c0),YQ(_);var R0=VQ(_,2);{var l0=(AQ)=>{var MQ=ne0(),DQ=$X(MQ),bQ=VQ(GQ(DQ),2),j8=GQ(bQ);j9(j8),v9(2),YQ(bQ);var tQ=VQ(bQ,2),K8=GQ(tQ);j9(K8),v9(2),YQ(tQ),YQ(DQ);var k8=VQ(DQ,2),d6=GQ(k8);j9(d6),v9(2),YQ(k8),C8(()=>{DQ.disabled=c(K),N7(j8,(c(H),FQ(()=>c(H).indexingMode==="live"))),N7(K8,(c(H),FQ(()=>c(H).indexingMode==="low-power"))),N7(d6,(c(H),FQ(()=>c(H).unloadModelWhenIdle))),d6.disabled=c(K)}),N8("change",j8,()=>R("live")),N8("change",K8,()=>R("low-power")),N8("change",d6,(r9)=>w(r9.target.checked)),TQ(AQ,MQ)};m8(R0,(AQ)=>{if(c(H),FQ(()=>c(H).provider!=="smart-connections"))AQ(l0)})}var d0=VQ(R0,2);Xx(d0,{get plugin(){return G()}});var m0=VQ(d0,2),ZQ=GQ(m0),LQ=GQ(ZQ);YQ(ZQ);var h0=VQ(ZQ,2),pQ=GQ(h0,!0);YQ(h0),YQ(m0);var iQ=VQ(m0,2);{var mQ=(AQ)=>{var MQ=ae0(),DQ=GQ(MQ,!0);YQ(MQ),C8(()=>q8(DQ,c(F))),TQ(AQ,MQ)};m8(iQ,(AQ)=>{if(c(F))AQ(mQ)})}YQ(y),C8((AQ)=>{_.disabled=c(K),N7(r,(c(H),FQ(()=>c(H).provider==="auto"))),N7(t,(c(H),FQ(()=>c(H).provider==="native"))),N7(u0,(c(H),FQ(()=>c(H).provider==="smart-connections"))),N7(n,(c(H),FQ(()=>c(H).provider==="embedding-gemma"))),N7(WQ,(c(H),FQ(()=>c(H).provider==="multilingual-e5-base"))),q8(LQ,`${AQ??""} chunks indexed`),h0.disabled=c(z)||c(K),q8(pQ,c(z)?"Rebuilding…":"Rebuild index from scratch")},[()=>(c(q),FQ(()=>c(q).toLocaleString()))]),N8("change",r,()=>I("auto")),N8("change",t,()=>I("native")),N8("change",u0,()=>I("smart-connections")),N8("change",n,()=>I("embedding-gemma")),N8("change",WQ,()=>I("multilingual-e5-base")),N8("click",h0,T),TQ(Q,y),i7()}var RK0={kind:"idle"};class wK0{opts;state=RK0;subscribers=new Set;inFlight=null;constructor(Q){this.opts=Q}getState(){return this.state}subscribe(Q){return this.subscribers.add(Q),Q(this.state),()=>{this.subscribers.delete(Q)}}retry(){if(this.state.kind==="downloading")return;this.setState(RK0)}factory=(Q)=>{if(this.inFlight)return this.inFlight;this.setState({kind:"downloading",progress:0});let J=(async()=>{try{let G=await this.opts.innerFactory(Q,(H)=>this.onProgress(H),this.opts.dtype!==void 0?{dtype:this.opts.dtype}:void 0);return this.setState({kind:"ready"}),G}catch(G){let H=G instanceof Error?G.message:String(G);throw this.setState({kind:"error",message:H}),G}finally{this.inFlight=null}})();return this.inFlight=J,J};onProgress(Q){if(Q.status==="progress"&&typeof Q.progress==="number")this.setState({kind:"downloading",progress:te0(Q.progress,0,100),file:Q.file})}setState(Q){this.state=Q;for(let J of this.subscribers)J(Q)}}function te0(Q,J,G){return Math.max(J,Math.min(G,Q))}function VU(Q){return new wK0(Q)}async function ee0(Q,J){return new n9(Q,J).loadSlice("semanticSearch",{schema:FK0,defaults:iP})}class EK0{async search(){throw Error("Semantic search provider not configured. Open Settings → MCP Connector → Semantic Search to choose a provider.")}isReady(){return!1}}async function SK0(Q,J={}){try{let G=xY,H=await ee0(Q,G),K,z=null;if(J.factoryDeps)z=CK0(J.factoryDeps),K=z(H);else K=new EK0;return{success:!0,state:{provider:K,settings:H,settingsMutex:G,chooser:z,downloader:null,indexer:null,store:J.factoryDeps?.store??null,registry:null,pendingProvider:null,autoSuggestProvider:null,startIndexerIfNeeded:void 0,teardown:async()=>{}}}}catch(G){return{success:!1,error:G instanceof Error?G.message:String(G)}}}async function TK0(Q){await Q.teardown()}var Q0Q={"embedding-gemma":"embedding-gemma-300m","multilingual-e5-base":"multilingual-e5-base"};async function IK0(Q,J,G){await new n9(Q,J.settingsMutex).updateSlice("semanticSearch",()=>G),J.settings=G;let H=Q0Q[G.provider];if(H&&J.registry&&!J.registry.isReady(H)){J.pendingProvider=H;return}if(J.pendingProvider=null,J.chooser)J.provider=J.chooser(G)}var Yx=require("obsidian");var kK0=3,Jx=["tool_catalog","activate_tool","activate_tools"],U5=[...Jx],qU=["get_server_info","get_active_file","update_active_file","append_to_active_file","get_vault_file","list_vault_files","create_vault_file","search_vault","search_vault_simple","list_tags","get_note_property","set_note_property","get_or_create_daily_note"];var X0Q={profile:"all",counters:{},promoted:[]};function tK(Q){let J=Q&&typeof Q==="object"?Q:void 0;return{...X0Q,...J??{},counters:J?.counters&&typeof J.counters==="object"?J.counters:{},promoted:Array.isArray(J?.promoted)?J.promoted:[]}}var eK="toolLoading";class bY{async loadState(Q){return tK(await new n9(Q).readSlice(eK))}getActiveToolNames(Q,J){if(J.profile==="all")return new Set([...U5,...Q]);let G=new Set(Jx);for(let H of qU)G.add(H);for(let H of J.promoted)G.add(H);return G}async recordCall(Q,J){await new n9(J).updateSlice(eK,(G)=>{let H=tK(G);if(H.counters[Q]=(H.counters[Q]??0)+1,H.profile==="adaptive"&&H.counters[Q]>=kK0&&!H.promoted.includes(Q)&&!U5.includes(Q))H.promoted=[...H.promoted,Q];return H})}async activateTool(Q,J,G){if(!J.includes(Q))return"not_found";let H="activated";return await new n9(G).updateSlice(eK,(K)=>{let z=tK(K);if(z.promoted.includes(Q))return H="already_active",K;return z.promoted=[...z.promoted,Q],z}),H}async activateTools(Q,J,G){let H=new Set(J),K={},z=[...new Set(Q)];return await new n9(G).updateSlice(eK,(q)=>{let F=tK(q),D=new Set(F.promoted),V=[];for(let O of z)if(!H.has(O))K[O]="not_found";else if(D.has(O))K[O]="already_active";else K[O]="activated",D.add(O),V.push(O);if(V.length===0)return q;return F.promoted=[...F.promoted,...V],F}),K}async deactivateTool(Q,J){await new n9(J).updateSlice(eK,(G)=>{let H=tK(G);return H.promoted=H.promoted.filter((K)=>K!==Q),H})}async resetAll(Q){await new n9(Q).updateSlice(eK,(J)=>{let G=tK(J);return G.counters={},G.promoted=[],G})}}var J0Q=oQ(`<p class="muted empty-hint svelte-1bx72mz">Connect an MCP client once so the tool list is available, then
reopen settings to add tools here.</p>`),Y0Q=oQ("<option> </option>"),G0Q=oQ('<div class="add-row svelte-1bx72mz"><select aria-label="Tool to promote" class="svelte-1bx72mz"><option disabled="" selected="">Add a tool…</option><!></select> <button type="button" aria-label="Add selected tool to promoted">Add</button></div>'),W0Q=oQ(`<p class="muted empty-hint svelte-1bx72mz">No promoted tools yet. Use a non-core tool 3 times in Adaptive mode
to auto-promote it, or call <code>activate_tool</code> from chat.</p>`),H0Q=oQ('<li class="svelte-1bx72mz"><code class="svelte-1bx72mz"> </code> <button type="button">Remove</button></li>'),B0Q=oQ('<ul class="promoted-list svelte-1bx72mz"></ul>'),A0Q=oQ('<div class="promoted-section svelte-1bx72mz"><p class="section-label svelte-1bx72mz">Promoted tools <span class="muted svelte-1bx72mz">— added here, via <code>activate_tool</code> </span></p> <!> <!> <button type="button" class="reset-btn svelte-1bx72mz" aria-label="Reset adaptive tool data">Reset adaptive data</button></div>'),K0Q=oQ('<div class="profile-group svelte-1bx72mz"><label class="radio-row svelte-1bx72mz"><input type="radio" name="tool-loading-profile" value="all"/> <span>All tools <span class="muted svelte-1bx72mz">(default — loads every tool)</span></span></label> <label class="radio-row svelte-1bx72mz"><input type="radio" name="tool-loading-profile" value="core"/> <span>Core set <span class="muted svelte-1bx72mz">(~13 essential tools)</span></span></label> <label class="radio-row svelte-1bx72mz"><input type="radio" name="tool-loading-profile" value="adaptive"/> <span>Adaptive <span class="muted svelte-1bx72mz">(core + promoted tools)</span></span></label></div> <!>',1),z0Q=oQ(`<div class="adaptive-tool-loading-settings svelte-1bx72mz"><h3>Tool Loading</h3> <p class="description svelte-1bx72mz">Control which MCP tools are loaded at connect time. "All tools" (default)
loads every tool. "Core set" loads ~13 essential tools plus any you
promote below. "Adaptive" is the core set plus your promotions, and also
auto-promotes tools you use often.</p> <!> <p class="footer-hint muted svelte-1bx72mz">Profile changes take effect on the next MCP client connection.</p></div>`),V0Q={hash:"svelte-1bx72mz",code:".adaptive-tool-loading-settings.svelte-1bx72mz {margin-top:2em;}.description.svelte-1bx72mz {color:var(--text-muted);font-size:0.9em;margin:0.5em 0 0.8em;}.profile-group.svelte-1bx72mz {display:flex;flex-direction:column;gap:0.4em;margin-bottom:1em;}.radio-row.svelte-1bx72mz {display:flex;align-items:center;gap:0.5em;cursor:pointer;}.muted.svelte-1bx72mz {color:var(--text-muted);font-size:0.9em;}.section-label.svelte-1bx72mz {font-weight:500;margin:0 0 0.5em;}.promoted-section.svelte-1bx72mz {padding:0.6em 0.8em;background:var(--background-secondary);border-radius:4px;margin-bottom:0.8em;}.add-row.svelte-1bx72mz {display:flex;gap:0.5em;align-items:center;margin-bottom:0.6em;}.add-row.svelte-1bx72mz select:where(.svelte-1bx72mz) {flex:1;min-width:0;}.promoted-list.svelte-1bx72mz {list-style:none;padding:0;margin:0 0 0.6em;display:flex;flex-direction:column;gap:0.3em;}.promoted-list.svelte-1bx72mz li:where(.svelte-1bx72mz) {display:flex;align-items:center;gap:0.6em;}.promoted-list.svelte-1bx72mz code:where(.svelte-1bx72mz) {font-family:var(--font-monospace);font-size:0.9em;flex:1;}.empty-hint.svelte-1bx72mz {font-size:0.85em;margin:0 0 0.5em;}.reset-btn.svelte-1bx72mz {margin-top:0.4em;}.footer-hint.svelte-1bx72mz {font-size:0.82em;margin:0.4em 0 0;}"};function nP(Q,J){c7(J,!1),bX(Q,V0Q);let G=dQ(),H=dQ(),K=gX(J,"plugin",8),z=dQ("all"),q=dQ([]),F=dQ(!1),D=dQ(!1),V=dQ([]),O=dQ(""),P=new bY;SY(async()=>{var b;let g=await P.loadState(K());qQ(z,g.profile),qQ(q,g.promoted);let l=(b=K().mcpTransportState)===null||b===void 0?void 0:b.mcp.registry;qQ(V,l?l.listAll().map((_)=>_.name):[]),qQ(D,!0)});async function N(b){if(!b)return;qQ(F,!0);try{await P.activateTool(b,c(V),K()),qQ(q,[...c(q),b]),qQ(O,"")}finally{qQ(F,!1)}}async function I(b){qQ(F,!0);try{await xY.run(async()=>{var g,l;let _=(g=await K().loadData())!==null&&g!==void 0?g:{},a=(l=_.toolLoading)!==null&&l!==void 0?l:{};_.toolLoading={...a,...b},await K().saveData(_)})}catch(g){let l=g instanceof Error?g.message:String(g);new Yx.Notice(`Failed to save tool loading settings: ${l}`)}finally{qQ(F,!1)}}function R(b){qQ(z,b),I({profile:c(z)})}async function w(b){await P.deactivateTool(b,K()),qQ(q,c(q).filter((g)=>g!==b))}async function E(){await P.resetAll(K()),qQ(q,[]),new Yx.Notice("Adaptive tool data reset.")}YY(()=>(U5,qU),()=>{qQ(G,new Set([...U5,...qU]))}),YY(()=>(c(V),c(G),c(q)),()=>{qQ(H,c(V).filter((b)=>!c(G).has(b)&&!c(q).includes(b)).sort((b,g)=>b.localeCompare(g)))}),J3(),vJ();var T=z0Q(),y=VQ(GQ(T),4);{var x=(b)=>{var g=K0Q(),l=$X(g),_=GQ(l),a=GQ(_);j9(a),v9(2),YQ(_);var r=VQ(_,2),f0=GQ(r);j9(f0),v9(2),YQ(r);var t=VQ(r,2),p0=GQ(t);j9(p0),v9(2),YQ(t),YQ(l);var u0=VQ(l,2);{var d=(n)=>{var c0=A0Q(),WQ=GQ(c0),R0=VQ(GQ(WQ)),l0=VQ(GQ(R0),2);l0.nodeValue=`, or auto-promoted
after 3 calls (Adaptive only). Active at connect time in both
Core and Adaptive.`,YQ(R0),YQ(WQ);var d0=VQ(WQ,2);{var m0=(mQ)=>{var AQ=J0Q();TQ(mQ,AQ)},ZQ=(mQ)=>{var AQ=G0Q(),MQ=GQ(AQ),DQ=GQ(MQ);DQ.value=DQ.__value="";var bQ=VQ(DQ);WY(bQ,1,()=>c(H),(tQ)=>tQ,(tQ,K8)=>{var k8=Y0Q(),d6=GQ(k8,!0);YQ(k8);var r9={};C8(()=>{if(q8(d6,c(K8)),r9!==(r9=c(K8)))k8.value=(k8.__value=c(K8))??""}),TQ(tQ,k8)}),YQ(MQ);var j8=VQ(MQ,2);YQ(AQ),C8(()=>{MQ.disabled=c(F),j8.disabled=c(F)||!c(O)}),eT(MQ,()=>c(O),(tQ)=>qQ(O,tQ)),N8("click",j8,()=>void N(c(O))),TQ(mQ,AQ)};m8(d0,(mQ)=>{if(c(V),FQ(()=>c(V).length===0))mQ(m0);else if(c(H),FQ(()=>c(H).length>0))mQ(ZQ,1)})}var LQ=VQ(d0,2);{var h0=(mQ)=>{var AQ=W0Q();TQ(mQ,AQ)},pQ=(mQ)=>{var AQ=B0Q();WY(AQ,5,()=>c(q),(MQ)=>MQ,(MQ,DQ)=>{var bQ=H0Q(),j8=GQ(bQ),tQ=GQ(j8,!0);YQ(j8);var K8=VQ(j8,2);YQ(bQ),C8(()=>{q8(tQ,c(DQ)),K8.disabled=c(F),N9(K8,"aria-label",`Remove ${c(DQ)??""} from promoted tools`)}),N8("click",K8,()=>void w(c(DQ))),TQ(MQ,bQ)}),YQ(AQ),TQ(mQ,AQ)};m8(LQ,(mQ)=>{if(c(q),FQ(()=>c(q).length===0))mQ(h0);else mQ(pQ,-1)})}var iQ=VQ(LQ,2);YQ(c0),C8(()=>iQ.disabled=c(F)),N8("click",iQ,()=>void E()),TQ(n,c0)};m8(u0,(n)=>{if(c(z)!=="all")n(d)})}C8(()=>{N7(a,c(z)==="all"),a.disabled=c(F),N7(f0,c(z)==="core"),f0.disabled=c(F),N7(p0,c(z)==="adaptive"),p0.disabled=c(F)}),N8("change",a,()=>R("all")),N8("change",f0,()=>R("core")),N8("change",p0,()=>R("adaptive")),TQ(b,g)};m8(y,(b)=>{if(c(D))b(x)})}v9(2),YQ(T),TQ(Q,T),i7()}async function Gx(Q,J){let G=new bY,H=await G.loadState(J);if(H.profile==="all")return;let z=Q.listAll().map((D)=>D.name),q=G.getActiveToolNames(z,H),F=[];for(let D of z)if(!q.has(D))Q.disableByName(D),F.push(D);SQ.info("adaptive-tool-loading: filter applied",{profile:H.profile,active:q.size,disabled:F.length})}var gY=K7(sE(),1),yK0=(Q)=>gY.interval(200).pipe(gY.takeUntil(gY.timer(5000)),gY.map(()=>{let J=Q.app.plugins.plugins["smart-connections"],G=J?.env?.smart_sources;if(G)return{id:"smart-connections",name:"Smart Connections",required:!1,installed:!0,api:{search:async(z,q)=>{try{return(await G.lookup({hypotheticals:[z],filter:{limit:q?.limit,key_starts_with_any:q?.key_starts_with_any,exclude_key_starts_with_any:q?.exclude_key_starts_with_any,exclude_key:q?.exclude_key,exclude_keys:q?.exclude_keys,exclude_key_starts_with:q?.exclude_key_starts_with,exclude_key_includes:q?.exclude_key_includes,key_ends_with:q?.key_ends_with,key_starts_with:q?.key_starts_with,key_includes:q?.key_includes}})).map((D)=>({item:{path:D.item.path,name:D.item.name||D.item.key?.split("/").pop()||D.item.key||D.item.path,breadcrumbs:D.item.breadcrumbs||D.item.path,read:()=>D.item.read(),key:D.item.key??D.item.path,file_path:D.item.path,link:D.item.link??"",size:D.item.size??0},score:D.score}))}catch(F){return console.error("Smart Connections v3.0 search error:",F),[]}}},plugin:J};let H=window.SmartSearch;if(!H&&J?.env){let K=J.env;if(typeof K.search==="function")H=K,window.SmartSearch=H}return{id:"smart-connections",name:"Smart Connections",required:!1,installed:!!H,api:H,plugin:J}}),gY.takeWhile((J)=>typeof J.api?.search!=="function",!0),gY.distinct(({installed:J})=>J));var uK0=require("node:http");var vK0=[27200,27201,27202,27203,27204,27205],F3="127.0.0.1",k4="/mcp",xK0=32,aP=1048576,bK0=/^https?:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/,$5={METHOD_NOT_ALLOWED:405,NOT_FOUND:404,ORIGIN_FORBIDDEN:403,UNAUTHORIZED:401,PAYLOAD_TOO_LARGE:413};function gK0(Q){if(Q==null)return!0;return bK0.test(Q)}var sP=require("node:crypto");function rP(){return sP.randomBytes(xK0).toString("base64url")}function hK0(Q,J){let G=Buffer.from(Q),H=Buffer.from(J);if(G.byteLength!==H.byteLength)return!1;return sP.timingSafeEqual(G,H)}var q0Q=new Set(["POST"]);function U0Q(Q,J){let G=(J??"").split("?")[0];if(G!==k4&&!G.startsWith(`${k4}/`))return{ok:!1,status:$5.NOT_FOUND};if(!q0Q.has((Q??"").toUpperCase()))return{ok:!1,status:$5.METHOD_NOT_ALLOWED};return{ok:!0}}function _K0(Q,J){let G=Q[J.toLowerCase()];return Array.isArray(G)?G[0]:G}function $0Q(Q,J){let G=_K0(Q,"authorization");if(!G)return{ok:!1,status:$5.UNAUTHORIZED};let H=/^Bearer\s+(.+)$/.exec(G);if(!H)return{ok:!1,status:$5.UNAUTHORIZED};let K=H[1].trim();if(!hK0(K,J))return{ok:!1,status:$5.UNAUTHORIZED};return{ok:!0}}function Z0Q(Q){let J=_K0(Q,"origin");return gK0(J)?{ok:!0}:{ok:!1,status:$5.ORIGIN_FORBIDDEN}}function fK0(Q,J){let G=U0Q(Q.method,Q.url);if(!G.ok)return G;let H=Z0Q(Q.headers);if(!H.ok)return H;let K=$0Q(Q.headers,J);if(!K.ok)return K;return{ok:!0}}async function mK0(Q,J){for(let G of J)try{return await new Promise((H,K)=>{let z=(F)=>{Q.off("listening",q),K(F)},q=()=>{Q.off("error",z),H()};Q.once("error",z),Q.once("listening",q),Q.listen(G,F3)}),G}catch(H){if(H.code!=="EADDRINUSE")throw H}throw Error(`No free port in range: ${J.join(", ")}`)}async function pK0(Q){let J=uK0.createServer((H,K)=>{let z=fK0({method:H.method,url:H.url,headers:H.headers},Q.bearerToken);if(!z.ok){K.writeHead(z.status),K.end();return}let q=Number(H.headers["content-length"]);if(Number.isFinite(q)&&q>aP){K.writeHead($5.PAYLOAD_TOO_LARGE),K.end(),H.destroy();return}Q.requestHandler(H,K).catch((F)=>{if(!K.headersSent)K.writeHead(500);K.end(),SQ.error("[mcp-transport] request handler failed",{error:F})})}),G;try{G=await mK0(J,[...vK0])}catch(H){try{J.close()}catch{}throw H}return{server:J,port:G}}async function lK0({server:Q}){Q.closeAllConnections?.(),await new Promise((J,G)=>{Q.close((H)=>{if(H&&H.code!=="ERR_SERVER_NOT_RUNNING"){G(H);return}J()})})}var $6;(function(Q){Q.assertEqual=(K)=>{};function J(K){}Q.assertIs=J;function G(K){throw Error()}Q.assertNever=G,Q.arrayToEnum=(K)=>{let z={};for(let q of K)z[q]=q;return z},Q.getValidEnumValues=(K)=>{let z=Q.objectKeys(K).filter((F)=>typeof K[K[F]]!=="number"),q={};for(let F of z)q[F]=K[F];return Q.objectValues(q)},Q.objectValues=(K)=>{return Q.objectKeys(K).map(function(z){return K[z]})},Q.objectKeys=typeof Object.keys==="function"?(K)=>Object.keys(K):(K)=>{let z=[];for(let q in K)if(Object.prototype.hasOwnProperty.call(K,q))z.push(q);return z},Q.find=(K,z)=>{for(let q of K)if(z(q))return q;return},Q.isInteger=typeof Number.isInteger==="function"?(K)=>Number.isInteger(K):(K)=>typeof K==="number"&&Number.isFinite(K)&&Math.floor(K)===K;function H(K,z=" | "){return K.map((q)=>typeof q==="string"?`'${q}'`:q).join(z)}Q.joinValues=H,Q.jsonStringifyReplacer=(K,z)=>{if(typeof z==="bigint")return z.toString();return z}})($6||($6={}));var dK0;(function(Q){Q.mergeShapes=(J,G)=>{return{...J,...G}}})(dK0||(dK0={}));var EQ=$6.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z5=(Q)=>{switch(typeof Q){case"undefined":return EQ.undefined;case"string":return EQ.string;case"number":return Number.isNaN(Q)?EQ.nan:EQ.number;case"boolean":return EQ.boolean;case"function":return EQ.function;case"bigint":return EQ.bigint;case"symbol":return EQ.symbol;case"object":if(Array.isArray(Q))return EQ.array;if(Q===null)return EQ.null;if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return EQ.promise;if(typeof Map<"u"&&Q instanceof Map)return EQ.map;if(typeof Set<"u"&&Q instanceof Set)return EQ.set;if(typeof Date<"u"&&Q instanceof Date)return EQ.date;return EQ.object;default:return EQ.unknown}};var jQ=$6.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class AY extends Error{get errors(){return this.issues}constructor(Q){super();this.issues=[],this.addIssue=(G)=>{this.issues=[...this.issues,G]},this.addIssues=(G=[])=>{this.issues=[...this.issues,...G]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=Q}format(Q){let J=Q||function(K){return K.message},G={_errors:[]},H=(K)=>{for(let z of K.issues)if(z.code==="invalid_union")z.unionErrors.map(H);else if(z.code==="invalid_return_type")H(z.returnTypeError);else if(z.code==="invalid_arguments")H(z.argumentsError);else if(z.path.length===0)G._errors.push(J(z));else{let q=G,F=0;while(F<z.path.length){let D=z.path[F];if(F!==z.path.length-1)q[D]=q[D]||{_errors:[]};else q[D]=q[D]||{_errors:[]},q[D]._errors.push(J(z));q=q[D],F++}}};return H(this),G}static assert(Q){if(!(Q instanceof AY))throw Error(`Not a ZodError: ${Q}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,$6.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(Q=(J)=>J.message){let J=Object.create(null),G=[];for(let H of this.issues)if(H.path.length>0){let K=H.path[0];J[K]=J[K]||[],J[K].push(Q(H))}else G.push(Q(H));return{formErrors:G,fieldErrors:J}}get formErrors(){return this.flatten()}}AY.create=(Q)=>{return new AY(Q)};var F0Q=(Q,J)=>{let G;switch(Q.code){case jQ.invalid_type:if(Q.received===EQ.undefined)G="Required";else G=`Expected ${Q.expected}, received ${Q.received}`;break;case jQ.invalid_literal:G=`Invalid literal value, expected ${JSON.stringify(Q.expected,$6.jsonStringifyReplacer)}`;break;case jQ.unrecognized_keys:G=`Unrecognized key(s) in object: ${$6.joinValues(Q.keys,", ")}`;break;case jQ.invalid_union:G="Invalid input";break;case jQ.invalid_union_discriminator:G=`Invalid discriminator value. Expected ${$6.joinValues(Q.options)}`;break;case jQ.invalid_enum_value:G=`Invalid enum value. Expected ${$6.joinValues(Q.options)}, received '${Q.received}'`;break;case jQ.invalid_arguments:G="Invalid function arguments";break;case jQ.invalid_return_type:G="Invalid function return type";break;case jQ.invalid_date:G="Invalid date";break;case jQ.invalid_string:if(typeof Q.validation==="object")if("includes"in Q.validation){if(G=`Invalid input: must include "${Q.validation.includes}"`,typeof Q.validation.position==="number")G=`${G} at one or more positions greater than or equal to ${Q.validation.position}`}else if("startsWith"in Q.validation)G=`Invalid input: must start with "${Q.validation.startsWith}"`;else if("endsWith"in Q.validation)G=`Invalid input: must end with "${Q.validation.endsWith}"`;else $6.assertNever(Q.validation);else if(Q.validation!=="regex")G=`Invalid ${Q.validation}`;else G="Invalid";break;case jQ.too_small:if(Q.type==="array")G=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at least":"more than"} ${Q.minimum} element(s)`;else if(Q.type==="string")G=`String must contain ${Q.exact?"exactly":Q.inclusive?"at least":"over"} ${Q.minimum} character(s)`;else if(Q.type==="number")G=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="bigint")G=`Number must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${Q.minimum}`;else if(Q.type==="date")G=`Date must be ${Q.exact?"exactly equal to ":Q.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(Q.minimum))}`;else G="Invalid input";break;case jQ.too_big:if(Q.type==="array")G=`Array must contain ${Q.exact?"exactly":Q.inclusive?"at most":"less than"} ${Q.maximum} element(s)`;else if(Q.type==="string")G=`String must contain ${Q.exact?"exactly":Q.inclusive?"at most":"under"} ${Q.maximum} character(s)`;else if(Q.type==="number")G=`Number must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="bigint")G=`BigInt must be ${Q.exact?"exactly":Q.inclusive?"less than or equal to":"less than"} ${Q.maximum}`;else if(Q.type==="date")G=`Date must be ${Q.exact?"exactly":Q.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(Q.maximum))}`;else G="Invalid input";break;case jQ.custom:G="Invalid input";break;case jQ.invalid_intersection_types:G="Intersection results could not be merged";break;case jQ.not_multiple_of:G=`Number must be a multiple of ${Q.multipleOf}`;break;case jQ.not_finite:G="Number must be finite";break;default:G=J.defaultError,$6.assertNever(Q)}return{message:G}},y4=F0Q;var D0Q=y4;function UU(){return D0Q}var tP=(Q)=>{let{data:J,path:G,errorMaps:H,issueData:K}=Q,z=[...G,...K.path||[]],q={...K,path:z};if(K.message!==void 0)return{...K,path:z,message:K.message};let F="",D=H.filter((V)=>!!V).slice().reverse();for(let V of D)F=V(q,{data:J,defaultError:F}).message;return{...K,path:z,message:F}};function vQ(Q,J){let G=UU(),H=tP({issueData:J,data:Q.data,path:Q.path,errorMaps:[Q.common.contextualErrorMap,Q.schemaErrorMap,G,G===y4?void 0:y4].filter((K)=>!!K)});Q.common.issues.push(H)}class fX{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(Q,J){let G=[];for(let H of J){if(H.status==="aborted")return w8;if(H.status==="dirty")Q.dirty();G.push(H.value)}return{status:Q.value,value:G}}static async mergeObjectAsync(Q,J){let G=[];for(let H of J){let K=await H.key,z=await H.value;G.push({key:K,value:z})}return fX.mergeObjectSync(Q,G)}static mergeObjectSync(Q,J){let G={};for(let H of J){let{key:K,value:z}=H;if(K.status==="aborted")return w8;if(z.status==="aborted")return w8;if(K.status==="dirty")Q.dirty();if(z.status==="dirty")Q.dirty();if(K.value!=="__proto__"&&(typeof z.value<"u"||H.alwaysSet))G[K.value]=z.value}return{status:Q.value,value:G}}}var w8=Object.freeze({status:"aborted"}),Qz=(Q)=>({status:"dirty",value:Q}),qJ=(Q)=>({status:"valid",value:Q}),Wx=(Q)=>Q.status==="aborted",Hx=(Q)=>Q.status==="dirty",D3=(Q)=>Q.status==="valid",$U=(Q)=>typeof Promise<"u"&&Q instanceof Promise;var X8;(function(Q){Q.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},Q.toString=(J)=>typeof J==="string"?J:J?.message})(X8||(X8={}));class FG{constructor(Q,J,G,H){this._cachedPath=[],this.parent=Q,this.data=J,this._path=G,this._key=H}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var cK0=(Q,J)=>{if(D3(J))return{success:!0,data:J.value};else{if(!Q.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let G=new AY(Q.common.issues);return this._error=G,this._error}}}};function o8(Q){if(!Q)return{};let{errorMap:J,invalid_type_error:G,required_error:H,description:K}=Q;if(J&&(G||H))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:K};return{errorMap:(q,F)=>{let{message:D}=Q;if(q.code==="invalid_enum_value")return{message:D??F.defaultError};if(typeof F.data>"u")return{message:D??H??F.defaultError};if(q.code!=="invalid_type")return{message:F.defaultError};return{message:D??G??F.defaultError}},description:K}}class W6{get description(){return this._def.description}_getType(Q){return Z5(Q.data)}_getOrReturnCtx(Q,J){return J||{common:Q.parent.common,data:Q.data,parsedType:Z5(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}_processInputParams(Q){return{status:new fX,ctx:{common:Q.parent.common,data:Q.data,parsedType:Z5(Q.data),schemaErrorMap:this._def.errorMap,path:Q.path,parent:Q.parent}}}_parseSync(Q){let J=this._parse(Q);if($U(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync(Q){let J=this._parse(Q);return Promise.resolve(J)}parse(Q,J){let G=this.safeParse(Q,J);if(G.success)return G.data;throw G.error}safeParse(Q,J){let G={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:Z5(Q)},H=this._parseSync({data:Q,path:G.path,parent:G});return cK0(G,H)}"~validate"(Q){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:Z5(Q)};if(!this["~standard"].async)try{let G=this._parseSync({data:Q,path:[],parent:J});return D3(G)?{value:G.value}:{issues:J.common.issues}}catch(G){if(G?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:Q,path:[],parent:J}).then((G)=>D3(G)?{value:G.value}:{issues:J.common.issues})}async parseAsync(Q,J){let G=await this.safeParseAsync(Q,J);if(G.success)return G.data;throw G.error}async safeParseAsync(Q,J){let G={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:Q,parsedType:Z5(Q)},H=this._parse({data:Q,path:G.path,parent:G}),K=await($U(H)?H:Promise.resolve(H));return cK0(G,K)}refine(Q,J){let G=(H)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(H);else return J};return this._refinement((H,K)=>{let z=Q(H),q=()=>K.addIssue({code:jQ.custom,...G(H)});if(typeof Promise<"u"&&z instanceof Promise)return z.then((F)=>{if(!F)return q(),!1;else return!0});if(!z)return q(),!1;else return!0})}refinement(Q,J){return this._refinement((G,H)=>{if(!Q(G))return H.addIssue(typeof J==="function"?J(G,H):J),!1;else return!0})}_refinement(Q){return new LW({schema:this,typeName:CQ.ZodEffects,effect:{type:"refinement",refinement:Q}})}superRefine(Q){return this._refinement(Q)}constructor(Q){this.spa=this.safeParseAsync,this._def=Q,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(J)=>this["~validate"](J)}}optional(){return MW.create(this,this._def)}nullable(){return v4.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return DW.create(this)}promise(){return Wz.create(this,this._def)}or(Q){return LU.create([this,Q],this._def)}and(Q){return OU.create(this,Q,this._def)}transform(Q){return new LW({...o8(this._def),schema:this,typeName:CQ.ZodEffects,effect:{type:"transform",transform:Q}})}default(Q){let J=typeof Q==="function"?Q:()=>Q;return new CU({...o8(this._def),innerType:this,defaultValue:J,typeName:CQ.ZodDefault})}brand(){return new Vx({typeName:CQ.ZodBranded,type:this,...o8(this._def)})}catch(Q){let J=typeof Q==="function"?Q:()=>Q;return new IU({...o8(this._def),innerType:this,catchValue:J,typeName:CQ.ZodCatch})}describe(Q){return new this.constructor({...this._def,description:Q})}pipe(Q){return BN.create(this,Q)}readonly(){return RU.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var M0Q=/^c[^\s-]{8,}$/i,L0Q=/^[0-9a-z]+$/,O0Q=/^[0-9A-HJKMNP-TV-Z]{26}$/i,P0Q=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,N0Q=/^[a-z0-9_-]{21}$/i,j0Q=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,C0Q=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,I0Q=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,R0Q="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Bx,w0Q=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,E0Q=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,S0Q=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,T0Q=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,k0Q=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,y0Q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,iK0="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",v0Q=new RegExp(`^${iK0}$`);function oK0(Q){let J="[0-5]\\d";if(Q.precision)J=`${J}\\.\\d{${Q.precision}}`;else if(Q.precision==null)J=`${J}(\\.\\d+)?`;let G=Q.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${J})${G}`}function x0Q(Q){return new RegExp(`^${oK0(Q)}$`)}function b0Q(Q){let J=`${iK0}T${oK0(Q)}`,G=[];if(G.push(Q.local?"Z?":"Z"),Q.offset)G.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${G.join("|")})`,new RegExp(`^${J}$`)}function g0Q(Q,J){if((J==="v4"||!J)&&w0Q.test(Q))return!0;if((J==="v6"||!J)&&S0Q.test(Q))return!0;return!1}function h0Q(Q,J){if(!j0Q.test(Q))return!1;try{let[G]=Q.split(".");if(!G)return!1;let H=G.replace(/-/g,"+").replace(/_/g,"/").padEnd(G.length+(4-G.length%4)%4,"="),K=JSON.parse(atob(H));if(typeof K!=="object"||K===null)return!1;if("typ"in K&&K?.typ!=="JWT")return!1;if(!K.alg)return!1;if(J&&K.alg!==J)return!1;return!0}catch{return!1}}function _0Q(Q,J){if((J==="v4"||!J)&&E0Q.test(Q))return!0;if((J==="v6"||!J)&&T0Q.test(Q))return!0;return!1}class D5 extends W6{_parse(Q){if(this._def.coerce)Q.data=String(Q.data);if(this._getType(Q)!==EQ.string){let K=this._getOrReturnCtx(Q);return vQ(K,{code:jQ.invalid_type,expected:EQ.string,received:K.parsedType}),w8}let G=new fX,H=void 0;for(let K of this._def.checks)if(K.kind==="min"){if(Q.data.length<K.value)H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.too_small,minimum:K.value,type:"string",inclusive:!0,exact:!1,message:K.message}),G.dirty()}else if(K.kind==="max"){if(Q.data.length>K.value)H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.too_big,maximum:K.value,type:"string",inclusive:!0,exact:!1,message:K.message}),G.dirty()}else if(K.kind==="length"){let z=Q.data.length>K.value,q=Q.data.length<K.value;if(z||q){if(H=this._getOrReturnCtx(Q,H),z)vQ(H,{code:jQ.too_big,maximum:K.value,type:"string",inclusive:!0,exact:!0,message:K.message});else if(q)vQ(H,{code:jQ.too_small,minimum:K.value,type:"string",inclusive:!0,exact:!0,message:K.message});G.dirty()}}else if(K.kind==="email"){if(!I0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"email",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="emoji"){if(!Bx)Bx=new RegExp(R0Q,"u");if(!Bx.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"emoji",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="uuid"){if(!P0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"uuid",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="nanoid"){if(!N0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"nanoid",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="cuid"){if(!M0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"cuid",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="cuid2"){if(!L0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"cuid2",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="ulid"){if(!O0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"ulid",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="url")try{new URL(Q.data)}catch{H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"url",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="regex"){if(K.regex.lastIndex=0,!K.regex.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"regex",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="trim")Q.data=Q.data.trim();else if(K.kind==="includes"){if(!Q.data.includes(K.value,K.position))H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.invalid_string,validation:{includes:K.value,position:K.position},message:K.message}),G.dirty()}else if(K.kind==="toLowerCase")Q.data=Q.data.toLowerCase();else if(K.kind==="toUpperCase")Q.data=Q.data.toUpperCase();else if(K.kind==="startsWith"){if(!Q.data.startsWith(K.value))H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.invalid_string,validation:{startsWith:K.value},message:K.message}),G.dirty()}else if(K.kind==="endsWith"){if(!Q.data.endsWith(K.value))H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.invalid_string,validation:{endsWith:K.value},message:K.message}),G.dirty()}else if(K.kind==="datetime"){if(!b0Q(K).test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.invalid_string,validation:"datetime",message:K.message}),G.dirty()}else if(K.kind==="date"){if(!v0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.invalid_string,validation:"date",message:K.message}),G.dirty()}else if(K.kind==="time"){if(!x0Q(K).test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.invalid_string,validation:"time",message:K.message}),G.dirty()}else if(K.kind==="duration"){if(!C0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"duration",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="ip"){if(!g0Q(Q.data,K.version))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"ip",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="jwt"){if(!h0Q(Q.data,K.alg))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"jwt",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="cidr"){if(!_0Q(Q.data,K.version))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"cidr",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="base64"){if(!k0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"base64",code:jQ.invalid_string,message:K.message}),G.dirty()}else if(K.kind==="base64url"){if(!y0Q.test(Q.data))H=this._getOrReturnCtx(Q,H),vQ(H,{validation:"base64url",code:jQ.invalid_string,message:K.message}),G.dirty()}else $6.assertNever(K);return{status:G.value,value:Q.data}}_regex(Q,J,G){return this.refinement((H)=>Q.test(H),{validation:J,code:jQ.invalid_string,...X8.errToObj(G)})}_addCheck(Q){return new D5({...this._def,checks:[...this._def.checks,Q]})}email(Q){return this._addCheck({kind:"email",...X8.errToObj(Q)})}url(Q){return this._addCheck({kind:"url",...X8.errToObj(Q)})}emoji(Q){return this._addCheck({kind:"emoji",...X8.errToObj(Q)})}uuid(Q){return this._addCheck({kind:"uuid",...X8.errToObj(Q)})}nanoid(Q){return this._addCheck({kind:"nanoid",...X8.errToObj(Q)})}cuid(Q){return this._addCheck({kind:"cuid",...X8.errToObj(Q)})}cuid2(Q){return this._addCheck({kind:"cuid2",...X8.errToObj(Q)})}ulid(Q){return this._addCheck({kind:"ulid",...X8.errToObj(Q)})}base64(Q){return this._addCheck({kind:"base64",...X8.errToObj(Q)})}base64url(Q){return this._addCheck({kind:"base64url",...X8.errToObj(Q)})}jwt(Q){return this._addCheck({kind:"jwt",...X8.errToObj(Q)})}ip(Q){return this._addCheck({kind:"ip",...X8.errToObj(Q)})}cidr(Q){return this._addCheck({kind:"cidr",...X8.errToObj(Q)})}datetime(Q){if(typeof Q==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:Q});return this._addCheck({kind:"datetime",precision:typeof Q?.precision>"u"?null:Q?.precision,offset:Q?.offset??!1,local:Q?.local??!1,...X8.errToObj(Q?.message)})}date(Q){return this._addCheck({kind:"date",message:Q})}time(Q){if(typeof Q==="string")return this._addCheck({kind:"time",precision:null,message:Q});return this._addCheck({kind:"time",precision:typeof Q?.precision>"u"?null:Q?.precision,...X8.errToObj(Q?.message)})}duration(Q){return this._addCheck({kind:"duration",...X8.errToObj(Q)})}regex(Q,J){return this._addCheck({kind:"regex",regex:Q,...X8.errToObj(J)})}includes(Q,J){return this._addCheck({kind:"includes",value:Q,position:J?.position,...X8.errToObj(J?.message)})}startsWith(Q,J){return this._addCheck({kind:"startsWith",value:Q,...X8.errToObj(J)})}endsWith(Q,J){return this._addCheck({kind:"endsWith",value:Q,...X8.errToObj(J)})}min(Q,J){return this._addCheck({kind:"min",value:Q,...X8.errToObj(J)})}max(Q,J){return this._addCheck({kind:"max",value:Q,...X8.errToObj(J)})}length(Q,J){return this._addCheck({kind:"length",value:Q,...X8.errToObj(J)})}nonempty(Q){return this.min(1,X8.errToObj(Q))}trim(){return new D5({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new D5({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new D5({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((Q)=>Q.kind==="datetime")}get isDate(){return!!this._def.checks.find((Q)=>Q.kind==="date")}get isTime(){return!!this._def.checks.find((Q)=>Q.kind==="time")}get isDuration(){return!!this._def.checks.find((Q)=>Q.kind==="duration")}get isEmail(){return!!this._def.checks.find((Q)=>Q.kind==="email")}get isURL(){return!!this._def.checks.find((Q)=>Q.kind==="url")}get isEmoji(){return!!this._def.checks.find((Q)=>Q.kind==="emoji")}get isUUID(){return!!this._def.checks.find((Q)=>Q.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((Q)=>Q.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((Q)=>Q.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((Q)=>Q.kind==="cuid2")}get isULID(){return!!this._def.checks.find((Q)=>Q.kind==="ulid")}get isIP(){return!!this._def.checks.find((Q)=>Q.kind==="ip")}get isCIDR(){return!!this._def.checks.find((Q)=>Q.kind==="cidr")}get isBase64(){return!!this._def.checks.find((Q)=>Q.kind==="base64")}get isBase64url(){return!!this._def.checks.find((Q)=>Q.kind==="base64url")}get minLength(){let Q=null;for(let J of this._def.checks)if(J.kind==="min"){if(Q===null||J.value>Q)Q=J.value}return Q}get maxLength(){let Q=null;for(let J of this._def.checks)if(J.kind==="max"){if(Q===null||J.value<Q)Q=J.value}return Q}}D5.create=(Q)=>{return new D5({checks:[],typeName:CQ.ZodString,coerce:Q?.coerce??!1,...o8(Q)})};function f0Q(Q,J){let G=(Q.toString().split(".")[1]||"").length,H=(J.toString().split(".")[1]||"").length,K=G>H?G:H,z=Number.parseInt(Q.toFixed(K).replace(".","")),q=Number.parseInt(J.toFixed(K).replace(".",""));return z%q/10**K}class Jz extends W6{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(Q){if(this._def.coerce)Q.data=Number(Q.data);if(this._getType(Q)!==EQ.number){let K=this._getOrReturnCtx(Q);return vQ(K,{code:jQ.invalid_type,expected:EQ.number,received:K.parsedType}),w8}let G=void 0,H=new fX;for(let K of this._def.checks)if(K.kind==="int"){if(!$6.isInteger(Q.data))G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.invalid_type,expected:"integer",received:"float",message:K.message}),H.dirty()}else if(K.kind==="min"){if(K.inclusive?Q.data<K.value:Q.data<=K.value)G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.too_small,minimum:K.value,type:"number",inclusive:K.inclusive,exact:!1,message:K.message}),H.dirty()}else if(K.kind==="max"){if(K.inclusive?Q.data>K.value:Q.data>=K.value)G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.too_big,maximum:K.value,type:"number",inclusive:K.inclusive,exact:!1,message:K.message}),H.dirty()}else if(K.kind==="multipleOf"){if(f0Q(Q.data,K.value)!==0)G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.not_multiple_of,multipleOf:K.value,message:K.message}),H.dirty()}else if(K.kind==="finite"){if(!Number.isFinite(Q.data))G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.not_finite,message:K.message}),H.dirty()}else $6.assertNever(K);return{status:H.value,value:Q.data}}gte(Q,J){return this.setLimit("min",Q,!0,X8.toString(J))}gt(Q,J){return this.setLimit("min",Q,!1,X8.toString(J))}lte(Q,J){return this.setLimit("max",Q,!0,X8.toString(J))}lt(Q,J){return this.setLimit("max",Q,!1,X8.toString(J))}setLimit(Q,J,G,H){return new Jz({...this._def,checks:[...this._def.checks,{kind:Q,value:J,inclusive:G,message:X8.toString(H)}]})}_addCheck(Q){return new Jz({...this._def,checks:[...this._def.checks,Q]})}int(Q){return this._addCheck({kind:"int",message:X8.toString(Q)})}positive(Q){return this._addCheck({kind:"min",value:0,inclusive:!1,message:X8.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:0,inclusive:!1,message:X8.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:0,inclusive:!0,message:X8.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:0,inclusive:!0,message:X8.toString(Q)})}multipleOf(Q,J){return this._addCheck({kind:"multipleOf",value:Q,message:X8.toString(J)})}finite(Q){return this._addCheck({kind:"finite",message:X8.toString(Q)})}safe(Q){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:X8.toString(Q)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:X8.toString(Q)})}get minValue(){let Q=null;for(let J of this._def.checks)if(J.kind==="min"){if(Q===null||J.value>Q)Q=J.value}return Q}get maxValue(){let Q=null;for(let J of this._def.checks)if(J.kind==="max"){if(Q===null||J.value<Q)Q=J.value}return Q}get isInt(){return!!this._def.checks.find((Q)=>Q.kind==="int"||Q.kind==="multipleOf"&&$6.isInteger(Q.value))}get isFinite(){let Q=null,J=null;for(let G of this._def.checks)if(G.kind==="finite"||G.kind==="int"||G.kind==="multipleOf")return!0;else if(G.kind==="min"){if(J===null||G.value>J)J=G.value}else if(G.kind==="max"){if(Q===null||G.value<Q)Q=G.value}return Number.isFinite(J)&&Number.isFinite(Q)}}Jz.create=(Q)=>{return new Jz({checks:[],typeName:CQ.ZodNumber,coerce:Q?.coerce||!1,...o8(Q)})};class Yz extends W6{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(Q){if(this._def.coerce)try{Q.data=BigInt(Q.data)}catch{return this._getInvalidInput(Q)}if(this._getType(Q)!==EQ.bigint)return this._getInvalidInput(Q);let G=void 0,H=new fX;for(let K of this._def.checks)if(K.kind==="min"){if(K.inclusive?Q.data<K.value:Q.data<=K.value)G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.too_small,type:"bigint",minimum:K.value,inclusive:K.inclusive,message:K.message}),H.dirty()}else if(K.kind==="max"){if(K.inclusive?Q.data>K.value:Q.data>=K.value)G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.too_big,type:"bigint",maximum:K.value,inclusive:K.inclusive,message:K.message}),H.dirty()}else if(K.kind==="multipleOf"){if(Q.data%K.value!==BigInt(0))G=this._getOrReturnCtx(Q,G),vQ(G,{code:jQ.not_multiple_of,multipleOf:K.value,message:K.message}),H.dirty()}else $6.assertNever(K);return{status:H.value,value:Q.data}}_getInvalidInput(Q){let J=this._getOrReturnCtx(Q);return vQ(J,{code:jQ.invalid_type,expected:EQ.bigint,received:J.parsedType}),w8}gte(Q,J){return this.setLimit("min",Q,!0,X8.toString(J))}gt(Q,J){return this.setLimit("min",Q,!1,X8.toString(J))}lte(Q,J){return this.setLimit("max",Q,!0,X8.toString(J))}lt(Q,J){return this.setLimit("max",Q,!1,X8.toString(J))}setLimit(Q,J,G,H){return new Yz({...this._def,checks:[...this._def.checks,{kind:Q,value:J,inclusive:G,message:X8.toString(H)}]})}_addCheck(Q){return new Yz({...this._def,checks:[...this._def.checks,Q]})}positive(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:X8.toString(Q)})}negative(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:X8.toString(Q)})}nonpositive(Q){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:X8.toString(Q)})}nonnegative(Q){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:X8.toString(Q)})}multipleOf(Q,J){return this._addCheck({kind:"multipleOf",value:Q,message:X8.toString(J)})}get minValue(){let Q=null;for(let J of this._def.checks)if(J.kind==="min"){if(Q===null||J.value>Q)Q=J.value}return Q}get maxValue(){let Q=null;for(let J of this._def.checks)if(J.kind==="max"){if(Q===null||J.value<Q)Q=J.value}return Q}}Yz.create=(Q)=>{return new Yz({checks:[],typeName:CQ.ZodBigInt,coerce:Q?.coerce??!1,...o8(Q)})};class QN extends W6{_parse(Q){if(this._def.coerce)Q.data=Boolean(Q.data);if(this._getType(Q)!==EQ.boolean){let G=this._getOrReturnCtx(Q);return vQ(G,{code:jQ.invalid_type,expected:EQ.boolean,received:G.parsedType}),w8}return qJ(Q.data)}}QN.create=(Q)=>{return new QN({typeName:CQ.ZodBoolean,coerce:Q?.coerce||!1,...o8(Q)})};class FU extends W6{_parse(Q){if(this._def.coerce)Q.data=new Date(Q.data);if(this._getType(Q)!==EQ.date){let K=this._getOrReturnCtx(Q);return vQ(K,{code:jQ.invalid_type,expected:EQ.date,received:K.parsedType}),w8}if(Number.isNaN(Q.data.getTime())){let K=this._getOrReturnCtx(Q);return vQ(K,{code:jQ.invalid_date}),w8}let G=new fX,H=void 0;for(let K of this._def.checks)if(K.kind==="min"){if(Q.data.getTime()<K.value)H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.too_small,message:K.message,inclusive:!0,exact:!1,minimum:K.value,type:"date"}),G.dirty()}else if(K.kind==="max"){if(Q.data.getTime()>K.value)H=this._getOrReturnCtx(Q,H),vQ(H,{code:jQ.too_big,message:K.message,inclusive:!0,exact:!1,maximum:K.value,type:"date"}),G.dirty()}else $6.assertNever(K);return{status:G.value,value:new Date(Q.data.getTime())}}_addCheck(Q){return new FU({...this._def,checks:[...this._def.checks,Q]})}min(Q,J){return this._addCheck({kind:"min",value:Q.getTime(),message:X8.toString(J)})}max(Q,J){return this._addCheck({kind:"max",value:Q.getTime(),message:X8.toString(J)})}get minDate(){let Q=null;for(let J of this._def.checks)if(J.kind==="min"){if(Q===null||J.value>Q)Q=J.value}return Q!=null?new Date(Q):null}get maxDate(){let Q=null;for(let J of this._def.checks)if(J.kind==="max"){if(Q===null||J.value<Q)Q=J.value}return Q!=null?new Date(Q):null}}FU.create=(Q)=>{return new FU({checks:[],coerce:Q?.coerce||!1,typeName:CQ.ZodDate,...o8(Q)})};class XN extends W6{_parse(Q){if(this._getType(Q)!==EQ.symbol){let G=this._getOrReturnCtx(Q);return vQ(G,{code:jQ.invalid_type,expected:EQ.symbol,received:G.parsedType}),w8}return qJ(Q.data)}}XN.create=(Q)=>{return new XN({typeName:CQ.ZodSymbol,...o8(Q)})};class DU extends W6{_parse(Q){if(this._getType(Q)!==EQ.undefined){let G=this._getOrReturnCtx(Q);return vQ(G,{code:jQ.invalid_type,expected:EQ.undefined,received:G.parsedType}),w8}return qJ(Q.data)}}DU.create=(Q)=>{return new DU({typeName:CQ.ZodUndefined,...o8(Q)})};class MU extends W6{_parse(Q){if(this._getType(Q)!==EQ.null){let G=this._getOrReturnCtx(Q);return vQ(G,{code:jQ.invalid_type,expected:EQ.null,received:G.parsedType}),w8}return qJ(Q.data)}}MU.create=(Q)=>{return new MU({typeName:CQ.ZodNull,...o8(Q)})};class JN extends W6{constructor(){super(...arguments);this._any=!0}_parse(Q){return qJ(Q.data)}}JN.create=(Q)=>{return new JN({typeName:CQ.ZodAny,...o8(Q)})};class M3 extends W6{constructor(){super(...arguments);this._unknown=!0}_parse(Q){return qJ(Q.data)}}M3.create=(Q)=>{return new M3({typeName:CQ.ZodUnknown,...o8(Q)})};class M5 extends W6{_parse(Q){let J=this._getOrReturnCtx(Q);return vQ(J,{code:jQ.invalid_type,expected:EQ.never,received:J.parsedType}),w8}}M5.create=(Q)=>{return new M5({typeName:CQ.ZodNever,...o8(Q)})};class YN extends W6{_parse(Q){if(this._getType(Q)!==EQ.undefined){let G=this._getOrReturnCtx(Q);return vQ(G,{code:jQ.invalid_type,expected:EQ.void,received:G.parsedType}),w8}return qJ(Q.data)}}YN.create=(Q)=>{return new YN({typeName:CQ.ZodVoid,...o8(Q)})};class DW extends W6{_parse(Q){let{ctx:J,status:G}=this._processInputParams(Q),H=this._def;if(J.parsedType!==EQ.array)return vQ(J,{code:jQ.invalid_type,expected:EQ.array,received:J.parsedType}),w8;if(H.exactLength!==null){let z=J.data.length>H.exactLength.value,q=J.data.length<H.exactLength.value;if(z||q)vQ(J,{code:z?jQ.too_big:jQ.too_small,minimum:q?H.exactLength.value:void 0,maximum:z?H.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:H.exactLength.message}),G.dirty()}if(H.minLength!==null){if(J.data.length<H.minLength.value)vQ(J,{code:jQ.too_small,minimum:H.minLength.value,type:"array",inclusive:!0,exact:!1,message:H.minLength.message}),G.dirty()}if(H.maxLength!==null){if(J.data.length>H.maxLength.value)vQ(J,{code:jQ.too_big,maximum:H.maxLength.value,type:"array",inclusive:!0,exact:!1,message:H.maxLength.message}),G.dirty()}if(J.common.async)return Promise.all([...J.data].map((z,q)=>{return H.type._parseAsync(new FG(J,z,J.path,q))})).then((z)=>{return fX.mergeArray(G,z)});let K=[...J.data].map((z,q)=>{return H.type._parseSync(new FG(J,z,J.path,q))});return fX.mergeArray(G,K)}get element(){return this._def.type}min(Q,J){return new DW({...this._def,minLength:{value:Q,message:X8.toString(J)}})}max(Q,J){return new DW({...this._def,maxLength:{value:Q,message:X8.toString(J)}})}length(Q,J){return new DW({...this._def,exactLength:{value:Q,message:X8.toString(J)}})}nonempty(Q){return this.min(1,Q)}}DW.create=(Q,J)=>{return new DW({type:Q,minLength:null,maxLength:null,exactLength:null,typeName:CQ.ZodArray,...o8(J)})};function Xz(Q){if(Q instanceof Q7){let J={};for(let G in Q.shape){let H=Q.shape[G];J[G]=MW.create(Xz(H))}return new Q7({...Q._def,shape:()=>J})}else if(Q instanceof DW)return new DW({...Q._def,type:Xz(Q.element)});else if(Q instanceof MW)return MW.create(Xz(Q.unwrap()));else if(Q instanceof v4)return v4.create(Xz(Q.unwrap()));else if(Q instanceof L5)return L5.create(Q.items.map((J)=>Xz(J)));else return Q}class Q7 extends W6{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let Q=this._def.shape(),J=$6.objectKeys(Q);return this._cached={shape:Q,keys:J},this._cached}_parse(Q){if(this._getType(Q)!==EQ.object){let D=this._getOrReturnCtx(Q);return vQ(D,{code:jQ.invalid_type,expected:EQ.object,received:D.parsedType}),w8}let{status:G,ctx:H}=this._processInputParams(Q),{shape:K,keys:z}=this._getCached(),q=[];if(!(this._def.catchall instanceof M5&&this._def.unknownKeys==="strip")){for(let D in H.data)if(!z.includes(D))q.push(D)}let F=[];for(let D of z){let V=K[D],O=H.data[D];F.push({key:{status:"valid",value:D},value:V._parse(new FG(H,O,H.path,D)),alwaysSet:D in H.data})}if(this._def.catchall instanceof M5){let D=this._def.unknownKeys;if(D==="passthrough")for(let V of q)F.push({key:{status:"valid",value:V},value:{status:"valid",value:H.data[V]}});else if(D==="strict"){if(q.length>0)vQ(H,{code:jQ.unrecognized_keys,keys:q}),G.dirty()}else if(D==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let D=this._def.catchall;for(let V of q){let O=H.data[V];F.push({key:{status:"valid",value:V},value:D._parse(new FG(H,O,H.path,V)),alwaysSet:V in H.data})}}if(H.common.async)return Promise.resolve().then(async()=>{let D=[];for(let V of F){let O=await V.key,P=await V.value;D.push({key:O,value:P,alwaysSet:V.alwaysSet})}return D}).then((D)=>{return fX.mergeObjectSync(G,D)});else return fX.mergeObjectSync(G,F)}get shape(){return this._def.shape()}strict(Q){return X8.errToObj,new Q7({...this._def,unknownKeys:"strict",...Q!==void 0?{errorMap:(J,G)=>{let H=this._def.errorMap?.(J,G).message??G.defaultError;if(J.code==="unrecognized_keys")return{message:X8.errToObj(Q).message??H};return{message:H}}}:{}})}strip(){return new Q7({...this._def,unknownKeys:"strip"})}passthrough(){return new Q7({...this._def,unknownKeys:"passthrough"})}extend(Q){return new Q7({...this._def,shape:()=>({...this._def.shape(),...Q})})}merge(Q){return new Q7({unknownKeys:Q._def.unknownKeys,catchall:Q._def.catchall,shape:()=>({...this._def.shape(),...Q._def.shape()}),typeName:CQ.ZodObject})}setKey(Q,J){return this.augment({[Q]:J})}catchall(Q){return new Q7({...this._def,catchall:Q})}pick(Q){let J={};for(let G of $6.objectKeys(Q))if(Q[G]&&this.shape[G])J[G]=this.shape[G];return new Q7({...this._def,shape:()=>J})}omit(Q){let J={};for(let G of $6.objectKeys(this.shape))if(!Q[G])J[G]=this.shape[G];return new Q7({...this._def,shape:()=>J})}deepPartial(){return Xz(this)}partial(Q){let J={};for(let G of $6.objectKeys(this.shape)){let H=this.shape[G];if(Q&&!Q[G])J[G]=H;else J[G]=H.optional()}return new Q7({...this._def,shape:()=>J})}required(Q){let J={};for(let G of $6.objectKeys(this.shape))if(Q&&!Q[G])J[G]=this.shape[G];else{let K=this.shape[G];while(K instanceof MW)K=K._def.innerType;J[G]=K}return new Q7({...this._def,shape:()=>J})}keyof(){return nK0($6.objectKeys(this.shape))}}Q7.create=(Q,J)=>{return new Q7({shape:()=>Q,unknownKeys:"strip",catchall:M5.create(),typeName:CQ.ZodObject,...o8(J)})};Q7.strictCreate=(Q,J)=>{return new Q7({shape:()=>Q,unknownKeys:"strict",catchall:M5.create(),typeName:CQ.ZodObject,...o8(J)})};Q7.lazycreate=(Q,J)=>{return new Q7({shape:Q,unknownKeys:"strip",catchall:M5.create(),typeName:CQ.ZodObject,...o8(J)})};class LU extends W6{_parse(Q){let{ctx:J}=this._processInputParams(Q),G=this._def.options;function H(K){for(let q of K)if(q.result.status==="valid")return q.result;for(let q of K)if(q.result.status==="dirty")return J.common.issues.push(...q.ctx.common.issues),q.result;let z=K.map((q)=>new AY(q.ctx.common.issues));return vQ(J,{code:jQ.invalid_union,unionErrors:z}),w8}if(J.common.async)return Promise.all(G.map(async(K)=>{let z={...J,common:{...J.common,issues:[]},parent:null};return{result:await K._parseAsync({data:J.data,path:J.path,parent:z}),ctx:z}})).then(H);else{let K=void 0,z=[];for(let F of G){let D={...J,common:{...J.common,issues:[]},parent:null},V=F._parseSync({data:J.data,path:J.path,parent:D});if(V.status==="valid")return V;else if(V.status==="dirty"&&!K)K={result:V,ctx:D};if(D.common.issues.length)z.push(D.common.issues)}if(K)return J.common.issues.push(...K.ctx.common.issues),K.result;let q=z.map((F)=>new AY(F));return vQ(J,{code:jQ.invalid_union,unionErrors:q}),w8}}get options(){return this._def.options}}LU.create=(Q,J)=>{return new LU({options:Q,typeName:CQ.ZodUnion,...o8(J)})};var F5=(Q)=>{if(Q instanceof PU)return F5(Q.schema);else if(Q instanceof LW)return F5(Q.innerType());else if(Q instanceof NU)return[Q.value];else if(Q instanceof L3)return Q.options;else if(Q instanceof jU)return $6.objectValues(Q.enum);else if(Q instanceof CU)return F5(Q._def.innerType);else if(Q instanceof DU)return[void 0];else if(Q instanceof MU)return[null];else if(Q instanceof MW)return[void 0,...F5(Q.unwrap())];else if(Q instanceof v4)return[null,...F5(Q.unwrap())];else if(Q instanceof Vx)return F5(Q.unwrap());else if(Q instanceof RU)return F5(Q.unwrap());else if(Q instanceof IU)return F5(Q._def.innerType);else return[]};class zx extends W6{_parse(Q){let{ctx:J}=this._processInputParams(Q);if(J.parsedType!==EQ.object)return vQ(J,{code:jQ.invalid_type,expected:EQ.object,received:J.parsedType}),w8;let G=this.discriminator,H=J.data[G],K=this.optionsMap.get(H);if(!K)return vQ(J,{code:jQ.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[G]}),w8;if(J.common.async)return K._parseAsync({data:J.data,path:J.path,parent:J});else return K._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(Q,J,G){let H=new Map;for(let K of J){let z=F5(K.shape[Q]);if(!z.length)throw Error(`A discriminator value for key \`${Q}\` could not be extracted from all schema options`);for(let q of z){if(H.has(q))throw Error(`Discriminator property ${String(Q)} has duplicate value ${String(q)}`);H.set(q,K)}}return new zx({typeName:CQ.ZodDiscriminatedUnion,discriminator:Q,options:J,optionsMap:H,...o8(G)})}}function Kx(Q,J){let G=Z5(Q),H=Z5(J);if(Q===J)return{valid:!0,data:Q};else if(G===EQ.object&&H===EQ.object){let K=$6.objectKeys(J),z=$6.objectKeys(Q).filter((F)=>K.indexOf(F)!==-1),q={...Q,...J};for(let F of z){let D=Kx(Q[F],J[F]);if(!D.valid)return{valid:!1};q[F]=D.data}return{valid:!0,data:q}}else if(G===EQ.array&&H===EQ.array){if(Q.length!==J.length)return{valid:!1};let K=[];for(let z=0;z<Q.length;z++){let q=Q[z],F=J[z],D=Kx(q,F);if(!D.valid)return{valid:!1};K.push(D.data)}return{valid:!0,data:K}}else if(G===EQ.date&&H===EQ.date&&+Q===+J)return{valid:!0,data:Q};else return{valid:!1}}class OU extends W6{_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q),H=(K,z)=>{if(Wx(K)||Wx(z))return w8;let q=Kx(K.value,z.value);if(!q.valid)return vQ(G,{code:jQ.invalid_intersection_types}),w8;if(Hx(K)||Hx(z))J.dirty();return{status:J.value,value:q.data}};if(G.common.async)return Promise.all([this._def.left._parseAsync({data:G.data,path:G.path,parent:G}),this._def.right._parseAsync({data:G.data,path:G.path,parent:G})]).then(([K,z])=>H(K,z));else return H(this._def.left._parseSync({data:G.data,path:G.path,parent:G}),this._def.right._parseSync({data:G.data,path:G.path,parent:G}))}}OU.create=(Q,J,G)=>{return new OU({left:Q,right:J,typeName:CQ.ZodIntersection,...o8(G)})};class L5 extends W6{_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q);if(G.parsedType!==EQ.array)return vQ(G,{code:jQ.invalid_type,expected:EQ.array,received:G.parsedType}),w8;if(G.data.length<this._def.items.length)return vQ(G,{code:jQ.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w8;if(!this._def.rest&&G.data.length>this._def.items.length)vQ(G,{code:jQ.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let K=[...G.data].map((z,q)=>{let F=this._def.items[q]||this._def.rest;if(!F)return null;return F._parse(new FG(G,z,G.path,q))}).filter((z)=>!!z);if(G.common.async)return Promise.all(K).then((z)=>{return fX.mergeArray(J,z)});else return fX.mergeArray(J,K)}get items(){return this._def.items}rest(Q){return new L5({...this._def,rest:Q})}}L5.create=(Q,J)=>{if(!Array.isArray(Q))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new L5({items:Q,typeName:CQ.ZodTuple,rest:null,...o8(J)})};class GN extends W6{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q);if(G.parsedType!==EQ.object)return vQ(G,{code:jQ.invalid_type,expected:EQ.object,received:G.parsedType}),w8;let H=[],K=this._def.keyType,z=this._def.valueType;for(let q in G.data)H.push({key:K._parse(new FG(G,q,G.path,q)),value:z._parse(new FG(G,G.data[q],G.path,q)),alwaysSet:q in G.data});if(G.common.async)return fX.mergeObjectAsync(J,H);else return fX.mergeObjectSync(J,H)}get element(){return this._def.valueType}static create(Q,J,G){if(J instanceof W6)return new GN({keyType:Q,valueType:J,typeName:CQ.ZodRecord,...o8(G)});return new GN({keyType:D5.create(),valueType:Q,typeName:CQ.ZodRecord,...o8(J)})}}class WN extends W6{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q);if(G.parsedType!==EQ.map)return vQ(G,{code:jQ.invalid_type,expected:EQ.map,received:G.parsedType}),w8;let H=this._def.keyType,K=this._def.valueType,z=[...G.data.entries()].map(([q,F],D)=>{return{key:H._parse(new FG(G,q,G.path,[D,"key"])),value:K._parse(new FG(G,F,G.path,[D,"value"]))}});if(G.common.async){let q=new Map;return Promise.resolve().then(async()=>{for(let F of z){let D=await F.key,V=await F.value;if(D.status==="aborted"||V.status==="aborted")return w8;if(D.status==="dirty"||V.status==="dirty")J.dirty();q.set(D.value,V.value)}return{status:J.value,value:q}})}else{let q=new Map;for(let F of z){let{key:D,value:V}=F;if(D.status==="aborted"||V.status==="aborted")return w8;if(D.status==="dirty"||V.status==="dirty")J.dirty();q.set(D.value,V.value)}return{status:J.value,value:q}}}}WN.create=(Q,J,G)=>{return new WN({valueType:J,keyType:Q,typeName:CQ.ZodMap,...o8(G)})};class Gz extends W6{_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q);if(G.parsedType!==EQ.set)return vQ(G,{code:jQ.invalid_type,expected:EQ.set,received:G.parsedType}),w8;let H=this._def;if(H.minSize!==null){if(G.data.size<H.minSize.value)vQ(G,{code:jQ.too_small,minimum:H.minSize.value,type:"set",inclusive:!0,exact:!1,message:H.minSize.message}),J.dirty()}if(H.maxSize!==null){if(G.data.size>H.maxSize.value)vQ(G,{code:jQ.too_big,maximum:H.maxSize.value,type:"set",inclusive:!0,exact:!1,message:H.maxSize.message}),J.dirty()}let K=this._def.valueType;function z(F){let D=new Set;for(let V of F){if(V.status==="aborted")return w8;if(V.status==="dirty")J.dirty();D.add(V.value)}return{status:J.value,value:D}}let q=[...G.data.values()].map((F,D)=>K._parse(new FG(G,F,G.path,D)));if(G.common.async)return Promise.all(q).then((F)=>z(F));else return z(q)}min(Q,J){return new Gz({...this._def,minSize:{value:Q,message:X8.toString(J)}})}max(Q,J){return new Gz({...this._def,maxSize:{value:Q,message:X8.toString(J)}})}size(Q,J){return this.min(Q,J).max(Q,J)}nonempty(Q){return this.min(1,Q)}}Gz.create=(Q,J)=>{return new Gz({valueType:Q,minSize:null,maxSize:null,typeName:CQ.ZodSet,...o8(J)})};class ZU extends W6{constructor(){super(...arguments);this.validate=this.implement}_parse(Q){let{ctx:J}=this._processInputParams(Q);if(J.parsedType!==EQ.function)return vQ(J,{code:jQ.invalid_type,expected:EQ.function,received:J.parsedType}),w8;function G(q,F){return tP({data:q,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,UU(),y4].filter((D)=>!!D),issueData:{code:jQ.invalid_arguments,argumentsError:F}})}function H(q,F){return tP({data:q,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,UU(),y4].filter((D)=>!!D),issueData:{code:jQ.invalid_return_type,returnTypeError:F}})}let K={errorMap:J.common.contextualErrorMap},z=J.data;if(this._def.returns instanceof Wz){let q=this;return qJ(async function(...F){let D=new AY([]),V=await q._def.args.parseAsync(F,K).catch((N)=>{throw D.addIssue(G(F,N)),D}),O=await Reflect.apply(z,this,V);return await q._def.returns._def.type.parseAsync(O,K).catch((N)=>{throw D.addIssue(H(O,N)),D})})}else{let q=this;return qJ(function(...F){let D=q._def.args.safeParse(F,K);if(!D.success)throw new AY([G(F,D.error)]);let V=Reflect.apply(z,this,D.data),O=q._def.returns.safeParse(V,K);if(!O.success)throw new AY([H(V,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...Q){return new ZU({...this._def,args:L5.create(Q).rest(M3.create())})}returns(Q){return new ZU({...this._def,returns:Q})}implement(Q){return this.parse(Q)}strictImplement(Q){return this.parse(Q)}static create(Q,J,G){return new ZU({args:Q?Q:L5.create([]).rest(M3.create()),returns:J||M3.create(),typeName:CQ.ZodFunction,...o8(G)})}}class PU extends W6{get schema(){return this._def.getter()}_parse(Q){let{ctx:J}=this._processInputParams(Q);return this._def.getter()._parse({data:J.data,path:J.path,parent:J})}}PU.create=(Q,J)=>{return new PU({getter:Q,typeName:CQ.ZodLazy,...o8(J)})};class NU extends W6{_parse(Q){if(Q.data!==this._def.value){let J=this._getOrReturnCtx(Q);return vQ(J,{received:J.data,code:jQ.invalid_literal,expected:this._def.value}),w8}return{status:"valid",value:Q.data}}get value(){return this._def.value}}NU.create=(Q,J)=>{return new NU({value:Q,typeName:CQ.ZodLiteral,...o8(J)})};function nK0(Q,J){return new L3({values:Q,typeName:CQ.ZodEnum,...o8(J)})}class L3 extends W6{_parse(Q){if(typeof Q.data!=="string"){let J=this._getOrReturnCtx(Q),G=this._def.values;return vQ(J,{expected:$6.joinValues(G),received:J.parsedType,code:jQ.invalid_type}),w8}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(Q.data)){let J=this._getOrReturnCtx(Q),G=this._def.values;return vQ(J,{received:J.data,code:jQ.invalid_enum_value,options:G}),w8}return qJ(Q.data)}get options(){return this._def.values}get enum(){let Q={};for(let J of this._def.values)Q[J]=J;return Q}get Values(){let Q={};for(let J of this._def.values)Q[J]=J;return Q}get Enum(){let Q={};for(let J of this._def.values)Q[J]=J;return Q}extract(Q,J=this._def){return L3.create(Q,{...this._def,...J})}exclude(Q,J=this._def){return L3.create(this.options.filter((G)=>!Q.includes(G)),{...this._def,...J})}}L3.create=nK0;class jU extends W6{_parse(Q){let J=$6.getValidEnumValues(this._def.values),G=this._getOrReturnCtx(Q);if(G.parsedType!==EQ.string&&G.parsedType!==EQ.number){let H=$6.objectValues(J);return vQ(G,{expected:$6.joinValues(H),received:G.parsedType,code:jQ.invalid_type}),w8}if(!this._cache)this._cache=new Set($6.getValidEnumValues(this._def.values));if(!this._cache.has(Q.data)){let H=$6.objectValues(J);return vQ(G,{received:G.data,code:jQ.invalid_enum_value,options:H}),w8}return qJ(Q.data)}get enum(){return this._def.values}}jU.create=(Q,J)=>{return new jU({values:Q,typeName:CQ.ZodNativeEnum,...o8(J)})};class Wz extends W6{unwrap(){return this._def.type}_parse(Q){let{ctx:J}=this._processInputParams(Q);if(J.parsedType!==EQ.promise&&J.common.async===!1)return vQ(J,{code:jQ.invalid_type,expected:EQ.promise,received:J.parsedType}),w8;let G=J.parsedType===EQ.promise?J.data:Promise.resolve(J.data);return qJ(G.then((H)=>{return this._def.type.parseAsync(H,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}Wz.create=(Q,J)=>{return new Wz({type:Q,typeName:CQ.ZodPromise,...o8(J)})};class LW extends W6{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===CQ.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q),H=this._def.effect||null,K={addIssue:(z)=>{if(vQ(G,z),z.fatal)J.abort();else J.dirty()},get path(){return G.path}};if(K.addIssue=K.addIssue.bind(K),H.type==="preprocess"){let z=H.transform(G.data,K);if(G.common.async)return Promise.resolve(z).then(async(q)=>{if(J.value==="aborted")return w8;let F=await this._def.schema._parseAsync({data:q,path:G.path,parent:G});if(F.status==="aborted")return w8;if(F.status==="dirty")return Qz(F.value);if(J.value==="dirty")return Qz(F.value);return F});else{if(J.value==="aborted")return w8;let q=this._def.schema._parseSync({data:z,path:G.path,parent:G});if(q.status==="aborted")return w8;if(q.status==="dirty")return Qz(q.value);if(J.value==="dirty")return Qz(q.value);return q}}if(H.type==="refinement"){let z=(q)=>{let F=H.refinement(q,K);if(G.common.async)return Promise.resolve(F);if(F instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return q};if(G.common.async===!1){let q=this._def.schema._parseSync({data:G.data,path:G.path,parent:G});if(q.status==="aborted")return w8;if(q.status==="dirty")J.dirty();return z(q.value),{status:J.value,value:q.value}}else return this._def.schema._parseAsync({data:G.data,path:G.path,parent:G}).then((q)=>{if(q.status==="aborted")return w8;if(q.status==="dirty")J.dirty();return z(q.value).then(()=>{return{status:J.value,value:q.value}})})}if(H.type==="transform")if(G.common.async===!1){let z=this._def.schema._parseSync({data:G.data,path:G.path,parent:G});if(!D3(z))return w8;let q=H.transform(z.value,K);if(q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:q}}else return this._def.schema._parseAsync({data:G.data,path:G.path,parent:G}).then((z)=>{if(!D3(z))return w8;return Promise.resolve(H.transform(z.value,K)).then((q)=>({status:J.value,value:q}))});$6.assertNever(H)}}LW.create=(Q,J,G)=>{return new LW({schema:Q,typeName:CQ.ZodEffects,effect:J,...o8(G)})};LW.createWithPreprocess=(Q,J,G)=>{return new LW({schema:J,effect:{type:"preprocess",transform:Q},typeName:CQ.ZodEffects,...o8(G)})};class MW extends W6{_parse(Q){if(this._getType(Q)===EQ.undefined)return qJ(void 0);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}MW.create=(Q,J)=>{return new MW({innerType:Q,typeName:CQ.ZodOptional,...o8(J)})};class v4 extends W6{_parse(Q){if(this._getType(Q)===EQ.null)return qJ(null);return this._def.innerType._parse(Q)}unwrap(){return this._def.innerType}}v4.create=(Q,J)=>{return new v4({innerType:Q,typeName:CQ.ZodNullable,...o8(J)})};class CU extends W6{_parse(Q){let{ctx:J}=this._processInputParams(Q),G=J.data;if(J.parsedType===EQ.undefined)G=this._def.defaultValue();return this._def.innerType._parse({data:G,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}CU.create=(Q,J)=>{return new CU({innerType:Q,typeName:CQ.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...o8(J)})};class IU extends W6{_parse(Q){let{ctx:J}=this._processInputParams(Q),G={...J,common:{...J.common,issues:[]}},H=this._def.innerType._parse({data:G.data,path:G.path,parent:{...G}});if($U(H))return H.then((K)=>{return{status:"valid",value:K.status==="valid"?K.value:this._def.catchValue({get error(){return new AY(G.common.issues)},input:G.data})}});else return{status:"valid",value:H.status==="valid"?H.value:this._def.catchValue({get error(){return new AY(G.common.issues)},input:G.data})}}removeCatch(){return this._def.innerType}}IU.create=(Q,J)=>{return new IU({innerType:Q,typeName:CQ.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...o8(J)})};class HN extends W6{_parse(Q){if(this._getType(Q)!==EQ.nan){let G=this._getOrReturnCtx(Q);return vQ(G,{code:jQ.invalid_type,expected:EQ.nan,received:G.parsedType}),w8}return{status:"valid",value:Q.data}}}HN.create=(Q)=>{return new HN({typeName:CQ.ZodNaN,...o8(Q)})};var F88=Symbol("zod_brand");class Vx extends W6{_parse(Q){let{ctx:J}=this._processInputParams(Q),G=J.data;return this._def.type._parse({data:G,path:J.path,parent:J})}unwrap(){return this._def.type}}class BN extends W6{_parse(Q){let{status:J,ctx:G}=this._processInputParams(Q);if(G.common.async)return(async()=>{let K=await this._def.in._parseAsync({data:G.data,path:G.path,parent:G});if(K.status==="aborted")return w8;if(K.status==="dirty")return J.dirty(),Qz(K.value);else return this._def.out._parseAsync({data:K.value,path:G.path,parent:G})})();else{let H=this._def.in._parseSync({data:G.data,path:G.path,parent:G});if(H.status==="aborted")return w8;if(H.status==="dirty")return J.dirty(),{status:"dirty",value:H.value};else return this._def.out._parseSync({data:H.value,path:G.path,parent:G})}}static create(Q,J){return new BN({in:Q,out:J,typeName:CQ.ZodPipeline})}}class RU extends W6{_parse(Q){let J=this._def.innerType._parse(Q),G=(H)=>{if(D3(H))H.value=Object.freeze(H.value);return H};return $U(J)?J.then((H)=>G(H)):G(J)}unwrap(){return this._def.innerType}}RU.create=(Q,J)=>{return new RU({innerType:Q,typeName:CQ.ZodReadonly,...o8(J)})};var D88={object:Q7.lazycreate},CQ;(function(Q){Q.ZodString="ZodString",Q.ZodNumber="ZodNumber",Q.ZodNaN="ZodNaN",Q.ZodBigInt="ZodBigInt",Q.ZodBoolean="ZodBoolean",Q.ZodDate="ZodDate",Q.ZodSymbol="ZodSymbol",Q.ZodUndefined="ZodUndefined",Q.ZodNull="ZodNull",Q.ZodAny="ZodAny",Q.ZodUnknown="ZodUnknown",Q.ZodNever="ZodNever",Q.ZodVoid="ZodVoid",Q.ZodArray="ZodArray",Q.ZodObject="ZodObject",Q.ZodUnion="ZodUnion",Q.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Q.ZodIntersection="ZodIntersection",Q.ZodTuple="ZodTuple",Q.ZodRecord="ZodRecord",Q.ZodMap="ZodMap",Q.ZodSet="ZodSet",Q.ZodFunction="ZodFunction",Q.ZodLazy="ZodLazy",Q.ZodLiteral="ZodLiteral",Q.ZodEnum="ZodEnum",Q.ZodEffects="ZodEffects",Q.ZodNativeEnum="ZodNativeEnum",Q.ZodOptional="ZodOptional",Q.ZodNullable="ZodNullable",Q.ZodDefault="ZodDefault",Q.ZodCatch="ZodCatch",Q.ZodPromise="ZodPromise",Q.ZodBranded="ZodBranded",Q.ZodPipeline="ZodPipeline",Q.ZodReadonly="ZodReadonly"})(CQ||(CQ={}));var M88=D5.create,L88=Jz.create,O88=HN.create,P88=Yz.create,N88=QN.create,j88=FU.create,C88=XN.create,I88=DU.create,R88=MU.create,w88=JN.create,E88=M3.create,S88=M5.create,T88=YN.create,k88=DW.create,aK0=Q7.create,y88=Q7.strictCreate,v88=LU.create,x88=zx.create,b88=OU.create,g88=L5.create,h88=GN.create,_88=WN.create,f88=Gz.create,m88=ZU.create,u88=PU.create,p88=NU.create,l88=L3.create,d88=jU.create,c88=Wz.create,i88=LW.create,o88=MW.create,n88=v4.create,a88=LW.createWithPreprocess,s88=BN.create;var t88=Object.freeze({status:"aborted"});function BQ(Q,J,G){function H(F,D){if(!F._zod)Object.defineProperty(F,"_zod",{value:{def:D,constr:q,traits:new Set},enumerable:!1});if(F._zod.traits.has(Q))return;F._zod.traits.add(Q),J(F,D);let V=q.prototype,O=Object.keys(V);for(let P=0;P<O.length;P++){let N=O[P];if(!(N in F))F[N]=V[N].bind(F)}}let K=G?.Parent??Object;class z extends K{}Object.defineProperty(z,"name",{value:Q});function q(F){var D;let V=G?.Parent?new z:this;H(V,F),(D=V._zod).deferred??(D.deferred=[]);for(let O of V._zod.deferred)O();return V}return Object.defineProperty(q,"init",{value:H}),Object.defineProperty(q,Symbol.hasInstance,{value:(F)=>{if(G?.Parent&&F instanceof G.Parent)return!0;return F?._zod?.traits?.has(Q)}}),Object.defineProperty(q,"name",{value:Q}),q}var e88=Symbol("zod_brand");class O5 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class wU extends Error{constructor(Q){super(`Encountered unidirectional transform during encode: ${Q}`);this.name="ZodEncodeError"}}var AN={};function hY(Q){if(Q)Object.assign(AN,Q);return AN}var I6={};UD(I6,{unwrapMessage:()=>EU,uint8ArrayToHex:()=>GQQ,uint8ArrayToBase64url:()=>JQQ,uint8ArrayToBase64:()=>Bz0,stringifyPrimitive:()=>qN,slugify:()=>Zx,shallowClone:()=>Mx,safeExtend:()=>Jz0,required:()=>Gz0,randomString:()=>a0Q,propertyKeyTypes:()=>jx,promiseAllObject:()=>n0Q,primitiveTypes:()=>rK0,prefixIssues:()=>j5,pick:()=>eK0,partial:()=>Yz0,parsedType:()=>ug,optionalKeys:()=>Rx,omit:()=>Qz0,objectClone:()=>c0Q,numKeys:()=>s0Q,nullish:()=>TU,normalizeParams:()=>Z8,mergeDefs:()=>P5,merge:()=>e0Q,jsonStringifyReplacer:()=>Hz,joinValues:()=>KN,issue:()=>Az,isPlainObject:()=>b4,isObject:()=>O3,hexToUint8Array:()=>YQQ,getSizableOrigin:()=>Wz0,getParsedType:()=>r0Q,getLengthableOrigin:()=>yU,getEnumValues:()=>SU,getElementAtPath:()=>o0Q,floatSafeRemainder:()=>Ux,finalizeIssue:()=>DG,extend:()=>Xz0,escapeRegex:()=>N5,esc:()=>zN,defineLazy:()=>k6,createTransparentProxy:()=>t0Q,cloneDef:()=>i0Q,clone:()=>KY,cleanRegex:()=>kU,cleanEnum:()=>QQQ,captureStackTrace:()=>VN,cached:()=>Bz,base64urlToUint8Array:()=>XQQ,base64ToUint8Array:()=>Hz0,assignProp:()=>x4,assertNotEqual:()=>u0Q,assertNever:()=>l0Q,assertIs:()=>p0Q,assertEqual:()=>m0Q,assert:()=>d0Q,allowsEval:()=>Fx,aborted:()=>g4,NUMBER_FORMAT_RANGES:()=>Pb,Class:()=>Az0,BIGINT_FORMAT_RANGES:()=>tK0});function m0Q(Q){return Q}function u0Q(Q){return Q}function p0Q(Q){}function l0Q(Q){throw Error("Unexpected value in exhaustive check")}function d0Q(Q){}function SU(Q){let J=Object.values(Q).filter((H)=>typeof H==="number");return Object.entries(Q).filter(([H,K])=>J.indexOf(+H)===-1).map(([H,K])=>K)}function KN(Q,J="|"){return Q.map((G)=>qN(G)).join(J)}function Hz(Q,J){if(typeof J==="bigint")return J.toString();return J}function Bz(Q){return{get value(){{let G=Q();return Object.defineProperty(this,"value",{value:G}),G}throw Error("cached value already set")}}}function TU(Q){return Q===null||Q===void 0}function kU(Q){let J=Q.startsWith("^")?1:0,G=Q.endsWith("$")?Q.length-1:Q.length;return Q.slice(J,G)}function Ux(Q,J){let G=(Q.toString().split(".")[1]||"").length,H=J.toString(),K=(H.split(".")[1]||"").length;if(K===0&&/\d?e-\d?/.test(H)){let D=H.match(/\d?e-(\d?)/);if(D?.[1])K=Number.parseInt(D[1])}let z=G>K?G:K,q=Number.parseInt(Q.toFixed(z).replace(".","")),F=Number.parseInt(J.toFixed(z).replace(".",""));return q%F/10**z}var sK0=Symbol("evaluating");function k6(Q,J,G){let H=void 0;Object.defineProperty(Q,J,{get(){if(H===sK0)return;if(H===void 0)H=sK0,H=G();return H},set(K){Object.defineProperty(Q,J,{value:K})},configurable:!0})}function c0Q(Q){return Object.create(Object.getPrototypeOf(Q),Object.getOwnPropertyDescriptors(Q))}function x4(Q,J,G){Object.defineProperty(Q,J,{value:G,writable:!0,enumerable:!0,configurable:!0})}function P5(...Q){let J={};for(let G of Q){let H=Object.getOwnPropertyDescriptors(G);Object.assign(J,H)}return Object.defineProperties({},J)}function i0Q(Q){return P5(Q._zod.def)}function o0Q(Q,J){if(!J)return Q;return J.reduce((G,H)=>G?.[H],Q)}function n0Q(Q){let J=Object.keys(Q),G=J.map((H)=>Q[H]);return Promise.all(G).then((H)=>{let K={};for(let z=0;z<J.length;z++)K[J[z]]=H[z];return K})}function a0Q(Q=10){let G="";for(let H=0;H<Q;H++)G+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return G}function zN(Q){return JSON.stringify(Q)}function Zx(Q){return Q.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var VN="captureStackTrace"in Error?Error.captureStackTrace:(...Q)=>{};function O3(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}var Fx=Bz(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(Q){return!1}});function b4(Q){if(O3(Q)===!1)return!1;let J=Q.constructor;if(J===void 0)return!0;if(typeof J!=="function")return!0;let G=J.prototype;if(O3(G)===!1)return!1;if(Object.prototype.hasOwnProperty.call(G,"isPrototypeOf")===!1)return!1;return!0}function Mx(Q){if(b4(Q))return{...Q};if(Array.isArray(Q))return[...Q];return Q}function s0Q(Q){let J=0;for(let G in Q)if(Object.prototype.hasOwnProperty.call(Q,G))J++;return J}var r0Q=(Q)=>{let J=typeof Q;switch(J){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(Q)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(Q))return"array";if(Q===null)return"null";if(Q.then&&typeof Q.then==="function"&&Q.catch&&typeof Q.catch==="function")return"promise";if(typeof Map<"u"&&Q instanceof Map)return"map";if(typeof Set<"u"&&Q instanceof Set)return"set";if(typeof Date<"u"&&Q instanceof Date)return"date";if(typeof File<"u"&&Q instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${J}`)}},jx=new Set(["string","number","symbol"]),rK0=new Set(["string","number","bigint","boolean","symbol","undefined"]);function N5(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KY(Q,J,G){let H=new Q._zod.constr(J??Q._zod.def);if(!J||G?.parent)H._zod.parent=Q;return H}function Z8(Q){let J=Q;if(!J)return{};if(typeof J==="string")return{error:()=>J};if(J?.message!==void 0){if(J?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");J.error=J.message}if(delete J.message,typeof J.error==="string")return{...J,error:()=>J.error};return J}function t0Q(Q){let J;return new Proxy({},{get(G,H,K){return J??(J=Q()),Reflect.get(J,H,K)},set(G,H,K,z){return J??(J=Q()),Reflect.set(J,H,K,z)},has(G,H){return J??(J=Q()),Reflect.has(J,H)},deleteProperty(G,H){return J??(J=Q()),Reflect.deleteProperty(J,H)},ownKeys(G){return J??(J=Q()),Reflect.ownKeys(J)},getOwnPropertyDescriptor(G,H){return J??(J=Q()),Reflect.getOwnPropertyDescriptor(J,H)},defineProperty(G,H,K){return J??(J=Q()),Reflect.defineProperty(J,H,K)}})}function qN(Q){if(typeof Q==="bigint")return Q.toString()+"n";if(typeof Q==="string")return`"${Q}"`;return`${Q}`}function Rx(Q){return Object.keys(Q).filter((J)=>{return Q[J]._zod.optin==="optional"&&Q[J]._zod.optout==="optional"})}var Pb={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tK0={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function eK0(Q,J){let G=Q._zod.def,H=G.checks;if(H&&H.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let z=P5(Q._zod.def,{get shape(){let q={};for(let F in J){if(!(F in G.shape))throw Error(`Unrecognized key: "${F}"`);if(!J[F])continue;q[F]=G.shape[F]}return x4(this,"shape",q),q},checks:[]});return KY(Q,z)}function Qz0(Q,J){let G=Q._zod.def,H=G.checks;if(H&&H.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let z=P5(Q._zod.def,{get shape(){let q={...Q._zod.def.shape};for(let F in J){if(!(F in G.shape))throw Error(`Unrecognized key: "${F}"`);if(!J[F])continue;delete q[F]}return x4(this,"shape",q),q},checks:[]});return KY(Q,z)}function Xz0(Q,J){if(!b4(J))throw Error("Invalid input to extend: expected a plain object");let G=Q._zod.def.checks;if(G&&G.length>0){let z=Q._zod.def.shape;for(let q in J)if(Object.getOwnPropertyDescriptor(z,q)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let K=P5(Q._zod.def,{get shape(){let z={...Q._zod.def.shape,...J};return x4(this,"shape",z),z}});return KY(Q,K)}function Jz0(Q,J){if(!b4(J))throw Error("Invalid input to safeExtend: expected a plain object");let G=P5(Q._zod.def,{get shape(){let H={...Q._zod.def.shape,...J};return x4(this,"shape",H),H}});return KY(Q,G)}function e0Q(Q,J){let G=P5(Q._zod.def,{get shape(){let H={...Q._zod.def.shape,...J._zod.def.shape};return x4(this,"shape",H),H},get catchall(){return J._zod.def.catchall},checks:[]});return KY(Q,G)}function Yz0(Q,J,G){let K=J._zod.def.checks;if(K&&K.length>0)throw Error(".partial() cannot be used on object schemas containing refinements");let q=P5(J._zod.def,{get shape(){let F=J._zod.def.shape,D={...F};if(G)for(let V in G){if(!(V in F))throw Error(`Unrecognized key: "${V}"`);if(!G[V])continue;D[V]=Q?new Q({type:"optional",innerType:F[V]}):F[V]}else for(let V in F)D[V]=Q?new Q({type:"optional",innerType:F[V]}):F[V];return x4(this,"shape",D),D},checks:[]});return KY(J,q)}function Gz0(Q,J,G){let H=P5(J._zod.def,{get shape(){let K=J._zod.def.shape,z={...K};if(G)for(let q in G){if(!(q in z))throw Error(`Unrecognized key: "${q}"`);if(!G[q])continue;z[q]=new Q({type:"nonoptional",innerType:K[q]})}else for(let q in K)z[q]=new Q({type:"nonoptional",innerType:K[q]});return x4(this,"shape",z),z}});return KY(J,H)}function g4(Q,J=0){if(Q.aborted===!0)return!0;for(let G=J;G<Q.issues.length;G++)if(Q.issues[G]?.continue!==!0)return!0;return!1}function j5(Q,J){return J.map((G)=>{var H;return(H=G).path??(H.path=[]),G.path.unshift(Q),G})}function EU(Q){return typeof Q==="string"?Q:Q?.message}function DG(Q,J,G){let H={...Q,path:Q.path??[]};if(!Q.message){let K=EU(Q.inst?._zod.def?.error?.(Q))??EU(J?.error?.(Q))??EU(G.customError?.(Q))??EU(G.localeError?.(Q))??"Invalid input";H.message=K}if(delete H.inst,delete H.continue,!J?.reportInput)delete H.input;return H}function Wz0(Q){if(Q instanceof Set)return"set";if(Q instanceof Map)return"map";if(Q instanceof File)return"file";return"unknown"}function yU(Q){if(Array.isArray(Q))return"array";if(typeof Q==="string")return"string";return"unknown"}function ug(Q){let J=typeof Q;switch(J){case"number":return Number.isNaN(Q)?"nan":"number";case"object":{if(Q===null)return"null";if(Array.isArray(Q))return"array";let G=Q;if(G&&Object.getPrototypeOf(G)!==Object.prototype&&"constructor"in G&&G.constructor)return G.constructor.name}}return J}function Az(...Q){let[J,G,H]=Q;if(typeof J==="string")return{message:J,code:"custom",input:G,inst:H};return{...J}}function QQQ(Q){return Object.entries(Q).filter(([J,G])=>{return Number.isNaN(Number.parseInt(J,10))}).map((J)=>J[1])}function Hz0(Q){let J=atob(Q),G=new Uint8Array(J.length);for(let H=0;H<J.length;H++)G[H]=J.charCodeAt(H);return G}function Bz0(Q){let J="";for(let G=0;G<Q.length;G++)J+=String.fromCharCode(Q[G]);return btoa(J)}function XQQ(Q){let J=Q.replace(/-/g,"+").replace(/_/g,"/"),G="=".repeat((4-J.length%4)%4);return Hz0(J+G)}function JQQ(Q){return Bz0(Q).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function YQQ(Q){let J=Q.replace(/^0x/,"");if(J.length%2!==0)throw Error("Invalid hex string length");let G=new Uint8Array(J.length/2);for(let H=0;H<J.length;H+=2)G[H/2]=Number.parseInt(J.slice(H,H+2),16);return G}function GQQ(Q){return Array.from(Q).map((J)=>J.toString(16).padStart(2,"0")).join("")}class Az0{constructor(...Q){}}var Kz0=(Q,J)=>{Q.name="$ZodError",Object.defineProperty(Q,"_zod",{value:Q._zod,enumerable:!1}),Object.defineProperty(Q,"issues",{value:J,enumerable:!1}),Q.message=JSON.stringify(J,Hz,2),Object.defineProperty(Q,"toString",{value:()=>Q.message,enumerable:!1})},UN=BQ("$ZodError",Kz0),vU=BQ("$ZodError",Kz0,{Parent:Error});function zz0(Q,J=(G)=>G.message){let G={},H=[];for(let K of Q.issues)if(K.path.length>0)G[K.path[0]]=G[K.path[0]]||[],G[K.path[0]].push(J(K));else H.push(J(K));return{formErrors:H,fieldErrors:G}}function Vz0(Q,J=(G)=>G.message){let G={_errors:[]},H=(K)=>{for(let z of K.issues)if(z.code==="invalid_union"&&z.errors.length)z.errors.map((q)=>H({issues:q}));else if(z.code==="invalid_key")H({issues:z.issues});else if(z.code==="invalid_element")H({issues:z.issues});else if(z.path.length===0)G._errors.push(J(z));else{let q=G,F=0;while(F<z.path.length){let D=z.path[F];if(F!==z.path.length-1)q[D]=q[D]||{_errors:[]};else q[D]=q[D]||{_errors:[]},q[D]._errors.push(J(z));q=q[D],F++}}};return H(Q),G}var xU=(Q)=>(J,G,H,K)=>{let z=H?Object.assign(H,{async:!1}):{async:!1},q=J._zod.run({value:G,issues:[]},z);if(q instanceof Promise)throw new O5;if(q.issues.length){let F=new(K?.Err??Q)(q.issues.map((D)=>DG(D,z,hY())));throw VN(F,K?.callee),F}return q.value},$N=xU(vU),bU=(Q)=>async(J,G,H,K)=>{let z=H?Object.assign(H,{async:!0}):{async:!0},q=J._zod.run({value:G,issues:[]},z);if(q instanceof Promise)q=await q;if(q.issues.length){let F=new(K?.Err??Q)(q.issues.map((D)=>DG(D,z,hY())));throw VN(F,K?.callee),F}return q.value},ZN=bU(vU),gU=(Q)=>(J,G,H)=>{let K=H?{...H,async:!1}:{async:!1},z=J._zod.run({value:G,issues:[]},K);if(z instanceof Promise)throw new O5;return z.issues.length?{success:!1,error:new(Q??UN)(z.issues.map((q)=>DG(q,K,hY())))}:{success:!0,data:z.value}},P3=gU(vU),hU=(Q)=>async(J,G,H)=>{let K=H?Object.assign(H,{async:!0}):{async:!0},z=J._zod.run({value:G,issues:[]},K);if(z instanceof Promise)z=await z;return z.issues.length?{success:!1,error:new Q(z.issues.map((q)=>DG(q,K,hY())))}:{success:!0,data:z.value}},N3=hU(vU),qz0=(Q)=>(J,G,H)=>{let K=H?Object.assign(H,{direction:"backward"}):{direction:"backward"};return xU(Q)(J,G,K)};var Uz0=(Q)=>(J,G,H)=>{return xU(Q)(J,G,H)};var $z0=(Q)=>async(J,G,H)=>{let K=H?Object.assign(H,{direction:"backward"}):{direction:"backward"};return bU(Q)(J,G,K)};var Zz0=(Q)=>async(J,G,H)=>{return bU(Q)(J,G,H)};var Fz0=(Q)=>(J,G,H)=>{let K=H?Object.assign(H,{direction:"backward"}):{direction:"backward"};return gU(Q)(J,G,K)};var Dz0=(Q)=>(J,G,H)=>{return gU(Q)(J,G,H)};var Mz0=(Q)=>async(J,G,H)=>{let K=H?Object.assign(H,{direction:"backward"}):{direction:"backward"};return hU(Q)(J,G,K)};var Lz0=(Q)=>async(J,G,H)=>{return hU(Q)(J,G,H)};var Oz0=/^[cC][^\s-]{8,}$/,Pz0=/^[0-9a-z]+$/,Nz0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,jz0=/^[0-9a-vA-V]{20}$/,Cz0=/^[A-Za-z0-9]{27}$/,Iz0=/^[a-zA-Z0-9_-]{21}$/,Rz0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var wz0=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,up=(Q)=>{if(!Q)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Q}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var Ez0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var HQQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Sz0(){return new RegExp(HQQ,"u")}var Tz0=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,kz0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var yz0=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,vz0=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,xz0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Sl=/^[A-Za-z0-9_-]*$/;var bz0=/^\+[1-9]\d{6,14}$/,gz0="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",hz0=new RegExp(`^${gz0}$`);function _z0(Q){return typeof Q.precision==="number"?Q.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":Q.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${Q.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function fz0(Q){return new RegExp(`^${_z0(Q)}$`)}function mz0(Q){let J=_z0({precision:Q.precision}),G=["Z"];if(Q.local)G.push("");if(Q.offset)G.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let H=`${J}(?:${G.join("|")})`;return new RegExp(`^${gz0}T(?:${H})$`)}var uz0=(Q)=>{let J=Q?`[\\s\\S]{${Q?.minimum??0},${Q?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${J}$`)};var pz0=/^-?\d+$/,FN=/^-?\d+(?:\.\d+)?$/,lz0=/^(?:true|false)$/i,dz0=/^null$/i;var cz0=/^[^A-Z]*$/,iz0=/^[^a-z]*$/;var s7=BQ("$ZodCheck",(Q,J)=>{var G;Q._zod??(Q._zod={}),Q._zod.def=J,(G=Q._zod).onattach??(G.onattach=[])}),oz0={number:"number",bigint:"bigint",object:"date"},Bd=BQ("$ZodCheckLessThan",(Q,J)=>{s7.init(Q,J);let G=oz0[typeof J.value];Q._zod.onattach.push((H)=>{let K=H._zod.bag,z=(J.inclusive?K.maximum:K.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(J.value<z)if(J.inclusive)K.maximum=J.value;else K.exclusiveMaximum=J.value}),Q._zod.check=(H)=>{if(J.inclusive?H.value<=J.value:H.value<J.value)return;H.issues.push({origin:G,code:"too_big",maximum:typeof J.value==="object"?J.value.getTime():J.value,input:H.value,inclusive:J.inclusive,inst:Q,continue:!J.abort})}}),Ad=BQ("$ZodCheckGreaterThan",(Q,J)=>{s7.init(Q,J);let G=oz0[typeof J.value];Q._zod.onattach.push((H)=>{let K=H._zod.bag,z=(J.inclusive?K.minimum:K.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(J.value>z)if(J.inclusive)K.minimum=J.value;else K.exclusiveMinimum=J.value}),Q._zod.check=(H)=>{if(J.inclusive?H.value>=J.value:H.value>J.value)return;H.issues.push({origin:G,code:"too_small",minimum:typeof J.value==="object"?J.value.getTime():J.value,input:H.value,inclusive:J.inclusive,inst:Q,continue:!J.abort})}}),nz0=BQ("$ZodCheckMultipleOf",(Q,J)=>{s7.init(Q,J),Q._zod.onattach.push((G)=>{var H;(H=G._zod.bag).multipleOf??(H.multipleOf=J.value)}),Q._zod.check=(G)=>{if(typeof G.value!==typeof J.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof G.value==="bigint"?G.value%J.value===BigInt(0):Ux(G.value,J.value)===0)return;G.issues.push({origin:typeof G.value,code:"not_multiple_of",divisor:J.value,input:G.value,inst:Q,continue:!J.abort})}}),az0=BQ("$ZodCheckNumberFormat",(Q,J)=>{s7.init(Q,J),J.format=J.format||"float64";let G=J.format?.includes("int"),H=G?"int":"number",[K,z]=Pb[J.format];Q._zod.onattach.push((q)=>{let F=q._zod.bag;if(F.format=J.format,F.minimum=K,F.maximum=z,G)F.pattern=pz0}),Q._zod.check=(q)=>{let F=q.value;if(G){if(!Number.isInteger(F)){q.issues.push({expected:H,format:J.format,code:"invalid_type",continue:!1,input:F,inst:Q});return}if(!Number.isSafeInteger(F)){if(F>0)q.issues.push({input:F,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:H,inclusive:!0,continue:!J.abort});else q.issues.push({input:F,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:Q,origin:H,inclusive:!0,continue:!J.abort});return}}if(F<K)q.issues.push({origin:"number",input:F,code:"too_small",minimum:K,inclusive:!0,inst:Q,continue:!J.abort});if(F>z)q.issues.push({origin:"number",input:F,code:"too_big",maximum:z,inclusive:!0,inst:Q,continue:!J.abort})}});var sz0=BQ("$ZodCheckMaxLength",(Q,J)=>{var G;s7.init(Q,J),(G=Q._zod.def).when??(G.when=(H)=>{let K=H.value;return!TU(K)&&K.length!==void 0}),Q._zod.onattach.push((H)=>{let K=H._zod.bag.maximum??Number.POSITIVE_INFINITY;if(J.maximum<K)H._zod.bag.maximum=J.maximum}),Q._zod.check=(H)=>{let K=H.value;if(K.length<=J.maximum)return;let q=yU(K);H.issues.push({origin:q,code:"too_big",maximum:J.maximum,inclusive:!0,input:K,inst:Q,continue:!J.abort})}}),rz0=BQ("$ZodCheckMinLength",(Q,J)=>{var G;s7.init(Q,J),(G=Q._zod.def).when??(G.when=(H)=>{let K=H.value;return!TU(K)&&K.length!==void 0}),Q._zod.onattach.push((H)=>{let K=H._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(J.minimum>K)H._zod.bag.minimum=J.minimum}),Q._zod.check=(H)=>{let K=H.value;if(K.length>=J.minimum)return;let q=yU(K);H.issues.push({origin:q,code:"too_small",minimum:J.minimum,inclusive:!0,input:K,inst:Q,continue:!J.abort})}}),tz0=BQ("$ZodCheckLengthEquals",(Q,J)=>{var G;s7.init(Q,J),(G=Q._zod.def).when??(G.when=(H)=>{let K=H.value;return!TU(K)&&K.length!==void 0}),Q._zod.onattach.push((H)=>{let K=H._zod.bag;K.minimum=J.length,K.maximum=J.length,K.length=J.length}),Q._zod.check=(H)=>{let K=H.value,z=K.length;if(z===J.length)return;let q=yU(K),F=z>J.length;H.issues.push({origin:q,...F?{code:"too_big",maximum:J.length}:{code:"too_small",minimum:J.length},inclusive:!0,exact:!0,input:H.value,inst:Q,continue:!J.abort})}}),fU=BQ("$ZodCheckStringFormat",(Q,J)=>{var G,H;if(s7.init(Q,J),Q._zod.onattach.push((K)=>{let z=K._zod.bag;if(z.format=J.format,J.pattern)z.patterns??(z.patterns=new Set),z.patterns.add(J.pattern)}),J.pattern)(G=Q._zod).check??(G.check=(K)=>{if(J.pattern.lastIndex=0,J.pattern.test(K.value))return;K.issues.push({origin:"string",code:"invalid_format",format:J.format,input:K.value,...J.pattern?{pattern:J.pattern.toString()}:{},inst:Q,continue:!J.abort})});else(H=Q._zod).check??(H.check=()=>{})}),ez0=BQ("$ZodCheckRegex",(Q,J)=>{fU.init(Q,J),Q._zod.check=(G)=>{if(J.pattern.lastIndex=0,J.pattern.test(G.value))return;G.issues.push({origin:"string",code:"invalid_format",format:"regex",input:G.value,pattern:J.pattern.toString(),inst:Q,continue:!J.abort})}}),QV0=BQ("$ZodCheckLowerCase",(Q,J)=>{J.pattern??(J.pattern=cz0),fU.init(Q,J)}),XV0=BQ("$ZodCheckUpperCase",(Q,J)=>{J.pattern??(J.pattern=iz0),fU.init(Q,J)}),JV0=BQ("$ZodCheckIncludes",(Q,J)=>{s7.init(Q,J);let G=N5(J.includes),H=new RegExp(typeof J.position==="number"?`^.{${J.position}}${G}`:G);J.pattern=H,Q._zod.onattach.push((K)=>{let z=K._zod.bag;z.patterns??(z.patterns=new Set),z.patterns.add(H)}),Q._zod.check=(K)=>{if(K.value.includes(J.includes,J.position))return;K.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:J.includes,input:K.value,inst:Q,continue:!J.abort})}}),YV0=BQ("$ZodCheckStartsWith",(Q,J)=>{s7.init(Q,J);let G=new RegExp(`^${N5(J.prefix)}.*`);J.pattern??(J.pattern=G),Q._zod.onattach.push((H)=>{let K=H._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(G)}),Q._zod.check=(H)=>{if(H.value.startsWith(J.prefix))return;H.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:J.prefix,input:H.value,inst:Q,continue:!J.abort})}}),GV0=BQ("$ZodCheckEndsWith",(Q,J)=>{s7.init(Q,J);let G=new RegExp(`.*${N5(J.suffix)}$`);J.pattern??(J.pattern=G),Q._zod.onattach.push((H)=>{let K=H._zod.bag;K.patterns??(K.patterns=new Set),K.patterns.add(G)}),Q._zod.check=(H)=>{if(H.value.endsWith(J.suffix))return;H.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:J.suffix,input:H.value,inst:Q,continue:!J.abort})}});var WV0=BQ("$ZodCheckOverwrite",(Q,J)=>{s7.init(Q,J),Q._zod.check=(G)=>{G.value=J.tx(G.value)}});class zd{constructor(Q=[]){if(this.content=[],this.indent=0,this)this.args=Q}indented(Q){this.indent+=1,Q(this),this.indent-=1}write(Q){if(typeof Q==="function"){Q(this,{execution:"sync"}),Q(this,{execution:"async"});return}let G=Q.split(`
`).filter((z)=>z),H=Math.min(...G.map((z)=>z.length-z.trimStart().length)),K=G.map((z)=>z.slice(H)).map((z)=>" ".repeat(this.indent*2)+z);for(let z of K)this.content.push(z)}compile(){let Q=Function,J=this?.args,H=[...(this?.content??[""]).map((K)=>` ${K}`)];return new Q(...J,H.join(`
`))}}var BV0={major:4,minor:3,patch:6};var q9=BQ("$ZodType",(Q,J)=>{var G;Q??(Q={}),Q._zod.def=J,Q._zod.bag=Q._zod.bag||{},Q._zod.version=BV0;let H=[...Q._zod.def.checks??[]];if(Q._zod.traits.has("$ZodCheck"))H.unshift(Q);for(let K of H)for(let z of K._zod.onattach)z(Q);if(H.length===0)(G=Q._zod).deferred??(G.deferred=[]),Q._zod.deferred?.push(()=>{Q._zod.run=Q._zod.parse});else{let K=(q,F,D)=>{let V=g4(q),O;for(let P of F){if(P._zod.def.when){if(!P._zod.def.when(q))continue}else if(V)continue;let N=q.issues.length,I=P._zod.check(q);if(I instanceof Promise&&D?.async===!1)throw new O5;if(O||I instanceof Promise)O=(O??Promise.resolve()).then(async()=>{if(await I,q.issues.length===N)return;if(!V)V=g4(q,N)});else{if(q.issues.length===N)continue;if(!V)V=g4(q,N)}}if(O)return O.then(()=>{return q});return q},z=(q,F,D)=>{if(g4(q))return q.aborted=!0,q;let V=K(F,H,D);if(V instanceof Promise){if(D.async===!1)throw new O5;return V.then((O)=>Q._zod.parse(O,D))}return Q._zod.parse(V,D)};Q._zod.run=(q,F)=>{if(F.skipChecks)return Q._zod.parse(q,F);if(F.direction==="backward"){let V=Q._zod.parse({value:q.value,issues:[]},{...F,skipChecks:!0});if(V instanceof Promise)return V.then((O)=>{return z(O,q,F)});return z(V,q,F)}let D=Q._zod.parse(q,F);if(D instanceof Promise){if(F.async===!1)throw new O5;return D.then((V)=>K(V,H,F))}return K(D,H,F)}}k6(Q,"~standard",()=>({validate:(K)=>{try{let z=P3(Q,K);return z.success?{value:z.data}:{issues:z.error?.issues}}catch(z){return N3(Q,K).then((q)=>q.success?{value:q.data}:{issues:q.error?.issues})}},vendor:"zod",version:1}))}),mU=BQ("$ZodString",(Q,J)=>{q9.init(Q,J),Q._zod.pattern=[...Q?._zod.bag?.patterns??[]].pop()??uz0(Q._zod.bag),Q._zod.parse=(G,H)=>{if(J.coerce)try{G.value=String(G.value)}catch(K){}if(typeof G.value==="string")return G;return G.issues.push({expected:"string",code:"invalid_type",input:G.value,inst:Q}),G}}),L9=BQ("$ZodStringFormat",(Q,J)=>{fU.init(Q,J),mU.init(Q,J)}),$d=BQ("$ZodGUID",(Q,J)=>{J.pattern??(J.pattern=wz0),L9.init(Q,J)}),Dd=BQ("$ZodUUID",(Q,J)=>{if(J.version){let H={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[J.version];if(H===void 0)throw Error(`Invalid UUID version: "${J.version}"`);J.pattern??(J.pattern=up(H))}else J.pattern??(J.pattern=up());L9.init(Q,J)}),Ld=BQ("$ZodEmail",(Q,J)=>{J.pattern??(J.pattern=Ez0),L9.init(Q,J)}),Pd=BQ("$ZodURL",(Q,J)=>{L9.init(Q,J),Q._zod.check=(G)=>{try{let H=G.value.trim(),K=new URL(H);if(J.hostname){if(J.hostname.lastIndex=0,!J.hostname.test(K.hostname))G.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:J.hostname.source,input:G.value,inst:Q,continue:!J.abort})}if(J.protocol){if(J.protocol.lastIndex=0,!J.protocol.test(K.protocol.endsWith(":")?K.protocol.slice(0,-1):K.protocol))G.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:J.protocol.source,input:G.value,inst:Q,continue:!J.abort})}if(J.normalize)G.value=K.href;else G.value=H;return}catch(H){G.issues.push({code:"invalid_format",format:"url",input:G.value,inst:Q,continue:!J.abort})}}}),Nd=BQ("$ZodEmoji",(Q,J)=>{J.pattern??(J.pattern=Sz0()),L9.init(Q,J)}),Id=BQ("$ZodNanoID",(Q,J)=>{J.pattern??(J.pattern=Iz0),L9.init(Q,J)}),wd=BQ("$ZodCUID",(Q,J)=>{J.pattern??(J.pattern=Oz0),L9.init(Q,J)}),Ed=BQ("$ZodCUID2",(Q,J)=>{J.pattern??(J.pattern=Pz0),L9.init(Q,J)}),Sd=BQ("$ZodULID",(Q,J)=>{J.pattern??(J.pattern=Nz0),L9.init(Q,J)}),Td=BQ("$ZodXID",(Q,J)=>{J.pattern??(J.pattern=jz0),L9.init(Q,J)}),yd=BQ("$ZodKSUID",(Q,J)=>{J.pattern??(J.pattern=Cz0),L9.init(Q,J)}),FV0=BQ("$ZodISODateTime",(Q,J)=>{J.pattern??(J.pattern=mz0(J)),L9.init(Q,J)}),DV0=BQ("$ZodISODate",(Q,J)=>{J.pattern??(J.pattern=hz0),L9.init(Q,J)}),MV0=BQ("$ZodISOTime",(Q,J)=>{J.pattern??(J.pattern=fz0(J)),L9.init(Q,J)}),LV0=BQ("$ZodISODuration",(Q,J)=>{J.pattern??(J.pattern=Rz0),L9.init(Q,J)}),vd=BQ("$ZodIPv4",(Q,J)=>{J.pattern??(J.pattern=Tz0),L9.init(Q,J),Q._zod.bag.format="ipv4"}),bd=BQ("$ZodIPv6",(Q,J)=>{J.pattern??(J.pattern=kz0),L9.init(Q,J),Q._zod.bag.format="ipv6",Q._zod.check=(G)=>{try{new URL(`http://[${G.value}]`)}catch{G.issues.push({code:"invalid_format",format:"ipv6",input:G.value,inst:Q,continue:!J.abort})}}});var gd=BQ("$ZodCIDRv4",(Q,J)=>{J.pattern??(J.pattern=yz0),L9.init(Q,J)}),hd=BQ("$ZodCIDRv6",(Q,J)=>{J.pattern??(J.pattern=vz0),L9.init(Q,J),Q._zod.check=(G)=>{let H=G.value.split("/");try{if(H.length!==2)throw Error();let[K,z]=H;if(!z)throw Error();let q=Number(z);if(`${q}`!==z)throw Error();if(q<0||q>128)throw Error();new URL(`http://[${K}]`)}catch{G.issues.push({code:"invalid_format",format:"cidrv6",input:G.value,inst:Q,continue:!J.abort})}}});function OV0(Q){if(Q==="")return!0;if(Q.length%4!==0)return!1;try{return atob(Q),!0}catch{return!1}}var _d=BQ("$ZodBase64",(Q,J)=>{J.pattern??(J.pattern=xz0),L9.init(Q,J),Q._zod.bag.contentEncoding="base64",Q._zod.check=(G)=>{if(OV0(G.value))return;G.issues.push({code:"invalid_format",format:"base64",input:G.value,inst:Q,continue:!J.abort})}});function BQQ(Q){if(!Sl.test(Q))return!1;let J=Q.replace(/[-_]/g,(H)=>H==="-"?"+":"/"),G=J.padEnd(Math.ceil(J.length/4)*4,"=");return OV0(G)}var fd=BQ("$ZodBase64URL",(Q,J)=>{J.pattern??(J.pattern=Sl),L9.init(Q,J),Q._zod.bag.contentEncoding="base64url",Q._zod.check=(G)=>{if(BQQ(G.value))return;G.issues.push({code:"invalid_format",format:"base64url",input:G.value,inst:Q,continue:!J.abort})}}),md=BQ("$ZodE164",(Q,J)=>{J.pattern??(J.pattern=bz0),L9.init(Q,J)});function AQQ(Q,J=null){try{let G=Q.split(".");if(G.length!==3)return!1;let[H]=G;if(!H)return!1;let K=JSON.parse(atob(H));if("typ"in K&&K?.typ!=="JWT")return!1;if(!K.alg)return!1;if(J&&(!("alg"in K)||K.alg!==J))return!1;return!0}catch{return!1}}var ud=BQ("$ZodJWT",(Q,J)=>{L9.init(Q,J),Q._zod.check=(G)=>{if(AQQ(G.value,J.alg))return;G.issues.push({code:"invalid_format",format:"jwt",input:G.value,inst:Q,continue:!J.abort})}});var LN=BQ("$ZodNumber",(Q,J)=>{q9.init(Q,J),Q._zod.pattern=Q._zod.bag.pattern??FN,Q._zod.parse=(G,H)=>{if(J.coerce)try{G.value=Number(G.value)}catch(q){}let K=G.value;if(typeof K==="number"&&!Number.isNaN(K)&&Number.isFinite(K))return G;let z=typeof K==="number"?Number.isNaN(K)?"NaN":!Number.isFinite(K)?"Infinity":void 0:void 0;return G.issues.push({expected:"number",code:"invalid_type",input:K,inst:Q,...z?{received:z}:{}}),G}}),pd=BQ("$ZodNumberFormat",(Q,J)=>{az0.init(Q,J),LN.init(Q,J)}),cd=BQ("$ZodBoolean",(Q,J)=>{q9.init(Q,J),Q._zod.pattern=lz0,Q._zod.parse=(G,H)=>{if(J.coerce)try{G.value=Boolean(G.value)}catch(z){}let K=G.value;if(typeof K==="boolean")return G;return G.issues.push({expected:"boolean",code:"invalid_type",input:K,inst:Q}),G}});var nd=BQ("$ZodNull",(Q,J)=>{q9.init(Q,J),Q._zod.pattern=dz0,Q._zod.values=new Set([null]),Q._zod.parse=(G,H)=>{let K=G.value;if(K===null)return G;return G.issues.push({expected:"null",code:"invalid_type",input:K,inst:Q}),G}});var ad=BQ("$ZodUnknown",(Q,J)=>{q9.init(Q,J),Q._zod.parse=(G)=>G}),rd=BQ("$ZodNever",(Q,J)=>{q9.init(Q,J),Q._zod.parse=(G,H)=>{return G.issues.push({expected:"never",code:"invalid_type",input:G.value,inst:Q}),G}});function AV0(Q,J,G){if(Q.issues.length)J.issues.push(...j5(G,Q.issues));J.value[G]=Q.value}var td=BQ("$ZodArray",(Q,J)=>{q9.init(Q,J),Q._zod.parse=(G,H)=>{let K=G.value;if(!Array.isArray(K))return G.issues.push({expected:"array",code:"invalid_type",input:K,inst:Q}),G;G.value=Array(K.length);let z=[];for(let q=0;q<K.length;q++){let F=K[q],D=J.element._zod.run({value:F,issues:[]},H);if(D instanceof Promise)z.push(D.then((V)=>AV0(V,G,q)));else AV0(D,G,q)}if(z.length)return Promise.all(z).then(()=>G);return G}});function MN(Q,J,G,H,K){if(Q.issues.length){if(K&&!(G in H))return;J.issues.push(...j5(G,Q.issues))}if(Q.value===void 0){if(G in H)J.value[G]=void 0}else J.value[G]=Q.value}function PV0(Q){let J=Object.keys(Q.shape);for(let H of J)if(!Q.shape?.[H]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${H}": expected a Zod schema`);let G=Rx(Q.shape);return{...Q,keys:J,keySet:new Set(J),numKeys:J.length,optionalKeys:new Set(G)}}function NV0(Q,J,G,H,K,z){let q=[],F=K.keySet,D=K.catchall._zod,V=D.def.type,O=D.optout==="optional";for(let P in J){if(F.has(P))continue;if(V==="never"){q.push(P);continue}let N=D.run({value:J[P],issues:[]},H);if(N instanceof Promise)Q.push(N.then((I)=>MN(I,G,P,J,O)));else MN(N,G,P,J,O)}if(q.length)G.issues.push({code:"unrecognized_keys",keys:q,input:J,inst:z});if(!Q.length)return G;return Promise.all(Q).then(()=>{return G})}var ed=BQ("$ZodObject",(Q,J)=>{if(q9.init(Q,J),!Object.getOwnPropertyDescriptor(J,"shape")?.get){let F=J.shape;Object.defineProperty(J,"shape",{get:()=>{let D={...F};return Object.defineProperty(J,"shape",{value:D}),D}})}let H=Bz(()=>PV0(J));k6(Q._zod,"propValues",()=>{let F=J.shape,D={};for(let V in F){let O=F[V]._zod;if(O.values){D[V]??(D[V]=new Set);for(let P of O.values)D[V].add(P)}}return D});let K=O3,z=J.catchall,q;Q._zod.parse=(F,D)=>{q??(q=H.value);let V=F.value;if(!K(V))return F.issues.push({expected:"object",code:"invalid_type",input:V,inst:Q}),F;F.value={};let O=[],P=q.shape;for(let N of q.keys){let I=P[N],R=I._zod.optout==="optional",w=I._zod.run({value:V[N],issues:[]},D);if(w instanceof Promise)O.push(w.then((E)=>MN(E,F,N,V,R)));else MN(w,F,N,V,R)}if(!z)return O.length?Promise.all(O).then(()=>F):F;return NV0(O,V,F,D,H.value,Q)}}),jV0=BQ("$ZodObjectJIT",(Q,J)=>{ed.init(Q,J);let G=Q._zod.parse,H=Bz(()=>PV0(J)),K=(N)=>{let I=new zd(["shape","payload","ctx"]),R=H.value,w=(x)=>{let b=zN(x);return`shape[${b}]._zod.run({ value: input[${b}], issues: [] }, ctx)`};I.write("const input = payload.value;");let E=Object.create(null),T=0;for(let x of R.keys)E[x]=`key_${T++}`;I.write("const newResult = {};");for(let x of R.keys){let b=E[x],g=zN(x),_=N[x]?._zod?.optout==="optional";if(I.write(`const ${b} = ${w(x)};`),_)I.write(`
if (${b}.issues.length) {
if (${g} in input) {
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
...iss,
path: iss.path ? [${g}, ...iss.path] : [${g}]
})));
}
}
if (${b}.value === undefined) {
if (${g} in input) {
newResult[${g}] = undefined;
}
} else {
newResult[${g}] = ${b}.value;
}
`);else I.write(`
if (${b}.issues.length) {
payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
...iss,
path: iss.path ? [${g}, ...iss.path] : [${g}]
})));
}
if (${b}.value === undefined) {
if (${g} in input) {
newResult[${g}] = undefined;
}
} else {
newResult[${g}] = ${b}.value;
}
`)}I.write("payload.value = newResult;"),I.write("return payload;");let y=I.compile();return(x,b)=>y(N,x,b)},z,q=O3,F=!AN.jitless,V=F&&Fx.value,O=J.catchall,P;Q._zod.parse=(N,I)=>{P??(P=H.value);let R=N.value;if(!q(R))return N.issues.push({expected:"object",code:"invalid_type",input:R,inst:Q}),N;if(F&&V&&I?.async===!1&&I.jitless!==!0){if(!z)z=K(J.shape);if(N=z(N,I),!O)return N;return NV0([],R,N,I,P,Q)}return G(N,I)}});function KV0(Q,J,G,H){for(let z of Q)if(z.issues.length===0)return J.value=z.value,J;let K=Q.filter((z)=>!g4(z));if(K.length===1)return J.value=K[0].value,K[0];return J.issues.push({code:"invalid_union",input:J.value,inst:G,errors:Q.map((z)=>z.issues.map((q)=>DG(q,H,hY())))}),J}var ON=BQ("$ZodUnion",(Q,J)=>{q9.init(Q,J),k6(Q._zod,"optin",()=>J.options.some((K)=>K._zod.optin==="optional")?"optional":void 0),k6(Q._zod,"optout",()=>J.options.some((K)=>K._zod.optout==="optional")?"optional":void 0),k6(Q._zod,"values",()=>{if(J.options.every((K)=>K._zod.values))return new Set(J.options.flatMap((K)=>Array.from(K._zod.values)));return}),k6(Q._zod,"pattern",()=>{if(J.options.every((K)=>K._zod.pattern)){let K=J.options.map((z)=>z._zod.pattern);return new RegExp(`^(${K.map((z)=>kU(z.source)).join("|")})$`)}return});let G=J.options.length===1,H=J.options[0]._zod.run;Q._zod.parse=(K,z)=>{if(G)return H(K,z);let q=!1,F=[];for(let D of J.options){let V=D._zod.run({value:K.value,issues:[]},z);if(V instanceof Promise)F.push(V),q=!0;else{if(V.issues.length===0)return V;F.push(V)}}if(!q)return KV0(F,K,Q,z);return Promise.all(F).then((D)=>{return KV0(D,K,Q,z)})}});var Qc=BQ("$ZodDiscriminatedUnion",(Q,J)=>{J.inclusive=!1,ON.init(Q,J);let G=Q._zod.parse;k6(Q._zod,"propValues",()=>{let K={};for(let z of J.options){let q=z._zod.propValues;if(!q||Object.keys(q).length===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(z)}"`);for(let[F,D]of Object.entries(q)){if(!K[F])K[F]=new Set;for(let V of D)K[F].add(V)}}return K});let H=Bz(()=>{let K=J.options,z=new Map;for(let q of K){let F=q._zod.propValues?.[J.discriminator];if(!F||F.size===0)throw Error(`Invalid discriminated union option at index "${J.options.indexOf(q)}"`);for(let D of F){if(z.has(D))throw Error(`Duplicate discriminator value "${String(D)}"`);z.set(D,q)}}return z});Q._zod.parse=(K,z)=>{let q=K.value;if(!O3(q))return K.issues.push({code:"invalid_type",expected:"object",input:q,inst:Q}),K;let F=H.value.get(q?.[J.discriminator]);if(F)return F._zod.run(K,z);if(J.unionFallback)return G(K,z);return K.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:J.discriminator,input:q,path:[J.discriminator],inst:Q}),K}}),Yc=BQ("$ZodIntersection",(Q,J)=>{q9.init(Q,J),Q._zod.parse=(G,H)=>{let K=G.value,z=J.left._zod.run({value:K,issues:[]},H),q=J.right._zod.run({value:K,issues:[]},H);if(z instanceof Promise||q instanceof Promise)return Promise.all([z,q]).then(([D,V])=>{return zV0(G,D,V)});return zV0(G,z,q)}});function Vd(Q,J){if(Q===J)return{valid:!0,data:Q};if(Q instanceof Date&&J instanceof Date&&+Q===+J)return{valid:!0,data:Q};if(b4(Q)&&b4(J)){let G=Object.keys(J),H=Object.keys(Q).filter((z)=>G.indexOf(z)!==-1),K={...Q,...J};for(let z of H){let q=Vd(Q[z],J[z]);if(!q.valid)return{valid:!1,mergeErrorPath:[z,...q.mergeErrorPath]};K[z]=q.data}return{valid:!0,data:K}}if(Array.isArray(Q)&&Array.isArray(J)){if(Q.length!==J.length)return{valid:!1,mergeErrorPath:[]};let G=[];for(let H=0;H<Q.length;H++){let K=Q[H],z=J[H],q=Vd(K,z);if(!q.valid)return{valid:!1,mergeErrorPath:[H,...q.mergeErrorPath]};G.push(q.data)}return{valid:!0,data:G}}return{valid:!1,mergeErrorPath:[]}}function zV0(Q,J,G){let H=new Map,K;for(let F of J.issues)if(F.code==="unrecognized_keys"){K??(K=F);for(let D of F.keys){if(!H.has(D))H.set(D,{});H.get(D).l=!0}}else Q.issues.push(F);for(let F of G.issues)if(F.code==="unrecognized_keys")for(let D of F.keys){if(!H.has(D))H.set(D,{});H.get(D).r=!0}else Q.issues.push(F);let z=[...H].filter(([,F])=>F.l&&F.r).map(([F])=>F);if(z.length&&K)Q.issues.push({...K,keys:z});if(g4(Q))return Q;let q=Vd(J.value,G.value);if(!q.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(q.mergeErrorPath)}`);return Q.value=q.data,Q}var Wc=BQ("$ZodRecord",(Q,J)=>{q9.init(Q,J),Q._zod.parse=(G,H)=>{let K=G.value;if(!b4(K))return G.issues.push({expected:"record",code:"invalid_type",input:K,inst:Q}),G;let z=[],q=J.keyType._zod.values;if(q){G.value={};let F=new Set;for(let V of q)if(typeof V==="string"||typeof V==="number"||typeof V==="symbol"){F.add(typeof V==="number"?V.toString():V);let O=J.valueType._zod.run({value:K[V],issues:[]},H);if(O instanceof Promise)z.push(O.then((P)=>{if(P.issues.length)G.issues.push(...j5(V,P.issues));G.value[V]=P.value}));else{if(O.issues.length)G.issues.push(...j5(V,O.issues));G.value[V]=O.value}}let D;for(let V in K)if(!F.has(V))D=D??[],D.push(V);if(D&&D.length>0)G.issues.push({code:"unrecognized_keys",input:K,inst:Q,keys:D})}else{G.value={};for(let F of Reflect.ownKeys(K)){if(F==="__proto__")continue;let D=J.keyType._zod.run({value:F,issues:[]},H);if(D instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof F==="string"&&FN.test(F)&&D.issues.length){let P=J.keyType._zod.run({value:Number(F),issues:[]},H);if(P instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(P.issues.length===0)D=P}if(D.issues.length){if(J.mode==="loose")G.value[F]=K[F];else G.issues.push({code:"invalid_key",origin:"record",issues:D.issues.map((P)=>DG(P,H,hY())),input:F,path:[F],inst:Q});continue}let O=J.valueType._zod.run({value:K[F],issues:[]},H);if(O instanceof Promise)z.push(O.then((P)=>{if(P.issues.length)G.issues.push(...j5(F,P.issues));G.value[D.value]=P.value}));else{if(O.issues.length)G.issues.push(...j5(F,O.issues));G.value[D.value]=O.value}}}if(z.length)return Promise.all(z).then(()=>G);return G}});var Bc=BQ("$ZodEnum",(Q,J)=>{q9.init(Q,J);let G=SU(J.entries),H=new Set(G);Q._zod.values=H,Q._zod.pattern=new RegExp(`^(${G.filter((K)=>jx.has(typeof K)).map((K)=>typeof K==="string"?N5(K):K.toString()).join("|")})$`),Q._zod.parse=(K,z)=>{let q=K.value;if(H.has(q))return K;return K.issues.push({code:"invalid_value",values:G,input:q,inst:Q}),K}}),Ac=BQ("$ZodLiteral",(Q,J)=>{if(q9.init(Q,J),J.values.length===0)throw Error("Cannot create literal schema with no valid values");let G=new Set(J.values);Q._zod.values=G,Q._zod.pattern=new RegExp(`^(${J.values.map((H)=>typeof H==="string"?N5(H):H?N5(H.toString()):String(H)).join("|")})$`),Q._zod.parse=(H,K)=>{let z=H.value;if(G.has(z))return H;return H.issues.push({code:"invalid_value",values:J.values,input:z,inst:Q}),H}});var Kc=BQ("$ZodTransform",(Q,J)=>{q9.init(Q,J),Q._zod.parse=(G,H)=>{if(H.direction==="backward")throw new wU(Q.constructor.name);let K=J.transform(G.value,G);if(H.async)return(K instanceof Promise?K:Promise.resolve(K)).then((q)=>{return G.value=q,G});if(K instanceof Promise)throw new O5;return G.value=K,G}});function VV0(Q,J){if(Q.issues.length&&J===void 0)return{issues:[],value:void 0};return Q}var PN=BQ("$ZodOptional",(Q,J)=>{q9.init(Q,J),Q._zod.optin="optional",Q._zod.optout="optional",k6(Q._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,void 0]):void 0}),k6(Q._zod,"pattern",()=>{let G=J.innerType._zod.pattern;return G?new RegExp(`^(${kU(G.source)})?$`):void 0}),Q._zod.parse=(G,H)=>{if(J.innerType._zod.optin==="optional"){let K=J.innerType._zod.run(G,H);if(K instanceof Promise)return K.then((z)=>VV0(z,G.value));return VV0(K,G.value)}if(G.value===void 0)return G;return J.innerType._zod.run(G,H)}}),zc=BQ("$ZodExactOptional",(Q,J)=>{PN.init(Q,J),k6(Q._zod,"values",()=>J.innerType._zod.values),k6(Q._zod,"pattern",()=>J.innerType._zod.pattern),Q._zod.parse=(G,H)=>{return J.innerType._zod.run(G,H)}}),qc=BQ("$ZodNullable",(Q,J)=>{q9.init(Q,J),k6(Q._zod,"optin",()=>J.innerType._zod.optin),k6(Q._zod,"optout",()=>J.innerType._zod.optout),k6(Q._zod,"pattern",()=>{let G=J.innerType._zod.pattern;return G?new RegExp(`^(${kU(G.source)}|null)$`):void 0}),k6(Q._zod,"values",()=>{return J.innerType._zod.values?new Set([...J.innerType._zod.values,null]):void 0}),Q._zod.parse=(G,H)=>{if(G.value===null)return G;return J.innerType._zod.run(G,H)}}),$c=BQ("$ZodDefault",(Q,J)=>{q9.init(Q,J),Q._zod.optin="optional",k6(Q._zod,"values",()=>J.innerType._zod.values),Q._zod.parse=(G,H)=>{if(H.direction==="backward")return J.innerType._zod.run(G,H);if(G.value===void 0)return G.value=J.defaultValue,G;let K=J.innerType._zod.run(G,H);if(K instanceof Promise)return K.then((z)=>qV0(z,J));return qV0(K,J)}});function qV0(Q,J){if(Q.value===void 0)Q.value=J.defaultValue;return Q}var Zc=BQ("$ZodPrefault",(Q,J)=>{q9.init(Q,J),Q._zod.optin="optional",k6(Q._zod,"values",()=>J.innerType._zod.values),Q._zod.parse=(G,H)=>{if(H.direction==="backward")return J.innerType._zod.run(G,H);if(G.value===void 0)G.value=J.defaultValue;return J.innerType._zod.run(G,H)}}),Fc=BQ("$ZodNonOptional",(Q,J)=>{q9.init(Q,J),k6(Q._zod,"values",()=>{let G=J.innerType._zod.values;return G?new Set([...G].filter((H)=>H!==void 0)):void 0}),Q._zod.parse=(G,H)=>{let K=J.innerType._zod.run(G,H);if(K instanceof Promise)return K.then((z)=>UV0(z,Q));return UV0(K,Q)}});function UV0(Q,J){if(!Q.issues.length&&Q.value===void 0)Q.issues.push({code:"invalid_type",expected:"nonoptional",input:Q.value,inst:J});return Q}var Dc=BQ("$ZodCatch",(Q,J)=>{q9.init(Q,J),k6(Q._zod,"optin",()=>J.innerType._zod.optin),k6(Q._zod,"optout",()=>J.innerType._zod.optout),k6(Q._zod,"values",()=>J.innerType._zod.values),Q._zod.parse=(G,H)=>{if(H.direction==="backward")return J.innerType._zod.run(G,H);let K=J.innerType._zod.run(G,H);if(K instanceof Promise)return K.then((z)=>{if(G.value=z.value,z.issues.length)G.value=J.catchValue({...G,error:{issues:z.issues.map((q)=>DG(q,H,hY()))},input:G.value}),G.issues=[];return G});if(G.value=K.value,K.issues.length)G.value=J.catchValue({...G,error:{issues:K.issues.map((z)=>DG(z,H,hY()))},input:G.value}),G.issues=[];return G}});var Mc=BQ("$ZodPipe",(Q,J)=>{q9.init(Q,J),k6(Q._zod,"values",()=>J.in._zod.values),k6(Q._zod,"optin",()=>J.in._zod.optin),k6(Q._zod,"optout",()=>J.out._zod.optout),k6(Q._zod,"propValues",()=>J.in._zod.propValues),Q._zod.parse=(G,H)=>{if(H.direction==="backward"){let z=J.out._zod.run(G,H);if(z instanceof Promise)return z.then((q)=>DN(q,J.in,H));return DN(z,J.in,H)}let K=J.in._zod.run(G,H);if(K instanceof Promise)return K.then((z)=>DN(z,J.out,H));return DN(K,J.out,H)}});function DN(Q,J,G){if(Q.issues.length)return Q.aborted=!0,Q;return J._zod.run({value:Q.value,issues:Q.issues},G)}var Lc=BQ("$ZodReadonly",(Q,J)=>{q9.init(Q,J),k6(Q._zod,"propValues",()=>J.innerType._zod.propValues),k6(Q._zod,"values",()=>J.innerType._zod.values),k6(Q._zod,"optin",()=>J.innerType?._zod?.optin),k6(Q._zod,"optout",()=>J.innerType?._zod?.optout),Q._zod.parse=(G,H)=>{if(H.direction==="backward")return J.innerType._zod.run(G,H);let K=J.innerType._zod.run(G,H);if(K instanceof Promise)return K.then($V0);return $V0(K)}});function $V0(Q){return Q.value=Object.freeze(Q.value),Q}var Oc=BQ("$ZodCustom",(Q,J)=>{s7.init(Q,J),q9.init(Q,J),Q._zod.parse=(G,H)=>{return G},Q._zod.check=(G)=>{let H=G.value,K=J.fn(H);if(K instanceof Promise)return K.then((z)=>ZV0(z,G,H,Q));ZV0(K,G,H,Q);return}});function ZV0(Q,J,G,H){if(!Q){let K={code:"custom",input:G,inst:H,path:[...H._zod.def.path??[]],continue:!H._zod.def.abort};if(H._zod.def.params)K.params=H._zod.def.params;J.issues.push(Az(K))}}var KQQ=()=>{let Q={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function J(K){return Q[K]??null}let G={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},H={nan:"NaN"};return(K)=>{switch(K.code){case"invalid_type":{let z=H[K.expected]??K.expected,q=ug(K.input),F=H[q]??q;return`Invalid input: expected ${z}, received ${F}`}case"invalid_value":if(K.values.length===1)return`Invalid input: expected ${qN(K.values[0])}`;return`Invalid option: expected one of ${KN(K.values,"|")}`;case"too_big":{let z=K.inclusive?"<=":"<",q=J(K.origin);if(q)return`Too big: expected ${K.origin??"value"} to have ${z}${K.maximum.toString()} ${q.unit??"elements"}`;return`Too big: expected ${K.origin??"value"} to be ${z}${K.maximum.toString()}`}case"too_small":{let z=K.inclusive?">=":">",q=J(K.origin);if(q)return`Too small: expected ${K.origin} to have ${z}${K.minimum.toString()} ${q.unit}`;return`Too small: expected ${K.origin} to be ${z}${K.minimum.toString()}`}case"invalid_format":{let z=K;if(z.format==="starts_with")return`Invalid string: must start with "${z.prefix}"`;if(z.format==="ends_with")return`Invalid string: must end with "${z.suffix}"`;if(z.format==="includes")return`Invalid string: must include "${z.includes}"`;if(z.format==="regex")return`Invalid string: must match pattern ${z.pattern}`;return`Invalid ${G[z.format]??K.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${K.divisor}`;case"unrecognized_keys":return`Unrecognized key${K.keys.length>1?"s":""}: ${KN(K.keys,", ")}`;case"invalid_key":return`Invalid key in ${K.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${K.origin}`;default:return"Invalid input"}}};function Pc(){return{localeError:KQQ()}}var CV0,$68=Symbol("ZodOutput"),Z68=Symbol("ZodInput");class IV0{constructor(){this._map=new WeakMap,this._idmap=new Map}add(Q,...J){let G=J[0];if(this._map.set(Q,G),G&&typeof G==="object"&&"id"in G)this._idmap.set(G.id,Q);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(Q){let J=this._map.get(Q);if(J&&typeof J==="object"&&"id"in J)this._idmap.delete(J.id);return this._map.delete(Q),this}get(Q){let J=Q._zod.parent;if(J){let G={...this.get(J)??{}};delete G.id;let H={...G,...this._map.get(Q)};return Object.keys(H).length?H:void 0}return this._map.get(Q)}has(Q){return this._map.has(Q)}}function zQQ(){return new IV0}(CV0=globalThis).__zod_globalRegistry??(CV0.__zod_globalRegistry=zQQ());var j3=globalThis.__zod_globalRegistry;function Nc(Q,J){return new Q({type:"string",...Z8(J)})}function jc(Q,J){return new Q({type:"string",format:"email",check:"string_format",abort:!1,...Z8(J)})}function NN(Q,J){return new Q({type:"string",format:"guid",check:"string_format",abort:!1,...Z8(J)})}function Cc(Q,J){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,...Z8(J)})}function Ic(Q,J){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Z8(J)})}function Rc(Q,J){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Z8(J)})}function Ec(Q,J){return new Q({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Z8(J)})}function Sc(Q,J){return new Q({type:"string",format:"url",check:"string_format",abort:!1,...Z8(J)})}function Tc(Q,J){return new Q({type:"string",format:"emoji",check:"string_format",abort:!1,...Z8(J)})}function kc(Q,J){return new Q({type:"string",format:"nanoid",check:"string_format",abort:!1,...Z8(J)})}function yc(Q,J){return new Q({type:"string",format:"cuid",check:"string_format",abort:!1,...Z8(J)})}function vc(Q,J){return new Q({type:"string",format:"cuid2",check:"string_format",abort:!1,...Z8(J)})}function xc(Q,J){return new Q({type:"string",format:"ulid",check:"string_format",abort:!1,...Z8(J)})}function _c(Q,J){return new Q({type:"string",format:"xid",check:"string_format",abort:!1,...Z8(J)})}function Ao(Q,J){return new Q({type:"string",format:"ksuid",check:"string_format",abort:!1,...Z8(J)})}function zo(Q,J){return new Q({type:"string",format:"ipv4",check:"string_format",abort:!1,...Z8(J)})}function $o(Q,J){return new Q({type:"string",format:"ipv6",check:"string_format",abort:!1,...Z8(J)})}function Mo(Q,J){return new Q({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Z8(J)})}function Lo(Q,J){return new Q({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Z8(J)})}function Oo(Q,J){return new Q({type:"string",format:"base64",check:"string_format",abort:!1,...Z8(J)})}function Po(Q,J){return new Q({type:"string",format:"base64url",check:"string_format",abort:!1,...Z8(J)})}function No(Q,J){return new Q({type:"string",format:"e164",check:"string_format",abort:!1,...Z8(J)})}function Co(Q,J){return new Q({type:"string",format:"jwt",check:"string_format",abort:!1,...Z8(J)})}function RV0(Q,J){return new Q({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Z8(J)})}function wV0(Q,J){return new Q({type:"string",format:"date",check:"string_format",...Z8(J)})}function EV0(Q,J){return new Q({type:"string",format:"time",check:"string_format",precision:null,...Z8(J)})}function SV0(Q,J){return new Q({type:"string",format:"duration",check:"string_format",...Z8(J)})}function Io(Q,J){return new Q({type:"number",checks:[],...Z8(J)})}function Ro(Q,J){return new Q({type:"number",check:"number_format",abort:!1,format:"safeint",...Z8(J)})}function wo(Q,J){return new Q({type:"boolean",...Z8(J)})}function Eo(Q,J){return new Q({type:"null",...Z8(J)})}function So(Q){return new Q({type:"unknown"})}function To(Q,J){return new Q({type:"never",...Z8(J)})}function jN(Q,J){return new Bd({check:"less_than",...Z8(J),value:Q,inclusive:!1})}function uU(Q,J){return new Bd({check:"less_than",...Z8(J),value:Q,inclusive:!0})}function CN(Q,J){return new Ad({check:"greater_than",...Z8(J),value:Q,inclusive:!1})}function pU(Q,J){return new Ad({check:"greater_than",...Z8(J),value:Q,inclusive:!0})}function IN(Q,J){return new nz0({check:"multiple_of",...Z8(J),value:Q})}function RN(Q,J){return new sz0({check:"max_length",...Z8(J),maximum:Q})}function Kz(Q,J){return new rz0({check:"min_length",...Z8(J),minimum:Q})}function wN(Q,J){return new tz0({check:"length_equals",...Z8(J),length:Q})}function vo(Q,J){return new ez0({check:"string_format",format:"regex",...Z8(J),pattern:Q})}function lo(Q){return new QV0({check:"string_format",format:"lowercase",...Z8(Q)})}function Xn(Q){return new XV0({check:"string_format",format:"uppercase",...Z8(Q)})}function Zn(Q,J){return new JV0({check:"string_format",format:"includes",...Z8(J),includes:Q})}function Ln(Q,J){return new YV0({check:"string_format",format:"starts_with",...Z8(J),prefix:Q})}function Nn(Q,J){return new GV0({check:"string_format",format:"ends_with",...Z8(J),suffix:Q})}function h4(Q){return new WV0({check:"overwrite",tx:Q})}function En(Q){return h4((J)=>J.normalize(Q))}function kn(){return h4((Q)=>Q.trim())}function un(){return h4((Q)=>Q.toLowerCase())}function ln(){return h4((Q)=>Q.toUpperCase())}function cn(){return h4((Q)=>Zx(Q))}function TV0(Q,J,G){return new Q({type:"array",element:J,...Z8(G)})}function on(Q,J,G){let H=Z8(G);return H.abort??(H.abort=!0),new Q({type:"custom",check:"custom",fn:J,...H})}function nn(Q,J,G){return new Q({type:"custom",check:"custom",fn:J,...Z8(G)})}function an(Q){let J=VQQ((G)=>{return G.addIssue=(H)=>{if(typeof H==="string")G.issues.push(Az(H,G.value,J._zod.def));else{let K=H;if(K.fatal)K.continue=!1;K.code??(K.code="custom"),K.input??(K.input=G.value),K.inst??(K.inst=J),K.continue??(K.continue=!J._zod.def.abort),G.issues.push(Az(K))}},Q(G.value,G)});return J}function VQQ(Q,J){let G=new s7({check:"custom",...Z8(J)});return G._zod.check=Q,G}function dU(Q){let J=Q?.target??"draft-2020-12";if(J==="draft-4")J="draft-04";if(J==="draft-7")J="draft-07";return{processors:Q.processors??{},metadataRegistry:Q?.metadata??j3,target:J,unrepresentable:Q?.unrepresentable??"throw",override:Q?.override??(()=>{}),io:Q?.io??"output",counter:0,seen:new Map,cycles:Q?.cycles??"ref",reused:Q?.reused??"inline",external:Q?.external??void 0}}function U9(Q,J,G={path:[],schemaPath:[]}){var H;let K=Q._zod.def,z=J.seen.get(Q);if(z){if(z.count++,G.schemaPath.includes(Q))z.cycle=G.path;return z.schema}let q={schema:{},count:1,cycle:void 0,path:G.path};J.seen.set(Q,q);let F=Q._zod.toJSONSchema?.();if(F)q.schema=F;else{let O={...G,schemaPath:[...G.schemaPath,Q],path:G.path};if(Q._zod.processJSONSchema)Q._zod.processJSONSchema(J,q.schema,O);else{let N=q.schema,I=J.processors[K.type];if(!I)throw Error(`[toJSONSchema]: Non-representable type encountered: ${K.type}`);I(Q,J,N,O)}let P=Q._zod.parent;if(P){if(!q.ref)q.ref=P;U9(P,J,O),J.seen.get(P).isParent=!0}}let D=J.metadataRegistry.get(Q);if(D)Object.assign(q.schema,D);if(J.io==="input"&&UJ(Q))delete q.schema.examples,delete q.schema.default;if(J.io==="input"&&q.schema._prefault)(H=q.schema).default??(H.default=q.schema._prefault);return delete q.schema._prefault,J.seen.get(Q).schema}function cU(Q,J){let G=Q.seen.get(J);if(!G)throw Error("Unprocessed schema. This is a bug in Zod.");let H=new Map;for(let q of Q.seen.entries()){let F=Q.metadataRegistry.get(q[0])?.id;if(F){let D=H.get(F);if(D&&D!==q[0])throw Error(`Duplicate schema id "${F}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);H.set(F,q[0])}}let K=(q)=>{let F=Q.target==="draft-2020-12"?"$defs":"definitions";if(Q.external){let P=Q.external.registry.get(q[0])?.id,N=Q.external.uri??((R)=>R);if(P)return{ref:N(P)};let I=q[1].defId??q[1].schema.id??`schema${Q.counter++}`;return q[1].defId=I,{defId:I,ref:`${N("__shared")}#/${F}/${I}`}}if(q[1]===G)return{ref:"#"};let V=`${"#"}/${F}/`,O=q[1].schema.id??`__schema${Q.counter++}`;return{defId:O,ref:V+O}},z=(q)=>{if(q[1].schema.$ref)return;let F=q[1],{ref:D,defId:V}=K(q);if(F.def={...F.schema},V)F.defId=V;let O=F.schema;for(let P in O)delete O[P];O.$ref=D};if(Q.cycles==="throw")for(let q of Q.seen.entries()){let F=q[1];if(F.cycle)throw Error(`Cycle detected: #/${F.cycle?.join("/")}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let q of Q.seen.entries()){let F=q[1];if(J===q[0]){z(q);continue}if(Q.external){let V=Q.external.registry.get(q[0])?.id;if(J!==q[0]&&V){z(q);continue}}if(Q.metadataRegistry.get(q[0])?.id){z(q);continue}if(F.cycle){z(q);continue}if(F.count>1){if(Q.reused==="ref"){z(q);continue}}}}function iU(Q,J){let G=Q.seen.get(J);if(!G)throw Error("Unprocessed schema. This is a bug in Zod.");let H=(q)=>{let F=Q.seen.get(q);if(F.ref===null)return;let D=F.def??F.schema,V={...D},O=F.ref;if(F.ref=null,O){H(O);let N=Q.seen.get(O),I=N.schema;if(I.$ref&&(Q.target==="draft-07"||Q.target==="draft-04"||Q.target==="openapi-3.0"))D.allOf=D.allOf??[],D.allOf.push(I);else Object.assign(D,I);if(Object.assign(D,V),q._zod.parent===O)for(let w in D){if(w==="$ref"||w==="allOf")continue;if(!(w in V))delete D[w]}if(I.$ref&&N.def)for(let w in D){if(w==="$ref"||w==="allOf")continue;if(w in N.def&&JSON.stringify(D[w])===JSON.stringify(N.def[w]))delete D[w]}}let P=q._zod.parent;if(P&&P!==O){H(P);let N=Q.seen.get(P);if(N?.schema.$ref){if(D.$ref=N.schema.$ref,N.def)for(let I in D){if(I==="$ref"||I==="allOf")continue;if(I in N.def&&JSON.stringify(D[I])===JSON.stringify(N.def[I]))delete D[I]}}}Q.override({zodSchema:q,jsonSchema:D,path:F.path??[]})};for(let q of[...Q.seen.entries()].reverse())H(q[0]);let K={};if(Q.target==="draft-2020-12")K.$schema="https://json-schema.org/draft/2020-12/schema";else if(Q.target==="draft-07")K.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="draft-04")K.$schema="http://json-schema.org/draft-04/schema#";else if(Q.target==="openapi-3.0");if(Q.external?.uri){let q=Q.external.registry.get(J)?.id;if(!q)throw Error("Schema is missing an `id` property");K.$id=Q.external.uri(q)}Object.assign(K,G.def??G.schema);let z=Q.external?.defs??{};for(let q of Q.seen.entries()){let F=q[1];if(F.def&&F.defId)z[F.defId]=F.def}if(Q.external);else if(Object.keys(z).length>0)if(Q.target==="draft-2020-12")K.$defs=z;else K.definitions=z;try{let q=JSON.parse(JSON.stringify(K));return Object.defineProperty(q,"~standard",{value:{...J["~standard"],jsonSchema:{input:lU(J,"input",Q.processors),output:lU(J,"output",Q.processors)}},enumerable:!1,writable:!1}),q}catch(q){throw Error("Error converting schema to JSON.")}}function UJ(Q,J){let G=J??{seen:new Set};if(G.seen.has(Q))return!1;G.seen.add(Q);let H=Q._zod.def;if(H.type==="transform")return!0;if(H.type==="array")return UJ(H.element,G);if(H.type==="set")return UJ(H.valueType,G);if(H.type==="lazy")return UJ(H.getter(),G);if(H.type==="promise"||H.type==="optional"||H.type==="nonoptional"||H.type==="nullable"||H.type==="readonly"||H.type==="default"||H.type==="prefault")return UJ(H.innerType,G);if(H.type==="intersection")return UJ(H.left,G)||UJ(H.right,G);if(H.type==="record"||H.type==="map")return UJ(H.keyType,G)||UJ(H.valueType,G);if(H.type==="pipe")return UJ(H.in,G)||UJ(H.out,G);if(H.type==="object"){for(let K in H.shape)if(UJ(H.shape[K],G))return!0;return!1}if(H.type==="union"){for(let K of H.options)if(UJ(K,G))return!0;return!1}if(H.type==="tuple"){for(let K of H.items)if(UJ(K,G))return!0;if(H.rest&&UJ(H.rest,G))return!0;return!1}return!1}var kV0=(Q,J={})=>(G)=>{let H=dU({...G,processors:J});return U9(Q,H),cU(H,Q),iU(H,Q)},lU=(Q,J,G={})=>(H)=>{let{libraryOptions:K,target:z}=H??{},q=dU({...K??{},target:z,io:J,processors:G});return U9(Q,q),cU(q,Q),iU(q,Q)};var qQQ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},sn=(Q,J,G,H)=>{let K=G;K.type="string";let{minimum:z,maximum:q,format:F,patterns:D,contentEncoding:V}=Q._zod.bag;if(typeof z==="number")K.minLength=z;if(typeof q==="number")K.maxLength=q;if(F){if(K.format=qQQ[F]??F,K.format==="")delete K.format;if(F==="time")delete K.format}if(V)K.contentEncoding=V;if(D&&D.size>0){let O=[...D];if(O.length===1)K.pattern=O[0].source;else if(O.length>1)K.allOf=[...O.map((P)=>({...J.target==="draft-07"||J.target==="draft-04"||J.target==="openapi-3.0"?{type:"string"}:{},pattern:P.source}))]}},rn=(Q,J,G,H)=>{let K=G,{minimum:z,maximum:q,format:F,multipleOf:D,exclusiveMaximum:V,exclusiveMinimum:O}=Q._zod.bag;if(typeof F==="string"&&F.includes("int"))K.type="integer";else K.type="number";if(typeof O==="number")if(J.target==="draft-04"||J.target==="openapi-3.0")K.minimum=O,K.exclusiveMinimum=!0;else K.exclusiveMinimum=O;if(typeof z==="number"){if(K.minimum=z,typeof O==="number"&&J.target!=="draft-04")if(O>=z)delete K.minimum;else delete K.exclusiveMinimum}if(typeof V==="number")if(J.target==="draft-04"||J.target==="openapi-3.0")K.maximum=V,K.exclusiveMaximum=!0;else K.exclusiveMaximum=V;if(typeof q==="number"){if(K.maximum=q,typeof V==="number"&&J.target!=="draft-04")if(V<=q)delete K.maximum;else delete K.exclusiveMaximum}if(typeof D==="number")K.multipleOf=D},tn=(Q,J,G,H)=>{G.type="boolean"},vV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},xV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Symbols cannot be represented in JSON Schema")},en=(Q,J,G,H)=>{if(J.target==="openapi-3.0")G.type="string",G.nullable=!0,G.enum=[null];else G.type="null"},bV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Undefined cannot be represented in JSON Schema")},gV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Void cannot be represented in JSON Schema")},Xa=(Q,J,G,H)=>{G.not={}},hV0=(Q,J,G,H)=>{},Ja=(Q,J,G,H)=>{},_V0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Date cannot be represented in JSON Schema")},Ga=(Q,J,G,H)=>{let K=Q._zod.def,z=SU(K.entries);if(z.every((q)=>typeof q==="number"))G.type="number";if(z.every((q)=>typeof q==="string"))G.type="string";G.enum=z},Wa=(Q,J,G,H)=>{let K=Q._zod.def,z=[];for(let q of K.values)if(q===void 0){if(J.unrepresentable==="throw")throw Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof q==="bigint")if(J.unrepresentable==="throw")throw Error("BigInt literals cannot be represented in JSON Schema");else z.push(Number(q));else z.push(q);if(z.length===0);else if(z.length===1){let q=z[0];if(G.type=q===null?"null":typeof q,J.target==="draft-04"||J.target==="openapi-3.0")G.enum=[q];else G.const=q}else{if(z.every((q)=>typeof q==="number"))G.type="number";if(z.every((q)=>typeof q==="string"))G.type="string";if(z.every((q)=>typeof q==="boolean"))G.type="boolean";if(z.every((q)=>q===null))G.type="null";G.enum=z}},fV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("NaN cannot be represented in JSON Schema")},mV0=(Q,J,G,H)=>{let K=G,z=Q._zod.pattern;if(!z)throw Error("Pattern not found in template literal");K.type="string",K.pattern=z.source},uV0=(Q,J,G,H)=>{let K=G,z={type:"string",format:"binary",contentEncoding:"binary"},{minimum:q,maximum:F,mime:D}=Q._zod.bag;if(q!==void 0)z.minLength=q;if(F!==void 0)z.maxLength=F;if(D)if(D.length===1)z.contentMediaType=D[0],Object.assign(K,z);else Object.assign(K,z),K.anyOf=D.map((V)=>({contentMediaType:V}));else Object.assign(K,z)},pV0=(Q,J,G,H)=>{G.type="boolean"},Aa=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Custom types cannot be represented in JSON Schema")},lV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Function types cannot be represented in JSON Schema")},qa=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Transforms cannot be represented in JSON Schema")},dV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Map cannot be represented in JSON Schema")},cV0=(Q,J,G,H)=>{if(J.unrepresentable==="throw")throw Error("Set cannot be represented in JSON Schema")},$a=(Q,J,G,H)=>{let K=G,z=Q._zod.def,{minimum:q,maximum:F}=Q._zod.bag;if(typeof q==="number")K.minItems=q;if(typeof F==="number")K.maxItems=F;K.type="array",K.items=U9(z.element,J,{...H,path:[...H.path,"items"]})},Fa=(Q,J,G,H)=>{let K=G,z=Q._zod.def;K.type="object",K.properties={};let q=z.shape;for(let V in q)K.properties[V]=U9(q[V],J,{...H,path:[...H.path,"properties",V]});let F=new Set(Object.keys(q)),D=new Set([...F].filter((V)=>{let O=z.shape[V]._zod;if(J.io==="input")return O.optin===void 0;else return O.optout===void 0}));if(D.size>0)K.required=Array.from(D);if(z.catchall?._zod.def.type==="never")K.additionalProperties=!1;else if(!z.catchall){if(J.io==="output")K.additionalProperties=!1}else if(z.catchall)K.additionalProperties=U9(z.catchall,J,{...H,path:[...H.path,"additionalProperties"]})},Ma=(Q,J,G,H)=>{let K=Q._zod.def,z=K.inclusive===!1,q=K.options.map((F,D)=>U9(F,J,{...H,path:[...H.path,z?"oneOf":"anyOf",D]}));if(z)G.oneOf=q;else G.anyOf=q},La=(Q,J,G,H)=>{let K=Q._zod.def,z=U9(K.left,J,{...H,path:[...H.path,"allOf",0]}),q=U9(K.right,J,{...H,path:[...H.path,"allOf",1]}),F=(V)=>("allOf"in V)&&Object.keys(V).length===1,D=[...F(z)?z.allOf:[z],...F(q)?q.allOf:[q]];G.allOf=D},iV0=(Q,J,G,H)=>{let K=G,z=Q._zod.def;K.type="array";let q=J.target==="draft-2020-12"?"prefixItems":"items",F=J.target==="draft-2020-12"?"items":J.target==="openapi-3.0"?"items":"additionalItems",D=z.items.map((N,I)=>U9(N,J,{...H,path:[...H.path,q,I]})),V=z.rest?U9(z.rest,J,{...H,path:[...H.path,F,...J.target==="openapi-3.0"?[z.items.length]:[]]}):null;if(J.target==="draft-2020-12"){if(K.prefixItems=D,V)K.items=V}else if(J.target==="openapi-3.0"){if(K.items={anyOf:D},V)K.items.anyOf.push(V);if(K.minItems=D.length,!V)K.maxItems=D.length}else if(K.items=D,V)K.additionalItems=V;let{minimum:O,maximum:P}=Q._zod.bag;if(typeof O==="number")K.minItems=O;if(typeof P==="number")K.maxItems=P},Na=(Q,J,G,H)=>{let K=G,z=Q._zod.def;K.type="object";let q=z.keyType,D=q._zod.bag?.patterns;if(z.mode==="loose"&&D&&D.size>0){let O=U9(z.valueType,J,{...H,path:[...H.path,"patternProperties","*"]});K.patternProperties={};for(let P of D)K.patternProperties[P.source]=O}else{if(J.target==="draft-07"||J.target==="draft-2020-12")K.propertyNames=U9(z.keyType,J,{...H,path:[...H.path,"propertyNames"]});K.additionalProperties=U9(z.valueType,J,{...H,path:[...H.path,"additionalProperties"]})}let V=q._zod.values;if(V){let O=[...V].filter((P)=>typeof P==="string"||typeof P==="number");if(O.length>0)K.required=O}},ja=(Q,J,G,H)=>{let K=Q._zod.def,z=U9(K.innerType,J,H),q=J.seen.get(Q);if(J.target==="openapi-3.0")q.ref=K.innerType,G.nullable=!0;else G.anyOf=[z,{type:"null"}]},Ca=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);z.ref=K.innerType},Ia=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);z.ref=K.innerType,G.default=JSON.parse(JSON.stringify(K.defaultValue))},ba=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);if(z.ref=K.innerType,J.io==="input")G._prefault=JSON.parse(JSON.stringify(K.defaultValue))},Xs=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);z.ref=K.innerType;let q;try{q=K.catchValue(void 0)}catch{throw Error("Dynamic catch values are not supported in JSON Schema")}G.default=q},Js=(Q,J,G,H)=>{let K=Q._zod.def,z=J.io==="input"?K.in._zod.def.type==="transform"?K.out:K.in:K.out;U9(z,J,H);let q=J.seen.get(Q);q.ref=z},Gs=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);z.ref=K.innerType,G.readOnly=!0},oV0=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);z.ref=K.innerType},EN=(Q,J,G,H)=>{let K=Q._zod.def;U9(K.innerType,J,H);let z=J.seen.get(Q);z.ref=K.innerType},nV0=(Q,J,G,H)=>{let K=Q._zod.innerType;U9(K,J,H);let z=J.seen.get(Q);z.ref=K},yV0={string:sn,number:rn,boolean:tn,bigint:vV0,symbol:xV0,null:en,undefined:bV0,void:gV0,never:Xa,any:hV0,unknown:Ja,date:_V0,enum:Ga,literal:Wa,nan:fV0,template_literal:mV0,file:uV0,success:pV0,custom:Aa,function:lV0,transform:qa,map:dV0,set:cV0,array:$a,object:Fa,union:Ma,intersection:La,tuple:iV0,record:Na,nullable:ja,nonoptional:Ca,default:Ia,prefault:ba,catch:Xs,pipe:Js,readonly:Gs,promise:oV0,optional:EN,lazy:nV0};function Ws(Q,J){if("_idmap"in Q){let H=Q,K=dU({...J,processors:yV0}),z={};for(let D of H._idmap.entries()){let[V,O]=D;U9(O,K)}let q={},F={registry:H,uri:J?.uri,defs:z};K.external=F;for(let D of H._idmap.entries()){let[V,O]=D;cU(K,O),q[V]=iU(K,O)}if(Object.keys(z).length>0){let D=K.target==="draft-2020-12"?"$defs":"definitions";q.__shared={[D]:z}}return{schemas:q}}let G=dU({...J,processors:yV0});return U9(Q,G),cU(G,Q),iU(G,Q)}var X8Q=BQ("ZodMiniType",(Q,J)=>{if(!Q._zod)throw Error("Uninitialized schema in ZodMiniType.");q9.init(Q,J),Q.def=J,Q.type=J.type,Q.parse=(G,H)=>$N(Q,G,H,{callee:Q.parse}),Q.safeParse=(G,H)=>P3(Q,G,H),Q.parseAsync=async(G,H)=>ZN(Q,G,H,{callee:Q.parseAsync}),Q.safeParseAsync=async(G,H)=>N3(Q,G,H),Q.check=(...G)=>{return Q.clone({...J,checks:[...J.checks??[],...G.map((H)=>typeof H==="function"?{_zod:{check:H,def:{check:"custom"},onattach:[]}}:H)]},{parent:!0})},Q.with=Q.check,Q.clone=(G,H)=>KY(Q,G,H),Q.brand=()=>Q,Q.register=(G,H)=>{return G.add(Q,H),Q},Q.apply=(G)=>G(Q)});var J8Q=BQ("ZodMiniObject",(Q,J)=>{ed.init(Q,J),X8Q.init(Q,J),k6(Q,"shape",()=>J.shape)});function Hs(Q,J){let G={type:"object",shape:Q??{},...Z8(J)};return new J8Q(G)}function _Y(Q){return!!Q._zod}function I3(Q){let J=Object.values(Q);if(J.length===0)return Hs({});let G=J.every(_Y),H=J.every((K)=>!_Y(K));if(G)return Hs(Q);if(H)return aK0(Q);throw Error("Mixed Zod versions detected in object shape.")}function _4(Q,J){if(_Y(Q))return P3(Q,J);return Q.safeParse(J)}async function SN(Q,J){if(_Y(Q))return await N3(Q,J);return await Q.safeParseAsync(J)}function f4(Q){if(!Q)return;let J;if(_Y(Q))J=Q._zod?.def?.shape;else J=Q.shape;if(!J)return;if(typeof J==="function")try{return J()}catch{return}return J}function zz(Q){if(!Q)return;if(typeof Q==="object"){let J=Q,G=Q;if(!J._def&&!G._zod){let H=Object.values(Q);if(H.length>0&&H.every((K)=>typeof K==="object"&&K!==null&&(K._def!==void 0||K._zod!==void 0||typeof K.parse==="function")))return I3(Q)}}if(_Y(Q)){let G=Q._zod?.def;if(G&&(G.type==="object"||G.shape!==void 0))return Q}else if(Q.shape!==void 0)return Q;return}function TN(Q){if(Q&&typeof Q==="object"){if("message"in Q&&typeof Q.message==="string")return Q.message;if("issues"in Q&&Array.isArray(Q.issues)&&Q.issues.length>0){let J=Q.issues[0];if(J&&typeof J==="object"&&"message"in J)return String(J.message)}try{return JSON.stringify(Q)}catch{return String(Q)}}return String(Q)}function sV0(Q){return Q.description}function rV0(Q){if(_Y(Q))return Q._zod?.def?.type==="optional";let J=Q;if(typeof Q.isOptional==="function")return Q.isOptional();return J._def?.typeName==="ZodOptional"}function kN(Q){if(_Y(Q)){let z=Q._zod?.def;if(z){if(z.value!==void 0)return z.value;if(Array.isArray(z.values)&&z.values.length>0)return z.values[0]}}let G=Q._def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}let H=Q.value;if(H!==void 0)return H;return}var oU={};UD(oU,{time:()=>Ks,duration:()=>Vs,datetime:()=>Bs,date:()=>As,ZodISOTime:()=>Qq0,ZodISODuration:()=>Xq0,ZodISODateTime:()=>tV0,ZodISODate:()=>eV0});var tV0=BQ("ZodISODateTime",(Q,J)=>{FV0.init(Q,J),g9.init(Q,J)});function Bs(Q){return RV0(tV0,Q)}var eV0=BQ("ZodISODate",(Q,J)=>{DV0.init(Q,J),g9.init(Q,J)});function As(Q){return wV0(eV0,Q)}var Qq0=BQ("ZodISOTime",(Q,J)=>{MV0.init(Q,J),g9.init(Q,J)});function Ks(Q){return EV0(Qq0,Q)}var Xq0=BQ("ZodISODuration",(Q,J)=>{LV0.init(Q,J),g9.init(Q,J)});function Vs(Q){return SV0(Xq0,Q)}var Jq0=(Q,J)=>{UN.init(Q,J),Q.name="ZodError",Object.defineProperties(Q,{format:{value:(G)=>Vz0(Q,G)},flatten:{value:(G)=>zz0(Q,G)},addIssue:{value:(G)=>{Q.issues.push(G),Q.message=JSON.stringify(Q.issues,Hz,2)}},addIssues:{value:(G)=>{Q.issues.push(...G),Q.message=JSON.stringify(Q.issues,Hz,2)}},isEmpty:{get(){return Q.issues.length===0}}})},z98=BQ("ZodError",Jq0),zY=BQ("ZodError",Jq0,{Parent:Error});var Yq0=xU(zY),Gq0=bU(zY),Wq0=gU(zY),Hq0=hU(zY),Bq0=qz0(zY),Aq0=Uz0(zY),Kq0=$z0(zY),zq0=Zz0(zY),Vq0=Fz0(zY),qq0=Dz0(zY),Uq0=Mz0(zY),$q0=Lz0(zY);var f9=BQ("ZodType",(Q,J)=>{return q9.init(Q,J),Object.assign(Q["~standard"],{jsonSchema:{input:lU(Q,"input"),output:lU(Q,"output")}}),Q.toJSONSchema=kV0(Q,{}),Q.def=J,Q.type=J.type,Object.defineProperty(Q,"_def",{value:J}),Q.check=(...G)=>{return Q.clone(I6.mergeDefs(J,{checks:[...J.checks??[],...G.map((H)=>typeof H==="function"?{_zod:{check:H,def:{check:"custom"},onattach:[]}}:H)]}),{parent:!0})},Q.with=Q.check,Q.clone=(G,H)=>KY(Q,G,H),Q.brand=()=>Q,Q.register=(G,H)=>{return G.add(Q,H),Q},Q.parse=(G,H)=>Yq0(Q,G,H,{callee:Q.parse}),Q.safeParse=(G,H)=>Wq0(Q,G,H),Q.parseAsync=async(G,H)=>Gq0(Q,G,H,{callee:Q.parseAsync}),Q.safeParseAsync=async(G,H)=>Hq0(Q,G,H),Q.spa=Q.safeParseAsync,Q.encode=(G,H)=>Bq0(Q,G,H),Q.decode=(G,H)=>Aq0(Q,G,H),Q.encodeAsync=async(G,H)=>Kq0(Q,G,H),Q.decodeAsync=async(G,H)=>zq0(Q,G,H),Q.safeEncode=(G,H)=>Vq0(Q,G,H),Q.safeDecode=(G,H)=>qq0(Q,G,H),Q.safeEncodeAsync=async(G,H)=>Uq0(Q,G,H),Q.safeDecodeAsync=async(G,H)=>$q0(Q,G,H),Q.refine=(G,H)=>Q.check(Q6Q(G,H)),Q.superRefine=(G)=>Q.check(X6Q(G)),Q.overwrite=(G)=>Q.check(h4(G)),Q.optional=()=>_9(Q),Q.exactOptional=()=>p8Q(Q),Q.nullable=()=>Dq0(Q),Q.nullish=()=>_9(Dq0(Q)),Q.nonoptional=(G)=>n8Q(Q,G),Q.array=()=>M6(Q),Q.or=(G)=>I9([Q,G]),Q.and=(G)=>vN(Q,G),Q.transform=(G)=>Us(Q,jq0(G)),Q.default=(G)=>c8Q(Q,G),Q.prefault=(G)=>o8Q(Q,G),Q.catch=(G)=>s8Q(Q,G),Q.pipe=(G)=>Us(Q,G),Q.readonly=()=>e8Q(Q),Q.describe=(G)=>{let H=Q.clone();return j3.add(H,{description:G}),H},Object.defineProperty(Q,"description",{get(){return j3.get(Q)?.description},configurable:!0}),Q.meta=(...G)=>{if(G.length===0)return j3.get(Q);let H=Q.clone();return j3.add(H,G[0]),H},Q.isOptional=()=>Q.safeParse(void 0).success,Q.isNullable=()=>Q.safeParse(null).success,Q.apply=(G)=>G(Q),Q}),Mq0=BQ("_ZodString",(Q,J)=>{mU.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(H,K,z)=>sn(Q,H,K,z);let G=Q._zod.bag;Q.format=G.format??null,Q.minLength=G.minimum??null,Q.maxLength=G.maximum??null,Q.regex=(...H)=>Q.check(vo(...H)),Q.includes=(...H)=>Q.check(Zn(...H)),Q.startsWith=(...H)=>Q.check(Ln(...H)),Q.endsWith=(...H)=>Q.check(Nn(...H)),Q.min=(...H)=>Q.check(Kz(...H)),Q.max=(...H)=>Q.check(RN(...H)),Q.length=(...H)=>Q.check(wN(...H)),Q.nonempty=(...H)=>Q.check(Kz(1,...H)),Q.lowercase=(H)=>Q.check(lo(H)),Q.uppercase=(H)=>Q.check(Xn(H)),Q.trim=()=>Q.check(kn()),Q.normalize=(...H)=>Q.check(En(...H)),Q.toLowerCase=()=>Q.check(un()),Q.toUpperCase=()=>Q.check(ln()),Q.slugify=()=>Q.check(cn())}),V8Q=BQ("ZodString",(Q,J)=>{mU.init(Q,J),Mq0.init(Q,J),Q.email=(G)=>Q.check(jc(q8Q,G)),Q.url=(G)=>Q.check(Sc(U8Q,G)),Q.jwt=(G)=>Q.check(Co(E8Q,G)),Q.emoji=(G)=>Q.check(Tc($8Q,G)),Q.guid=(G)=>Q.check(NN(Zq0,G)),Q.uuid=(G)=>Q.check(Cc(yN,G)),Q.uuidv4=(G)=>Q.check(Ic(yN,G)),Q.uuidv6=(G)=>Q.check(Rc(yN,G)),Q.uuidv7=(G)=>Q.check(Ec(yN,G)),Q.nanoid=(G)=>Q.check(kc(Z8Q,G)),Q.guid=(G)=>Q.check(NN(Zq0,G)),Q.cuid=(G)=>Q.check(yc(F8Q,G)),Q.cuid2=(G)=>Q.check(vc(D8Q,G)),Q.ulid=(G)=>Q.check(xc(M8Q,G)),Q.base64=(G)=>Q.check(Oo(I8Q,G)),Q.base64url=(G)=>Q.check(Po(R8Q,G)),Q.xid=(G)=>Q.check(_c(L8Q,G)),Q.ksuid=(G)=>Q.check(Ao(O8Q,G)),Q.ipv4=(G)=>Q.check(zo(P8Q,G)),Q.ipv6=(G)=>Q.check($o(N8Q,G)),Q.cidrv4=(G)=>Q.check(Mo(j8Q,G)),Q.cidrv6=(G)=>Q.check(Lo(C8Q,G)),Q.e164=(G)=>Q.check(No(w8Q,G)),Q.datetime=(G)=>Q.check(Bs(G)),Q.date=(G)=>Q.check(As(G)),Q.time=(G)=>Q.check(Ks(G)),Q.duration=(G)=>Q.check(Vs(G))});function HQ(Q){return Nc(V8Q,Q)}var g9=BQ("ZodStringFormat",(Q,J)=>{L9.init(Q,J),Mq0.init(Q,J)}),q8Q=BQ("ZodEmail",(Q,J)=>{Ld.init(Q,J),g9.init(Q,J)});var Zq0=BQ("ZodGUID",(Q,J)=>{$d.init(Q,J),g9.init(Q,J)});var yN=BQ("ZodUUID",(Q,J)=>{Dd.init(Q,J),g9.init(Q,J)});var U8Q=BQ("ZodURL",(Q,J)=>{Pd.init(Q,J),g9.init(Q,J)});var $8Q=BQ("ZodEmoji",(Q,J)=>{Nd.init(Q,J),g9.init(Q,J)});var Z8Q=BQ("ZodNanoID",(Q,J)=>{Id.init(Q,J),g9.init(Q,J)});var F8Q=BQ("ZodCUID",(Q,J)=>{wd.init(Q,J),g9.init(Q,J)});var D8Q=BQ("ZodCUID2",(Q,J)=>{Ed.init(Q,J),g9.init(Q,J)});var M8Q=BQ("ZodULID",(Q,J)=>{Sd.init(Q,J),g9.init(Q,J)});var L8Q=BQ("ZodXID",(Q,J)=>{Td.init(Q,J),g9.init(Q,J)});var O8Q=BQ("ZodKSUID",(Q,J)=>{yd.init(Q,J),g9.init(Q,J)});var P8Q=BQ("ZodIPv4",(Q,J)=>{vd.init(Q,J),g9.init(Q,J)});var N8Q=BQ("ZodIPv6",(Q,J)=>{bd.init(Q,J),g9.init(Q,J)});var j8Q=BQ("ZodCIDRv4",(Q,J)=>{gd.init(Q,J),g9.init(Q,J)});var C8Q=BQ("ZodCIDRv6",(Q,J)=>{hd.init(Q,J),g9.init(Q,J)});var I8Q=BQ("ZodBase64",(Q,J)=>{_d.init(Q,J),g9.init(Q,J)});var R8Q=BQ("ZodBase64URL",(Q,J)=>{fd.init(Q,J),g9.init(Q,J)});var w8Q=BQ("ZodE164",(Q,J)=>{md.init(Q,J),g9.init(Q,J)});var E8Q=BQ("ZodJWT",(Q,J)=>{ud.init(Q,J),g9.init(Q,J)});var Lq0=BQ("ZodNumber",(Q,J)=>{LN.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(H,K,z)=>rn(Q,H,K,z),Q.gt=(H,K)=>Q.check(CN(H,K)),Q.gte=(H,K)=>Q.check(pU(H,K)),Q.min=(H,K)=>Q.check(pU(H,K)),Q.lt=(H,K)=>Q.check(jN(H,K)),Q.lte=(H,K)=>Q.check(uU(H,K)),Q.max=(H,K)=>Q.check(uU(H,K)),Q.int=(H)=>Q.check(Fq0(H)),Q.safe=(H)=>Q.check(Fq0(H)),Q.positive=(H)=>Q.check(CN(0,H)),Q.nonnegative=(H)=>Q.check(pU(0,H)),Q.negative=(H)=>Q.check(jN(0,H)),Q.nonpositive=(H)=>Q.check(uU(0,H)),Q.multipleOf=(H,K)=>Q.check(IN(H,K)),Q.step=(H,K)=>Q.check(IN(H,K)),Q.finite=()=>Q;let G=Q._zod.bag;Q.minValue=Math.max(G.minimum??Number.NEGATIVE_INFINITY,G.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,Q.maxValue=Math.min(G.maximum??Number.POSITIVE_INFINITY,G.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,Q.isInt=(G.format??"").includes("int")||Number.isSafeInteger(G.multipleOf??0.5),Q.isFinite=!0,Q.format=G.format??null});function o6(Q){return Io(Lq0,Q)}var S8Q=BQ("ZodNumberFormat",(Q,J)=>{pd.init(Q,J),Lq0.init(Q,J)});function Fq0(Q){return Ro(S8Q,Q)}var T8Q=BQ("ZodBoolean",(Q,J)=>{cd.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>tn(Q,G,H,K)});function r7(Q){return wo(T8Q,Q)}var k8Q=BQ("ZodNull",(Q,J)=>{nd.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>en(Q,G,H,K)});function Oq0(Q){return Eo(k8Q,Q)}var y8Q=BQ("ZodUnknown",(Q,J)=>{ad.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Ja(Q,G,H,K)});function h9(){return So(y8Q)}var v8Q=BQ("ZodNever",(Q,J)=>{rd.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Xa(Q,G,H,K)});function x8Q(Q){return To(v8Q,Q)}var b8Q=BQ("ZodArray",(Q,J)=>{td.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>$a(Q,G,H,K),Q.element=J.element,Q.min=(G,H)=>Q.check(Kz(G,H)),Q.nonempty=(G)=>Q.check(Kz(1,G)),Q.max=(G,H)=>Q.check(RN(G,H)),Q.length=(G,H)=>Q.check(wN(G,H)),Q.unwrap=()=>Q.element});function M6(Q,J){return TV0(b8Q,Q,J)}var Pq0=BQ("ZodObject",(Q,J)=>{jV0.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Fa(Q,G,H,K),I6.defineLazy(Q,"shape",()=>{return J.shape}),Q.keyof=()=>_J(Object.keys(Q._zod.def.shape)),Q.catchall=(G)=>Q.clone({...Q._zod.def,catchall:G}),Q.passthrough=()=>Q.clone({...Q._zod.def,catchall:h9()}),Q.loose=()=>Q.clone({...Q._zod.def,catchall:h9()}),Q.strict=()=>Q.clone({...Q._zod.def,catchall:x8Q()}),Q.strip=()=>Q.clone({...Q._zod.def,catchall:void 0}),Q.extend=(G)=>{return I6.extend(Q,G)},Q.safeExtend=(G)=>{return I6.safeExtend(Q,G)},Q.merge=(G)=>I6.merge(Q,G),Q.pick=(G)=>I6.pick(Q,G),Q.omit=(G)=>I6.omit(Q,G),Q.partial=(...G)=>I6.partial(xN,Q,G[0]),Q.required=(...G)=>I6.required(Cq0,Q,G[0])});function cQ(Q,J){let G={type:"object",shape:Q??{},...I6.normalizeParams(J)};return new Pq0(G)}function $J(Q,J){return new Pq0({type:"object",shape:Q,catchall:h9(),...I6.normalizeParams(J)})}var Nq0=BQ("ZodUnion",(Q,J)=>{ON.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Ma(Q,G,H,K),Q.options=J.options});function I9(Q,J){return new Nq0({type:"union",options:Q,...I6.normalizeParams(J)})}var g8Q=BQ("ZodDiscriminatedUnion",(Q,J)=>{Nq0.init(Q,J),Qc.init(Q,J)});function Fs(Q,J,G){return new g8Q({type:"union",options:J,discriminator:Q,...I6.normalizeParams(G)})}var h8Q=BQ("ZodIntersection",(Q,J)=>{Yc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>La(Q,G,H,K)});function vN(Q,J){return new h8Q({type:"intersection",left:Q,right:J})}var _8Q=BQ("ZodRecord",(Q,J)=>{Wc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Na(Q,G,H,K),Q.keyType=J.keyType,Q.valueType=J.valueType});function O9(Q,J,G){return new _8Q({type:"record",keyType:Q,valueType:J,...I6.normalizeParams(G)})}var qs=BQ("ZodEnum",(Q,J)=>{Bc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(H,K,z)=>Ga(Q,H,K,z),Q.enum=J.entries,Q.options=Object.values(J.entries);let G=new Set(Object.keys(J.entries));Q.extract=(H,K)=>{let z={};for(let q of H)if(G.has(q))z[q]=J.entries[q];else throw Error(`Key ${q} not found in enum`);return new qs({...J,checks:[],...I6.normalizeParams(K),entries:z})},Q.exclude=(H,K)=>{let z={...J.entries};for(let q of H)if(G.has(q))delete z[q];else throw Error(`Key ${q} not found in enum`);return new qs({...J,checks:[],...I6.normalizeParams(K),entries:z})}});function _J(Q,J){let G=Array.isArray(Q)?Object.fromEntries(Q.map((H)=>[H,H])):Q;return new qs({type:"enum",entries:G,...I6.normalizeParams(J)})}var f8Q=BQ("ZodLiteral",(Q,J)=>{Ac.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Wa(Q,G,H,K),Q.values=new Set(J.values),Object.defineProperty(Q,"value",{get(){if(J.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return J.values[0]}})});function H8(Q,J){return new f8Q({type:"literal",values:Array.isArray(Q)?Q:[Q],...I6.normalizeParams(J)})}var m8Q=BQ("ZodTransform",(Q,J)=>{Kc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>qa(Q,G,H,K),Q._zod.parse=(G,H)=>{if(H.direction==="backward")throw new wU(Q.constructor.name);G.addIssue=(z)=>{if(typeof z==="string")G.issues.push(I6.issue(z,G.value,J));else{let q=z;if(q.fatal)q.continue=!1;q.code??(q.code="custom"),q.input??(q.input=G.value),q.inst??(q.inst=Q),G.issues.push(I6.issue(q))}};let K=J.transform(G.value,G);if(K instanceof Promise)return K.then((z)=>{return G.value=z,G});return G.value=K,G}});function jq0(Q){return new m8Q({type:"transform",transform:Q})}var xN=BQ("ZodOptional",(Q,J)=>{PN.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>EN(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType});function _9(Q){return new xN({type:"optional",innerType:Q})}var u8Q=BQ("ZodExactOptional",(Q,J)=>{zc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>EN(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType});function p8Q(Q){return new u8Q({type:"optional",innerType:Q})}var l8Q=BQ("ZodNullable",(Q,J)=>{qc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>ja(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType});function Dq0(Q){return new l8Q({type:"nullable",innerType:Q})}var d8Q=BQ("ZodDefault",(Q,J)=>{$c.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Ia(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType,Q.removeDefault=Q.unwrap});function c8Q(Q,J){return new d8Q({type:"default",innerType:Q,get defaultValue(){return typeof J==="function"?J():I6.shallowClone(J)}})}var i8Q=BQ("ZodPrefault",(Q,J)=>{Zc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>ba(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType});function o8Q(Q,J){return new i8Q({type:"prefault",innerType:Q,get defaultValue(){return typeof J==="function"?J():I6.shallowClone(J)}})}var Cq0=BQ("ZodNonOptional",(Q,J)=>{Fc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Ca(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType});function n8Q(Q,J){return new Cq0({type:"nonoptional",innerType:Q,...I6.normalizeParams(J)})}var a8Q=BQ("ZodCatch",(Q,J)=>{Dc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Xs(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType,Q.removeCatch=Q.unwrap});function s8Q(Q,J){return new a8Q({type:"catch",innerType:Q,catchValue:typeof J==="function"?J:()=>J})}var r8Q=BQ("ZodPipe",(Q,J)=>{Mc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Js(Q,G,H,K),Q.in=J.in,Q.out=J.out});function Us(Q,J){return new r8Q({type:"pipe",in:Q,out:J})}var t8Q=BQ("ZodReadonly",(Q,J)=>{Lc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Gs(Q,G,H,K),Q.unwrap=()=>Q._zod.def.innerType});function e8Q(Q){return new t8Q({type:"readonly",innerType:Q})}var Iq0=BQ("ZodCustom",(Q,J)=>{Oc.init(Q,J),f9.init(Q,J),Q._zod.processJSONSchema=(G,H,K)=>Aa(Q,G,H,K)});function Rq0(Q,J){return on(Iq0,Q??(()=>!0),J)}function Q6Q(Q,J={}){return nn(Iq0,Q,J)}function X6Q(Q){return an(Q)}function Os(Q,J){return Us(jq0(Q),J)}hY(Pc());var Cs="2025-11-25",wq0="2025-03-26",qz=[Cs,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],m4="io.modelcontextprotocol/related-task",gN="2.0",b7=Rq0((Q)=>Q!==null&&(typeof Q==="object"||typeof Q==="function")),Eq0=I9([HQ(),o6().int()]),Sq0=HQ(),I98=$J({ttl:o6().optional(),pollInterval:o6().optional()}),J6Q=cQ({ttl:o6().optional()}),Y6Q=cQ({taskId:HQ()}),ws=$J({progressToken:Eq0.optional(),[m4]:Y6Q.optional()}),VY=cQ({_meta:ws.optional()}),nU=VY.extend({task:J6Q.optional()}),Tq0=(Q)=>nU.safeParse(Q).success,FX=cQ({method:HQ(),params:VY.loose().optional()}),fY=cQ({_meta:ws.optional()}),mY=cQ({method:HQ(),params:fY.loose().optional()}),DX=$J({_meta:ws.optional()}),hN=I9([HQ(),o6().int()]),kq0=cQ({jsonrpc:H8(gN),id:hN,...FX.shape}).strict(),u4=(Q)=>kq0.safeParse(Q).success,yq0=cQ({jsonrpc:H8(gN),...mY.shape}).strict(),vq0=(Q)=>yq0.safeParse(Q).success,Ss=cQ({jsonrpc:H8(gN),id:hN,result:DX}).strict(),C5=(Q)=>Ss.safeParse(Q).success;var nQ;(function(Q){Q[Q.ConnectionClosed=-32000]="ConnectionClosed",Q[Q.RequestTimeout=-32001]="RequestTimeout",Q[Q.ParseError=-32700]="ParseError",Q[Q.InvalidRequest=-32600]="InvalidRequest",Q[Q.MethodNotFound=-32601]="MethodNotFound",Q[Q.InvalidParams=-32602]="InvalidParams",Q[Q.InternalError=-32603]="InternalError",Q[Q.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(nQ||(nQ={}));var ks=cQ({jsonrpc:H8(gN),id:hN.optional(),error:cQ({code:o6().int(),message:HQ(),data:h9().optional()})}).strict();var Uz=(Q)=>ks.safeParse(Q).success;var vs=I9([kq0,yq0,Ss,ks]),R98=I9([Ss,ks]),_N=DX.strict(),G6Q=fY.extend({requestId:hN.optional(),reason:HQ().optional()}),fN=mY.extend({method:H8("notifications/cancelled"),params:G6Q}),W6Q=cQ({src:HQ(),mimeType:HQ().optional(),sizes:M6(HQ()).optional(),theme:_J(["light","dark"]).optional()}),aU=cQ({icons:M6(W6Q).optional()}),Vz=cQ({name:HQ(),title:HQ().optional()}),xq0=Vz.extend({...Vz.shape,...aU.shape,version:HQ(),websiteUrl:HQ().optional(),description:HQ().optional()}),H6Q=vN(cQ({applyDefaults:r7().optional()}),O9(HQ(),h9())),B6Q=Os((Q)=>{if(Q&&typeof Q==="object"&&!Array.isArray(Q)){if(Object.keys(Q).length===0)return{form:{}}}return Q},vN(cQ({form:H6Q.optional(),url:b7.optional()}),O9(HQ(),h9()).optional())),A6Q=$J({list:b7.optional(),cancel:b7.optional(),requests:$J({sampling:$J({createMessage:b7.optional()}).optional(),elicitation:$J({create:b7.optional()}).optional()}).optional()}),K6Q=$J({list:b7.optional(),cancel:b7.optional(),requests:$J({tools:$J({call:b7.optional()}).optional()}).optional()}),z6Q=cQ({experimental:O9(HQ(),b7).optional(),sampling:cQ({context:b7.optional(),tools:b7.optional()}).optional(),elicitation:B6Q.optional(),roots:cQ({listChanged:r7().optional()}).optional(),tasks:A6Q.optional(),extensions:O9(HQ(),b7).optional()}),V6Q=VY.extend({protocolVersion:HQ(),capabilities:z6Q,clientInfo:xq0}),mN=FX.extend({method:H8("initialize"),params:V6Q}),xs=(Q)=>mN.safeParse(Q).success,q6Q=cQ({experimental:O9(HQ(),b7).optional(),logging:b7.optional(),completions:b7.optional(),prompts:cQ({listChanged:r7().optional()}).optional(),resources:cQ({subscribe:r7().optional(),listChanged:r7().optional()}).optional(),tools:cQ({listChanged:r7().optional()}).optional(),tasks:K6Q.optional(),extensions:O9(HQ(),b7).optional()}),U6Q=DX.extend({protocolVersion:HQ(),capabilities:q6Q,serverInfo:xq0,instructions:HQ().optional()}),bs=mY.extend({method:H8("notifications/initialized"),params:fY.optional()});var uN=FX.extend({method:H8("ping"),params:VY.optional()}),$6Q=cQ({progress:o6(),total:_9(o6()),message:_9(HQ())}),Z6Q=cQ({...fY.shape,...$6Q.shape,progressToken:Eq0}),pN=mY.extend({method:H8("notifications/progress"),params:Z6Q}),F6Q=VY.extend({cursor:Sq0.optional()}),sU=FX.extend({params:F6Q.optional()}),rU=DX.extend({nextCursor:Sq0.optional()}),D6Q=_J(["working","input_required","completed","failed","cancelled"]),tU=cQ({taskId:HQ(),status:D6Q,ttl:I9([o6(),Oq0()]),createdAt:HQ(),lastUpdatedAt:HQ(),pollInterval:_9(o6()),statusMessage:_9(HQ())}),$z=DX.extend({task:tU}),M6Q=fY.merge(tU),eU=mY.extend({method:H8("notifications/tasks/status"),params:M6Q}),lN=FX.extend({method:H8("tasks/get"),params:VY.extend({taskId:HQ()})}),dN=DX.merge(tU),cN=FX.extend({method:H8("tasks/result"),params:VY.extend({taskId:HQ()})}),w98=DX.loose(),iN=sU.extend({method:H8("tasks/list")}),oN=rU.extend({tasks:M6(tU)}),nN=FX.extend({method:H8("tasks/cancel"),params:VY.extend({taskId:HQ()})}),bq0=DX.merge(tU),gq0=cQ({uri:HQ(),mimeType:_9(HQ()),_meta:O9(HQ(),h9()).optional()}),hq0=gq0.extend({text:HQ()}),gs=HQ().refine((Q)=>{try{return atob(Q),!0}catch{return!1}},{message:"Invalid Base64 string"}),_q0=gq0.extend({blob:gs}),D$=_J(["user","assistant"]),Zz=cQ({audience:M6(D$).optional(),priority:o6().min(0).max(1).optional(),lastModified:oU.datetime({offset:!0}).optional()}),fq0=cQ({...Vz.shape,...aU.shape,uri:HQ(),description:_9(HQ()),mimeType:_9(HQ()),size:_9(o6()),annotations:Zz.optional(),_meta:_9($J({}))}),L6Q=cQ({...Vz.shape,...aU.shape,uriTemplate:HQ(),description:_9(HQ()),mimeType:_9(HQ()),annotations:Zz.optional(),_meta:_9($J({}))}),aN=sU.extend({method:H8("resources/list")}),O6Q=rU.extend({resources:M6(fq0)}),sN=sU.extend({method:H8("resources/templates/list")}),P6Q=rU.extend({resourceTemplates:M6(L6Q)}),hs=VY.extend({uri:HQ()}),N6Q=hs,rN=FX.extend({method:H8("resources/read"),params:N6Q}),j6Q=DX.extend({contents:M6(I9([hq0,_q0]))}),C6Q=mY.extend({method:H8("notifications/resources/list_changed"),params:fY.optional()}),I6Q=hs,R6Q=FX.extend({method:H8("resources/subscribe"),params:I6Q}),w6Q=hs,E6Q=FX.extend({method:H8("resources/unsubscribe"),params:w6Q}),S6Q=fY.extend({uri:HQ()}),T6Q=mY.extend({method:H8("notifications/resources/updated"),params:S6Q}),k6Q=cQ({name:HQ(),description:_9(HQ()),required:_9(r7())}),y6Q=cQ({...Vz.shape,...aU.shape,description:_9(HQ()),arguments:_9(M6(k6Q)),_meta:_9($J({}))}),Fz=sU.extend({method:H8("prompts/list")}),v6Q=rU.extend({prompts:M6(y6Q)}),x6Q=VY.extend({name:HQ(),arguments:O9(HQ(),HQ()).optional()}),Dz=FX.extend({method:H8("prompts/get"),params:x6Q}),fs=cQ({type:H8("text"),text:HQ(),annotations:Zz.optional(),_meta:O9(HQ(),h9()).optional()}),ps=cQ({type:H8("image"),data:gs,mimeType:HQ(),annotations:Zz.optional(),_meta:O9(HQ(),h9()).optional()}),ls=cQ({type:H8("audio"),data:gs,mimeType:HQ(),annotations:Zz.optional(),_meta:O9(HQ(),h9()).optional()}),b6Q=cQ({type:H8("tool_use"),name:HQ(),id:HQ(),input:O9(HQ(),h9()),_meta:O9(HQ(),h9()).optional()}),g6Q=cQ({type:H8("resource"),resource:I9([hq0,_q0]),annotations:Zz.optional(),_meta:O9(HQ(),h9()).optional()}),h6Q=fq0.extend({type:H8("resource_link")}),cs=I9([fs,ps,ls,h6Q,g6Q]),_6Q=cQ({role:D$,content:cs}),f6Q=DX.extend({description:HQ().optional(),messages:M6(_6Q)}),m6Q=mY.extend({method:H8("notifications/prompts/list_changed"),params:fY.optional()}),u6Q=cQ({title:HQ().optional(),readOnlyHint:r7().optional(),destructiveHint:r7().optional(),idempotentHint:r7().optional(),openWorldHint:r7().optional()}),p6Q=cQ({taskSupport:_J(["required","optional","forbidden"]).optional()}),mq0=cQ({...Vz.shape,...aU.shape,description:HQ().optional(),inputSchema:cQ({type:H8("object"),properties:O9(HQ(),b7).optional(),required:M6(HQ()).optional()}).catchall(h9()),outputSchema:cQ({type:H8("object"),properties:O9(HQ(),b7).optional(),required:M6(HQ()).optional()}).catchall(h9()).optional(),annotations:u6Q.optional(),execution:p6Q.optional(),_meta:O9(HQ(),h9()).optional()}),Mz=sU.extend({method:H8("tools/list")}),l6Q=rU.extend({tools:M6(mq0)}),tN=DX.extend({content:M6(cs).default([]),structuredContent:O9(HQ(),h9()).optional(),isError:r7().optional()}),E98=tN.or(DX.extend({toolResult:h9()})),d6Q=nU.extend({name:HQ(),arguments:O9(HQ(),h9()).optional()}),p4=FX.extend({method:H8("tools/call"),params:d6Q}),c6Q=mY.extend({method:H8("notifications/tools/list_changed"),params:fY.optional()}),S98=cQ({autoRefresh:r7().default(!0),debounceMs:o6().int().nonnegative().default(300)}),k$=_J(["debug","info","notice","warning","error","critical","alert","emergency"]),i6Q=VY.extend({level:k$}),os=FX.extend({method:H8("logging/setLevel"),params:i6Q}),o6Q=fY.extend({level:k$,logger:HQ().optional(),data:h9()}),n6Q=mY.extend({method:H8("notifications/message"),params:o6Q}),a6Q=cQ({name:HQ().optional()}),s6Q=cQ({hints:M6(a6Q).optional(),costPriority:o6().min(0).max(1).optional(),speedPriority:o6().min(0).max(1).optional(),intelligencePriority:o6().min(0).max(1).optional()}),r6Q=cQ({mode:_J(["auto","required","none"]).optional()}),t6Q=cQ({type:H8("tool_result"),toolUseId:HQ().describe("The unique identifier for the corresponding tool call."),content:M6(cs).default([]),structuredContent:cQ({}).loose().optional(),isError:r7().optional(),_meta:O9(HQ(),h9()).optional()}),e6Q=Fs("type",[fs,ps,ls]),bN=Fs("type",[fs,ps,ls,b6Q,t6Q]),Q9Q=cQ({role:D$,content:I9([bN,M6(bN)]),_meta:O9(HQ(),h9()).optional()}),X9Q=nU.extend({messages:M6(Q9Q),modelPreferences:s6Q.optional(),systemPrompt:HQ().optional(),includeContext:_J(["none","thisServer","allServers"]).optional(),temperature:o6().optional(),maxTokens:o6().int(),stopSequences:M6(HQ()).optional(),metadata:b7.optional(),tools:M6(mq0).optional(),toolChoice:r6Q.optional()}),J9Q=FX.extend({method:H8("sampling/createMessage"),params:X9Q}),QZ=DX.extend({model:HQ(),stopReason:_9(_J(["endTurn","stopSequence","maxTokens"]).or(HQ())),role:D$,content:e6Q}),ns=DX.extend({model:HQ(),stopReason:_9(_J(["endTurn","stopSequence","maxTokens","toolUse"]).or(HQ())),role:D$,content:I9([bN,M6(bN)])}),Y9Q=cQ({type:H8("boolean"),title:HQ().optional(),description:HQ().optional(),default:r7().optional()}),G9Q=cQ({type:H8("string"),title:HQ().optional(),description:HQ().optional(),minLength:o6().optional(),maxLength:o6().optional(),format:_J(["email","uri","date","date-time"]).optional(),default:HQ().optional()}),W9Q=cQ({type:_J(["number","integer"]),title:HQ().optional(),description:HQ().optional(),minimum:o6().optional(),maximum:o6().optional(),default:o6().optional()}),H9Q=cQ({type:H8("string"),title:HQ().optional(),description:HQ().optional(),enum:M6(HQ()),default:HQ().optional()}),B9Q=cQ({type:H8("string"),title:HQ().optional(),description:HQ().optional(),oneOf:M6(cQ({const:HQ(),title:HQ()})),default:HQ().optional()}),A9Q=cQ({type:H8("string"),title:HQ().optional(),description:HQ().optional(),enum:M6(HQ()),enumNames:M6(HQ()).optional(),default:HQ().optional()}),K9Q=I9([H9Q,B9Q]),z9Q=cQ({type:H8("array"),title:HQ().optional(),description:HQ().optional(),minItems:o6().optional(),maxItems:o6().optional(),items:cQ({type:H8("string"),enum:M6(HQ())}),default:M6(HQ()).optional()}),V9Q=cQ({type:H8("array"),title:HQ().optional(),description:HQ().optional(),minItems:o6().optional(),maxItems:o6().optional(),items:cQ({anyOf:M6(cQ({const:HQ(),title:HQ()}))}),default:M6(HQ()).optional()}),q9Q=I9([z9Q,V9Q]),U9Q=I9([A9Q,K9Q,q9Q]),$9Q=I9([U9Q,Y9Q,G9Q,W9Q]),Z9Q=nU.extend({mode:H8("form").optional(),message:HQ(),requestedSchema:cQ({type:H8("object"),properties:O9(HQ(),$9Q),required:M6(HQ()).optional()})}),F9Q=nU.extend({mode:H8("url"),message:HQ(),elicitationId:HQ(),url:HQ().url()}),D9Q=I9([Z9Q,F9Q]),M9Q=FX.extend({method:H8("elicitation/create"),params:D9Q}),L9Q=fY.extend({elicitationId:HQ()}),O9Q=mY.extend({method:H8("notifications/elicitation/complete"),params:L9Q}),Lz=DX.extend({action:_J(["accept","decline","cancel"]),content:Os((Q)=>Q===null?void 0:Q,O9(HQ(),I9([HQ(),o6(),r7(),M6(HQ())])).optional())}),P9Q=cQ({type:H8("ref/resource"),uri:HQ()});var N9Q=cQ({type:H8("ref/prompt"),name:HQ()}),j9Q=VY.extend({ref:I9([N9Q,P9Q]),argument:cQ({name:HQ(),value:HQ()}),context:cQ({arguments:O9(HQ(),HQ()).optional()}).optional()}),eN=FX.extend({method:H8("completion/complete"),params:j9Q});function uq0(Q){if(Q.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${Q.params.ref.type}`)}function pq0(Q){if(Q.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${Q.params.ref.type}`)}var C9Q=DX.extend({completion:$J({values:M6(HQ()).max(100),total:_9(o6().int()),hasMore:_9(r7())})}),I9Q=cQ({uri:HQ().startsWith("file://"),name:HQ().optional(),_meta:O9(HQ(),h9()).optional()}),R9Q=FX.extend({method:H8("roots/list"),params:VY.optional()}),as=DX.extend({roots:M6(I9Q)}),w9Q=mY.extend({method:H8("notifications/roots/list_changed"),params:fY.optional()}),T98=I9([uN,mN,eN,os,Dz,Fz,aN,sN,rN,R6Q,E6Q,p4,Mz,lN,cN,iN,nN]),k98=I9([fN,pN,bs,w9Q,eU]),y98=I9([_N,QZ,ns,Lz,as,dN,oN,$z]),v98=I9([uN,J9Q,M9Q,R9Q,lN,cN,iN,nN]),x98=I9([fN,pN,n6Q,T6Q,C6Q,c6Q,m6Q,eU,O9Q]),b98=I9([_N,U6Q,C9Q,f6Q,v6Q,O6Q,P6Q,j6Q,tN,l6Q,dN,oN,$z]);class gQ extends Error{constructor(Q,J,G){super(`MCP error ${Q}: ${J}`);this.code=Q,this.data=G,this.name="McpError"}static fromError(Q,J,G){if(Q===nQ.UrlElicitationRequired&&G){let H=G;if(H.elicitations)return new lq0(H.elicitations,J)}return new gQ(Q,J,G)}}class lq0 extends gQ{constructor(Q,J=`URL elicitation${Q.length>1?"s":""} required`){super(nQ.UrlElicitationRequired,J,{elicitations:Q})}get elicitations(){return this.data?.elicitations??[]}}function l4(Q){return Q==="completed"||Q==="failed"||Q==="cancelled"}var cq0=Symbol("Let zodToJsonSchema decide on which parser to use");var dq0={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},iq0=(Q)=>typeof Q==="string"?{...dq0,name:Q}:{...dq0,...Q};var oq0=(Q)=>{let J=iq0(Q),G=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,flags:{hasReferencedOpenAiAnyType:!1},currentPath:G,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([H,K])=>[K._def,{def:K._def,path:[...J.basePath,J.definitionPath,H],jsonSchema:void 0}]))}};function es(Q,J,G,H){if(!H?.errorMessages)return;if(G)Q.errorMessage={...Q.errorMessage,[J]:G}}function L6(Q,J,G,H,K){Q[J]=G,es(Q,J,H,K)}var Qj=(Q,J)=>{let G=0;for(;G<Q.length&&G<J.length;G++)if(Q[G]!==J[G])break;return[(Q.length-G).toString(),...J.slice(G)].join("/")};function m9(Q){if(Q.target!=="openAi")return{};let J=[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName];return Q.flags.hasReferencedOpenAiAnyType=!0,{$ref:Q.$refStrategy==="relative"?Qj(J,Q.currentPath):J.join("/")}}function nq0(Q,J){let G={type:"array"};if(Q.type?._def&&Q.type?._def?.typeName!==CQ.ZodAny)G.items=E8(Q.type._def,{...J,currentPath:[...J.currentPath,"items"]});if(Q.minLength)L6(G,"minItems",Q.minLength.value,Q.minLength.message,J);if(Q.maxLength)L6(G,"maxItems",Q.maxLength.value,Q.maxLength.message,J);if(Q.exactLength)L6(G,"minItems",Q.exactLength.value,Q.exactLength.message,J),L6(G,"maxItems",Q.exactLength.value,Q.exactLength.message,J);return G}function aq0(Q,J){let G={type:"integer",format:"int64"};if(!Q.checks)return G;for(let H of Q.checks)switch(H.kind){case"min":if(J.target==="jsonSchema7")if(H.inclusive)L6(G,"minimum",H.value,H.message,J);else L6(G,"exclusiveMinimum",H.value,H.message,J);else{if(!H.inclusive)G.exclusiveMinimum=!0;L6(G,"minimum",H.value,H.message,J)}break;case"max":if(J.target==="jsonSchema7")if(H.inclusive)L6(G,"maximum",H.value,H.message,J);else L6(G,"exclusiveMaximum",H.value,H.message,J);else{if(!H.inclusive)G.exclusiveMaximum=!0;L6(G,"maximum",H.value,H.message,J)}break;case"multipleOf":L6(G,"multipleOf",H.value,H.message,J);break}return G}function sq0(){return{type:"boolean"}}function Xj(Q,J){return E8(Q.type._def,J)}var rq0=(Q,J)=>{return E8(Q.innerType._def,J)};function Gr(Q,J,G){let H=G??J.dateStrategy;if(Array.isArray(H))return{anyOf:H.map((K,z)=>Gr(Q,J,K))};switch(H){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return E9Q(Q,J)}}var E9Q=(Q,J)=>{let G={type:"integer",format:"unix-time"};if(J.target==="openApi3")return G;for(let H of Q.checks)switch(H.kind){case"min":L6(G,"minimum",H.value,H.message,J);break;case"max":L6(G,"maximum",H.value,H.message,J);break}return G};function tq0(Q,J){return{...E8(Q.innerType._def,J),default:Q.defaultValue()}}function eq0(Q,J){return J.effectStrategy==="input"?E8(Q.schema._def,J):m9(J)}function QU0(Q){return{type:"string",enum:Array.from(Q.values)}}var S9Q=(Q)=>{if("type"in Q&&Q.type==="string")return!1;return"allOf"in Q};function XU0(Q,J){let G=[E8(Q.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),E8(Q.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((z)=>!!z),H=J.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,K=[];return G.forEach((z)=>{if(S9Q(z)){if(K.push(...z.allOf),z.unevaluatedProperties===void 0)H=void 0}else{let q=z;if("additionalProperties"in z&&z.additionalProperties===!1){let{additionalProperties:F,...D}=z;q=D}else H=void 0;K.push(q)}}),K.length?{allOf:K,...H}:void 0}function JU0(Q,J){let G=typeof Q.value;if(G!=="bigint"&&G!=="number"&&G!=="boolean"&&G!=="string")return{type:Array.isArray(Q.value)?"array":"object"};if(J.target==="openApi3")return{type:G==="bigint"?"integer":G,enum:[Q.value]};return{type:G==="bigint"?"integer":G,const:Q.value}}var Vr=void 0,MG={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Vr===void 0)Vr=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Vr},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Jj(Q,J){let G={type:"string"};if(Q.checks)for(let H of Q.checks)switch(H.kind){case"min":L6(G,"minLength",typeof G.minLength==="number"?Math.max(G.minLength,H.value):H.value,H.message,J);break;case"max":L6(G,"maxLength",typeof G.maxLength==="number"?Math.min(G.maxLength,H.value):H.value,H.message,J);break;case"email":switch(J.emailStrategy){case"format:email":LG(G,"email",H.message,J);break;case"format:idn-email":LG(G,"idn-email",H.message,J);break;case"pattern:zod":ZJ(G,MG.email,H.message,J);break}break;case"url":LG(G,"uri",H.message,J);break;case"uuid":LG(G,"uuid",H.message,J);break;case"regex":ZJ(G,H.regex,H.message,J);break;case"cuid":ZJ(G,MG.cuid,H.message,J);break;case"cuid2":ZJ(G,MG.cuid2,H.message,J);break;case"startsWith":ZJ(G,RegExp(`^${Fr(H.value,J)}`),H.message,J);break;case"endsWith":ZJ(G,RegExp(`${Fr(H.value,J)}$`),H.message,J);break;case"datetime":LG(G,"date-time",H.message,J);break;case"date":LG(G,"date",H.message,J);break;case"time":LG(G,"time",H.message,J);break;case"duration":LG(G,"duration",H.message,J);break;case"length":L6(G,"minLength",typeof G.minLength==="number"?Math.max(G.minLength,H.value):H.value,H.message,J),L6(G,"maxLength",typeof G.maxLength==="number"?Math.min(G.maxLength,H.value):H.value,H.message,J);break;case"includes":{ZJ(G,RegExp(Fr(H.value,J)),H.message,J);break}case"ip":{if(H.version!=="v6")LG(G,"ipv4",H.message,J);if(H.version!=="v4")LG(G,"ipv6",H.message,J);break}case"base64url":ZJ(G,MG.base64url,H.message,J);break;case"jwt":ZJ(G,MG.jwt,H.message,J);break;case"cidr":{if(H.version!=="v6")ZJ(G,MG.ipv4Cidr,H.message,J);if(H.version!=="v4")ZJ(G,MG.ipv6Cidr,H.message,J);break}case"emoji":ZJ(G,MG.emoji(),H.message,J);break;case"ulid":{ZJ(G,MG.ulid,H.message,J);break}case"base64":{switch(J.base64Strategy){case"format:binary":{LG(G,"binary",H.message,J);break}case"contentEncoding:base64":{L6(G,"contentEncoding","base64",H.message,J);break}case"pattern:zod":{ZJ(G,MG.base64,H.message,J);break}}break}case"nanoid":ZJ(G,MG.nanoid,H.message,J);case"toLowerCase":case"toUpperCase":case"trim":break;default:((K)=>{})(H)}return G}function Fr(Q,J){return J.patternStrategy==="escape"?k9Q(Q):Q}var T9Q=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function k9Q(Q){let J="";for(let G=0;G<Q.length;G++){if(!T9Q.has(Q[G]))J+="\\";J+=Q[G]}return J}function LG(Q,J,G,H){if(Q.format||Q.anyOf?.some((K)=>K.format)){if(!Q.anyOf)Q.anyOf=[];if(Q.format){if(Q.anyOf.push({format:Q.format,...Q.errorMessage&&H.errorMessages&&{errorMessage:{format:Q.errorMessage.format}}}),delete Q.format,Q.errorMessage){if(delete Q.errorMessage.format,Object.keys(Q.errorMessage).length===0)delete Q.errorMessage}}Q.anyOf.push({format:J,...G&&H.errorMessages&&{errorMessage:{format:G}}})}else L6(Q,"format",J,G,H)}function ZJ(Q,J,G,H){if(Q.pattern||Q.allOf?.some((K)=>K.pattern)){if(!Q.allOf)Q.allOf=[];if(Q.pattern){if(Q.allOf.push({pattern:Q.pattern,...Q.errorMessage&&H.errorMessages&&{errorMessage:{pattern:Q.errorMessage.pattern}}}),delete Q.pattern,Q.errorMessage){if(delete Q.errorMessage.pattern,Object.keys(Q.errorMessage).length===0)delete Q.errorMessage}}Q.allOf.push({pattern:YU0(J,H),...G&&H.errorMessages&&{errorMessage:{pattern:G}}})}else L6(Q,"pattern",YU0(J,H),G,H)}function YU0(Q,J){if(!J.applyRegexFlags||!Q.flags)return Q.source;let G={i:Q.flags.includes("i"),m:Q.flags.includes("m"),s:Q.flags.includes("s")},H=G.i?Q.source.toLowerCase():Q.source,K="",z=!1,q=!1,F=!1;for(let D=0;D<H.length;D++){if(z){K+=H[D],z=!1;continue}if(G.i){if(q){if(H[D].match(/[a-z]/)){if(F)K+=H[D],K+=`${H[D-2]}-${H[D]}`.toUpperCase(),F=!1;else if(H[D+1]==="-"&&H[D+2]?.match(/[a-z]/))K+=H[D],F=!0;else K+=`${H[D]}${H[D].toUpperCase()}`;continue}}else if(H[D].match(/[a-z]/)){K+=`[${H[D]}${H[D].toUpperCase()}]`;continue}}if(G.m){if(H[D]==="^"){K+=`(^|(?<=[\r
]))`;continue}else if(H[D]==="$"){K+=`($|(?=[\r
]))`;continue}}if(G.s&&H[D]==="."){K+=q?`${H[D]}\r
`:`[${H[D]}\r
]`;continue}if(K+=H[D],H[D]==="\\")z=!0;else if(q&&H[D]==="]")q=!1;else if(!q&&H[D]==="[")q=!0}try{new RegExp(K)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),Q.source}return K}function Yj(Q,J){if(J.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(J.target==="openApi3"&&Q.keyType?._def.typeName===CQ.ZodEnum)return{type:"object",required:Q.keyType._def.values,properties:Q.keyType._def.values.reduce((H,K)=>({...H,[K]:E8(Q.valueType._def,{...J,currentPath:[...J.currentPath,"properties",K]})??m9(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let G={type:"object",additionalProperties:E8(Q.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(J.target==="openApi3")return G;if(Q.keyType?._def.typeName===CQ.ZodString&&Q.keyType._def.checks?.length){let{type:H,...K}=Jj(Q.keyType._def,J);return{...G,propertyNames:K}}else if(Q.keyType?._def.typeName===CQ.ZodEnum)return{...G,propertyNames:{enum:Q.keyType._def.values}};else if(Q.keyType?._def.typeName===CQ.ZodBranded&&Q.keyType._def.type._def.typeName===CQ.ZodString&&Q.keyType._def.type._def.checks?.length){let{type:H,...K}=Xj(Q.keyType._def,J);return{...G,propertyNames:K}}return G}function GU0(Q,J){if(J.mapStrategy==="record")return Yj(Q,J);let G=E8(Q.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||m9(J),H=E8(Q.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||m9(J);return{type:"array",maxItems:125,items:{type:"array",items:[G,H],minItems:2,maxItems:2}}}function WU0(Q){let J=Q.values,H=Object.keys(Q.values).filter((z)=>{return typeof J[J[z]]!=="number"}).map((z)=>J[z]),K=Array.from(new Set(H.map((z)=>typeof z)));return{type:K.length===1?K[0]==="string"?"string":"number":["string","number"],enum:H}}function HU0(Q){return Q.target==="openAi"?void 0:{not:m9({...Q,currentPath:[...Q.currentPath,"not"]})}}function BU0(Q){return Q.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var XZ={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function KU0(Q,J){if(J.target==="openApi3")return AU0(Q,J);let G=Q.options instanceof Map?Array.from(Q.options.values()):Q.options;if(G.every((H)=>(H._def.typeName in XZ)&&(!H._def.checks||!H._def.checks.length))){let H=G.reduce((K,z)=>{let q=XZ[z._def.typeName];return q&&!K.includes(q)?[...K,q]:K},[]);return{type:H.length>1?H:H[0]}}else if(G.every((H)=>H._def.typeName==="ZodLiteral"&&!H.description)){let H=G.reduce((K,z)=>{let q=typeof z._def.value;switch(q){case"string":case"number":case"boolean":return[...K,q];case"bigint":return[...K,"integer"];case"object":if(z._def.value===null)return[...K,"null"];case"symbol":case"undefined":case"function":default:return K}},[]);if(H.length===G.length){let K=H.filter((z,q,F)=>F.indexOf(z)===q);return{type:K.length>1?K:K[0],enum:G.reduce((z,q)=>{return z.includes(q._def.value)?z:[...z,q._def.value]},[])}}}else if(G.every((H)=>H._def.typeName==="ZodEnum"))return{type:"string",enum:G.reduce((H,K)=>[...H,...K._def.values.filter((z)=>!H.includes(z))],[])};return AU0(Q,J)}var AU0=(Q,J)=>{let G=(Q.options instanceof Map?Array.from(Q.options.values()):Q.options).map((H,K)=>E8(H._def,{...J,currentPath:[...J.currentPath,"anyOf",`${K}`]})).filter((H)=>!!H&&(!J.strictUnions||typeof H==="object"&&Object.keys(H).length>0));return G.length?{anyOf:G}:void 0};function zU0(Q,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(Q.innerType._def.typeName)&&(!Q.innerType._def.checks||!Q.innerType._def.checks.length)){if(J.target==="openApi3")return{type:XZ[Q.innerType._def.typeName],nullable:!0};return{type:[XZ[Q.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let H=E8(Q.innerType._def,{...J,currentPath:[...J.currentPath]});if(H&&"$ref"in H)return{allOf:[H],nullable:!0};return H&&{...H,nullable:!0}}let G=E8(Q.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return G&&{anyOf:[G,{type:"null"}]}}function VU0(Q,J){let G={type:"number"};if(!Q.checks)return G;for(let H of Q.checks)switch(H.kind){case"int":G.type="integer",es(G,"type",H.message,J);break;case"min":if(J.target==="jsonSchema7")if(H.inclusive)L6(G,"minimum",H.value,H.message,J);else L6(G,"exclusiveMinimum",H.value,H.message,J);else{if(!H.inclusive)G.exclusiveMinimum=!0;L6(G,"minimum",H.value,H.message,J)}break;case"max":if(J.target==="jsonSchema7")if(H.inclusive)L6(G,"maximum",H.value,H.message,J);else L6(G,"exclusiveMaximum",H.value,H.message,J);else{if(!H.inclusive)G.exclusiveMaximum=!0;L6(G,"maximum",H.value,H.message,J)}break;case"multipleOf":L6(G,"multipleOf",H.value,H.message,J);break}return G}function qU0(Q,J){let G=J.target==="openAi",H={type:"object",properties:{}},K=[],z=Q.shape();for(let F in z){let D=z[F];if(D===void 0||D._def===void 0)continue;let V=v9Q(D);if(V&&G){if(D._def.typeName==="ZodOptional")D=D._def.innerType;if(!D.isNullable())D=D.nullable();V=!1}let O=E8(D._def,{...J,currentPath:[...J.currentPath,"properties",F],propertyPath:[...J.currentPath,"properties",F]});if(O===void 0)continue;if(H.properties[F]=O,!V)K.push(F)}if(K.length)H.required=K;let q=y9Q(Q,J);if(q!==void 0)H.additionalProperties=q;return H}function y9Q(Q,J){if(Q.catchall._def.typeName!=="ZodNever")return E8(Q.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch(Q.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function v9Q(Q){try{return Q.isOptional()}catch{return!0}}var UU0=(Q,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return E8(Q.innerType._def,J);let G=E8(Q.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return G?{anyOf:[{not:m9(J)},G]}:m9(J)};var $U0=(Q,J)=>{if(J.pipeStrategy==="input")return E8(Q.in._def,J);else if(J.pipeStrategy==="output")return E8(Q.out._def,J);let G=E8(Q.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),H=E8(Q.out._def,{...J,currentPath:[...J.currentPath,"allOf",G?"1":"0"]});return{allOf:[G,H].filter((K)=>K!==void 0)}};function ZU0(Q,J){return E8(Q.type._def,J)}function FU0(Q,J){let H={type:"array",uniqueItems:!0,items:E8(Q.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if(Q.minSize)L6(H,"minItems",Q.minSize.value,Q.minSize.message,J);if(Q.maxSize)L6(H,"maxItems",Q.maxSize.value,Q.maxSize.message,J);return H}function DU0(Q,J){if(Q.rest)return{type:"array",minItems:Q.items.length,items:Q.items.map((G,H)=>E8(G._def,{...J,currentPath:[...J.currentPath,"items",`${H}`]})).reduce((G,H)=>H===void 0?G:[...G,H],[]),additionalItems:E8(Q.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:Q.items.length,maxItems:Q.items.length,items:Q.items.map((G,H)=>E8(G._def,{...J,currentPath:[...J.currentPath,"items",`${H}`]})).reduce((G,H)=>H===void 0?G:[...G,H],[])}}function MU0(Q){return{not:m9(Q)}}function LU0(Q){return m9(Q)}var OU0=(Q,J)=>{return E8(Q.innerType._def,J)};var PU0=(Q,J,G)=>{switch(J){case CQ.ZodString:return Jj(Q,G);case CQ.ZodNumber:return VU0(Q,G);case CQ.ZodObject:return qU0(Q,G);case CQ.ZodBigInt:return aq0(Q,G);case CQ.ZodBoolean:return sq0();case CQ.ZodDate:return Gr(Q,G);case CQ.ZodUndefined:return MU0(G);case CQ.ZodNull:return BU0(G);case CQ.ZodArray:return nq0(Q,G);case CQ.ZodUnion:case CQ.ZodDiscriminatedUnion:return KU0(Q,G);case CQ.ZodIntersection:return XU0(Q,G);case CQ.ZodTuple:return DU0(Q,G);case CQ.ZodRecord:return Yj(Q,G);case CQ.ZodLiteral:return JU0(Q,G);case CQ.ZodEnum:return QU0(Q);case CQ.ZodNativeEnum:return WU0(Q);case CQ.ZodNullable:return zU0(Q,G);case CQ.ZodOptional:return UU0(Q,G);case CQ.ZodMap:return GU0(Q,G);case CQ.ZodSet:return FU0(Q,G);case CQ.ZodLazy:return()=>Q.getter()._def;case CQ.ZodPromise:return ZU0(Q,G);case CQ.ZodNaN:case CQ.ZodNever:return HU0(G);case CQ.ZodEffects:return eq0(Q,G);case CQ.ZodAny:return m9(G);case CQ.ZodUnknown:return LU0(G);case CQ.ZodDefault:return tq0(Q,G);case CQ.ZodBranded:return Xj(Q,G);case CQ.ZodReadonly:return OU0(Q,G);case CQ.ZodCatch:return rq0(Q,G);case CQ.ZodPipeline:return $U0(Q,G);case CQ.ZodFunction:case CQ.ZodVoid:case CQ.ZodSymbol:return;default:return((H)=>{return})(J)}};function E8(Q,J,G=!1){let H=J.seen.get(Q);if(J.override){let F=J.override?.(Q,J,H,G);if(F!==cq0)return F}if(H&&!G){let F=x9Q(H,J);if(F!==void 0)return F}let K={def:Q,path:J.currentPath,jsonSchema:void 0};J.seen.set(Q,K);let z=PU0(Q,Q.typeName,J),q=typeof z==="function"?E8(z(),J):z;if(q)b9Q(Q,J,q);if(J.postProcess){let F=J.postProcess(q,Q,J);return K.jsonSchema=q,F}return K.jsonSchema=q,q}var x9Q=(Q,J)=>{switch(J.$refStrategy){case"root":return{$ref:Q.path.join("/")};case"relative":return{$ref:Qj(J.currentPath,Q.path)};case"none":case"seen":{if(Q.path.length<J.currentPath.length&&Q.path.every((G,H)=>J.currentPath[H]===G))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),m9(J);return J.$refStrategy==="seen"?m9(J):void 0}}},b9Q=(Q,J,G)=>{if(Q.description){if(G.description=Q.description,J.markdownDescription)G.markdownDescription=Q.description}return G};var mr=(Q,J)=>{let G=oq0(J),H=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((D,[V,O])=>({...D,[V]:E8(O._def,{...G,currentPath:[...G.basePath,G.definitionPath,V]},!0)??m9(G)}),{}):void 0,K=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,z=E8(Q._def,K===void 0?G:{...G,currentPath:[...G.basePath,G.definitionPath,K]},!1)??m9(G),q=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(q!==void 0)z.title=q;if(G.flags.hasReferencedOpenAiAnyType){if(!H)H={};if(!H[G.openAiAnyTypeName])H[G.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:G.$refStrategy==="relative"?"1":[...G.basePath,G.definitionPath,G.openAiAnyTypeName].join("/")}}}let F=K===void 0?H?{...z,[G.definitionPath]:H}:z:{$ref:[...G.$refStrategy==="relative"?[]:G.basePath,G.definitionPath,K].join("/"),[G.definitionPath]:{...H,[K]:z}};if(G.target==="jsonSchema7")F.$schema="http://json-schema.org/draft-07/schema#";else if(G.target==="jsonSchema2019-09"||G.target==="openAi")F.$schema="https://json-schema.org/draft/2019-09/schema#";if(G.target==="openAi"&&(("anyOf"in F)||("oneOf"in F)||("allOf"in F)||("type"in F)&&Array.isArray(F.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return F};function g9Q(Q){if(!Q)return"draft-7";if(Q==="jsonSchema7"||Q==="draft-7")return"draft-7";if(Q==="jsonSchema2019-09"||Q==="draft-2020-12")return"draft-2020-12";return"draft-7"}function ar(Q,J){if(_Y(Q))return Ws(Q,{target:g9Q(J?.target),io:J?.pipeStrategy??"input"});return mr(Q,{strictUnions:J?.strictUnions??!0,pipeStrategy:J?.pipeStrategy??"input"})}function Qt(Q){let G=f4(Q)?.method;if(!G)throw Error("Schema is missing a method literal");let H=kN(G);if(typeof H!=="string")throw Error("Schema method literal must be a string");return H}function Xt(Q,J){let G=_4(Q,J);if(!G.success)throw G.error;return G.data}var h9Q=60000;class Jt{constructor(Q){if(this._options=Q,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(fN,(J)=>{this._oncancel(J)}),this.setNotificationHandler(pN,(J)=>{this._onprogress(J)}),this.setRequestHandler(uN,(J)=>({})),this._taskStore=Q?.taskStore,this._taskMessageQueue=Q?.taskMessageQueue,this._taskStore)this.setRequestHandler(lN,async(J,G)=>{let H=await this._taskStore.getTask(J.params.taskId,G.sessionId);if(!H)throw new gQ(nQ.InvalidParams,"Failed to retrieve task: Task not found");return{...H}}),this.setRequestHandler(cN,async(J,G)=>{let H=async()=>{let K=J.params.taskId;if(this._taskMessageQueue){let q;while(q=await this._taskMessageQueue.dequeue(K,G.sessionId)){if(q.type==="response"||q.type==="error"){let F=q.message,D=F.id,V=this._requestResolvers.get(D);if(V)if(this._requestResolvers.delete(D),q.type==="response")V(F);else{let O=F,P=new gQ(O.error.code,O.error.message,O.error.data);V(P)}else{let O=q.type==="response"?"Response":"Error";this._onerror(Error(`${O} handler missing for request ${D}`))}continue}await this._transport?.send(q.message,{relatedRequestId:G.requestId})}}let z=await this._taskStore.getTask(K,G.sessionId);if(!z)throw new gQ(nQ.InvalidParams,`Task not found: ${K}`);if(!l4(z.status))return await this._waitForTaskUpdate(K,G.signal),await H();if(l4(z.status)){let q=await this._taskStore.getTaskResult(K,G.sessionId);return this._clearTaskQueue(K),{...q,_meta:{...q._meta,[m4]:{taskId:K}}}}return await H()};return await H()}),this.setRequestHandler(iN,async(J,G)=>{try{let{tasks:H,nextCursor:K}=await this._taskStore.listTasks(J.params?.cursor,G.sessionId);return{tasks:H,nextCursor:K,_meta:{}}}catch(H){throw new gQ(nQ.InvalidParams,`Failed to list tasks: ${H instanceof Error?H.message:String(H)}`)}}),this.setRequestHandler(nN,async(J,G)=>{try{let H=await this._taskStore.getTask(J.params.taskId,G.sessionId);if(!H)throw new gQ(nQ.InvalidParams,`Task not found: ${J.params.taskId}`);if(l4(H.status))throw new gQ(nQ.InvalidParams,`Cannot cancel task in terminal status: ${H.status}`);await this._taskStore.updateTaskStatus(J.params.taskId,"cancelled","Client cancelled task execution.",G.sessionId),this._clearTaskQueue(J.params.taskId);let K=await this._taskStore.getTask(J.params.taskId,G.sessionId);if(!K)throw new gQ(nQ.InvalidParams,`Task not found after cancellation: ${J.params.taskId}`);return{_meta:{},...K}}catch(H){if(H instanceof gQ)throw H;throw new gQ(nQ.InvalidRequest,`Failed to cancel task: ${H instanceof Error?H.message:String(H)}`)}})}async _oncancel(Q){if(!Q.params.requestId)return;this._requestHandlerAbortControllers.get(Q.params.requestId)?.abort(Q.params.reason)}_setupTimeout(Q,J,G,H,K=!1){this._timeoutInfo.set(Q,{timeoutId:setTimeout(H,J),startTime:Date.now(),timeout:J,maxTotalTimeout:G,resetTimeoutOnProgress:K,onTimeout:H})}_resetTimeout(Q){let J=this._timeoutInfo.get(Q);if(!J)return!1;let G=Date.now()-J.startTime;if(J.maxTotalTimeout&&G>=J.maxTotalTimeout)throw this._timeoutInfo.delete(Q),gQ.fromError(nQ.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:J.maxTotalTimeout,totalElapsed:G});return clearTimeout(J.timeoutId),J.timeoutId=setTimeout(J.onTimeout,J.timeout),!0}_cleanupTimeout(Q){let J=this._timeoutInfo.get(Q);if(J)clearTimeout(J.timeoutId),this._timeoutInfo.delete(Q)}async connect(Q){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=Q;let J=this.transport?.onclose;this._transport.onclose=()=>{J?.(),this._onclose()};let G=this.transport?.onerror;this._transport.onerror=(K)=>{G?.(K),this._onerror(K)};let H=this._transport?.onmessage;this._transport.onmessage=(K,z)=>{if(H?.(K,z),C5(K)||Uz(K))this._onresponse(K);else if(u4(K))this._onrequest(K,z);else if(vq0(K))this._onnotification(K);else this._onerror(Error(`Unknown message type: ${JSON.stringify(K)}`))},await this._transport.start()}_onclose(){let Q=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let G of this._timeoutInfo.values())clearTimeout(G.timeoutId);this._timeoutInfo.clear();for(let G of this._requestHandlerAbortControllers.values())G.abort();this._requestHandlerAbortControllers.clear();let J=gQ.fromError(nQ.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let G of Q.values())G(J)}_onerror(Q){this.onerror?.(Q)}_onnotification(Q){let J=this._notificationHandlers.get(Q.method)??this.fallbackNotificationHandler;if(J===void 0)return;Promise.resolve().then(()=>J(Q)).catch((G)=>this._onerror(Error(`Uncaught error in notification handler: ${G}`)))}_onrequest(Q,J){let G=this._requestHandlers.get(Q.method)??this.fallbackRequestHandler,H=this._transport,K=Q.params?._meta?.[m4]?.taskId;if(G===void 0){let V={jsonrpc:"2.0",id:Q.id,error:{code:nQ.MethodNotFound,message:"Method not found"}};if(K&&this._taskMessageQueue)this._enqueueTaskMessage(K,{type:"error",message:V,timestamp:Date.now()},H?.sessionId).catch((O)=>this._onerror(Error(`Failed to enqueue error response: ${O}`)));else H?.send(V).catch((O)=>this._onerror(Error(`Failed to send an error response: ${O}`)));return}let z=new AbortController;this._requestHandlerAbortControllers.set(Q.id,z);let q=Tq0(Q.params)?Q.params.task:void 0,F=this._taskStore?this.requestTaskStore(Q,H?.sessionId):void 0,D={signal:z.signal,sessionId:H?.sessionId,_meta:Q.params?._meta,sendNotification:async(V)=>{if(z.signal.aborted)return;let O={relatedRequestId:Q.id};if(K)O.relatedTask={taskId:K};await this.notification(V,O)},sendRequest:async(V,O,P)=>{if(z.signal.aborted)throw new gQ(nQ.ConnectionClosed,"Request was cancelled");let N={...P,relatedRequestId:Q.id};if(K&&!N.relatedTask)N.relatedTask={taskId:K};let I=N.relatedTask?.taskId??K;if(I&&F)await F.updateTaskStatus(I,"input_required");return await this.request(V,O,N)},authInfo:J?.authInfo,requestId:Q.id,requestInfo:J?.requestInfo,taskId:K,taskStore:F,taskRequestedTtl:q?.ttl,closeSSEStream:J?.closeSSEStream,closeStandaloneSSEStream:J?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(q)this.assertTaskHandlerCapability(Q.method)}).then(()=>G(Q,D)).then(async(V)=>{if(z.signal.aborted)return;let O={result:V,jsonrpc:"2.0",id:Q.id};if(K&&this._taskMessageQueue)await this._enqueueTaskMessage(K,{type:"response",message:O,timestamp:Date.now()},H?.sessionId);else await H?.send(O)},async(V)=>{if(z.signal.aborted)return;let O={jsonrpc:"2.0",id:Q.id,error:{code:Number.isSafeInteger(V.code)?V.code:nQ.InternalError,message:V.message??"Internal error",...V.data!==void 0&&{data:V.data}}};if(K&&this._taskMessageQueue)await this._enqueueTaskMessage(K,{type:"error",message:O,timestamp:Date.now()},H?.sessionId);else await H?.send(O)}).catch((V)=>this._onerror(Error(`Failed to send response: ${V}`))).finally(()=>{if(this._requestHandlerAbortControllers.get(Q.id)===z)this._requestHandlerAbortControllers.delete(Q.id)})}_onprogress(Q){let{progressToken:J,...G}=Q.params,H=Number(J),K=this._progressHandlers.get(H);if(!K){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(Q)}`));return}let z=this._responseHandlers.get(H),q=this._timeoutInfo.get(H);if(q&&z&&q.resetTimeoutOnProgress)try{this._resetTimeout(H)}catch(F){this._responseHandlers.delete(H),this._progressHandlers.delete(H),this._cleanupTimeout(H),z(F);return}K(G)}_onresponse(Q){let J=Number(Q.id),G=this._requestResolvers.get(J);if(G){if(this._requestResolvers.delete(J),C5(Q))G(Q);else{let z=new gQ(Q.error.code,Q.error.message,Q.error.data);G(z)}return}let H=this._responseHandlers.get(J);if(H===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(Q)}`));return}this._responseHandlers.delete(J),this._cleanupTimeout(J);let K=!1;if(C5(Q)&&Q.result&&typeof Q.result==="object"){let z=Q.result;if(z.task&&typeof z.task==="object"){let q=z.task;if(typeof q.taskId==="string")K=!0,this._taskProgressTokens.set(q.taskId,J)}}if(!K)this._progressHandlers.delete(J);if(C5(Q))H(Q);else{let z=gQ.fromError(Q.error.code,Q.error.message,Q.error.data);H(z)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(Q,J,G){let{task:H}=G??{};if(!H){try{yield{type:"result",result:await this.request(Q,J,G)}}catch(z){yield{type:"error",error:z instanceof gQ?z:new gQ(nQ.InternalError,String(z))}}return}let K;try{let z=await this.request(Q,$z,G);if(z.task)K=z.task.taskId,yield{type:"taskCreated",task:z.task};else throw new gQ(nQ.InternalError,"Task creation did not return a task");while(!0){let q=await this.getTask({taskId:K},G);if(yield{type:"taskStatus",task:q},l4(q.status)){if(q.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:K},J,G)};else if(q.status==="failed")yield{type:"error",error:new gQ(nQ.InternalError,`Task ${K} failed`)};else if(q.status==="cancelled")yield{type:"error",error:new gQ(nQ.InternalError,`Task ${K} was cancelled`)};return}if(q.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:K},J,G)};return}let F=q.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((D)=>setTimeout(D,F)),G?.signal?.throwIfAborted()}}catch(z){yield{type:"error",error:z instanceof gQ?z:new gQ(nQ.InternalError,String(z))}}}request(Q,J,G){let{relatedRequestId:H,resumptionToken:K,onresumptiontoken:z,task:q,relatedTask:F}=G??{};return new Promise((D,V)=>{let O=(T)=>{V(T)};if(!this._transport){O(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod(Q.method),q)this.assertTaskCapability(Q.method)}catch(T){O(T);return}G?.signal?.throwIfAborted();let P=this._requestMessageId++,N={...Q,jsonrpc:"2.0",id:P};if(G?.onprogress)this._progressHandlers.set(P,G.onprogress),N.params={...Q.params,_meta:{...Q.params?._meta||{},progressToken:P}};if(q)N.params={...N.params,task:q};if(F)N.params={...N.params,_meta:{...N.params?._meta||{},[m4]:F}};let I=(T)=>{this._responseHandlers.delete(P),this._progressHandlers.delete(P),this._cleanupTimeout(P),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:P,reason:String(T)}},{relatedRequestId:H,resumptionToken:K,onresumptiontoken:z}).catch((x)=>this._onerror(Error(`Failed to send cancellation: ${x}`)));let y=T instanceof gQ?T:new gQ(nQ.RequestTimeout,String(T));V(y)};this._responseHandlers.set(P,(T)=>{if(G?.signal?.aborted)return;if(T instanceof Error)return V(T);try{let y=_4(J,T.result);if(!y.success)V(y.error);else D(y.data)}catch(y){V(y)}}),G?.signal?.addEventListener("abort",()=>{I(G?.signal?.reason)});let R=G?.timeout??h9Q,w=()=>I(gQ.fromError(nQ.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(P,R,G?.maxTotalTimeout,w,G?.resetTimeoutOnProgress??!1);let E=F?.taskId;if(E){let T=(y)=>{let x=this._responseHandlers.get(P);if(x)x(y);else this._onerror(Error(`Response handler missing for side-channeled request ${P}`))};this._requestResolvers.set(P,T),this._enqueueTaskMessage(E,{type:"request",message:N,timestamp:Date.now()}).catch((y)=>{this._cleanupTimeout(P),V(y)})}else this._transport.send(N,{relatedRequestId:H,resumptionToken:K,onresumptiontoken:z}).catch((T)=>{this._cleanupTimeout(P),V(T)})})}async getTask(Q,J){return this.request({method:"tasks/get",params:Q},dN,J)}async getTaskResult(Q,J,G){return this.request({method:"tasks/result",params:Q},J,G)}async listTasks(Q,J){return this.request({method:"tasks/list",params:Q},oN,J)}async cancelTask(Q,J){return this.request({method:"tasks/cancel",params:Q},bq0,J)}async notification(Q,J){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(Q.method);let G=J?.relatedTask?.taskId;if(G){let q={...Q,jsonrpc:"2.0",params:{...Q.params,_meta:{...Q.params?._meta||{},[m4]:J.relatedTask}}};await this._enqueueTaskMessage(G,{type:"notification",message:q,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(Q.method)&&!Q.params&&!J?.relatedRequestId&&!J?.relatedTask){if(this._pendingDebouncedNotifications.has(Q.method))return;this._pendingDebouncedNotifications.add(Q.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(Q.method),!this._transport)return;let q={...Q,jsonrpc:"2.0"};if(J?.relatedTask)q={...q,params:{...q.params,_meta:{...q.params?._meta||{},[m4]:J.relatedTask}}};this._transport?.send(q,J).catch((F)=>this._onerror(F))});return}let z={...Q,jsonrpc:"2.0"};if(J?.relatedTask)z={...z,params:{...z.params,_meta:{...z.params?._meta||{},[m4]:J.relatedTask}}};await this._transport.send(z,J)}setRequestHandler(Q,J){let G=Qt(Q);this.assertRequestHandlerCapability(G),this._requestHandlers.set(G,(H,K)=>{let z=Xt(Q,H);return Promise.resolve(J(z,K))})}removeRequestHandler(Q){this._requestHandlers.delete(Q)}assertCanSetRequestHandler(Q){if(this._requestHandlers.has(Q))throw Error(`A request handler for ${Q} already exists, which would be overridden`)}setNotificationHandler(Q,J){let G=Qt(Q);this._notificationHandlers.set(G,(H)=>{let K=Xt(Q,H);return Promise.resolve(J(K))})}removeNotificationHandler(Q){this._notificationHandlers.delete(Q)}_cleanupTaskProgressHandler(Q){let J=this._taskProgressTokens.get(Q);if(J!==void 0)this._progressHandlers.delete(J),this._taskProgressTokens.delete(Q)}async _enqueueTaskMessage(Q,J,G){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let H=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(Q,J,G,H)}async _clearTaskQueue(Q,J){if(this._taskMessageQueue){let G=await this._taskMessageQueue.dequeueAll(Q,J);for(let H of G)if(H.type==="request"&&u4(H.message)){let K=H.message.id,z=this._requestResolvers.get(K);if(z)z(new gQ(nQ.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(K);else this._onerror(Error(`Resolver missing for request ${K} during task ${Q} cleanup`))}}}async _waitForTaskUpdate(Q,J){let G=this._options?.defaultTaskPollInterval??1000;try{let H=await this._taskStore?.getTask(Q);if(H?.pollInterval)G=H.pollInterval}catch{}return new Promise((H,K)=>{if(J.aborted){K(new gQ(nQ.InvalidRequest,"Request cancelled"));return}let z=setTimeout(H,G);J.addEventListener("abort",()=>{clearTimeout(z),K(new gQ(nQ.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(Q,J){let G=this._taskStore;if(!G)throw Error("No task store configured");return{createTask:async(H)=>{if(!Q)throw Error("No request provided");return await G.createTask(H,Q.id,{method:Q.method,params:Q.params},J)},getTask:async(H)=>{let K=await G.getTask(H,J);if(!K)throw new gQ(nQ.InvalidParams,"Failed to retrieve task: Task not found");return K},storeTaskResult:async(H,K,z)=>{await G.storeTaskResult(H,K,z,J);let q=await G.getTask(H,J);if(q){let F=eU.parse({method:"notifications/tasks/status",params:q});if(await this.notification(F),l4(q.status))this._cleanupTaskProgressHandler(H)}},getTaskResult:(H)=>{return G.getTaskResult(H,J)},updateTaskStatus:async(H,K,z)=>{let q=await G.getTask(H,J);if(!q)throw new gQ(nQ.InvalidParams,`Task "${H}" not found - it may have been cleaned up`);if(l4(q.status))throw new gQ(nQ.InvalidParams,`Cannot update task "${H}" from terminal status "${q.status}" to "${K}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await G.updateTaskStatus(H,K,z,J);let F=await G.getTask(H,J);if(F){let D=eU.parse({method:"notifications/tasks/status",params:F});if(await this.notification(D),l4(F.status))this._cleanupTaskProgressHandler(H)}},listTasks:(H)=>{return G.listTasks(H,J)}}}}function NU0(Q){return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)}function jU0(Q,J){let G={...Q};for(let H in J){let K=H,z=J[K];if(z===void 0)continue;let q=G[K];if(NU0(q)&&NU0(z))G[K]={...q,...z};else G[K]=z}return G}var SF0=K7(b00(),1),TF0=K7(EF0(),1);function mGQ(){let Q=new SF0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return TF0.default(Q),Q}class l00{constructor(Q){this._ajv=Q??mGQ()}getValidator(Q){let J="$id"in Q&&typeof Q.$id==="string"?this._ajv.getSchema(Q.$id)??this._ajv.compile(Q):this._ajv.compile(Q);return(G)=>{if(J(G))return{valid:!0,data:G,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(J.errors)}}}}class d00{constructor(Q){this._server=Q}requestStream(Q,J,G){return this._server.requestStream(Q,J,G)}createMessageStream(Q,J){let G=this._server.getClientCapabilities();if((Q.tools||Q.toolChoice)&&!G?.sampling?.tools)throw Error("Client does not support sampling tools capability.");if(Q.messages.length>0){let H=Q.messages[Q.messages.length-1],K=Array.isArray(H.content)?H.content:[H.content],z=K.some((V)=>V.type==="tool_result"),q=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,F=q?Array.isArray(q.content)?q.content:[q.content]:[],D=F.some((V)=>V.type==="tool_use");if(z){if(K.some((V)=>V.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!D)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(D){let V=new Set(F.filter((P)=>P.type==="tool_use").map((P)=>P.id)),O=new Set(K.filter((P)=>P.type==="tool_result").map((P)=>P.toolUseId));if(V.size!==O.size||![...V].every((P)=>O.has(P)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:Q},QZ,J)}elicitInputStream(Q,J){let G=this._server.getClientCapabilities(),H=Q.mode??"form";switch(H){case"url":{if(!G?.elicitation?.url)throw Error("Client does not support url elicitation.");break}case"form":{if(!G?.elicitation?.form)throw Error("Client does not support form elicitation.");break}}let K=H==="form"&&Q.mode===void 0?{...Q,mode:"form"}:Q;return this.requestStream({method:"elicitation/create",params:K},Lz,J)}async getTask(Q,J){return this._server.getTask({taskId:Q},J)}async getTaskResult(Q,J,G){return this._server.getTaskResult({taskId:Q},J,G)}async listTasks(Q,J){return this._server.listTasks(Q?{cursor:Q}:void 0,J)}async cancelTask(Q,J){return this._server.cancelTask({taskId:Q},J)}}function kF0(Q,J,G){if(!Q)throw Error(`${G} does not support task creation (required for ${J})`);switch(J){case"tools/call":if(!Q.tools?.call)throw Error(`${G} does not support task creation for tools/call (required for ${J})`);break;default:break}}function yF0(Q,J,G){if(!Q)throw Error(`${G} does not support task creation (required for ${J})`);switch(J){case"sampling/createMessage":if(!Q.sampling?.createMessage)throw Error(`${G} does not support task creation for sampling/createMessage (required for ${J})`);break;case"elicitation/create":if(!Q.elicitation?.create)throw Error(`${G} does not support task creation for elicitation/create (required for ${J})`);break;default:break}}class c00 extends Jt{constructor(Q,J){super(J);if(this._serverInfo=Q,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(k$.options.map((G,H)=>[G,H])),this.isMessageIgnored=(G,H)=>{let K=this._loggingLevels.get(H);return K?this.LOG_LEVEL_SEVERITY.get(G)<this.LOG_LEVEL_SEVERITY.get(K):!1},this._capabilities=J?.capabilities??{},this._instructions=J?.instructions,this._jsonSchemaValidator=J?.jsonSchemaValidator??new l00,this.setRequestHandler(mN,(G)=>this._oninitialize(G)),this.setNotificationHandler(bs,()=>this.oninitialized?.()),this._capabilities.logging)this.setRequestHandler(os,async(G,H)=>{let K=H.sessionId||H.requestInfo?.headers["mcp-session-id"]||void 0,{level:z}=G.params,q=k$.safeParse(z);if(q.success)this._loggingLevels.set(K,q.data);return{}})}get experimental(){if(!this._experimental)this._experimental={tasks:new d00(this)};return this._experimental}registerCapabilities(Q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=jU0(this._capabilities,Q)}setRequestHandler(Q,J){let H=f4(Q)?.method;if(!H)throw Error("Schema is missing a method literal");let K;if(_Y(H)){let q=H;K=q._zod?.def?.value??q.value}else{let q=H;K=q._def?.value??q.value}if(typeof K!=="string")throw Error("Schema method literal must be a string");if(K==="tools/call"){let q=async(F,D)=>{let V=_4(p4,F);if(!V.success){let I=V.error instanceof Error?V.error.message:String(V.error);throw new gQ(nQ.InvalidParams,`Invalid tools/call request: ${I}`)}let{params:O}=V.data,P=await Promise.resolve(J(F,D));if(O.task){let I=_4($z,P);if(!I.success){let R=I.error instanceof Error?I.error.message:String(I.error);throw new gQ(nQ.InvalidParams,`Invalid task creation result: ${R}`)}return I.data}let N=_4(tN,P);if(!N.success){let I=N.error instanceof Error?N.error.message:String(N.error);throw new gQ(nQ.InvalidParams,`Invalid tools/call result: ${I}`)}return N.data};return super.setRequestHandler(Q,q)}return super.setRequestHandler(Q,J)}assertCapabilityForMethod(Q){switch(Q){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${Q})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${Q})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${Q})`);break;case"ping":break}}assertNotificationCapability(Q){switch(Q){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${Q})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${Q})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${Q})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${Q})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(Q){if(!this._capabilities)return;switch(Q){case"completion/complete":if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${Q})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${Q})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${Q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${Q})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${Q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${Q})`);break;case"ping":case"initialize":break}}assertTaskCapability(Q){yF0(this._clientCapabilities?.tasks?.requests,Q,"Client")}assertTaskHandlerCapability(Q){if(!this._capabilities)return;kF0(this._capabilities.tasks?.requests,Q,"Server")}async _oninitialize(Q){let J=Q.params.protocolVersion;return this._clientCapabilities=Q.params.capabilities,this._clientVersion=Q.params.clientInfo,{protocolVersion:qz.includes(J)?J:Cs,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},_N)}async createMessage(Q,J){if(Q.tools||Q.toolChoice){if(!this._clientCapabilities?.sampling?.tools)throw Error("Client does not support sampling tools capability.")}if(Q.messages.length>0){let G=Q.messages[Q.messages.length-1],H=Array.isArray(G.content)?G.content:[G.content],K=H.some((D)=>D.type==="tool_result"),z=Q.messages.length>1?Q.messages[Q.messages.length-2]:void 0,q=z?Array.isArray(z.content)?z.content:[z.content]:[],F=q.some((D)=>D.type==="tool_use");if(K){if(H.some((D)=>D.type!=="tool_result"))throw Error("The last message must contain only tool_result content if any is present");if(!F)throw Error("tool_result blocks are not matching any tool_use from the previous message")}if(F){let D=new Set(q.filter((O)=>O.type==="tool_use").map((O)=>O.id)),V=new Set(H.filter((O)=>O.type==="tool_result").map((O)=>O.toolUseId));if(D.size!==V.size||![...D].every((O)=>V.has(O)))throw Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}if(Q.tools)return this.request({method:"sampling/createMessage",params:Q},ns,J);return this.request({method:"sampling/createMessage",params:Q},QZ,J)}async elicitInput(Q,J){switch(Q.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support url elicitation.");let H=Q;return this.request({method:"elicitation/create",params:H},Lz,J)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw Error("Client does not support form elicitation.");let H=Q.mode==="form"?Q:{...Q,mode:"form"},K=await this.request({method:"elicitation/create",params:H},Lz,J);if(K.action==="accept"&&K.content&&H.requestedSchema)try{let q=this._jsonSchemaValidator.getValidator(H.requestedSchema)(K.content);if(!q.valid)throw new gQ(nQ.InvalidParams,`Elicitation response content does not match requested schema: ${q.errorMessage}`)}catch(z){if(z instanceof gQ)throw z;throw new gQ(nQ.InternalError,`Error validating elicitation response: ${z instanceof Error?z.message:String(z)}`)}return K}}}createElicitationCompletionNotifier(Q,J){if(!this._clientCapabilities?.elicitation?.url)throw Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:Q}},J)}async listRoots(Q,J){return this.request({method:"roots/list",params:Q},as,J)}async sendLoggingMessage(Q,J){if(this._capabilities.logging){if(!this.isMessageIgnored(Q.level,J))return this.notification({method:"notifications/message",params:Q})}}async sendResourceUpdated(Q){return this.notification({method:"notifications/resources/updated",params:Q})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}var xF0=Symbol.for("mcp.completable");function i00(Q){return!!Q&&typeof Q==="object"&&xF0 in Q}function bF0(Q){return Q[xF0]?.complete}var vF0;(function(Q){Q.Completable="McpCompletable"})(vF0||(vF0={}));var uGQ=/^[A-Za-z0-9._-]{1,128}$/;function pGQ(Q){let J=[];if(Q.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(Q.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${Q.length})`]};if(Q.includes(" "))J.push("Tool name contains spaces, which may cause parsing issues");if(Q.includes(","))J.push("Tool name contains commas, which may cause parsing issues");if(Q.startsWith("-")||Q.endsWith("-"))J.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts");if(Q.startsWith(".")||Q.endsWith("."))J.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts");if(!uGQ.test(Q)){let G=Q.split("").filter((H)=>!/[A-Za-z0-9._-]/.test(H)).filter((H,K,z)=>z.indexOf(H)===K);return J.push(`Tool name contains invalid characters: ${G.map((H)=>`"${H}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:J}}return{isValid:!0,warnings:J}}function lGQ(Q,J){if(J.length>0){console.warn(`Tool name validation warning for "${Q}":`);for(let G of J)console.warn(` - ${G}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function o00(Q){let J=pGQ(Q);return lGQ(Q,J.warnings),J.isValid}class n00{constructor(Q){this._mcpServer=Q}registerToolTask(Q,J,G){let H={taskSupport:"required",...J.execution};if(H.taskSupport==="forbidden")throw Error(`Cannot register task-based tool '${Q}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(Q,J.title,J.description,J.inputSchema,J.outputSchema,J.annotations,H,J._meta,G)}}class s00{constructor(Q,J){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new c00(Q,J)}get experimental(){if(!this._experimental)this._experimental={tasks:new n00(this)};return this._experimental}async connect(Q){return await this.server.connect(Q)}async close(){await this.server.close()}setToolRequestHandlers(){if(this._toolHandlersInitialized)return;this.server.assertCanSetRequestHandler(QH(Mz)),this.server.assertCanSetRequestHandler(QH(p4)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Mz,()=>({tools:Object.entries(this._registeredTools).filter(([,Q])=>Q.enabled).map(([Q,J])=>{let G={name:Q,title:J.title,description:J.description,inputSchema:(()=>{let H=zz(J.inputSchema);return H?ar(H,{strictUnions:!0,pipeStrategy:"input"}):dGQ})(),annotations:J.annotations,execution:J.execution,_meta:J._meta};if(J.outputSchema){let H=zz(J.outputSchema);if(H)G.outputSchema=ar(H,{strictUnions:!0,pipeStrategy:"output"})}return G})})),this.server.setRequestHandler(p4,async(Q,J)=>{try{let G=this._registeredTools[Q.params.name];if(!G)throw new gQ(nQ.InvalidParams,`Tool ${Q.params.name} not found`);if(!G.enabled)throw new gQ(nQ.InvalidParams,`Tool ${Q.params.name} disabled`);let H=!!Q.params.task,K=G.execution?.taskSupport,z="createTask"in G.handler;if((K==="required"||K==="optional")&&!z)throw new gQ(nQ.InternalError,`Tool ${Q.params.name} has taskSupport '${K}' but was not registered with registerToolTask`);if(K==="required"&&!H)throw new gQ(nQ.MethodNotFound,`Tool ${Q.params.name} requires task augmentation (taskSupport: 'required')`);if(K==="optional"&&!H&&z)return await this.handleAutomaticTaskPolling(G,Q,J);let q=await this.validateToolInput(G,Q.params.arguments,Q.params.name),F=await this.executeToolHandler(G,q,J);if(H)return F;return await this.validateToolOutput(G,F,Q.params.name),F}catch(G){if(G instanceof gQ){if(G.code===nQ.UrlElicitationRequired)throw G}return this.createToolError(G instanceof Error?G.message:String(G))}}),this._toolHandlersInitialized=!0}createToolError(Q){return{content:[{type:"text",text:Q}],isError:!0}}async validateToolInput(Q,J,G){if(!Q.inputSchema)return;let K=zz(Q.inputSchema)??Q.inputSchema,z=await SN(K,J);if(!z.success){let q="error"in z?z.error:"Unknown error",F=TN(q);throw new gQ(nQ.InvalidParams,`Input validation error: Invalid arguments for tool ${G}: ${F}`)}return z.data}async validateToolOutput(Q,J,G){if(!Q.outputSchema)return;if(!("content"in J))return;if(J.isError)return;if(!J.structuredContent)throw new gQ(nQ.InvalidParams,`Output validation error: Tool ${G} has an output schema but no structured content was provided`);let H=zz(Q.outputSchema),K=await SN(H,J.structuredContent);if(!K.success){let z="error"in K?K.error:"Unknown error",q=TN(z);throw new gQ(nQ.InvalidParams,`Output validation error: Invalid structured content for tool ${G}: ${q}`)}}async executeToolHandler(Q,J,G){let H=Q.handler;if("createTask"in H){if(!G.taskStore)throw Error("No task store provided.");let z={...G,taskStore:G.taskStore};if(Q.inputSchema)return await Promise.resolve(H.createTask(J,z));else return await Promise.resolve(H.createTask(z))}if(Q.inputSchema)return await Promise.resolve(H(J,G));else return await Promise.resolve(H(G))}async handleAutomaticTaskPolling(Q,J,G){if(!G.taskStore)throw Error("No task store provided for task-capable tool.");let H=await this.validateToolInput(Q,J.params.arguments,J.params.name),K=Q.handler,z={...G,taskStore:G.taskStore},q=H?await Promise.resolve(K.createTask(H,z)):await Promise.resolve(K.createTask(z)),F=q.task.taskId,D=q.task,V=D.pollInterval??5000;while(D.status!=="completed"&&D.status!=="failed"&&D.status!=="cancelled"){await new Promise((P)=>setTimeout(P,V));let O=await G.taskStore.getTask(F);if(!O)throw new gQ(nQ.InternalError,`Task ${F} not found during polling`);D=O}return await G.taskStore.getTaskResult(F)}setCompletionRequestHandler(){if(this._completionHandlerInitialized)return;this.server.assertCanSetRequestHandler(QH(eN)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(eN,async(Q)=>{switch(Q.params.ref.type){case"ref/prompt":return uq0(Q),this.handlePromptCompletion(Q,Q.params.ref);case"ref/resource":return pq0(Q),this.handleResourceCompletion(Q,Q.params.ref);default:throw new gQ(nQ.InvalidParams,`Invalid completion reference: ${Q.params.ref}`)}}),this._completionHandlerInitialized=!0}async handlePromptCompletion(Q,J){let G=this._registeredPrompts[J.name];if(!G)throw new gQ(nQ.InvalidParams,`Prompt ${J.name} not found`);if(!G.enabled)throw new gQ(nQ.InvalidParams,`Prompt ${J.name} disabled`);if(!G.argsSchema)return wZ;let K=f4(G.argsSchema)?.[Q.params.argument.name];if(!i00(K))return wZ;let z=bF0(K);if(!z)return wZ;let q=await z(Q.params.argument.value,Q.params.context);return hF0(q)}async handleResourceCompletion(Q,J){let G=Object.values(this._registeredResourceTemplates).find((z)=>z.resourceTemplate.uriTemplate.toString()===J.uri);if(!G){if(this._registeredResources[J.uri])return wZ;throw new gQ(nQ.InvalidParams,`Resource template ${Q.params.ref.uri} not found`)}let H=G.resourceTemplate.completeCallback(Q.params.argument.name);if(!H)return wZ;let K=await H(Q.params.argument.value,Q.params.context);return hF0(K)}setResourceRequestHandlers(){if(this._resourceHandlersInitialized)return;this.server.assertCanSetRequestHandler(QH(aN)),this.server.assertCanSetRequestHandler(QH(sN)),this.server.assertCanSetRequestHandler(QH(rN)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(aN,async(Q,J)=>{let G=Object.entries(this._registeredResources).filter(([K,z])=>z.enabled).map(([K,z])=>({uri:K,name:z.name,...z.metadata})),H=[];for(let K of Object.values(this._registeredResourceTemplates)){if(!K.resourceTemplate.listCallback)continue;let z=await K.resourceTemplate.listCallback(J);for(let q of z.resources)H.push({...K.metadata,...q})}return{resources:[...G,...H]}}),this.server.setRequestHandler(sN,async()=>{return{resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([J,G])=>({name:J,uriTemplate:G.resourceTemplate.uriTemplate.toString(),...G.metadata}))}}),this.server.setRequestHandler(rN,async(Q,J)=>{let G=new URL(Q.params.uri),H=this._registeredResources[G.toString()];if(H){if(!H.enabled)throw new gQ(nQ.InvalidParams,`Resource ${G} disabled`);return H.readCallback(G,J)}for(let K of Object.values(this._registeredResourceTemplates)){let z=K.resourceTemplate.uriTemplate.match(G.toString());if(z)return K.readCallback(G,z,J)}throw new gQ(nQ.InvalidParams,`Resource ${G} not found`)}),this._resourceHandlersInitialized=!0}setPromptRequestHandlers(){if(this._promptHandlersInitialized)return;this.server.assertCanSetRequestHandler(QH(Fz)),this.server.assertCanSetRequestHandler(QH(Dz)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Fz,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,Q])=>Q.enabled).map(([Q,J])=>{return{name:Q,title:J.title,description:J.description,arguments:J.argsSchema?cGQ(J.argsSchema):void 0}})})),this.server.setRequestHandler(Dz,async(Q,J)=>{let G=this._registeredPrompts[Q.params.name];if(!G)throw new gQ(nQ.InvalidParams,`Prompt ${Q.params.name} not found`);if(!G.enabled)throw new gQ(nQ.InvalidParams,`Prompt ${Q.params.name} disabled`);if(G.argsSchema){let H=zz(G.argsSchema),K=await SN(H,Q.params.arguments);if(!K.success){let F="error"in K?K.error:"Unknown error",D=TN(F);throw new gQ(nQ.InvalidParams,`Invalid arguments for prompt ${Q.params.name}: ${D}`)}let z=K.data,q=G.callback;return await Promise.resolve(q(z,J))}else{let H=G.callback;return await Promise.resolve(H(J))}}),this._promptHandlersInitialized=!0}resource(Q,J,...G){let H;if(typeof G[0]==="object")H=G.shift();let K=G[0];if(typeof J==="string"){if(this._registeredResources[J])throw Error(`Resource ${J} is already registered`);let z=this._createRegisteredResource(Q,void 0,J,H,K);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),z}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let z=this._createRegisteredResourceTemplate(Q,void 0,J,H,K);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),z}}registerResource(Q,J,G,H){if(typeof J==="string"){if(this._registeredResources[J])throw Error(`Resource ${J} is already registered`);let K=this._createRegisteredResource(Q,G.title,J,G,H);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),K}else{if(this._registeredResourceTemplates[Q])throw Error(`Resource template ${Q} is already registered`);let K=this._createRegisteredResourceTemplate(Q,G.title,J,G,H);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),K}}_createRegisteredResource(Q,J,G,H,K){let z={name:Q,title:J,metadata:H,readCallback:K,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({uri:null}),update:(q)=>{if(typeof q.uri<"u"&&q.uri!==G){if(delete this._registeredResources[G],q.uri)this._registeredResources[q.uri]=z}if(typeof q.name<"u")z.name=q.name;if(typeof q.title<"u")z.title=q.title;if(typeof q.metadata<"u")z.metadata=q.metadata;if(typeof q.callback<"u")z.readCallback=q.callback;if(typeof q.enabled<"u")z.enabled=q.enabled;this.sendResourceListChanged()}};return this._registeredResources[G]=z,z}_createRegisteredResourceTemplate(Q,J,G,H,K){let z={resourceTemplate:G,title:J,metadata:H,readCallback:K,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(D)=>{if(typeof D.name<"u"&&D.name!==Q){if(delete this._registeredResourceTemplates[Q],D.name)this._registeredResourceTemplates[D.name]=z}if(typeof D.title<"u")z.title=D.title;if(typeof D.template<"u")z.resourceTemplate=D.template;if(typeof D.metadata<"u")z.metadata=D.metadata;if(typeof D.callback<"u")z.readCallback=D.callback;if(typeof D.enabled<"u")z.enabled=D.enabled;this.sendResourceListChanged()}};this._registeredResourceTemplates[Q]=z;let q=G.uriTemplate.variableNames;if(Array.isArray(q)&&q.some((D)=>!!G.completeCallback(D)))this.setCompletionRequestHandler();return z}_createRegisteredPrompt(Q,J,G,H,K){let z={title:J,description:G,argsSchema:H===void 0?void 0:I3(H),callback:K,enabled:!0,disable:()=>z.update({enabled:!1}),enable:()=>z.update({enabled:!0}),remove:()=>z.update({name:null}),update:(q)=>{if(typeof q.name<"u"&&q.name!==Q){if(delete this._registeredPrompts[Q],q.name)this._registeredPrompts[q.name]=z}if(typeof q.title<"u")z.title=q.title;if(typeof q.description<"u")z.description=q.description;if(typeof q.argsSchema<"u")z.argsSchema=I3(q.argsSchema);if(typeof q.callback<"u")z.callback=q.callback;if(typeof q.enabled<"u")z.enabled=q.enabled;this.sendPromptListChanged()}};if(this._registeredPrompts[Q]=z,H){if(Object.values(H).some((F)=>{let D=F instanceof xN?F._def?.innerType:F;return i00(D)}))this.setCompletionRequestHandler()}return z}_createRegisteredTool(Q,J,G,H,K,z,q,F,D){o00(Q);let V={title:J,description:G,inputSchema:gF0(H),outputSchema:gF0(K),annotations:z,execution:q,_meta:F,handler:D,enabled:!0,disable:()=>V.update({enabled:!1}),enable:()=>V.update({enabled:!0}),remove:()=>V.update({name:null}),update:(O)=>{if(typeof O.name<"u"&&O.name!==Q){if(typeof O.name==="string")o00(O.name);if(delete this._registeredTools[Q],O.name)this._registeredTools[O.name]=V}if(typeof O.title<"u")V.title=O.title;if(typeof O.description<"u")V.description=O.description;if(typeof O.paramsSchema<"u")V.inputSchema=I3(O.paramsSchema);if(typeof O.outputSchema<"u")V.outputSchema=I3(O.outputSchema);if(typeof O.callback<"u")V.handler=O.callback;if(typeof O.annotations<"u")V.annotations=O.annotations;if(typeof O._meta<"u")V._meta=O._meta;if(typeof O.enabled<"u")V.enabled=O.enabled;this.sendToolListChanged()}};return this._registeredTools[Q]=V,this.setToolRequestHandlers(),this.sendToolListChanged(),V}tool(Q,...J){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let G,H,K,z;if(typeof J[0]==="string")G=J.shift();if(J.length>1){let F=J[0];if(a00(F)){if(H=J.shift(),J.length>1&&typeof J[0]==="object"&&J[0]!==null&&!a00(J[0]))z=J.shift()}else if(typeof F==="object"&&F!==null){if(Object.values(F).some((D)=>typeof D==="object"&&D!==null))throw Error(`Tool ${Q} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);z=J.shift()}}let q=J[0];return this._createRegisteredTool(Q,void 0,G,H,K,z,{taskSupport:"forbidden"},void 0,q)}registerTool(Q,J,G){if(this._registeredTools[Q])throw Error(`Tool ${Q} is already registered`);let{title:H,description:K,inputSchema:z,outputSchema:q,annotations:F,_meta:D}=J;return this._createRegisteredTool(Q,H,K,z,q,F,{taskSupport:"forbidden"},D,G)}prompt(Q,...J){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let G;if(typeof J[0]==="string")G=J.shift();let H;if(J.length>1)H=J.shift();let K=J[0],z=this._createRegisteredPrompt(Q,void 0,G,H,K);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),z}registerPrompt(Q,J,G){if(this._registeredPrompts[Q])throw Error(`Prompt ${Q} is already registered`);let{title:H,description:K,argsSchema:z}=J,q=this._createRegisteredPrompt(Q,H,K,z,G);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),q}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(Q,J){return this.server.sendLoggingMessage(Q,J)}sendResourceListChanged(){if(this.isConnected())this.server.sendResourceListChanged()}sendToolListChanged(){if(this.isConnected())this.server.sendToolListChanged()}sendPromptListChanged(){if(this.isConnected())this.server.sendPromptListChanged()}}var dGQ={type:"object",properties:{}};function _F0(Q){return Q!==null&&typeof Q==="object"&&"parse"in Q&&typeof Q.parse==="function"&&"safeParse"in Q&&typeof Q.safeParse==="function"}function fF0(Q){return"_def"in Q||"_zod"in Q||_F0(Q)}function a00(Q){if(typeof Q!=="object"||Q===null)return!1;if(fF0(Q))return!1;if(Object.keys(Q).length===0)return!0;return Object.values(Q).some(_F0)}function gF0(Q){if(!Q)return;if(a00(Q))return I3(Q);if(!fF0(Q))throw Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return Q}function cGQ(Q){let J=f4(Q);if(!J)return[];return Object.entries(J).map(([G,H])=>{let K=sV0(H),z=rV0(H);return{name:G,description:K,required:!z}})}function QH(Q){let G=f4(Q)?.method;if(!G)throw Error("Schema is missing a method literal");let H=kN(G);if(typeof H==="string")return H;throw Error("Schema method literal must be a string")}function hF0(Q){return{completion:{values:Q.slice(0,100),total:Q.length,hasMore:Q.length>100}}}var wZ={completion:{values:[],hasMore:!1}};var SZ=require("http2"),mj=require("http2"),t00=require("stream"),dF0=K7(require("crypto")),x3=class extends Error{constructor(Q,J){super(Q,J);this.name="RequestError"}},iGQ=(Q)=>{if(Q instanceof x3)return Q;return new x3(Q.message,{cause:Q})},oGQ=global.Request,EZ=class extends oGQ{constructor(Q,J){if(typeof Q==="object"&&fz in Q)Q=Q[fz]();if(typeof J?.body?.getReader<"u")J.duplex??="half";super(Q,J)}},nGQ=(Q)=>{let J=[],G=Q.rawHeaders;for(let H=0;H<G.length;H+=2){let{[H]:K,[H+1]:z}=G;if(K.charCodeAt(0)!==58)J.push([K,z])}return new Headers(J)},pF0=Symbol("wrapBodyStream"),aGQ=(Q,J,G,H,K)=>{let z={method:Q,headers:G,signal:K.signal};if(Q==="TRACE"){z.method="GET";let q=new EZ(J,z);return Object.defineProperty(q,"method",{get(){return"TRACE"}}),q}if(!(Q==="GET"||Q==="HEAD"))if("rawBody"in H&&H.rawBody instanceof Buffer)z.body=new ReadableStream({start(q){q.enqueue(H.rawBody),q.close()}});else if(H[pF0]){let q;z.body=new ReadableStream({async pull(F){try{q||=t00.Readable.toWeb(H).getReader();let{done:D,value:V}=await q.read();if(D)F.close();else F.enqueue(V)}catch(D){F.error(D)}}})}else z.body=t00.Readable.toWeb(H);return new EZ(J,z)},fz=Symbol("getRequestCache"),sGQ=Symbol("requestCache"),uj=Symbol("incomingKey"),pj=Symbol("urlKey"),rGQ=Symbol("headersKey"),_z=Symbol("abortControllerKey"),tGQ=Symbol("getAbortController"),lj={get method(){return this[uj].method||"GET"},get url(){return this[pj]},get headers(){return this[rGQ]||=nGQ(this[uj])},[tGQ](){return this[fz](),this[_z]},[fz](){return this[_z]||=new AbortController,this[sGQ]||=aGQ(this.method,this[pj],this.headers,this[uj],this[_z])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach((Q)=>{Object.defineProperty(lj,Q,{get(){return this[fz]()[Q]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach((Q)=>{Object.defineProperty(lj,Q,{value:function(){return this[fz]()[Q]()}})});Object.setPrototypeOf(lj,EZ.prototype);var eGQ=(Q,J)=>{let G=Object.create(lj);G[uj]=Q;let H=Q.url||"";if(H[0]!=="/"&&(H.startsWith("http://")||H.startsWith("https://"))){if(Q instanceof mj.Http2ServerRequest)throw new x3("Absolute URL for :path is not allowed in HTTP/2");try{let F=new URL(H);G[pj]=F.href}catch(F){throw new x3("Invalid absolute URL",{cause:F})}return G}let K=(Q instanceof mj.Http2ServerRequest?Q.authority:Q.headers.host)||J;if(!K)throw new x3("Missing host header");let z;if(Q instanceof mj.Http2ServerRequest){if(z=Q.scheme,!(z==="http"||z==="https"))throw new x3("Unsupported scheme")}else z=Q.socket&&Q.socket.encrypted?"https":"http";let q=new URL(`${z}://${K}${H}`);if(q.hostname.length!==K.length&&q.hostname!==K.replace(/:\d+$/,""))throw new x3("Invalid host header");return G[pj]=q.href,G},mF0=Symbol("responseCache"),hz=Symbol("getResponseCache"),b3=Symbol("cache"),XQ0=global.Response,TZ=class Q{#X;#Q;[hz](){return delete this[b3],this[mF0]||=new XQ0(this.#X,this.#Q)}constructor(J,G){let H;if(this.#X=J,G instanceof Q){let K=G[mF0];if(K){this.#Q=K,this[hz]();return}else this.#Q=G.#Q,H=new Headers(G.#Q.headers)}else this.#Q=G;if(typeof J==="string"||typeof J?.getReader<"u"||J instanceof Blob||J instanceof Uint8Array)this[b3]=[G?.status||200,J,H||G?.headers]}get headers(){let J=this[b3];if(J){if(!(J[2]instanceof Headers))J[2]=new Headers(J[2]||{"content-type":"text/plain; charset=UTF-8"});return J[2]}return this[hz]().headers}get status(){return this[b3]?.[0]??this[hz]().status}get ok(){let J=this.status;return J>=200&&J<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach((Q)=>{Object.defineProperty(TZ.prototype,Q,{get(){return this[hz]()[Q]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach((Q)=>{Object.defineProperty(TZ.prototype,Q,{value:function(){return this[hz]()[Q]()}})});Object.setPrototypeOf(TZ,XQ0);Object.setPrototypeOf(TZ.prototype,XQ0.prototype);async function QWQ(Q){return Promise.race([Q,Promise.resolve().then(()=>Promise.resolve(void 0))])}function lF0(Q,J,G){let H=(F)=>{Q.cancel(F).catch(()=>{})};return J.on("close",H),J.on("error",H),(G??Q.read()).then(q,K),Q.closed.finally(()=>{J.off("close",H),J.off("error",H)});function K(F){if(F)J.destroy(F)}function z(){Q.read().then(q,K)}function q({done:F,value:D}){try{if(F)J.end();else if(!J.write(D))J.once("drain",z);else return Q.read().then(q,K)}catch(V){K(V)}}}function XWQ(Q,J){if(Q.locked)throw TypeError("ReadableStream is locked.");else if(J.destroyed)return;return lF0(Q.getReader(),J)}var e00=(Q)=>{let J={};if(!(Q instanceof Headers))Q=new Headers(Q??void 0);let G=[];for(let[H,K]of Q)if(H==="set-cookie")G.push(K);else J[H]=K;if(G.length>0)J["set-cookie"]=G;return J["content-type"]??="text/plain; charset=UTF-8",J},JWQ="x-hono-already-sent";if(typeof global.crypto>"u")global.crypto=dF0.default;var JQ0=Symbol("outgoingEnded"),uF0=Symbol("incomingDraining"),YWQ=500,GWQ=67108864,r00=(Q)=>{let J=Q;if(Q.destroyed||J[uF0])return;if(J[uF0]=!0,Q instanceof SZ.Http2ServerRequest){try{Q.stream?.close?.(SZ.constants.NGHTTP2_NO_ERROR)}catch{}return}let G=0,H=()=>{clearTimeout(z),Q.off("data",q),Q.off("end",H),Q.off("error",H)},K=()=>{H();let F=Q.socket;if(F&&!F.destroyed)F.destroySoon()},z=setTimeout(K,YWQ);z.unref?.();let q=(F)=>{if(G+=F.length,G>GWQ)K()};Q.on("data",q),Q.on("end",H),Q.on("error",H),Q.resume()},WWQ=()=>new Response(null,{status:400}),cF0=(Q)=>new Response(null,{status:Q instanceof Error&&(Q.name==="TimeoutError"||Q.constructor.name==="TimeoutError")?504:500}),QQ0=(Q,J)=>{let G=Q instanceof Error?Q:Error("unknown error",{cause:Q});if(G.code==="ERR_STREAM_PREMATURE_CLOSE")console.info("The user aborted a request.");else{if(console.error(Q),!J.headersSent)J.writeHead(500,{"Content-Type":"text/plain"});J.end(`Error: ${G.message}`),J.destroy(G)}},iF0=(Q)=>{if("flushHeaders"in Q&&Q.writable)Q.flushHeaders()},oF0=async(Q,J)=>{let[G,H,K]=Q[b3],z=!1;if(!K)K={"content-type":"text/plain; charset=UTF-8"};else if(K instanceof Headers)z=K.has("content-length"),K=e00(K);else if(Array.isArray(K)){let q=new Headers(K);z=q.has("content-length"),K=e00(q)}else for(let q in K)if(q.length===14&&q.toLowerCase()==="content-length"){z=!0;break}if(!z){if(typeof H==="string")K["Content-Length"]=Buffer.byteLength(H);else if(H instanceof Uint8Array)K["Content-Length"]=H.byteLength;else if(H instanceof Blob)K["Content-Length"]=H.size}if(J.writeHead(G,K),typeof H==="string"||H instanceof Uint8Array)J.end(H);else if(H instanceof Blob)J.end(new Uint8Array(await H.arrayBuffer()));else iF0(J),await XWQ(H,J)?.catch((q)=>QQ0(q,J));J[JQ0]?.()},HWQ=(Q)=>typeof Q.then==="function",BWQ=async(Q,J,G={})=>{if(HWQ(Q))if(G.errorHandler)try{Q=await Q}catch(K){let z=await G.errorHandler(K);if(!z)return;Q=z}else Q=await Q.catch(cF0);if(b3 in Q)return oF0(Q,J);let H=e00(Q.headers);if(Q.body){let K=Q.body.getReader(),z=[],q=!1,F=void 0;if(H["transfer-encoding"]!=="chunked"){let D=2;for(let V=0;V<D;V++){F||=K.read();let O=await QWQ(F).catch((P)=>{console.error(P),q=!0});if(!O){if(V===1){await new Promise((P)=>setTimeout(P)),D=3;continue}break}if(F=void 0,O.value)z.push(O.value);if(O.done){q=!0;break}}if(q&&!("content-length"in H))H["content-length"]=z.reduce((V,O)=>V+O.length,0)}if(J.writeHead(Q.status,H),z.forEach((D)=>{J.write(D)}),q)J.end();else{if(z.length===0)iF0(J);await lF0(K,J,F)}}else if(H[JWQ]);else J.writeHead(Q.status,H),J.end();J[JQ0]?.()},YQ0=(Q,J={})=>{let G=J.autoCleanupIncoming??!0;if(J.overrideGlobalObjects!==!1&&global.Request!==EZ)Object.defineProperty(global,"Request",{value:EZ}),Object.defineProperty(global,"Response",{value:TZ});return async(H,K)=>{let z,q;try{q=eGQ(H,J.hostname);let F=!G||H.method==="GET"||H.method==="HEAD";if(!F){if(H[pF0]=!0,H.on("end",()=>{F=!0}),H instanceof SZ.Http2ServerRequest)K[JQ0]=()=>{if(!F)setTimeout(()=>{if(!F)setTimeout(()=>{r00(H)})})};K.on("finish",()=>{if(!F)r00(H)})}if(K.on("close",()=>{if(q[_z]){if(H.errored)q[_z].abort(H.errored.toString());else if(!K.writableFinished)q[_z].abort("Client connection prematurely closed.")}if(!F)setTimeout(()=>{if(!F)setTimeout(()=>{r00(H)})})}),z=Q(q,{incoming:H,outgoing:K}),b3 in z)return oF0(z,K)}catch(F){if(!z)if(J.errorHandler){if(z=await J.errorHandler(q?F:iGQ(F)),!z)return}else if(!q)z=WWQ();else z=cF0(F);else return QQ0(F,K)}try{return await BWQ(z,K,J)}catch(F){return QQ0(F,K)}}};class GQ0{constructor(Q={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=Q.sessionIdGenerator,this._enableJsonResponse=Q.enableJsonResponse??!1,this._eventStore=Q.eventStore,this._onsessioninitialized=Q.onsessioninitialized,this._onsessionclosed=Q.onsessionclosed,this._allowedHosts=Q.allowedHosts,this._allowedOrigins=Q.allowedOrigins,this._enableDnsRebindingProtection=Q.enableDnsRebindingProtection??!1,this._retryInterval=Q.retryInterval}async start(){if(this._started)throw Error("Transport already started");this._started=!0}createJsonErrorResponse(Q,J,G,H){let K={code:J,message:G};if(H?.data!==void 0)K.data=H.data;return new Response(JSON.stringify({jsonrpc:"2.0",error:K,id:null}),{status:Q,headers:{"Content-Type":"application/json",...H?.headers}})}validateRequestHeaders(Q){if(!this._enableDnsRebindingProtection)return;if(this._allowedHosts&&this._allowedHosts.length>0){let J=Q.headers.get("host");if(!J||!this._allowedHosts.includes(J)){let G=`Invalid Host header: ${J}`;return this.onerror?.(Error(G)),this.createJsonErrorResponse(403,-32000,G)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let J=Q.headers.get("origin");if(J&&!this._allowedOrigins.includes(J)){let G=`Invalid Origin header: ${J}`;return this.onerror?.(Error(G)),this.createJsonErrorResponse(403,-32000,G)}}return}async handleRequest(Q,J){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let G=this.validateRequestHeaders(Q);if(G)return G;switch(Q.method){case"POST":return this.handlePostRequest(Q,J);case"GET":return this.handleGetRequest(Q);case"DELETE":return this.handleDeleteRequest(Q);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(Q,J,G,H){if(!this._eventStore)return;if(H<"2025-11-25")return;let K=await this._eventStore.storeEvent(G,{}),z=`id: ${K}
data:
`;if(this._retryInterval!==void 0)z=`id: ${K}
retry: ${this._retryInterval}
data:
`;Q.enqueue(J.encode(z))}async handleGetRequest(Q){if(!Q.headers.get("accept")?.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept text/event-stream");let G=this.validateSession(Q);if(G)return G;let H=this.validateProtocolVersion(Q);if(H)return H;if(this._eventStore){let D=Q.headers.get("last-event-id");if(D)return this.replayEvents(D)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error("Conflict: Only one SSE stream is allowed per session")),this.createJsonErrorResponse(409,-32000,"Conflict: Only one SSE stream is allowed per session");let K=new TextEncoder,z,q=new ReadableStream({start:(D)=>{z=D},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),F={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};if(this.sessionId!==void 0)F["mcp-session-id"]=this.sessionId;return this._streamMapping.set(this._standaloneSseStreamId,{controller:z,encoder:K,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{z.close()}catch{}}}),new Response(q,{headers:F})}async replayEvents(Q){if(!this._eventStore)return this.onerror?.(Error("Event store not configured")),this.createJsonErrorResponse(400,-32000,"Event store not configured");try{let J;if(this._eventStore.getStreamIdForEventId){if(J=await this._eventStore.getStreamIdForEventId(Q),!J)return this.onerror?.(Error("Invalid event ID format")),this.createJsonErrorResponse(400,-32000,"Invalid event ID format");if(this._streamMapping.get(J)!==void 0)return this.onerror?.(Error("Conflict: Stream already has an active connection")),this.createJsonErrorResponse(409,-32000,"Conflict: Stream already has an active connection")}let G={"Content-Type":"text/event-stream","Cache-Control":"no-cache, no-transform",Connection:"keep-alive"};if(this.sessionId!==void 0)G["mcp-session-id"]=this.sessionId;let H=new TextEncoder,K,z=new ReadableStream({start:(F)=>{K=F},cancel:()=>{}}),q=await this._eventStore.replayEventsAfter(Q,{send:async(F,D)=>{if(!this.writeSSEEvent(K,H,D,F)){this.onerror?.(Error("Failed replay events"));try{K.close()}catch{}}}});return this._streamMapping.set(q,{controller:K,encoder:H,cleanup:()=>{this._streamMapping.delete(q);try{K.close()}catch{}}}),new Response(z,{headers:G})}catch(J){return this.onerror?.(J),this.createJsonErrorResponse(500,-32000,"Error replaying events")}}writeSSEEvent(Q,J,G,H){try{let K=`event: message
`;if(H)K+=`id: ${H}
`;return K+=`data: ${JSON.stringify(G)}
`,Q.enqueue(J.encode(K)),!0}catch(K){return this.onerror?.(K),!1}}handleUnsupportedRequest(){return this.onerror?.(Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32000,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(Q,J){try{let G=Q.headers.get("accept");if(!G?.includes("application/json")||!G.includes("text/event-stream"))return this.onerror?.(Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32000,"Not Acceptable: Client must accept both application/json and text/event-stream");let H=Q.headers.get("content-type");if(!H||!H.includes("application/json"))return this.onerror?.(Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32000,"Unsupported Media Type: Content-Type must be application/json");let K={headers:Object.fromEntries(Q.headers.entries()),url:new URL(Q.url)},z;if(J?.parsedBody!==void 0)z=J.parsedBody;else try{z=await Q.json()}catch{return this.onerror?.(Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let q;try{if(Array.isArray(z))q=z.map((E)=>vs.parse(E));else q=[vs.parse(z)]}catch{return this.onerror?.(Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let F=q.some(xs);if(F){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(q.length>1)return this.onerror?.(Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");if(this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized)await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!F){let E=this.validateSession(Q);if(E)return E;let T=this.validateProtocolVersion(Q);if(T)return T}if(!q.some(u4)){for(let E of q)this.onmessage?.(E,{authInfo:J?.authInfo,requestInfo:K});return new Response(null,{status:202})}let V=crypto.randomUUID(),O=q.find((E)=>xs(E)),P=O?O.params.protocolVersion:Q.headers.get("mcp-protocol-version")??wq0;if(this._enableJsonResponse)return new Promise((E)=>{this._streamMapping.set(V,{resolveJson:E,cleanup:()=>{this._streamMapping.delete(V)}});for(let T of q)if(u4(T))this._requestToStreamMapping.set(T.id,V);for(let T of q)this.onmessage?.(T,{authInfo:J?.authInfo,requestInfo:K})});let N=new TextEncoder,I,R=new ReadableStream({start:(E)=>{I=E},cancel:()=>{this._streamMapping.delete(V)}}),w={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};if(this.sessionId!==void 0)w["mcp-session-id"]=this.sessionId;for(let E of q)if(u4(E))this._streamMapping.set(V,{controller:I,encoder:N,cleanup:()=>{this._streamMapping.delete(V);try{I.close()}catch{}}}),this._requestToStreamMapping.set(E.id,V);await this.writePrimingEvent(I,N,V,P);for(let E of q){let T,y;if(u4(E)&&this._eventStore&&P>="2025-11-25")T=()=>{this.closeSSEStream(E.id)},y=()=>{this.closeStandaloneSSEStream()};this.onmessage?.(E,{authInfo:J?.authInfo,requestInfo:K,closeSSEStream:T,closeStandaloneSSEStream:y})}return new Response(R,{status:200,headers:w})}catch(G){return this.onerror?.(G),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(G)})}}async handleDeleteRequest(Q){let J=this.validateSession(Q);if(J)return J;let G=this.validateProtocolVersion(Q);if(G)return G;return await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200})}validateSession(Q){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error("Bad Request: Server not initialized")),this.createJsonErrorResponse(400,-32000,"Bad Request: Server not initialized");let J=Q.headers.get("mcp-session-id");if(!J)return this.onerror?.(Error("Bad Request: Mcp-Session-Id header is required")),this.createJsonErrorResponse(400,-32000,"Bad Request: Mcp-Session-Id header is required");if(J!==this.sessionId)return this.onerror?.(Error("Session not found")),this.createJsonErrorResponse(404,-32001,"Session not found");return}validateProtocolVersion(Q){let J=Q.headers.get("mcp-protocol-version");if(J!==null&&!qz.includes(J))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${J} (supported versions: ${qz.join(", ")})`)),this.createJsonErrorResponse(400,-32000,`Bad Request: Unsupported protocol version: ${J} (supported versions: ${qz.join(", ")})`);return}async close(){this._streamMapping.forEach(({cleanup:Q})=>{Q()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(Q){let J=this._requestToStreamMapping.get(Q);if(!J)return;let G=this._streamMapping.get(J);if(G)G.cleanup()}closeStandaloneSSEStream(){let Q=this._streamMapping.get(this._standaloneSseStreamId);if(Q)Q.cleanup()}async send(Q,J){let G=J?.relatedRequestId;if(C5(Q)||Uz(Q))G=Q.id;if(G===void 0){if(C5(Q)||Uz(Q))throw Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let z;if(this._eventStore)z=await this._eventStore.storeEvent(this._standaloneSseStreamId,Q);let q=this._streamMapping.get(this._standaloneSseStreamId);if(q===void 0)return;if(q.controller&&q.encoder)this.writeSSEEvent(q.controller,q.encoder,Q,z);return}let H=this._requestToStreamMapping.get(G);if(!H)throw Error(`No connection established for request ID: ${String(G)}`);let K=this._streamMapping.get(H);if(!this._enableJsonResponse&&K?.controller&&K?.encoder){let z;if(this._eventStore)z=await this._eventStore.storeEvent(H,Q);this.writeSSEEvent(K.controller,K.encoder,Q,z)}if(C5(Q)||Uz(Q)){this._requestResponseMap.set(G,Q);let z=Array.from(this._requestToStreamMapping.entries()).filter(([F,D])=>D===H).map(([F])=>F);if(z.every((F)=>this._requestResponseMap.has(F))){if(!K)throw Error(`No connection established for request ID: ${String(G)}`);if(this._enableJsonResponse&&K.resolveJson){let F={"Content-Type":"application/json"};if(this.sessionId!==void 0)F["mcp-session-id"]=this.sessionId;let D=z.map((V)=>this._requestResponseMap.get(V));if(D.length===1)K.resolveJson(new Response(JSON.stringify(D[0]),{status:200,headers:F}));else K.resolveJson(new Response(JSON.stringify(D),{status:200,headers:F}))}else K.cleanup();for(let F of z)this._requestResponseMap.delete(F),this._requestToStreamMapping.delete(F)}}}}class WQ0{constructor(Q={}){this._requestContext=new WeakMap,this._webStandardTransport=new GQ0(Q),this._requestListener=YQ0(async(J)=>{let G=this._requestContext.get(J);return this._webStandardTransport.handleRequest(J,{authInfo:G?.authInfo,parsedBody:G?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(Q){this._webStandardTransport.onclose=Q}get onclose(){return this._webStandardTransport.onclose}set onerror(Q){this._webStandardTransport.onerror=Q}get onerror(){return this._webStandardTransport.onerror}set onmessage(Q){this._webStandardTransport.onmessage=Q}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(Q,J){return this._webStandardTransport.send(Q,J)}async handleRequest(Q,J,G){let H=Q.auth;await YQ0(async(z)=>{return this._webStandardTransport.handleRequest(z,{authInfo:H,parsedBody:G})},{overrideGlobalObjects:!1})(Q,J)}closeSSEStream(Q){this._webStandardTransport.closeSSEStream(Q)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}var t80=require("obsidian");function nF0(Q){if(Q instanceof gQ)return Q;if(Q instanceof e.errors){let J=Q.summary;return new gQ(nQ.InvalidParams,J)}if(e({message:"string"}).allows(Q))return new gQ(nQ.InternalError,Q.message);return new gQ(nQ.InternalError,"An unexpected error occurred",Q)}function HQ0(Q){if(Array.isArray(Q)){for(let G of Q)HQ0(G);return}if(typeof Q!=="object"||Q===null)return;let J=Q;if(Array.isArray(J.anyOf)){let G=J.anyOf.filter((H)=>typeof H==="object"&&H!==null);if(typeof J.description==="string"){for(let H of G)if(H.description===J.description)delete H.description}else{let H=new Set(G.map((K)=>K.description));if(H.size===1){let[K]=H;if(typeof K==="string"){J.description=K;for(let z of G)delete z.description}}}}for(let G of Object.values(J))HQ0(G)}function AWQ(Q){let J=typeof Q==="object"&&Q!==null?Q:{type:"object"},G=structuredClone(J);if(HQ0(G),!("type"in G))G.type="object";if(!("properties"in G))G.properties={};let H=G.additionalProperties;if(H!==void 0&&typeof H==="object"&&H!==null&&Object.keys(H).length===0)delete G.additionalProperties;return G}var KWQ=e({type:'"text"',text:"string"}),zWQ=e({type:'"image"',data:"string.base64",mimeType:"string"}),VWQ=e({type:'"audio"',data:"string.base64",mimeType:"string"}),fY8=e({content:KWQ.or(zWQ).or(VWQ).array(),"isError?":"boolean","structuredContent?":e("Record<string, unknown>")});class BQ0 extends Map{enabled=new Set;listCache=null;annotationsByName=new Map;byName=new Map;toolNameOf=(Q)=>{let G=Q.get("name").toJsonSchema().const;if(typeof G!=="string")throw Error("tool schema has no string-literal name");return G};setAnnotations=(Q)=>{for(let[J,G]of Object.entries(Q))this.annotationsByName.set(J,G);return this.listCache=null,this};register(Q,J){let G=this.toolNameOf(Q);if(this.byName.has(G))throw Error(`Tool already registered: ${G}`);return this.byName.set(G,Q),this.enable(Q),super.set(Q,J)}enable=(Q)=>{return this.enabled.add(Q),this.listCache=null,this};disable=(Q)=>{return this.enabled.delete(Q),this.listCache=null,this};enableByName=(Q)=>{let J=this.byName.get(Q);if(!J)return!1;return this.enable(J),!0};disableByName=(Q)=>{let J=this.byName.get(Q);if(!J)return!1;return this.disable(J),!0};list=()=>{return this.listCache??={tools:Array.from(this.enabled.values()).map((Q)=>{let J=this.toolNameOf(Q),G=this.annotationsByName.get(J);return{name:J,description:Q.description,inputSchema:AWQ(Q.get("arguments").toJsonSchema()),...G?{annotations:G}:{}}})},this.listCache};listAll=()=>Array.from(this.keys()).map((Q)=>({name:this.toolNameOf(Q),description:Q.description??"",enabled:this.enabled.has(Q)}));coerceBooleanParams=(Q,J)=>{let G=J.arguments,H=Q.get("arguments").exclude("undefined");if(!G||!H)return J;let K={...G};for(let[z,q]of Object.entries(G))if(H.get(z).exclude("undefined").expression==="boolean"&&typeof q==="string"&&["true","false"].includes(q))K[z]=q==="true";return{...J,arguments:K}};dispatch=async(Q,J)=>{try{let G=this.byName.get(Q.name),H=G?this.get(G):void 0;if(G&&H&&this.enabled.has(G)){let K=G.assert(this.coerceBooleanParams(G,Q));return await H(K,J)}throw new gQ(nQ.InvalidRequest,`Unknown tool: ${Q.name}`)}catch(G){let H=nF0(G);return SQ.error(`Error handling ${Q.name}`,{...H,message:H.message,stack:H.stack,error:G,tool:Q.name}),{content:[{type:"text",text:H.message}],isError:!0}}}}class AQ0{lister=async()=>[];handler=null;setLister(Q){this.lister=Q}setHandler(Q,J){this.handler=J}list=async()=>({prompts:await this.lister()});dispatch=async(Q)=>{if(!this.handler)throw new gQ(nQ.InvalidParams,`Prompt not found: ${Q.name}`);return this.handler(Q.name,Q.arguments??{})}}var u9={readOnlyHint:!0,openWorldHint:!1},XH={readOnlyHint:!1,destructiveHint:!1,openWorldHint:!1},lJ={readOnlyHint:!1,destructiveHint:!0,openWorldHint:!1},aF0={get_server_info:u9,get_active_file:u9,update_active_file:{...lJ,idempotentHint:!0},append_to_active_file:XH,patch_active_file:lJ,delete_active_file:lJ,show_file_in_obsidian:{...u9,idempotentHint:!0},list_vault_files:u9,get_vault_file:u9,get_vault_file_partial:u9,create_vault_file:{...lJ,idempotentHint:!0},append_to_vault_file:XH,patch_vault_file:lJ,delete_vault_file:lJ,rename_vault_file:lJ,rename_heading:lJ,create_vault_directory:{...XH,idempotentHint:!0},delete_vault_directory:lJ,search_vault:u9,search_vault_simple:u9,search_vault_smart:u9,search_and_replace:lJ,fetch:{readOnlyHint:!0,openWorldHint:!0},execute_obsidian_command:lJ,list_obsidian_commands:u9,execute_template:lJ,execute_dataview_query:u9,find_broken_links:u9,find_orphaned_notes:u9,get_backlinks:u9,get_outgoing_links:u9,get_files_by_tag:u9,list_tags:u9,list_property_values:u9,get_note_outline:u9,get_note_property:u9,set_note_property:{...lJ,idempotentHint:!0},delete_note_property:lJ,get_recent_files:u9,list_bookmarks:u9,get_or_create_daily_note:{...XH,idempotentHint:!0},get_or_create_periodic_note:{...XH,idempotentHint:!0},append_to_periodic_note:XH,get_canvas:u9,add_canvas_node:XH,connect_canvas_nodes:XH,tool_catalog:u9,activate_tool:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},activate_tools:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}};function xQ(Q){return{content:[{type:"text",text:Q}],isError:!0}}function OX(Q,J,G){return{content:[{type:"text",text:JSON.stringify({error:Q,errorCode:J,...G})}],isError:!0}}function J8(Q){return{content:[{type:"text",text:Q}]}}function qWQ(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}function MJ(Q){if(Q===void 0)return{content:[{type:"text",text:"null"}]};let J=JSON.stringify(Q),G=qWQ(Q)?Q:{result:Q};return{content:[{type:"text",text:J}],structuredContent:G}}var sF0=e({name:'"get_server_info"',arguments:{}}).describe("Returns health status and version of the MCP Connector server.");async function rF0(Q){let J=Q.getLocalTransport?.(),G={status:"ok",version:Q.pluginVersion,transport:"streamable-http",...J?{localTransport:J}:{}};return MJ(G)}var tF0=e({name:'"get_active_file"',arguments:{"format?":'"markdown"|"json"'}}).describe("Returns content of the currently active note. Default format is markdown; pass format=json to receive an object with content, frontmatter, tags, stat, and path.");async function eF0(Q){let J=Q.app.workspace.getActiveFile();if(!J)return xQ("No active file.");let G=await Q.app.vault.read(J);if(Q.arguments.format!=="json")return J8(G);let K=Q.app.metadataCache.getFileCache(J)?.frontmatter??{},z=Array.isArray(K.tags)?K.tags:[],q={path:J.path,content:G,frontmatter:K,tags:z,stat:{ctime:J.stat.ctime,mtime:J.stat.mtime,size:J.stat.size}};return J8(JSON.stringify(q))}var QD0=e({name:'"update_active_file"',arguments:{content:e("string").describe("Full new markdown content to replace the current active file's content with.")}}).describe("Overwrites the entire content of the currently active note with the supplied content.");async function XD0(Q){let J=Q.app.workspace.getActiveFile();if(!J)return xQ("No active file.");return await Q.app.vault.modify(J,Q.arguments.content),J8("OK")}function kZ(Q,J,G){let H=Q.split(`
`),K=[];for(let z of H){let q=z.match(/^(#{1,6})\s+(.+)$/);if(!q)continue;let F=q[1].length,D=q[2].trim();if(K.length=F-1,K[F-1]=D,D===J)return K.slice(0,F).join(G)}return null}function KQ0(Q,J){for(let G=0;G<Q.length;G++){let H=Q[G].match(/^(#{1,6})\s+(.+)$/);if(H&&H[2].trim()===J)return{line:G,level:H[1].length}}return null}function dJ(Q,J){if(J==="append"&&!Q.endsWith(`
`))return Q+`
`;return Q}function UWQ(Q,J){let G=Q.split(`
`),H=`^${J}`;for(let K=0;K<G.length;K++)if(G[K].trimEnd()===H){let z=K;while(z>0&&G[z-1].trim()!=="")z--;return{startLine:z,endLine:K}}return null}function zQ0(Q,J){for(let G=0;G<J;G++)if(/^#\s/.test(Q[G]))return!0;return!1}function VQ0(Q){return Q.some((J)=>/^#\s/.test(J))}function qQ0(Q){let J=Array(Q.length),G=!1;for(let H=0;H<Q.length;H++){J[H]=G;let K=Q[H].trim();if(K.startsWith("```")||K.startsWith("~~~"))G=!G}return J}function YD0(Q,J,G){if(J<0||J>=Q.length)return!1;if(Q[J].trim().startsWith("```"))return!0;if(G[J])return!0;let H=Q[J].trim(),K=(q)=>q.startsWith("|")&&q.endsWith("|"),z=(q)=>/^\|[\s:|-]+\|$/.test(q)&&q.includes("---");if(!K(H))return!1;if(z(H))return!0;for(let q=J-1;q>=0;q--){let F=Q[q].trim();if(F===""||!K(F))break;if(z(F))return!0}for(let q=J+1;q<Q.length;q++){let F=Q[q].trim();if(F===""||!K(F))break;if(z(F))return!0}return!1}function dj(Q,J){return YD0(Q,J,qQ0(Q))}function UQ0(Q,J,G){let H=qQ0(Q);for(let K=J;K<=G;K++)if(YD0(Q,K,H))return!0;return!1}function $Q0(Q,J,G){let H=qQ0(Q);for(let K=J+1;K<Q.length;K++){if(H[K])continue;let z=Q[K].match(/^(#{1,6})\s/);if(z&&z[1].length<=G)return K}return Q.length}function ZQ0(Q,J){if(!Q?.blocks)return null;let G=Q.blocks[J];if(!G)return null;return{startLine:G.position.start.line,endLine:G.position.end.line}}function FQ0(Q,J,G){if(!Array.isArray(Q))return{kind:"ok-string"};let H;try{H=JSON.parse(J)}catch{return{kind:"reject",message:JD0(G)}}if(H===null||Array.isArray(H))return{kind:"ok",value:H};return{kind:"reject",message:JD0(G)}}function JD0(Q){return`Refusing to replace array-valued frontmatter field "${Q}" with a scalar value: this would silently destroy the existing array `+"structure. Pass content as a JSON-encoded value — for example "+`'["new"]' to set a single-element array, '["a","b"]' for multiple elements, or 'null' to clear the field.`}function DQ0(Q,J){if(!Array.isArray(Q))return{kind:"string-concat"};let G;try{G=JSON.parse(J)}catch{return{kind:"array-push",values:[J]}}if(Array.isArray(G))return{kind:"array-push",values:G};return{kind:"array-push",values:[G]}}async function GD0(Q,J,G){let H=G.targetDelimiter??"::",K=G.targetType!=="block",z=G.createTargetIfMissing??K;if(G.targetType==="frontmatter"){let N=null;if(await Q.fileManager.processFrontMatter(J,(I)=>{let R=I,w=R[G.target];if(G.operation==="replace"){let T=FQ0(w,G.content,G.target);if(T.kind==="reject"){N=T.message;return}R[G.target]=T.kind==="ok"?T.value:G.content;return}let E=DQ0(w,G.content);if(E.kind==="array-push"){let T=w.slice();if(G.operation==="append")T.push(...E.values);else T.unshift(...E.values);R[G.target]=T;return}if(w==null){R[G.target]=G.content;return}R[G.target]=G.operation==="append"?String(w)+G.content:G.content+String(w)}),N!==null)return{content:[{type:"text",text:N}],isError:!0};return{content:[{type:"text",text:"File patched successfully"}]}}let q=await Q.vault.read(J),F=q.split(`
`);if(G.targetType==="heading"){let N=G.target;if(!G.target.includes(H)){let a=kZ(q,G.target,H);if(a)N=a}let I=N.split(H),R=I[I.length-1],w=KQ0(F,R);if(w===null){if(!z)return{content:[{type:"text",text:`Heading not found: ${G.target}`}],isError:!0};let a=dJ(G.content,G.operation);return await Q.vault.modify(J,q+a),{content:[{type:"text",text:"File patched successfully"}]}}let{line:E,level:T}=w;if(T>=2&&!z&&!zQ0(F,E)&&!G.allowRootHeadings&&VQ0(F))return{content:[{type:"text",text:`Heading "${G.target}" is a level-${T} heading with no level-1 (#) parent, while the document does contain an H1 elsewhere — the section boundary is ambiguous. Refusing to patch. Pass allowRootHeadings:true to target it explicitly, or createTargetIfMissing:true to bypass. (Files with no H1 at all are accepted automatically.)`}],isError:!0};let y=$Q0(F,E,T),x=dJ(G.content,G.operation),b=y<F.length&&/^#{1,6}\s/.test(F[y]),g=x===""||x.startsWith(`
`),l=x===""||x.endsWith(`
`),_;if(G.operation==="replace"){let a=g?[]:[""],r=b&&!l?[""]:[];_=[...F.slice(0,E+1),...a,x,...r,...F.slice(y)]}else if(G.operation==="prepend")_=[...F.slice(0,E+1),x,...F.slice(E+1)];else _=[...F.slice(0,y),x,...F.slice(y)];return await Q.vault.modify(J,_.join(`
`)),{content:[{type:"text",text:"File patched successfully"}]}}let D=Q.metadataCache.getFileCache(J),V=ZQ0(D,G.target);if(!V)V=UWQ(q,G.target);if(!V){if(!z)return{content:[{type:"text",text:`Block not found: ^${G.target} (unresolved — block may be inside a table, which is not indexed by Obsidian's metadataCache)`}],isError:!0};let N=dJ(G.content,G.operation);return await Q.vault.modify(J,q+N),{content:[{type:"text",text:"File patched successfully"}]}}if(UQ0(F,V.startLine,V.endLine))return{content:[{type:"text",text:`Block "^${G.target}" resolved to line ${V.startLine+1} but it is inside a markdown table or fenced code block. Refusing to patch — replacing or splicing this region would corrupt the surrounding structure. Move the block id outside the table/code block to make it patchable.`}],isError:!0};let O=dJ(G.content,G.operation),P;if(G.operation==="replace")P=[...F.slice(0,V.startLine),O,...F.slice(V.endLine+1)];else if(G.operation==="prepend")P=[...F.slice(0,V.startLine),O,...F.slice(V.startLine)];else P=[...F.slice(0,V.endLine+1),O,...F.slice(V.endLine+1)];return await Q.vault.modify(J,P.join(`
`)),{content:[{type:"text",text:"File patched successfully"}]}}var WD0=e({name:'"append_to_active_file"',arguments:{content:e("string").describe("Markdown content to append at the end of the active note.")}}).describe("Appends content to the end of the currently active note. A trailing double newline is added when missing to keep the next section visually separated.");async function HD0(Q){let J=Q.app.workspace.getActiveFile();if(!J)return xQ("No active file.");let G=await Q.app.vault.read(J),H=dJ(Q.arguments.content,"append");return await Q.app.vault.modify(J,G+H),J8("OK")}var BD0=e({name:'"patch_active_file"',arguments:{operation:'"append"|"prepend"|"replace"',targetType:'"heading"|"block"|"frontmatter"',target:e("string>0").describe("Heading name, block id, or frontmatter key (depending on targetType)."),content:e("string").describe("Content to apply (semantics depend on operation+targetType)."),"targetDelimiter?":"string","createTargetIfMissing?":"boolean","allowRootHeadings?":e("boolean").describe("When true, allow targeting a level-2-or-deeper heading with no level-1 (#) parent even when the document contains an H1 elsewhere (the ambiguous 'mixed' case the H2-root guard rejects with createTargetIfMissing=false). Files with no H1 at all are accepted without this flag. Default false.")}}).describe("Patches the currently active note relative to a heading, block reference, or frontmatter key.");async function AD0(Q){let J=Q.app.workspace.getActiveFile();if(!J)return xQ("No active file.");return await $WQ(Q.app,J,Q.arguments)}async function $WQ(Q,J,G){let H=G.createTargetIfMissing??G.targetType!=="block",K=G.targetDelimiter??"::";if(G.targetType==="frontmatter"){let F=null;if(await Q.fileManager.processFrontMatter(J,(D)=>{let V=D,O=V[G.target];if(G.operation==="replace"){let N=FQ0(O,G.content,G.target);if(N.kind==="reject"){F=N.message;return}V[G.target]=N.kind==="ok"?N.value:G.content;return}let P=DQ0(O,G.content);if(P.kind==="array-push"){let N=O.slice();if(G.operation==="append")N.push(...P.values);else N.unshift(...P.values);V[G.target]=N;return}if(O==null){V[G.target]=G.content;return}V[G.target]=G.operation==="append"?String(O)+G.content:G.content+String(O)}),F!==null)return xQ(F);return J8("OK")}let z=await Q.vault.read(J),q=z.split(`
`);if(G.targetType==="heading"){let F=kZ(z,G.target,K);if(!F&&!H)return xQ(`Heading "${G.target}" not found and createTargetIfMissing=false.`);if(!F){let N=dJ(G.content,G.operation);return await Q.vault.modify(J,z+N),J8("OK")}let D=F.split(K).pop(),V=-1,O=0;for(let N=0;N<q.length;N++){let I=/^(#+)\s+(.+?)\s*$/.exec(q[N]);if(I&&I[2].trim()===D){V=N,O=I[1].length;break}}if(V!==-1&&O>=2&&!H&&!zQ0(q,V)&&!G.allowRootHeadings&&VQ0(q))return xQ(`Heading "${G.target}" is a level-${O} heading with no level-1 (#) parent, while the document does contain an H1 elsewhere — the section boundary is ambiguous. Refusing to patch. Pass allowRootHeadings:true to target it explicitly, or createTargetIfMissing:true to bypass. (Files with no H1 at all are accepted automatically.)`);let P=q.length;for(let N=V+1;N<q.length;N++){let I=/^(#+)\s+/.exec(q[N]);if(I&&I[1].length<=O){P=N;break}}if(G.operation==="append"){let N=dJ(G.content,"append");q.splice(P,0,N.replace(/\n$/,""))}else if(G.operation==="prepend")q.splice(V+1,0,G.content);else{let N=P<q.length&&/^#{1,6}\s/.test(q[P]),I=G.content===""||G.content.startsWith(`
`),R=G.content===""||G.content.endsWith(`
`),w=[];if(!I)w.push("");if(w.push(G.content),N&&!R)w.push("");q.splice(V+1,P-V-1,...w)}return await Q.vault.modify(J,q.join(`
`)),J8("OK")}if(G.targetType==="block"){let F=Q.metadataCache.getFileCache(J),D=ZQ0(F,G.target);if(!D&&!H)return xQ(`Block "^${G.target}" not found in active file (createTargetIfMissing=false).`);if(!D){let V=dJ(G.content,G.operation);return await Q.vault.modify(J,z+V),J8("OK")}if(UQ0(q,D.startLine,D.endLine))return xQ(`Block "^${G.target}" resolved to line ${D.startLine+1} but it is inside a markdown table or fenced code block. Refusing to patch — replacing or splicing this region would corrupt the surrounding structure. Move the block id outside the table/code block to make it patchable.`);if(G.operation==="append")q.splice(D.endLine+1,0,G.content);else if(G.operation==="prepend")q.splice(D.startLine,0,G.content);else q.splice(D.startLine,D.endLine-D.startLine+1,G.content);return await Q.vault.modify(J,q.join(`
`)),J8("OK")}return xQ(`Unknown targetType: ${G.targetType}`)}var KD0=e({name:'"delete_active_file"',arguments:{}}).describe("Deletes the currently active note from the vault.");async function zD0(Q){let J=Q.app.workspace.getActiveFile();if(!J)return xQ("No active file.");return await Q.app.fileManager.trashFile(J),J8("OK")}var VD0=e({name:'"show_file_in_obsidian"',arguments:{filename:e("string>0").describe("Vault-relative path (e.g. 'Notes/foo.md'). Created if missing."),"newLeaf?":"boolean"}}).describe("Opens the given file in the Obsidian UI. Creates it if it does not exist. Optionally opens in a new leaf (split).");async function qD0(Q){return await Q.app.workspace.openLinkText(Q.arguments.filename,"",Q.arguments.newLeaf??!1),J8("File opened successfully")}var UD0=e({name:'"list_vault_files"',arguments:{"directory?":e("string").describe("Optional vault-relative directory prefix. Empty/omitted = vault root (all files)."),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Lists vault files, optionally filtered by directory prefix. Returns an array of vault-relative paths.");async function $D0(Q){let J=Q.app.vault.getFiles(),G=Q.arguments.directory??"";if(G&&!G.endsWith("/"))G=G+"/";let H=G?J.filter((q)=>q.path.startsWith(G)).map((q)=>q.path):J.map((q)=>q.path),K=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),z=H.length>K;return J8(JSON.stringify({files:z?H.slice(0,K):H,...z?{truncated:!0,total:H.length}:{}}))}var ZD0=require("obsidian");function n6(Q,J){let G=Q.getAbstractFileByPath(J);if(!G)return{ok:!1,reason:"not_found"};if(!(G instanceof ZD0.TFile))return{ok:!1,reason:"not_a_file"};return{ok:!0,file:G}}var ZWQ=new Map([["png",{mime:"image/png",kind:"image"}],["jpg",{mime:"image/jpeg",kind:"image"}],["jpeg",{mime:"image/jpeg",kind:"image"}],["gif",{mime:"image/gif",kind:"image"}],["webp",{mime:"image/webp",kind:"image"}],["svg",{mime:"image/svg+xml",kind:"image"}],["bmp",{mime:"image/bmp",kind:"image"}],["tiff",{mime:"image/tiff",kind:"image"}],["tif",{mime:"image/tiff",kind:"image"}],["ico",{mime:"image/x-icon",kind:"image"}],["avif",{mime:"image/avif",kind:"image"}],["heic",{mime:"image/heic",kind:"image"}],["heif",{mime:"image/heif",kind:"image"}],["mp3",{mime:"audio/mpeg",kind:"audio"}],["wav",{mime:"audio/wav",kind:"audio"}],["m4a",{mime:"audio/mp4",kind:"audio"}],["ogg",{mime:"audio/ogg",kind:"audio"}],["opus",{mime:"audio/opus",kind:"audio"}],["flac",{mime:"audio/flac",kind:"audio"}],["aac",{mime:"audio/aac",kind:"audio"}],["wma",{mime:"audio/x-ms-wma",kind:"audio"}]]),FWQ=10485760,DWQ=new Set(["md","txt","csv","json","yaml","yml","html","xml","css","js","ts","canvas"]),FD0=e({name:'"get_vault_file"',arguments:{path:e("string>0").describe("Vault-relative path to the file."),"format?":e('"text"|"json"').describe('Force output format. "text" returns raw content; "json" returns content + frontmatter + tags as a structured object. Default: auto-detect by extension.')}}).describe("Reads a file from the vault. Markdown and other text files return a text content block. Supported image and audio files up to 10 MiB are returned as native MCP image/audio content blocks. Video, PDF, Office documents, archives, and oversized audio/image files return a structured JSON metadata hint.");function MWQ(Q){let J=new Uint8Array(Q),G=8192,H="";for(let K=0;K<J.length;K+=8192)H+=String.fromCharCode(...J.subarray(K,K+8192));return btoa(H)}async function DD0(Q){let J=n6(Q.app.vault,Q.arguments.path);if(!J.ok)return{content:[{type:"text",text:J.reason==="not_found"?`File not found: ${Q.arguments.path}`:`Path is a folder: ${Q.arguments.path}`}],isError:!0};let G=J.file,H=G.extension.toLowerCase(),K=ZWQ.get(H);if(Q.arguments.format==="json"){let F=await Q.app.vault.read(G),V=Q.app.metadataCache.getFileCache(G)?.frontmatter??{},O=Array.isArray(V.tags)?V.tags:[],P={ctime:G.stat?.ctime??0,mtime:G.stat?.mtime??0,size:G.stat?.size??0};return{content:[{type:"text",text:JSON.stringify({path:G.path,content:F,frontmatter:V,tags:O,stat:P})}]}}if(!K||Q.arguments.format==="text"){if(DWQ.has(H)||!H||Q.arguments.format==="text")return{content:[{type:"text",text:await Q.app.vault.read(G)}]};return{content:[{type:"text",text:JSON.stringify({kind:"binary_file",filename:G.path,mimeType:"application/octet-stream",hint:"This file is binary (video, PDF, Office document, or archive) and cannot be returned as text content. Use show_file_in_obsidian to open it in the Obsidian UI."})}]}}let z=await Q.app.vault.readBinary(G);if(z.byteLength>FWQ)return{content:[{type:"text",text:JSON.stringify({kind:"binary_file",filename:G.path,mimeType:K.mime,hint:"This file is too large to be returned inline (exceeds the 10 MiB cap to avoid overflowing the MCP client context window). Use show_file_in_obsidian to open it in the Obsidian UI."})}]};let q=MWQ(z);if(K.kind==="image")return{content:[{type:"image",data:q,mimeType:K.mime}]};return{content:[{type:"audio",data:q,mimeType:K.mime}]}}var MD0=require("obsidian");async function MQ0(Q,J){if(!J)return;let G=J.split("/").filter((K)=>K.length>0);if(G.length===0)return;let H="";for(let K of G){if(H=H?`${H}/${K}`:K,Q.vault.getAbstractFileByPath(H))continue;try{await Q.vault.createFolder(H)}catch(z){let q=z instanceof Error?z.message:String(z);if(!/already exists/i.test(q))throw z}}}async function RG(Q,J){let G=J.lastIndexOf("/");if(G<=0)return;await MQ0(Q,J.slice(0,G))}var LD0=e({name:'"create_vault_file"',arguments:{path:e("string>0").describe("Vault-relative path including extension (e.g. 'Notes/new.md'). Any missing parent directories are created automatically."),content:e("string").describe("Full content of the file. If the path already exists, the content is overwritten.")}}).describe("Creates a new file at the given vault-relative path. Overwrites the file if it already exists. Missing parent directories along the path are created automatically.");async function OD0(Q){let J=Q.app.vault.getAbstractFileByPath(Q.arguments.path);if(J){if(!(J instanceof MD0.TFile))return xQ(`Path ${Q.arguments.path} is a folder, not a file.`);await Q.app.vault.modify(J,Q.arguments.content)}else await RG(Q.app,Q.arguments.path),await Q.app.vault.create(Q.arguments.path,Q.arguments.content);return J8("OK")}var PD0=e({name:'"append_to_vault_file"',arguments:{path:e("string>0").describe("Vault-relative path. Any missing parent directories are created automatically when the file does not exist."),content:e("string").describe("Markdown content to append.")}}).describe("Appends content to a vault file. Creates the file (and any missing parent directories) if it does not exist.");async function ND0(Q){let J=dJ(Q.arguments.content,"append"),G=n6(Q.app.vault,Q.arguments.path);if(G.ok){let H=await Q.app.vault.read(G.file);await Q.app.vault.modify(G.file,H+J)}else if(G.reason==="not_a_file")return xQ(`Path ${Q.arguments.path} is a folder, not a file.`);else await RG(Q.app,Q.arguments.path),await Q.app.vault.create(Q.arguments.path,J);return J8("OK")}var jD0=e({name:'"patch_vault_file"',arguments:{path:e("string>0").describe("Vault-relative path to the file to patch."),operation:'"append"|"prepend"|"replace"',targetType:'"heading"|"block"|"frontmatter"',target:e("string>0").describe("Heading name, block id (without ^), or frontmatter key."),content:e("string").describe("Content to apply."),"targetDelimiter?":e("string").describe("Delimiter used to join ancestor heading names (default: '::')."),"createTargetIfMissing?":e("boolean").describe("Creates the target if not found. Default true for heading/frontmatter, false for block. Pass false to fail loud when patching an H2-or-deeper heading in a file with no parent H1."),"allowRootHeadings?":e("boolean").describe("Allows targeting an H2-or-deeper heading with no H1 parent in a file that has an H1 elsewhere (otherwise rejected when createTargetIfMissing=false). Default false.")}}).describe("Patches a vault file relative to a heading, block reference, or frontmatter key. Unlike patch_active_file, operates on any file by vault-relative path.");async function CD0(Q){let J=n6(Q.app.vault,Q.arguments.path);if(!J.ok)return J.reason==="not_found"?xQ(`File not found: ${Q.arguments.path}`):xQ(`Path is a folder: ${Q.arguments.path}`);let G=J.file,H={...Q.arguments};return delete H.path,await GD0(Q.app,G,H)}var ID0=e({name:'"delete_vault_file"',arguments:{path:e("string>0").describe("Vault-relative path of the file to delete.")}}).describe("Deletes a file from the vault.");async function RD0(Q){let J=Q.app.vault.getAbstractFileByPath(Q.arguments.path);if(!J)return xQ(`File not found: ${Q.arguments.path}`);return await Q.app.fileManager.trashFile(J),J8("OK")}var wD0=e({name:'"rename_vault_file"',arguments:{from:e("string>0").describe("Vault-relative path of the source file, including extension (e.g. 'Notes/old.md')."),to:e("string>0").describe("Vault-relative destination path, including extension (e.g. 'Notes/new.md'). Parent directory must already exist — missing ancestors are NOT auto-created.")}}).describe("Renames or moves a vault file via app.fileManager.renameFile, preserving link integrity (wikilinks, markdown links, embeds, and frontmatter aliases referencing the file are rewritten across the vault). Source must exist, destination must not exist, destination parent directory must already exist.");async function ED0(Q){let{from:J,to:G}=Q.arguments;if(J===G)return{content:[{type:"text",text:`Source and destination are identical: ${J}`}],isError:!0};let H=Q.app.vault.getAbstractFileByPath(J);if(!H)return xQ(`Source file not found: ${J}`);if(Q.app.vault.getAbstractFileByPath(G))return xQ(`Destination already exists: ${G}`);let K=G.lastIndexOf("/");if(K>0){let z=G.slice(0,K);if(!Q.app.vault.getAbstractFileByPath(z))return xQ(`Destination parent directory does not exist: ${z}`)}try{await Q.app.fileManager.renameFile(H,G)}catch(z){return xQ(`Failed to rename: ${z instanceof Error?z.message:String(z)}`)}return{content:[{type:"text",text:JSON.stringify({ok:!0,path:G})}]}}var OQ0=require("obsidian");function LWQ(Q,J,G){let H=[];for(let K of Q){if(K.heading!==G.text)continue;if(G.level!==void 0&&K.level!==G.level)continue;if(dj(J,K.position.start.line))continue;H.push({line:K.position.start.line,level:K.level,text:K.heading})}if(H.length===0){let K=G.level!==void 0?` at level ${G.level}`:"";return{errorCode:"heading-not-found",message:`Heading not found: "${G.text}"${K}.`}}if(H.length>1)return{errorCode:"ambiguous-heading",message:`Ambiguous heading match for "${G.text}": ${H.length} candidates. Pass \`from.level\` to disambiguate.`,candidates:H};return H[0]}function OWQ(Q,J,G,H,K){for(let z of Q){if(z.position.start.line===K)continue;if(z.heading!==G)continue;if(z.level!==H)continue;if(dj(J,z.position.start.line))continue;return{errorCode:"heading-collision",message:`Heading collision: "${G}" already exists at level ${H} on line ${z.position.start.line+1}. Refusing to rename; resolve the collision first or rename the existing heading instead.`}}return null}function PWQ(Q,J,G,H){let K=Q[J],z=/^(\s*#{1,6}\s+)(.+?)(\s+\^\S+)?(\s*)$/,q=K.match(z);if(!q){let P=Q.slice();return P[J]=`${"#".repeat(H)} ${G}`,P}let[,F,,D="",V=""]=q,O=Q.slice();return O[J]=`${F}${G}${D}${V}`,O}var LQ0=" > ";function NWQ(Q){try{return decodeURIComponent(Q)}catch{return Q}}function jWQ(Q){return Q.replace(/%/g,"%25").replace(/ /g,"%20").replace(/#/g,"%23").replace(/\?/g,"%3F").replace(/&/g,"%26").replace(/\[/g,"%5B").replace(/\]/g,"%5D")}function CWQ(Q){if(!Q.includes(LQ0))return{segments:[Q],hadPath:!1};return{segments:Q.split(LQ0).map((G)=>G.trim()),hadPath:!0}}function SD0(Q,J,G){let{segments:H,hadPath:K}=CWQ(Q),z=!1,q=H.map((F)=>{if(F===J)return z=!0,G;return F});if(!z)return null;return K?q.join(LQ0):q[0]}function TD0(Q,J,G,H,K,z){let q=0,F=/\[\[([^\]]+?)\]\]/g,D=/\[([^\]]*)\]\(([^)]+)\)/g,V=(N)=>{let I=N.replace(F,(R,w)=>{let E=w.indexOf("#");if(E===-1)return R;let T=w.slice(0,E),y=w.slice(E+1),x=y.indexOf("|"),b=x===-1?y:y.slice(0,x),g=x===-1?"":y.slice(x);if(z(T===""?K:T,K)!==H)return R;let a=SD0(b,J,G);if(a===null)return R;return q++,`[[${T}#${a}${g}]]`});return I=I.replace(D,(R,w,E)=>{let T=E.indexOf("#");if(T===-1)return R;let y=E.slice(0,T),x=E.slice(T+1);if(z(y,K)!==H)return R;let g=NWQ(x),l=SD0(g,J,G);if(l===null)return R;return q++,`[${w}](${y}#${jWQ(l)})`}),I},O=Q.split(`
`);return{newText:O.map((N,I)=>dj(O,I)?N:V(N)).join(`
`),rewriteCount:q}}function kD0(Q){let J=Q.sourceText.split(`
`),G=LWQ(Q.sourceHeadings,J,Q.from);if("errorCode"in G)return G;if(G.text===Q.to)return{errorCode:"heading-collision",message:`Heading "${Q.to}" is already the current heading text (line ${G.line+1}, level ${G.level}). No-op rename.`};let H=OWQ(Q.sourceHeadings,J,Q.to,G.level,G.line);if(H)return H;let z=PWQ(J,G.line,Q.to,G.level).join(`
`),q=TD0(z,G.text,Q.to,Q.sourcePath,Q.sourcePath,Q.resolve),F={path:Q.sourcePath,newText:q.newText,matchedHeading:G},D=[],V=q.rewriteCount;for(let[O,P]of Object.entries(Q.backlinkers)){if(O===Q.sourcePath)continue;let{newText:N,rewriteCount:I}=TD0(P,G.text,Q.to,Q.sourcePath,O,Q.resolve);if(I===0)continue;D.push({path:O,newText:N,rewriteCount:I}),V+=I}return{source:F,backlinkers:D,linkRewriteCount:V}}var yD0=e({name:'"rename_heading"',arguments:{path:e("string>0").describe("Vault-relative path of the file containing the heading to rename."),from:{text:e("string>0").describe("Exact (case-sensitive) heading text to match. Cache-derived; matching is case-sensitive, mirroring Obsidian's link resolution."),"level?":e("1<=number.integer<=6").describe("Heading level (1-6). Optional. When omitted, ambiguity across levels surfaces as `errorCode: ambiguous-heading` with a `candidates` array.")},to:e("string>0").describe("New heading text. Must not match an existing same-level heading in the file (fail-loud per `heading-collision`).")}}).describe("Renames a heading in a vault file and rewrites every backlinking reference (wikilinks, markdown links, subheading-path links) across the vault to keep link integrity. Two-phase commit: dry-run plan first, then apply atomically. Fails loud on missing heading, multi-match ambiguity, or destination collision. Out of scope for v1: frontmatter aliases. Implements RFC #68.");function yZ(Q){return xQ(JSON.stringify(Q))}function IWQ(Q){return J8(JSON.stringify(Q))}function RWQ(Q){return xQ(JSON.stringify(Q))}function wWQ(Q,J){let G=[];for(let[H,K]of Object.entries(Q)){if(H===J)continue;if(J in K)G.push(H)}return G}async function vD0(Q){let{path:J,from:G,to:H}=Q.arguments,K=n6(Q.app.vault,J);if(!K.ok)return yZ({errorCode:"file-not-found",message:`Source file not found: ${J}`});let z=K.file,q=await Q.app.vault.cachedRead(z),D=(Q.app.metadataCache.getFileCache(z)??{}).headings??[],V=Q.app.metadataCache.resolvedLinks??{},O=wWQ(V,J),P={};for(let E of O){let T=Q.app.vault.getAbstractFileByPath(E);if(!(T instanceof OQ0.TFile))continue;try{P[E]=await Q.app.vault.cachedRead(T)}catch{continue}}let I=kD0({sourcePath:J,sourceText:q,sourceHeadings:D,from:G,to:H,backlinkers:P,resolve:(E,T)=>{return Q.app.metadataCache.getFirstLinkpathDest?.(E,T)?.path??null}});if("errorCode"in I)return EWQ(I);let R=[],w=[];try{if(await Q.app.vault.cachedRead(z)!==q)return yZ({errorCode:"source-write-failed",message:"Source file changed between plan and apply; aborted before any write to avoid overwriting a concurrent edit. Re-run the rename."});await Q.app.vault.modify(z,I.source.newText),R.push(I.source.path)}catch(E){return yZ({errorCode:"source-write-failed",message:`Failed to write source file: ${E instanceof Error?E.message:String(E)}`})}for(let E of I.backlinkers){let T=Q.app.vault.getAbstractFileByPath(E.path);if(!(T instanceof OQ0.TFile)){w.push({path:E.path,error:"Backlinker file disappeared between plan and apply."});continue}try{if(await Q.app.vault.cachedRead(T)!==P[E.path]){w.push({path:E.path,error:"File changed between plan and apply; left untouched to avoid overwriting a concurrent edit. Re-run the rename."});continue}await Q.app.vault.modify(T,E.newText),R.push(E.path)}catch(y){w.push({path:E.path,error:y instanceof Error?y.message:String(y)})}}if(w.length>0)return RWQ({errorCode:"partial-failure",message:`Heading renamed but ${w.length} backlinker write(s) failed. The source file was updated; some references may still point at the old heading.`,updatedFiles:R,failedFiles:w,linkRewriteCount:I.linkRewriteCount});return IWQ({ok:!0,updatedFiles:R,linkRewriteCount:I.linkRewriteCount})}function EWQ(Q){if(Q.errorCode==="ambiguous-heading")return yZ({errorCode:Q.errorCode,message:Q.message,candidates:Q.candidates});return yZ({errorCode:Q.errorCode,message:Q.message})}var xD0=e({name:'"create_vault_directory"',arguments:{path:e("string>0").describe("Vault-relative directory path (e.g. 'Projects/2026/Q2'). Any missing intermediate ancestors are created. The leading and trailing slashes are tolerated but ignored.")}}).describe("Creates a directory at the given vault-relative path, recursively creating any missing parent directories. Idempotent — succeeds silently if the directory already exists.");async function bD0(Q){let J=Q.arguments.path.replace(/^\/+|\/+$/g,"");if(!J)return xQ("Path is empty after normalisation; cannot create the vault root.");let G=Q.app.vault.getAbstractFileByPath(J);if(G){if(G.children===void 0)return xQ(`A file already exists at ${J}; cannot create directory with the same path.`);return J8("OK")}return await MQ0(Q.app,J),J8("OK")}var gD0=e({name:'"delete_vault_directory"',arguments:{path:e("string>0").describe("Vault-relative directory path to delete (e.g. 'Archive/old-project'). Cannot be empty or the vault root."),"recursive?":e('"true" | "false"').describe('When `"true"`, deletes the directory together with every file and sub-directory it contains. When `"false"` (default), the call fails if the directory is non-empty. Use `"true"` deliberately — this operation is irreversible from MCP and bypasses the trash setting.')}}).describe('Deletes a directory from the vault. Defaults to non-recursive (fails if the directory is not empty). Use `recursive: "true"` to remove the directory and all its contents in one call. Bottoms out in `app.vault.adapter.rmdir`, so deleted content does NOT go through the Obsidian trash.');async function hD0(Q){let J=Q.arguments.path.replace(/^\/+|\/+$/g,"");if(!J)return xQ("Path is empty after normalisation; refusing to delete the vault root.");let G=(Q.arguments.recursive??"false")==="true",H=Q.app.vault.getAbstractFileByPath(J);if(H){if(H.children===void 0)return xQ(`Path ${J} is a file, not a directory. Use delete_vault_file instead.`)}try{await Q.app.vault.adapter.rmdir(J,G)}catch(K){let z=K?.code,q=z==="ENOTEMPTY"?'directory not empty (use recursive: "true" to delete it together with its contents)':z==="ENOENT"?"directory does not exist":z==="EACCES"||z==="EPERM"?"permission denied":K instanceof Error?K.message:String(K);return{content:[{type:"text",text:`Failed to delete directory ${J}: ${q}`}],isError:!0}}return J8("OK")}var uD0=K7(fD0(),1);var mD0=e({name:'"execute_dataview_query"',arguments:{query:e("string>0").describe('Dataview DQL query. Supports `TABLE`, `LIST`, `TASK`, and `CALENDAR` query types. Examples: `TABLE file.mtime FROM "Projects"`, `LIST FROM #client`, `TASK WHERE !completed`. For large vaults prefer `LIMIT n` in the query itself — the tool returns the full result with no row cap.'),"sourcePath?":e("string>0").describe("Optional vault-relative origin file. Establishes relative-link / `this.*` resolution context for the query (maps to Dataview's `originFile` internally).")}}).describe('Run a Dataview DQL query against the vault and return the native typed result. In-process via the Dataview plugin API (`app.plugins.plugins.dataview.api.query`) — no Local REST API required. Returns the typed shape per query type: TABLE → `{type:"table", headers, values}`, LIST → `{type:"list", values}`, TASK → `{type:"task", values}`, CALENDAR → `{type:"calendar", values}`. Requires the Dataview community plugin: `errorCode: "dataview_not_installed"` if absent, `dataview_not_ready` if loaded but the index has not finished building (retry shortly — Dataview fires `dataview:index-ready` when done), `dataview_query_failed` if the DQL itself is rejected (the underlying error is surfaced verbatim).');async function cj(Q){let{query:J,sourcePath:G}=Q.arguments,K=Q.app.plugins?.plugins?.dataview;if(!K)return vZ("The Dataview community plugin is not installed. Install it from Obsidian's community plugins and enable it, then retry.","dataview_not_installed",{query:J});if(!K.api)return vZ("Dataview is loaded but its index has not finished building yet. Retry shortly (Dataview fires `dataview:index-ready` when ready).","dataview_not_ready",{query:J});let z;try{z=await K.api.query(J,G)}catch(F){return vZ(String(F instanceof Error?F.message:F),"dataview_query_failed",{query:J})}if(!z.successful)return vZ(String(z.error),"dataview_query_failed",{query:J});let q;try{q=JSON.stringify(z.value)}catch{return vZ("Dataview result contains non-serialisable values (circular reference or BigInt). Add LIMIT or simplify the query to reduce result complexity.","dataview_query_failed",{query:J})}return{content:[{type:"text",text:q}]}}function vZ(Q,J,G){return xQ(JSON.stringify({error:Q,errorCode:J,...G}))}var pD0=e({name:'"search_vault"',arguments:{query:e("string>0").describe(`Dataview DQL query (e.g. 'TABLE FROM "Notes"') or JsonLogic expression (JSON string).`),"queryType?":e('"dataview"|"jsonlogic"').describe("Query language. Default: dataview.")}}).describe('Run a Dataview DQL or JsonLogic query against the vault. DQL: in-process via the Dataview plugin API — requires the Dataview community plugin (`errorCode: "dataview_not_installed"` if absent). JsonLogic: filter all vault markdown files by frontmatter/tags/path using a JsonLogic rule (JSON string); no additional plugin required. Returns the Dataview query result for DQL, or a JSON array of matching `{path}` objects for JsonLogic.');async function lD0(Q){let{query:J,queryType:G="dataview"}=Q.arguments;if(G==="jsonlogic"){let H;try{H=JSON.parse(J)}catch{return xQ('JsonLogic query must be a valid JSON string. Example: {"==": [{"var": "frontmatter.status"}, "active"]}')}let K=Q.app.vault.getMarkdownFiles().filter((z)=>{let q=Q.app.metadataCache.getFileCache(z),F={path:z.path,basename:z.basename,tags:(q?.tags??[]).map((D)=>D.tag),frontmatter:q?.frontmatter??{},created:z.stat.ctime,modified:z.stat.mtime,size:z.stat.size};try{return!!uD0.apply(H,F)}catch{return!1}}).map((z)=>({path:z.path}));return J8(JSON.stringify(K))}return cj({arguments:{query:J},app:Q.app})}var SWQ=100,TWQ=50,cD0=e({name:'"search_vault_simple"',arguments:{query:e("string>0").describe("Substring to search for (case-insensitive)."),"contextLength?":e("number.integer>=0").describe("Characters of context to include before/after each match. Default 100."),"limit?":e("number.integer>=1").describe("Max number of files to return matches from. Default 50.")}}).describe("Plain-text substring search across all markdown files in the vault. Returns each matching file with surrounding context for each hit."),dD0=8;function kWQ(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function iD0(Q){let J=Q.arguments.query,G=Q.arguments.contextLength??SWQ,H=Q.arguments.limit??TWQ,K=kWQ(J),z=Q.app.vault.getMarkdownFiles(),q=[];for(let F=0;F<z.length&&q.length<H;F+=dD0){let D=z.slice(F,F+dD0),V=await Promise.all(D.map(async(O)=>{let P=await Q.app.vault.cachedRead(O),N=[],I,R=new RegExp(K,"gi");while((I=R.exec(P))!==null){let w=I.index,E=Math.max(0,w-G),T=Math.min(P.length,w+J.length+G);N.push({context:P.slice(E,T),match:{start:w,end:w+J.length}}),R.lastIndex=w+J.length}return N.length>0?{filename:O.path,matches:N}:null}));for(let O of V){if(O===null)continue;if(q.length>=H)break;q.push(O)}}return J8(JSON.stringify({results:q}))}var oD0=!1;function ij(Q){let J=Q.metadataCache.isUserIgnored?.bind(Q.metadataCache);if(!J){if(!oD0)oD0=!0,SQ.warn("isUserIgnored unavailable — `Files & Links → Excluded files` filtering disabled for this session. If you see this in production, the Obsidian runtime API may have changed.");return()=>!1}return(G)=>J(G)}var nD0=e({name:'"search_vault_smart"',arguments:{query:e("string>0").describe("Natural-language search phrase. Returns notes ranked by semantic similarity."),"filter?":{"includeFolders?":e("string[]").describe("Restrict results to notes whose path starts with one of these folder prefixes."),"excludeFolders?":e("string[]").describe("Skip notes whose path starts with one of these folder prefixes.")},"limit?":e("number.integer>=1").describe("Maximum number of results to return. Default 10.")}}).describe("Semantic search through the configured semantic search provider — native Transformers.js (default) or Smart Connections, per Settings → MCP Connector → Semantic Search. Returns notes ranked by similarity to the query.");function oj(Q){return{content:[{type:"text",text:Q}],isError:!0}}async function aD0(Q){let J=Q.plugin.semanticSearchState;if(!J)return oj("Semantic search is not initialized yet. Reload the MCP Connector plugin and try again, or check the developer console for the setup error.");let G=J.settings,H=G?.provider==="smart-connections"||G?.provider==="auto"&&Qx(Q.plugin),K=G?.provider==="embedding-gemma"||G?.provider==="multilingual-e5-base";if(!H&&!K)J.startIndexerIfNeeded?.();let z=J.provider;if(!z.isReady()){if(J.pendingProvider)return oj(`Semantic search is not ready: the "${J.pendingProvider}" index is still being built. Open Settings → MCP Connector → Semantic Search and click "Rebuild now" if the build has not started yet.`);return oj(H?"Semantic search is not ready: the Smart Connections plugin is not loaded or has not finished indexing this vault. Wait for Smart Connections to finish loading, or open Settings → MCP Connector → Semantic Search to switch providers.":"Semantic search is not ready. The provider may still be loading the embedding model, or the configured backend is unavailable. Open Settings → MCP Connector → Semantic Search to choose or reconfigure a provider.")}let q;try{q=await z.search(Q.arguments.query,{folders:Q.arguments.filter?.includeFolders,excludeFolders:Q.arguments.filter?.excludeFolders,limit:Q.arguments.limit})}catch(D){let V=D instanceof Error?D.message:String(D);return oj(`Semantic search failed: ${V}`)}let F=ij(Q.app);return q=q.filter((D)=>!F(D.filePath)),J8(JSON.stringify({results:q}))}var sD0=e({name:'"list_obsidian_commands"',arguments:{"filter?":e("string").describe("Case-insensitive substring; matches against command id or display name."),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Lists registered Obsidian commands (core + plugins). Always read-only and unrestricted by command-permissions.");async function rD0(Q){let J=Q.app.commands.listCommands(),G=Q.arguments.filter?.toLowerCase(),H=G?J.filter((q)=>q.id.toLowerCase().includes(G)||q.name.toLowerCase().includes(G)):J,K=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),z=H.length>K;return J8(JSON.stringify({commands:z?H.slice(0,K):H,...z?{truncated:!0,total:H.length}:{}}))}var NQ0=0,jQ0=0;function tD0(){let Q=Date.now(),J=Math.floor(Q/60000)*60000;if(J!==NQ0)NQ0=J,jQ0=0;if(jQ0>=100)return{ok:!1,retryAfterMs:NQ0+60000-Q};return jQ0+=1,{ok:!0}}var eD0=e({name:'"execute_obsidian_command"',arguments:{commandId:e("string>0").describe("Obsidian command id to execute, e.g. 'editor:toggle-bold'. Use list_obsidian_commands to discover available commands. The user must have authorized this command in plugin settings.")}}).describe("Execute a registered Obsidian command by id. Gated by the command-permissions policy (deny-by-default + per-command allowlist, with optional modal confirmation) and rate-limited at 100/min. Always call list_obsidian_commands first to discover what commands exist in the current vault.");async function QM0(Q){let J=tD0();if(!J.ok){let q=Math.ceil((J.retryAfterMs??0)/1000);return xQ(`Rate limit exceeded: too many command executions in the last minute. Retry in ${q}s.`)}let G=Q.plugin;if(typeof G.checkCommandPermission!=="function")return xQ("Internal error: permission check not available on plugin.");let H=await G.checkCommandPermission(Q.arguments.commandId);if(H.outcome!=="allow"){let q=H.reason?`: ${H.reason}`:". Command is denied or not allowed by plugin settings.";return xQ(`Command denied${q}`)}if(!Q.app.commands.executeCommandById(Q.arguments.commandId))return xQ(`Command not found: '${Q.arguments.commandId}'. Use list_obsidian_commands to discover available commands.`);return J8(`Executed Obsidian command '${Q.arguments.commandId}'.`)}var LP0=require("obsidian"),OP0=K7(DP0(),1),fHQ=5000,mHQ=500000,MP0=30000;function uHQ(Q){let J=Q.replace(/^\[|\]$/g,"").toLowerCase();if(J==="localhost"||J.endsWith(".local")||J==="0.0.0.0"||J==="::"||J==="::1")return!0;let G=/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(J);if(G){let[H,K]=[Number(G[1]),Number(G[2])];if(H===127)return!0;if(H===10)return!0;if(H===192&&K===168)return!0;if(H===169&&K===254)return!0;if(H===172&&K>=16&&K<=31)return!0;return!1}if(J.includes(":")){if(/^f[cd][0-9a-f]{0,2}:/.test(J))return!0;if(/^fe[89ab][0-9a-f]:/.test(J))return!0}return!1}function pHQ(Q){let J;try{J=new URL(Q)}catch{return"Invalid URL."}if(J.protocol!=="http:"&&J.protocol!=="https:")return`Unsupported URL scheme "${J.protocol}". Only http: and https: are allowed.`;if(uHQ(J.hostname))return`Refusing to fetch internal/loopback host "${J.hostname}".`;return null}var PP0=e({name:'"fetch"',arguments:{url:e("string").describe("URL to fetch."),"format?":e('"markdown"|"html"').describe("Response format. Default markdown (HTML→MD via Turndown)."),"maxLength?":e("number.integer>=1").describe("Maximum characters to return. Default 5000."),"startIndex?":e("number.integer>=0").describe("Starting character offset. Default 0.")}}).describe("Fetches a URL and returns the body as Markdown (default) or raw HTML, with pagination support for long pages.");async function NP0(Q){let J=Q.arguments.format??"markdown",G=Math.min(Q.arguments.maxLength??fHQ,mHQ),H=Q.arguments.startIndex??0,K=pHQ(Q.arguments.url);if(K)return xQ(`Fetch rejected: ${K}`);let z;try{let P,N=new Promise((I,R)=>{P=window.setTimeout(()=>R(Error("__FETCH_TIMEOUT__")),MP0)});try{z=await Promise.race([LP0.requestUrl({url:Q.arguments.url}),N])}finally{if(P)window.clearTimeout(P)}}catch(P){let N=P instanceof Error?P.message:String(P);if(N==="__FETCH_TIMEOUT__")return xQ(`Fetch failed: request timed out after ${MP0}ms.`);return xQ(`Fetch failed: ${N}`)}let q=z.text;if(J==="markdown")q=new OP0.default({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced"}).turndown(q);let F=q.slice(H,H+G),D=q.length,O=D>H+G?`
[Content truncated. ${D-H-G} characters remaining; resume with startIndex=${H+G}.]`:"";return J8(F+O)}var o80=require("obsidian");var lHQ=fP(),jP0=e({name:'"execute_template"',arguments:{templatePath:e("string>0").describe("Vault-relative path to the Templater template file (e.g. 'Templates/daily.md')."),"targetPath?":e("string").describe("Optional vault-relative path where the rendered file will be created. If omitted, the template is rendered and the content returned without writing a file."),"createFile?":e('"true"|"false"').describe('Set to "true" to create a file at targetPath after rendering. Ignored if targetPath is not supplied.'),"arguments?":e("Record<string, string>").describe("Optional key-value pairs forwarded to the template via tp.user.mcpTools.prompt(argName).")}}).describe('Renders a template via Templater when installed, else the core Templates plugin ({{title}}/{{date}}/{{time}} only). With targetPath and createFile="true" also creates the note at targetPath. Error codes: templater_not_installed, template_not_found, template_execution_failed, core_templates_execution_failed. `arguments` is Templater-only (warning on the core path).');async function CP0(Q){let J=Q.plugin.app.plugins.plugins["templater-obsidian"]?.templater;if(!J){let F=Q.app.internalPlugins?.plugins?.templates;if(F?.enabled)return dHQ(Q,F.instance?.options);return c3("No template engine found. Install Templater for dynamic templates, or enable the core Templates plugin for basic {{title}}/{{date}}/{{time}} substitution.","templater_not_installed",{templatePath:Q.arguments.templatePath})}let G=n6(Q.app.vault,Q.arguments.templatePath);if(!G.ok)return G.reason==="not_found"?c3(`Template not found: ${Q.arguments.templatePath}`,"template_not_found",{templatePath:Q.arguments.templatePath}):c3(`Template path is a folder: ${Q.arguments.templatePath}`,"template_not_found",{templatePath:Q.arguments.templatePath});let H=G.file,K=Q.arguments.createFile==="true",z=Q.arguments.arguments??{},q=(F)=>z[F]??"";return lHQ.run(async()=>{let F=J.functions_generator.generate_object.bind(J.functions_generator);J.functions_generator.generate_object=async function(D,V){let O=await F(D,V);return Object.assign(O,{mcpTools:{prompt:q}}),O};try{let D=J.create_running_config(H,H,pP.RunMode.CreateNewFromTemplate),V=await J.read_and_parse_template(D);if(K&&Q.arguments.targetPath)return await RG(Q.app,Q.arguments.targetPath),await Q.app.vault.create(Q.arguments.targetPath,V),{content:[{type:"text",text:JSON.stringify({message:"Template executed and file created successfully",content:V,path:Q.arguments.targetPath})}]};return{content:[{type:"text",text:JSON.stringify({message:"Template executed without creating a file",content:V})}]}}catch(D){let V=D instanceof Error?D.message:String(D);return c3(`Template execution failed: ${V}`,"template_execution_failed",{templatePath:Q.arguments.templatePath})}finally{J.functions_generator.generate_object=F}})}async function dHQ(Q,J){let{templatePath:G,targetPath:H,createFile:K,arguments:z}=Q.arguments,q=n6(Q.app.vault,G);if(!q.ok)return q.reason==="not_found"?c3(`Template not found: ${G}`,"template_not_found",{templatePath:G}):c3(`Template path is a folder: ${G}`,"template_not_found",{templatePath:G});let F=q.file,D;try{D=await Q.app.vault.read(F)}catch(T){return c3(`Core Templates could not read template file: ${T instanceof Error?T.message:String(T)}`,"core_templates_execution_failed",{templatePath:G})}let V=J?.dateFormat??"YYYY-MM-DD",O=J?.timeFormat??"HH:mm",P=(T)=>{return(T.split("/").pop()??T).replace(/\.[^.]+$/,"")},N=H?P(H):P(G),I=D.replace(/\{\{title\}\}/g,N).replace(/\{\{date\}\}/g,o80.moment().format(V)).replace(/\{\{time\}\}/g,o80.moment().format(O)),R=K==="true",E=z&&Object.keys(z).length>0?"arguments map is ignored by the core Templates engine (Templater-specific)":void 0;if(R&&H)return await RG(Q.app,H),await Q.app.vault.create(H,I),{content:[{type:"text",text:JSON.stringify({message:"Template executed and file created successfully",content:I,path:H,...E?{warning:E}:{}})}]};return{content:[{type:"text",text:JSON.stringify({message:"Template executed without creating a file",content:I,...E?{warning:E}:{}})}]}}function c3(Q,J,G){return xQ(JSON.stringify({error:Q,errorCode:J,...G}))}var IP0=e({name:'"list_tags"',arguments:{"sort?":e('"name" | "count"').describe("Sort by tag name (alphabetical, ascending) or by usage count (descending). Defaults to 'count'."),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Lists all tags used across the vault with their usage counts. Aggregates both inline `#tags` and frontmatter tags via Obsidian's metadata cache. Useful for discovering content categories, finding related notes, and understanding vault organization. Always read-only.");async function RP0(Q){let J=Q.app.metadataCache.getTags(),G=Q.arguments.sort??"count",H=(V,O)=>V.localeCompare(O,"en",{sensitivity:"variant"}),K=Object.entries(J).sort((V,O)=>{if(G==="name")return H(V[0],O[0]);if(O[1]!==V[1])return O[1]-V[1];return H(V[0],O[0])}),z=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),q=K.map(([V,O])=>({tag:V,count:O})),F=q.length>z,D={totalTags:q.length,...F?{truncated:!0}:{},tags:F?q.slice(0,z):q};return J8(JSON.stringify(D))}var wP0=e({name:'"get_files_by_tag"',arguments:{tag:e("string>0").describe("Tag to search for. The leading `#` is optional and matching is case-insensitive."),"includeNested?":e('"true" | "false"').describe('When `"true"` (default), `tag="#project"` matches `#project`, `#project/active`, `#project/archived`, etc., mirroring Obsidian\'s hierarchical tag pane behaviour. When `"false"`, only exact matches are returned.'),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Returns all vault files tagged with the given tag, with per-file occurrence count. Aggregates inline `#tags` and frontmatter tags via Obsidian's metadata cache (`getAllTags`). Sorted by occurrence count descending, with file path tiebreaker for determinism. Always read-only.");async function EP0(Q){let J=Q.arguments.tag.trim().replace(/^#+/,"").toLowerCase();if(!J)return xQ('Invalid tag: input is empty or contains only "#" characters.');let G=(Q.arguments.includeNested??"true")==="true",H=(V,O)=>V.localeCompare(O,"en",{sensitivity:"variant"}),K=(V)=>{if(V===J)return!0;if(G&&V.startsWith(`${J}/`))return!0;return!1},z=[];for(let V of Q.app.vault.getMarkdownFiles()){let O=Q.app.metadataCache.getFileCache(V);if(!O)continue;let P=0,N=O.tags??[];for(let R of N){let w=(R.tag??"").replace(/^#+/,"").toLowerCase();if(K(w))P++}let I=O.frontmatter?.tags;if(Array.isArray(I))for(let R of I){if(typeof R!=="string")continue;if(K(R.replace(/^#+/,"").toLowerCase()))P++}else if(typeof I==="string"){if(K(I.replace(/^#+/,"").toLowerCase()))P++}if(P>0)z.push({path:V.path,count:P})}z.sort((V,O)=>{if(O.count!==V.count)return O.count-V.count;return H(V.path,O.path)});let q=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),F=z.length>q,D={tag:`#${J}`,includeNested:G,totalFiles:z.length,...F?{truncated:!0}:{},files:F?z.slice(0,q):z};return J8(JSON.stringify(D))}var SP0=e({name:'"get_note_property"',arguments:{path:e("string>0").describe("Vault-relative path to the note (e.g. `Projects/Roadmap.md`)."),key:e("string>0").describe("Top-level frontmatter (YAML) key to read.")}}).describe('Reads a single frontmatter (note property) value from a vault note, preserving its native YAML type (string, number, boolean, or list). Returns `value: null` when the key is absent or the note has no frontmatter — that is not an error. Reads from Obsidian\'s metadata cache (no file I/O). Always read-only. To read the whole frontmatter block, use `get_vault_file_partial` with `mode:"frontmatter"`.');async function TP0(Q){let J=n6(Q.app.vault,Q.arguments.path);if(!J.ok)return{content:[{type:"text",text:J.reason==="not_found"?JSON.stringify({error:"File not found",errorCode:"file_not_found",path:Q.arguments.path}):JSON.stringify({error:"Path is a folder, not a file",errorCode:"not_a_file",path:Q.arguments.path})}],isError:!0};let G=J.file,H=Q.app.metadataCache.getFileCache(G)?.frontmatter,K=H&&Object.prototype.hasOwnProperty.call(H,Q.arguments.key)?H[Q.arguments.key]:null;return{content:[{type:"text",text:JSON.stringify({path:Q.arguments.path,key:Q.arguments.key,value:K??null})}]}}var kP0=e({name:'"set_note_property"',arguments:{path:e("string>0").describe("Vault-relative path to the note."),key:e("string>0").describe("Top-level frontmatter (YAML) key to set. Must not contain `:`, a newline, or a leading `#`."),value:e("string | number | boolean | string[] | number[] | null").describe("String, number, boolean, or homogeneous list of strings/numbers (dates as ISO 8601 strings). `null` removes the key. No mixed-type lists.")}}).describe('Sets one frontmatter key on a note atomically. Creates the frontmatter block if missing; `value: null` deletes the key. To replace the whole block use `patch_vault_file` with `targetType: "frontmatter"`.');function cHQ(Q){return/[:\n\r]/.test(Q)||Q.trimStart().startsWith("#")}function iHQ(Q){if(typeof Q!=="string")return Q;let J=Q.trim();if(!J.startsWith("["))return Q;try{let G=JSON.parse(J);if(!Array.isArray(G)||G.length===0)return Q;if(G.every((H)=>typeof H==="string"))return G;if(G.every((H)=>typeof H==="number"))return G}catch{}return Q}async function yP0(Q){let{path:J,key:G,value:H}=Q.arguments;if(cHQ(G))return{content:[{type:"text",text:JSON.stringify({error:"Invalid frontmatter key",errorCode:"invalid_key",key:G})}],isError:!0};let K=n6(Q.app.vault,J);if(!K.ok)return{content:[{type:"text",text:K.reason==="not_found"?JSON.stringify({error:"File not found",errorCode:"file_not_found",path:J}):JSON.stringify({error:"Path is a folder, not a file",errorCode:"not_a_file",path:J})}],isError:!0};let z=K.file;return await Q.app.fileManager.processFrontMatter(z,(F)=>{let D=F;if(H===null)delete D[G];else D[G]=iHQ(H)}),{content:[{type:"text",text:JSON.stringify({path:J,key:G,action:H===null?"deleted":"set"})}]}}var vP0=e({name:'"delete_note_property"',arguments:{path:e("string>0").describe("Vault-relative path to the note."),key:e("string>0").describe("Top-level frontmatter (YAML) key to remove.")}}).describe("Removes a single frontmatter (note property) key from a vault note via Obsidian's atomic `processFrontMatter` API. Idempotent: deleting a key that is absent (or a note with no frontmatter) succeeds as a no-op. To clear a key you can also call `set_note_property` with `value: null`.");async function xP0(Q){let{path:J,key:G}=Q.arguments,H=n6(Q.app.vault,J);if(!H.ok)return{content:[{type:"text",text:H.reason==="not_found"?JSON.stringify({error:"File not found",errorCode:"file_not_found",path:J}):JSON.stringify({error:"Path is a folder, not a file",errorCode:"not_a_file",path:J})}],isError:!0};let K=H.file;return await Q.app.fileManager.processFrontMatter(K,(z)=>{let q=z;delete q[G]}),MJ({path:J,key:G,action:"deleted"})}var bP0=e({name:'"list_property_values"',arguments:{key:e("string>0").describe("Frontmatter (YAML) key whose distinct values to enumerate across the vault."),"folder?":e("string").describe("Optional vault-relative folder prefix; only notes under it are scanned. Empty/omitted = whole vault."),"limit?":e("number>0").describe("Max distinct values to return (default 500), ordered by count descending. If more exist, `truncated` is true and `totalDistinct` reports the full count.")}}).describe("Enumerates the distinct values of a single frontmatter (note property) key across the vault, with per-value occurrence counts and native types preserved. List-valued frontmatter contributes each element. Scans Obsidian's metadata cache only (no file I/O), so it scales to large vaults. To find which notes carry a given value, use `search_vault` with a DQL/JsonLogic query. Always read-only.");async function gP0(Q){let{key:J}=Q.arguments,G=Q.arguments.limit??500,H=Q.arguments.folder??"";if(H&&!H.endsWith("/"))H=H+"/";let K=new Map,z=(V)=>{let O=JSON.stringify(V),P=K.get(O);if(P)P.count++;else K.set(O,{value:V,count:1,key:O})};for(let V of Q.app.vault.getMarkdownFiles()){if(H&&!V.path.startsWith(H))continue;let O=Q.app.metadataCache.getFileCache(V)?.frontmatter;if(!O||!Object.prototype.hasOwnProperty.call(O,J))continue;let P=O[J];if(Array.isArray(P))for(let N of P)z(N);else z(P)}let q=[...K.values()].sort((V,O)=>{if(O.count!==V.count)return O.count-V.count;return V.key.localeCompare(O.key,"en")}),F=q.length,D=q.slice(0,G).map(({value:V,count:O})=>({value:V,count:O}));return{content:[{type:"text",text:JSON.stringify({key:J,values:D,truncated:F>G,totalDistinct:F})}]}}var _P0=e({name:'"get_recent_files"',arguments:{"limit?":e("1<=number.integer<=100").describe("Maximum number of files to return (1-100, default 20). Values outside this range, zero, negative, or non-integer numbers are rejected at schema validation.")}}).describe("Returns the most recently modified markdown files in the vault, ordered by `mtime` descending with a `path` ascending tiebreaker on equal `mtime`. Each entry includes `path`, `mtime`, `ctime` (Unix epoch milliseconds), and `size` (bytes). Honours Obsidian's `Files & Links → Excluded files` configuration via `MetadataCache.isUserIgnored`; markdown-only via `vault.getMarkdownFiles()`. Useful for agent-recency context. Always read-only."),hP0=!1;async function fP0(Q){let J=Q.arguments.limit??20,G=Q.app.metadataCache.isUserIgnored?.bind(Q.app.metadataCache);if(!G&&!hP0)hP0=!0,SQ.warn("get_recent_files: app.metadataCache.isUserIgnored is unavailable — `Files & Links → Excluded files` filtering disabled for this session. If you see this in production, the Obsidian runtime API may have changed.");let H=Q.app.vault.getMarkdownFiles(),K=G?H.filter((V)=>!G(V.path)):H,z=K.length,q=(V,O)=>V.localeCompare(O,"en",{sensitivity:"variant"}),F=K.slice().sort((V,O)=>{if(O.stat.mtime!==V.stat.mtime)return O.stat.mtime-V.stat.mtime;return q(V.path,O.path)}).slice(0,J).map((V)=>({path:V.path,mtime:V.stat.mtime,ctime:V.stat.ctime,size:V.stat.size}));return J8(JSON.stringify({totalFiles:z,files:F}))}var mP0=e({name:'"get_vault_file_partial"',arguments:{filename:e("string>0").describe("Vault-relative path to the file."),mode:e('"frontmatter" | "heading" | "block" | "document-map"').describe("`frontmatter` = one field value; `heading` = the markdown section under the heading; `block` = the range of the block reference; `document-map` = outline only (headings, block ids, frontmatter keys), no body."),"target?":e("string>0").describe("Frontmatter field name, heading text (nested path via `targetDelimiter`), or block id (leading `^` optional). Ignored for `document-map`."),"targetDelimiter?":e("string>0").describe('Delimiter for nested heading paths, e.g. `Parent::Child`. Default `::`. Only for `mode: "heading"`.')}}).describe("Reads part of a vault file without loading the body: a single frontmatter field, a heading section, a block range, or the file outline. Read-only and cheap on large notes.");function oHQ(Q,J,G,H){let K=J.split(G).map((V)=>V.trim()).filter(Boolean);if(K.length===0)return{error:"Invalid heading target: empty after delimiter split."};let z=-1,q=H,F=0,D=null;for(let V=0;V<K.length;V++){let O=K[V],P=Q.filter((R)=>R.heading===O&&R.position.start.line>z&&R.position.start.line<q&&(V===0||R.level>F));if(P.length===0){let R=V===0?"in the file":`under "${K.slice(0,V).join(G)}"`;return{error:`Heading not found: "${O}" ${R}.`}}if(P.length>1){let R=P.map((w)=>`level ${w.level} at line ${w.position.start.line}`).join(", ");return{error:`Ambiguous heading target: "${O}" matches multiple headings (${R}). Use a nested path with \`targetDelimiter\` to disambiguate.`}}let N=P[0];D=N,z=N.position.start.line,F=N.level;let I=Q.find((R)=>R.position.start.line>N.position.start.line&&R.level<=N.level);q=I?I.position.start.line:H}if(!D)return{error:`Heading not found: "${J}".`};return{startLine:D.position.start.line,endLine:q,level:D.level}}async function uP0(Q){let{filename:J,mode:G,target:H,targetDelimiter:K}=Q.arguments,z=n6(Q.app.vault,J);if(!z.ok)return z.reason==="not_found"?xQ(`File not found: ${J}`):xQ(`Path is a folder: ${J}`);let q=z.file;if(G!=="document-map"&&(!H||!H.trim()))return xQ(`Missing required \`target\` for mode "${G}". The \`target\` argument is required for "frontmatter", "heading", and "block" modes.`);let F=Q.app.metadataCache.getFileCache(q)??{};if(G==="frontmatter"){let O=F.frontmatter;if(!O||Object.keys(O).length===0){let N=(await Q.app.vault.cachedRead(q)).split(`
`),I=!1;if(N[0]?.trim()==="---"){let R=-1;for(let E=1;E<N.length;E++)if(N[E].trim()==="---"){R=E;break}I=(R===-1?N.slice(1):N.slice(1,R)).some((E)=>E.trim()!=="")}if(I)return xQ(`Frontmatter block present in ${J} but Obsidian's metadata cache exposed no fields — its YAML parser could not read it. Common cause: an unquoted scalar whose value contains ": " (e.g. \`key: a value with: a colon\`); quote the value (\`key: "a value with: a colon"\`). This tool reflects Obsidian's cache and does not re-parse YAML independently, so the source file must be fixed.`);return xQ(`File has no frontmatter: ${J}.`)}let P=H.trim();if(!(P in O))return xQ(`Frontmatter field not found: "${P}" in ${J}.`);return MJ(O[P])}if(G==="document-map"){let O=(R,w)=>R.localeCompare(w,"en",{sensitivity:"variant"}),P=(F.headings??[]).map((R)=>({heading:R.heading,level:R.level,line:R.position.start.line})),N=Object.keys(F.blocks??{}).slice().sort(O),I=Object.keys(F.frontmatter??{}).slice().sort(O);return MJ({path:q.path,frontmatter:I,headings:P,blocks:N})}let V=(await Q.app.vault.cachedRead(q)).split(`
`);if(G==="heading"){let O=F.headings??[];if(O.length===0)return xQ(`File has no headings: ${J}.`);let N=oHQ(O,H,K??"::",V.length);if("error"in N)return xQ(N.error);let I=V.slice(N.startLine,N.endLine).join(`
`);return J8(I)}if(G==="block"){let O=F.blocks??{},P=H.trim().replace(/^\^+/,"");if(!P)return xQ('Invalid block target: input is empty or contains only "^" characters.');let N=O[P];if(!N)return xQ(`Block not found: "^${P}" in ${J}.`);let I=V.slice(N.position.start.line,N.position.end.line+1).join(`
`);return J8(I)}return xQ(`Unknown mode: "${G}".`)}var pP0=e({name:'"get_outgoing_links"',arguments:{path:e("string>0").describe("Vault-relative path to the source file."),"includeEmbeds?":e('"true" | "false"').describe('Default `"true"`: embeds included, marked `embed: true`. `"false"` returns only regular links.'),"includeUnresolved?":e('"true" | "false"').describe('Default `"true"`: unresolved links included with `resolved: false`. `"false"` filters them out.'),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Returns every link in a file: body links, embeds (`![[…]]`), and frontmatter links. Each entry has linkpath, original syntax, display text, layer (`body` | `frontmatter`), embed flag, resolution status, and resolved path. Document order. `isError: true` if the file does not exist.");async function lP0(Q){let J=Q.arguments.path,G=n6(Q.app.vault,J);if(!G.ok)return G.reason==="not_found"?xQ(`File not found: ${J}`):xQ(`Path is a folder: ${J}`);let H=G.file,K=Q.app.metadataCache.getFileCache(H),z=(Q.arguments.includeEmbeds??"true")==="true",q=(Q.arguments.includeUnresolved??"true")==="true",F=(R)=>{let w=Q.app.metadataCache.getFirstLinkpathDest(R,J);if(w)return{resolved:!0,targetPath:w.path};return{resolved:!1,targetPath:null}},D=(R,w,E)=>{let{resolved:T,targetPath:y}=F(R.link),x={link:R.link,original:R.original,source:w,embed:E,resolved:T,targetPath:y};if(R.displayText!==void 0)x.displayText=R.displayText;return x},V=[];for(let R of K?.links??[])V.push(D(R,"body",!1));if(z)for(let R of K?.embeds??[])V.push(D(R,"body",!0));for(let R of K?.frontmatterLinks??[])V.push(D(R,"frontmatter",!1));let O=q?V:V.filter((R)=>R.resolved),P=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),N=O.length>P,I={source:J,totalLinks:O.length,...N?{truncated:!0}:{},links:N?O.slice(0,P):O};return MJ(I)}var dP0=e({name:'"get_backlinks"',arguments:{path:e("string>0").describe("Vault-relative path of the target file. The tool returns every file that links to this path."),"includeUnresolved?":e('"true" | "false"').describe('When `"true"`, also includes sources whose link does not resolve (typo or broken-link sources matching by path or filename). Default `"false"`: unresolved backlinks are usually noise.'),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Lists every file linking to the target, with per-source link count, sorted by count descending. Works even if the target does not exist (backlinks can outlive it). Read-only.");async function cP0(Q){let J=Q.arguments.path,G=(Q.arguments.includeUnresolved??"false")==="true",H=(O,P)=>O.localeCompare(P,"en",{sensitivity:"variant"}),K=new Map,z=Q.app.metadataCache.resolvedLinks??{};for(let[O,P]of Object.entries(z)){let N=P[J]??0;if(N>0)K.set(O,(K.get(O)??0)+N)}if(G){let O=Q.app.metadataCache.unresolvedLinks??{},P=J.replace(/\.md$/,""),N=J.split("/").pop()?.replace(/\.md$/,"")??J;for(let[I,R]of Object.entries(O))for(let[w,E]of Object.entries(R)){if(E<=0)continue;if(w===J||w===P||w===N)K.set(I,(K.get(I)??0)+E)}}let q=Array.from(K,([O,P])=>({path:O,count:P}));q.sort((O,P)=>{if(P.count!==O.count)return P.count-O.count;return H(O.path,P.path)});let F=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),D=q.length>F,V={target:J,totalBacklinks:q.length,...D?{truncated:!0}:{},backlinks:D?q.slice(0,F):q};return J8(JSON.stringify(V))}var qN0=require("obsidian");var HH=require("obsidian"),r6=K7(zN0(),1);function GV(Q,J,G){let H=G??L3Q(J),K=VN0(J,H),z=Z3Q(J),q=z?F3Q(J):null,F=O3Q(J,K,q),D=Q.vault.getAbstractFileByPath(F),V=D!=null&&D.children===void 0;return{path:F,exists:V,create:async()=>{if(z)return await D3Q(J,K);return await RG(Q,F),await Q.vault.create(F,"")}}}function Z3Q(Q){switch(Q){case"daily":return r6.appHasDailyNotesPluginLoaded();case"weekly":return r6.appHasWeeklyNotesPluginLoaded();case"monthly":return r6.appHasMonthlyNotesPluginLoaded();case"quarterly":return r6.appHasQuarterlyNotesPluginLoaded();case"yearly":return r6.appHasYearlyNotesPluginLoaded()}}function F3Q(Q){switch(Q){case"daily":return r6.getDailyNoteSettings();case"weekly":return r6.getWeeklyNoteSettings();case"monthly":return r6.getMonthlyNoteSettings();case"quarterly":return r6.getQuarterlyNoteSettings();case"yearly":return r6.getYearlyNoteSettings()}}function D3Q(Q,J){switch(Q){case"daily":return r6.createDailyNote(J);case"weekly":return r6.createWeeklyNote(J);case"monthly":return r6.createMonthlyNote(J);case"quarterly":return r6.createQuarterlyNote(J);case"yearly":return r6.createYearlyNote(J)}}var M3Q={daily:"YYYY-MM-DD",weekly:"GGGG-[W]WW",monthly:"YYYY-MM",quarterly:"YYYY-[Q]Q",yearly:"YYYY"},i3={daily:/^\d{4}-\d{2}-\d{2}$/,weekly:/^\d{4}-W\d{2}$/,monthly:/^\d{4}-\d{2}$/,quarterly:/^\d{4}-Q[1-4]$/,yearly:/^\d{4}$/};function WV(Q,J){if(!i3[Q].test(J))return!1;return VN0(Q,J).isValid()}function VN0(Q,J){switch(Q){case"daily":return HH.moment(J,"YYYY-MM-DD",!0);case"weekly":return HH.moment(J,"GGGG-[W]WW",!0);case"monthly":return HH.moment(J,"YYYY-MM",!0);case"quarterly":{let G=/^(\d{4})-Q([1-4])$/.exec(J);if(!G)return HH.moment.invalid();return HH.moment().year(parseInt(G[1],10)).quarter(parseInt(G[2],10)).startOf("quarter")}case"yearly":return HH.moment(J,"YYYY",!0)}}function L3Q(Q){let J=HH.moment();switch(Q){case"daily":return J.format("YYYY-MM-DD");case"weekly":return J.format("GGGG-[W]WW");case"monthly":return J.format("YYYY-MM");case"quarterly":return`${J.format("YYYY")}-Q${J.quarter()}`;case"yearly":return J.format("YYYY")}}function O3Q(Q,J,G){let H=G?.format??M3Q[Q],K=(G?.folder??"").replace(/^\/+|\/+$/g,"").trim(),z=`${J.format(H)}.md`;return K?`${K}/${z}`:z}function yC(Q){switch(Q){case"daily":return"`YYYY-MM-DD`";case"weekly":return"`YYYY-Www` (ISO week, e.g. `2026-W21`)";case"monthly":return"`YYYY-MM`";case"quarterly":return"`YYYY-QN` (N=1-4)";case"yearly":return"`YYYY`"}}var UN0=e({name:'"get_or_create_daily_note"',arguments:{"date?":e("string").describe("ISO date `YYYY-MM-DD`. Default: today in the plugin process timezone (the user's machine TZ in the in-process / desktop deployment, which is the 99% case). For headless or multi-host setups where the MCP server runs on a different host than the Obsidian client, pass an explicit `date` to avoid TZ-driven off-by-one resolution.")}}).describe("Reads today's daily note (or the one at `date`), creating it if missing. Returns `{path, content, created}`. When the Daily Notes core plugin or the community Periodic Notes plugin is enabled, the note is created via the plugin's API so the configured template + `{{date}}`/`{{title}}` interpolations run; otherwise it is created as an empty file at the ISO path under the vault root. For weekly/monthly/quarterly/yearly notes use `get_or_create_periodic_note`.");async function $N0(Q){let{date:J}=Q.arguments;if(J!==void 0){if(!i3.daily.test(J))return{content:[{type:"text",text:JSON.stringify({error:"Invalid date format for period 'daily' — expected `YYYY-MM-DD`.",errorCode:"invalid_date_for_period",period:"daily",date:J})}],isError:!0};if(!WV("daily",J))return{content:[{type:"text",text:JSON.stringify({error:"Date is well-shaped but not a real calendar date (e.g. month 13, Feb 30).",errorCode:"invalid_date_for_period",period:"daily",date:J})}],isError:!0}}let G=GV(Q.app,"daily",J),H=!1,K=Q.app.vault.getAbstractFileByPath(G.path);if(!G.exists)K=await G.create(),H=!0;if(!K)return{content:[{type:"text",text:JSON.stringify({error:"Internal: daily note resolved but not retrievable after create.",errorCode:"internal_error",path:G.path})}],isError:!0};if(!(K instanceof qN0.TFile))return{content:[{type:"text",text:JSON.stringify({error:"Path is not a file",errorCode:"not_a_file",path:G.path})}],isError:!0};let z=await Q.app.vault.cachedRead(K);return{content:[{type:"text",text:JSON.stringify({path:G.path,content:z,created:H})}]}}var ZN0=require("obsidian");var FN0=e({name:'"get_or_create_periodic_note"',arguments:{period:e('"daily"|"weekly"|"monthly"|"quarterly"|"yearly"').describe("Period granularity. For daily, `get_or_create_daily_note` is a shortcut."),"date?":e("string").describe("Period-specific ISO date: daily `YYYY-MM-DD`, weekly `YYYY-Www`, monthly `YYYY-MM`, quarterly `YYYY-QN`, yearly `YYYY`. Default: the period containing today, host machine timezone.")}}).describe("Reads the periodic note for `period` (and optional `date`), creating it if missing. Returns `{path, content, created}`. Uses the Daily Notes / Periodic Notes plugin API when available (so configured templates run); otherwise creates an empty file at the ISO path. For structured edits, take the returned path and use `set_note_property` or `patch_vault_file`.");async function DN0(Q){let{period:J,date:G}=Q.arguments;if(G!==void 0){if(!i3[J].test(G))return{content:[{type:"text",text:JSON.stringify({error:`Invalid date format for period '${J}' — expected ${yC(J)}.`,errorCode:"invalid_date_for_period",period:J,date:G})}],isError:!0};if(!WV(J,G))return{content:[{type:"text",text:JSON.stringify({error:"Date is well-shaped but not a real calendar value (e.g. month 13, Feb 30, ISO-week 99).",errorCode:"invalid_date_for_period",period:J,date:G})}],isError:!0}}let H=GV(Q.app,J,G),K=!1,z=Q.app.vault.getAbstractFileByPath(H.path);if(!H.exists)z=await H.create(),K=!0;if(!z)return{content:[{type:"text",text:JSON.stringify({error:"Internal: periodic note resolved but not retrievable after create.",errorCode:"internal_error",period:J,path:H.path})}],isError:!0};if(!(z instanceof ZN0.TFile))return{content:[{type:"text",text:JSON.stringify({error:"Internal: periodic note resolved to a folder, not a file.",errorCode:"internal_error",period:J,path:H.path})}],isError:!0};let q=z,F=await Q.app.vault.cachedRead(q);return{content:[{type:"text",text:JSON.stringify({period:J,path:H.path,content:F,created:K})}]}}var MN0=require("obsidian");var LN0=e({name:'"append_to_periodic_note"',arguments:{"period?":e('"daily"|"weekly"|"monthly"|"quarterly"|"yearly"').describe("Period granularity. Default `daily`."),content:e("string").describe("Markdown content to append."),"date?":e("string").describe("Period-specific ISO date. Formats: daily `YYYY-MM-DD`, weekly `YYYY-Www`, monthly `YYYY-MM`, quarterly `YYYY-QN`, yearly `YYYY`. Default: the period instance containing today in the plugin process timezone."),"underHeading?":e("string>0").describe('Appends inside this heading\'s section (exact leaf name or `Parent::Child` path). If the heading is missing the call fails with `errorCode: "heading_not_found"` but the auto-created note is kept; add the heading via `patch_vault_file` and retry.')}}).describe("Appends to a periodic note (daily by default), auto-creating it like `get_or_create_periodic_note`. With `underHeading`, inserts inside that section; otherwise appends at end of file."),s80="::";async function ON0(Q){let{period:J="daily",content:G,date:H,underHeading:K}=Q.arguments;if(H!==void 0){if(!i3[J].test(H))return BF(`Invalid date format for period '${J}' — expected ${yC(J)}.`,"invalid_date_for_period",{period:J,date:H});if(!WV(J,H))return BF("Date is well-shaped but not a real calendar value (e.g. month 13, Feb 30, ISO-week 99).","invalid_date_for_period",{period:J,date:H})}let z=GV(Q.app,J,H),q=!1,F=Q.app.vault.getAbstractFileByPath(z.path);if(!z.exists)F=await z.create(),q=!0;if(!F)return BF("Internal: periodic note resolved but not retrievable after create.","internal_error",{period:J,path:z.path});if(!(F instanceof MN0.TFile))return BF("Internal: periodic note resolved to a folder, not a file.","internal_error",{period:J,path:z.path});let D=F,V=dJ(G,"append");if(K!==void 0){let O=await Q.app.vault.read(D),P=O.split(`
`),N=K;if(!K.includes(s80)){let b=kZ(O,K,s80);if(b)N=b}let I=N.split(s80),R=I[I.length-1],w=KQ0(P,R);if(w===null)return BF(`Heading not found in periodic note: "${K}".`,"heading_not_found",{period:J,path:z.path,created:q,underHeading:K});let{line:E,level:T}=w,y=$Q0(P,E,T),x=[...P.slice(0,y),V,...P.slice(y)];await Q.app.vault.modify(D,x.join(`
`))}else{let O=await Q.app.vault.read(D);await Q.app.vault.modify(D,O+V)}return{content:[{type:"text",text:JSON.stringify({period:J,path:z.path,appended:!0,created:q})}]}}function BF(Q,J,G){return xQ(JSON.stringify({error:Q,errorCode:J,...G}))}var PN0=e({name:'"find_broken_links"',arguments:{"exclude_folders?":e("string[]").describe('Vault-relative folder prefixes to skip. Default: `["templates","attachments","_archive"]`. Override is complete (not additive): passing `["custom"]` scans templates too.'),"scope?":e("string[]").describe("Optional list of vault-relative paths or folder prefixes to limit the scan. A folder prefix matches any file under it. Omit for vault-wide scan."),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Scans the vault (or a scoped subset) for unresolved links (wiki-links, markdown links, embeds, frontmatter links) and returns every broken link with its source file, 1-based line number, link target, original syntax, and link type. Uses Obsidian's metadata cache — no file I/O. Always read-only."),P3Q=["templates","attachments","_archive"];async function NN0(Q){let G=(Q.arguments.exclude_folders??P3Q).map((P)=>P.replace(/\/+$/,"")),H=Q.arguments.scope?.map((P)=>P.replace(/\/+$/,"")),K=(P)=>G.some((N)=>P===N||P.startsWith(N+"/")),z=(P)=>H===void 0||H.some((N)=>P===N||P.startsWith(N+"/")),q=Q.app.vault.getMarkdownFiles(),F=[],D=0;for(let P of q){if(K(P.path))continue;if(!z(P.path))continue;D++;let N=Q.app.metadataCache.getFileCache(P);if(!N){SQ.warn("find_broken_links: no cache for file, skipping",{path:P.path});continue}let I=(w,E)=>{if(Q.app.metadataCache.getFirstLinkpathDest(w.link,P.path)!==null)return;let y={source_path:P.path,line_number:w.position!=null?w.position.start.line+1:0,link_target:w.link,link_type:E,original:w.original};if(w.displayText!==void 0)y.display_text=w.displayText;F.push(y)},R=N;for(let w of R.links??[])I(w,"link");for(let w of R.embeds??[])I(w,"embed");for(let w of R.frontmatterLinks??[])I(w,"frontmatter")}let V=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),O=F.length>V;return{content:[{type:"text",text:JSON.stringify({total_broken_links:F.length,scanned_files:D,excluded_folders:G,...H!==void 0?{scope:H}:{},...O?{truncated:!0}:{},broken_links:O?F.slice(0,V):F})}]}}var jN0=e({name:'"find_orphaned_notes"',arguments:{"exclude_folders?":e("string[]").describe('Vault-relative folder prefixes whose notes are omitted from the orphan list. Default: `["templates","attachments","_archive"]`. Links FROM excluded folders still count as incoming references — they do not make a note an orphan.'),"limit?":e("number>0").describe("Max results returned (default 200).")}}).describe("Returns all markdown notes that have zero incoming resolved links from any vault file. Builds the referenced-file set from Obsidian's resolvedLinks cache (no file I/O). Notes in excluded folders are omitted from the output but their outgoing links still count toward other notes' reference status. Always read-only."),N3Q=["templates","attachments","_archive"];async function CN0(Q){let G=(Q.arguments.exclude_folders??N3Q).map((P)=>P.replace(/\/+$/,"")),H=(P)=>G.some((N)=>P===N||P.startsWith(N+"/")),K=new Set,z=Q.app.metadataCache.resolvedLinks;for(let P of Object.values(z))for(let N of Object.keys(P))K.add(N);let q=Q.app.vault.getMarkdownFiles(),F=[],D=0;for(let P of q){if(H(P.path))continue;if(D++,K.has(P.path))continue;let N=P.stat;if(!N){SQ.warn("find_orphaned_notes: file has no stat, skipping",{path:P.path});continue}F.push({path:P.path,mtime:N.mtime,size:N.size})}let V=Math.min(1000,Math.max(1,Math.floor(Q.arguments.limit??200))),O=F.length>V;return{content:[{type:"text",text:JSON.stringify({total_orphaned:F.length,scanned_files:D,excluded_folders:G,...O?{truncated:!0}:{},orphaned_notes:O?F.slice(0,V):F})}]}}var IN0=e({name:'"search_and_replace"',arguments:{pattern:e("string>0").describe("JavaScript regex pattern (passed to `new RegExp(pattern, flags)`). Do not include surrounding `/` delimiters."),replacement:e("string").describe("Replacement string. Supports backreferences (`$1`, `$2`, `$&` for full match, `$'`/`$\\`` for surrounding text)."),"flags?":e("string").describe('Regex flags (default `"g"`). The `g` flag is always active — omitting it is equivalent to passing `"g"`. Combine: `"gi"`, `"gm"`, `"gims"`, etc.'),"dry_run?":e('"true" | "false"').describe('When `"true"` (default), no files are modified — returns a preview of changes. Pass `"false"` to apply. Always preview first to verify scope and intent.'),"scope?":e("string[]").describe("Optional list of vault-relative paths or folder prefixes to limit the search. A folder prefix matches any file under it. Omit for vault-wide search.")}}).describe('Regex find-and-replace across the vault or a scoped file list. `dry_run` defaults to `"true"` (preview only); pass `"false"` to write. Returns files_matched, total_replacements, and up to 5 match previews per file (`line_number: 0` = multi-line match). JavaScript regex, `g` flag always active; patterns with nested quantifiers are rejected.');async function RN0(Q){let{pattern:J,replacement:G}=Q.arguments,H=(Q.arguments.dry_run??"true")==="true",K=Q.arguments.scope,z=Q.arguments.flags??"g",q=z.includes("g")?z:`g${z}`,F;try{F=new RegExp(J,q)}catch(N){let I=N instanceof Error?N.message:String(N);return SQ.warn("search_and_replace: invalid regex",{pattern:J,flags:q,error:I}),{content:[{type:"text",text:JSON.stringify({error:`Invalid regex: ${I}`,errorCode:"invalid_regex",pattern:J,flags:q})}],isError:!0}}if(/\([^)]*[+*][^)]*\)[+*?]/.test(J)||/\((?:[^()]*[+*?][^()]*\|)+[^()]+\)[+*?{]/.test(J))return{content:[{type:"text",text:JSON.stringify({error:"Pattern contains nested quantifiers (ReDoS risk). Simplify the pattern.",errorCode:"unsafe_regex",pattern:J})}],isError:!0};let D=(N)=>{if(!K||K.length===0)return!0;return K.some((I)=>N===I||N===`${I}.md`||N.startsWith(I.endsWith("/")?I:`${I}/`))},V=Q.app.vault.getMarkdownFiles().filter((N)=>D(N.path)),O=[],P=0;for(let N of V){let I=await Q.app.vault.read(N),R=(I.match(F)??[]).length;if(R===0)continue;let w=I.split(`
`),E=[];for(let T=0;T<w.length&&E.length<5;T++){if(F.lastIndex=0,!F.test(w[T]))continue;F.lastIndex=0;let y=w[T].replace(F,G);F.lastIndex=0,E.push({line_number:T+1,before:w[T].slice(0,200),after:y.slice(0,200)})}if(F.lastIndex=0,E.length===0&&R>0)E.push({line_number:0,before:"(multi-line match — no per-line preview)",after:'(apply with dry_run:"false" to see result)'});if(!H){let T=I.replace(F,G);F.lastIndex=0,await Q.app.vault.modify(N,T)}P+=R,O.push({path:N.path,replacements:R,preview:E})}return{content:[{type:"text",text:JSON.stringify({dry_run:H,pattern:J,flags_used:q,files_matched:O.length,total_replacements:P,details:O})}]}}var wN0=e({name:'"get_note_outline"',arguments:{path:e("string>0").describe("Vault-relative path to the note.")}}).describe("Returns the structured heading outline of a note: level (16), heading text, 1-based line number, and an Obsidian-compatible anchor slug. Empty array when the note has no headings. Use the anchors to construct `[[note#heading]]` links. Reads from Obsidian's metadata cache (no file I/O). Always read-only.");function j3Q(Q){return Q.trim().toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,"").replace(/\s+/g,"-")}async function EN0(Q){let{path:J}=Q.arguments,G=n6(Q.app.vault,J);if(!G.ok)return{content:[{type:"text",text:G.reason==="not_found"?JSON.stringify({error:`File not found: ${J}`,errorCode:"file_not_found",path:J}):JSON.stringify({error:`Path is a folder: ${J}`,errorCode:"not_a_file",path:J})}],isError:!0};let H=G.file,q=(Q.app.metadataCache.getFileCache(H)?.headings??[]).map((F)=>({level:F.level,text:F.heading,line_number:F.position.start.line+1,anchor:j3Q(F.heading)}));return{content:[{type:"text",text:JSON.stringify({path:J,heading_count:q.length,headings:q})}]}}var SN0=e({name:'"list_bookmarks"',arguments:{"include_types?":e('("file" | "folder" | "search" | "heading" | "block" | "group")[]').describe('Optional filter: only include items of these types. When `"group"` is excluded, group children are flattened to the parent level instead of being nested under a group node. Omit for all types.')}}).describe("Returns the native Obsidian bookmarks (core Bookmarks plugin) with their full hierarchy: groups, file bookmarks, folder bookmarks, searches, heading anchors, and block refs. `enabled: false` when the Bookmarks core plugin is disabled. `total_items` counts non-group items recursively. Always read-only.");function TN0(Q){let J=Q.type;if(!J)return null;if(J==="group"){let G=Array.isArray(Q.items)?Q.items.map(TN0).filter((H)=>H!==null):[];return{type:"group",title:String(Q.title??""),items:G}}if(J==="file"||J==="folder")return{type:J,path:String(Q.path??""),title:Q.title!=null?String(Q.title):void 0};if(J==="search")return{type:"search",query:String(Q.query??""),title:Q.title!=null?String(Q.title):void 0};if(J==="heading")return{type:"heading",path:String(Q.path??""),heading:String(Q.subpath??Q.heading??""),title:Q.title!=null?String(Q.title):void 0};if(J==="block")return{type:"block",path:String(Q.path??""),id:String(Q.subpath??Q.id??""),title:Q.title!=null?String(Q.title):void 0};return SQ.warn("list_bookmarks: unrecognized bookmark type, skipping",{type:J}),null}function kN0(Q,J){let G=[];for(let H of Q)if(H.type==="group"){let K=kN0(H.items,J);if(J.has("group"))G.push({...H,items:K});else G.push(...K)}else if(J.has(H.type))G.push(H);return G}function yN0(Q){let J=0;for(let G of Q)if(G.type==="group")J+=yN0(G.items);else J++;return J}async function vN0(Q){let J=Q.app.internalPlugins.plugins.bookmarks;if(!J?.enabled)return{content:[{type:"text",text:JSON.stringify({enabled:!1,total_items:0,items:[]})}]};if(!J.instance)return{content:[{type:"text",text:JSON.stringify({enabled:!0,total_items:0,items:[],note:"Bookmarks plugin not yet initialized"})}]};let H=J.instance.items.map(TN0).filter((K)=>K!==null);if(Q.arguments.include_types&&Q.arguments.include_types.length>0){let K=new Set(Q.arguments.include_types);H=kN0(H,K)}return{content:[{type:"text",text:JSON.stringify({enabled:!0,total_items:yN0(H),items:H})}]}}var xN0={text:{width:400,height:200},file:{width:400,height:300},link:{width:400,height:200}};function HV(Q){if(!Q)return null;let J;try{J=JSON.parse(Q)}catch{return null}if(typeof J!=="object"||J===null||Array.isArray(J))return null;let G=J;if(!Array.isArray(G.nodes)||!Array.isArray(G.edges))return null;return G}function bN0(){return{nodes:[],edges:[]}}function vC(Q){return JSON.stringify(Q,null,2)}function xC(Q,J){let G=new Set(Q),K=J??(()=>{let z=new Uint8Array(8);return crypto.getRandomValues(z),Array.from(z).map((q)=>q.toString(16).padStart(2,"0")).join("")});while(!0){let z=K();if(!G.has(z))return z}}function gN0(Q,J){let{width:G,height:H,explicitX:K,explicitY:z}=J,q=C3Q(Q,G);return{x:K??q.x,y:z??q.y,width:G,height:H}}function C3Q(Q,J){if(Q.length===0)return{x:0,y:0};let G=-1/0,H=-1/0,K=1/0;for(let q of Q){let F=q.x+q.width,D=q.y+q.height;if(F>G)G=F;if(D>H)H=D;if(q.y<K)K=q.y}let z=G+32;if(z+J>3200)return{x:0,y:H+32};return{x:z,y:K}}var _N0=e({name:'"get_canvas"',arguments:{path:e("string>0").describe("Vault-relative path to the .canvas file.")}}).describe("Reads a canvas file and returns its nodes and edges as structured JSON."),hN0=500;async function fN0(Q){let{path:J}=Q.arguments,G=n6(Q.app.vault,J);if(!G.ok)return G.reason==="not_found"?OX(`Canvas file not found: ${J}`,"canvas_not_found",{path:J}):OX(`Path is a folder: ${J}`,"not_a_file",{path:J});let H=await Q.app.vault.read(G.file),K=HV(H);if(!K)return OX(`Canvas file is malformed: ${J}`,"malformed_canvas",{path:J});let z=K.nodes.map((q)=>{if(q.type==="text"&&typeof q.text==="string"&&q.text.length>hN0)return{...q,text:q.text.slice(0,hN0),textTruncated:!0};return q});return MJ({path:J,nodeCount:K.nodes.length,edgeCount:K.edges.length,nodes:z,edges:K.edges})}var mN0=e({name:'"add_canvas_node"',arguments:{path:"string>0",type:'"text" | "file" | "link"',"text?":"string","file?":"string>0","subpath?":"string","url?":"string>0","color?":"string","x?":"number","y?":"number","width?":"number","height?":"number"}}).describe("Adds a node (text, file, or link) to a canvas. Creates the canvas if it does not exist.");async function uN0(Q){let{path:J,type:G,color:H,x:K,y:z,width:q,height:F}=Q.arguments,D=n6(Q.app.vault,J);if(!D.ok&&D.reason==="not_a_file")return OX(`Path is a folder: ${J}`,"not_a_file",{path:J});let V,O=!1,P=null;if(D.ok){P=D.file;let g=await Q.app.vault.read(D.file);if(V=HV(g),!V)return OX(`Canvas file is malformed: ${J}`,"malformed_canvas",{path:J})}else V=bN0(),O=!0;if(G==="file"){let g=Q.arguments.file;if(!g)return OX('The "file" argument is required when type is "file".',"missing_argument",{path:J});if(!n6(Q.app.vault,g).ok)return OX(`Embed target not found: ${g}`,"embed_target_not_found",{path:g})}let N=xN0[G]??{width:400,height:200},I=q??N.width,R=F??N.height,w=gN0(V.nodes,{width:I,height:R,explicitX:K,explicitY:z}),E=V.nodes.map((g)=>g.id),T=xC(E),y={id:T,type:G,x:w.x,y:w.y,width:w.width,height:w.height,...H!==void 0?{color:H}:{}},x;if(G==="text")x={...y,text:Q.arguments.text??""};else if(G==="file")x={...y,file:Q.arguments.file,...Q.arguments.subpath!==void 0?{subpath:Q.arguments.subpath}:{}};else if(G==="link"){if(!Q.arguments.url)return OX('The "url" argument is required when type is "link".',"missing_argument",{path:J});x={...y,url:Q.arguments.url}}else return OX(`Unsupported node type: ${G}`,"invalid_node_type",{nodeType:G});V.nodes.push(x);let b=vC(V);if(O)await RG(Q.app,J),await Q.app.vault.create(J,b);else await Q.app.vault.modify(P,b);return MJ({id:T,x:w.x,y:w.y,width:w.width,height:w.height,created:O})}var pN0=e({name:'"connect_canvas_nodes"',arguments:{path:"string>0",fromNode:"string>0",toNode:"string>0","fromSide?":'"top" | "right" | "bottom" | "left"',"toSide?":'"top" | "right" | "bottom" | "left"',"label?":"string","color?":"string"}}).describe("Adds an edge between two existing nodes in a canvas. Both node ids must exist.");async function lN0(Q){let{path:J,fromNode:G,toNode:H,fromSide:K,toSide:z,label:q,color:F}=Q.arguments,D=n6(Q.app.vault,J);if(!D.ok)return D.reason==="not_found"?OX(`Canvas file not found: ${J}`,"canvas_not_found",{path:J}):OX(`Path is a folder: ${J}`,"not_a_file",{path:J});let V=await Q.app.vault.read(D.file),O=HV(V);if(!O)return OX(`Canvas file is malformed: ${J}`,"malformed_canvas",{path:J});let P=new Set(O.nodes.map((w)=>w.id));if(!P.has(G))return OX(`Node not found: ${G}`,"node_not_found",{nodeId:G});if(!P.has(H))return OX(`Node not found: ${H}`,"node_not_found",{nodeId:H});let N=[...O.nodes.map((w)=>w.id),...O.edges.map((w)=>w.id)],I=xC(N),R={id:I,fromNode:G,fromSide:K??"right",toNode:H,toSide:z??"left",...q!==void 0?{label:q}:{},...F!==void 0?{color:F}:{}};return O.edges.push(R),await Q.app.vault.modify(D.file,vC(O)),MJ({id:I})}async function dN0(Q,J){Q.register(sF0,async({arguments:G})=>rF0({arguments:G,pluginVersion:J.pluginVersion,getLocalTransport:()=>{let H=J.plugin.mcpTransportState?.server.port;if(H===void 0)return;return{protocol:"http",host:"127.0.0.1",port:H,path:"/mcp"}}})),Q.register(tF0,async({arguments:G})=>eF0({arguments:G,app:J.app})),Q.register(QD0,async({arguments:G})=>XD0({arguments:G,app:J.app})),Q.register(WD0,async({arguments:G})=>HD0({arguments:G,app:J.app})),Q.register(BD0,async({arguments:G})=>AD0({arguments:G,app:J.app})),Q.register(KD0,async({arguments:G})=>zD0({arguments:G,app:J.app})),Q.register(VD0,async({arguments:G})=>qD0({arguments:G,app:J.app})),Q.register(UD0,async({arguments:G})=>$D0({arguments:G,app:J.app})),Q.register(FD0,async({arguments:G})=>DD0({arguments:G,app:J.app})),Q.register(LD0,async({arguments:G})=>OD0({arguments:G,app:J.app})),Q.register(PD0,async({arguments:G})=>ND0({arguments:G,app:J.app})),Q.register(jD0,async({arguments:G})=>CD0({arguments:G,app:J.app})),Q.register(ID0,async({arguments:G})=>RD0({arguments:G,app:J.app})),Q.register(wD0,async({arguments:G})=>ED0({arguments:G,app:J.app})),Q.register(yD0,async({arguments:G})=>vD0({arguments:G,app:J.app})),Q.register(xD0,async({arguments:G})=>bD0({arguments:G,app:J.app})),Q.register(gD0,async({arguments:G})=>hD0({arguments:G,app:J.app})),Q.register(IP0,async({arguments:G})=>RP0({arguments:G,app:J.app})),Q.register(wP0,async({arguments:G})=>EP0({arguments:G,app:J.app})),Q.register(SP0,async({arguments:G})=>TP0({arguments:G,app:J.app})),Q.register(kP0,async({arguments:G})=>yP0({arguments:G,app:J.app})),Q.register(vP0,async({arguments:G})=>xP0({arguments:G,app:J.app})),Q.register(bP0,async({arguments:G})=>gP0({arguments:G,app:J.app})),Q.register(_P0,async({arguments:G})=>fP0({arguments:G,app:J.app})),Q.register(mP0,async({arguments:G})=>uP0({arguments:G,app:J.app})),Q.register(pP0,async({arguments:G})=>lP0({arguments:G,app:J.app})),Q.register(dP0,async({arguments:G})=>cP0({arguments:G,app:J.app})),Q.register(PN0,async({arguments:G})=>NN0({arguments:G,app:J.app})),Q.register(jN0,async({arguments:G})=>CN0({arguments:G,app:J.app})),Q.register(IN0,async({arguments:G})=>RN0({arguments:G,app:J.app})),Q.register(wN0,async({arguments:G})=>EN0({arguments:G,app:J.app})),Q.register(SN0,async({arguments:G})=>vN0({arguments:G,app:J.app})),Q.register(_N0,async({arguments:G})=>fN0({arguments:G,app:J.app})),Q.register(mN0,async({arguments:G})=>uN0({arguments:G,app:J.app})),Q.register(pN0,async({arguments:G})=>lN0({arguments:G,app:J.app})),Q.register(pD0,async({arguments:G})=>lD0({arguments:G,app:J.app})),Q.register(cD0,async({arguments:G})=>iD0({arguments:G,app:J.app})),Q.register(nD0,async({arguments:G})=>aD0({arguments:G,app:J.app,plugin:J.plugin})),Q.register(mD0,async({arguments:G})=>cj({arguments:G,app:J.app})),Q.register(sD0,async({arguments:G})=>rD0({arguments:G,app:J.app})),Q.register(eD0,async({arguments:G})=>QM0({arguments:G,app:J.app,plugin:J.plugin})),Q.register(UN0,async({arguments:G})=>$N0({arguments:G,app:J.app})),Q.register(FN0,async({arguments:G})=>DN0({arguments:G,app:J.app})),Q.register(LN0,async({arguments:G})=>ON0({arguments:G,app:J.app})),Q.register(PP0,async({arguments:G})=>NP0({arguments:G})),Q.register(jP0,async({arguments:G})=>CP0({arguments:G,app:J.app,plugin:J.plugin})),Q.setAnnotations(aF0)}var w3Q=require("obsidian");var z38=oQ('<label><input type="checkbox"/> <code class="svelte-mqyj3n"> </code></label>'),V38=oQ('<div class="grid svelte-mqyj3n"></div>'),q38=oQ(`<div class="tool-toggle-settings svelte-mqyj3n"><h3>Disabled MCP tools</h3> <p class="description svelte-mqyj3n">Tick a tool to hide it from your MCP client. Disabled tools are not
even registered with the MCP server, so the client never sees them.
Changes apply on the next plugin reload (or after the next API key
rotation, which restarts the transport automatically).</p> <div class="presets svelte-mqyj3n"><button type="button" aria-label="Disable destructive operations"> </button> <button type="button" aria-label="Enable all MCP tools">Enable all</button></div> <!> <p class="counter svelte-mqyj3n"> </p></div>`);async function r80(Q,J){let G;try{G=await J.loadData()}catch(F){return SQ.warn("tool-toggle: loadData failed; skipping filter",{error:F instanceof Error?F.message:String(F)}),{disabled:[],unknown:[]}}if(!G||typeof G!=="object")return{disabled:[],unknown:[]};let H=G.toolToggle;if(!H||typeof H!=="object")return{disabled:[],unknown:[]};let K=H.disabled;if(!Array.isArray(K)){if(K!==void 0)SQ.warn("tool-toggle: `disabled` is not an array; ignoring",{actual:typeof K});return{disabled:[],unknown:[]}}let z=[],q=[];for(let F of K){if(typeof F!=="string")continue;let D=F.trim();if(D.length===0)continue;if(Q.disableByName(D))z.push(D);else q.push(D)}if(z.length>0)SQ.info("tool-toggle: filtered tools",{disabled:z});if(q.length>0)SQ.warn("tool-toggle: unknown tool names in disabled list",{unknown:q});return{disabled:z,unknown:q}}var cN0=e({name:'"tool_catalog"',arguments:{}}).describe("Lists all available MCP tools with their status (active/inactive/promoted), call count, and description for inactive tools. Use this to discover which tools are currently loaded and which can be activated.");function E3Q(Q){let J=Q.indexOf(". ");return J===-1?Q:Q.slice(0,J+1)}async function iN0({registry:Q,plugin:J}){let G=Q.listAll(),K=(await J.loadData())?.toolLoading??{},z=K.counters??{},q=new Set(Array.isArray(K.promoted)?K.promoted:[]),F=G.map((D)=>{let V=z[D.name]??0;if(!D.enabled)return{name:D.name,status:"inactive",call_count:V,description:D.description?E3Q(D.description):void 0};return{name:D.name,status:q.has(D.name)?"promoted":"active",call_count:V}});return J8(JSON.stringify(F))}var oN0=e({name:'"activate_tool"',arguments:{name:e("string").describe("Exact name of the tool to activate."),"persist?":e("boolean").describe("If true, write the promotion to data.json so it survives plugin reloads. Defaults to false (in-memory until the plugin reloads, available immediately).")}}).describe("Promotes an inactive tool to active status. With persist=false (default) the tool is available immediately and stays active until the Obsidian plugin reloads. With persist=true the promotion is saved and survives plugin reloads. Run tool_catalog first to see available tool names.");async function nN0({arguments:Q,registry:J,plugin:G,server:H,onActivated:K,enableInRegistry:z,sendNotification:q}){let F=J.listAll(),D=F.find((V)=>V.name===Q.name);if(!D)return xQ(`Unknown tool: '${Q.name}'. Run tool_catalog to see available tools.`);if(D.enabled)return J8("Tool is already active in the current session.");if(K?.(Q.name),z?.(Q.name),Q.persist===!0){let V=F.map((P)=>P.name);await new bY().activateTool(Q.name,V,G)}try{if(q)await q({method:"notifications/tools/list_changed"});else await H.server.notification({method:"notifications/tools/list_changed"})}catch{}return{content:[{type:"text",text:Q.persist===!0?"Tool activated and saved. Available immediately; survives plugin reloads.":"Tool activated. Available immediately; stays active until the plugin reloads."}]}}var aN0=e({name:'"activate_tools"',arguments:{names:e("string[]").describe("Exact names of the tools to activate, in one batch."),"persist?":e("boolean").describe("If true, write the promotions to data.json so they survive plugin reloads. Defaults to false (in-memory until the plugin reloads, available immediately).")}}).describe("Promotes several inactive tools to active status in ONE call. Prefer this over multiple `activate_tool` calls when a task needs more than one inactive tool: it activates them all and refreshes the client's tool list only once, instead of once per tool. Run `tool_catalog` first to see available tool names. With persist=true the promotions survive plugin reloads.");async function sN0({arguments:Q,registry:J,plugin:G,server:H,onActivated:K,enableInRegistry:z,sendNotification:q}){let F=J.listAll(),D=new Map(F.map((I)=>[I.name,I])),V=[...new Set(Q.names)],O={},P=[];for(let I of V){let R=D.get(I);if(!R)O[I]="not_found";else if(R.enabled)O[I]="already_active";else O[I]="activated",P.push(I),K?.(I),z?.(I)}if(Q.persist===!0&&P.length>0){let I=F.map((R)=>R.name);await new bY().activateTools(P,I,G)}if(P.length>0)try{if(q)await q({method:"notifications/tools/list_changed"});else await H.server.notification({method:"notifications/tools/list_changed"})}catch{}let N={requested:V.length,activated:P.length,outcomes:O,...Q.persist===!0?{persisted:P.length>0}:{},note:P.length>0?"Activated tools are available immediately.":"No changes: all requested tools were already active or unknown."};return J8(JSON.stringify(N))}async function rN0(Q){let J=new BQ0,G=new AQ0;return await dN0(J,{app:Q.app,plugin:Q.plugin,pluginVersion:Q.pluginVersion}),J.register(cN0,()=>iN0({registry:J,plugin:Q.plugin})),J.register(oN0,async(H,{server:K,sendNotification:z})=>nN0({arguments:H.arguments,registry:J,plugin:Q.plugin,server:K,onActivated:(q)=>new t80.Notice(`MCP Connector: "${q}" promoted to active`),enableInRegistry:(q)=>J.enableByName(q),sendNotification:z})),J.register(aN0,async(H,{server:K,sendNotification:z})=>sN0({arguments:H.arguments,registry:J,plugin:Q.plugin,server:K,onActivated:(q)=>new t80.Notice(`MCP Connector: "${q}" promoted to active`),enableInRegistry:(q)=>J.enableByName(q),sendNotification:z})),await Gx(J,Q.plugin),await r80(J,Q.plugin),{toolRegistry:J,promptRegistry:G}}var S3Q=new Set(["activate_tool","activate_tools"]);function tN0(Q){return(Array.isArray(Q)?Q:[Q]).some((G)=>{if(typeof G!=="object"||G===null)return!1;let H=G;if(H.method!=="tools/call")return!1;let K=H.params;if(typeof K!=="object"||K===null)return!1;let z=K.name;return typeof z==="string"&&S3Q.has(z)})}async function eN0(Q,J){return new Promise((G,H)=>{let K=[],z=0,q=!1;Q.on("data",(F)=>{if(q)return;if(z+=F.length,z>J){q=!0,G(null);return}K.push(F)}),Q.on("end",()=>{if(!q)G(Buffer.concat(K).toString("utf8"))}),Q.on("error",(F)=>{if(!q)H(F)})})}async function Qj0(Q){let J=new bY,{toolRegistry:G,promptRegistry:H}=await rN0(Q);return{registry:G,promptRegistry:H,handleRequest:async(z,q)=>{let F=new s00({name:"mcp-connector",version:Q.pluginVersion},{capabilities:{tools:{listChanged:!0},prompts:{}}});F.server.setRequestHandler(Mz,G.list),F.server.setRequestHandler(p4,async(N,I)=>{let R=await G.dispatch(N.params,{server:F,sendNotification:I.sendNotification});if(!U5.includes(N.params.name))J.recordCall(N.params.name,Q.plugin).catch(()=>{});return R}),F.server.setRequestHandler(Fz,H.list),F.server.setRequestHandler(Dz,(N)=>H.dispatch(N.params));let D=await eN0(z,aP),V,O=!1;if(D!==null)try{V=JSON.parse(D),O=tN0(V)}catch{V=void 0}let P=new WQ0({sessionIdGenerator:void 0,enableJsonResponse:!O});try{await F.connect(P),await P.handleRequest(z,q,V)}finally{try{await P.close()}catch(N){SQ.error("[mcp] transport.close failed",{error:N})}try{await F.close()}catch(N){SQ.error("[mcp] server.close failed",{error:N})}}}}}async function Xj0(Q){}async function AF(Q){try{let J;await new n9(Q).updateSlice("mcpTransport",(K)=>{let z=K??{},q=z.bearerToken;if(!q||Buffer.byteLength(q,"utf8")<32)return J=rP(),{...z,bearerToken:J};return J=q,K});let G=await Qj0({app:Q.app,plugin:Q,pluginVersion:Q.manifest.version}),H=await pK0({bearerToken:J,requestHandler:G.handleRequest});return SQ.info("MCP Connector HTTP server listening",{port:H.port,pluginVersion:Q.manifest.version}),{success:!0,state:{server:H,mcp:G,bearerToken:J}}}catch(J){let G=J instanceof Error?J.message:String(J);return SQ.error("MCP Connector failed to start HTTP server",{error:G}),{success:!1,error:G}}}async function KF(Q){await lK0(Q.server),await Xj0(Q.mcp)}var BB8=e("string>=32"),AB8=e("1024<=number.integer<=65535");var AV=require("obsidian");var zF=K7(require("fs/promises")),e80=K7(require("os")),Q60=K7(require("path"));var gC="mcp-tools-istefox",bC="obsidian-mcp-tools",T3Q={macos:"~/Library/Application Support/Claude/claude_desktop_config.json",windows:"%APPDATA%\\Claude\\claude_desktop_config.json",linux:"~/.config/Claude/claude_desktop_config.json"},k3Q=e({token:"string > 0",port:"number.integer > 0","pluginId?":"string","configPath?":"string","removeLegacyKey?":"boolean","backupBeforeWrite?":"boolean"}).describe("Inputs for updateClaudeDesktopConfig");async function X60(Q){let J=Q.pluginId??gC,G=Q.configPath??Jj0();if(!G)throw Error("Cannot resolve Claude Desktop config path on this platform.");let H=Q.removeLegacyKey??!0,K=Q.backupBeforeWrite??!0;await zF.default.mkdir(Q60.default.dirname(G),{recursive:!0});let z=null;try{z=await zF.default.readFile(G,"utf8")}catch(F){if(F.code!=="ENOENT")throw F}let q={mcpServers:{}};if(z!==null){try{let F=JSON.parse(z);if(F&&typeof F==="object"){let D=F,V=D.mcpServers;q={...D,mcpServers:V&&typeof V==="object"?{...V}:{}}}}catch(F){throw Error(`Refusing to overwrite malformed JSON at ${G}: ${F instanceof Error?F.message:String(F)}`)}if(K)try{await zF.default.writeFile(`${G}.backup`,z,"utf8")}catch(F){SQ.warn("Claude Desktop config backup failed",{configPath:`${G}.backup`,error:F instanceof Error?F.message:String(F)})}}if(H&&J!==bC)delete q.mcpServers[bC];q.mcpServers[J]=y3Q(Q.port,Q.token),await zF.default.writeFile(G,JSON.stringify(q,null,2),"utf8"),SQ.info("Claude Desktop config updated",{configPath:G,pluginId:J,legacyKeyRemoved:H&&J!==bC})}function Jj0(){let Q=v3Q();if(!Q)return;return x3Q(T3Q[Q])}function y3Q(Q,J){return{command:"npx",args:["-y","mcp-remote",`http://127.0.0.1:${Q}/mcp`,"--header",`Authorization: Bearer ${J}`]}}function v3Q(){switch(e80.default.platform()){case"darwin":return"macos";case"win32":return"windows";case"linux":return"linux";default:return null}}function x3Q(Q){let J=Q;if(J.startsWith("~"))J=Q60.default.join(e80.default.homedir(),J.slice(1));return J=J.replace(/%([^%]+)%/g,(G,H)=>process.env[H]||""),J}var b3Q=e({url:e(/^https?:\/\//).describe("MCP endpoint URL, e.g. http://127.0.0.1:27200/mcp"),token:"string > 0","pluginId?":"string"});function J60(Q){return{command:"npx",args:["-y","mcp-remote",Q.url,"--header",`Authorization: Bearer ${Q.token}`]}}function Y60(Q){return{type:"http",url:Q.url,headers:{Authorization:`Bearer ${Q.token}`}}}function G60(Q){return{type:"streamable-http",url:Q.url,headers:{Authorization:`Bearer ${Q.token}`}}}function VF(Q,J=gC){return{mcpServers:{[J]:Q}}}var Yj0="mcpClientConfig",Gj0="autoWriteClaudeDesktopConfig";async function qF(Q){try{let J=await new n9(Q).readSlice(Yj0);if(!J||typeof J!=="object")return!1;return J[Gj0]===!0}catch(J){return SQ.warn("autoWrite: getAutoWriteEnabled failed",{error:J instanceof Error?J.message:String(J)}),!1}}async function W60(Q,J){await new n9(Q).updateSlice(Yj0,(G)=>{return{...G??{},[Gj0]:J}})}async function UF(Q){if(!await qF(Q))return{applied:!1,reason:"disabled"};let G=Q.mcpTransportState;if(!G)return{applied:!1,reason:"transport-offline"};try{return await X60({port:G.server.port,token:G.bearerToken}),{applied:!0}}catch(H){return{applied:!1,reason:"error",error:H instanceof Error?H.message:String(H)}}}var Hj0=require("child_process"),Bj0=require("util"),hC=K7(require("os")),Aj0=Bj0.promisify(Hj0.execFile),k5=null,EW=null;function g3Q(){let Q=hC.default.platform();if(Q==="darwin")return["/opt/homebrew/bin/node","/usr/local/bin/node","/opt/homebrew/opt/node/bin/node"];if(Q==="linux")return["/usr/bin/node","/usr/local/bin/node",`${hC.default.homedir()}/.local/bin/node`];if(Q==="win32")return["C:\\Program Files\\nodejs\\node.exe","C:\\Program Files (x86)\\nodejs\\node.exe"];return[]}async function o3(Q){if(!Q?.forceRefresh&&k5!==null)return k5;let J=Q?.runner??Aj0,G=Q?.candidatePaths??g3Q(),H=Q?.pathExists,K=null;try{let{stdout:z}=await J("node",["--version"]),q=Wj0(z);if(q)return k5={found:!0,version:q,raw:z},EW="node",k5;K=`Unrecognized output: ${z.slice(0,80)}`}catch(z){K=z instanceof Error?z.message:String(z)}for(let z of G){if(H&&!H(z))continue;try{let{stdout:q}=await J(z,["--version"]),F=Wj0(q);if(F)return k5={found:!0,version:F,raw:q},EW=z,k5}catch{}}return k5={found:!1,error:f3Q(K??"node --version failed")},EW=null,k5}function H60(){if(EW===null)return null;if(EW==="node")return"";return/^(.*)[\\/](?:node(?:\.exe)?)$/i.exec(EW)?.[1]??null}function _C(){if(EW===null)return null;if(EW==="node")return hC.default.platform()==="win32"?"npx.cmd":"npx";return EW.replace(/node(\.exe)?$/i,(Q,J)=>J?"npx.cmd":"npx")}function Kj0(){k5=null,EW=null,y5=null,$F=null}var y5=null,$F=null;function h3Q(){return["/opt/homebrew/bin/brew","/usr/local/bin/brew"]}async function fC(Q){if(!Q?.forceRefresh&&y5!==null)return y5;let J=Q?.runner??Aj0,G=Q?.candidatePaths??h3Q(),H=Q?.pathExists,K=(z)=>{let q=/Homebrew\s+(\d+\.\d+\.\d+)/.exec(z);return q?{found:!0,version:q[1]}:{found:!0,version:"unknown"}};try{let{stdout:z}=await J("brew",["--version"]);return y5=K(z),$F="brew",y5}catch{}for(let z of G){if(H&&!H(z))continue;try{let{stdout:q}=await J(z,["--version"]);return y5=K(q),$F=z,y5}catch{}}return y5={found:!1},$F=null,y5}var _3Q=({onLine:Q})=>new Promise((J,G)=>{let H=$F??"brew";import("child_process").then(({spawn:K})=>{let z=K(H,["install","node"],{stdio:["ignore","pipe","pipe"]}),q="",F="",D=(V,O)=>{if(O==="out")q+=V;else F+=V;V.split(/\r?\n/).filter((P)=>P.trim().length>0).forEach((P)=>Q(P))};z.stdout?.on("data",(V)=>D(V.toString(),"out")),z.stderr?.on("data",(V)=>D(V.toString(),"err")),z.on("error",(V)=>G(V)),z.on("close",(V)=>{if(V===0)J({stdout:q,stderr:F});else G(Error(`brew install node exited with code ${V}`))})}).catch(G)});async function B60(Q){let J=Q?.runner??_3Q,G=Q?.onLine??(()=>{});try{await J({onLine:G}),Kj0();let H=await o3();if(H.found)return{ok:!0,version:H.version};return{ok:!1,error:"Homebrew install completed but `node --version` still failed. You may need to restart Obsidian to pick up PATH changes."}}catch(H){return{ok:!1,error:H instanceof Error?H.message:String(H)}}}function Wj0(Q){return/v(\d+\.\d+\.\d+(?:-[A-Za-z0-9.+]+)?)/.exec(Q.trim())?.[1]??null}function f3Q(Q){if(/ENOENT|not found|not recognized/i.test(Q))return"Node.js not found on PATH. Install from nodejs.org.";return`Failed to run "node --version": ${Q}`}var Uj0=require("child_process"),$j0=require("util");var Zj0="mcpClientConfig",Fj0="mcpRemotePreWarm",m3Q=120000,u3Q=(Q,J,G)=>{return $j0.promisify(Uj0.execFile)(Q,J,G)};async function A60(Q){let J=await new n9(Q).readSlice(Zj0);if(!J||typeof J!=="object")return null;let G=J[Fj0];if(!G||typeof G!=="object")return null;let H=G;if(typeof H.lastWarmedAt!=="string")return null;return{lastWarmedAt:H.lastWarmedAt,...typeof H.version==="string"?{version:H.version}:{}}}async function zj0(Q,J){await new n9(Q).updateSlice(Zj0,(G)=>{return{...G??{},[Fj0]:J}})}async function K60(Q,J){let G=J?.runner??u3Q,H=J?.npxPath??_C();if(!H)await o3(),H=_C();if(!H)return{ok:!1,error:"npx not available — install Node.js from nodejs.org first."};try{let K=["-y","mcp-remote@latest","--help"],z=H60(),q={...process.env,...z?{PATH:`${z}:${process.env.PATH??""}`}:{}},{stdout:F,stderr:D}=await G(H,K,{timeout:m3Q,env:q});if(D)if(qj0(D))SQ.debug("preWarm: mcp-remote emitted its expected no-arguments probe error on stderr (benign — the package is cached)");else SQ.debug("preWarm: stderr from mcp-remote",{stderr:D.slice(0,200)});let V=Vj0(F)??Vj0(D),O={lastWarmedAt:new Date().toISOString(),...V?{version:V}:{}};return await zj0(Q,O),{ok:!0,entry:O}}catch(K){let z=K instanceof Error?K.message:String(K);if(qj0(z)){SQ.debug("preWarm: npx exited non-zero but mcp-remote was loaded — treating as success (mcp-remote has no --help flag; its probe rejection is expected and the package is now cached)");let q={lastWarmedAt:new Date().toISOString()};return await zj0(Q,q),{ok:!0,entry:q}}return{ok:!1,error:p3Q(z)}}}function Vj0(Q){return/mcp-remote[\s/@v]+(\d+\.\d+\.\d+(?:-[A-Za-z0-9.+]+)?)/i.exec(Q)?.[1]}function qj0(Q){return/mcp-remote/i.test(Q)||/ERR_INVALID_URL/i.test(Q)||/Invalid URL/i.test(Q)}function p3Q(Q){if(/ENOENT|not found|not recognized/i.test(Q))return"npx not available — install Node.js from nodejs.org first.";if(/ETIMEDOUT|timed out/i.test(Q))return"Timed out reaching the npm registry. Check your network and retry.";if(/ENETUNREACH|getaddrinfo|EAI_AGAIN/i.test(Q))return"Could not reach the npm registry. Check your network and retry.";return`Pre-warm failed: ${Q}`}var jj0=require("module"),l3Q=jj0.createRequire("/"),BV,d3Q,c3Q;try{BV=l3Q("worker_threads"),d3Q=BV.Worker,c3Q=BV.isMarkedAsUntransferable}catch(Q){}var oX=Uint8Array,UY=Uint16Array,Z60=Int32Array,F60=new oX([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,0,0,0]),D60=new oX([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,0,0]),Dj0=new oX([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Cj0=function(Q,J){var G=new UY(31);for(var H=0;H<31;++H)G[H]=J+=1<<Q[H-1];var K=new Z60(G[30]);for(var H=1;H<30;++H)for(var z=G[H];z<G[H+1];++z)K[z]=z-G[H]<<5|H;return{b:G,r:K}},BV=Cj0(F60,2),i3Q=BV.b,V60=BV.r;i3Q[28]=258,V60[258]=28;var Ij0=Cj0(D60,0),IB8=Ij0.b,Mj0=Ij0.r,q60=new UY(32768);for(z6=0;z6<32768;++z6)SW=(z6&43690)>>1|(z6&21845)<<1,SW=(SW&52428)>>2|(SW&13107)<<2,SW=(SW&61680)>>4|(SW&3855)<<4,q60[z6]=((SW&65280)>>8|(SW&255)<<8)>>1;var SW,z6,DF=function(Q,J,G){var H=Q.length,K=0,z=new UY(J);for(;K<H;++K)if(Q[K])++z[Q[K]-1];var q=new UY(J);for(K=1;K<J;++K)q[K]=q[K-1]+z[K-1]<<1;var F;if(G){F=new UY(1<<J);var D=15-J;for(K=0;K<H;++K)if(Q[K]){var V=K<<4|Q[K],O=J-Q[K],P=q[Q[K]-1]++<<O;for(var N=P|(1<<O)-1;P<=N;++P)F[q60[P]>>D]=V}}else{F=new UY(H);for(K=0;K<H;++K)if(Q[K])F[K]=q60[q[Q[K]-1]++]>>15-Q[K]}return F},n3=new oX(288);for(z6=0;z6<144;++z6)n3[z6]=8;var z6;for(z6=144;z6<256;++z6)n3[z6]=9;var z6;for(z6=256;z6<280;++z6)n3[z6]=7;var z6;for(z6=280;z6<288;++z6)n3[z6]=8;var z6,mC=new oX(32);for(z6=0;z6<32;++z6)mC[z6]=5;var z6,o3Q=DF(n3,9,0);var n3Q=DF(mC,5,0);var Rj0=function(Q){return(Q+7)/8|0},wj0=function(Q,J,G){if(J==null||J<0)J=0;if(G==null||G>Q.length)G=Q.length;return new oX(Q.subarray(J,G))};var a3Q=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],uC=function(Q,J,G){var H=Error(J||a3Q[Q]);if(H.code=Q,Error.captureStackTrace)Error.captureStackTrace(H,uC);if(!G)throw H;return H};var v5=function(Q,J,G){G<<=J&7;var H=J/8|0;Q[H]|=G,Q[H+1]|=G>>8},ZF=function(Q,J,G){G<<=J&7;var H=J/8|0;Q[H]|=G,Q[H+1]|=G>>8,Q[H+2]|=G>>16},z60=function(Q,J){var G=[];for(var H=0;H<Q.length;++H)if(Q[H])G.push({s:H,f:Q[H]});var K=G.length,z=G.slice();if(!K)return{t:Sj0,l:0};if(K==1){var q=new oX(G[0].s+1);return q[G[0].s]=1,{t:q,l:1}}G.sort(function(g,l){return g.f-l.f}),G.push({s:-1,f:25001});var F=G[0],D=G[1],V=0,O=1,P=2;G[0]={s:-1,f:F.f+D.f,l:F,r:D};while(O!=K-1)F=G[G[V].f<G[P].f?V++:P++],D=G[V!=O&&G[V].f<G[P].f?V++:P++],G[O++]={s:-1,f:F.f+D.f,l:F,r:D};var N=z[0].s;for(var H=1;H<K;++H)if(z[H].s>N)N=z[H].s;var I=new UY(N+1),R=U60(G[O-1],I,0);if(R>J){var H=0,w=0,E=R-J,T=1<<E;z.sort(function(l,_){return I[_.s]-I[l.s]||l.f-_.f});for(;H<K;++H){var y=z[H].s;if(I[y]>J)w+=T-(1<<R-I[y]),I[y]=J;else break}w>>=E;while(w>0){var x=z[H].s;if(I[x]<J)w-=1<<J-I[x]++-1;else++H}for(;H>=0&&w;--H){var b=z[H].s;if(I[b]==J)--I[b],++w}R=J}return{t:new oX(I),l:R}},U60=function(Q,J,G){return Q.s==-1?Math.max(U60(Q.l,J,G+1),U60(Q.r,J,G+1)):J[Q.s]=G},Lj0=function(Q){var J=Q.length;while(J&&!Q[--J]);var G=new UY(++J),H=0,K=Q[0],z=1,q=function(D){G[H++]=D};for(var F=1;F<=J;++F)if(Q[F]==K&&F!=J)++z;else{if(!K&&z>2){for(;z>138;z-=138)q(32754);if(z>2)q(z>10?z-11<<5|28690:z-3<<5|12305),z=0}else if(z>3){q(K),--z;for(;z>6;z-=6)q(8304);if(z>2)q(z-3<<5|8208),z=0}while(z--)q(K);z=1,K=Q[F]}return{c:G.subarray(0,H),n:J}},FF=function(Q,J){var G=0;for(var H=0;H<J.length;++H)G+=Q[H]*J[H];return G},Ej0=function(Q,J,G){var H=G.length,K=Rj0(J+2);Q[K]=H&255,Q[K+1]=H>>8,Q[K+2]=Q[K]^255,Q[K+3]=Q[K+1]^255;for(var z=0;z<H;++z)Q[K+z+4]=G[z];return(K+4+H)*8},Oj0=function(Q,J,G,H,K,z,q,F,D,V,O){v5(J,O++,G),++K[256];var P=z60(K,15),N=P.t,I=P.l,R=z60(z,15),w=R.t,E=R.l,T=Lj0(N),y=T.c,x=T.n,b=Lj0(w),g=b.c,l=b.n,_=new UY(19);for(var a=0;a<y.length;++a)++_[y[a]&31];for(var a=0;a<g.length;++a)++_[g[a]&31];var r=z60(_,7),f0=r.t,t=r.l,p0=19;for(;p0>4&&!f0[Dj0[p0-1]];--p0);var u0=V+5<<3,d=FF(K,n3)+FF(z,mC)+q,n=FF(K,N)+FF(z,w)+q+14+3*p0+FF(_,f0)+2*_[16]+3*_[17]+7*_[18];if(D>=0&&u0<=d&&u0<=n)return Ej0(J,O,Q.subarray(D,D+V));var c0,WQ,R0,l0;if(v5(J,O,1+(n<d)),O+=2,n<d){c0=DF(N,I,0),WQ=N,R0=DF(w,E,0),l0=w;var d0=DF(f0,t,0);v5(J,O,x-257),v5(J,O+5,l-1),v5(J,O+10,p0-4),O+=14;for(var a=0;a<p0;++a)v5(J,O+3*a,f0[Dj0[a]]);O+=3*p0;var m0=[y,g];for(var ZQ=0;ZQ<2;++ZQ){var LQ=m0[ZQ];for(var a=0;a<LQ.length;++a){var h0=LQ[a]&31;if(v5(J,O,d0[h0]),O+=f0[h0],h0>15)v5(J,O,LQ[a]>>5&127),O+=LQ[a]>>12}}}else c0=o3Q,WQ=n3,R0=n3Q,l0=mC;for(var a=0;a<F;++a){var pQ=H[a];if(pQ>255){var h0=pQ>>18&31;if(ZF(J,O,c0[h0+257]),O+=WQ[h0+257],h0>7)v5(J,O,pQ>>23&31),O+=F60[h0];var iQ=pQ&31;if(ZF(J,O,R0[iQ]),O+=l0[iQ],iQ>3)ZF(J,O,pQ>>5&8191),O+=D60[iQ]}else ZF(J,O,c0[pQ]),O+=WQ[pQ]}return ZF(J,O,c0[256]),O+WQ[256]},s3Q=new Z60([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Sj0=new oX(0),r3Q=function(Q,J,G,H,K,z){var q=z.z||Q.length,F=new oX(H+q+5*(1+Math.ceil(q/7000))+K),D=F.subarray(H,F.length-K),V=z.l,O=(z.r||0)&7;if(J){if(O)D[0]=z.r>>3;var P=s3Q[J-1],N=P>>13,I=P&8191,R=(1<<G)-1,w=z.p||new UY(32768),E=z.h||new UY(R+1),T=Math.ceil(G/3),y=2*T,x=function(K8){return(Q[K8]^Q[K8+1]<<T^Q[K8+2]<<y)&R},b=new Z60(25000),g=new UY(288),l=new UY(32),_=0,a=0,r=z.i||0,f0=0,t=z.w||0,p0=0;for(;r+2<q;++r){var u0=x(r),d=r&32767,n=E[u0];if(w[d]=n,E[u0]=d,t<=r){var c0=q-r;if((_>7000||f0>24576)&&(c0>423||!V)){O=Oj0(Q,D,0,b,g,l,a,f0,p0,r-p0,O),f0=_=a=0,p0=r;for(var WQ=0;WQ<286;++WQ)g[WQ]=0;for(var WQ=0;WQ<30;++WQ)l[WQ]=0}var R0=2,l0=0,d0=I,m0=d-n&32767;if(c0>2&&u0==x(r-m0)){var ZQ=Math.min(N,c0)-1,LQ=Math.min(32767,r),h0=Math.min(258,c0);while(m0<=LQ&&--d0&&d!=n){if(Q[r+R0]==Q[r+R0-m0]){var pQ=0;for(;pQ<h0&&Q[r+pQ]==Q[r+pQ-m0];++pQ);if(pQ>R0){if(R0=pQ,l0=m0,pQ>ZQ)break;var iQ=Math.min(m0,pQ-2),mQ=0;for(var WQ=0;WQ<iQ;++WQ){var AQ=r-m0+WQ&32767,MQ=w[AQ],DQ=AQ-MQ&32767;if(DQ>mQ)mQ=DQ,n=AQ}}}d=n,n=w[d],m0+=d-n&32767}}if(l0){b[f0++]=268435456|V60[R0]<<18|Mj0[l0];var bQ=V60[R0]&31,j8=Mj0[l0]&31;a+=F60[bQ]+D60[j8],++g[257+bQ],++l[j8],t=r+R0,++_}else b[f0++]=Q[r],++g[Q[r]]}}for(r=Math.max(r,t);r<q;++r)b[f0++]=Q[r],++g[Q[r]];if(O=Oj0(Q,D,V,b,g,l,a,f0,p0,r-p0,O),!V)z.r=O&7|D[O/8|0]<<3,O-=7,z.h=E,z.p=w,z.i=r,z.w=t}else{for(var r=z.w||0;r<q+V;r+=65535){var tQ=r+65535;if(tQ>=q)D[O/8|0]=V,tQ=q;O=Ej0(D,O+1,Q.subarray(r,tQ))}z.i=q}return wj0(F,0,H+Rj0(O)+K)},t3Q=function(){var Q=new Int32Array(256);for(var J=0;J<256;++J){var G=J,H=9;while(--H)G=(G&1&&-306674912)^G>>>1;Q[J]=G}return Q}(),e3Q=function(){var Q=-1;return{p:function(J){var G=Q;for(var H=0;H<J.length;++H)G=t3Q[G&255^J[H]]^G>>>8;Q=G},d:function(){return~Q}}};var QBQ=function(Q,J,G,H,K){if(!K){if(K={l:1},J.dictionary){var z=J.dictionary.subarray(-32768),q=new oX(z.length+Q.length);q.set(z),q.set(Q,z.length),Q=q,K.w=z.length}}return r3Q(Q,J.level==null?6:J.level,J.mem==null?K.l?Math.ceil(Math.max(8,Math.min(13,Math.log(Q.length)))*1.5):20:12+J.mem,G,H,K)},Tj0=function(Q,J){var G={};for(var H in Q)G[H]=Q[H];for(var H in J)G[H]=J[H];return G};var CX=function(Q,J,G){for(;G;++J)Q[J]=G,G>>>=8};function XBQ(Q,J){return QBQ(Q,J||{},0,0)}var kj0=function(Q,J,G,H){for(var K in Q){var z=Q[K],q=J+K,F=H;if(Array.isArray(z))F=Tj0(H,z[1]),z=z[0];if(ArrayBuffer.isView(z))G[q]=[z,F];else G[q+="/"]=[new oX(0),F],kj0(z,q,G,H)}},Pj0=typeof TextEncoder<"u"&&new TextEncoder,JBQ=typeof TextDecoder<"u"&&new TextDecoder,YBQ=0;try{JBQ.decode(Sj0,{stream:!0}),YBQ=1}catch(Q){}function MF(Q,J){if(J){var G=new oX(Q.length);for(var H=0;H<Q.length;++H)G[H]=Q.charCodeAt(H);return G}if(Pj0)return Pj0.encode(Q);var K=Q.length,z=new oX(Q.length+(Q.length>>1)),q=0,F=function(O){z[q++]=O};for(var H=0;H<K;++H){if(q+5>z.length){var D=new oX(q+8+(K-H<<1));D.set(z),z=D}var V=Q.charCodeAt(H);if(V<128||J)F(V);else if(V<2048)F(192|V>>6),F(128|V&63);else if(V>55295&&V<57344)V=65536+(V&1047552)|Q.charCodeAt(++H)&1023,F(240|V>>18),F(128|V>>12&63),F(128|V>>6&63),F(128|V&63);else F(224|V>>12),F(128|V>>6&63),F(128|V&63)}return wj0(z,0,q)}var $60=function(Q){var J=0;if(Q)for(var G in Q){var H=Q[G].length;if(H>65535)uC(9);J+=H+4}return J},Nj0=function(Q,J,G,H,K,z,q,F){var D=H.length,V=G.extra,O=F&&F.length,P=$60(V);if(CX(Q,J,q!=null?33639248:67324752),J+=4,q!=null)Q[J++]=20,Q[J++]=G.os;Q[J]=20,J+=2,Q[J++]=G.flag<<1|(z<0&&8),Q[J++]=K&&8,Q[J++]=G.compression&255,Q[J++]=G.compression>>8;var N=new Date(G.mtime==null?Date.now():G.mtime),I=N.getFullYear()-1980;if(I<0||I>119)uC(10);if(CX(Q,J,I<<25|N.getMonth()+1<<21|N.getDate()<<16|N.getHours()<<11|N.getMinutes()<<5|N.getSeconds()>>1),J+=4,z!=-1)CX(Q,J,G.crc),CX(Q,J+4,z<0?-z-2:z),CX(Q,J+8,G.size);if(CX(Q,J+12,D),CX(Q,J+14,P),J+=16,q!=null)CX(Q,J,O),CX(Q,J+6,G.attrs),CX(Q,J+10,q),J+=14;if(Q.set(H,J),J+=D,P)for(var R in V){var w=V[R],E=w.length;CX(Q,J,+R),CX(Q,J+2,E),Q.set(w,J+4),J+=4+E}if(O)Q.set(F,J),J+=O;return J},GBQ=function(Q,J,G,H,K){CX(Q,J,101010256),CX(Q,J+8,G),CX(Q,J+10,G),CX(Q,J+12,H),CX(Q,J+16,K)};function yj0(Q,J){if(!J)J={};var G={},H=[];kj0(Q,"",G,J);var K=0,z=0;for(var q in G){var F=G[q],D=F[0],V=F[1],O=V.level==0?0:8,P=MF(q),N=P.length,I=V.comment,R=I&&MF(I),w=R&&R.length,E=$60(V.extra);if(N>65535)uC(11);var T=O?XBQ(D,V):D,y=T.length,x=e3Q();x.p(D),H.push(Tj0(V,{size:D.length,crc:x.d(),c:T,f:P,m:R,u:N!=q.length||R&&I.length!=w,o:K,compression:O})),K+=30+N+E+y,z+=76+2*(N+E)+(w||0)+y}var b=new oX(z+22),g=K,l=z-K;for(var _=0;_<H.length;++_){var P=H[_];Nj0(b,P.o,P,P.f,P.u,P.c.length);var a=30+P.f.length+$60(P.extra);b.set(P.c,P.o+a),Nj0(b,K,P,P.f,P.u,P.c.length,P.o,P.m),K+=16+a+(P.m?P.m.length:0)}return GBQ(b,K,H.length,l,g),b}var vj0="iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAYAAAD0eNT6AAARJ0lEQVR42u3b4anCQBCFUSuxROu0q4j/RRMQkp3vDJwCXnbv7IWHt5sxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGPMH+b+eG4AfOaVMB51AJQF47EHQCkwHnwAFALj0QdAGTAefQCUAePhB0ARMB5+ABQBDz8AKAIefgBQBDz8ACgCxsMPgCJgPP4AKAHGww+AImA8/gAoAcbjD4ASYDz8ACgCxuMPgBJgPP4AKAHG4w+AEuDxBwAlwOMPAEqAxx8AlACPPwAoAR5/AFACPP4AoAR4/AFACfD4A4ASoAAAgALg8QcAJcDjDwBKgMcfAJQABQAAFACPPwCUS4DDB0AJUAAAQAHw+AOAEqAAAIAC4PEHACVAAQAABcDjDwBKgAIAAAqAxx8AlAAFAAAUAI8/ACgBCgAAKAAefwBQAhQAAFAAFAAAUAA8/gBQLQEOEAAUAABgegFweAAQLAEODgAUAABAAQAAxhUAhwYAwRLgwABAAQAAFAAAQAEAANYvAA4LAIIlwEEBgAIAACgAAIACAAAoAACAAgAAKAAAoAAoAACgACgAAKAAKAAAoAB4/Od5j+8A2ENKgAIQDJ7wAXaQAqAARMMngID9owAoANEACiFg9ygACkA0hIII2DsKgAIQDaIwAnaOAqAARMMokIB9owAoANFACiVg1ygACkA0lIIJ2DMKgAIQDaZwAnaMAqAARMMpoID9ogAoANGACilgtygACkA0pIIK2CsKgAIQDaqwAnaKAqAARMMqsIB9ogAoANHACi1glygACkA0tIIL2CMKgAIQDa7wgh1ihygACkA0vAIM9of9oQAoANEACzHYHXaHAqAALBQ8QQbsIAVAARA+AQTsHwVAARBAIQTsHgVAARBCQQR7x95RABQAQRRIsG/sGwVAARBIoQS7xq5RABQAoRRMsGfsGQVAARBM4QQ7xo5RABSAbjgFFOwX+0UBUACiARVSsFvsFgVAAYiGVFDBXrFXFAAFIBpUYQU7xU5RABSAaFgFFuwT+0QBUACigRVasEvsEgVAAYiGVnDBHrFHFACHFA2u8IIdYocoAETDK8Bgf9gfCgDRAAsx2B12hwJANMSCDPaGvaEAEA2yMIOdYWcoAETDLNBgX9gXCgDRQAs12BV2hQIg1OFx/mBP2BMKgGALN2BH2BEKgHALOGDsBwVAwIUc7Aa7AQVAyAUd7AV7AQVA0AUe7AP7QAFQAARe6MEusAsUAAVA6AUf7AF7QAFQAARf+MEOsAMUAAVA+C0AkH/5VwAUAAvAEgDZl30FQAGwBCwCkHu5VwAUAIvAMgCZl3kFQAGwDCwEkHd5VwAUAAvBUgBZl3UFQAGwFCwGkHM5VwCwGCwHZNzIuAKA5WBBIN9GvhUAC+K6wbMkYPbjv8IeQgGwJE4KnhIAcx9/BUABUAAsiq/BUwJg5uOvACgACoBl8TN4SgDMe/wVAAVAAbAwdgdPCYBZuZBlBUABsDR2B08JgDl5kGMFQAGwOA4FTwmAGTmQYQVAAbA8DgdPCUB+NzmWXwVAAegVACUA2ZVh2VUAFIBoAVACkFv5lVsFQAGIFgA/E0ReZVdeFQAFIBw8JQBZlVtZVQAUgGjwlADkVGblVAFQAKLBUwKQUXmVUQXAIUWDpwQgn7IqnwoA0eApAcimnMqmAkA0eEoAcimjcqkAEA2eEoBMyqdMKgBEg6cEII+yKY8KANHgKQHIolzKogJANHhKAHIok3KoAFg80eApAcigPMqgAmD5RINn8SJ/sih/CoAFFA2eBYzsyaHsKQCWUDR4FjFyJ4NypwBYRNHgWci4a/IncwqAZRQNnsWMOyZ78qYAWEjh4FnQuFe+jawpAJZSNHiWNe6T7yNnCoDFFA2epY175Bu5wwqA5RQNnuWN+2MPoQBYUNHgWeK4N/YQCoAlFQ2eZY77Yg+hAFhU0eCtMu61OyJb8qQAKACCZ8HjbsiVLCkACJ5Fjzvh+8mRAoDgWfi4C76hDCkAlpfgWfy4A76j/CgAFpjgeQBw9vaQu64AWGKC5yHAmdtDKAAWmeB5EGTGWdtDCoACYJkJnodBXpyxPaQAKACClw2eB0JWnK09pAAoAIIXDZ6HQk6cqT2kACgAghcNngdDRpylPaQAKACCFw2eh0M+nKE9pAAoAIIXDZ4HxNk5O3tIAVAABC8aPA+JM3Nm9pACoAAIXjR4HhRn5azsIQVAARC8aPA8LM7IGdlDCoACIHjh4HlgnItzsYcUAAVA8KLB89g4D+dhDykACoDgRYPn0XEOzsEeUgAUAMHz+DgH318OfH8FQAEQvFLwPEK+uww4AwVAARA8/4N2Hr63++8cFAAFQPCchXPxjd19Z6EAKACC5zycjW/r3jsPBUABEDxn4nx8U3femSgACoDgORdn5Fu6785FAVAABM/ZOCff0F13NgoAgud8Ymfl27nnzkcBcEiC54xi5+WbuePOSAFQAATPOcXOzLdyv52TAqAACJ6zip2bb+RuOysFQAEQPOcVOzvfxr12XgqAAiB4zix2fr6JO+3MFAAFQPCcW+wMfQv32bkpAAqA4Dm72Dn6Bu6ys1MAFADBc36xs/T4u8fOTwFQAATPGcYeQo+/O+wMFQAFQPCIPYgef/fXOSoACoDgEXsYPf7urrNUABQAwWPhR9LfhT2kACgAgid4SoDH3311rgqAAiB4gqcEePzdVWerACgAgke6BHj83VPnqwAoAIJHrAR4/N1RZ6wAKACCR6wEePzdT+esACgAgkfsZ4Ief3fTWSsACoDgoQS4l+6l81YAFADBQwlwJ91JZ64AKACChxLgPrqPzl0BUAAEDyXAXXQXnb0CoAAIHkqAe+geOn8FAMFDCXAH3UF3QAFA8FAC3D/3zz1QAARP8FAC3D13z11QAARP8NwHjz/unfugAAie4LkTHn/sIRQAwRM898Ljjz2EAiB4guduePyxhxQABUDwBM/98PhjDykACoDgCZ474o5hDykACoDgCZ574n5hDykACoDgCZ674m5hDykACoDgCZ474065U+6MAqAACJ7zcW/cJ/fJvVEAFADBw91xl9wld0cBUAAED/fHPXKP3B8FQAEQPNwhd8gdcocUAAVA8HCPnIv74x4pAA5J8IjdJefh7rhLCoACIHjE7pNzcG/cJwVAARA8YnfK93dn3CkFQAEQPGL3ynd3X9wrBUABEDxid8v3dlfcLQVAARA8YvfLd3ZP3C8FQAEQPGJ3zPd1R+whBUABEDxi98x3dT/sIQVAARA8YnfN93Q37CEFQAEQPGL3zXd0L+whBUABEDxid873cyfsIQVAARA8YvfOd3Mf7CEFQAEQPGJ3z/dyF+whBUABEDxi9893cg/sIQVAARA8YnfQ93EH7CEFQAEQPGL30Hexh+whBUABEDxid9H3sIfsIQVAARA8YvfRd7CH7CEFQAEQPMAesocUAAVA8AB7yB5SABQAwQPsIXtIAVAABA+wh+whBUABEDzAHrKHFAAED7CH7CEFAMED7CF7SAEQPMED7CF7SAEQPMED7CF7SAEQPMED7CEUAMETPMAeQgEQPMED7CEFQAEQPMED7CEFQAEQPMED7CEFQAEQPMED7CEFQAEQPMED7CEFQAEQPMEDe8geUgAUAMFzPmAP2UMKgAIgeIA9ZA8pAAqA4AH2kD2kACgAggfYQ/aQAqAACB5gD9lDCoBDEjzAHrKHFAAED7CH7CEFQPAED7CH7CEFQPAED7CH7CEFQPAED7CHUAAET/AAewgFQPAED7CHFAAFQPAED7CHFAAFQPAED7CHFAAFQPAED7CHFAAFQPAED7CHFAAFQPAED+whe0gBUAAET/DAHrKHFAAFQPAAe8geUgAUAMED7CF7SAFQAAQPsIfsIQVAARA8wB6yhxQAByR4gD1kDykACB5gD9lDCgCCB9hD9pACIHiCB9hD9pACIHiCB9hDKACCJ3iAPYQCIHiCB9hDCoACIHiCB9hDCoACIHiCB9hDCoACIHiCB9hDCoACIHiCB9hDCoACIHiCB/aQPaQAKACCJ3hgD9lDCoACIHiAPWQPKQAKgOAB9pA9pAAoAIIH2EP2kAKgAAgeYA/ZQwqAAiB4gD1kDykACB5gD9lDCgCCB9hD9pACIHiCB9hD9pACIHiCB9hDzkcBEDzBA+whFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzywh+whBUABEDzBA3vIHlIAFADBA+whe0gBUAAED7CH7CEFQAEQPMAesocUAAVA8AB7yB5SABQAwQPsIXtIAUDwAHvIHlIAEDzAHrKHFADBEzzAHrKHFADBEzzAHrKHFADBEzzAHkIBEDzBA+whFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzywh+whBUABEDzBA3vIHlIAFADBA+whe0gBUAAED7CH7CEFQAEQPMAesocUAAVA8AB7yB5SABQAwQPsIXtIAUDwAHvIHlIAEDzAHrKHFADBEzzAHrKHFADBEzzAHrKHFADBEzzAHkIBEDzBA+whFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzzAHlIAFADBEzywh+whBUABEDznA/aQPaQAKACCB9hD9pACoAAIHmAP2UMKgAIgeIA9ZA8pAAqA4AH2kD2kADgkwQPsIXtIAUDwAHvIHlIABE/wAHvIHlIABE/wAHvIHlIABE/wAHsIBUDwBA+wh1AABE/wAHtIAVAABE/wAHtIAVAABE/wAHtIAVAABE/wAHtIAVAABE/wAHtIAVAABE/wwB6yhxQABUDwBA/sIXtIAVAABA+wh+whBUABEDzAHrKHFAAFQPAAe8geUgAUAMED7CF7SAFwQIIH2EP2kAKA4AH2kD2kACB4gD1kDykAgid4gD1kDykAgid4gD2EAiB4ggfYQygAgid4gD2kACgAgid4gD2kACgAgid4gD2kACgAgid4gD2kACgAgid4gD2kACgAgid4YA/ZQwqAAiB4ggf2kD2kACgAggfYQ/aQAqAAAIACoAAAgAKgAACAAqAAAIACAAAoAACAAgAAKAAAgAIAACgAAKAAXH0cEgDEHn8FAAAUAABAAQAAFAAAQAEAABQAAEABAAAFQAEAAAVAAQAABUABAAAFQAkAAI+/AgAACoACAAAKgAIAAAqAAgAACoASAAAefwUAABQABQAAFAAHBwDBAqAEAEDw8VcAAEABAAAqBUAJAIDg468AAIACAABUCoASAADBx18BAIBoAVACACD4+CsAABAtAEoAAAQffwUAAKIFQAkAgODjrwAAQLQAKAEAEHz8FQAAiBYAJQAAgo+/AgAA0QKgBADg8Q+PSwCAx18BAAAFQAkAAI+/EgAAHn8lAAA8/goAACgASgAAePyVAADw+CsBAODxVwIAwOOvBACAx18JAACPvxIAAB5/JQAAPP5KAAAef6MEAODxN0oAAB5/owgA4OE3SgAAHn+jBADg8TeKAAAefqMEAODxN4oAAB5+owgA4OE3igAAHn5FwEUHwMOvCADg4TeKAAAefqMMAODRN8oAAB59oxAA4ME3SgEAHntjlAUAj7oxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY4wxxhhjTpoXPm9idKN+8HIAAAAASUVORK5CYII=";function WBQ(Q){let J=`http://127.0.0.1:${Q.port}/mcp`;return`#!/usr/bin/env node
const { spawn } = require("child_process");
const url = process.env.MCP_REMOTE_URL || ${JSON.stringify(J)};
const token = process.env.MCP_REMOTE_TOKEN || ${JSON.stringify(Q.token)};
const args = ["-y", "mcp-remote", url];
if (token) args.push("--header", \`Authorization: Bearer \${token}\`);
spawn("npx", args, { stdio: "inherit" }).on("exit", (c) => process.exit(c ?? 0));
`}function HBQ(Q){let J=`http://127.0.0.1:${Q.port}/mcp`;return{manifest_version:"0.3",name:"obsidian-mcp-connector",display_name:"Obsidian MCP Connector",version:Q.version,description:"Access your Obsidian vault (semantic search, notes, Templater prompts) via MCP.",author:{name:"Stefano Ferri"},icon:"icon.png",server:{type:"node",entry_point:"server/index.js",mcp_config:{command:"npx",args:["-y","mcp-remote",J,"--header",`Authorization: Bearer ${Q.token}`]}}}}function M60(Q){let J=HBQ(Q),G=MF(JSON.stringify(J,null,2)),H=MF(WBQ(Q)),K=Uint8Array.from(atob(vj0),(z)=>z.charCodeAt(0));return yj0({"manifest.json":G,"server/index.js":H,"icon.png":K})}var IX=require("obsidian");var BBQ=oQ(`<p class="hint svelte-c19ahs">MCP transport is not running. Copy buttons are disabled until the
HTTP server is up.</p>`),ABQ=oQ('<span class="status-ok svelte-c19ahs"> </span>'),KBQ=oQ(`<span class="status-fail svelte-c19ahs"> </span> <p class="hint svelte-c19ahs"><strong>Note for fnm / nvm / asdf users:</strong> Obsidian inherits PATH from <code class="svelte-c19ahs">launchctl</code> and does
not see version-manager-shimmed Node binaries. Install Node
globally (Homebrew on macOS, system installer otherwise) so
Obsidian and Claude Desktop can both find it.</p>`,1),zBQ=oQ('<p class="brew-status svelte-c19ahs"> </p>'),VBQ=oQ('<button type="button" aria-label="Install Node.js via Homebrew"> </button>'),qBQ=oQ('<div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">Install Node.js</div> <div class="setting-item-description"><!> <!></div></div> <div class="setting-item-control install-buttons svelte-c19ahs"><button type="button" aria-label="Open Node.js download page">Open download page</button> <!></div></div>'),UBQ=oQ("Cached <!> ",1),$BQ=oQ('<span class="status-fail svelte-c19ahs"> </span>'),ZBQ=oQ(`<div class="mcp-client-config svelte-c19ahs"><h3>Quick setup for clients</h3> <div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">Copy config snippets</div> <div class="setting-item-description">Each button copies a ready-to-paste JSON block for the
corresponding MCP client. Paste into the client's config file
under <code class="svelte-c19ahs">mcpServers</code>.</div></div> <div class="setting-item-control copy-buttons svelte-c19ahs"><button type="button" aria-label="Copy Claude Desktop config">Claude Desktop</button> <button type="button" aria-label="Copy Claude Code config">Claude Code</button> <button type="button" aria-label="Copy streamable-http config (Cursor, Cline, Continue, VS Code)">Cursor / Cline / Continue</button></div></div> <div class="setting-item mcpb-row"><div class="setting-item-info"><div class="setting-item-name">Claude Desktop extension</div> <div class="setting-item-description">Drag the downloaded file onto Claude Desktop. The token is embedded —
no paste needed. Do not share this file. Node.js must be on your PATH
(see below).</div></div> <div class="setting-item-control"><button type="button" aria-label="Download Claude Desktop extension (.mcpb)"> </button></div></div> <div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">Auto-write Claude Desktop config</div> <div class="setting-item-description">When enabled, the plugin rewrites <code class="svelte-c19ahs">claude_desktop_config.json</code> whenever the bearer token rotates or the port changes. A
backup is saved alongside the file as <code class="svelte-c19ahs">.backup</code>. Off by default — turning it on touches
a user-managed file outside the vault.</div></div> <div class="setting-item-control"><input type="checkbox" aria-label="Auto-write Claude Desktop config"/></div></div> <!> <h3>Claude Desktop integration</h3> <p class="lead svelte-c19ahs">Claude Desktop reaches the in-process MCP server through the <code class="svelte-c19ahs">mcp-remote</code> bridge, which requires Node.js on PATH. Other clients (Claude
Code, Cursor, Cline, Continue) speak HTTP MCP natively and do
NOT need either of these.</p> <div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">Node.js</div> <div class="setting-item-description"><!></div></div> <div class="setting-item-control"><button type="button" aria-label="Verify Node.js installation"> </button></div></div> <!> <div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">mcp-remote (npm cache)</div> <div class="setting-item-description"><!> <!></div></div> <div class="setting-item-control"><button type="button" aria-label="Pre-warm mcp-remote"> </button></div></div></div>`),FBQ={hash:"svelte-c19ahs",code:".mcp-client-config.svelte-c19ahs {margin-bottom:1.5em;}.copy-buttons.svelte-c19ahs {display:flex;flex-wrap:wrap;gap:0.4em;}.hint.svelte-c19ahs {color:var(--text-muted);font-size:0.85em;margin-top:0.4em;}code.svelte-c19ahs {font-family:var(--font-monospace);font-size:0.9em;}.lead.svelte-c19ahs {color:var(--text-normal);margin:0.5em 0 1em;}.status-ok.svelte-c19ahs {color:var(--text-success);font-weight:600;}.status-fail.svelte-c19ahs {color:var(--text-error);}.install-buttons.svelte-c19ahs {display:flex;gap:0.4em;flex-wrap:wrap;}.brew-status.svelte-c19ahs {margin:0.4em 0 0;padding:0.3em 0.5em;border-radius:3px;background:var(--background-secondary);font-family:var(--font-monospace);font-size:0.8em;color:var(--text-muted);}"};function pC(Q,J){c7(J,!1),bX(Q,FBQ);var G=dQ(),H=dQ(),K=dQ(),z=dQ();let q=gX(J,"plugin",8),F=dQ(""),D=dQ(0),V=dQ(""),O=dQ(!1),P=dQ(!1),N=dQ(!1),I=dQ(null),R=dQ(!1),w=dQ(null),E=dQ(!1),T=dQ(null),y=dQ(null),x=dQ(!1),b=dQ(null),g="https://nodejs.org/en/download/";SY(async()=>{if(qQ(O,await qF(q())),qQ(I,await o3()),qQ(y,await A60(q())),c(I)&&!c(I).found)qQ(w,await fC())});async function l(){if(c(R))return;qQ(R,!0);try{if(qQ(I,await o3({forceRefresh:!0})),c(I)&&!c(I).found&&c(w)===null)qQ(w,await fC())}finally{qQ(R,!1)}}function _(){window.open(g,"_blank")}async function a(){if(c(E))return;qQ(E,!0),qQ(T,"Starting Homebrew install…");try{let IQ=await B60({onLine:(rQ)=>{r(rQ)}});if(IQ.ok)qQ(T,`Node ${IQ.version} installed.`),qQ(I,{found:!0,version:IQ.version,raw:`v${IQ.version}`}),new IX.Notice(`Node.js ${IQ.version} installed via Homebrew.`);else qQ(T,`Failed: ${IQ.error}`),new IX.Notice(`Homebrew install failed: ${IQ.error}`)}catch(IQ){let rQ=IQ instanceof Error?IQ.message:String(IQ);qQ(T,`Failed: ${rQ}`),new IX.Notice(`Homebrew install failed: ${rQ}`)}finally{qQ(E,!1)}}function r(IQ){let rQ=IQ.replace(/^==> /,"").trim();if(rQ.length===0)return;qQ(T,rQ.length>80?rQ.slice(0,77)+"…":rQ)}async function f0(){if(c(x))return;qQ(x,!0),qQ(b,null);try{let IQ=await K60(q());if(IQ.ok)qQ(y,IQ.entry),new IX.Notice("mcp-remote pre-warmed.");else qQ(b,IQ.error),new IX.Notice(`Pre-warm failed: ${IQ.error}`)}finally{qQ(x,!1)}}function t(IQ){try{return new Date(IQ).toLocaleString()}catch(rQ){return IQ}}async function p0(){if(c(N))return;qQ(N,!0);try{let IQ=M60({version:q().manifest.version,port:c(D),token:c(F)}),rQ="obsidian-mcp-connector.mcpb",l8=(()=>{try{let U6=require("electron").remote;return(U6===null||U6===void 0?void 0:U6.dialog)?U6:null}catch(U6){return null}})();if(l8){let{filePath:U6}=await l8.dialog.showSaveDialog({defaultPath:"obsidian-mcp-connector.mcpb",filters:[{name:"Claude Desktop Extension",extensions:["mcpb"]}]});if(!U6){new IX.Notice("Save cancelled.");return}let{writeFile:G8}=require("fs/promises");await G8(U6,Buffer.from(IQ)),new IX.Notice("obsidian-mcp-connector.mcpb saved.")}else{let U6=IQ.buffer.slice(IQ.byteOffset,IQ.byteOffset+IQ.byteLength);await q().app.vault.adapter.writeBinary("obsidian-mcp-connector.mcpb",U6),new IX.Notice("Saved to vault root: obsidian-mcp-connector.mcpb")}}catch(IQ){let rQ=IQ instanceof Error?IQ.message:String(IQ);new IX.Notice(`Failed to generate .mcpb: ${rQ}`),console.error("[mcpb] generation failed",IQ)}finally{qQ(N,!1)}}async function u0(IQ,rQ){try{await navigator.clipboard.writeText(JSON.stringify(IQ,null,2)),new IX.Notice(`${rQ} config copied to clipboard.`)}catch(l8){let U6=l8 instanceof Error?l8.message:String(l8);new IX.Notice(`Copy failed: ${U6}`)}}function d(){return u0(VF(J60({url:c(V),token:c(F)})),"Claude Desktop")}function n(){return u0(VF(Y60({url:c(V),token:c(F)})),"Claude Code")}function c0(){return u0(VF(G60({url:c(V),token:c(F)})),"Streamable HTTP")}async function WQ(IQ){if(c(P))return;let rQ=IQ.currentTarget.checked;qQ(P,!0);try{if(await W60(q(),rQ),qQ(O,rQ),rQ){let l8=await UF(q());if(l8.applied)new IX.Notice("Claude Desktop config rewritten.");else if(l8.applied===!1&&l8.reason==="transport-offline")new IX.Notice("Auto-write enabled, but the MCP transport is not running yet.");else if(l8.applied===!1&&l8.reason==="error")new IX.Notice(`Auto-write enabled, but write failed: ${l8.error}`)}else new IX.Notice("Auto-write disabled.")}catch(l8){let U6=l8 instanceof Error?l8.message:String(l8);new IX.Notice(`Toggle failed: ${U6}`),qQ(O,await qF(q()))}finally{qQ(P,!1)}}YY(()=>(kJ(H),kJ(G),yJ(q()),c(D),kJ(z),kJ(K),F3,k4),()=>{qQ(F,qQ(H,qQ(G,q().mcpTransportState)===null||kJ(G)===void 0?void 0:kJ(G).bearerToken)!==null&&kJ(H)!==void 0?kJ(H):""),qQ(D,qQ(z,qQ(K,q().mcpTransportState)===null||kJ(K)===void 0?void 0:kJ(K).server.port)!==null&&kJ(z)!==void 0?kJ(z):0),qQ(V,c(D)?`http://${F3}:${c(D)}${k4}`:"")}),J3(),vJ();var R0=ZBQ(),l0=VQ(GQ(R0),2),d0=VQ(GQ(l0),2),m0=GQ(d0),ZQ=VQ(m0,2),LQ=VQ(ZQ,2);YQ(d0),YQ(l0);var h0=VQ(l0,2),pQ=VQ(GQ(h0),2),iQ=GQ(pQ),mQ=GQ(iQ,!0);YQ(iQ),YQ(pQ),YQ(h0);var AQ=VQ(h0,2),MQ=VQ(GQ(AQ),2),DQ=GQ(MQ);j9(DQ),YQ(MQ),YQ(AQ);var bQ=VQ(AQ,2);{var j8=(IQ)=>{var rQ=BBQ();TQ(IQ,rQ)};m8(bQ,(IQ)=>{if(!c(F)||!c(D))IQ(j8)})}var tQ=VQ(bQ,6),K8=GQ(tQ),k8=VQ(GQ(K8),2),d6=GQ(k8);{var r9=(IQ)=>{var rQ=Y5("Checking…");TQ(IQ,rQ)},H7=(IQ)=>{var rQ=ABQ(),l8=GQ(rQ);YQ(rQ),C8(()=>q8(l8,`Detected v${(c(I),FQ(()=>c(I).version))??""}`)),TQ(IQ,rQ)},LJ=(IQ)=>{var rQ=KBQ(),l8=$X(rQ),U6=GQ(l8,!0);YQ(l8),v9(2),C8(()=>q8(U6,(c(I),FQ(()=>c(I).error)))),TQ(IQ,rQ)};m8(d6,(IQ)=>{if(c(I)===null)IQ(r9);else if(c(I),FQ(()=>c(I).found))IQ(H7,1);else IQ(LJ,-1)})}YQ(k8),YQ(K8);var OJ=VQ(K8,2),w7=GQ(OJ),QJ=GQ(w7,!0);YQ(w7),YQ(OJ),YQ(tQ);var e8=VQ(tQ,2);{var wQ=(IQ)=>{var rQ=qBQ(),l8=GQ(rQ),U6=VQ(GQ(l8),2),G8=GQ(U6);{var e9=(h8)=>{var F6=Y5();C8(()=>q8(F6,`Homebrew detected (v${(c(w),FQ(()=>c(w).version))??""}). Click below to
install Node.js with one command. No sudo needed.`)),TQ(h8,F6)},TX=(h8)=>{var F6=Y5(`Open the Node.js download page and run the installer for
your platform.`);TQ(h8,F6)};m8(G8,(h8)=>{if(c(w),FQ(()=>c(w)?.found))h8(e9);else h8(TX,-1)})}var j6=VQ(G8,2);{var s8=(h8)=>{var F6=zBQ(),L7=GQ(F6,!0);YQ(F6),C8(()=>q8(L7,c(T))),TQ(h8,F6)};m8(j6,(h8)=>{if(c(T))h8(s8)})}YQ(U6),YQ(l8);var x6=VQ(l8,2),t6=GQ(x6),M7=VQ(t6,2);{var Z9=(h8)=>{var F6=VBQ(),L7=GQ(F6,!0);YQ(F6),C8(()=>{F6.disabled=c(E),q8(L7,c(E)?"Installing…":"Install via Homebrew")}),N8("click",F6,a),TQ(h8,F6)};m8(M7,(h8)=>{if(c(w),FQ(()=>c(w)?.found))h8(Z9)})}YQ(x6),YQ(rQ),N8("click",t6,_),TQ(IQ,rQ)};m8(e8,(IQ)=>{if(c(I),FQ(()=>c(I)!==null&&!c(I).found))IQ(wQ)})}var lQ=VQ(e8,2),U8=GQ(lQ),P6=VQ(GQ(U8),2),N6=GQ(P6);{var t9=(IQ)=>{var rQ=UBQ(),l8=VQ($X(rQ));{var U6=(e9)=>{var TX=Y5();C8(()=>q8(TX,`(v${(c(y),FQ(()=>c(y).version))??""})`)),TQ(e9,TX)};m8(l8,(e9)=>{if(c(y),FQ(()=>c(y).version))e9(U6)})}var G8=VQ(l8);C8((e9)=>q8(G8,` on ${e9??""}.`),[()=>(c(y),FQ(()=>t(c(y).lastWarmedAt)))]),TQ(IQ,rQ)},F8=(IQ)=>{var rQ=Y5(`Not cached. The first Claude Desktop launch will pause for
20-60s while npx downloads the package (~5 MB).`);TQ(IQ,rQ)};m8(N6,(IQ)=>{if(c(y))IQ(t9);else IQ(F8,-1)})}var SX=VQ(N6,2);{var B7=(IQ)=>{var rQ=$BQ(),l8=GQ(rQ);YQ(rQ),C8(()=>q8(l8,`— ${c(b)??""}`)),TQ(IQ,rQ)};m8(SX,(IQ)=>{if(c(b))IQ(B7)})}YQ(P6),YQ(U8);var f8=VQ(U8,2),D8=GQ(f8),S6=GQ(D8,!0);YQ(D8),YQ(f8),YQ(lQ),YQ(R0),C8(()=>{m0.disabled=!c(F)||!c(D),ZQ.disabled=!c(F)||!c(D),LQ.disabled=!c(F)||!c(D),iQ.disabled=(c(F),c(D),c(I),c(N),FQ(()=>!c(F)||!c(D)||c(I)!==null&&!c(I).found||c(N))),q8(mQ,c(N)?"Generating…":"Download .mcpb"),N7(DQ,c(O)),DQ.disabled=c(P),w7.disabled=c(R),q8(QJ,c(R)?"Checking…":"Verify again"),D8.disabled=(c(x),c(I),FQ(()=>c(x)||c(I)!==null&&!c(I).found)),q8(S6,c(x)?"Pre-warming…":"Pre-warm now")}),N8("click",m0,d),N8("click",ZQ,n),N8("click",LQ,c0),N8("click",iQ,p0),N8("change",DQ,WQ),N8("click",w7,l),N8("click",D8,f0),TQ(Q,R0),i7()}var DBQ=oQ('<input readonly="" aria-label="Bearer token" class="token-input svelte-1ozrv0q"/> <button type="button"> </button> <button type="button" aria-label="Copy token to clipboard">Copy</button>',1),MBQ=oQ('<span class="token-unavailable svelte-1ozrv0q">HTTP transport not running</span>'),LBQ=oQ('HTTP MCP endpoint at <code class="svelte-1ozrv0q"> </code>',1),OBQ=oQ('<div class="mcp-access-control svelte-1ozrv0q"><h3>Access Control</h3> <div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">API key</div> <div class="setting-item-description">Bearer token required by MCP clients. Treat as a secret.</div></div> <div class="setting-item-control token-control svelte-1ozrv0q"><!> <button type="button" aria-label="Regenerate bearer token"> </button></div></div> <div class="setting-item"><div class="setting-item-info"><div class="setting-item-name">Server port</div> <div class="setting-item-description"><!></div></div></div></div>'),PBQ={hash:"svelte-1ozrv0q",code:".mcp-access-control.svelte-1ozrv0q {margin-bottom:1.5em;}.token-control.svelte-1ozrv0q {display:flex;align-items:center;gap:0.4em;flex-wrap:wrap;}.token-input.svelte-1ozrv0q {flex:1;min-width:180px;font-family:var(--font-monospace);font-size:0.9em;}.token-unavailable.svelte-1ozrv0q {color:var(--text-muted);font-size:0.9em;font-style:italic;}code.svelte-1ozrv0q {font-family:var(--font-monospace);font-size:0.9em;}"};function lC(Q,J){c7(J,!1),bX(Q,PBQ);var G,H,K,z;let q=gX(J,"plugin",12),F=dQ((H=(G=q().mcpTransportState)===null||G===void 0?void 0:G.bearerToken)!==null&&H!==void 0?H:""),D=dQ((z=(K=q().mcpTransportState)===null||K===void 0?void 0:K.server.port)!==null&&z!==void 0?z:27200),V=dQ(!1),O=dQ(!1);async function P(t){await navigator.clipboard.writeText(t),new AV.Notice("Copied to clipboard.")}async function N(){if(!confirm("Regenerate API key? This invalidates the current token — all MCP clients will need updated config."))return;qQ(O,!0);try{let p0=rP();if(await xY.run(async()=>{var n,c0;let WQ=(n=await q().loadData())!==null&&n!==void 0?n:{},R0=(c0=WQ.mcpTransport)!==null&&c0!==void 0?c0:{};await q().saveData({...WQ,mcpTransport:{...R0,bearerToken:p0}})}),q().mcpTransportState)await KF(q().mcpTransportState),q(q().mcpTransportState=void 0,!0);let u0=await AF(q());if(!u0.success){new AV.Notice(`MCP Connector: failed to restart — ${u0.error}`);return}if(q(q().mcpTransportState=u0.state,!0),qQ(F,u0.state.bearerToken),qQ(D,u0.state.server.port),(await UF(q())).applied)new AV.Notice("API key regenerated and Claude Desktop config updated.");else new AV.Notice("API key regenerated. Update your MCP client config.")}catch(p0){let u0=p0 instanceof Error?p0.message:String(p0);new AV.Notice(`MCP Connector: regenerate failed — ${u0}`)}finally{qQ(O,!1)}}vJ();var I=OBQ(),R=VQ(GQ(I),2),w=VQ(GQ(R),2),E=GQ(w);{var T=(t)=>{var p0=DBQ(),u0=$X(p0);j9(u0);var d=VQ(u0,2),n=GQ(d,!0);YQ(d);var c0=VQ(d,2);C8(()=>{N9(u0,"type",c(V)?"text":"password"),Xk(u0,c(F)),N9(d,"aria-label",c(V)?"Hide token":"Show token"),q8(n,c(V)?"Hide":"Show")}),N8("click",d,()=>qQ(V,!c(V))),N8("click",c0,()=>P(c(F))),TQ(t,p0)},y=(t)=>{var p0=MBQ();TQ(t,p0)};m8(E,(t)=>{if(c(F))t(T);else t(y,-1)})}var x=VQ(E,2),b=GQ(x,!0);YQ(x),YQ(w),YQ(R);var g=VQ(R,2),l=GQ(g),_=VQ(GQ(l),2),a=GQ(_);{var r=(t)=>{var p0=LBQ(),u0=VQ($X(p0)),d=GQ(u0);YQ(u0),C8(()=>q8(d,`http://${F3??""}:${c(D)??""}${k4??""}`)),TQ(t,p0)},f0=(t)=>{var p0=Y5("HTTP transport not running — port unavailable.");TQ(t,p0)};m8(a,(t)=>{if(c(D))t(r);else t(f0,-1)})}YQ(_),YQ(l),YQ(g),YQ(I),C8(()=>{x.disabled=c(O),q8(b,c(O)?"Regenerating…":"Regenerate")}),N8("click",x,N),TQ(Q,I),i7()}var NBQ=oQ('<div class="settings-container"><!> <!> <!> <!> <!></div>');function L60(Q,J){let G=gX(J,"plugin",8);var H=NBQ(),K=GQ(H);lC(K,{get plugin(){return G()}});var z=VQ(K,2);pC(z,{get plugin(){return G()}});var q=VQ(z,2);cP(q,{get plugin(){return G()}});var F=VQ(q,2);oP(F,{get plugin(){return G()}});var D=VQ(F,2);nP(D,{get plugin(){return G()}}),YQ(H),TQ(Q,H)}var xj0=require("obsidian");class bj0 extends xj0.PluginSettingTab{plugin;component;constructor(Q,J){super(Q,J);this.plugin=J}display(){let{containerEl:Q}=this;Q.empty(),this.component=O4(L60,{target:Q,props:{plugin:this.plugin}})}hide(){if(this.component)G3(this.component)}}function gj0(Q){try{return Q.addSettingTab(new bj0(Q.app,Q)),Promise.resolve({success:!0})}catch(J){return Promise.resolve({success:!1,error:J instanceof Error?J.message:String(J)})}}var mj0=require("obsidian");var jBQ=/<% tp\.mcpTools\.prompt\("([^"]+)",\s*"([^"]*)"\) %>/g,CBQ=/<% tp\.mcpTools\.prompt\("([^"]+)"\) %>/g;function IBQ(Q){let J=new Set,G=[];for(let H of Q.matchAll(jBQ)){let K=H[1];if(!J.has(K))J.add(K),G.push({name:K,description:H[2]})}for(let H of Q.matchAll(CBQ)){let K=H[1];if(!J.has(K))J.add(K),G.push({name:K,description:""})}return G}async function hj0(Q){let J=Q.vault.getMarkdownFiles().filter((H)=>{if(!H.path.startsWith("Prompts/"))return!1;return!H.path.slice(8).includes("/")}),G=[];for(let H of J){let z=Q.metadataCache.getFileCache(H)?.frontmatter;if(!z)continue;let q=z.tags,F=Array.isArray(q)?q:typeof q==="string"?[q]:null;if(!F)continue;try{lP.assert({...z,tags:F})}catch{continue}let D=await Q.vault.cachedRead(H),V=IBQ(D),O=H.basename;G.push({name:O,description:typeof z.description==="string"?z.description:void 0,arguments:V.map((P)=>({name:P.name,description:P.description,required:!1}))})}return G}function RBQ(Q){if(!Q.startsWith(`---
`))return Q;let J=Q.indexOf(`
---
`,4);if(J===-1)return Q;return Q.slice(J+5)}function wBQ(Q){return Q.split(`
`).filter((J)=>!/^\s*<%[-*]?\s*tp\.mcpTools\.prompt\(/.test(J)).join(`
`)}function EBQ(Q,J){return Q.replace(/\{\{([^}]+)\}\}/g,(G,H)=>{let K=H.trim();return K in J?J[K]:`{{${H}}}`})}function _j0(Q,J){let G=RBQ(Q),H=wBQ(G);return EBQ(H,J).replace(/^\n+/,"")}function dC(Q){if(!Q.startsWith("Prompts/"))return!1;if(!Q.endsWith(".md"))return!1;return!Q.slice(8).includes("/")}function fj0(Q,J){let G=Q.vault.on("create",(z)=>{if(dC(z.path))J()}),H=Q.vault.on("delete",(z)=>{if(dC(z.path))J()}),K=Q.vault.on("rename",(z,q)=>{if(dC(z.path)||dC(q))J()});return{stop:()=>{Q.vault.offref(G),Q.vault.offref(H),Q.vault.offref(K)}}}async function uj0(Q,J){try{return Q.setLister(()=>hj0(J)),Q.setHandler("*",async(H,K)=>{let z=`Prompts/${H}.md`,q=J.vault.getAbstractFileByPath(z);if(q===null)throw new gQ(nQ.InvalidParams,`Prompt not found: ${H}`);if(!(q instanceof mj0.TFile))throw new gQ(nQ.InvalidParams,`Prompt not found: ${H}`);let F=q,V=J.metadataCache.getFileCache(F)?.frontmatter,O=V?.tags,P=Array.isArray(O)?O:typeof O==="string"?[O]:null;if(!P)throw new gQ(nQ.InvalidParams,`Prompt not found: ${H}`);try{lP.assert({...V,tags:P})}catch{throw new gQ(nQ.InvalidParams,`Prompt not found: ${H}`)}let N=await J.vault.cachedRead(F);return{messages:[{role:"user",content:{type:"text",text:_j0(N,K)}}]}}),{success:!0,state:{watcher:fj0(J,()=>{})}}}catch(G){return{success:!1,error:G instanceof Error?G.message:String(G)}}}function pj0(Q){Q.watcher.stop()}var $B=require("obsidian");var bI0=K7(require("fs")),WB=K7(require("path")),gI0=K7(require("url")),QB=K7(require("fs")),ZV=K7(require("fs")),EF=K7(require("path")),CVQ=K7(cj0(),1);var ij0="1.26.0";var oj0="warning",P60={wasm:{},webgl:{},webgpu:{},versions:{common:ij0},set logLevel(Q){if(Q===void 0)return;if(typeof Q!=="string"||["verbose","info","warning","error","fatal"].indexOf(Q)===-1)throw Error(`Unsupported logging level: ${Q}`);oj0=Q},get logLevel(){return oj0}};Object.defineProperty(P60,"logLevel",{enumerable:!0});var nj0=(Q,J)=>{let G=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);G.width=Q.dims[3],G.height=Q.dims[2];let H=G.getContext("2d");if(H!=null){let K,z;if(J?.tensorLayout!==void 0&&J.tensorLayout==="NHWC")K=Q.dims[2],z=Q.dims[3];else K=Q.dims[3],z=Q.dims[2];let q=J?.format!==void 0?J.format:"RGB",F=J?.norm,D,V;if(F===void 0||F.mean===void 0)D=[255,255,255,255];else if(typeof F.mean==="number")D=[F.mean,F.mean,F.mean,F.mean];else if(D=[F.mean[0],F.mean[1],F.mean[2],0],F.mean[3]!==void 0)D[3]=F.mean[3];if(F===void 0||F.bias===void 0)V=[0,0,0,0];else if(typeof F.bias==="number")V=[F.bias,F.bias,F.bias,F.bias];else if(V=[F.bias[0],F.bias[1],F.bias[2],0],F.bias[3]!==void 0)V[3]=F.bias[3];let O=z*K,P=0,N=O,I=O*2,R=-1;if(q==="RGBA")P=0,N=O,I=O*2,R=O*3;else if(q==="RGB")P=0,N=O,I=O*2;else if(q==="RBG")P=0,I=O,N=O*2;for(let w=0;w<z;w++)for(let E=0;E<K;E++){let T=(Q.data[P++]-V[0])*D[0],y=(Q.data[N++]-V[1])*D[1],x=(Q.data[I++]-V[2])*D[2],b=R===-1?255:(Q.data[R++]-V[3])*D[3];H.fillStyle="rgba("+T+","+y+","+x+","+b+")",H.fillRect(E,w,1,1)}if("toDataURL"in G)return G.toDataURL();else throw Error("toDataURL is not supported")}else throw Error("Can not access image data")},aj0=(Q,J)=>{let G=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),H;if(G!=null){let K,z,q;if(J?.tensorLayout!==void 0&&J.tensorLayout==="NHWC")K=Q.dims[2],z=Q.dims[1],q=Q.dims[3];else K=Q.dims[3],z=Q.dims[2],q=Q.dims[1];let F=J!==void 0?J.format!==void 0?J.format:"RGB":"RGB",D=J?.norm,V,O;if(D===void 0||D.mean===void 0)V=[255,255,255,255];else if(typeof D.mean==="number")V=[D.mean,D.mean,D.mean,D.mean];else if(V=[D.mean[0],D.mean[1],D.mean[2],255],D.mean[3]!==void 0)V[3]=D.mean[3];if(D===void 0||D.bias===void 0)O=[0,0,0,0];else if(typeof D.bias==="number")O=[D.bias,D.bias,D.bias,D.bias];else if(O=[D.bias[0],D.bias[1],D.bias[2],0],D.bias[3]!==void 0)O[3]=D.bias[3];let P=z*K;if(J!==void 0){if(J.format!==void 0&&q===4&&J.format!=="RGBA"||q===3&&J.format!=="RGB"&&J.format!=="BGR")throw Error("Tensor format doesn't match input tensor dims")}let N=4,I=0,R=1,w=2,E=3,T=0,y=P,x=P*2,b=-1;if(F==="RGBA")T=0,y=P,x=P*2,b=P*3;else if(F==="RGB")T=0,y=P,x=P*2;else if(F==="RBG")T=0,x=P,y=P*2;H=G.createImageData(K,z);for(let g=0;g<z*K;I+=N,R+=N,w+=N,E+=N,g++)H.data[I]=(Q.data[T++]-O[0])*V[0],H.data[R]=(Q.data[y++]-O[1])*V[1],H.data[w]=(Q.data[x++]-O[2])*V[2],H.data[E]=b===-1?255:(Q.data[b++]-O[3])*V[3]}else throw Error("Can not access image data");return H};var N60=(Q,J)=>{if(Q===void 0)throw Error("Image buffer must be defined");if(J.height===void 0||J.width===void 0)throw Error("Image height and width must be defined");if(J.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:G,width:H}=J,K=J.norm??{mean:255,bias:0},z,q;if(typeof K.mean==="number")z=[K.mean,K.mean,K.mean,K.mean];else z=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255];if(typeof K.bias==="number")q=[K.bias,K.bias,K.bias,K.bias];else q=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];let F=J.format!==void 0?J.format:"RGBA",D=J.tensorFormat!==void 0?J.tensorFormat!==void 0?J.tensorFormat:"RGB":"RGB",V=G*H,O=D==="RGBA"?new Float32Array(V*4):new Float32Array(V*3),P=4,N=0,I=1,R=2,w=3,E=0,T=V,y=V*2,x=-1;if(F==="RGB")P=3,N=0,I=1,R=2,w=-1;if(D==="RGBA")x=V*3;else if(D==="RBG")E=0,y=V,T=V*2;else if(D==="BGR")y=0,T=V,E=V*2;for(let g=0;g<V;g++,N+=P,R+=P,I+=P,w+=P)if(O[E++]=(Q[N]+q[0])/z[0],O[T++]=(Q[I]+q[1])/z[1],O[y++]=(Q[R]+q[2])/z[2],x!==-1&&w!==-1)O[x++]=(Q[w]+q[3])/z[3];return D==="RGBA"?new nX("float32",O,[1,4,G,H]):new nX("float32",O,[1,3,G,H])},sj0=async(Q,J)=>{let G=typeof HTMLImageElement<"u"&&Q instanceof HTMLImageElement,H=typeof ImageData<"u"&&Q instanceof ImageData,K=typeof ImageBitmap<"u"&&Q instanceof ImageBitmap,z=typeof Q==="string",q,F=J??{},D=()=>{if(typeof document<"u")return document.createElement("canvas");else if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);else throw Error("Canvas is not supported")},V=(O)=>{if(typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement)return O.getContext("2d");else if(O instanceof OffscreenCanvas)return O.getContext("2d");else return null};if(G){let O=D();O.width=Q.width,O.height=Q.height;let P=V(O);if(P!=null){let{height:N,width:I}=Q;if(J!==void 0&&J.resizedHeight!==void 0&&J.resizedWidth!==void 0)N=J.resizedHeight,I=J.resizedWidth;if(J!==void 0){if(F=J,J.tensorFormat!==void 0)throw Error("Image input config format must be RGBA for HTMLImageElement");else F.tensorFormat="RGBA";F.height=N,F.width=I}else F.tensorFormat="RGBA",F.height=N,F.width=I;P.drawImage(Q,0,0),q=P.getImageData(0,0,I,N).data}else throw Error("Can not access image data")}else if(H){let O,P;if(J!==void 0&&J.resizedWidth!==void 0&&J.resizedHeight!==void 0)O=J.resizedHeight,P=J.resizedWidth;else O=Q.height,P=Q.width;if(J!==void 0)F=J;if(F.format="RGBA",F.height=O,F.width=P,J!==void 0){let N=D();N.width=P,N.height=O;let I=V(N);if(I!=null)I.putImageData(Q,0,0),q=I.getImageData(0,0,P,O).data;else throw Error("Can not access image data")}else q=Q.data}else if(K){if(J===void 0)throw Error("Please provide image config with format for Imagebitmap");let O=D();O.width=Q.width,O.height=Q.height;let P=V(O);if(P!=null){let{height:N,width:I}=Q;return P.drawImage(Q,0,0,I,N),q=P.getImageData(0,0,I,N).data,F.height=N,F.width=I,N60(q,F)}else throw Error("Can not access image data")}else if(z)return new Promise((O,P)=>{let N=D(),I=V(N);if(!Q||!I)return P();let R=new Image;R.crossOrigin="Anonymous",R.src=Q,R.onload=()=>{N.width=R.width,N.height=R.height,I.drawImage(R,0,0,N.width,N.height);let w=I.getImageData(0,0,N.width,N.height);F.height=N.height,F.width=N.width,O(N60(w.data,F))}});else throw Error("Input data provided is not supported - aborted tensor creation");if(q!==void 0)return N60(q,F);else throw Error("Input data provided is not supported - aborted tensor creation")},rj0=(Q,J)=>{let{width:G,height:H,download:K,dispose:z}=J;return new nX({location:"texture",type:"float32",texture:Q,dims:[1,H,G,4],download:K,dispose:z})},tj0=(Q,J)=>{let{dataType:G,dims:H,download:K,dispose:z}=J;return new nX({location:"gpu-buffer",type:G??"float32",gpuBuffer:Q,dims:H,download:K,dispose:z})},ej0=(Q,J)=>{let{dataType:G,dims:H,download:K,dispose:z}=J;return new nX({location:"ml-tensor",type:G??"float32",mlTensor:Q,dims:H,download:K,dispose:z})},QC0=(Q,J,G)=>new nX({location:"cpu-pinned",type:Q,data:J,dims:G??[J.length]});var a3=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),LF=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),XC0=!1,JC0=()=>{if(!XC0){XC0=!0;let Q=typeof BigInt64Array<"u"&&BigInt64Array.from,J=typeof BigUint64Array<"u"&&BigUint64Array.from,G=globalThis.Float16Array,H=typeof G<"u"&&G.from;if(Q)a3.set("int64",BigInt64Array),LF.set(BigInt64Array,"int64");if(J)a3.set("uint64",BigUint64Array),LF.set(BigUint64Array,"uint64");if(H)a3.set("float16",G),LF.set(G,"float16");else a3.set("float16",Uint16Array)}};var YC0=(Q)=>{let J=1;for(let G=0;G<Q.length;G++){let H=Q[G];if(typeof H!=="number"||!Number.isSafeInteger(H))throw TypeError(`dims[${G}] must be an integer, got: ${H}`);if(H<0)throw RangeError(`dims[${G}] must be a non-negative integer, got: ${H}`);J*=H}return J},GC0=(Q,J)=>{switch(Q.location){case"cpu":return new nX(Q.type,Q.data,J);case"cpu-pinned":return new nX({location:"cpu-pinned",data:Q.data,type:Q.type,dims:J});case"texture":return new nX({location:"texture",texture:Q.texture,type:Q.type,dims:J});case"gpu-buffer":return new nX({location:"gpu-buffer",gpuBuffer:Q.gpuBuffer,type:Q.type,dims:J});case"ml-tensor":return new nX({location:"ml-tensor",mlTensor:Q.mlTensor,type:Q.type,dims:J});default:throw Error(`tensorReshape: tensor location ${Q.location} is not supported`)}};class nX{constructor(Q,J,G){JC0();let H,K;if(typeof Q==="object"&&"location"in Q)switch(this.dataLocation=Q.location,H=Q.type,K=Q.dims,Q.location){case"cpu-pinned":{let q=a3.get(H);if(!q)throw TypeError(`unsupported type "${H}" to create tensor from pinned buffer`);if(!(Q.data instanceof q))throw TypeError(`buffer should be of type ${q.name}`);this.cpuData=Q.data;break}case"texture":{if(H!=="float32")throw TypeError(`unsupported type "${H}" to create tensor from texture`);this.gpuTextureData=Q.texture,this.downloader=Q.download,this.disposer=Q.dispose;break}case"gpu-buffer":{if(H!=="float32"&&H!=="float16"&&H!=="int32"&&H!=="int64"&&H!=="uint32"&&H!=="uint8"&&H!=="bool"&&H!=="uint4"&&H!=="int4")throw TypeError(`unsupported type "${H}" to create tensor from gpu buffer`);this.gpuBufferData=Q.gpuBuffer,this.downloader=Q.download,this.disposer=Q.dispose;break}case"ml-tensor":{if(H!=="float32"&&H!=="float16"&&H!=="int32"&&H!=="int64"&&H!=="uint32"&&H!=="uint64"&&H!=="int8"&&H!=="uint8"&&H!=="bool"&&H!=="uint4"&&H!=="int4")throw TypeError(`unsupported type "${H}" to create tensor from MLTensor`);this.mlTensorData=Q.mlTensor,this.downloader=Q.download,this.disposer=Q.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let q,F;if(typeof Q==="string")if(H=Q,F=G,Q==="string"){if(!Array.isArray(J))throw TypeError("A string tensor's data must be a string array.");q=J}else{let D=a3.get(Q);if(D===void 0)throw TypeError(`Unsupported tensor type: ${Q}.`);if(Array.isArray(J))if(Q==="float16"&&D===Uint16Array||Q==="uint4"||Q==="int4")throw TypeError(`Creating a ${Q} tensor from number array is not supported. Please use ${D.name} as data.`);else if(Q==="uint64"||Q==="int64")q=D.from(J,BigInt);else q=D.from(J);else if(J instanceof D)q=J;else if(J instanceof Uint8ClampedArray)if(Q==="uint8")q=Uint8Array.from(J);else throw TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Q==="float16"&&J instanceof Uint16Array&&D!==Uint16Array)q=new globalThis.Float16Array(J.buffer,J.byteOffset,J.length);else throw TypeError(`A ${H} tensor's data must be type of ${D}`)}else if(F=J,Array.isArray(Q)){if(Q.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let D=typeof Q[0];if(D==="string")H="string",q=Q;else if(D==="boolean")H="bool",q=Uint8Array.from(Q);else throw TypeError(`Invalid element type of data array: ${D}.`)}else if(Q instanceof Uint8ClampedArray)H="uint8",q=Uint8Array.from(Q);else{let D=LF.get(Q.constructor);if(D===void 0)throw TypeError(`Unsupported type for tensor data: ${Q.constructor}.`);H=D,q=Q}if(F===void 0)F=[q.length];else if(!Array.isArray(F))throw TypeError("A tensor's dims must be a number array");K=F,this.cpuData=q,this.dataLocation="cpu"}let z=YC0(K);if(this.cpuData&&z!==this.cpuData.length)if((H==="uint4"||H==="int4")&&Math.ceil(z/2)===this.cpuData.length);else throw Error(`Tensor's size(${z}) does not match data length(${this.cpuData.length}).`);this.type=H,this.dims=K,this.size=z}static async fromImage(Q,J){return sj0(Q,J)}static fromTexture(Q,J){return rj0(Q,J)}static fromGpuBuffer(Q,J){return tj0(Q,J)}static fromMLTensor(Q,J){return ej0(Q,J)}static fromPinnedBuffer(Q,J,G){return QC0(Q,J,G)}toDataURL(Q){return nj0(this,Q)}toImageData(Q){return aj0(this,Q)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(Q){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let J=await this.downloader();if(this.downloader=void 0,this.dataLocation="cpu",this.cpuData=J,Q&&this.disposer)this.disposer(),this.disposer=void 0;return J}finally{this.isDownloading=!1}}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error("The current tensor is being downloaded.");if(this.disposer)this.disposer(),this.disposer=void 0;this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw Error("The tensor is disposed.")}reshape(Q){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return GC0(this,Q)}}var j60=nX;var $w0=K7(require("fs")),Zw0=require("stream"),Fw0=require("stream/promises"),OR=K7(HC0(),1),TBQ=Object.defineProperty,KV=((Q)=>require)(function(Q){return require.apply(this,arguments)}),IV=(Q,J)=>{for(var G in J)TBQ(Q,G,{get:J[G],enumerable:!0})},kBQ="4.2.0",M90=typeof self<"u",PV=!mI0(bI0.default),hI0=!mI0(WB.default),AR=M90&&"caches"in self,yBQ=typeof globalThis.Deno<"u",kz8=typeof globalThis.Bun<"u",CR=yBQ&&AR&&!PV,_I0=typeof process<"u",fI0=_I0&&process?.release?.name==="node"&&!CR,L90=typeof window<"u"&&typeof window.document<"u",O90=M90&&["DedicatedWorkerGlobalScope","ServiceWorkerGlobalScope","SharedWorkerGlobalScope"].includes(self.constructor?.name),vBQ=L90||O90||CR,xBQ=fI0||typeof navigator<"u"&&"gpu"in navigator,bBQ=typeof navigator<"u"&&"ml"in navigator,gBQ=typeof crypto<"u"&&typeof crypto.getRandomValues==="function",hBQ=typeof chrome<"u"&&typeof chrome.runtime<"u"&&typeof chrome.runtime.id==="string",_BQ=typeof ServiceWorkerGlobalScope<"u"&&M90&&self instanceof ServiceWorkerGlobalScope,fBQ=()=>{if(typeof navigator>"u")return!1;let Q=navigator.userAgent,G=(navigator.vendor||"").indexOf("Apple")>-1,H=!Q.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!Q.includes("Chrome")&&!Q.includes("Android");return G&&H},mBQ=fBQ(),Y6=Object.freeze({IS_BROWSER_ENV:L90,IS_WEBWORKER_ENV:O90,IS_WEB_ENV:vBQ,IS_SERVICE_WORKER_ENV:_BQ,IS_DENO_WEB_RUNTIME:CR,IS_WEB_CACHE_AVAILABLE:AR,IS_WEBGPU_AVAILABLE:xBQ,IS_WEBNN_AVAILABLE:bBQ,IS_SAFARI:mBQ,IS_PROCESS_AVAILABLE:_I0,IS_NODE_ENV:fI0,IS_FS_AVAILABLE:PV,IS_PATH_AVAILABLE:hI0,IS_CRYPTO_AVAILABLE:gBQ,IS_CHROME_AVAILABLE:hBQ}),P90=PV&&hI0,KR="./";if(P90){let Q="file:///C:/mcp-tools-for-obsidian.ts";if(Q)KR=WB.default.dirname(WB.default.dirname(gI0.default.fileURLToPath(Q)));else KR=WB.default.dirname("/")}var uBQ=P90?WB.default.join(KR,"/.cache/"):null,BC0="/models/",pBQ=P90?WB.default.join(KR,BC0):BC0,lBQ=typeof globalThis.fetch==="function"?globalThis.fetch.bind(globalThis):void 0,yG=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),AC0=yG.WARNING,A6={version:kBQ,backends:{onnx:{}},get logLevel(){return AC0},set logLevel(Q){AC0=Q,A6.backends.onnx?.setLogLevel?.(Q)},allowRemoteModels:!0,remoteHost:"https://huggingface.co/",remotePathTemplate:"{model}/resolve/{revision}/",allowLocalModels:!(L90||O90||CR),localModelPath:pBQ,useFS:PV,useBrowserCache:AR,useFSCache:PV,cacheDir:uBQ,useCustomCache:!1,customCache:null,useWasmCache:AR||PV,cacheKey:"transformers-cache",experimental_useCrossOriginStorage:!1,fetch:lBQ};function mI0(Q){return Object.keys(Q).length===0}var nJ=class{constructor(){let Q=function(...J){return Q._call(...J)};return Object.setPrototypeOf(Q,new.target.prototype)}_call(...Q){throw Error("Must implement _call method in subclass")}};function UH(Q,J){if(Q)Q(J)}var J90=class extends nJ{constructor(Q,J){super();this.callback=Q,this.files_loading=J}_call(Q){if(Q.status==="progress"){this.files_loading[Q.file]={loaded:Q.loaded,total:Q.total};let J=Object.values(this.files_loading).reduce((K,z)=>K+z.loaded,0),G=Object.values(this.files_loading).reduce((K,z)=>K+z.total,0),H=G>0?J/G*100:0;this.callback({status:"progress_total",name:Q.name,progress:H,loaded:J,total:G,files:structuredClone(this.files_loading)})}this.callback(Q)}};function dBQ(Q){return Number.isInteger(Q)||typeof Q==="bigint"}function KC0(Q){return Q===null||Q===void 0||Q===-1}function zC0(Q){let J=[],G=Q;while(Array.isArray(G))J.push(G.length),G=G[0];return J}function yW(...Q){return Array.prototype.concat.apply([],Q)}function cBQ(...Q){return Q.reduce((J,G)=>J.flatMap((H)=>G.map((K)=>[H,K])))}function zR(Q,J){return Math.abs((Q+J)%(2*J)-J)}function JX(Q,J){return Object.assign({},...J.map((G)=>{if(Q[G]!==void 0)return{[G]:Q[G]}}))}function iBQ(Q,J){let G=0;for(let H of Q)if(H===J)++G;return G}var g8={error(...Q){if(A6.logLevel<=yG.ERROR)console.error(...Q)},warn(...Q){if(A6.logLevel<=yG.WARNING)console.warn(...Q)},info(...Q){if(A6.logLevel<=yG.INFO)console.log(...Q)},debug(...Q){if(A6.logLevel<=yG.DEBUG)console.log(...Q)},log(...Q){this.info(...Q)}},oBQ=class{constructor(Q){this.trie=this._build_trie(Q)}_build_trie(Q){let J=Object.create(null);for(let G of Q){let H=J;for(let K=0;K<G.length;++K){let z=G[K];H=H[z]??=Object.create(null)}H.end=G}return J}split(Q){let J=[],G=Q.length,H=0,K=0;while(K<G){let z=this.trie,q=null,F=K;while(F<G&&(z=z[Q[F]])){if(z.end)q=z.end;++F}if(q){if(K>H)J.push(Q.slice(H,K));J.push(q),K+=q.length,H=K}else++K}if(H<G)J.push(Q.slice(H));return J}},VC0=oBQ,nBQ=class{constructor(Q){this.content=Q.content,this.id=Q.id,this.single_word=Q.single_word??!1,this.lstrip=Q.lstrip??!1,this.rstrip=Q.rstrip??!1,this.special=Q.special??!1,this.normalized=Q.normalized??!this.special}},aBQ=nBQ,uI0=(()=>{let Q=[...Array.from({length:94},(K,z)=>z+33),...Array.from({length:"¬".charCodeAt(0)-"¡".charCodeAt(0)+1},(K,z)=>z+"¡".charCodeAt(0)),...Array.from({length:"ÿ".charCodeAt(0)-"®".charCodeAt(0)+1},(K,z)=>z+"®".charCodeAt(0))],J=Q.slice(),G=0;for(let K=0;K<256;++K)if(!Q.includes(K))Q.push(K),J.push(256+G),G+=1;let H=J.map((K)=>String.fromCharCode(K));return Object.fromEntries(Q.map((K,z)=>[K,H[z]]))})(),sBQ=(Q)=>Object.fromEntries(Object.entries(Q).map(([J,G])=>[G,J])),rBQ=sBQ(uI0),qC0=".,!?…。,、।۔،",tBQ=new Map([["(?i:'s|'t|'re|'ve|'m|'ll|'d)","(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))"],["(?i:[sdmt]|ll|ve|re)","(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])"],["[^\\r\\n\\p{L}\\p{N}]?+","[^\\r\\n\\p{L}\\p{N}]?"],["[^\\s\\p{L}\\p{N}]++","[^\\s\\p{L}\\p{N}]+"],["(?>\\p{Nd}{510})","(?:\\p{Nd}{510})"],["\\p{Nd}{3}+","(?:\\p{Nd}{3})+"],["\\G",""],[` ?[^(\\s|[${qC0}])]+`,` ?[^\\s${qC0}]+`]]),VR="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",N90=(Q)=>Q.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"),IR=(Q,J=!0)=>{if(Q.Regex!==void 0){let G=Q.Regex.replace(/\\([#&~])/g,"$1");G=G.replace(/\\A/g,"^").replace(/\\z/g,"$").replace(/\\Z/g,"(?=\\r?\\n?$)");for(let[H,K]of tBQ)G=G.replaceAll(H,K);try{return new RegExp(G,"gu")}catch(H){if(!(H instanceof SyntaxError)||!H.message.toLowerCase().includes("invalid property name"))throw H;let K=!1,z=G.replace(/(\\[pP])\{([^}=]+)\}/g,(q,F,D)=>{try{return new RegExp(`\\p{${D}}`,"u"),`${F}{${D}}`}catch{return K=!0,`${F}{Script=${D}}`}});if(!K)throw H;try{return new RegExp(z,"gu")}catch(q){throw H}}}else if(Q.String!==void 0){let G=eBQ(Q.String);return new RegExp(J?G:`(${G})`,"gu")}else return console.warn("Unknown pattern type:",Q),null},eBQ=(Q)=>Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),QAQ=(Q,J,G)=>{let H=[],K=0;while(K<Q.length){if(H.push(Q[K]),(J.get(Q[K])??G)!==G){++K;continue}while(++K<Q.length&&(J.get(Q[K])??G)===G)if(J.get(H.at(-1))!==G)H[H.length-1]+=Q[K]}return H},XAQ=(Q)=>Q>=19968&&Q<=40959||Q>=13312&&Q<=19903||Q>=131072&&Q<=173791||Q>=173824&&Q<=177983||Q>=177984&&Q<=178207||Q>=178208&&Q<=183983||Q>=63744&&Q<=64255||Q>=194560&&Q<=195103,JAQ=(Q)=>Number.isInteger(Q)||typeof Q==="bigint",YAQ=(Q)=>{let J=0;for(let G of Q)++J;return J},GAQ=(Q)=>pI0(Q.toLowerCase()),vG=(...Q)=>Array.prototype.concat.apply([],Q),j90=(Q)=>new Map(Object.entries(Q)),WAQ=(Q,J)=>{let G=[],H=0;for(let K of Q.matchAll(J)){let z=K[0];if(H<K.index)G.push(Q.slice(H,K.index));if(z.length>0)G.push(z);H=K.index+z.length}if(H<Q.length)G.push(Q.slice(H));return G},pI0=(Q)=>Q.replace(/\p{M}/gu,""),UC0=(Q,J,G=[])=>{if(!Q||Array.isArray(Q)||typeof Q!=="object")return`${J} must be a valid object`;for(let H of G)if(!(H in Q))return`${J} must contain a "${H}" property`;return null},HAQ=(Q)=>Q.match(/\S+/g)||[],BAQ=class{constructor(){let Q=function(...J){return Q._call(...J)};return Object.setPrototypeOf(Q,new.target.prototype)}},fF=BAQ,AAQ=class extends fF{constructor(Q){super();this.config=Q}_call(Q){return this.normalize(Q)}},f5=AAQ,KAQ=class extends f5{tokenize_chinese_chars(Q){let J=[];for(let G=0;G<Q.length;++G){let H=Q[G],K=H.charCodeAt(0);if(XAQ(K))J.push(" "),J.push(H),J.push(" ");else J.push(H)}return J.join("")}strip_accents(Q){return Q.normalize("NFD").replace(/\p{Mn}/gu,"")}is_control(Q){switch(Q){case"\t":case`
`:case"\r":return!1;default:return/^\p{Cc}|\p{Cf}|\p{Co}|\p{Cs}$/u.test(Q)}}clean_text(Q){let J=[];for(let G of Q){let H=G.charCodeAt(0);if(H===0||H===65533||this.is_control(G))continue;if(/^\s$/.test(G))J.push(" ");else J.push(G)}return J.join("")}normalize(Q){if(this.config.clean_text)Q=this.clean_text(Q);if(this.config.handle_chinese_chars)Q=this.tokenize_chinese_chars(Q);if(this.config.lowercase){if(Q=Q.toLowerCase(),this.config.strip_accents!==!1)Q=this.strip_accents(Q)}else if(this.config.strip_accents)Q=this.strip_accents(Q);return Q}},zAQ=KAQ,VAQ=class extends f5{constructor(Q){super(Q);this.charsmap=Q.precompiled_charsmap??null}normalize(Q){if(Q=Q.replace(/[\u0001-\u0008\u000B\u000E-\u001F\u007F\u008F\u009F]/gm,""),Q=Q.replace(/[\u0009\u000A\u000C\u000D\u00A0\u1680\u2000-\u200F\u2028\u2029\u202F\u205F\u2581\u3000\uFEFF\uFFFD]/gm," "),Q.includes(""))Q=Q.split("").map((G)=>G.normalize("NFKC")).join("");else Q=Q.normalize("NFKC");return Q}},qAQ=VAQ,UAQ=class extends f5{constructor(Q){super(Q);this.normalizers=(Q.normalizers??[]).map((J)=>lI0(J))}normalize(Q){return this.normalizers.reduce((J,G)=>{return G?G.normalize(J):J},Q)}},$AQ=UAQ,ZAQ=class extends f5{normalize(Q){let J=IR(this.config.pattern??{});return J===null?Q:Q.replaceAll(J,this.config.content??"")}},FAQ=ZAQ,DAQ=class extends f5{constructor(){super(...arguments);this.form="NFC"}normalize(Q){return Q=Q.normalize(this.form),Q}},RR=DAQ,MAQ=class extends RR{constructor(){super(...arguments);this.form="NFC"}},LAQ=MAQ,OAQ=class extends RR{constructor(){super(...arguments);this.form="NFD"}},PAQ=OAQ,NAQ=class extends RR{constructor(){super(...arguments);this.form="NFKC"}},jAQ=NAQ,CAQ=class extends RR{constructor(){super(...arguments);this.form="NFKD"}},IAQ=CAQ,RAQ=class extends f5{normalize(Q){if(this.config.strip_left&&this.config.strip_right)Q=Q.trim();else{if(this.config.strip_left)Q=Q.trimStart();if(this.config.strip_right)Q=Q.trimEnd()}return Q}},wAQ=RAQ,EAQ=class extends f5{normalize(Q){return pI0(Q)}},SAQ=EAQ,TAQ=class extends f5{normalize(Q){return Q.toLowerCase()}},kAQ=TAQ,yAQ=class extends f5{normalize(Q){return Q=this.config.prepend+Q,Q}},vAQ=yAQ;function xAQ(Q){if(Q===null)return null;switch(Q.type){case"BertNormalizer":return new zAQ(Q);case"Precompiled":return new qAQ(Q);case"Sequence":return new $AQ(Q);case"Replace":return new FAQ(Q);case"NFC":return new LAQ(Q);case"NFD":return new PAQ(Q);case"NFKC":return new jAQ(Q);case"NFKD":return new IAQ(Q);case"Strip":return new wAQ(Q);case"StripAccents":return new SAQ(Q);case"Lowercase":return new kAQ(Q);case"Prepend":return new vAQ(Q);default:throw Error(`Unknown Normalizer type: ${Q.type}`)}}var lI0=xAQ,bAQ=class extends fF{pre_tokenize(Q,J){return(Array.isArray(Q)?Q.map((G)=>this.pre_tokenize_text(G,J)):this.pre_tokenize_text(Q,J)).flat()}_call(Q,J){return this.pre_tokenize(Q,J)}},hG=bAQ,gAQ=class extends hG{constructor(Q){super();this.config=Q,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=uI0,this.text_encoder=new TextEncoder}pre_tokenize_text(Q,J){if(this.add_prefix_space&&!Q.startsWith(" "))Q=" "+Q;return(this.use_regex?Q.match(this.pattern)||[]:[Q]).map((H)=>Array.from(this.text_encoder.encode(H),(K)=>this.byte_encoder[K]).join(""))}},hAQ=gAQ,_AQ=class extends hG{pre_tokenize_text(Q,J){return Q.match(/\w+|[^\w\s]+/g)||[]}},fAQ=_AQ,mAQ=class extends hG{constructor(Q){super();this.replacement=Q.replacement??"▁",this.str_rep=Q.str_rep||this.replacement,this.prepend_scheme=Q.prepend_scheme??"always"}pre_tokenize_text(Q,J){let{section_index:G=void 0}=J??{},H=Q.replaceAll(" ",this.str_rep);if(!H.startsWith(this.replacement)&&(this.prepend_scheme==="always"||this.prepend_scheme==="first"&&G===0))H=this.str_rep+H;return[H]}},uAQ=mAQ,pAQ=class extends hG{constructor(Q){super();this.config=Q,this.pattern=IR(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(Q){if(this.pattern===null)return[];if(this.config.invert)return Q.match(this.pattern)||[];else if(this.config.behavior?.toLowerCase()==="removed")return Q.split(this.pattern).filter((J)=>J);else return WAQ(Q,this.pattern)}},lAQ=pAQ,dAQ=class extends hG{constructor(Q){super();this.config=Q,this.pattern=new RegExp(`[^${VR}]+|[${VR}]+`,"gu")}pre_tokenize_text(Q){return Q.match(this.pattern)||[]}},cAQ=dAQ,iAQ=class extends hG{constructor(Q){super();this.config=Q;let J=`[^\\d]+|\\d${this.config.individual_digits?"":"+"}`;this.pattern=new RegExp(J,"gu")}pre_tokenize_text(Q){return Q.match(this.pattern)||[]}},oAQ=iAQ,nAQ=class extends hG{constructor(){super();this.pattern=new RegExp(`[^\\s${VR}]+|[${VR}]`,"gu")}pre_tokenize_text(Q,J){return Q.trim().match(this.pattern)||[]}},aAQ=nAQ,sAQ=class extends hG{constructor(Q){super();this.config=Q,this.pattern=IR(this.config.pattern??{}),this.content=this.config.content??""}pre_tokenize_text(Q){if(this.pattern===null)return[Q];return[Q.replaceAll(this.pattern,this.config.content??"")]}},rAQ=sAQ,tAQ=class extends hG{constructor(Q){super();this.tokenizers=(Q.pretokenizers??[]).map((J)=>dI0(J))}pre_tokenize_text(Q,J){return this.tokenizers.reduce((G,H)=>{return H?H.pre_tokenize(G,J):G},[Q])}},eAQ=tAQ,QKQ=class extends hG{pre_tokenize_text(Q){return HAQ(Q)}},XKQ=QKQ,JKQ=class extends hG{constructor(Q){super();this.config=Q,this._length=Q.length}pre_tokenize_text(Q){let J=[];for(let G=0;G<Q.length;G+=this._length)J.push(Q.slice(G,G+this._length));return J}},YKQ=JKQ;function GKQ(Q){if(Q===null)return null;switch(Q.type){case"BertPreTokenizer":return new aAQ;case"Sequence":return new eAQ(Q);case"Whitespace":return new fAQ;case"WhitespaceSplit":return new XKQ;case"Metaspace":return new uAQ(Q);case"ByteLevel":return new hAQ(Q);case"Split":return new lAQ(Q);case"Punctuation":return new cAQ(Q);case"Digits":return new oAQ(Q);case"Replace":return new rAQ(Q);case"FixedLength":return new YKQ(Q);default:throw Error(`Unknown PreTokenizer type: ${Q.type}`)}}var dI0=GKQ,WKQ=class extends fF{constructor(Q){super();this.config=Q,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}_call(Q){let J=this.encode(Q);if(this.fuse_unk)J=QAQ(J,this.tokens_to_ids,this.unk_token_id);return J}},wR=WKQ,HKQ=class extends wR{constructor(Q){super(Q);this.max_input_chars_per_word=100,this.tokens_to_ids=j90(Q.vocab),this.unk_token_id=this.tokens_to_ids.get(Q.unk_token),this.unk_token=Q.unk_token,this.max_input_chars_per_word=Q.max_input_chars_per_word??100,this.vocab=Array(this.tokens_to_ids.size);for(let[J,G]of this.tokens_to_ids)this.vocab[G]=J}encode(Q){let J=[];for(let G of Q){let H=[...G];if(H.length>this.max_input_chars_per_word){J.push(this.unk_token);continue}let K=!1,z=0,q=[];while(z<H.length){let F=H.length,D=null;while(z<F){let V=H.slice(z,F).join("");if(z>0)V=this.config.continuing_subword_prefix+V;if(this.tokens_to_ids.has(V)){D=V;break}--F}if(D===null){K=!0;break}q.push(D),z=F}if(K)J.push(this.unk_token);else J.push(...q)}return J}},$C0=HKQ,ZC0=class Q{constructor(J,G){this.is_leaf=J,this.children=G}static default(){return new Q(!1,new Map)}},BKQ=class{constructor(){this.root=ZC0.default()}extend(Q){for(let J of Q)this.push(J)}push(Q){let J=this.root;for(let G of Q){let H=J.children.get(G);if(H===void 0)H=ZC0.default(),J.children.set(G,H);J=H}J.is_leaf=!0}*common_prefix_search(Q){let J=this.root;if(J===void 0)return;let G="";for(let H of Q){if(G+=H,J=J.children.get(H),J===void 0)return;if(J.is_leaf)yield G}}},AKQ=BKQ,C60=class Q{constructor(J,G,H,K,z){this.token_id=J,this.node_id=G,this.pos=H,this.length=K,this.score=z,this.prev=null,this.backtrace_score=0}clone(){let J=new Q(this.token_id,this.node_id,this.pos,this.length,this.score);return J.prev=this.prev,J.backtrace_score=this.backtrace_score,J}},KKQ=class{constructor(Q,J,G){this.chars=Array.from(Q),this.len=this.chars.length,this.bos_token_id=J,this.eos_token_id=G,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let H=new C60(this.bos_token_id??0,0,0,0,0),K=new C60(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(H.clone()),this.nodes.push(K.clone()),this.begin_nodes[this.len].push(K),this.end_nodes[0].push(H)}insert(Q,J,G,H){let K=this.nodes.length,z=new C60(H,K,Q,J,G);this.begin_nodes[Q].push(z),this.end_nodes[Q+J].push(z),this.nodes.push(z)}viterbi(){let Q=this.len,J=0;while(J<=Q){if(this.begin_nodes[J].length==0)return[];for(let q of this.begin_nodes[J]){q.prev=null;let F=0,D=null;for(let V of this.end_nodes[J]){let O=V.backtrace_score+q.score;if(D===null||O>F)D=V.clone(),F=O}if(D!==null)q.prev=D,q.backtrace_score=F;else return[]}++J}let G=[],K=this.begin_nodes[Q][0].prev;if(K===null)return[];let z=K.clone();while(z.prev!==null)G.push(z.clone()),z=z.clone().prev.clone();return G.reverse(),G}piece(Q){return this.chars.slice(Q.pos,Q.pos+Q.length).join("")}tokens(){return this.viterbi().map((J)=>this.piece(J))}token_ids(){return this.viterbi().map((J)=>J.token_id)}},zKQ=KKQ;function VKQ(Q){if(Q.length===0)throw Error("Array must not be empty");let J=Q[0],G=0;for(let H=1;H<Q.length;++H)if(Q[H]<J)J=Q[H],G=H;return[J,G]}var qKQ=class extends wR{constructor(Q,J){super(Q);let G=Q.vocab.length;this.vocab=Array(G),this.scores=Array(G);for(let H=0;H<G;++H)[this.vocab[H],this.scores[H]]=Q.vocab[H];this.unk_token_id=Q.unk_id,this.unk_token=this.vocab[Q.unk_id],this.tokens_to_ids=new Map(this.vocab.map((H,K)=>[H,K])),this.bos_token=" ",this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=J,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=VKQ(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new AKQ,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(Q){let J=Q.chars,G=1,H=0;while(H<J.length){let K=!1,z=[],q=J.slice(H).join(""),F=this.trie.common_prefix_search(q);for(let D of F){z.push(D);let V=this.tokens_to_ids.get(D),O=this.scores[V],P=YAQ(D);if(Q.insert(H,P,O,V),!K&&P===1)K=!0}if(!K)Q.insert(H,1,this.unk_score,this.unk_token_id);H+=1}}tokenize(Q){let J=new zKQ(Q,this.bos_token_id,this.eos_token_id);return this.populate_nodes(J),J.tokens()}encode(Q){let J=[];for(let G of Q){let H=this.tokenize(G);J.push(...H)}return J}},FC0=qKQ,UKQ=class{constructor(Q=(G,H)=>G>H,J=1/0){this._heap=[],this._comparator=Q,this._max_size=J}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...Q){return this.extend(Q)}extend(Q){for(let J of Q)if(this.size<this._max_size)this._heap.push(J),this._sift_up();else{let G=this._smallest();if(this._comparator(J,this._heap[G]))this._heap[G]=J,this._sift_up_from(G)}return this.size}pop(){let Q=this.peek(),J=this.size-1;if(J>0)this._swap(0,J);return this._heap.pop(),this._sift_down(),Q}replace(Q){let J=this.peek();return this._heap[0]=Q,this._sift_down(),J}_parent(Q){return(Q+1>>>1)-1}_left(Q){return(Q<<1)+1}_right(Q){return Q+1<<1}_greater(Q,J){return this._comparator(this._heap[Q],this._heap[J])}_swap(Q,J){let G=this._heap[Q];this._heap[Q]=this._heap[J],this._heap[J]=G}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(Q){while(Q>0&&this._greater(Q,this._parent(Q)))this._swap(Q,this._parent(Q)),Q=this._parent(Q)}_sift_down(){let Q=0;while(this._left(Q)<this.size&&this._greater(this._left(Q),Q)||this._right(Q)<this.size&&this._greater(this._right(Q),Q)){let J=this._right(Q)<this.size&&this._greater(this._right(Q),this._left(Q))?this._right(Q):this._left(Q);this._swap(Q,J),Q=J}}_smallest(){return 2**Math.floor(Math.log2(this.size))-1}},$KQ=UKQ,ZKQ=class{constructor(Q){this.capacity=Q,this.cache=new Map}get(Q){if(!this.cache.has(Q))return;let J=this.cache.get(Q);return this.cache.delete(Q),this.cache.set(Q,J),J}put(Q,J){if(this.cache.has(Q))this.cache.delete(Q);if(this.cache.set(Q,J),this.cache.size>this.capacity)this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},FKQ=ZKQ,DKQ=class extends wR{constructor(Q){super(Q);this.tokens_to_ids=j90(Q.vocab),this.unk_token_id=this.tokens_to_ids.get(Q.unk_token),this.unk_token=Q.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[G,H]of this.tokens_to_ids)this.vocab[H]=G;let J=Array.isArray(Q.merges[0]);if(this.merges=J?Q.merges:Q.merges.map((G)=>G.split(" ",2)),this.bpe_ranks=new Map(this.merges.map((G,H)=>[JSON.stringify(G),H])),this.end_of_word_suffix=Q.end_of_word_suffix,this.continuing_subword_suffix=Q.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.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new FKQ(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(Q){if(Q.length===0)return[];let J=this.cache.get(Q);if(J!==void 0)return J;let G=Array.from(Q);if(this.end_of_word_suffix)G[G.length-1]+=this.end_of_word_suffix;let H=[];if(G.length>1){let K=new $KQ((F,D)=>F.score<D.score),z={token:G[0],bias:0,prev:null,next:null},q=z;for(let F=1;F<G.length;++F){let D={bias:F/G.length,token:G[F],prev:q,next:null};q.next=D,this.add_node(K,q),q=D}while(!K.is_empty()){let F=K.pop();if(F.deleted||!F.next||F.next.deleted)continue;if(F.deleted=!0,F.next.deleted=!0,F.prev){let V={...F.prev};if(F.prev.deleted=!0,F.prev=V,V.prev)V.prev.next=V;else z=V}let D={token:F.token+F.next.token,bias:F.bias,prev:F.prev,next:F.next.next};if(D.prev)D.prev.next=D,this.add_node(K,D.prev);else z=D;if(D.next)D.next.prev=D,this.add_node(K,D)}for(let F=z;F!==null;F=F.next)H.push(F.token)}else H=G;if(this.continuing_subword_suffix)for(let K=0;K<H.length-1;++K)H[K]+=this.continuing_subword_suffix;if(Q.length<this.max_length_to_cache)this.cache.put(Q,H);return H}add_node(Q,J){let G=this.bpe_ranks.get(JSON.stringify([J.token,J.next.token]));if(G!==void 0)J.score=G+J.bias,Q.push(J)}encode(Q){let J=[];for(let G of Q){if(this.ignore_merges&&this.tokens_to_ids.has(G)){J.push(G);continue}let H=this.bpe(G);for(let K of H)if(this.tokens_to_ids.has(K))J.push(K);else if(this.byte_fallback){let z=Array.from(this.text_encoder.encode(K)).map((q)=>`<0x${q.toString(16).toUpperCase().padStart(2,"0")}>`);if(z.every((q)=>this.tokens_to_ids.has(q)))J.push(...z);else if(this.unk_token!=null)J.push(this.unk_token)}else if(this.unk_token!=null)J.push(this.unk_token)}return J}},DC0=DKQ,MKQ=class extends wR{constructor(Q,J){super(Q);let G=Q.vocab;this.tokens_to_ids=j90(J.target_lang?G[J.target_lang]:G),this.bos_token=J.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=J.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=J.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=J.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[H,K]of this.tokens_to_ids)this.vocab[K]=H}encode(Q){return Q}},LKQ=MKQ;function OKQ(Q,J){switch(Q.type){case"WordPiece":return new $C0(Q);case"Unigram":return new FC0(Q,J.eos_token);case"BPE":return new DC0(Q);default:if(Q.vocab)if(Array.isArray(Q.vocab))return new FC0(Q,J.eos_token);else if(Object.hasOwn(Q,"continuing_subword_prefix")&&Object.hasOwn(Q,"unk_token"))if(Object.hasOwn(Q,"merges"))return new DC0(Q);else return new $C0(Q);else return new LKQ(Q,{target_lang:J.target_lang,bos_token:J.bos_token,eos_token:J.eos_token,pad_token:J.pad_token,unk_token:J.unk_token});throw Error(`Unknown TokenizerModel type: ${Q?.type}`)}}var PKQ=OKQ,NKQ=class extends fF{constructor(Q){super();this.config=Q}_call(Q,...J){return this.post_process(Q,...J)}},mF=NKQ,jKQ=class extends mF{post_process(Q,J=null,G=!0){let H=J===null?this.config.single:this.config.pair,K=[],z=[];for(let q of H)if("SpecialToken"in q){if(G)K.push(q.SpecialToken.id),z.push(q.SpecialToken.type_id)}else if("Sequence"in q){if(q.Sequence.id==="A")K=vG(K,Q),z=vG(z,Array(Q.length).fill(q.Sequence.type_id));else if(q.Sequence.id==="B")K=vG(K,J),z=vG(z,Array(J.length).fill(q.Sequence.type_id))}return{tokens:K,token_type_ids:z}}},CKQ=jKQ,IKQ=class extends mF{post_process(Q,J=null){return{tokens:Q,tokens_pair:J}}},RKQ=IKQ,wKQ=class extends mF{constructor(Q){super(Q);this.sep=Q.sep,this.cls=Q.cls}post_process(Q,J=null,G=!0){if(G)Q=vG([this.cls[0]],Q,[this.sep[0]]);let H=Array(Q.length).fill(0);if(J){let K=[],z=G?[this.sep[0]]:[];Q=vG(Q,K,J,z),H=vG(H,Array(J.length+K.length+z.length).fill(1))}return{tokens:Q,token_type_ids:H}}},EKQ=wKQ,SKQ=class extends mF{constructor(Q){super(Q);this.sep=Q.sep,this.cls=Q.cls}post_process(Q,J,G=!0){if(G)Q=vG([this.cls[0]],Q,[this.sep[0]]);let H=Array(Q.length).fill(0);if(J){let K=G?[this.sep[0]]:[],z=G?[this.sep[0]]:[];Q=vG(Q,K,J,z),H=vG(H,Array(J.length+K.length+z.length).fill(1))}return{tokens:Q,token_type_ids:H}}},TKQ=SKQ,kKQ=class extends mF{constructor(Q){super(Q);this.processors=(Q.processors??[]).map((J)=>cI0(J))}post_process(Q,J=null,G=!0){let H={tokens:Q,tokens_pair:J};for(let K of this.processors)H=K.post_process(H.tokens,H.tokens_pair,G);return H}},yKQ=kKQ;function vKQ(Q){if(Q===null)return null;switch(Q.type){case"TemplateProcessing":return new CKQ(Q);case"ByteLevel":return new RKQ(Q);case"BertProcessing":return new EKQ(Q);case"RobertaProcessing":return new TKQ(Q);case"Sequence":return new yKQ(Q);default:throw Error(`Unknown PostProcessor type: ${Q.type}`)}}var cI0=vKQ,xKQ=class extends fF{constructor(Q){super();this.config=Q,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets="trim_offsets"in Q?Q.trim_offsets:!1}_call(Q){return this.decode(Q)}decode(Q){return this.decode_chain(Q).join("")}},_G=xKQ,bKQ=class extends _G{constructor(Q){super(Q);this.byte_decoder=rBQ,this.text_decoder=new TextDecoder("utf-8",{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(Q){let J=Q.join(""),G=new Uint8Array([...J].map((H)=>this.byte_decoder[H]));return this.text_decoder.decode(G)}decode_chain(Q){let J=[],G=[];for(let H of Q)if(this.added_tokens.find((K)=>K.content===H)!==void 0){if(G.length>0)J.push(this.convert_tokens_to_string(G)),G=[];J.push(H)}else G.push(H);if(G.length>0)J.push(this.convert_tokens_to_string(G));return J}},gKQ=bKQ,hKQ=class extends _G{constructor(Q){super(Q);this.cleanup=Q.cleanup}decode_chain(Q){return Q.map((J,G)=>{if(G!==0){let H=this.config.prefix;if(H&&J.startsWith(H))J=J.replace(H,"");else J=" "+J}if(this.cleanup)J=N90(J);return J})}},_KQ=hKQ,fKQ=class extends _G{constructor(Q){super(Q);this.replacement=Q.replacement??"▁"}decode_chain(Q){let J=[];for(let G=0;G<Q.length;++G){let H=Q[G].replaceAll(this.replacement," ");if(G==0&&H.startsWith(" "))H=H.substring(1);J.push(H)}return J}},mKQ=fKQ,uKQ=class extends _G{constructor(Q){super(Q);this.suffix=Q.suffix??""}decode_chain(Q){return Q.map((J,G)=>{return J.replaceAll(this.suffix,G===Q.length-1?"":" ")})}},pKQ=uKQ,lKQ=class extends _G{constructor(Q){super(Q);this.pad_token=Q.pad_token??"",this.word_delimiter_token=Q.word_delimiter_token??"",this.cleanup=Q.cleanup}convert_tokens_to_string(Q){if(Q.length===0)return"";let J=[Q[0]];for(let K=1;K<Q.length;++K)if(Q[K]!==J.at(-1))J.push(Q[K]);let H=J.filter((K)=>K!==this.pad_token).join("");if(this.cleanup)H=N90(H).replaceAll(this.word_delimiter_token," ").trim();return H}decode_chain(Q){return[this.convert_tokens_to_string(Q)]}},dKQ=lKQ,cKQ=class extends _G{constructor(Q){super(Q);this.decoders=(Q.decoders??[]).map((J)=>iI0(J))}decode_chain(Q){return this.decoders.reduce((J,G)=>{return G.decode_chain(J)},Q)}},iKQ=cKQ,oKQ=class extends _G{decode_chain(Q){let J=IR(this.config.pattern),G=this.config.content??"";return J===null?Q:Q.map((H)=>H.replaceAll(J,G))}},nKQ=oKQ,aKQ=class extends _G{decode_chain(Q){return[Q.join("")]}},sKQ=aKQ,rKQ=class extends _G{constructor(Q){super(Q);this.content=Q.content??"",this.start=Q.start??0,this.stop=Q.stop??0}decode_chain(Q){return Q.map((J)=>{let G=0;for(let K=0;K<this.start;++K)if(J[K]===this.content){G=K+1;continue}else break;let H=J.length;for(let K=0;K<this.stop;++K){let z=J.length-K-1;if(J[z]===this.content){H=z;continue}else break}return J.slice(G,H)})}},tKQ=rKQ,eKQ=class extends _G{constructor(Q){super(Q);this.text_decoder=new TextDecoder}decode_chain(Q){let J=[],G=[];for(let H of Q){let K=null;if(H.length===6&&H.startsWith("<0x")&&H.endsWith(">")){let z=parseInt(H.slice(3,5),16);if(!isNaN(z))K=z}if(K!==null)G.push(K);else{if(G.length>0){let z=this.text_decoder.decode(Uint8Array.from(G));J.push(z),G=[]}J.push(H)}}if(G.length>0){let H=this.text_decoder.decode(Uint8Array.from(G));J.push(H),G=[]}return J}},QzQ=eKQ;function XzQ(Q){if(Q===null)return null;switch(Q.type){case"ByteLevel":return new gKQ(Q);case"WordPiece":return new _KQ(Q);case"Metaspace":return new mKQ(Q);case"BPEDecoder":return new pKQ(Q);case"CTC":return new dKQ(Q);case"Sequence":return new iKQ(Q);case"Replace":return new nKQ(Q);case"Fuse":return new sKQ(Q);case"Strip":return new tKQ(Q);case"ByteFallback":return new QzQ(Q);default:throw Error(`Unknown Decoder type: ${Q.type}`)}}var iI0=XzQ,JzQ=class{constructor(Q,J){let G=UC0(Q,"Tokenizer",["model","decoder","post_processor","pre_tokenizer","normalizer"]);if(G)throw Error(G);let H=UC0(J,"Config");if(H)throw Error(H);this.tokenizer=Q,this.config=J,this.normalizer=lI0(this.tokenizer.normalizer),this.pre_tokenizer=dI0(this.tokenizer.pre_tokenizer),this.model=PKQ(this.tokenizer.model,this.config),this.post_processor=cI0(this.tokenizer.post_processor),this.decoder=iI0(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let K=[],z=[];this.added_tokens_map=new Map;for(let q of this.tokenizer.added_tokens){let F=new aBQ(q);if(this.added_tokens.push(F),this.model.tokens_to_ids.set(F.content,F.id),this.model.vocab[F.id]=F.content,F.special)this.special_tokens.push(F.content),this.all_special_ids.push(F.id);if(this.added_tokens_map.set(F.content,F),F.normalized&&this.normalizer!==null){let D=this.normalizer(F.content);z.push(D),this.added_tokens_map.set(D,F)}else K.push(F.content)}if((this.config.additional_special_tokens??[]).forEach((q)=>{if(!this.special_tokens.includes(q))this.special_tokens.push(q)}),this.decoder)this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix;this.splitter_unnormalized=new VC0(K),this.splitter_normalized=new VC0(z),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(Q,{text_pair:J=null,add_special_tokens:G=!0,return_token_type_ids:H=null}={}){let{tokens:K,token_type_ids:z}=this.tokenize_helper(Q,{text_pair:J,add_special_tokens:G}),q=K.map((D)=>this.added_tokens_map.get(D)?.id??this.model.tokens_to_ids.get(D)??this.model.unk_token_id),F={ids:q,tokens:K,attention_mask:Array(q.length).fill(1)};if(H&&z)F.token_type_ids=z;return F}decode(Q,J={}){if(!Array.isArray(Q)||Q.length===0||!JAQ(Q[0]))throw Error("token_ids must be a non-empty array of integers.");let G=Q.map((K)=>this.model.vocab[Number(K)]??this.model.unk_token);if(J.skip_special_tokens)G=G.filter((K)=>!this.special_tokens.includes(K));let H=this.decoder?this.decoder(G):G.join(" ");if(this.decoder&&this.decoder.end_of_word_suffix){if(H=H.replaceAll(this.decoder.end_of_word_suffix," "),J.skip_special_tokens)H=H.trim()}if(J.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)H=N90(H);return H}tokenize(Q,{text_pair:J=null,add_special_tokens:G=!1}={}){return this.tokenize_helper(Q,{text_pair:J,add_special_tokens:G}).tokens}encode_text(Q){if(Q===null)return null;let J=this.splitter_unnormalized.split(Q);return J.forEach((G,H)=>{let K=this.added_tokens_map.get(G);if(K){if(K.lstrip&&H>0)J[H-1]=J[H-1].trimEnd();if(K.rstrip&&H<J.length-1)J[H+1]=J[H+1].trimStart()}}),J.flatMap((G,H)=>{if(G.length===0)return[];if(this.added_tokens_map.has(G))return[G];if(this.remove_space===!0)G=G.trim().split(/\s+/).join(" ");if(this.do_lowercase_and_remove_accent)G=GAQ(G);if(this.normalizer!==null)G=this.normalizer(G);if(G.length===0)return[];let K=this.splitter_normalized.split(G);return K.forEach((z,q)=>{let F=this.added_tokens_map.get(z);if(F){if(F.lstrip&&q>0)K[q-1]=K[q-1].trimEnd();if(F.rstrip&&q<K.length-1)K[q+1]=K[q+1].trimStart()}}),K.flatMap((z)=>{if(z.length===0)return[];if(this.added_tokens_map.has(z))return[z];let q=this.pre_tokenizer!==null?this.pre_tokenizer(z,{section_index:H}):[z];return this.model(q)})})}tokenize_helper(Q,{text_pair:J=null,add_special_tokens:G=!0}){let H=this.encode_text(Q),K=this.encode_text(J||null);return this.post_processor?this.post_processor(H,K,G):{tokens:vG(H??[],K??[])}}token_to_id(Q){return this.model.tokens_to_ids.get(Q)}id_to_token(Q){return this.model.vocab[Q]}get_added_tokens_decoder(){let Q=new Map;for(let J of this.added_tokens)Q.set(J.id,J);return Q}get_vocab(Q=!0){let J=new Map;for(let G=0;G<this.model.vocab.length;++G){let H=this.model.vocab[G];if(Q||!this.added_tokens_map.has(H))J.set(H,G)}return J}},YzQ=JzQ,$Q=Object.freeze({Text:"Text",NumericLiteral:"NumericLiteral",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",Comment:"Comment"}),oY=class{constructor(Q,J){this.value=Q,this.type=J}};function MC0(Q){return/\w/.test(Q)}function OF(Q){return/[0-9]/.test(Q)}function LC0(Q){return/\s/.test(Q)}var GzQ=[["{%",$Q.OpenStatement],["%}",$Q.CloseStatement],["{{",$Q.OpenExpression],["}}",$Q.CloseExpression],["(",$Q.OpenParen],[")",$Q.CloseParen],["{",$Q.OpenCurlyBracket],["}",$Q.CloseCurlyBracket],["[",$Q.OpenSquareBracket],["]",$Q.CloseSquareBracket],[",",$Q.Comma],[".",$Q.Dot],[":",$Q.Colon],["|",$Q.Pipe],["<=",$Q.ComparisonBinaryOperator],[">=",$Q.ComparisonBinaryOperator],["==",$Q.ComparisonBinaryOperator],["!=",$Q.ComparisonBinaryOperator],["<",$Q.ComparisonBinaryOperator],[">",$Q.ComparisonBinaryOperator],["+",$Q.AdditiveBinaryOperator],["-",$Q.AdditiveBinaryOperator],["~",$Q.AdditiveBinaryOperator],["*",$Q.MultiplicativeBinaryOperator],["/",$Q.MultiplicativeBinaryOperator],["%",$Q.MultiplicativeBinaryOperator],["=",$Q.Equals]],WzQ=new Map([["n",`
`],["t","\t"],["r","\r"],["b","\b"],["f","\f"],["v","\v"],["'","'"],['"','"'],["\\","\\"]]);function HzQ(Q,J={}){if(Q.endsWith(`
`))Q=Q.slice(0,-1);if(J.lstrip_blocks)Q=Q.replace(/^[ \t]*({[#%-])/gm,"$1");if(J.trim_blocks)Q=Q.replace(/([#%-]})\n/g,"$1");return Q.replace(/{%\s*(end)?generation\s*%}/gs,"")}function BzQ(Q,J={}){let G=[],H=HzQ(Q,J),K=0,z=0,q=(V)=>{let O="";while(V(H[K])){if(H[K]==="\\"){if(++K,K>=H.length)throw SyntaxError("Unexpected end of input");let P=H[K++],N=WzQ.get(P);if(N===void 0)throw SyntaxError(`Unexpected escaped character: ${P}`);O+=N;continue}if(O+=H[K++],K>=H.length)throw SyntaxError("Unexpected end of input")}return O},F=()=>{let V=G.at(-1);if(V&&V.type===$Q.Text){if(V.value=V.value.trimEnd(),V.value==="")G.pop()}},D=()=>{while(K<H.length&&LC0(H[K]))++K};Q:while(K<H.length){let V=G.at(-1)?.type;if(V===void 0||V===$Q.CloseStatement||V===$Q.CloseExpression||V===$Q.Comment){let P="";while(K<H.length&&!(H[K]==="{"&&(H[K+1]==="%"||H[K+1]==="{"||H[K+1]==="#")))P+=H[K++];if(P.length>0){G.push(new oY(P,$Q.Text));continue}}if(H[K]==="{"&&H[K+1]==="#"){K+=2;let P=H[K]==="-";if(P)++K;let N="";while(H[K]!=="#"||H[K+1]!=="}"){if(K+2>=H.length)throw SyntaxError("Missing end of comment tag");N+=H[K++]}let I=N.endsWith("-");if(I)N=N.slice(0,-1);if(P)F();if(G.push(new oY(N,$Q.Comment)),K+=2,I)D();continue}if(H.slice(K,K+3)==="{%-"){F(),G.push(new oY("{%",$Q.OpenStatement)),K+=3;continue}if(H.slice(K,K+3)==="{{-"){F(),G.push(new oY("{{",$Q.OpenExpression)),z=0,K+=3;continue}if(q(LC0),H.slice(K,K+3)==="-%}"){G.push(new oY("%}",$Q.CloseStatement)),K+=3,D();continue}if(H.slice(K,K+3)==="-}}"){G.push(new oY("}}",$Q.CloseExpression)),K+=3,D();continue}let O=H[K];if(O==="-"||O==="+"){let P=G.at(-1)?.type;if(P===$Q.Text||P===void 0)throw SyntaxError(`Unexpected character: ${O}`);switch(P){case $Q.Identifier:case $Q.NumericLiteral:case $Q.StringLiteral:case $Q.CloseParen:case $Q.CloseSquareBracket:break;default:{++K;let N=q(OF);G.push(new oY(`${O}${N}`,N.length>0?$Q.NumericLiteral:$Q.UnaryOperator));continue}}}for(let[P,N]of GzQ){if(P==="}}"&&z>0)continue;if(H.slice(K,K+P.length)===P){if(G.push(new oY(P,N)),N===$Q.OpenExpression)z=0;else if(N===$Q.OpenCurlyBracket)++z;else if(N===$Q.CloseCurlyBracket)--z;K+=P.length;continue Q}}if(O==="'"||O==='"'){++K;let P=q((N)=>N!==O);G.push(new oY(P,$Q.StringLiteral)),++K;continue}if(OF(O)){let P=q(OF);if(H[K]==="."&&OF(H[K+1])){++K;let N=q(OF);P=`${P}.${N}`}G.push(new oY(P,$Q.NumericLiteral));continue}if(MC0(O)){let P=q(MC0);G.push(new oY(P,$Q.Identifier));continue}throw SyntaxError(`Unexpected character: ${O}`)}return G}var fG=class{type="Statement"},AzQ=class extends fG{constructor(Q){super();this.body=Q}type="Program"},KzQ=class extends fG{constructor(Q,J,G){super();this.test=Q,this.body=J,this.alternate=G}type="If"},zzQ=class extends fG{constructor(Q,J,G,H){super();this.loopvar=Q,this.iterable=J,this.body=G,this.defaultBlock=H}type="For"},VzQ=class extends fG{type="Break"},qzQ=class extends fG{type="Continue"},UzQ=class extends fG{constructor(Q,J,G){super();this.assignee=Q,this.value=J,this.body=G}type="Set"},$zQ=class extends fG{constructor(Q,J,G){super();this.name=Q,this.args=J,this.body=G}type="Macro"},ZzQ=class extends fG{constructor(Q){super();this.value=Q}type="Comment"},MY=class extends fG{type="Expression"},FzQ=class extends MY{constructor(Q,J,G){super();this.object=Q,this.property=J,this.computed=G}type="MemberExpression"},OC0=class extends MY{constructor(Q,J){super();this.callee=Q,this.args=J}type="CallExpression"},zV=class extends MY{constructor(Q){super();this.value=Q}type="Identifier"},RV=class extends MY{constructor(Q){super();this.value=Q}type="Literal"},DzQ=class extends RV{type="IntegerLiteral"},MzQ=class extends RV{type="FloatLiteral"},PC0=class extends RV{type="StringLiteral"},LzQ=class extends RV{type="ArrayLiteral"},NC0=class extends RV{type="TupleLiteral"},OzQ=class extends RV{type="ObjectLiteral"},PF=class extends MY{constructor(Q,J,G){super();this.operator=Q,this.left=J,this.right=G}type="BinaryExpression"},PzQ=class extends MY{constructor(Q,J){super();this.operand=Q,this.filter=J}type="FilterExpression"},NzQ=class extends fG{constructor(Q,J){super();this.filter=Q,this.body=J}type="FilterStatement"},jzQ=class extends MY{constructor(Q,J){super();this.lhs=Q,this.test=J}type="SelectExpression"},CzQ=class extends MY{constructor(Q,J,G){super();this.operand=Q,this.negate=J,this.test=G}type="TestExpression"},IzQ=class extends MY{constructor(Q,J){super();this.operator=Q,this.argument=J}type="UnaryExpression"},RzQ=class extends MY{constructor(Q=void 0,J=void 0,G=void 0){super();this.start=Q,this.stop=J,this.step=G}type="SliceExpression"},wzQ=class extends MY{constructor(Q,J){super();this.key=Q,this.value=J}type="KeywordArgumentExpression"},EzQ=class extends MY{constructor(Q){super();this.argument=Q}type="SpreadExpression"},SzQ=class extends fG{constructor(Q,J,G){super();this.call=Q,this.callerArgs=J,this.body=G}type="CallStatement"},TzQ=class extends MY{constructor(Q,J,G){super();this.condition=Q,this.trueExpr=J,this.falseExpr=G}type="Ternary"};function kzQ(Q){let J=new AzQ([]),G=0;function H(R0,l0){let d0=Q[G++];if(!d0||d0.type!==R0)throw Error(`Parser Error: ${l0}. ${d0.type} !== ${R0}.`);return d0}function K(R0){if(!D(R0))throw SyntaxError(`Expected ${R0}`);++G}function z(){switch(Q[G].type){case $Q.Comment:return new ZzQ(Q[G++].value);case $Q.Text:return V();case $Q.OpenStatement:return O();case $Q.OpenExpression:return P();default:throw SyntaxError(`Unexpected token type: ${Q[G].type}`)}}function q(...R0){return G+R0.length<=Q.length&&R0.every((l0,d0)=>l0===Q[G+d0].type)}function F(...R0){return Q[G]?.type===$Q.OpenStatement&&Q[G+1]?.type===$Q.Identifier&&R0.includes(Q[G+1]?.value)}function D(...R0){return G+R0.length<=Q.length&&R0.every((l0,d0)=>Q[G+d0].type==="Identifier"&&l0===Q[G+d0].value)}function V(){return new PC0(H($Q.Text,"Expected text token").value)}function O(){if(H($Q.OpenStatement,"Expected opening statement token"),Q[G].type!==$Q.Identifier)throw SyntaxError(`Unknown statement, got ${Q[G].type}`);let R0=Q[G].value,l0;switch(R0){case"set":++G,l0=N();break;case"if":++G,l0=I(),H($Q.OpenStatement,"Expected {% token"),K("endif"),H($Q.CloseStatement,"Expected %} token");break;case"macro":++G,l0=R(),H($Q.OpenStatement,"Expected {% token"),K("endmacro"),H($Q.CloseStatement,"Expected %} token");break;case"for":++G,l0=E(),H($Q.OpenStatement,"Expected {% token"),K("endfor"),H($Q.CloseStatement,"Expected %} token");break;case"call":{++G;let d0=null;if(q($Q.OpenParen))d0=f0();let m0=WQ();if(m0.type!=="Identifier")throw SyntaxError("Expected identifier following call statement");let ZQ=f0();H($Q.CloseStatement,"Expected closing statement token");let LQ=[];while(!F("endcall"))LQ.push(z());H($Q.OpenStatement,"Expected '{%'"),K("endcall"),H($Q.CloseStatement,"Expected closing statement token");let h0=new OC0(m0,ZQ);l0=new SzQ(h0,d0,LQ);break}case"break":++G,H($Q.CloseStatement,"Expected closing statement token"),l0=new VzQ;break;case"continue":++G,H($Q.CloseStatement,"Expected closing statement token"),l0=new qzQ;break;case"filter":{++G;let d0=WQ();if(d0 instanceof zV&&q($Q.OpenParen))d0=r(d0);H($Q.CloseStatement,"Expected closing statement token");let m0=[];while(!F("endfilter"))m0.push(z());H($Q.OpenStatement,"Expected '{%'"),K("endfilter"),H($Q.CloseStatement,"Expected '%}'"),l0=new NzQ(d0,m0);break}default:throw SyntaxError(`Unknown statement type: ${R0}`)}return l0}function P(){H($Q.OpenExpression,"Expected opening expression token");let R0=T();return H($Q.CloseExpression,"Expected closing expression token"),R0}function N(){let R0=w(),l0=null,d0=[];if(q($Q.Equals))++G,l0=w();else{H($Q.CloseStatement,"Expected %} token");while(!F("endset"))d0.push(z());H($Q.OpenStatement,"Expected {% token"),K("endset")}return H($Q.CloseStatement,"Expected closing statement token"),new UzQ(R0,l0,d0)}function I(){let R0=T();H($Q.CloseStatement,"Expected closing statement token");let l0=[],d0=[];while(!F("elif","else","endif"))l0.push(z());if(F("elif")){++G,++G;let m0=I();d0.push(m0)}else if(F("else")){++G,++G,H($Q.CloseStatement,"Expected closing statement token");while(!F("endif"))d0.push(z())}return new KzQ(R0,l0,d0)}function R(){let R0=WQ();if(R0.type!=="Identifier")throw SyntaxError("Expected identifier following macro statement");let l0=f0();H($Q.CloseStatement,"Expected closing statement token");let d0=[];while(!F("endmacro"))d0.push(z());return new $zQ(R0,l0,d0)}function w(R0=!1){let l0=R0?WQ:T,d0=[l0()],m0=q($Q.Comma);while(m0)if(++G,d0.push(l0()),!q($Q.Comma))break;return m0?new NC0(d0):d0[0]}function E(){let R0=w(!0);if(!(R0 instanceof zV||R0 instanceof NC0))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${R0.type} instead`);if(!D("in"))throw SyntaxError("Expected `in` keyword following loop variable");++G;let l0=T();H($Q.CloseStatement,"Expected closing statement token");let d0=[];while(!F("endfor","else"))d0.push(z());let m0=[];if(F("else")){++G,++G,H($Q.CloseStatement,"Expected closing statement token");while(!F("endfor"))m0.push(z())}return new zzQ(R0,l0,d0,m0)}function T(){return y()}function y(){let R0=x();if(D("if")){++G;let l0=x();if(D("else")){++G;let d0=y();return new TzQ(l0,R0,d0)}else return new jzQ(R0,l0)}return R0}function x(){let R0=b();while(D("or")){let l0=Q[G];++G;let d0=b();R0=new PF(l0,R0,d0)}return R0}function b(){let R0=g();while(D("and")){let l0=Q[G];++G;let d0=g();R0=new PF(l0,R0,d0)}return R0}function g(){let R0;while(D("not")){let l0=Q[G];++G;let d0=g();R0=new IzQ(l0,d0)}return R0??l()}function l(){let R0=_();while(!0){let l0;if(D("not","in"))l0=new oY("not in",$Q.Identifier),G+=2;else if(D("in"))l0=Q[G++];else if(q($Q.ComparisonBinaryOperator))l0=Q[G++];else break;let d0=_();R0=new PF(l0,R0,d0)}return R0}function _(){let R0=d();while(q($Q.AdditiveBinaryOperator)){let l0=Q[G];++G;let d0=d();R0=new PF(l0,R0,d0)}return R0}function a(){let R0=u0(WQ());if(q($Q.OpenParen))return r(R0);return R0}function r(R0){let l0=new OC0(R0,f0());if(l0=u0(l0),q($Q.OpenParen))l0=r(l0);return l0}function f0(){H($Q.OpenParen,"Expected opening parenthesis for arguments list");let R0=t();return H($Q.CloseParen,"Expected closing parenthesis for arguments list"),R0}function t(){let R0=[];while(!q($Q.CloseParen)){let l0;if(Q[G].type===$Q.MultiplicativeBinaryOperator&&Q[G].value==="*"){++G;let d0=T();l0=new EzQ(d0)}else if(l0=T(),q($Q.Equals)){if(++G,!(l0 instanceof zV))throw SyntaxError("Expected identifier for keyword argument");let d0=T();l0=new wzQ(l0,d0)}if(R0.push(l0),q($Q.Comma))++G}return R0}function p0(){let R0=[],l0=!1;while(!q($Q.CloseSquareBracket))if(q($Q.Colon))R0.push(void 0),++G,l0=!0;else if(R0.push(T()),q($Q.Colon))++G,l0=!0;if(R0.length===0)throw SyntaxError("Expected at least one argument for member/slice expression");if(l0){if(R0.length>3)throw SyntaxError("Expected 0-3 arguments for slice expression");return new RzQ(...R0)}return R0[0]}function u0(R0){while(q($Q.Dot)||q($Q.OpenSquareBracket)){let l0=Q[G];++G;let d0,m0=l0.type===$Q.OpenSquareBracket;if(m0)d0=p0(),H($Q.CloseSquareBracket,"Expected closing square bracket");else if(d0=WQ(),d0.type!=="Identifier")throw SyntaxError("Expected identifier following dot operator");R0=new FzQ(R0,d0,m0)}return R0}function d(){let R0=n();while(q($Q.MultiplicativeBinaryOperator)){let l0=Q[G++],d0=n();R0=new PF(l0,R0,d0)}return R0}function n(){let R0=c0();while(D("is")){++G;let l0=D("not");if(l0)++G;let d0=WQ();if(!(d0 instanceof zV))throw SyntaxError("Expected identifier for the test");R0=new CzQ(R0,l0,d0)}return R0}function c0(){let R0=a();while(q($Q.Pipe)){++G;let l0=WQ();if(!(l0 instanceof zV))throw SyntaxError("Expected identifier for the filter");if(q($Q.OpenParen))l0=r(l0);R0=new PzQ(R0,l0)}return R0}function WQ(){let R0=Q[G++];switch(R0.type){case $Q.NumericLiteral:{let l0=R0.value;return l0.includes(".")?new MzQ(Number(l0)):new DzQ(Number(l0))}case $Q.StringLiteral:{let l0=R0.value;while(q($Q.StringLiteral))l0+=Q[G++].value;return new PC0(l0)}case $Q.Identifier:return new zV(R0.value);case $Q.OpenParen:{let l0=w();return H($Q.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),l0}case $Q.OpenSquareBracket:{let l0=[];while(!q($Q.CloseSquareBracket))if(l0.push(T()),q($Q.Comma))++G;return++G,new LzQ(l0)}case $Q.OpenCurlyBracket:{let l0=new Map;while(!q($Q.CloseCurlyBracket)){let d0=T();H($Q.Colon,"Expected colon between key and value in object literal");let m0=T();if(l0.set(d0,m0),q($Q.Comma))++G}return++G,new OzQ(l0)}default:throw SyntaxError(`Unexpected token: ${R0.type}`)}}while(G<Q.length)J.body.push(z());return J}function yzQ(Q,J,G=1){if(J===void 0)J=Q,Q=0;if(G===0)throw Error("range() step must not be zero");let H=[];if(G>0)for(let K=Q;K<J;K+=G)H.push(K);else for(let K=Q;K>J;K+=G)H.push(K);return H}function jC0(Q,J,G,H=1){let K=Math.sign(H);if(K>=0)J=(J??=0)<0?Math.max(Q.length+J,0):Math.min(J,Q.length),G=(G??=Q.length)<0?Math.max(Q.length+G,0):Math.min(G,Q.length);else J=(J??=Q.length-1)<0?Math.max(Q.length+J,-1):Math.min(J,Q.length-1),G=(G??=-1)<-1?Math.max(Q.length+G,-1):Math.min(G,Q.length-1);let z=[];for(let q=J;K*q<K*G;q+=H)z.push(Q[q]);return z}function vzQ(Q){return Q.replace(/\b\w/g,(J)=>J.toUpperCase())}function xzQ(Q){return bzQ(new Date,Q)}function bzQ(Q,J){let G=new Intl.DateTimeFormat(void 0,{month:"long"}),H=new Intl.DateTimeFormat(void 0,{month:"short"}),K=(z)=>z<10?"0"+z:z.toString();return J.replace(/%[YmdbBHM%]/g,(z)=>{switch(z){case"%Y":return Q.getFullYear().toString();case"%m":return K(Q.getMonth()+1);case"%d":return K(Q.getDate());case"%b":return H.format(Q);case"%B":return G.format(Q);case"%H":return K(Q.getHours());case"%M":return K(Q.getMinutes());case"%%":return"%";default:return z}})}function gzQ(Q){return Q.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hzQ(Q,J,G,H){if(H===0)return Q;let K=H==null||H<0?1/0:H,z=J.length===0?new RegExp("(?=)","gu"):new RegExp(gzQ(J),"gu");return Q.replaceAll(z,(q)=>{if(K>0)return--K,G;return q})}var CC0=class extends Error{},IC0=class extends Error{},xW=class{type="RuntimeValue";value;builtins=new Map;constructor(Q=void 0){this.value=Q}__bool__(){return new v8(!!this.value)}toString(){return String(this.value)}},c8=class extends xW{type="IntegerValue"},G7=class extends xW{type="FloatValue";toString(){return this.value%1===0?this.value.toFixed(1):this.value.toString()}},sQ=class extends xW{type="StringValue";builtins=new Map([["upper",new S9(()=>{return new sQ(this.value.toUpperCase())})],["lower",new S9(()=>{return new sQ(this.value.toLowerCase())})],["strip",new S9(()=>{return new sQ(this.value.trim())})],["title",new S9(()=>{return new sQ(vzQ(this.value))})],["capitalize",new S9(()=>{return new sQ(this.value.charAt(0).toUpperCase()+this.value.slice(1))})],["length",new c8(this.value.length)],["rstrip",new S9(()=>{return new sQ(this.value.trimEnd())})],["lstrip",new S9(()=>{return new sQ(this.value.trimStart())})],["startswith",new S9((Q)=>{if(Q.length===0)throw Error("startswith() requires at least one argument");let J=Q[0];if(J instanceof sQ)return new v8(this.value.startsWith(J.value));else if(J instanceof V6){for(let G of J.value){if(!(G instanceof sQ))throw Error("startswith() tuple elements must be strings");if(this.value.startsWith(G.value))return new v8(!0)}return new v8(!1)}throw Error("startswith() argument must be a string or tuple of strings")})],["endswith",new S9((Q)=>{if(Q.length===0)throw Error("endswith() requires at least one argument");let J=Q[0];if(J instanceof sQ)return new v8(this.value.endsWith(J.value));else if(J instanceof V6){for(let G of J.value){if(!(G instanceof sQ))throw Error("endswith() tuple elements must be strings");if(this.value.endsWith(G.value))return new v8(!0)}return new v8(!1)}throw Error("endswith() argument must be a string or tuple of strings")})],["split",new S9((Q)=>{let J=Q[0]??new d9;if(!(J instanceof sQ||J instanceof d9))throw Error("sep argument must be a string or null");let G=Q[1]??new c8(-1);if(!(G instanceof c8))throw Error("maxsplit argument must be a number");let H=[];if(J instanceof d9){let K=this.value.trimStart();for(let{0:z,index:q}of K.matchAll(/\S+/g)){if(G.value!==-1&&H.length>=G.value&&q!==void 0){H.push(z+K.slice(q+z.length));break}H.push(z)}}else{if(J.value==="")throw Error("empty separator");if(H=this.value.split(J.value),G.value!==-1&&H.length>G.value)H.push(H.splice(G.value).join(J.value))}return new V6(H.map((K)=>new sQ(K)))})],["replace",new S9((Q)=>{if(Q.length<2)throw Error("replace() requires at least two arguments");let J=Q[0],G=Q[1];if(!(J instanceof sQ&&G instanceof sQ))throw Error("replace() arguments must be strings");let H;if(Q.length>2)if(Q[2].type==="KeywordArgumentsValue")H=Q[2].value.get("count")??new d9;else H=Q[2];else H=new d9;if(!(H instanceof c8||H instanceof d9))throw Error("replace() count argument must be a number or null");return new sQ(hzQ(this.value,J.value,G.value,H.value))})]])},v8=class extends xW{type="BooleanValue"},_zQ=/[\x7f-\uffff]/g;function RC0(Q){return Q.replace(_zQ,(J)=>"\\u"+J.charCodeAt(0).toString(16).padStart(4,"0"))}function HB(Q,J={},G=0,H=!0){let{indent:K=null,ensureAscii:z=!1,separators:q=null,sortKeys:F=!1}=J,D,V;if(q)[D,V]=q;else if(K)D=",",V=": ";else D=", ",V=": ";switch(Q.type){case"NullValue":return"null";case"UndefinedValue":return H?"null":"undefined";case"IntegerValue":case"FloatValue":case"BooleanValue":return JSON.stringify(Q.value);case"StringValue":{let O=JSON.stringify(Q.value);if(z)O=RC0(O);return O}case"ArrayValue":case"ObjectValue":{let O=K?" ".repeat(K):"",P=`
`+O.repeat(G),N=P+O;if(Q.type==="ArrayValue"){let I=Q.value.map((R)=>HB(R,J,G+1,H));return K?`[${N}${I.join(`${D}${N}`)}${P}]`:`[${I.join(D)}]`}else{let I=Array.from(Q.value.entries());if(F)I=I.sort(([w],[E])=>w.localeCompare(E));let R=I.map(([w,E])=>{let T=JSON.stringify(w);if(z)T=RC0(T);let y=`${T}${V}${HB(E,J,G+1,H)}`;return K?`${N}${y}`:y});return K?`{${R.join(D)}${P}}`:`{${R.join(D)}}`}}default:throw Error(`Cannot convert to JSON: ${Q.type}`)}}var XX=class extends xW{type="ObjectValue";__bool__(){return new v8(this.value.size>0)}builtins=new Map([["get",new S9(([Q,J])=>{if(!(Q instanceof sQ))throw Error(`Object key must be a string: got ${Q.type}`);return this.value.get(Q.value)??J??new d9})],["items",new S9(()=>this.items())],["keys",new S9(()=>this.keys())],["values",new S9(()=>this.values())],["dictsort",new S9((Q)=>{let J=new Map,G=Q.filter((F)=>{if(F instanceof wF)return J=F.value,!1;return!0}),H=G.at(0)??J.get("case_sensitive")??new v8(!1);if(!(H instanceof v8))throw Error("case_sensitive must be a boolean");let K=G.at(1)??J.get("by")??new sQ("key");if(!(K instanceof sQ))throw Error("by must be a string");if(!["key","value"].includes(K.value))throw Error("by must be either 'key' or 'value'");let z=G.at(2)??J.get("reverse")??new v8(!1);if(!(z instanceof v8))throw Error("reverse must be a boolean");let q=Array.from(this.value.entries()).map(([F,D])=>new V6([new sQ(F),D])).sort((F,D)=>{let V=K.value==="key"?0:1,O=F.value[V],P=D.value[V],N=Y90(O,P,H.value);return z.value?-N:N});return new V6(q)})]]);items(){return new V6(Array.from(this.value.entries()).map(([Q,J])=>new V6([new sQ(Q),J])))}keys(){return new V6(Array.from(this.value.keys()).map((Q)=>new sQ(Q)))}values(){return new V6(Array.from(this.value.values()))}toString(){return HB(this,{},0,!1)}},wF=class extends XX{type="KeywordArgumentsValue"},V6=class extends xW{type="ArrayValue";builtins=new Map([["length",new c8(this.value.length)]]);__bool__(){return new v8(this.value.length>0)}toString(){return HB(this,{},0,!1)}},wC0=class extends V6{type="TupleValue"},S9=class extends xW{type="FunctionValue"},d9=class extends xW{type="NullValue"},E9=class extends xW{type="UndefinedValue"},e3=class{constructor(Q){this.parent=Q}variables=new Map([["namespace",new S9((Q)=>{if(Q.length===0)return new XX(new Map);if(Q.length!==1||!(Q[0]instanceof XX))throw Error("`namespace` expects either zero arguments or a single object argument");return Q[0]})]]);tests=new Map([["boolean",(Q)=>Q.type==="BooleanValue"],["callable",(Q)=>Q instanceof S9],["odd",(Q)=>{if(!(Q instanceof c8))throw Error(`cannot odd on ${Q.type}`);return Q.value%2!==0}],["even",(Q)=>{if(!(Q instanceof c8))throw Error(`cannot even on ${Q.type}`);return Q.value%2===0}],["false",(Q)=>Q.type==="BooleanValue"&&!Q.value],["true",(Q)=>Q.type==="BooleanValue"&&Q.value],["none",(Q)=>Q.type==="NullValue"],["string",(Q)=>Q.type==="StringValue"],["number",(Q)=>Q instanceof c8||Q instanceof G7],["integer",(Q)=>Q instanceof c8],["iterable",(Q)=>Q.type==="ArrayValue"||Q.type==="StringValue"],["mapping",(Q)=>Q instanceof XX],["sequence",(Q)=>Q instanceof V6||Q instanceof XX||Q instanceof sQ],["lower",(Q)=>{let J=Q.value;return Q.type==="StringValue"&&J===J.toLowerCase()}],["upper",(Q)=>{let J=Q.value;return Q.type==="StringValue"&&J===J.toUpperCase()}],["none",(Q)=>Q.type==="NullValue"],["defined",(Q)=>Q.type!=="UndefinedValue"],["undefined",(Q)=>Q.type==="UndefinedValue"],["equalto",(Q,J)=>Q.value===J.value],["eq",(Q,J)=>Q.value===J.value]]);set(Q,J){return this.declareVariable(Q,WR(J))}declareVariable(Q,J){if(this.variables.has(Q))throw SyntaxError(`Variable already declared: ${Q}`);return this.variables.set(Q,J),J}setVariable(Q,J){return this.variables.set(Q,J),J}resolve(Q){if(this.variables.has(Q))return this;if(this.parent)return this.parent.resolve(Q);throw Error(`Unknown variable: ${Q}`)}lookupVariable(Q){try{return this.resolve(Q).variables.get(Q)??new E9}catch{return new E9}}};function fzQ(Q){Q.set("false",!1),Q.set("true",!0),Q.set("none",null),Q.set("raise_exception",(J)=>{throw Error(J)}),Q.set("range",yzQ),Q.set("strftime_now",xzQ),Q.set("True",!0),Q.set("False",!1),Q.set("None",null)}function EC0(Q,J){let G=J.split("."),H=Q;for(let K of G)if(H instanceof XX)H=H.value.get(K)??new E9;else if(H instanceof V6){let z=parseInt(K,10);if(!isNaN(z)&&z>=0&&z<H.value.length)H=H.value[z];else return new E9}else return new E9;return H}function Y90(Q,J,G=!1){if(Q instanceof d9&&J instanceof d9)return 0;if(Q instanceof d9||J instanceof d9)throw Error(`Cannot compare ${Q.type} with ${J.type}`);if(Q instanceof E9&&J instanceof E9)return 0;if(Q instanceof E9||J instanceof E9)throw Error(`Cannot compare ${Q.type} with ${J.type}`);let H=(z)=>z instanceof c8||z instanceof G7||z instanceof v8,K=(z)=>{if(z instanceof v8)return z.value?1:0;return z.value};if(H(Q)&&H(J)){let z=K(Q),q=K(J);return z<q?-1:z>q?1:0}if(Q.type!==J.type)throw Error(`Cannot compare different types: ${Q.type} and ${J.type}`);switch(Q.type){case"StringValue":{let z=Q.value,q=J.value;if(!G)z=z.toLowerCase(),q=q.toLowerCase();return z<q?-1:z>q?1:0}default:throw Error(`Cannot compare type: ${Q.type}`)}}var mzQ=class{global;constructor(Q){this.global=Q??new e3}run(Q){return this.evaluate(Q,this.global)}evaluateBinaryExpression(Q,J){let G=this.evaluate(Q.left,J);switch(Q.operator.value){case"and":return G.__bool__().value?this.evaluate(Q.right,J):G;case"or":return G.__bool__().value?G:this.evaluate(Q.right,J)}let H=this.evaluate(Q.right,J);switch(Q.operator.value){case"==":return new v8(G.value==H.value);case"!=":return new v8(G.value!=H.value)}if(G instanceof E9||H instanceof E9){if(H instanceof E9&&["in","not in"].includes(Q.operator.value))return new v8(Q.operator.value==="not in");throw Error(`Cannot perform operation ${Q.operator.value} on undefined values`)}else if(G instanceof d9||H instanceof d9)throw Error("Cannot perform operation on null values");else if(Q.operator.value==="~")return new sQ(G.value.toString()+H.value.toString());else if((G instanceof c8||G instanceof G7)&&(H instanceof c8||H instanceof G7)){let K=G.value,z=H.value;switch(Q.operator.value){case"+":case"-":case"*":{let q=Q.operator.value==="+"?K+z:Q.operator.value==="-"?K-z:K*z;return G instanceof G7||H instanceof G7?new G7(q):new c8(q)}case"/":return new G7(K/z);case"%":{let q=K%z;return G instanceof G7||H instanceof G7?new G7(q):new c8(q)}case"<":return new v8(K<z);case">":return new v8(K>z);case">=":return new v8(K>=z);case"<=":return new v8(K<=z)}}else if(G instanceof V6&&H instanceof V6)switch(Q.operator.value){case"+":return new V6(G.value.concat(H.value))}else if(H instanceof V6){let K=H.value.find((z)=>z.value===G.value)!==void 0;switch(Q.operator.value){case"in":return new v8(K);case"not in":return new v8(!K)}}if(G instanceof sQ||H instanceof sQ)switch(Q.operator.value){case"+":return new sQ(G.value.toString()+H.value.toString())}if(G instanceof sQ&&H instanceof sQ)switch(Q.operator.value){case"in":return new v8(H.value.includes(G.value));case"not in":return new v8(!H.value.includes(G.value))}if(G instanceof sQ&&H instanceof XX)switch(Q.operator.value){case"in":return new v8(H.value.has(G.value));case"not in":return new v8(!H.value.has(G.value))}throw SyntaxError(`Unknown operator "${Q.operator.value}" between ${G.type} and ${H.type}`)}evaluateArguments(Q,J){let G=[],H=new Map;for(let K of Q)if(K.type==="SpreadExpression"){let z=K,q=this.evaluate(z.argument,J);if(!(q instanceof V6))throw Error(`Cannot unpack non-iterable type: ${q.type}`);for(let F of q.value)G.push(F)}else if(K.type==="KeywordArgumentExpression"){let z=K;H.set(z.key.value,this.evaluate(z.value,J))}else{if(H.size>0)throw Error("Positional arguments must come before keyword arguments");G.push(this.evaluate(K,J))}return[G,H]}applyFilter(Q,J,G){if(J.type==="Identifier"){let H=J;if(H.value==="safe")return Q;if(H.value==="tojson")return new sQ(HB(Q,{}));if(Q instanceof V6)switch(H.value){case"list":return Q;case"first":return Q.value[0];case"last":return Q.value[Q.value.length-1];case"length":return new c8(Q.value.length);case"reverse":return new V6(Q.value.slice().reverse());case"sort":return new V6(Q.value.slice().sort((K,z)=>Y90(K,z,!1)));case"join":return new sQ(Q.value.map((K)=>K.value).join(""));case"string":return new sQ(HB(Q,{},0,!1));case"unique":{let K=new Set,z=[];for(let q of Q.value)if(!K.has(q.value))K.add(q.value),z.push(q);return new V6(z)}default:throw Error(`Unknown ArrayValue filter: ${H.value}`)}else if(Q instanceof sQ)switch(H.value){case"length":case"upper":case"lower":case"title":case"capitalize":{let K=Q.builtins.get(H.value);if(K instanceof S9)return K.value([],G);else if(K instanceof c8)return K;else throw Error(`Unknown StringValue filter: ${H.value}`)}case"trim":return new sQ(Q.value.trim());case"indent":return new sQ(Q.value.split(`
`).map((K,z)=>z===0||K.length===0?K:" "+K).join(`
`));case"join":case"string":return Q;case"int":{let K=parseInt(Q.value,10);return new c8(isNaN(K)?0:K)}case"float":{let K=parseFloat(Q.value);return new G7(isNaN(K)?0:K)}default:throw Error(`Unknown StringValue filter: ${H.value}`)}else if(Q instanceof c8||Q instanceof G7)switch(H.value){case"abs":return Q instanceof c8?new c8(Math.abs(Q.value)):new G7(Math.abs(Q.value));case"int":return new c8(Math.floor(Q.value));case"float":return new G7(Q.value);case"string":return new sQ(Q.toString());default:throw Error(`Unknown NumericValue filter: ${H.value}`)}else if(Q instanceof XX)switch(H.value){case"items":return new V6(Array.from(Q.value.entries()).map(([K,z])=>new V6([new sQ(K),z])));case"length":return new c8(Q.value.size);default:{let K=Q.builtins.get(H.value);if(K){if(K instanceof S9)return K.value([],G);return K}throw Error(`Unknown ObjectValue filter: ${H.value}`)}}else if(Q instanceof v8)switch(H.value){case"bool":return new v8(Q.value);case"int":return new c8(Q.value?1:0);case"float":return new G7(Q.value?1:0);case"string":return new sQ(Q.value?"true":"false");default:throw Error(`Unknown BooleanValue filter: ${H.value}`)}throw Error(`Cannot apply filter "${H.value}" to type: ${Q.type}`)}else if(J.type==="CallExpression"){let H=J;if(H.callee.type!=="Identifier")throw Error(`Unknown filter: ${H.callee.type}`);let K=H.callee.value;if(K==="tojson"){let[,z]=this.evaluateArguments(H.args,G),q=z.get("indent")??new d9;if(!(q instanceof c8||q instanceof d9))throw Error("If set, indent must be a number");let F=z.get("ensure_ascii")??new v8(!1);if(!(F instanceof v8))throw Error("If set, ensure_ascii must be a boolean");let D=z.get("sort_keys")??new v8(!1);if(!(D instanceof v8))throw Error("If set, sort_keys must be a boolean");let V=z.get("separators")??new d9,O=null;if(V instanceof V6||V instanceof wC0){if(V.value.length!==2)throw Error("separators must be a tuple of two strings");let[P,N]=V.value;if(!(P instanceof sQ)||!(N instanceof sQ))throw Error("separators must be a tuple of two strings");O=[P.value,N.value]}else if(!(V instanceof d9))throw Error("If set, separators must be a tuple of two strings");return new sQ(HB(Q,{indent:q.value,ensureAscii:F.value,sortKeys:D.value,separators:O}))}else if(K==="join"){let z;if(Q instanceof sQ)z=Array.from(Q.value);else if(Q instanceof V6)z=Q.value.map((V)=>V.value);else throw Error(`Cannot apply filter "${K}" to type: ${Q.type}`);let[q,F]=this.evaluateArguments(H.args,G),D=q.at(0)??F.get("separator")??new sQ("");if(!(D instanceof sQ))throw Error("separator must be a string");return new sQ(z.join(D.value))}else if(K==="int"||K==="float"){let[z,q]=this.evaluateArguments(H.args,G),F=z.at(0)??q.get("default")??(K==="int"?new c8(0):new G7(0));if(Q instanceof sQ){let D=K==="int"?parseInt(Q.value,10):parseFloat(Q.value);return isNaN(D)?F:K==="int"?new c8(D):new G7(D)}else if(Q instanceof c8||Q instanceof G7)return Q;else if(Q instanceof v8)return K==="int"?new c8(Q.value?1:0):new G7(Q.value?1:0);else throw Error(`Cannot apply filter "${K}" to type: ${Q.type}`)}else if(K==="default"){let[z,q]=this.evaluateArguments(H.args,G),F=z[0]??new sQ(""),D=z[1]??q.get("boolean")??new v8(!1);if(!(D instanceof v8))throw Error("`default` filter flag must be a boolean");if(Q instanceof E9||D.value&&!Q.__bool__().value)return F;return Q}if(Q instanceof V6){switch(K){case"sort":{let[z,q]=this.evaluateArguments(H.args,G),F=z.at(0)??q.get("reverse")??new v8(!1);if(!(F instanceof v8))throw Error("reverse must be a boolean");let D=z.at(1)??q.get("case_sensitive")??new v8(!1);if(!(D instanceof v8))throw Error("case_sensitive must be a boolean");let V=z.at(2)??q.get("attribute")??new d9;if(!(V instanceof sQ||V instanceof c8||V instanceof d9))throw Error("attribute must be a string, integer, or null");let O=(P)=>{if(V instanceof d9)return P;let N=V instanceof c8?String(V.value):V.value;return EC0(P,N)};return new V6(Q.value.slice().sort((P,N)=>{let I=O(P),R=O(N),w=Y90(I,R,D.value);return F.value?-w:w}))}case"selectattr":case"rejectattr":{let z=K==="selectattr";if(Q.value.some((P)=>!(P instanceof XX)))throw Error(`\`${K}\` can only be applied to array of objects`);if(H.args.some((P)=>P.type!=="StringLiteral"))throw Error(`arguments of \`${K}\` must be strings`);let[q,F,D]=H.args.map((P)=>this.evaluate(P,G)),V;if(F){let P=G.tests.get(F.value);if(!P)throw Error(`Unknown test: ${F.value}`);V=P}else V=(...P)=>P[0].__bool__().value;let O=Q.value.filter((P)=>{let N=P.value.get(q.value),I=N?V(N,D):!1;return z?I:!I});return new V6(O)}case"map":{let[,z]=this.evaluateArguments(H.args,G);if(z.has("attribute")){let q=z.get("attribute");if(!(q instanceof sQ))throw Error("attribute must be a string");let F=z.get("default"),D=Q.value.map((V)=>{if(!(V instanceof XX))throw Error("items in map must be an object");let O=EC0(V,q.value);return O instanceof E9?F??new E9:O});return new V6(D)}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${K}`)}else if(Q instanceof sQ){switch(K){case"indent":{let[z,q]=this.evaluateArguments(H.args,G),F=z.at(0)??q.get("width")??new c8(4);if(!(F instanceof c8))throw Error("width must be a number");let D=z.at(1)??q.get("first")??new v8(!1),V=z.at(2)??q.get("blank")??new v8(!1),O=Q.value.split(`
`),P=" ".repeat(F.value),N=O.map((I,R)=>!D.value&&R===0||!V.value&&I.length===0?I:P+I);return new sQ(N.join(`
`))}case"replace":{let z=Q.builtins.get("replace");if(!(z instanceof S9))throw Error("replace filter not available");let[q,F]=this.evaluateArguments(H.args,G);return z.value([...q,new wF(F)],G)}}throw Error(`Unknown StringValue filter: ${K}`)}else if(Q instanceof XX){let z=Q.builtins.get(K);if(z&&z instanceof S9){let[q,F]=this.evaluateArguments(H.args,G);if(F.size>0)q.push(new wF(F));return z.value(q,G)}throw Error(`Unknown ObjectValue filter: ${K}`)}else throw Error(`Cannot apply filter "${K}" to type: ${Q.type}`)}throw Error(`Unknown filter: ${J.type}`)}evaluateFilterExpression(Q,J){let G=this.evaluate(Q.operand,J);return this.applyFilter(G,Q.filter,J)}evaluateTestExpression(Q,J){let G=this.evaluate(Q.operand,J),H=J.tests.get(Q.test.value);if(!H)throw Error(`Unknown test: ${Q.test.value}`);let K=H(G);return new v8(Q.negate?!K:K)}evaluateSelectExpression(Q,J){if(!this.evaluate(Q.test,J).__bool__().value)return new E9;return this.evaluate(Q.lhs,J)}evaluateUnaryExpression(Q,J){let G=this.evaluate(Q.argument,J);switch(Q.operator.value){case"not":return new v8(!G.value);default:throw SyntaxError(`Unknown operator: ${Q.operator.value}`)}}evaluateTernaryExpression(Q,J){return this.evaluate(Q.condition,J).__bool__().value?this.evaluate(Q.trueExpr,J):this.evaluate(Q.falseExpr,J)}evalProgram(Q,J){return this.evaluateBlock(Q.body,J)}evaluateBlock(Q,J){let G="";for(let H of Q){let K=this.evaluate(H,J);if(K.type!=="NullValue"&&K.type!=="UndefinedValue")G+=K.toString()}return new sQ(G)}evaluateIdentifier(Q,J){return J.lookupVariable(Q.value)}evaluateCallExpression(Q,J){let[G,H]=this.evaluateArguments(Q.args,J);if(H.size>0)G.push(new wF(H));let K=this.evaluate(Q.callee,J);if(K.type!=="FunctionValue")throw Error(`Cannot call something that is not a function: got ${K.type}`);return K.value(G,J)}evaluateSliceExpression(Q,J,G){if(!(Q instanceof V6||Q instanceof sQ))throw Error("Slice object must be an array or string");let H=this.evaluate(J.start,G),K=this.evaluate(J.stop,G),z=this.evaluate(J.step,G);if(!(H instanceof c8||H instanceof E9))throw Error("Slice start must be numeric or undefined");if(!(K instanceof c8||K instanceof E9))throw Error("Slice stop must be numeric or undefined");if(!(z instanceof c8||z instanceof E9))throw Error("Slice step must be numeric or undefined");if(Q instanceof V6)return new V6(jC0(Q.value,H.value,K.value,z.value));else return new sQ(jC0(Array.from(Q.value),H.value,K.value,z.value).join(""))}evaluateMemberExpression(Q,J){let G=this.evaluate(Q.object,J),H;if(Q.computed)if(Q.property.type==="SliceExpression")return this.evaluateSliceExpression(G,Q.property,J);else H=this.evaluate(Q.property,J);else H=new sQ(Q.property.value);let K;if(G instanceof XX){if(!(H instanceof sQ))throw Error(`Cannot access property with non-string: got ${H.type}`);K=G.value.get(H.value)??G.builtins.get(H.value)}else if(G instanceof V6||G instanceof sQ)if(H instanceof c8){if(K=G.value.at(H.value),G instanceof sQ)K=new sQ(G.value.at(H.value))}else if(H instanceof sQ)K=G.builtins.get(H.value);else throw Error(`Cannot access property with non-string/non-number: got ${H.type}`);else{if(!(H instanceof sQ))throw Error(`Cannot access property with non-string: got ${H.type}`);K=G.builtins.get(H.value)}return K instanceof xW?K:new E9}evaluateSet(Q,J){let G=Q.value?this.evaluate(Q.value,J):this.evaluateBlock(Q.body,J);if(Q.assignee.type==="Identifier"){let H=Q.assignee.value;J.setVariable(H,G)}else if(Q.assignee.type==="TupleLiteral"){let H=Q.assignee;if(!(G instanceof V6))throw Error(`Cannot unpack non-iterable type in set: ${G.type}`);let K=G.value;if(K.length!==H.value.length)throw Error(`Too ${H.value.length>K.length?"few":"many"} items to unpack in set`);for(let z=0;z<H.value.length;++z){let q=H.value[z];if(q.type!=="Identifier")throw Error(`Cannot unpack to non-identifier in set: ${q.type}`);J.setVariable(q.value,K[z])}}else if(Q.assignee.type==="MemberExpression"){let H=Q.assignee,K=this.evaluate(H.object,J);if(!(K instanceof XX))throw Error("Cannot assign to member of non-object");if(H.property.type!=="Identifier")throw Error("Cannot assign to member with non-identifier property");K.value.set(H.property.value,G)}else throw Error(`Invalid LHS inside assignment expression: ${JSON.stringify(Q.assignee)}`);return new d9}evaluateIf(Q,J){let G=this.evaluate(Q.test,J);return this.evaluateBlock(G.__bool__().value?Q.body:Q.alternate,J)}evaluateFor(Q,J){let G=new e3(J),H,K;if(Q.iterable.type==="SelectExpression"){let V=Q.iterable;K=this.evaluate(V.lhs,G),H=V.test}else K=this.evaluate(Q.iterable,G);if(!(K instanceof V6||K instanceof XX))throw Error(`Expected iterable or object type in for loop: got ${K.type}`);if(K instanceof XX)K=K.keys();let z=[],q=[];for(let V=0;V<K.value.length;++V){let O=new e3(G),P=K.value[V],N;if(Q.loopvar.type==="Identifier")N=(I)=>I.setVariable(Q.loopvar.value,P);else if(Q.loopvar.type==="TupleLiteral"){let I=Q.loopvar;if(P.type!=="ArrayValue")throw Error(`Cannot unpack non-iterable type: ${P.type}`);let R=P;if(I.value.length!==R.value.length)throw Error(`Too ${I.value.length>R.value.length?"few":"many"} items to unpack`);N=(w)=>{for(let E=0;E<I.value.length;++E){if(I.value[E].type!=="Identifier")throw Error(`Cannot unpack non-identifier type: ${I.value[E].type}`);w.setVariable(I.value[E].value,R.value[E])}}}else throw Error(`Invalid loop variable(s): ${Q.loopvar.type}`);if(H){if(N(O),!this.evaluate(H,O).__bool__().value)continue}z.push(P),q.push(N)}let F="",D=!0;for(let V=0;V<z.length;++V){let O=new Map([["index",new c8(V+1)],["index0",new c8(V)],["revindex",new c8(z.length-V)],["revindex0",new c8(z.length-V-1)],["first",new v8(V===0)],["last",new v8(V===z.length-1)],["length",new c8(z.length)],["previtem",V>0?z[V-1]:new E9],["nextitem",V<z.length-1?z[V+1]:new E9]]);G.setVariable("loop",new XX(O)),q[V](G);try{let P=this.evaluateBlock(Q.body,G);F+=P.value}catch(P){if(P instanceof IC0)continue;if(P instanceof CC0)break;throw P}D=!1}if(D){let V=this.evaluateBlock(Q.defaultBlock,G);F+=V.value}return new sQ(F)}evaluateMacro(Q,J){return J.setVariable(Q.name.value,new S9((G,H)=>{let K=new e3(H);G=G.slice();let z;if(G.at(-1)?.type==="KeywordArgumentsValue")z=G.pop();for(let q=0;q<Q.args.length;++q){let F=Q.args[q],D=G[q];if(F.type==="Identifier"){let V=F;if(!D)throw Error(`Missing positional argument: ${V.value}`);K.setVariable(V.value,D)}else if(F.type==="KeywordArgumentExpression"){let V=F,O=D??z?.value.get(V.key.value)??this.evaluate(V.value,K);K.setVariable(V.key.value,O)}else throw Error(`Unknown argument type: ${F.type}`)}return this.evaluateBlock(Q.body,K)})),new d9}evaluateCallStatement(Q,J){let G=new S9((F,D)=>{let V=new e3(D);if(Q.callerArgs)for(let O=0;O<Q.callerArgs.length;++O){let P=Q.callerArgs[O];if(P.type!=="Identifier")throw Error(`Caller parameter must be an identifier, got ${P.type}`);V.setVariable(P.value,F[O]??new E9)}return this.evaluateBlock(Q.body,V)}),[H,K]=this.evaluateArguments(Q.call.args,J);H.push(new wF(K));let z=this.evaluate(Q.call.callee,J);if(z.type!=="FunctionValue")throw Error(`Cannot call something that is not a function: got ${z.type}`);let q=new e3(J);return q.setVariable("caller",G),z.value(H,q)}evaluateFilterStatement(Q,J){let G=this.evaluateBlock(Q.body,J);return this.applyFilter(G,Q.filter,J)}evaluate(Q,J){if(!Q)return new E9;switch(Q.type){case"Program":return this.evalProgram(Q,J);case"Set":return this.evaluateSet(Q,J);case"If":return this.evaluateIf(Q,J);case"For":return this.evaluateFor(Q,J);case"Macro":return this.evaluateMacro(Q,J);case"CallStatement":return this.evaluateCallStatement(Q,J);case"Break":throw new CC0;case"Continue":throw new IC0;case"IntegerLiteral":return new c8(Q.value);case"FloatLiteral":return new G7(Q.value);case"StringLiteral":return new sQ(Q.value);case"ArrayLiteral":return new V6(Q.value.map((G)=>this.evaluate(G,J)));case"TupleLiteral":return new wC0(Q.value.map((G)=>this.evaluate(G,J)));case"ObjectLiteral":{let G=new Map;for(let[H,K]of Q.value){let z=this.evaluate(H,J);if(!(z instanceof sQ))throw Error(`Object keys must be strings: got ${z.type}`);G.set(z.value,this.evaluate(K,J))}return new XX(G)}case"Identifier":return this.evaluateIdentifier(Q,J);case"CallExpression":return this.evaluateCallExpression(Q,J);case"MemberExpression":return this.evaluateMemberExpression(Q,J);case"UnaryExpression":return this.evaluateUnaryExpression(Q,J);case"BinaryExpression":return this.evaluateBinaryExpression(Q,J);case"FilterExpression":return this.evaluateFilterExpression(Q,J);case"FilterStatement":return this.evaluateFilterStatement(Q,J);case"TestExpression":return this.evaluateTestExpression(Q,J);case"SelectExpression":return this.evaluateSelectExpression(Q,J);case"Ternary":return this.evaluateTernaryExpression(Q,J);case"Comment":return new d9;default:throw SyntaxError(`Unknown node type: ${Q.type}`)}}};function WR(Q){switch(typeof Q){case"number":return Number.isInteger(Q)?new c8(Q):new G7(Q);case"string":return new sQ(Q);case"boolean":return new v8(Q);case"undefined":return new E9;case"object":if(Q===null)return new d9;else if(Array.isArray(Q))return new V6(Q.map(WR));else return new XX(new Map(Object.entries(Q).map(([J,G])=>[J,WR(G)])));case"function":return new S9((J,G)=>{let H=Q(...J.map((K)=>K.value))??null;return WR(H)});default:throw Error(`Cannot convert to runtime value: ${Q}`)}}var h7=`
`,uzQ="{%- ",pzQ=" -%}";function lzQ(Q){switch(Q.operator.type){case"MultiplicativeBinaryOperator":return 4;case"AdditiveBinaryOperator":return 3;case"ComparisonBinaryOperator":return 2;case"Identifier":if(Q.operator.value==="and")return 1;if(Q.operator.value==="in"||Q.operator.value==="not in")return 2;return 0}return 0}function dzQ(Q,J="\t"){let G=typeof J==="number"?" ".repeat(J):J;return xG(Q.body,0,G).replace(/\n$/,"")}function RX(...Q){return uzQ+Q.join(" ")+pzQ}function xG(Q,J,G){return Q.map((H)=>czQ(H,J,G)).join(h7)}function czQ(Q,J,G){let H=G.repeat(J);switch(Q.type){case"Program":return xG(Q.body,J,G);case"If":return izQ(Q,J,G);case"For":return ozQ(Q,J,G);case"Set":return nzQ(Q,J,G);case"Macro":return azQ(Q,J,G);case"Break":return H+RX("break");case"Continue":return H+RX("continue");case"CallStatement":return szQ(Q,J,G);case"FilterStatement":return rzQ(Q,J,G);case"Comment":return H+"{# "+Q.value+" #}";default:return H+"{{- "+Z6(Q)+" -}}"}}function izQ(Q,J,G){let H=G.repeat(J),K=[],z=Q;while(z)if(K.push({test:z.test,body:z.body}),z.alternate.length===1&&z.alternate[0].type==="If")z=z.alternate[0];else break;let q=H+RX("if",Z6(K[0].test))+h7+xG(K[0].body,J+1,G);for(let F=1;F<K.length;++F)q+=h7+H+RX("elif",Z6(K[F].test))+h7+xG(K[F].body,J+1,G);if(z&&z.alternate.length>0)q+=h7+H+RX("else")+h7+xG(z.alternate,J+1,G);return q+=h7+H+RX("endif"),q}function ozQ(Q,J,G){let H=G.repeat(J),K="";if(Q.iterable.type==="SelectExpression"){let q=Q.iterable;K=`${Z6(q.lhs)} if ${Z6(q.test)}`}else K=Z6(Q.iterable);let z=H+RX("for",Z6(Q.loopvar),"in",K)+h7+xG(Q.body,J+1,G);if(Q.defaultBlock.length>0)z+=h7+H+RX("else")+h7+xG(Q.defaultBlock,J+1,G);return z+=h7+H+RX("endfor"),z}function nzQ(Q,J,G){let H=G.repeat(J),K=Z6(Q.assignee),z=Q.value?Z6(Q.value):"",q=H+RX("set",`${K}${Q.value?" = "+z:""}`);if(Q.body.length===0)return q;return q+h7+xG(Q.body,J+1,G)+h7+H+RX("endset")}function azQ(Q,J,G){let H=G.repeat(J),K=Q.args.map(Z6).join(", ");return H+RX("macro",`${Q.name.value}(${K})`)+h7+xG(Q.body,J+1,G)+h7+H+RX("endmacro")}function szQ(Q,J,G){let H=G.repeat(J),K=Q.callerArgs&&Q.callerArgs.length>0?`(${Q.callerArgs.map(Z6).join(", ")})`:"",z=Z6(Q.call),q=H+RX(`call${K}`,z)+h7;return q+=xG(Q.body,J+1,G)+h7,q+=H+RX("endcall"),q}function rzQ(Q,J,G){let H=G.repeat(J),K=Q.filter.type==="Identifier"?Q.filter.value:Z6(Q.filter),z=H+RX("filter",K)+h7;return z+=xG(Q.body,J+1,G)+h7,z+=H+RX("endfilter"),z}function Z6(Q,J=-1){switch(Q.type){case"SpreadExpression":return`*${Z6(Q.argument)}`;case"Identifier":return Q.value;case"IntegerLiteral":return`${Q.value}`;case"FloatLiteral":return`${Q.value}`;case"StringLiteral":return JSON.stringify(Q.value);case"BinaryExpression":{let G=Q,H=lzQ(G),K=Z6(G.left,H),z=Z6(G.right,H+1),q=`${K} ${G.operator.value} ${z}`;return H<J?`(${q})`:q}case"UnaryExpression":{let G=Q;return G.operator.value+(G.operator.value==="not"?" ":"")+Z6(G.argument,1/0)}case"CallExpression":{let G=Q,H=G.args.map(Z6).join(", ");return`${Z6(G.callee)}(${H})`}case"MemberExpression":{let G=Q,H=Z6(G.object);if(!["Identifier","MemberExpression","CallExpression","StringLiteral","IntegerLiteral","FloatLiteral","ArrayLiteral","TupleLiteral","ObjectLiteral"].includes(G.object.type))H=`(${H})`;let K=Z6(G.property);if(!G.computed&&G.property.type!=="Identifier")K=`(${K})`;return G.computed?`${H}[${K}]`:`${H}.${K}`}case"FilterExpression":{let G=Q,H=Z6(G.operand,1/0);if(G.filter.type==="CallExpression")return`${H} | ${Z6(G.filter)}`;return`${H} | ${G.filter.value}`}case"SelectExpression":{let G=Q;return`${Z6(G.lhs)} if ${Z6(G.test)}`}case"TestExpression":{let G=Q;return`${Z6(G.operand)} is${G.negate?" not":""} ${G.test.value}`}case"ArrayLiteral":case"TupleLiteral":{let G=Q.value.map(Z6),H=Q.type==="ArrayLiteral"?"[]":"()";return`${H[0]}${G.join(", ")}${H[1]}`}case"ObjectLiteral":return`{${Array.from(Q.value.entries()).map(([H,K])=>`${Z6(H)}: ${Z6(K)}`).join(", ")}}`;case"SliceExpression":{let G=Q,H=G.start?Z6(G.start):"",K=G.stop?Z6(G.stop):"",z=G.step?`:${Z6(G.step)}`:"";return`${H}:${K}${z}`}case"KeywordArgumentExpression":{let G=Q;return`${G.key.value}=${Z6(G.value)}`}case"Ternary":{let G=Q,H=`${Z6(G.trueExpr)} if ${Z6(G.condition,0)} else ${Z6(G.falseExpr)}`;return J>-1?`(${H})`:H}default:throw Error(`Unknown expression type: ${Q.type}`)}}var tzQ=class{parsed;constructor(Q){let J=BzQ(Q,{lstrip_blocks:!0,trim_blocks:!0});this.parsed=kzQ(J)}render(Q){let J=new e3;if(fzQ(J),Q)for(let[K,z]of Object.entries(Q))J.set(K,z);return new mzQ(J).run(this.parsed).value}format(Q){return dzQ(this.parsed,Q?.indent||"\t")}},ezQ={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"},qR=class Q{constructor(J){if(this.filePath=J,this.headers=new Headers,this.exists=QB.default.existsSync(J),this.exists){this.status=200,this.statusText="OK";let G=QB.default.statSync(J);this.headers.set("content-length",G.size.toString()),this.updateContentType();let H=QB.default.createReadStream(J);this.body=new ReadableStream({start(K){H.on("data",(z)=>K.enqueue(z)),H.on("end",()=>K.close()),H.on("error",(z)=>K.error(z))},cancel(){H.destroy()}})}else this.status=404,this.statusText="Not Found",this.body=null}updateContentType(){let J=this.filePath.toString().split(".").pop().toLowerCase();this.headers.set("content-type",ezQ[J]??"application/octet-stream")}clone(){let J=new Q(this.filePath);return J.exists=this.exists,J.status=this.status,J.statusText=this.statusText,J.headers=new Headers(this.headers),J}async arrayBuffer(){return(await QB.default.promises.readFile(this.filePath)).buffer}async blob(){let J=await QB.default.promises.readFile(this.filePath);return new Blob([J],{type:this.headers.get("content-type")})}async text(){return await QB.default.promises.readFile(this.filePath,"utf8")}async json(){return JSON.parse(await this.text())}},ER=class{constructor(Q){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(Q)}seed(Q){if(Q===void 0||Q===null)if(Y6.IS_CRYPTO_AVAILABLE){let q=new Uint32Array(1);crypto.getRandomValues(q),Q=q[0]}else Q=Date.now()>>>0;let J=this._mt,G=(q,F)=>Math.imul(q,F)>>>0,H=[];for(let q=Q||0;q>0;q=Math.floor(q/4294967296))H.push(q&4294967295);if(!H.length)H.push(0);J[0]=19650218;for(let q=1;q<624;++q)J[q]=G(1812433253,J[q-1]^J[q-1]>>>30)+q>>>0;let K=1,z=0;for(let q=Math.max(624,H.length);q>0;--q,++K,++z){if(K>=624)J[0]=J[623],K=1;if(z>=H.length)z=0;J[K]=(J[K]^G(J[K-1]^J[K-1]>>>30,1664525))+H[z]+z>>>0}for(let q=623;q>0;--q,++K){if(K>=624)J[0]=J[623],K=1;J[K]=(J[K]^G(J[K-1]^J[K-1]>>>30,1566083941))-K>>>0}J[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let Q=this._mt;if(this._idx>=624){for(let G=0;G<624;++G){let H=Q[G]&2147483648|Q[(G+1)%624]&2147483647;Q[G]=(Q[(G+397)%624]^H>>>1^(H&1?2567483615:0))>>>0}this._idx=0}let J=Q[this._idx++];return J^=J>>>11,J^=J<<7&2636928640,J^=J<<15&4022730752,J^=J>>>18,J>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(Q=0,J=1){let G=this._gauss_next;if(this._gauss_next=null,G===null){let H=this.random()*2*Math.PI,K=Math.sqrt(-2*Math.log(1-this.random()));G=Math.cos(H)*K,this._gauss_next=Math.sin(H)*K}return Q+G*J}shuffle(Q){for(let J=Q.length-1;J>0;--J){let G=32-Math.clz32(J+1),H=this._int32()>>>32-G;while(H>J)H=this._int32()>>>32-G;let K=Q[J];Q[J]=Q[H],Q[H]=K}}choices(Q,J){return Q[oI0(this._random_fn,J)]}};function oI0(Q,J){let G=0;for(let K=0;K<J.length;++K)G+=J[K];let H=Q()*G;for(let K=0;K<J.length;++K)if(H-=J[K],H<0)return K;return J.length-1}var TW=new ER,C90=Object.freeze({Random:ER,seed:TW.seed.bind(TW),random:TW.random.bind(TW),gauss:TW.gauss.bind(TW),shuffle:TW.shuffle.bind(TW),choices:TW.choices.bind(TW)}),QVQ=(Q)=>oI0(C90.random,Q),XVQ=new ER,nI0=class{constructor(Q){this.path=Q}async match(Q){let J=EF.default.join(this.path,Q),G=new qR(J);if(G.exists)return G;else return}async put(Q,J,G=void 0){let H=EF.default.join(this.path,Q),K=Y6.IS_PROCESS_AVAILABLE?process.pid:Date.now(),z=XVQ._int32().toString(36),q=H+`.tmp.${K}.${z}`;try{let F=J.headers.get("Content-Length"),D=parseInt(F??"0"),V=0;await ZV.default.promises.mkdir(EF.default.dirname(H),{recursive:!0});let O=ZV.default.createWriteStream(q),P=J.body.getReader();while(!0){let{done:N,value:I}=await P.read();if(N)break;await new Promise((w,E)=>{O.write(I,(T)=>{if(T){E(T);return}w()})}),V+=I.length;let R=D?V/D*100:0;G?.({progress:R,loaded:V,total:D})}await new Promise((N,I)=>{O.close((R)=>R?I(R):N())}),await ZV.default.promises.rename(q,H)}catch(F){try{await ZV.default.promises.unlink(q)}catch{}throw F}}async delete(Q){let J=EF.default.join(this.path,Q);try{return await ZV.default.promises.unlink(J),!0}catch(G){return!1}}},JVQ={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"},SC0=100,YVQ=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function iC(...Q){return Q=Q.map((J,G)=>{if(G)J=J.replace(new RegExp("^/"),"");if(G!==Q.length-1)J=J.replace(new RegExp("/$"),"");return J}),Q.join("/")}function wV(Q,J=null,G=null){let H;try{H=new URL(Q)}catch(K){return!1}if(J&&!J.includes(H.protocol))return!1;if(G&&!G.includes(H.hostname))return!1;return!0}function GVQ(Q){if(!YVQ.test(Q))return!1;if(Q.includes("..")||Q.includes("--"))return!1;if(Q.endsWith(".git")||Q.endsWith(".ipynb"))return!1;return!0}function WVQ(Q,J,G){if(!G)return null;let H=JVQ[Q]??`Error (${Q}) occurred while trying to load file`;throw Error(`${H}: "${J}".`)}async function HVQ(Q,J,G){let H=Q.headers.get("Content-Length"),K=H?parseInt(H,10):G??0;if(H===null&&!G)g8.warn("Unable to determine content-length from response headers. Will expand buffer when needed.");let z=new Uint8Array(K),q=0,F=Q.body.getReader();async function D(){let{done:V,value:O}=await F.read();if(V)return;let P=q+O.length;if(P>K){K=P;let I=new Uint8Array(K);I.set(z),z=I}z.set(O,q),q=P;let N=q/K*100;return J({progress:N,loaded:q,total:K}),D()}return await D(),z}function TC0(Q){return wV(Q,["blob:"])}function kC0(Q){let J;if(typeof location<"u"&&location.href)J=location.href;else if("object"<"u")J="file:///C:/mcp-tools-for-obsidian.ts";else return Q;return new URL(Q,J).href}var aI0="SHA-256",BVQ="experimental_transformers-hash-cache",yC0=(Q)=>({algorithm:aI0,value:Q}),vC0=class{#X=null;_getHashCache=()=>{return this.#X??=caches.open(BVQ),this.#X};static isAvailable=()=>typeof navigator<"u"&&("crossOriginStorage"in navigator);match=async(Q)=>{let J=await this._getFileHash(Q);if(!J)return;try{let[G]=await navigator.crossOriginStorage.requestFileHandles([yC0(J)]),H=await G.getFile();return new Response(H,{headers:{"Content-Length":String(H.size)}})}catch{return}};put=async(Q,J)=>{let G=await this._getFileHash(Q);if(G){let H=await J.blob();await this._storeBlobInCOS(H,G)}else this._processAndStore(Q,J.body)};_storeBlobInCOS=async(Q,J)=>{let[G]=await navigator.crossOriginStorage.requestFileHandles([yC0(J)],{create:!0}),H=await G.createWritable();await H.write(Q),await H.close()};_processAndStore=async(Q,J)=>{try{let G=[];for await(let z of J)G.push(z);let H=new Blob(G),K=await this._getBlobHash(H);await this._storeBlobInCOS(H,K);try{await(await this._getHashCache()).put(Q,new Response(K))}catch{}}catch{}};delete=async(Q)=>{try{return await(await this._getHashCache()).delete(Q)}catch{return!1}};_getFileHash=async(Q)=>{try{let J=await this._getHashCache(),G=await J.match(Q);if(G)return G.text();let H=await this._getLfsFileHash(Q);if(H)return await J.put(Q,new Response(H)),H;return null}catch{return null}};_getLfsFileHash=async(Q)=>{if(!Q.includes("/resolve/"))return null;let J=Q.replace("/resolve/","/raw/");try{let H=(await fetch(J).then((K)=>K.text())).match(/^oid sha256:([0-9a-f]+)$/m);return H?H[1]:null}catch{return null}};_getBlobHash=async(Q)=>{let J=await Q.arrayBuffer(),G=await crypto.subtle.digest(aI0,J);return Array.from(new Uint8Array(G)).map((K)=>K.toString(16).padStart(2,"0")).join("")}};async function I90(Q=null){let J=null;if(A6.useCustomCache){if(!A6.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!A6.customCache.match||!A6.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");J=A6.customCache}if(!J&&A6.experimental_useCrossOriginStorage&&vC0.isAvailable())J=new vC0;if(!J&&A6.useBrowserCache){if(typeof caches>"u")throw Error("Browser cache is not available in this environment.");try{J=await caches.open(A6.cacheKey)}catch(G){g8.warn("An error occurred while opening the browser cache:",G)}}if(!J&&A6.useFSCache){if(!Y6.IS_FS_AVAILABLE)throw Error("File System Cache is not available in this environment.");J=new nI0(Q??A6.cacheDir)}return J}async function AVQ(Q,...J){for(let G of J)try{let H=await Q.match(G);if(H)return H}catch(H){continue}return}var KVQ=class{#X;#Q;constructor(Q){this.#X=Q,this.#Q=new Map}get(Q){if(!this.#Q.has(Q))return;let J=this.#Q.get(Q);return this.#Q.delete(Q),this.#Q.set(Q,J),J}put(Q,J){if(this.#Q.has(Q))this.#Q.delete(Q);if(this.#Q.set(Q,J),this.#Q.size>this.#X)this.#Q.delete(this.#Q.keys().next().value)}delete(Q){return this.#Q.delete(Q)}clear(){this.#Q.clear()}},zVQ=100,I60=new KVQ(zVQ);function sI0(Q,J){let G=I60.get(Q);if(G!==void 0)return G;let H=J().then((K)=>K,(K)=>{return I60.delete(Q),Promise.reject(K)});return I60.put(Q,H),H}async function VVQ(Q){if(!wV(Q,["http:","https:"]))return null;let J=rI0(Q);return J.set("Range","bytes=0-0"),A6.fetch(Q,{method:"GET",headers:J,cache:"no-store"})}function uF(Q,J,G={}){let H=JSON.stringify([Q,J,G?.revision,G?.cache_dir,G?.local_files_only]);return sI0(H,()=>qVQ(Q,J,G))}async function qVQ(Q,J,G){let H=await I90(G?.cache_dir),{localPath:K,remoteURL:z,proposedCacheKey:q,validModelId:F}=tI0(Q,J,G,H),D=await eI0(H,K,q);if(D!==void 0&&typeof D!=="string"){let V=D.headers.get("content-length"),O=D.headers.get("content-type");return{exists:!0,size:V?parseInt(V,10):void 0,contentType:O||void 0,fromCache:!0}}if(A6.allowLocalModels){if(!wV(K,["http:","https:"]))try{let O=await xF(K);if(typeof O!=="string"&&O.status!==404){let P=O.headers.get("content-length"),N=O.headers.get("content-type");return{exists:!0,size:P?parseInt(P,10):void 0,contentType:N||void 0,fromCache:!1}}}catch(O){}}if(A6.allowRemoteModels&&!G.local_files_only&&F)try{let V=await VVQ(z);if(V&&V.status>=200&&V.status<300){let O,P=V.headers.get("content-type");if(V.status===206){let N=V.headers.get("content-range");if(N){let I=N.match(/bytes \d+-\d+\/(\d+)/);if(I)O=parseInt(I[1],10)}}else if(V.status===200)try{await V.body?.cancel()}catch(N){}if(O===void 0){let N=V.headers.get("content-length");O=N?parseInt(N,10):void 0}return{exists:!0,size:O,contentType:P||void 0,fromCache:!1}}}catch(V){g8.warn(`Unable to fetch file metadata for "${z}": ${V}`)}return{exists:!1,fromCache:!1}}async function xF(Q){if(A6.useFS&&!wV(Q,["http:","https:","blob:"]))return new qR(Q instanceof URL?Q.protocol==="file:"?Q.pathname:Q.toString():Q);else return A6.fetch(Q,{headers:rI0(Q)})}function rI0(Q){let J=typeof process<"u"&&process?.release?.name==="node",G=new Headers;if(J){let H=!!process.env?.TESTING_REMOTELY,K=A6.version;if(G.set("User-Agent",`transformers.js/${K}; is_ci/${H};`),wV(Q,["http:","https:"],["huggingface.co","hf.co"])){let q=process.env?.HF_TOKEN??process.env?.HF_ACCESS_TOKEN;if(q)G.set("Authorization",`Bearer ${q}`)}}return G}function tI0(Q,J,G={},H=null){let K=G.revision??"main",z=iC(Q,J),q=GVQ(Q),F=q?iC(A6.localModelPath,z):z,D=iC(A6.remoteHost,A6.remotePathTemplate.replaceAll("{model}",Q).replaceAll("{revision}",encodeURIComponent(K)),J),V=H instanceof nI0?K==="main"?z:iC(Q,K,J):D;return{requestURL:z,localPath:F,remoteURL:D,proposedCacheKey:V,validModelId:q}}async function eI0(Q,J,G){if(!Q)return;return await AVQ(Q,J,G)}async function UVQ(Q,J,G,H,K,z,q={}){if(await G.match(H)!==void 0)return;if(!z){let F=q.progress_callback?(D)=>UH(q.progress_callback,{status:"progress",name:Q,file:J,...D}):void 0;await G.put(H,K,F)}else if(typeof K!=="string"){let F=new Headers(K.headers);F.set("content-length",z.byteLength.toString()),await G.put(H,new Response(z,{headers:F})).catch((D)=>{g8.warn(`Unable to add response to browser cache: ${D}.`)})}}async function $VQ(Q,J,G=!0,H={},K=!1,z=null){let{requestURL:q,localPath:F,remoteURL:D,proposedCacheKey:V,validModelId:O}=tI0(Q,J,H,z),P,N=!1,I;I=await eI0(z,F,V);let R=I!==void 0;if(R)P=V;else{if(A6.allowLocalModels){if(!wV(q,["http:","https:"]))try{I=await xF(F),P=F}catch(y){g8.warn(`Unable to load from local path "${F}": "${y}"`)}else if(H.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${q}.`);else if(!A6.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${q}.`)}if(I===void 0||typeof I!=="string"&&I.status===404){if(H.local_files_only||!A6.allowRemoteModels)if(G)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${F}".`);else return null;if(!O)throw Error(`Local file missing at "${F}" and download aborted due to invalid model ID "${Q}".`);if(I=await xF(D),I.status!==200)return WVQ(I.status,D,G);P=V}N=z&&typeof Response<"u"&&I instanceof Response&&I.status===200}UH(H.progress_callback,{status:"download",name:Q,file:J});let w;if(Y6.IS_NODE_ENV&&K);else{let T;if(typeof I!=="string")if(!H.progress_callback)T=new Uint8Array(await I.arrayBuffer());else if(R&&typeof navigator<"u"&&/firefox/i.test(navigator.userAgent))T=new Uint8Array(await I.arrayBuffer()),UH(H.progress_callback,{status:"progress",name:Q,file:J,progress:100,loaded:T.length,total:T.length});else{let y,x=I.headers.get("content-length");if(x)y=parseInt(x,10);else try{let b=await uF(Q,J,H);if(b.size)y=b.size}catch(b){}T=await HVQ(I,(b)=>{UH(H.progress_callback,{status:"progress",name:Q,file:J,...b})},y)}w=T}if(N&&P&&typeof I!=="string")await UVQ(Q,J,z,P,I,w,H);if(Y6.IS_NODE_ENV&&K&&H.progress_callback&&typeof I!=="string"){let T=parseInt(I.headers.get("content-length"),10)||0;UH(H.progress_callback,{status:"progress",name:Q,file:J,progress:100,loaded:T,total:T})}if(UH(H.progress_callback,{status:"done",name:Q,file:J}),w){if(!Y6.IS_NODE_ENV&&K)throw Error("Cannot return path in a browser environment.");return w}if(I instanceof qR)return I.filePath;let E=await z?.match(P);if(E instanceof qR)return E.filePath;else if(E instanceof Response)return new Uint8Array(await E.arrayBuffer());else if(typeof E==="string")return E;throw Error("Unable to get model file path or buffer.")}var oC=new Map;async function UR(Q,J,G=!0,H={},K=!1){if(!A6.allowLocalModels){if(H.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`).");else if(!A6.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}UH(H.progress_callback,{status:"initiate",name:Q,file:J});let z=`${Q}::${J}`,q=oC.get(z);if(!q){let F=await I90(H?.cache_dir);q=$VQ(Q,J,G,H,K,F).then((D)=>{return oC.delete(z),D},(D)=>{throw oC.delete(z),D}),oC.set(z,q)}return await q}async function R90(Q,J,G=!0,H={}){let K=await UR(Q,J,G,H,!1);if(K===null)return null;return new TextDecoder("utf-8").decode(K)}async function bW(Q,J,G=!0,H={}){let K=await R90(Q,J,G,H);if(K===null)return{};return JSON.parse(K)}function ZVQ(Q,[J,G,H],[K,z],q="bilinear",F=!1){let D=z/H,V=K/G,O=new Q.constructor(K*z*J),P=G*H,N=K*z;for(let I=0;I<K;++I)for(let R=0;R<z;++R){let w=I*z+R,E=(R+0.5)/D-0.5,T=(I+0.5)/V-0.5,y=Math.floor(E),x=Math.floor(T),b=Math.min(y+1,H-1),g=Math.min(x+1,G-1);y=Math.max(y,0),x=Math.max(x,0);let l=E-y,_=T-x,a=(1-l)*(1-_),r=l*(1-_),f0=(1-l)*_,t=l*_,p0=x*H,u0=g*H,d=p0+y,n=p0+b,c0=u0+y,WQ=u0+b;for(let R0=0;R0<J;++R0){let l0=R0*P;O[R0*N+w]=a*Q[l0+d]+r*Q[l0+n]+f0*Q[l0+c0]+t*Q[l0+WQ]}}return O}function FVQ(Q,J,G){let H=Array(G.length),K=Array(G.length);for(let F=G.length-1,D=1;F>=0;--F)K[F]=D,H[F]=J[G[F]],D*=H[F];let z=G.map((F,D)=>K[G.indexOf(D)]),q=new Q.constructor(Q.length);for(let F=0;F<Q.length;++F){let D=0;for(let V=J.length-1,O=F;V>=0;--V)D+=O%J[V]*z[V],O=Math.floor(O/J[V]);q[D]=Q[F]}return[q,H]}function wX(Q){let J=D7(Q)[0],G=Q.map((z)=>Math.exp(z-J)),H=G.reduce((z,q)=>z+q,0);return G.map((z)=>z/H)}function DVQ(Q){let J=D7(Q)[0],G=0;for(let z=0;z<Q.length;++z)G+=Math.exp(Q[z]-J);let H=Math.log(G);return Q.map((z)=>z-J-H)}function G90(Q){if(Q.length===0)throw Error("Array must not be empty");let J=Q[0],G=0;for(let H=1;H<Q.length;++H)if(Q[H]<J)J=Q[H],G=H;return[J,G]}function D7(Q){if(Q.length===0)throw Error("Array must not be empty");let J=Q[0],G=0;for(let H=1;H<Q.length;++H)if(Q[H]>J)J=Q[H],G=H;return[J,G]}function QR0(Q){return Q>0&&(Q&Q-1)===0}var XR0=class{constructor(Q){if(this.size=Q|0,this.size<=1||!QR0(this.size))throw Error("FFT size must be a power of two larger than 1");this._csize=Q<<1,this.table=new Float64Array(this.size*2);for(let G=0;G<this.table.length;G+=2){let H=Math.PI*G/this.size;this.table[G]=Math.cos(H),this.table[G+1]=-Math.sin(H)}let J=0;for(let G=1;this.size>G;G<<=1)++J;this._width=J%2===0?J-1:J,this._bitrev=new Int32Array(1<<this._width);for(let G=0;G<this._bitrev.length;++G){this._bitrev[G]=0;for(let H=0;H<this._width;H+=2){let K=this._width-H-2;this._bitrev[G]|=(G>>>H&3)<<K}}}createComplexArray(){return new Float64Array(this._csize)}fromComplexArray(Q,J){let G=J||Array(Q.length>>>1);for(let H=0;H<Q.length;H+=2)G[H>>>1]=Q[H];return G}toComplexArray(Q,J){let G=J||this.createComplexArray();for(let H=0;H<G.length;H+=2)G[H]=Q[H>>>1],G[H+1]=0;return G}transform(Q,J){if(Q===J)throw Error("Input and output buffers must be different");this._transform4(Q,J,1)}realTransform(Q,J){if(Q===J)throw Error("Input and output buffers must be different");this._realTransform4(Q,J,1)}inverseTransform(Q,J){if(Q===J)throw Error("Input and output buffers must be different");this._transform4(Q,J,-1);for(let G=0;G<Q.length;++G)Q[G]/=this.size}_transform4(Q,J,G){let H=this._csize,z=1<<this._width,q=H/z<<1,F,D,V=this._bitrev;if(q===4)for(F=0,D=0;F<H;F+=q,++D){let P=V[D];this._singleTransform2(J,Q,F,P,z)}else for(F=0,D=0;F<H;F+=q,++D){let P=V[D];this._singleTransform4(J,Q,F,P,z,G)}let O=this.table;for(z>>=2;z>=2;z>>=2){q=H/z<<1;let P=q>>>2;for(F=0;F<H;F+=q){let N=F+P-1;for(let I=F,R=0;I<N;I+=2,R+=z){let w=I,E=w+P,T=E+P,y=T+P,x=Q[w],b=Q[w+1],g=Q[E],l=Q[E+1],_=Q[T],a=Q[T+1],r=Q[y],f0=Q[y+1],t=O[R],p0=G*O[R+1],u0=g*t-l*p0,d=g*p0+l*t,n=O[2*R],c0=G*O[2*R+1],WQ=_*n-a*c0,R0=_*c0+a*n,l0=O[3*R],d0=G*O[3*R+1],m0=r*l0-f0*d0,ZQ=r*d0+f0*l0,LQ=x+WQ,h0=b+R0,pQ=x-WQ,iQ=b-R0,mQ=u0+m0,AQ=d+ZQ,MQ=G*(u0-m0),DQ=G*(d-ZQ);Q[w]=LQ+mQ,Q[w+1]=h0+AQ,Q[E]=pQ+DQ,Q[E+1]=iQ-MQ,Q[T]=LQ-mQ,Q[T+1]=h0-AQ,Q[y]=pQ-DQ,Q[y+1]=iQ+MQ}}}}_singleTransform2(Q,J,G,H,K){let z=Q[H],q=Q[H+1],F=Q[H+K],D=Q[H+K+1];J[G]=z+F,J[G+1]=q+D,J[G+2]=z-F,J[G+3]=q-D}_singleTransform4(Q,J,G,H,K,z){let q=K*2,F=K*3,D=Q[H],V=Q[H+1],O=Q[H+K],P=Q[H+K+1],N=Q[H+q],I=Q[H+q+1],R=Q[H+F],w=Q[H+F+1],E=D+N,T=V+I,y=D-N,x=V-I,b=O+R,g=P+w,l=z*(O-R),_=z*(P-w);J[G]=E+b,J[G+1]=T+g,J[G+2]=y+_,J[G+3]=x-l,J[G+4]=E-b,J[G+5]=T-g,J[G+6]=y-_,J[G+7]=x+l}_realTransform4(Q,J,G){let H=this._csize,z=1<<this._width,q=H/z<<1,F,D,V=this._bitrev;if(q===4)for(F=0,D=0;F<H;F+=q,++D){let N=V[D];this._singleRealTransform2(J,Q,F,N>>>1,z>>>1)}else for(F=0,D=0;F<H;F+=q,++D){let N=V[D];this._singleRealTransform4(J,Q,F,N>>>1,z>>>1,G)}let O=this.table;for(z>>=2;z>=2;z>>=2){q=H/z<<1;let N=q>>>1,I=N>>>1,R=I>>>1;for(F=0;F<H;F+=q)for(let w=0,E=0;w<=R;w+=2,E+=z){let T=F+w,y=T+I,x=y+I,b=x+I,g=Q[T],l=Q[T+1],_=Q[y],a=Q[y+1],r=Q[x],f0=Q[x+1],t=Q[b],p0=Q[b+1],u0=g,d=l,n=O[E],c0=G*O[E+1],WQ=_*n-a*c0,R0=_*c0+a*n,l0=O[2*E],d0=G*O[2*E+1],m0=r*l0-f0*d0,ZQ=r*d0+f0*l0,LQ=O[3*E],h0=G*O[3*E+1],pQ=t*LQ-p0*h0,iQ=t*h0+p0*LQ,mQ=u0+m0,AQ=d+ZQ,MQ=u0-m0,DQ=d-ZQ,bQ=WQ+pQ,j8=R0+iQ,tQ=G*(WQ-pQ),K8=G*(R0-iQ);if(Q[T]=mQ+bQ,Q[T+1]=AQ+j8,Q[y]=MQ+K8,Q[y+1]=DQ-tQ,w===0){Q[x]=mQ-bQ,Q[x+1]=AQ-j8;continue}if(w===R)continue;let k8=F+I-w,d6=F+N-w;Q[k8]=MQ-G*K8,Q[k8+1]=-DQ-G*tQ,Q[d6]=mQ-G*bQ,Q[d6+1]=-AQ+G*j8}}let P=H>>>1;for(let N=2;N<P;N+=2)Q[H-N]=Q[N],Q[H-N+1]=-Q[N+1]}_singleRealTransform2(Q,J,G,H,K){let z=Q[H],q=Q[H+K];J[G]=z+q,J[G+1]=0,J[G+2]=z-q,J[G+3]=0}_singleRealTransform4(Q,J,G,H,K,z){let q=K*2,F=K*3,D=Q[H],V=Q[H+K],O=Q[H+q],P=Q[H+F],N=D+O,I=D-O,R=V+P,w=z*(V-P);J[G]=N+R,J[G+1]=0,J[G+2]=I,J[G+3]=-w,J[G+4]=N-R,J[G+5]=0,J[G+6]=I,J[G+7]=w}},MVQ=class{constructor(Q){let J=2*(Q-1),G=2*(2*Q-1),H=2**Math.ceil(Math.log2(G));this.bufferSize=H,this._a=J;let K=new Float64Array(G),z=new Float64Array(H);this._chirpBuffer=new Float64Array(H),this._buffer1=new Float64Array(H),this._buffer2=new Float64Array(H),this._outBuffer1=new Float64Array(H),this._outBuffer2=new Float64Array(H);let q=-2*Math.PI/Q,F=Math.cos(q),D=Math.sin(q);for(let V=0;V<G>>1;++V){let O=(V+1-Q)**2/2,P=Math.sqrt(F**2+D**2)**O,N=O*Math.atan2(D,F),I=2*V;K[I]=P*Math.cos(N),K[I+1]=P*Math.sin(N),z[I]=K[I],z[I+1]=-K[I+1]}this._slicedChirpBuffer=K.subarray(J,G),this._f=new XR0(H>>1),this._f.transform(this._chirpBuffer,z)}_transform(Q,J,G){let H=this._buffer1,K=this._buffer2,z=this._outBuffer1,q=this._outBuffer2,F=this._chirpBuffer,D=this._slicedChirpBuffer,V=this._a;if(G)for(let O=0;O<D.length;O+=2){let P=O+1,N=O>>1,I=J[N];H[O]=I*D[O],H[P]=I*D[P]}else for(let O=0;O<D.length;O+=2){let P=O+1;H[O]=J[O]*D[O]-J[P]*D[P],H[P]=J[O]*D[P]+J[P]*D[O]}this._f.transform(z,H);for(let O=0;O<F.length;O+=2){let P=O+1;K[O]=z[O]*F[O]-z[P]*F[P],K[P]=z[O]*F[P]+z[P]*F[O]}this._f.inverseTransform(q,K);for(let O=0;O<q.length;O+=2){let P=q[O+V],N=q[O+V+1],I=D[O],R=D[O+1];Q[O]=P*I-N*R,Q[O+1]=P*R+N*I}}transform(Q,J){this._transform(Q,J,!1)}realTransform(Q,J){this._transform(Q,J,!0)}},LVQ=class{constructor(Q){if(this.fft_length=Q,this.isPowerOfTwo=QR0(Q),this.isPowerOfTwo)this.fft=new XR0(Q),this.outputBufferSize=2*Q;else this.fft=new MVQ(Q),this.outputBufferSize=this.fft.bufferSize}realTransform(Q,J){this.fft.realTransform(Q,J)}transform(Q,J){this.fft.transform(Q,J)}};function OVQ(Q,J){if(J%2===0||J<=0)throw Error("Window size must be a positive odd number");let G=new Q.constructor(Q.length),H=new Q.constructor(J),K=Math.floor(J/2);for(let z=0;z<Q.length;++z){let q=0;for(let F=-K;F<=K;++F){let D=z+F;if(D<0)D=Math.abs(D);else if(D>=Q.length)D=2*(Q.length-1)-D;H[q++]=Q[D]}H.sort(),G[z]=H[K]}return G}function SF(Q,J){let G=Math.pow(10,J);return Math.round(Q*G)/G}function PVQ(Q){let J=Math.round(Q);return Math.abs(Q)%1===0.5?J%2===0?J:J-1:J}function NVQ(Q){let J=Q.length,G=Q[0].length,H=[J+1,G+1],K=Array.from({length:H[0]},()=>Array(H[1]).fill(1/0));K[0][0]=0;let z=Array.from({length:H[0]},()=>Array(H[1]).fill(-1));for(let O=1;O<H[1];++O)for(let P=1;P<H[0];++P){let N=K[P-1][O-1],I=K[P-1][O],R=K[P][O-1],w,E;if(N<I&&N<R)w=N,E=0;else if(I<N&&I<R)w=I,E=1;else w=R,E=2;K[P][O]=Q[P-1][O-1]+w,z[P][O]=E}for(let O=0;O<H[1];++O)z[0][O]=2;for(let O=0;O<H[0];++O)z[O][0]=1;let q=J,F=G,D=[],V=[];while(q>0||F>0)switch(D.push(q-1),V.push(F-1),z[q][F]){case 0:--q,--F;break;case 1:--q;break;case 2:--F;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${q}, ${F}]. Please file a bug report.`)}return D.reverse(),V.reverse(),[D,V]}var jVQ=function(){let Q=null;return function(J){if(!Q){Q=new Float32Array(65536);let z=new ArrayBuffer(4),q=new Uint32Array(z),F=new Float32Array(z);for(let D=0;D<Q.length;++D){let V=0,O=(D&32768)<<16,P=(D&31744)>>10,N=D&1023;if(P===31)V=O|2139095040|N<<13;else if(P===0)if(N===0)V=O;else{let I=113;while((N&1024)===0)N<<=1,--I;N&=-1025,V=O|I<<23|N<<13}else V=O|P+112<<23|N<<13;q[0]=V,Q[D]=F[0]}}let G=J.length,H=Q,K=new Float32Array(G);for(let z=0;z<G;++z)K[z]=H[J[z]];return K}}(),JR0={};IV(JR0,{InferenceSession:()=>S90,TRACE:()=>ZR,TRACE_EVENT_BEGIN:()=>$H,TRACE_EVENT_END:()=>ZH,TRACE_FUNC_BEGIN:()=>BB,TRACE_FUNC_END:()=>AB,Tensor:()=>kG,default:()=>eVQ,env:()=>l9,registerBackend:()=>GB});var{defineProperty:w90,getOwnPropertyDescriptor:IVQ,getOwnPropertyNames:RVQ}=Object,wVQ=Object.prototype.hasOwnProperty,EVQ=((Q)=>typeof KV<"u"?KV:typeof Proxy<"u"?new Proxy(Q,{get:(J,G)=>(typeof KV<"u"?KV:J)[G]}):Q)(function(Q){if(typeof KV<"u")return KV.apply(this,arguments);throw Error('Dynamic require of "'+Q+'" is not supported')}),q6=(Q,J)=>()=>(Q&&(J=Q(Q=0)),J),pF=(Q,J)=>{for(var G in J)w90(Q,G,{get:J[G],enumerable:!0})},SVQ=(Q,J,G,H)=>{if(J&&typeof J=="object"||typeof J=="function")for(let K of RVQ(J))!wVQ.call(Q,K)&&K!==G&&w90(Q,K,{get:()=>J[K],enumerable:!(H=IVQ(J,K))||H.enumerable});return Q},$R=(Q)=>SVQ(w90({},"__esModule",{value:!0}),Q),NF,BH,GB,xC0,YR0,GR0=q6(()=>{NF=new Map,BH=[],GB=(Q,J,G)=>{if(J&&typeof J.init=="function"&&typeof J.createInferenceSessionHandler=="function"){let H=NF.get(Q);if(H===void 0)NF.set(Q,{backend:J,priority:G});else{if(H.priority>G)return;if(H.priority===G&&H.backend!==J)throw Error(`cannot register backend "${Q}" using priority ${G}`)}if(G>=0){let K=BH.indexOf(Q);K!==-1&&BH.splice(K,1);for(let z=0;z<BH.length;z++)if(NF.get(BH[z]).priority<=G){BH.splice(z,0,Q);return}BH.push(Q)}return}throw TypeError("not a valid backend")},xC0=async(Q)=>{let J=NF.get(Q);if(!J)return"backend not found.";if(J.initialized)return J.backend;if(J.aborted)return J.error;{let G=!!J.initPromise;try{return G||(J.initPromise=J.backend.init(Q)),await J.initPromise,J.initialized=!0,J.backend}catch(H){return G||(J.error=`${H}`,J.aborted=!0),J.error}finally{delete J.initPromise}}},YR0=async(Q)=>{let J=Q.executionProviders||[],G=J.map((D)=>typeof D=="string"?D:D.name),H=G.length===0?BH:G,K,z=[],q=new Set;for(let D of H){let V=await xC0(D);typeof V=="string"?z.push({name:D,err:V}):(K||(K=V),K===V&&q.add(D))}if(!K)throw Error(`no available backend found. ERR: ${z.map((D)=>`[${D.name}] ${D.err}`).join(", ")}`);for(let{name:D,err:V}of z)G.includes(D)&&console.warn(`removing requested execution provider "${D}" from session options because it is not available: ${V}`);let F=J.filter((D)=>q.has(typeof D=="string"?D:D.name));return[K,new Proxy(Q,{get:(D,V)=>V==="executionProviders"?F:Reflect.get(D,V)})]}}),TVQ=q6(()=>{GR0()}),WR0,kVQ=q6(()=>{WR0="1.24.0-dev.20251116-b39e144322"}),R60,QX,HR0=q6(()=>{kVQ(),R60="warning",QX={wasm:{},webgl:{},webgpu:{},versions:{common:WR0},set logLevel(Q){if(Q!==void 0){if(typeof Q!="string"||["verbose","info","warning","error","fatal"].indexOf(Q)===-1)throw Error(`Unsupported logging level: ${Q}`);R60=Q}},get logLevel(){return R60}},Object.defineProperty(QX,"logLevel",{enumerable:!0})}),l9,yVQ=q6(()=>{HR0(),l9=QX}),BR0,AR0,vVQ=q6(()=>{BR0=(Q,J)=>{let G=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);G.width=Q.dims[3],G.height=Q.dims[2];let H=G.getContext("2d");if(H!=null){let K,z;J?.tensorLayout!==void 0&&J.tensorLayout==="NHWC"?(K=Q.dims[2],z=Q.dims[3]):(K=Q.dims[3],z=Q.dims[2]);let q=J?.format!==void 0?J.format:"RGB",F=J?.norm,D,V;F===void 0||F.mean===void 0?D=[255,255,255,255]:typeof F.mean=="number"?D=[F.mean,F.mean,F.mean,F.mean]:(D=[F.mean[0],F.mean[1],F.mean[2],0],F.mean[3]!==void 0&&(D[3]=F.mean[3])),F===void 0||F.bias===void 0?V=[0,0,0,0]:typeof F.bias=="number"?V=[F.bias,F.bias,F.bias,F.bias]:(V=[F.bias[0],F.bias[1],F.bias[2],0],F.bias[3]!==void 0&&(V[3]=F.bias[3]));let O=z*K,P=0,N=O,I=O*2,R=-1;q==="RGBA"?(P=0,N=O,I=O*2,R=O*3):q==="RGB"?(P=0,N=O,I=O*2):q==="RBG"&&(P=0,I=O,N=O*2);for(let w=0;w<z;w++)for(let E=0;E<K;E++){let T=(Q.data[P++]-V[0])*D[0],y=(Q.data[N++]-V[1])*D[1],x=(Q.data[I++]-V[2])*D[2],b=R===-1?255:(Q.data[R++]-V[3])*D[3];H.fillStyle="rgba("+T+","+y+","+x+","+b+")",H.fillRect(E,w,1,1)}if("toDataURL"in G)return G.toDataURL();throw Error("toDataURL is not supported")}else throw Error("Can not access image data")},AR0=(Q,J)=>{let G=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),H;if(G!=null){let K,z,q;J?.tensorLayout!==void 0&&J.tensorLayout==="NHWC"?(K=Q.dims[2],z=Q.dims[1],q=Q.dims[3]):(K=Q.dims[3],z=Q.dims[2],q=Q.dims[1]);let F=J!==void 0&&J.format!==void 0?J.format:"RGB",D=J?.norm,V,O;D===void 0||D.mean===void 0?V=[255,255,255,255]:typeof D.mean=="number"?V=[D.mean,D.mean,D.mean,D.mean]:(V=[D.mean[0],D.mean[1],D.mean[2],255],D.mean[3]!==void 0&&(V[3]=D.mean[3])),D===void 0||D.bias===void 0?O=[0,0,0,0]:typeof D.bias=="number"?O=[D.bias,D.bias,D.bias,D.bias]:(O=[D.bias[0],D.bias[1],D.bias[2],0],D.bias[3]!==void 0&&(O[3]=D.bias[3]));let P=z*K;if(J!==void 0&&(J.format!==void 0&&q===4&&J.format!=="RGBA"||q===3&&J.format!=="RGB"&&J.format!=="BGR"))throw Error("Tensor format doesn't match input tensor dims");let N=4,I=0,R=1,w=2,E=3,T=0,y=P,x=P*2,b=-1;F==="RGBA"?(T=0,y=P,x=P*2,b=P*3):F==="RGB"?(T=0,y=P,x=P*2):F==="RBG"&&(T=0,x=P,y=P*2),H=G.createImageData(K,z);for(let g=0;g<z*K;I+=N,R+=N,w+=N,E+=N,g++)H.data[I]=(Q.data[T++]-O[0])*V[0],H.data[R]=(Q.data[y++]-O[1])*V[1],H.data[w]=(Q.data[x++]-O[2])*V[2],H.data[E]=b===-1?255:(Q.data[b++]-O[3])*V[3]}else throw Error("Can not access image data");return H}}),nC,KR0,zR0,VR0,qR0,UR0,xVQ=q6(()=>{E90(),nC=(Q,J)=>{if(Q===void 0)throw Error("Image buffer must be defined");if(J.height===void 0||J.width===void 0)throw Error("Image height and width must be defined");if(J.tensorLayout==="NHWC")throw Error("NHWC Tensor layout is not supported yet");let{height:G,width:H}=J,K=J.norm??{mean:255,bias:0},z,q;typeof K.mean=="number"?z=[K.mean,K.mean,K.mean,K.mean]:z=[K.mean[0],K.mean[1],K.mean[2],K.mean[3]??255],typeof K.bias=="number"?q=[K.bias,K.bias,K.bias,K.bias]:q=[K.bias[0],K.bias[1],K.bias[2],K.bias[3]??0];let F=J.format!==void 0?J.format:"RGBA",D=J.tensorFormat!==void 0&&J.tensorFormat!==void 0?J.tensorFormat:"RGB",V=G*H,O=D==="RGBA"?new Float32Array(V*4):new Float32Array(V*3),P=4,N=0,I=1,R=2,w=3,E=0,T=V,y=V*2,x=-1;F==="RGB"&&(P=3,N=0,I=1,R=2,w=-1),D==="RGBA"?x=V*3:D==="RBG"?(E=0,y=V,T=V*2):D==="BGR"&&(y=0,T=V,E=V*2);for(let b=0;b<V;b++,N+=P,R+=P,I+=P,w+=P)O[E++]=(Q[N]+q[0])/z[0],O[T++]=(Q[I]+q[1])/z[1],O[y++]=(Q[R]+q[2])/z[2],x!==-1&&w!==-1&&(O[x++]=(Q[w]+q[3])/z[3]);return D==="RGBA"?new DY("float32",O,[1,4,G,H]):new DY("float32",O,[1,3,G,H])},KR0=async(Q,J)=>{let G=typeof HTMLImageElement<"u"&&Q instanceof HTMLImageElement,H=typeof ImageData<"u"&&Q instanceof ImageData,K=typeof ImageBitmap<"u"&&Q instanceof ImageBitmap,z=typeof Q=="string",q,F=J??{},D=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw Error("Canvas is not supported")},V=(O)=>typeof HTMLCanvasElement<"u"&&O instanceof HTMLCanvasElement||O instanceof OffscreenCanvas?O.getContext("2d"):null;if(G){let O=D();O.width=Q.width,O.height=Q.height;let P=V(O);if(P!=null){let{height:N,width:I}=Q;if(J!==void 0&&J.resizedHeight!==void 0&&J.resizedWidth!==void 0&&(N=J.resizedHeight,I=J.resizedWidth),J!==void 0){if(F=J,J.tensorFormat!==void 0)throw Error("Image input config format must be RGBA for HTMLImageElement");F.tensorFormat="RGBA",F.height=N,F.width=I}else F.tensorFormat="RGBA",F.height=N,F.width=I;P.drawImage(Q,0,0),q=P.getImageData(0,0,I,N).data}else throw Error("Can not access image data")}else if(H){let O,P;if(J!==void 0&&J.resizedWidth!==void 0&&J.resizedHeight!==void 0?(O=J.resizedHeight,P=J.resizedWidth):(O=Q.height,P=Q.width),J!==void 0&&(F=J),F.format="RGBA",F.height=O,F.width=P,J!==void 0){let N=D();N.width=P,N.height=O;let I=V(N);if(I!=null)I.putImageData(Q,0,0),q=I.getImageData(0,0,P,O).data;else throw Error("Can not access image data")}else q=Q.data}else if(K){if(J===void 0)throw Error("Please provide image config with format for Imagebitmap");let O=D();O.width=Q.width,O.height=Q.height;let P=V(O);if(P!=null){let{height:N,width:I}=Q;return P.drawImage(Q,0,0,I,N),q=P.getImageData(0,0,I,N).data,F.height=N,F.width=I,nC(q,F)}else throw Error("Can not access image data")}else{if(z)return new Promise((O,P)=>{let N=D(),I=V(N);if(!Q||!I)return P();let R=new Image;R.crossOrigin="Anonymous",R.src=Q,R.onload=()=>{N.width=R.width,N.height=R.height,I.drawImage(R,0,0,N.width,N.height);let w=I.getImageData(0,0,N.width,N.height);F.height=N.height,F.width=N.width,O(nC(w.data,F))}});throw Error("Input data provided is not supported - aborted tensor creation")}if(q!==void 0)return nC(q,F);throw Error("Input data provided is not supported - aborted tensor creation")},zR0=(Q,J)=>{let{width:G,height:H,download:K,dispose:z}=J;return new DY({location:"texture",type:"float32",texture:Q,dims:[1,H,G,4],download:K,dispose:z})},VR0=(Q,J)=>{let{dataType:G,dims:H,download:K,dispose:z}=J;return new DY({location:"gpu-buffer",type:G??"float32",gpuBuffer:Q,dims:H,download:K,dispose:z})},qR0=(Q,J)=>{let{dataType:G,dims:H,download:K,dispose:z}=J;return new DY({location:"ml-tensor",type:G??"float32",mlTensor:Q,dims:H,download:K,dispose:z})},UR0=(Q,J,G)=>new DY({location:"cpu-pinned",type:Q,data:J,dims:G??[J.length]})}),JB,TF,w60,$R0,bVQ=q6(()=>{JB=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),TF=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),w60=!1,$R0=()=>{if(!w60){w60=!0;let Q=typeof BigInt64Array<"u"&&BigInt64Array.from,J=typeof BigUint64Array<"u"&&BigUint64Array.from,G=globalThis.Float16Array,H=typeof G<"u"&&G.from;Q&&(JB.set("int64",BigInt64Array),TF.set(BigInt64Array,"int64")),J&&(JB.set("uint64",BigUint64Array),TF.set(BigUint64Array,"uint64")),H?(JB.set("float16",G),TF.set(G,"float16")):JB.set("float16",Uint16Array)}}}),ZR0,FR0,gVQ=q6(()=>{E90(),ZR0=(Q)=>{let J=1;for(let G=0;G<Q.length;G++){let H=Q[G];if(typeof H!="number"||!Number.isSafeInteger(H))throw TypeError(`dims[${G}] must be an integer, got: ${H}`);if(H<0)throw RangeError(`dims[${G}] must be a non-negative integer, got: ${H}`);J*=H}return J},FR0=(Q,J)=>{switch(Q.location){case"cpu":return new DY(Q.type,Q.data,J);case"cpu-pinned":return new DY({location:"cpu-pinned",data:Q.data,type:Q.type,dims:J});case"texture":return new DY({location:"texture",texture:Q.texture,type:Q.type,dims:J});case"gpu-buffer":return new DY({location:"gpu-buffer",gpuBuffer:Q.gpuBuffer,type:Q.type,dims:J});case"ml-tensor":return new DY({location:"ml-tensor",mlTensor:Q.mlTensor,type:Q.type,dims:J});default:throw Error(`tensorReshape: tensor location ${Q.location} is not supported`)}}}),DY,E90=q6(()=>{vVQ(),xVQ(),bVQ(),gVQ(),DY=class{constructor(Q,J,G){$R0();let H,K;if(typeof Q=="object"&&"location"in Q)switch(this.dataLocation=Q.location,H=Q.type,K=Q.dims,Q.location){case"cpu-pinned":{let q=JB.get(H);if(!q)throw TypeError(`unsupported type "${H}" to create tensor from pinned buffer`);if(!(Q.data instanceof q))throw TypeError(`buffer should be of type ${q.name}`);this.cpuData=Q.data;break}case"texture":{if(H!=="float32")throw TypeError(`unsupported type "${H}" to create tensor from texture`);this.gpuTextureData=Q.texture,this.downloader=Q.download,this.disposer=Q.dispose;break}case"gpu-buffer":{if(H!=="float32"&&H!=="float16"&&H!=="int32"&&H!=="int64"&&H!=="uint32"&&H!=="uint8"&&H!=="bool"&&H!=="uint4"&&H!=="int4")throw TypeError(`unsupported type "${H}" to create tensor from gpu buffer`);this.gpuBufferData=Q.gpuBuffer,this.downloader=Q.download,this.disposer=Q.dispose;break}case"ml-tensor":{if(H!=="float32"&&H!=="float16"&&H!=="int32"&&H!=="int64"&&H!=="uint32"&&H!=="uint64"&&H!=="int8"&&H!=="uint8"&&H!=="bool"&&H!=="uint4"&&H!=="int4")throw TypeError(`unsupported type "${H}" to create tensor from MLTensor`);this.mlTensorData=Q.mlTensor,this.downloader=Q.download,this.disposer=Q.dispose;break}default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let q,F;if(typeof Q=="string")if(H=Q,F=G,Q==="string"){if(!Array.isArray(J))throw TypeError("A string tensor's data must be a string array.");q=J}else{let D=JB.get(Q);if(D===void 0)throw TypeError(`Unsupported tensor type: ${Q}.`);if(Array.isArray(J)){if(Q==="float16"&&D===Uint16Array||Q==="uint4"||Q==="int4")throw TypeError(`Creating a ${Q} tensor from number array is not supported. Please use ${D.name} as data.`);Q==="uint64"||Q==="int64"?q=D.from(J,BigInt):q=D.from(J)}else if(J instanceof D)q=J;else if(J instanceof Uint8ClampedArray)if(Q==="uint8")q=Uint8Array.from(J);else throw TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Q==="float16"&&J instanceof Uint16Array&&D!==Uint16Array)q=new globalThis.Float16Array(J.buffer,J.byteOffset,J.length);else throw TypeError(`A ${H} tensor's data must be type of ${D}`)}else if(F=J,Array.isArray(Q)){if(Q.length===0)throw TypeError("Tensor type cannot be inferred from an empty array.");let D=typeof Q[0];if(D==="string")H="string",q=Q;else if(D==="boolean")H="bool",q=Uint8Array.from(Q);else throw TypeError(`Invalid element type of data array: ${D}.`)}else if(Q instanceof Uint8ClampedArray)H="uint8",q=Uint8Array.from(Q);else{let D=TF.get(Q.constructor);if(D===void 0)throw TypeError(`Unsupported type for tensor data: ${Q.constructor}.`);H=D,q=Q}if(F===void 0)F=[q.length];else if(!Array.isArray(F))throw TypeError("A tensor's dims must be a number array");K=F,this.cpuData=q,this.dataLocation="cpu"}let z=ZR0(K);if(this.cpuData&&z!==this.cpuData.length&&!((H==="uint4"||H==="int4")&&Math.ceil(z/2)===this.cpuData.length))throw Error(`Tensor's size(${z}) does not match data length(${this.cpuData.length}).`);this.type=H,this.dims=K,this.size=z}static async fromImage(Q,J){return KR0(Q,J)}static fromTexture(Q,J){return zR0(Q,J)}static fromGpuBuffer(Q,J){return VR0(Q,J)}static fromMLTensor(Q,J){return qR0(Q,J)}static fromPinnedBuffer(Q,J,G){return UR0(Q,J,G)}toDataURL(Q){return BR0(this,Q)}toImageData(Q){return AR0(this,Q)}get data(){if(this.ensureValid(),!this.cpuData)throw 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 Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(Q){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let J=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=J,Q&&this.disposer&&(this.disposer(),this.disposer=void 0),J}finally{this.isDownloading=!1}}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw 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.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw Error("The tensor is disposed.")}reshape(Q){if(this.ensureValid(),this.downloader||this.disposer)throw Error("Cannot reshape a tensor that owns GPU resource.");return FR0(this,Q)}}}),kG,DR0=q6(()=>{E90(),kG=DY}),ZR,E60,BB,AB,$H,ZH,MR0=q6(()=>{HR0(),ZR=(Q,J)=>{(typeof QX.trace>"u"?!QX.wasm.trace:!QX.trace)||console.timeStamp(`${Q}::ORT::${J}`)},E60=(Q,J)=>{let G=Error().stack?.split(/\r\n|\r|\n/g)||[],H=!1;for(let K=0;K<G.length;K++){if(H&&!G[K].includes("TRACE_FUNC")){let z=`FUNC_${Q}::${G[K].trim().split(" ")[1]}`;J&&(z+=`::${J}`),ZR("CPU",z);return}G[K].includes("TRACE_FUNC")&&(H=!0)}},BB=(Q)=>{(typeof QX.trace>"u"?!QX.wasm.trace:!QX.trace)||E60("BEGIN",Q)},AB=(Q)=>{(typeof QX.trace>"u"?!QX.wasm.trace:!QX.trace)||E60("END",Q)},$H=(Q)=>{(typeof QX.trace>"u"?!QX.wasm.trace:!QX.trace)||console.time(`ORT::${Q}`)},ZH=(Q)=>{(typeof QX.trace>"u"?!QX.wasm.trace:!QX.trace)||console.timeEnd(`ORT::${Q}`)}}),LR0,hVQ=q6(()=>{GR0(),DR0(),MR0(),LR0=class Q{constructor(J){this.handler=J}async run(J,G,H){BB(),$H("InferenceSession.run");let K={},z={};if(typeof J!="object"||J===null||J instanceof kG||Array.isArray(J))throw TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let q=!0;if(typeof G=="object"){if(G===null)throw TypeError("Unexpected argument[1]: cannot be null.");if(G instanceof kG)throw TypeError("'fetches' cannot be a Tensor");if(Array.isArray(G)){if(G.length===0)throw TypeError("'fetches' cannot be an empty array.");q=!1;for(let V of G){if(typeof V!="string")throw TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(V)===-1)throw RangeError(`'fetches' contains invalid output name: ${V}.`);K[V]=null}if(typeof H=="object"&&H!==null)z=H;else if(typeof H<"u")throw TypeError("'options' must be an object.")}else{let V=!1,O=Object.getOwnPropertyNames(G);for(let P of this.outputNames)if(O.indexOf(P)!==-1){let N=G[P];(N===null||N instanceof kG)&&(V=!0,q=!1,K[P]=N)}if(V){if(typeof H=="object"&&H!==null)z=H;else if(typeof H<"u")throw TypeError("'options' must be an object.")}else z=G}}else if(typeof G<"u")throw TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let V of this.inputNames)if(typeof J[V]>"u")throw Error(`input '${V}' is missing in 'feeds'.`);if(q)for(let V of this.outputNames)K[V]=null;let F=await this.handler.run(J,K,z),D={};for(let V in F)if(Object.hasOwnProperty.call(F,V)){let O=F[V];O instanceof kG?D[V]=O:D[V]=new kG(O.type,O.data,O.dims)}return ZH("InferenceSession.run"),AB(),D}async release(){return this.handler.dispose()}static async create(J,G,H,K){BB(),$H("InferenceSession.create");let z,q={};if(typeof J=="string"){if(z=J,typeof G=="object"&&G!==null)q=G;else if(typeof G<"u")throw TypeError("'options' must be an object.")}else if(J instanceof Uint8Array){if(z=J,typeof G=="object"&&G!==null)q=G;else if(typeof G<"u")throw TypeError("'options' must be an object.")}else if(J instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&J instanceof SharedArrayBuffer){let O=J,P=0,N=J.byteLength;if(typeof G=="object"&&G!==null)q=G;else if(typeof G=="number"){if(P=G,!Number.isSafeInteger(P))throw RangeError("'byteOffset' must be an integer.");if(P<0||P>=O.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${O.byteLength}).`);if(N=J.byteLength-P,typeof H=="number"){if(N=H,!Number.isSafeInteger(N))throw RangeError("'byteLength' must be an integer.");if(N<=0||P+N>O.byteLength)throw RangeError(`'byteLength' is out of range (0, ${O.byteLength-P}].`);if(typeof K=="object"&&K!==null)q=K;else if(typeof K<"u")throw TypeError("'options' must be an object.")}else if(typeof H<"u")throw TypeError("'byteLength' must be a number.")}else if(typeof G<"u")throw TypeError("'options' must be an object.");z=new Uint8Array(O,P,N)}else throw TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[F,D]=await YR0(q),V=await F.createInferenceSessionHandler(z,D);return ZH("InferenceSession.create"),AB(),new Q(V)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),S90,_VQ=q6(()=>{hVQ(),S90=LR0}),fVQ=q6(()=>{}),mVQ=q6(()=>{}),uVQ=q6(()=>{}),pVQ=q6(()=>{}),OR0={};pF(OR0,{InferenceSession:()=>S90,TRACE:()=>ZR,TRACE_EVENT_BEGIN:()=>$H,TRACE_EVENT_END:()=>ZH,TRACE_FUNC_BEGIN:()=>BB,TRACE_FUNC_END:()=>AB,Tensor:()=>kG,env:()=>l9,registerBackend:()=>GB});var KB=q6(()=>{TVQ(),yVQ(),_VQ(),DR0(),fVQ(),mVQ(),MR0(),uVQ(),pVQ()}),T90=q6(()=>{}),PR0={};pF(PR0,{default:()=>NR0});var S60,T60,NR0,lVQ=q6(()=>{hR0(),zB(),k90(),S60="ort-wasm-proxy-worker",T60=globalThis.self?.name===S60,T60&&(self.onmessage=(Q)=>{let{type:J,in:G}=Q.data;try{switch(J){case"init-wasm":y90(G.wasm).then(()=>{h90(G).then(()=>{postMessage({type:J})},(H)=>{postMessage({type:J,err:H})})},(H)=>{postMessage({type:J,err:H})});break;case"init-ep":{let{epName:H,env:K}=G;_90(K,H).then(()=>{postMessage({type:J})},(z)=>{postMessage({type:J,err:z})});break}case"copy-from":{let{buffer:H}=G,K=MR(H);postMessage({type:J,out:K});break}case"create":{let{model:H,options:K}=G;f90(H,K).then((z)=>{postMessage({type:J,out:z})},(z)=>{postMessage({type:J,err:z})});break}case"release":m90(G),postMessage({type:J});break;case"run":{let{sessionId:H,inputIndices:K,inputs:z,outputIndices:q,options:F}=G;u90(H,K,z,q,Array(q.length).fill(null),F).then((D)=>{D.some((V)=>V[3]!=="cpu")?postMessage({type:J,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:J,out:D},l90([...z,...D]))},(D)=>{postMessage({type:J,err:D})});break}case"end-profiling":p90(G),postMessage({type:J});break;default:}}catch(H){postMessage({type:J,err:H})}}),NR0=T60?null:(Q)=>new Worker(Q??ZY,{type:"module",name:S60})}),jR0={};pF(jR0,{default:()=>CR0});async function bC0(Q={}){var J=Q,G=!!globalThis.window,H=!!globalThis.WorkerGlobalScope,K=H&&self.name?.startsWith("em-pthread");J.mountExternalData=(v,h)=>{v.startsWith("./")&&(v=v.substring(2)),(J.Uc||(J.Uc=new Map)).set(v,h)},J.unmountExternalData=()=>{delete J.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let z=()=>{let v=(h)=>(...f)=>{let m=NY;return f=h(...f),NY!=m?new Promise((s,C0)=>{l5={resolve:s,reject:C0}}):f};(()=>{for(let h of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])J[h]=v(J[h])})(),typeof jsepRunAsync<"u"&&(J._OrtRun=jsepRunAsync(J._OrtRun),J._OrtRunWithBinding=jsepRunAsync(J._OrtRunWithBinding)),z=void 0};J.asyncInit=()=>{z?.()};var q,F,D=(v,h)=>{throw h},V="file:///C:/mcp-tools-for-obsidian.ts",O="";if(G||H){try{O=new URL(".",V).href}catch{}H&&(F=(v)=>{var h=new XMLHttpRequest;return h.open("GET",v,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)}),q=async(v)=>{if(l(v))return new Promise((f,m)=>{var s=new XMLHttpRequest;s.open("GET",v,!0),s.responseType="arraybuffer",s.onload=()=>{s.status==200||s.status==0&&s.response?f(s.response):m(s.status)},s.onerror=m,s.send(null)});var h=await fetch(v,{credentials:"same-origin"});if(h.ok)return h.arrayBuffer();throw Error(h.status+" : "+h.url)}}var P,N,I,R,w,E,T=console.log.bind(console),y=console.error.bind(console),x=T,b=y,g=!1,l=(v)=>v.startsWith("file://");function _(){U8.buffer!=f0.buffer&&ZQ()}if(K){let v=function(h){try{var f=h.data,m=f.Oc;if(m==="load"){let s=[];self.onmessage=(C0)=>s.push(C0),E=()=>{postMessage({Oc:"loaded"});for(let C0 of s)v(C0);self.onmessage=v};for(let C0 of f.ce)J[C0]&&!J[C0].proxy||(J[C0]=(...QQ)=>{postMessage({Oc:"callHandler",be:C0,args:QQ})},C0=="print"&&(x=J[C0]),C0=="printErr"&&(b=J[C0]));U8=f.ie,ZQ(),N=f.je,iQ(),qD()}else if(m==="run"){(function(s){var C0=(_(),n)[s+52>>>2>>>0];s=(_(),n)[s+56>>>2>>>0],oX0(C0,C0-s),I8(C0)})(f.Nc),Tw(f.Nc,0,0,1,0,0),e8(),aV(f.Nc),r||(SX0(),r=!0);try{P6(f.ge,f.Wc)}catch(s){if(s!="unwind")throw s}}else f.target!=="setimmediate"&&(m==="checkMailbox"?r&&OB():m&&(b(`worker: received unknown command ${m}`),b(f)))}catch(s){throw pX0(),s}};var a=v,r=!1;self.onunhandledrejection=(h)=>{throw h.reason||h},self.onmessage=v}var f0,t,p0,u0,d,n,c0,WQ,R0,l0,d0,m0=!1;function ZQ(){var v=U8.buffer;J.HEAP8=f0=new Int8Array(v),p0=new Int16Array(v),J.HEAPU8=t=new Uint8Array(v),u0=new Uint16Array(v),J.HEAP32=d=new Int32Array(v),J.HEAPU32=n=new Uint32Array(v),c0=new Float32Array(v),WQ=new Float64Array(v),R0=new BigInt64Array(v),l0=new BigUint64Array(v)}function LQ(){m0=!0,K?E():lW._b()}function h0(v){throw b(v="Aborted("+v+")"),g=!0,v=new WebAssembly.RuntimeError(v+". Build with -sASSERTIONS for more info."),w?.(v),v}function pQ(){return{a:{f:SX,J:f8,k:l8,p:U6,l:G8,sa:e9,b:TX,ca:j6,Ja:x6,q:t6,da:L7,Za:C6,Fa:A9,Ha:kQ,_a:$8,Xa:c6,Qa:XJ,Wa:YX,oa:LY,Ga:sY,Xb:OY,Ya:hW,Yb:pG,db:MH,Da:ZB,Sb:cV,Qb:NJ,Ca:Yw,M:iV,I:Gw,Rb:Ww,ja:tF,Tb:Hw,Ta:Bw,Vb:Kw,Ka:PB,Ob:zw,ka:Vw,Sa:aV,ab:eF,U:iG,n:Zw,c:lG,rb:Fw,w:Dw,L:Mw,z:IB,j:fW,o:GD,sb:WD,G:RB,T:k9,h:HD,u:tV,m:M8,i:wB,Na:jJ,Oa:mW,Pa:IH,La:uW,Ma:jY,Pb:Qq,eb:Xq,cb:Pw,Y:p,qb:Z0,la:XQ,bb:Lw,fb:KQ,$a:yQ,Wb:L8,N:eV,gb:Q6,X:P9,Ub:S7,nb:mS0,C:uS0,ra:pS0,qa:lS0,pb:dS0,W:cS0,v:iS0,mb:oS0,lb:nS0,kb:aS0,ob:sS0,jb:rS0,ib:tS0,hb:eS0,Ua:NX0,Va:jX0,Ia:r9,V:CX0,na:IX0,Ra:RX0,ma:wX0,Cb:Kk0,xa:Yk0,Db:Ak0,ya:Jk0,F:cT0,e:yT0,s:TT0,x:ST0,B:pT0,Fb:eT0,ba:tT0,D:bT0,za:Qk0,$:Gk0,ga:rT0,Gb:sT0,Hb:aT0,Ba:iT0,Aa:nT0,Ib:oT0,wa:Bk0,aa:Xk0,d:kT0,A:xT0,r:vT0,Bb:zk0,t:hT0,y:lT0,H:gT0,E:_T0,K:dT0,R:Wk0,ia:uT0,_:Hk0,Jb:mT0,Kb:fT0,g:XT0,a:U8,Nb:k8,Eb:JT0,ha:YT0,O:GT0,pa:WT0,Lb:HT0,ta:BT0,Q:AT0,yb:KT0,zb:zT0,ua:VT0,ea:qT0,P:UT0,Ea:$T0,va:ZT0,Z:FT0,wb:DT0,Zb:MT0,S:LT0,Ab:OT0,tb:PT0,ub:jT0,vb:CT0,fa:IT0,xb:RT0,Mb:wT0}}}async function iQ(){function v(m,s){var C0=lW=m.exports;m={};for(let[QQ,JQ]of Object.entries(C0))typeof JQ=="function"?(C0=QD(JQ),m[QQ]=C0):m[QQ]=JQ;return lW=m,lW=function(){var QQ=lW,JQ=(hQ)=>(T6)=>hQ(T6)>>>0,OQ=(hQ)=>()=>hQ()>>>0;return(QQ=Object.assign({},QQ)).$b=JQ(QQ.$b),QQ.Cc=OQ(QQ.Cc),QQ.Ec=JQ(QQ.Ec),QQ.rd=((hQ)=>(T6,h6)=>hQ(T6,h6)>>>0)(QQ.rd),QQ.wd=JQ(QQ.wd),QQ.xd=OQ(QQ.xd),QQ.Bd=JQ(QQ.Bd),QQ}(),OJ.push(lW.id),EX0=(m=lW).$b,SX0=m.ac,J._OrtInit=m.bc,J._OrtGetLastError=m.cc,J._OrtCreateSessionOptions=m.dc,J._OrtAppendExecutionProvider=m.ec,J._OrtAddFreeDimensionOverride=m.fc,J._OrtAddSessionConfigEntry=m.gc,J._OrtReleaseSessionOptions=m.hc,J._OrtCreateSession=m.ic,J._OrtReleaseSession=m.jc,J._OrtGetInputOutputCount=m.kc,J._OrtGetInputOutputMetadata=m.lc,J._OrtFree=m.mc,J._OrtCreateTensor=m.nc,J._OrtGetTensorData=m.oc,J._OrtReleaseTensor=m.pc,J._OrtCreateRunOptions=m.qc,J._OrtAddRunConfigEntry=m.rc,J._OrtReleaseRunOptions=m.sc,J._OrtCreateBinding=m.tc,J._OrtBindInput=m.uc,J._OrtBindOutput=m.vc,J._OrtClearBoundOutputs=m.wc,J._OrtReleaseBinding=m.xc,J._OrtRunWithBinding=m.yc,J._OrtRun=m.zc,J._OrtEndProfiling=m.Ac,Cw=J._OrtGetWebGpuDevice=m.Bc,zD=m.Cc,QG=J._free=m.Dc,kB=J._malloc=m.Ec,TX0=J._wgpuBufferRelease=m.Fc,kX0=J._wgpuCreateInstance=m.Gc,yX0=m.Hc,vX0=m.Ic,xX0=m.Jc,bX0=m.Kc,gX0=m.Lc,hX0=m.Pc,_X0=m.Zc,fX0=m._c,mX0=m.$c,Iw=m.bd,Rw=m.cd,ww=m.dd,Ew=m.ed,Jq=m.fd,Sw=m.gd,uX0=m.hd,Tw=m.kd,pX0=m.ld,lX0=m.md,dX0=m.nd,kw=m.od,cX0=m.pd,iX0=m.qd,yw=m.rd,G6=m.sd,Yq=m.td,oX0=m.ud,I8=m.vd,VD=m.wd,R8=m.xd,nX0=m.yd,vw=m.zd,aX0=m.Ad,sX0=m.Bd,rX0=m.Cd,xw=m.Dd,tX0=m.Ed,eX0=m.Fd,QJ0=m.Gd,XJ0=m.Hd,JJ0=m.Id,YJ0=m.Jd,GJ0=m.Kd,WJ0=m.Ld,HJ0=m.Md,BJ0=m.Nd,AJ0=m.Od,KJ0=m.Pd,zJ0=m.Qd,VJ0=m.Rd,qJ0=m.Td,UJ0=m.Ud,$J0=m.Vd,ZJ0=m.Wd,FJ0=m.Yd,DJ0=m.Zd,MJ0=m._d,LJ0=m.$d,OJ0=m.ae,PJ0=m.oe,NJ0=m.pe,jJ0=m.qe,CJ0=m.re,IJ0=m.se,RJ0=m.te,wJ0=m.ue,EJ0=m.ve,SJ0=m.we,TJ0=m.xe,kJ0=m.ye,yJ0=m.Ye,vJ0=m.Ze,xJ0=m._e,bJ0=m.$e,N=s,lW}var h,f=pQ();return J.instantiateWasm?new Promise((m)=>{J.instantiateWasm(f,(s,C0)=>{m(v(s,C0))})}):K?v(new WebAssembly.Instance(N,pQ()),N):(d0??=J.locateFile?J.locateFile?J.locateFile("ort-wasm-simd-threaded.asyncify.wasm",O):O+"ort-wasm-simd-threaded.asyncify.wasm":new URL("ort-wasm-simd-threaded.asyncify.wasm","file:///C:/mcp-tools-for-obsidian.ts").href,h=await async function(m){var s=d0;if(!P&&!l(s))try{var C0=fetch(s,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(C0,m)}catch(QQ){b(`wasm streaming compile failed: ${QQ}`),b("falling back to ArrayBuffer instantiation")}return async function(QQ,JQ){try{var OQ=await async function(hQ){if(!P)try{var T6=await q(hQ);return new Uint8Array(T6)}catch{}if(hQ==d0&&P)hQ=new Uint8Array(P);else{if(!F)throw"both async and sync fetching of the wasm failed";hQ=F(hQ)}return hQ}(QQ);return await WebAssembly.instantiate(OQ,JQ)}catch(hQ){b(`failed to asynchronously prepare wasm: ${hQ}`),h0(hQ)}}(s,m)}(f),v(h.instance,h.module))}class mQ{name="ExitStatus";constructor(v){this.message=`Program terminated with exit(${v})`,this.status=v}}var AQ=(v)=>{v.terminate(),v.onmessage=()=>{}},MQ=[],DQ=0,bQ=null,j8=(v)=>{H7.length==0&&(lQ(),wQ(H7[0]));var h=H7.pop();if(!h)return 6;LJ.push(h),w7[v.Nc]=h,h.Nc=v.Nc;var f={Oc:"run",ge:v.fe,Wc:v.Wc,Nc:v.Nc};return h.postMessage(f,v.Yc),0},tQ=0,K8=(v,h,...f)=>{var m,s=16*f.length,C0=R8(),QQ=VD(s),JQ=QQ>>>3;for(m of f)typeof m=="bigint"?((_(),R0)[JQ++>>>0]=1n,(_(),R0)[JQ++>>>0]=m):((_(),R0)[JQ++>>>0]=0n,(_(),WQ)[JQ++>>>0]=m);return v=lX0(v,0,s,QQ,h),I8(C0),v};function k8(v){if(K)return K8(0,1,v);if(I=v,!(0<tQ)){for(var h of LJ)AQ(h);for(h of H7)AQ(h);H7=[],LJ=[],w7={},g=!0}D(0,new mQ(v))}function d6(v){if(K)return K8(1,0,v);r9(v)}var r9=(v)=>{if(I=v,K)throw d6(v),"unwind";k8(v)},H7=[],LJ=[],OJ=[],w7={},QJ=(v)=>{var h=v.Nc;delete w7[h],H7.push(v),LJ.splice(LJ.indexOf(v),1),v.Nc=0,dX0(h)};function e8(){OJ.forEach((v)=>v())}var wQ=(v)=>new Promise((h)=>{v.onmessage=(s)=>{var C0=s.data;if(s=C0.Oc,C0.Vc&&C0.Vc!=zD()){var QQ=w7[C0.Vc];QQ?QQ.postMessage(C0,C0.Yc):b(`Internal error! Worker sent a message "${s}" to target pthread ${C0.Vc}, but that thread no longer exists!`)}else s==="checkMailbox"?OB():s==="spawnThread"?j8(C0):s==="cleanupThread"?c9(()=>{QJ(w7[C0.he])}):s==="loaded"?(v.loaded=!0,h(v)):C0.target==="setimmediate"?v.postMessage(C0):s==="uncaughtException"?v.onerror(C0.error):s==="callHandler"?J[C0.be](...C0.args):s&&b(`worker sent an unknown command ${s}`)},v.onerror=(s)=>{throw b(`worker sent an error! ${s.filename}:${s.lineno}: ${s.message}`),s};var f,m=[];for(f of[])J.propertyIsEnumerable(f)&&m.push(f);v.postMessage({Oc:"load",ce:m,ie:U8,je:N})});function lQ(){var v=new Worker((()=>{return new URL("ort.webgpu.bundle.min.mjs","file:///C:/mcp-tools-for-obsidian.ts")})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});H7.push(v)}var U8,P6=(v,h)=>{tQ=0,v=xw(v,h),0<tQ?I=v:kw(v)},N6=[],t9=0,F8=(v)=>-9007199254740992>v||9007199254740992<v?NaN:Number(v);function SX(v){var h=new IQ(v>>>=0);return(_(),f0)[h.Qc+12>>>0]==0&&(D8(h,!0),t9--),S6(h,!1),N6.push(h),sX0(v)}var B7=0,f8=()=>{G6(0,0);var v=N6.pop();nX0(v.Xc),B7=0};function D8(v,h){h=h?1:0,(_(),f0)[v.Qc+12>>>0]=h}function S6(v,h){h=h?1:0,(_(),f0)[v.Qc+13>>>0]=h}class IQ{constructor(v){this.Xc=v,this.Qc=v-24}}var rQ=(v)=>{var h=B7;if(!h)return Yq(0),0;var f=new IQ(h);(_(),n)[f.Qc+16>>>2>>>0]=h;var m=(_(),n)[f.Qc+4>>>2>>>0];if(!m)return Yq(0),h;for(var s of v){if(s===0||s===m)break;if(aX0(s,m,f.Qc+16))return Yq(s),h}return Yq(m),h};function l8(){return rQ([])}function U6(v){return rQ([v>>>0])}function G8(v,h,f,m){return rQ([v>>>0,h>>>0,f>>>0,m>>>0])}var e9=()=>{var v=N6.pop();v||h0("no exception to throw");var h=v.Xc;throw(_(),f0)[v.Qc+13>>>0]==0&&(N6.push(v),S6(v,!0),D8(v,!1),t9++),vw(h),B7=h};function TX(v,h,f){var m=new IQ(v>>>=0);throw h>>>=0,f>>>=0,(_(),n)[m.Qc+16>>>2>>>0]=0,(_(),n)[m.Qc+4>>>2>>>0]=h,(_(),n)[m.Qc+8>>>2>>>0]=f,vw(v),t9++,B7=v}var j6=()=>t9;function s8(v,h,f,m){return K?K8(2,1,v,h,f,m):x6(v,h,f,m)}function x6(v,h,f,m){if(v>>>=0,h>>>=0,f>>>=0,m>>>=0,!globalThis.SharedArrayBuffer)return 6;var s=[];return K&&s.length===0?s8(v,h,f,m):(v={fe:f,Nc:v,Wc:m,Yc:s},K?(v.Oc="spawnThread",postMessage(v,s),0):j8(v))}function t6(v){throw B7||=v>>>0,B7}var M7=globalThis.TextDecoder&&new TextDecoder,Z9=(v,h,f,m)=>{if(f=h+f,m)return f;for(;v[h]&&!(h>=f);)++h;return h},h8=(v,h=0,f,m)=>{if(16<(f=Z9(v,h>>>=0,f,m))-h&&v.buffer&&M7)return M7.decode(v.buffer instanceof ArrayBuffer?v.subarray(h,f):v.slice(h,f));for(m="";h<f;){var s=v[h++];if(128&s){var C0=63&v[h++];if((224&s)==192)m+=String.fromCharCode((31&s)<<6|C0);else{var QQ=63&v[h++];65536>(s=(240&s)==224?(15&s)<<12|C0<<6|QQ:(7&s)<<18|C0<<12|QQ<<6|63&v[h++])?m+=String.fromCharCode(s):(s-=65536,m+=String.fromCharCode(55296|s>>10,56320|1023&s))}}else m+=String.fromCharCode(s)}return m},F6=(v,h,f)=>(v>>>=0)?h8((_(),t),v,h,f):"";function L7(v,h,f){return K?K8(3,1,v,h,f):0}function C6(v,h){if(K)return K8(4,1,v,h)}function A9(v,h){if(K)return K8(5,1,v,h)}function kQ(v,h,f){if(K)return K8(6,1,v,h,f)}function $8(v,h,f){return K?K8(7,1,v,h,f):0}function c6(v,h){if(K)return K8(8,1,v,h)}function XJ(v,h,f){if(K)return K8(9,1,v,h,f)}function YX(v,h,f,m){if(K)return K8(10,1,v,h,f,m)}function LY(v,h,f,m){if(K)return K8(11,1,v,h,f,m)}function sY(v,h,f,m){if(K)return K8(12,1,v,h,f,m)}function OY(v){if(K)return K8(13,1,v)}function hW(v,h){if(K)return K8(14,1,v,h)}function pG(v,h,f){if(K)return K8(15,1,v,h,f)}var MH=()=>h0(""),A7=(v)=>{v>>>=0;for(var h="";;){var f=(_(),t)[v++>>>0];if(!f)return h;h+=String.fromCharCode(f)}},JJ={},E7={},u5={},rY=class extends Error{constructor(v){super(v),this.name="BindingError"}};function PJ(v,h,f={}){return function(m,s,C0={}){var QQ=s.name;if(!m)throw new rY(`type "${QQ}" must have a positive integer typeid pointer`);if(E7.hasOwnProperty(m)){if(C0.de)return;throw new rY(`Cannot register type '${QQ}' twice`)}E7[m]=s,delete u5[m],JJ.hasOwnProperty(m)&&(s=JJ[m],delete JJ[m],s.forEach((JQ)=>JQ()))}(v,h,f)}var tY=(v,h,f)=>{switch(h){case 1:return f?(m)=>(_(),f0)[m>>>0]:(m)=>(_(),t)[m>>>0];case 2:return f?(m)=>(_(),p0)[m>>>1>>>0]:(m)=>(_(),u0)[m>>>1>>>0];case 4:return f?(m)=>(_(),d)[m>>>2>>>0]:(m)=>(_(),n)[m>>>2>>>0];case 8:return f?(m)=>(_(),R0)[m>>>3>>>0]:(m)=>(_(),l0)[m>>>3>>>0];default:throw TypeError(`invalid integer width (${h}): ${v}`)}};function ZB(v,h,f,m,s){v>>>=0,f>>>=0,h=A7(h>>>0);let C0=(QQ)=>QQ;if(m=m===0n){let QQ=8*f;C0=(JQ)=>BigInt.asUintN(QQ,JQ),s=C0(s)}PJ(v,{name:h,Mc:C0,Sc:(QQ,JQ)=>(typeof JQ=="number"&&(JQ=BigInt(JQ)),JQ),Rc:tY(h,f,!m),Tc:null})}function cV(v,h,f,m){PJ(v>>>=0,{name:h=A7(h>>>0),Mc:function(s){return!!s},Sc:function(s,C0){return C0?f:m},Rc:function(s){return this.Mc((_(),t)[s>>>0])},Tc:null})}var YJ=[],PY=[0,1,,1,null,1,!0,1,!1,1];function lG(v){9<(v>>>=0)&&--PY[v+1]==0&&(PY[v]=void 0,YJ.push(v))}var m7=(v)=>{if(!v)throw new rY(`Cannot use deleted val. handle = ${v}`);return PY[v]},kX=(v)=>{switch(v){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let h=YJ.pop()||PY.length;return PY[h]=v,PY[h+1]=1,h}};function LH(v){return this.Mc((_(),n)[v>>>2>>>0])}var _W={name:"emscripten::val",Mc:(v)=>{var h=m7(v);return lG(v),h},Sc:(v,h)=>kX(h),Rc:LH,Tc:null};function NJ(v){return PJ(v>>>0,_W)}var Jw=(v,h)=>{switch(h){case 4:return function(f){return this.Mc((_(),c0)[f>>>2>>>0])};case 8:return function(f){return this.Mc((_(),WQ)[f>>>3>>>0])};default:throw TypeError(`invalid float width (${h}): ${v}`)}};function Yw(v,h,f){f>>>=0,PJ(v>>>=0,{name:h=A7(h>>>0),Mc:(m)=>m,Sc:(m,s)=>s,Rc:Jw(h,f),Tc:null})}function iV(v,h,f,m,s){v>>>=0,f>>>=0,h=A7(h>>>0);let C0=(JQ)=>JQ;if(m===0){var QQ=32-8*f;C0=(JQ)=>JQ<<QQ>>>QQ,s=C0(s)}PJ(v,{name:h,Mc:C0,Sc:(JQ,OQ)=>OQ,Rc:tY(h,f,m!==0),Tc:null})}function Gw(v,h,f){function m(C0){var QQ=(_(),n)[C0>>>2>>>0];return C0=(_(),n)[C0+4>>>2>>>0],new s((_(),f0).buffer,C0,QQ)}var s=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][h];PJ(v>>>=0,{name:f=A7(f>>>0),Mc:m,Rc:m},{de:!0})}var O7=(v,h,f)=>{var m=(_(),t);if(h>>>=0,0<f){var s=h;f=h+f-1;for(var C0=0;C0<v.length;++C0){var QQ=v.codePointAt(C0);if(127>=QQ){if(h>=f)break;m[h++>>>0]=QQ}else if(2047>=QQ){if(h+1>=f)break;m[h++>>>0]=192|QQ>>6,m[h++>>>0]=128|63&QQ}else if(65535>=QQ){if(h+2>=f)break;m[h++>>>0]=224|QQ>>12,m[h++>>>0]=128|QQ>>6&63,m[h++>>>0]=128|63&QQ}else{if(h+3>=f)break;m[h++>>>0]=240|QQ>>18,m[h++>>>0]=128|QQ>>12&63,m[h++>>>0]=128|QQ>>6&63,m[h++>>>0]=128|63&QQ,C0++}}m[h>>>0]=0,v=h-s}else v=0;return v},aJ=(v)=>{for(var h=0,f=0;f<v.length;++f){var m=v.charCodeAt(f);127>=m?h++:2047>=m?h+=2:55296<=m&&57343>=m?(h+=4,++f):h+=3}return h};function Ww(v,h){PJ(v>>>=0,{name:h=A7(h>>>0),Mc(f){var m=(_(),n)[f>>>2>>>0];return m=F6(f+4,m,!0),QG(f),m},Sc(f,m){m instanceof ArrayBuffer&&(m=new Uint8Array(m));var s=typeof m=="string";if(!(s||ArrayBuffer.isView(m)&&m.BYTES_PER_ELEMENT==1))throw new rY("Cannot pass non-string to std::string");var C0=s?aJ(m):m.length,QQ=kB(4+C0+1),JQ=QQ+4;return(_(),n)[QQ>>>2>>>0]=C0,s?O7(m,JQ,C0+1):(_(),t).set(m,JQ>>>0),f!==null&&f.push(QG,QQ),QQ},Rc:LH,Tc(f){QG(f)}})}var oV=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,FB=(v,h,f)=>{if(v>>>=1,16<(h=Z9((_(),u0),v,h/2,f))-v&&oV)return oV.decode((_(),u0).slice(v,h));for(f="";v<h;++v){var m=(_(),u0)[v>>>0];f+=String.fromCharCode(m)}return f},DB=(v,h,f)=>{if(f??=2147483647,2>f)return 0;var m=h;f=(f-=2)<2*v.length?f/2:v.length;for(var s=0;s<f;++s){var C0=v.charCodeAt(s);(_(),p0)[h>>>1>>>0]=C0,h+=2}return(_(),p0)[h>>>1>>>0]=0,h-m},MB=(v)=>2*v.length,nV=(v,h,f)=>{var m="";v>>>=2;for(var s=0;!(s>=h/4);s++){var C0=(_(),n)[v+s>>>0];if(!C0&&!f)break;m+=String.fromCodePoint(C0)}return m},dG=(v,h,f)=>{if(h>>>=0,f??=2147483647,4>f)return 0;var m=h;f=m+f-4;for(var s=0;s<v.length;++s){var C0=v.codePointAt(s);if(65535<C0&&s++,(_(),d)[h>>>2>>>0]=C0,(h+=4)+4>f)break}return(_(),d)[h>>>2>>>0]=0,h-m},LB=(v)=>{for(var h=0,f=0;f<v.length;++f)65535<v.codePointAt(f)&&f++,h+=4;return h};function tF(v,h,f){if(v>>>=0,h>>>=0,f=A7(f>>>=0),h===2)var m=FB,s=DB,C0=MB;else m=nV,s=dG,C0=LB;PJ(v,{name:f,Mc:(QQ)=>{var JQ=(_(),n)[QQ>>>2>>>0];return JQ=m(QQ+4,JQ*h,!0),QG(QQ),JQ},Sc:(QQ,JQ)=>{if(typeof JQ!="string")throw new rY(`Cannot pass non-string to C++ string type ${f}`);var OQ=C0(JQ),hQ=kB(4+OQ+h);return(_(),n)[hQ>>>2>>>0]=OQ/h,s(JQ,hQ+4,OQ+h),QQ!==null&&QQ.push(QG,hQ),hQ},Rc:LH,Tc(QQ){QG(QQ)}})}function Hw(v,h){PJ(v>>>=0,{ee:!0,name:h=A7(h>>>0),Mc:()=>{},Sc:()=>{}})}function Bw(v){Tw(v>>>0,!H,1,!G,131072,!1),e8()}var c9=(v)=>{if(!g)try{if(v(),!(0<tQ))try{K?zD()&&kw(I):r9(I)}catch(h){h instanceof mQ||h=="unwind"||D(0,h)}}catch(h){h instanceof mQ||h=="unwind"||D(0,h)}},Aw=!Atomics.waitAsync||globalThis.navigator?.userAgent&&91>Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function aV(v){v>>>=0,Aw||(Atomics.waitAsync((_(),d),v>>>2,v).value.then(OB),v+=128,Atomics.store((_(),d),v>>>2,1))}var OB=()=>c9(()=>{var v=zD();v&&(aV(v),iX0())});function Kw(v,h){(v>>>=0)==h>>>0?setTimeout(OB):K?postMessage({Vc:v,Oc:"checkMailbox"}):(v=w7[v])&&v.postMessage({Oc:"checkMailbox"})}var OH=[];function PB(v,h,f,m,s){for(h>>>=0,s>>>=0,OH.length=0,f=s>>>3,m=s+m>>>3;f<m;){var C0;C0=(_(),R0)[f++>>>0]?(_(),R0)[f++>>>0]:(_(),WQ)[f++>>>0],OH.push(C0)}return(h?bw[h]:ET0[v])(...OH)}var zw=()=>{tQ=0};function Vw(v){v>>>=0,K?postMessage({Oc:"cleanupThread",he:v}):QJ(w7[v])}function eF(v){}var p5=(v)=>{try{v()}catch(h){h0(h)}};function QD(v){var h=(...f)=>{PH.push(v);try{return v(...f)}finally{g||(PH.pop(),NY&&cG===1&&PH.length===0&&(cG=0,tQ+=1,p5(vJ0),typeof Fibers<"u"&&Fibers.Be()))}};return JD.set(v,h),h}var cG=0,NY=null,sV=0,PH=[],NB=new Map,XD=new Map,JD=new Map,qw=0,l5=null,jB=[],rV=(v)=>function(h){if(!g){if(cG===0){var f=!1,m=!1;h((s=0)=>{if(!g&&(sV=s,f=!0,m)){cG=2,p5(()=>xJ0(NY)),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.resume(),s=!1;try{var C0=function(){var OQ=(_(),d)[NY+8>>>2>>>0];return OQ=XD.get(OQ),OQ=JD.get(OQ),--tQ,OQ()}()}catch(OQ){C0=OQ,s=!0}var QQ=!1;if(!NY){var JQ=l5;JQ&&(l5=null,(s?JQ.reject:JQ.resolve)(C0),QQ=!0)}if(s&&!QQ)throw C0}}),m=!0,f||(cG=1,NY=function(){var s=kB(65548),C0=s+12;if((_(),n)[s>>>2>>>0]=C0,(_(),n)[s+4>>>2>>>0]=C0+65536,C0=PH[0],!NB.has(C0)){var QQ=qw++;NB.set(C0,QQ),XD.set(QQ,C0)}return C0=NB.get(C0),(_(),d)[s+8>>>2>>>0]=C0,s}(),typeof MainLoop<"u"&&MainLoop.Xd&&MainLoop.pause(),p5(()=>yJ0(NY)))}else cG===2?(cG=0,p5(bJ0),QG(NY),NY=null,jB.forEach(c9)):h0(`invalid state: ${cG}`);return sV}}((h)=>{v().then(h)});function iG(v){return v>>>=0,rV(async()=>{var h=await m7(v);return kX(h)})}var NH=[],Uw=(v)=>{var h=NH.length;return NH.push(v),h},$w=(v,h)=>{for(var f=Array(v),m=0;m<v;++m){var s=m,C0=(_(),n)[h+4*m>>>2>>>0],QQ=E7[C0];if(QQ===void 0)throw v=`parameter ${m}`,C0=EX0(C0),h=A7(C0),QG(C0),new rY(`${v} has unknown type ${h}`);f[s]=QQ}return f},jH=(v,h,f)=>{var m=[];return v=v(m,f),m.length&&((_(),n)[h>>>2>>>0]=kX(m)),v},YD={},CB=(v)=>{var h=YD[v];return h===void 0?A7(v):h};function Zw(v,h,f){var[m,...s]=$w(v,h>>>0);h=m.Sc.bind(m);var C0=s.map((OQ)=>OQ.Rc.bind(OQ));v--;var QQ={toValue:m7};switch(v=C0.map((OQ,hQ)=>{var T6=`argFromPtr${hQ}`;return QQ[T6]=OQ,`${T6}(args${hQ?"+"+8*hQ:""})`}),f){case 0:var JQ="toValue(handle)";break;case 2:JQ="new (toValue(handle))";break;case 3:JQ="";break;case 1:QQ.getStringOrSymbol=CB,JQ="toValue(handle)[getStringOrSymbol(methodName)]"}return JQ+=`(${v})`,m.ee||(QQ.toReturnWire=h,QQ.emval_returnValue=jH,JQ=`return emval_returnValue(toReturnWire, destructorsRef, ${JQ})`),JQ=`return function (handle, methodName, destructorsRef, args) {
${JQ}
}`,f=Function(Object.keys(QQ),JQ)(...Object.values(QQ)),JQ=`methodCaller<(${s.map((OQ)=>OQ.name)}) => ${m.name}>`,Uw(Object.defineProperty(f,"name",{value:JQ}))}function Fw(v,h){return h>>>=0,(v=m7(v>>>0))==m7(h)}function Dw(v){return(v>>>=0)?(v=CB(v),kX(globalThis[v])):kX(globalThis)}function Mw(v){return v=CB(v>>>0),kX(J[v])}function IB(v,h){return h>>>=0,v=m7(v>>>0),h=m7(h),kX(v[h])}function fW(v){9<(v>>>=0)&&(PY[v+1]+=1)}function GD(v,h,f,m,s){return NH[v>>>0](h>>>0,f>>>0,m>>>0,s>>>0)}function WD(v,h,f,m,s){return GD(v>>>0,h>>>0,f>>>0,m>>>0,s>>>0)}function RB(){return kX([])}function k9(v){v=m7(v>>>0);for(var h=Array(v.length),f=0;f<v.length;f++)h[f]=v[f];return kX(h)}function HD(v){return kX(CB(v>>>0))}function tV(){return kX({})}function M8(v){for(var h=m7(v>>>=0);h.length;){var f=h.pop();h.pop()(f)}lG(v)}function wB(v,h,f){h>>>=0,f>>>=0,v=m7(v>>>0),h=m7(h),f=m7(f),v[h]=f}function jJ(v,h){v=F8(v),h>>>=0,v=new Date(1000*v),(_(),d)[h>>>2>>>0]=v.getUTCSeconds(),(_(),d)[h+4>>>2>>>0]=v.getUTCMinutes(),(_(),d)[h+8>>>2>>>0]=v.getUTCHours(),(_(),d)[h+12>>>2>>>0]=v.getUTCDate(),(_(),d)[h+16>>>2>>>0]=v.getUTCMonth(),(_(),d)[h+20>>>2>>>0]=v.getUTCFullYear()-1900,(_(),d)[h+24>>>2>>>0]=v.getUTCDay(),v=(v.getTime()-Date.UTC(v.getUTCFullYear(),0,1,0,0,0,0))/86400000|0,(_(),d)[h+28>>>2>>>0]=v}var BD=(v)=>v%4==0&&(v%100!=0||v%400==0),EB=[0,31,60,91,121,152,182,213,244,274,305,335],CH=[0,31,59,90,120,151,181,212,243,273,304,334];function mW(v,h){v=F8(v),h>>>=0,v=new Date(1000*v),(_(),d)[h>>>2>>>0]=v.getSeconds(),(_(),d)[h+4>>>2>>>0]=v.getMinutes(),(_(),d)[h+8>>>2>>>0]=v.getHours(),(_(),d)[h+12>>>2>>>0]=v.getDate(),(_(),d)[h+16>>>2>>>0]=v.getMonth(),(_(),d)[h+20>>>2>>>0]=v.getFullYear()-1900,(_(),d)[h+24>>>2>>>0]=v.getDay();var f=(BD(v.getFullYear())?EB:CH)[v.getMonth()]+v.getDate()-1|0;(_(),d)[h+28>>>2>>>0]=f,(_(),d)[h+36>>>2>>>0]=-60*v.getTimezoneOffset(),f=new Date(v.getFullYear(),6,1).getTimezoneOffset();var m=new Date(v.getFullYear(),0,1).getTimezoneOffset();v=0|(f!=m&&v.getTimezoneOffset()==Math.min(m,f)),(_(),d)[h+32>>>2>>>0]=v}function IH(v){v>>>=0;var h=new Date((_(),d)[v+20>>>2>>>0]+1900,(_(),d)[v+16>>>2>>>0],(_(),d)[v+12>>>2>>>0],(_(),d)[v+8>>>2>>>0],(_(),d)[v+4>>>2>>>0],(_(),d)[v>>>2>>>0],0),f=(_(),d)[v+32>>>2>>>0],m=h.getTimezoneOffset(),s=new Date(h.getFullYear(),6,1).getTimezoneOffset(),C0=new Date(h.getFullYear(),0,1).getTimezoneOffset(),QQ=Math.min(C0,s);return 0>f?(_(),d)[v+32>>>2>>>0]=+(s!=C0&&QQ==m):0<f!=(QQ==m)&&(s=Math.max(C0,s),h.setTime(h.getTime()+60000*((0<f?QQ:s)-m))),(_(),d)[v+24>>>2>>>0]=h.getDay(),f=(BD(h.getFullYear())?EB:CH)[h.getMonth()]+h.getDate()-1|0,(_(),d)[v+28>>>2>>>0]=f,(_(),d)[v>>>2>>>0]=h.getSeconds(),(_(),d)[v+4>>>2>>>0]=h.getMinutes(),(_(),d)[v+8>>>2>>>0]=h.getHours(),(_(),d)[v+12>>>2>>>0]=h.getDate(),(_(),d)[v+16>>>2>>>0]=h.getMonth(),(_(),d)[v+20>>>2>>>0]=h.getYear(),v=h.getTime(),BigInt(isNaN(v)?-1:v/1000)}function uW(v,h,f,m,s,C0,QQ){return K?K8(16,1,v,h,f,m,s,C0,QQ):-52}function jY(v,h,f,m,s,C0){if(K)return K8(17,1,v,h,f,m,s,C0)}var oG={},eV=()=>performance.timeOrigin+performance.now();function Qq(v,h){if(K)return K8(18,1,v,h);if(oG[v]&&(clearTimeout(oG[v].id),delete oG[v]),!h)return 0;var f=setTimeout(()=>{delete oG[v],c9(()=>cX0(v,performance.timeOrigin+performance.now()))},h);return oG[v]={id:f,Ae:h},0}function Xq(v,h,f,m){v>>>=0,h>>>=0,f>>>=0,m>>>=0;var s=new Date().getFullYear(),C0=new Date(s,0,1).getTimezoneOffset();s=new Date(s,6,1).getTimezoneOffset();var QQ=Math.max(C0,s);(_(),n)[v>>>2>>>0]=60*QQ,(_(),d)[h>>>2>>>0]=+(C0!=s),v=(h=(JQ)=>{var OQ=Math.abs(JQ);return`UTC${0<=JQ?"-":"+"}${String(Math.floor(OQ/60)).padStart(2,"0")}${String(OQ%60).padStart(2,"0")}`})(C0),h=h(s),s<C0?(O7(v,f,17),O7(h,m,17)):(O7(v,m,17),O7(h,f,17))}var Lw=()=>Date.now(),Ow=1;function Pw(v,h,f){if(f>>>=0,!(0<=v&&3>=v))return 28;if(v===0)v=Date.now();else{if(!Ow)return 52;v=performance.timeOrigin+performance.now()}return v=Math.round(1e6*v),(_(),R0)[f>>>3>>>0]=BigInt(v),0}var SB=[],u=(v,h)=>{SB.length=0;for(var f;f=(_(),t)[v++>>>0];){var m=f!=105;h+=(m&=f!=112)&&h%8?4:0,SB.push(f==112?(_(),n)[h>>>2>>>0]:f==106?(_(),R0)[h>>>3>>>0]:f==105?(_(),d)[h>>>2>>>0]:(_(),WQ)[h>>>3>>>0]),h+=m?8:4}return SB};function p(v,h,f){return v>>>=0,h=u(h>>>0,f>>>0),bw[v](...h)}function Z0(v,h,f){return v>>>=0,h=u(h>>>0,f>>>0),bw[v](...h)}var XQ=()=>{};function KQ(v,h){return b(F6(v>>>0,h>>>0))}var yQ=()=>{throw tQ+=1,"unwind"};function L8(){return 4294901760}var Q6=()=>1,P9=()=>navigator.hardwareConcurrency;function S7(v){v>>>=0;var h=(_(),t).length;if(v<=h||4294901760<v)return!1;for(var f=1;4>=f;f*=2){var m=h*(1+0.2/f);m=Math.min(m,v+100663296);Q:{m=(Math.min(4294901760,65536*Math.ceil(Math.max(v,m)/65536))-U8.buffer.byteLength+65535)/65536|0;try{U8.grow(m),ZQ();var s=1;break Q}catch{}s=void 0}if(s)return!0}return!1}var i9=(v)=>{var h=aJ(v)+1,f=VD(h);return O7(v,f,h),f},GJ=(v,h)=>{(_(),n)[v>>>2>>>0]=h;var f=(_(),n)[v>>>2>>>0];(_(),n)[v+4>>>2>>>0]=(h-f)/4294967296},sJ=(v)=>(_(),n)[v>>>2>>>0]+4294967296*(_(),d)[v+4>>>2>>>0],F9=[],RH=(v,h)=>{F9[v>>>0]=h},eY=[],AD=[],TB=(v,h)=>{AD[v]=new Promise((f)=>h.finally(()=>f(v)))},W8=(v)=>{if(v)return F9[v>>>0]},vS0=(v,h)=>{for(v=(_(),n)[v>>>2>>>0];v;v=(_(),n)[v>>>2>>>0])h[(_(),d)[v+4>>>2>>>0]](v)},KD=(v,h,f)=>{(_(),n)[v>>>2>>>0]=h,(_(),n)[v+4>>>2>>>0]=f},MX0=(v)=>{var h=(_(),n)[v>>>2>>>0];return v=(_(),n)[v+4>>>2>>>0],F6(h,v)},pW=(v)=>{var h=(_(),n)[v>>>2>>>0];return v=(_(),n)[v+4>>>2>>>0],h?F6(h,v):v===0?"":void 0},xS0=(v)=>{var h=pW(v+4),f=(f=(_(),n)[v+12>>>2>>>0])?W8(f):"auto";if(v+=16){var m=W8((_(),n)[v+4>>>2>>>0]),s=(_(),n)[v+16>>>2>>>0],C0=(_(),n)[v+20>>>2>>>0];if(s){for(var QQ={},JQ=0;JQ<s;++JQ){var OQ=C0+24*JQ;QQ[MX0(OQ+4)]=(_(),WQ)[OQ+16>>>3>>>0]}s=QQ}else s=void 0;v={module:m,constants:s,entryPoint:pW(v+8)}}else v=void 0;return{label:h,layout:f,compute:v}},LX0=(v,h)=>{function f(m,s){m=v[m],(_(),n)[h+s>>>2>>>0]=m}f("maxTextureDimension1D",4),f("maxTextureDimension2D",8),f("maxTextureDimension3D",12),f("maxTextureArrayLayers",16),f("maxBindGroups",20),f("maxBindGroupsPlusVertexBuffers",24),f("maxBindingsPerBindGroup",28),f("maxDynamicUniformBuffersPerPipelineLayout",32),f("maxDynamicStorageBuffersPerPipelineLayout",36),f("maxSampledTexturesPerShaderStage",40),f("maxSamplersPerShaderStage",44),f("maxStorageBuffersPerShaderStage",48),f("maxStorageTexturesPerShaderStage",52),f("maxUniformBuffersPerShaderStage",56),f("minUniformBufferOffsetAlignment",80),f("minStorageBufferOffsetAlignment",84),GJ(h+64,v.maxUniformBufferBindingSize),GJ(h+72,v.maxStorageBufferBindingSize),f("maxVertexBuffers",88),GJ(h+96,v.maxBufferSize),f("maxVertexAttributes",104),f("maxVertexBufferArrayStride",108),f("maxInterStageShaderVariables",112),f("maxColorAttachments",116),f("maxColorAttachmentBytesPerSample",120),f("maxComputeWorkgroupStorageSize",124),f("maxComputeInvocationsPerWorkgroup",128),f("maxComputeWorkgroupSizeX",132),f("maxComputeWorkgroupSizeY",136),f("maxComputeWorkgroupSizeZ",140),f("maxComputeWorkgroupsPerDimension",144),v.ze!==void 0&&f("maxImmediateSize",148)},bS0=[,"validation","out-of-memory","internal"],gS0=[,"compatibility","core"],OX0={1:"core-features-and-limits",2:"depth-clip-control",3:"depth32float-stencil8",4:"texture-compression-bc",5:"texture-compression-bc-sliced-3d",6:"texture-compression-etc2",7:"texture-compression-astc",8:"texture-compression-astc-sliced-3d",9:"timestamp-query",10:"indirect-first-instance",11:"shader-f16",12:"rg11b10ufloat-renderable",13:"bgra8unorm-storage",14:"float32-filterable",15:"float32-blendable",16:"clip-distances",17:"dual-source-blending",18:"subgroups",19:"texture-formats-tier1",20:"texture-formats-tier2",21:"primitive-index",22:"texture-component-swizzle",327692:"chromium-experimental-unorm16-texture-formats",327729:"chromium-experimental-multi-draw-indirect"},hS0=[,"low-power","high-performance"],_S0=[,"occlusion","timestamp"],fS0={undefined:1,unknown:1,destroyed:2};function mS0(v,h,f,m,s,C0){h=F8(h),f=F8(f),m>>>=0,s>>>=0,C0>>>=0;var QQ=W8(v>>>0);if(v={},C0){var JQ=(_(),n)[C0+12>>>2>>>0];if(JQ){var OQ=(_(),n)[C0+16>>>2>>>0];v.requiredFeatures=Array.from((_(),n).subarray(OQ>>>2>>>0,OQ+4*JQ>>>2>>>0),(V8)=>OX0[V8])}var hQ=(_(),n)[C0+20>>>2>>>0];if(hQ){let V8=function(WJ,p7,wH=!1){p7=hQ+p7,(p7=(_(),n)[p7>>>2>>>0])==4294967295||wH&&p7==0||(K9[WJ]=p7)},u7=function(WJ,p7){p7=hQ+p7;var wH=(_(),n)[p7>>>2>>>0],Vk0=(_(),n)[p7+4>>>2>>>0];wH==4294967295&&Vk0==4294967295||(K9[WJ]=sJ(p7))};var T6=V8,h6=u7,K9={};V8("maxTextureDimension1D",4),V8("maxTextureDimension2D",8),V8("maxTextureDimension3D",12),V8("maxTextureArrayLayers",16),V8("maxBindGroups",20),V8("maxBindGroupsPlusVertexBuffers",24),V8("maxDynamicUniformBuffersPerPipelineLayout",32),V8("maxDynamicStorageBuffersPerPipelineLayout",36),V8("maxSampledTexturesPerShaderStage",40),V8("maxSamplersPerShaderStage",44),V8("maxStorageBuffersPerShaderStage",48),V8("maxStorageTexturesPerShaderStage",52),V8("maxUniformBuffersPerShaderStage",56),V8("minUniformBufferOffsetAlignment",80),V8("minStorageBufferOffsetAlignment",84),u7("maxUniformBufferBindingSize",64),u7("maxStorageBufferBindingSize",72),V8("maxVertexBuffers",88),u7("maxBufferSize",96),V8("maxVertexAttributes",104),V8("maxVertexBufferArrayStride",108),V8("maxInterStageShaderVariables",112),V8("maxColorAttachments",116),V8("maxColorAttachmentBytesPerSample",120),V8("maxComputeWorkgroupStorageSize",124),V8("maxComputeInvocationsPerWorkgroup",128),V8("maxComputeWorkgroupSizeX",132),V8("maxComputeWorkgroupSizeY",136),V8("maxComputeWorkgroupSizeZ",140),V8("maxComputeWorkgroupsPerDimension",144),V8("maxImmediateSize",148,!0),v.requiredLimits=K9}(JQ=(_(),n)[C0+24>>>2>>>0])&&(JQ={label:pW(JQ+4)},v.defaultQueue=JQ),v.label=pW(C0+4)}tQ+=1,TB(h,QQ.requestDevice(v).then((V8)=>{--tQ,c9(()=>{F9[s>>>0]=V8.queue,F9[m>>>0]=V8,tQ+=1,TB(f,V8.lost.then((u7)=>{c9(()=>{V8.onuncapturederror=()=>{};var WJ=R8(),p7=i9(u7.message);Rw(f,fS0[u7.reason],p7),I8(WJ)}),--tQ})),V8.onuncapturederror=(u7)=>{var WJ=5;u7.error instanceof GPUValidationError?WJ=2:u7.error instanceof GPUOutOfMemoryError?WJ=3:u7.error instanceof GPUInternalError&&(WJ=4);var p7=R8();u7=i9(u7.error.message),uX0(m,WJ,u7),I8(p7)},"adapterInfo"in V8||(V8.adapterInfo=QQ.info),Sw(h,1,m,0)})},(V8)=>{--tQ,c9(()=>{var u7=R8(),WJ=i9(V8.message);Sw(h,3,m,WJ),f&&Rw(f,4,WJ),I8(u7)})}))}function uS0(v){var h=W8(v>>>=0),f=eY[v];if(f){for(var m=0;m<f.length;++m)f[m]();delete eY[v]}h.destroy()}function pS0(v,h,f){f>>>=0;var m=W8(v>>>=0);f==4294967295&&(f=void 0);try{var s=m.getMappedRange(h>>>0,f)}catch{return 0}var C0=yw(16,s.byteLength);return(_(),t).set(new Uint8Array(s),C0>>>0),eY[v].push(()=>QG(C0)),C0}function lS0(v,h,f){f>>>=0;var m=W8(v>>>=0);f==4294967295&&(f=void 0);try{var s=m.getMappedRange(h>>>0,f)}catch{return 0}var C0=yw(16,s.byteLength);return(_(),t).fill(0,C0,s.byteLength),eY[v].push(()=>{new Uint8Array(s).set((_(),t).subarray(C0>>>0,C0+s.byteLength>>>0)),QG(C0)}),C0}function dS0(v,h,f,m,s){v>>>=0,h=F8(h),f=F8(f),s>>>=0;var C0=W8(v);eY[v]=[],s==4294967295&&(s=void 0),tQ+=1,TB(h,C0.mapAsync(f,m>>>0,s).then(()=>{--tQ,c9(()=>{ww(h,1,0)})},(QQ)=>{--tQ,c9(()=>{R8();var JQ=i9(QQ.message);ww(h,QQ.name==="AbortError"?4:QQ.name==="OperationError"?3:0,JQ),delete eY[v]})}))}function cS0(v){var h=W8(v>>>=0),f=eY[v];if(f){for(var m=0;m<f.length;++m)f[m]();delete eY[v],h.unmap()}}function iS0(v){delete F9[v>>>0]}function oS0(v,h,f){v>>>=0,h>>>=0,f>>>=0;var m=!!(_(),n)[h+32>>>2>>>0];h={label:pW(h+4),usage:(_(),n)[h+16>>>2>>>0],size:sJ(h+24),mappedAtCreation:m},v=W8(v);try{var s=v.createBuffer(h)}catch{return!1}return F9[f>>>0]=s,m&&(eY[f]=[]),!0}function nS0(v,h,f,m){v>>>=0,h=F8(h),m>>>=0,f=xS0(f>>>0),v=W8(v),tQ+=1,TB(h,v.createComputePipelineAsync(f).then((s)=>{--tQ,c9(()=>{F9[m>>>0]=s,Iw(h,1,m,0)})},(s)=>{--tQ,c9(()=>{var C0=R8(),QQ=i9(s.message);Iw(h,s.reason==="validation"?3:s.reason==="internal"?4:0,m,QQ),I8(C0)})}))}function aS0(v,h,f){v>>>=0,h>>>=0,f>>>=0;var m=(_(),n)[h>>>2>>>0],s=(_(),d)[m+4>>>2>>>0];h={label:pW(h+4),code:""},s===2&&(h.code=MX0(m+8)),v=W8(v).createShaderModule(h),F9[f>>>0]=v}var sS0=(v)=>{(v=W8(v)).onuncapturederror=null,v.destroy()};function rS0(v,h){h=F8(h),v=W8(v>>>0),tQ+=1,TB(h,v.popErrorScope().then((f)=>{--tQ,c9(()=>{var m=5;f?f instanceof GPUValidationError?m=2:f instanceof GPUOutOfMemoryError?m=3:f instanceof GPUInternalError&&(m=4):m=1;var s=R8(),C0=f?i9(f.message):0;Ew(h,1,m,C0),I8(s)})},(f)=>{--tQ,c9(()=>{var m=R8(),s=i9(f.message);Ew(h,1,5,s),I8(m)})}))}function tS0(v,h,f,m){if(h=F8(h),m>>>=0,f>>>=0){var s={featureLevel:gS0[(_(),d)[f+4>>>2>>>0]],powerPreference:hS0[(_(),d)[f+8>>>2>>>0]],forceFallbackAdapter:!!(_(),n)[f+12>>>2>>>0]};(v=(_(),n)[f>>>2>>>0])!==0&&(_(),s.De=!!(_(),n)[v+8>>>2>>>0])}"gpu"in navigator?(tQ+=1,TB(h,navigator.gpu.requestAdapter(s).then((C0)=>{--tQ,c9(()=>{if(C0)F9[m>>>0]=C0,Jq(h,1,m,0);else{var QQ=R8(),JQ=i9("WebGPU not available on this browser (requestAdapter returned null)");Jq(h,3,m,JQ),I8(QQ)}})},(C0)=>{--tQ,c9(()=>{var QQ=R8(),JQ=i9(C0.message);Jq(h,4,m,JQ),I8(QQ)})}))):(s=R8(),v=i9("WebGPU not available on this browser (navigator.gpu is not available)"),Jq(h,3,m,v),I8(s))}function eS0(v,h,f){return v>>>=0,h>>>=0,f>>>=0,rV(async()=>{var m=[];if(f){var s=(_(),d)[f>>>2>>>0];m.length=h+1,m[h]=new Promise((JQ)=>setTimeout(JQ,s,0))}else m.length=h;for(var C0=0;C0<h;++C0){var QQ=sJ(v+8*C0);if(!(QQ in AD))return QQ;m[C0]=AD[QQ]}return m=await Promise.race(m),delete AD[m],m})}var Nw,jw={},PX0=()=>{if(!Nw){var v,h={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(v in jw)jw[v]===void 0?delete h[v]:h[v]=jw[v];var f=[];for(v in h)f.push(`${v}=${h[v]}`);Nw=f}return Nw};function NX0(v,h){if(K)return K8(19,1,v,h);v>>>=0,h>>>=0;var f,m=0,s=0;for(f of PX0()){var C0=h+m;(_(),n)[v+s>>>2>>>0]=C0,m+=O7(f,C0,1/0)+1,s+=4}return 0}function jX0(v,h){if(K)return K8(20,1,v,h);v>>>=0,h>>>=0;var f=PX0();for(var m of((_(),n)[v>>>2>>>0]=f.length,v=0,f))v+=aJ(m)+1;return(_(),n)[h>>>2>>>0]=v,0}function CX0(v){return K?K8(21,1,v):52}function IX0(v,h,f,m){return K?K8(22,1,v,h,f,m):52}function RX0(v,h,f,m){return K?K8(23,1,v,h,f,m):70}var QT0=[null,[],[]];function wX0(v,h,f,m){if(K)return K8(24,1,v,h,f,m);h>>>=0,f>>>=0,m>>>=0;for(var s=0,C0=0;C0<f;C0++){var QQ=(_(),n)[h>>>2>>>0],JQ=(_(),n)[h+4>>>2>>>0];h+=8;for(var OQ=0;OQ<JQ;OQ++){var hQ=v,T6=(_(),t)[QQ+OQ>>>0],h6=QT0[hQ];T6===0||T6===10?((hQ===1?x:b)(h8(h6)),h6.length=0):h6.push(T6)}s+=JQ}return(_(),n)[m>>>2>>>0]=s,0}function XT0(v){return v>>>0}function JT0(v,h){return LX0(W8(v>>>0).limits,h>>>0),1}function YT0(v,h){return W8(v>>>0).features.has(OX0[h])}function GT0(v){return BigInt(W8(v>>>0).size)}function WT0(v){return BigInt(W8(v>>>0).usage)}function HT0(v,h){if(v>>>=0,h>>>=0){var f=pW(h+4);f={label:f,timestampWrites:h=(h=(_(),n)[h+12>>>2>>>0])!==0?{querySet:W8((_(),n)[h+4>>>2>>>0]),beginningOfPassWriteIndex:(_(),n)[h+8>>>2>>>0],endOfPassWriteIndex:(_(),n)[h+12>>>2>>>0]}:void 0}}return h=W8(v),v=gX0(0),f=h.beginComputePass(f),F9[v>>>0]=f,v}function BT0(v,h,f,m){f=F8(f),(m=F8(m))==-1&&(m=void 0),(v=W8(v>>>0)).clearBuffer(W8(h>>>0),f,m)}function AT0(v,h,f,m,s,C0){f=F8(f),s=F8(s),C0=F8(C0),W8(v>>>0).copyBufferToBuffer(W8(h>>>0),f,W8(m>>>0),s,C0)}function KT0(v){var h=W8(v>>>0);return v=xX0(0),h=h.finish(),F9[v>>>0]=h,v}function zT0(v,h,f,m,s,C0){C0=F8(C0),W8(v>>>0).resolveQuerySet(W8(h>>>0),f,m,W8(s>>>0),C0)}function VT0(v,h,f,m){W8(v>>>0).dispatchWorkgroups(h,f,m)}function qT0(v,h,f){f=F8(f),W8(v>>>0).dispatchWorkgroupsIndirect(W8(h>>>0),f)}function UT0(v){W8(v>>>0).end()}function $T0(v,h,f,m,s){m>>>=0,s>>>=0,v=W8(v>>>0),f=W8(f>>>0),m==0?v.setBindGroup(h,f):v.setBindGroup(h,f,(_(),n),s>>>2,m)}function ZT0(v,h){W8(v>>>0).setPipeline(W8(h>>>0))}function FT0(v,h,f){W8(v>>>0).Ce(W8(h>>>0),f)}function DT0(v,h){var f=W8(v>>>0);return v=vX0(0),h=f.getBindGroupLayout(h),F9[v>>>0]=h,v}function MT0(v,h){function f(s){var C0=(_(),n)[s+8>>>2>>>0],QQ=(_(),n)[s+32>>>2>>>0],JQ=(_(),n)[s+36>>>2>>>0],OQ=0;return vS0(s,{327681:(hQ)=>{OQ=(_(),n)[hQ+8>>>2>>>0]}}),C0?((QQ=sJ(s+24))==-1&&(QQ=void 0),C0={buffer:W8(C0),offset:sJ(s+16),size:QQ}):C0=W8(QQ||JQ||OQ),{binding:(_(),n)[s+4>>>2>>>0],resource:C0}}v>>>=0,h={label:pW(4+(h>>>=0)),layout:W8((_(),n)[h+12>>>2>>>0]),entries:function(s,C0){for(var QQ=[],JQ=0;JQ<s;++JQ)QQ.push(f(C0+40*JQ));return QQ}((_(),n)[h+16>>>2>>>0],(_(),n)[h+20>>>2>>>0])},v=W8(v);var m=yX0(0);return RH(m,v.createBindGroup(h)),m}function LT0(v,h){var f;return v>>>=0,(h>>>=0)&&(f={label:pW(h+4)}),h=W8(v),v=bX0(0),f=h.createCommandEncoder(f),F9[v>>>0]=f,v}function OT0(v,h){v>>>=0,h>>>=0,h={type:_S0[(_(),d)[h+12>>>2>>>0]],count:(_(),n)[h+16>>>2>>>0]};var f=W8(v);return v=hX0(0),h=f.createQuerySet(h),F9[v>>>0]=h,v}function PT0(v,h){v=W8(v>>>0).adapterInfo,h>>>=0,(_(),n)[h+52>>>2>>>0]=v.subgroupMinSize,(_(),n)[h+56>>>2>>>0]=v.subgroupMaxSize;var f=v.vendor+v.architecture+v.device+v.description,m=aJ(f)+1,s=kB(m);return s&&O7(f,s,m),f=s,m=aJ(v.vendor),KD(h+4,f,m),f+=m,m=aJ(v.architecture),KD(h+12,f,m),f+=m,m=aJ(v.device),KD(h+20,f,m),KD(h+28,f+m,aJ(v.description)),(_(),d)[h+36>>>2>>>0]=2,v=v.isFallbackAdapter?3:4,(_(),d)[h+40>>>2>>>0]=v,(_(),n)[h+44>>>2>>>0]=0,(_(),n)[h+48>>>2>>>0]=0,1}var NT0={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function jT0(v,h){h>>>=0;var f=W8(v>>>0);v=kB(4*f.features.size);var m=0,s=0;for(let C0 of f.features)0<=(f=NT0[C0])&&((_(),d)[v+m>>>2>>>0]=f,m+=4,s++);(_(),n)[h+4>>>2>>>0]=v,(_(),n)[h>>>2>>>0]=s}function CT0(v,h){return LX0(W8(v>>>0).limits,h>>>0),1}function IT0(v,h){W8(v>>>0).pushErrorScope(bS0[h])}function RT0(v,h,f){h>>>=0,f>>>=0,v=W8(v>>>0),h=Array.from((_(),d).subarray(f>>>2>>>0,f+4*h>>>2>>>0),(m)=>W8(m)),v.submit(h)}function wT0(v,h,f,m,s){f=F8(f),m>>>=0,s>>>=0,v=W8(v>>>0),h=W8(h>>>0),m=(_(),t).subarray(m>>>0,m+s>>>0),v.writeBuffer(h,f,m,0,s)}K||function(){for(var v=J.numThreads-1;v--;)lQ();MQ.push(async()=>{var h=async function(){if(!K)return Promise.all(H7.map(wQ))}();DQ++,await h,--DQ==0&&bQ&&(h=bQ,bQ=null,h())})}(),K||(U8=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),ZQ()),J.wasmBinary&&(P=J.wasmBinary),J.stackSave=()=>R8(),J.stackRestore=(v)=>I8(v),J.stackAlloc=(v)=>VD(v),J.setValue=function(v,h,f="i8"){switch(f.endsWith("*")&&(f="*"),f){case"i1":case"i8":(_(),f0)[v>>>0]=h;break;case"i16":(_(),p0)[v>>>1>>>0]=h;break;case"i32":(_(),d)[v>>>2>>>0]=h;break;case"i64":(_(),R0)[v>>>3>>>0]=BigInt(h);break;case"float":(_(),c0)[v>>>2>>>0]=h;break;case"double":(_(),WQ)[v>>>3>>>0]=h;break;case"*":(_(),n)[v>>>2>>>0]=h;break;default:h0(`invalid type for setValue: ${f}`)}},J.getValue=function(v,h="i8"){switch(h.endsWith("*")&&(h="*"),h){case"i1":case"i8":return(_(),f0)[v>>>0];case"i16":return(_(),p0)[v>>>1>>>0];case"i32":return(_(),d)[v>>>2>>>0];case"i64":return(_(),R0)[v>>>3>>>0];case"float":return(_(),c0)[v>>>2>>>0];case"double":return(_(),WQ)[v>>>3>>>0];case"*":return(_(),n)[v>>>2>>>0];default:h0(`invalid type for getValue: ${h}`)}},J.UTF8ToString=F6,J.stringToUTF8=O7,J.lengthBytesUTF8=aJ;var EX0,SX0,Cw,zD,QG,kB,TX0,kX0,yX0,vX0,xX0,bX0,gX0,hX0,_X0,fX0,mX0,Iw,Rw,ww,Ew,Jq,Sw,uX0,Tw,pX0,lX0,dX0,kw,cX0,iX0,yw,G6,Yq,oX0,I8,VD,R8,nX0,vw,aX0,sX0,rX0,xw,tX0,eX0,QJ0,XJ0,JJ0,YJ0,GJ0,WJ0,HJ0,BJ0,AJ0,KJ0,zJ0,VJ0,qJ0,UJ0,$J0,ZJ0,FJ0,DJ0,MJ0,LJ0,OJ0,PJ0,NJ0,jJ0,CJ0,IJ0,RJ0,wJ0,EJ0,SJ0,TJ0,kJ0,yJ0,vJ0,xJ0,bJ0,lW,ET0=[k8,d6,s8,L7,C6,A9,kQ,$8,c6,XJ,YX,LY,sY,OY,hW,pG,uW,jY,Qq,NX0,jX0,CX0,IX0,RX0,wX0],bw={970348:(v,h,f,m,s)=>{if(J===void 0||!J.Uc)return 1;if((v=F6(Number(v>>>0))).startsWith("./")&&(v=v.substring(2)),!(v=J.Uc.get(v)))return 2;if(h=Number(h>>>0),f=Number(f>>>0),m=Number(m>>>0),h+f>v.byteLength)return 3;try{let C0=v.subarray(h,h+f);switch(s){case 0:(_(),t).set(C0,m>>>0);break;case 1:J.ad?J.ad(m,C0):J.ne(m,C0);break;default:return 4}return 0}catch{return 4}},971172:(v,h,f)=>{J.Sd(v,(_(),t).subarray(h>>>0,h+f>>>0))},971236:()=>J.le(),971278:(v)=>{J.jd(v)},971315:()=>typeof wasmOffsetConverter<"u"};function ST0(v,h,f,m){var s=R8();try{return WJ0(v,h,f,m)}catch(C0){if(I8(s),C0!==C0+0)throw C0;G6(1,0)}}function TT0(v,h,f){var m=R8();try{return JJ0(v,h,f)}catch(s){if(I8(m),s!==s+0)throw s;G6(1,0)}}function kT0(v){var h=R8();try{tX0(v)}catch(f){if(I8(h),f!==f+0)throw f;G6(1,0)}}function yT0(v,h){var f=R8();try{return xw(v,h)}catch(m){if(I8(f),m!==m+0)throw m;G6(1,0)}}function vT0(v,h,f){var m=R8();try{rX0(v,h,f)}catch(s){if(I8(m),s!==s+0)throw s;G6(1,0)}}function xT0(v,h){var f=R8();try{HJ0(v,h)}catch(m){if(I8(f),m!==m+0)throw m;G6(1,0)}}function bT0(v,h,f,m,s,C0,QQ){var JQ=R8();try{return XJ0(v,h,f,m,s,C0,QQ)}catch(OQ){if(I8(JQ),OQ!==OQ+0)throw OQ;G6(1,0)}}function gT0(v,h,f,m,s,C0){var QQ=R8();try{eX0(v,h,f,m,s,C0)}catch(JQ){if(I8(QQ),JQ!==JQ+0)throw JQ;G6(1,0)}}function hT0(v,h,f,m){var s=R8();try{GJ0(v,h,f,m)}catch(C0){if(I8(s),C0!==C0+0)throw C0;G6(1,0)}}function _T0(v,h,f,m,s,C0,QQ){var JQ=R8();try{AJ0(v,h,f,m,s,C0,QQ)}catch(OQ){if(I8(JQ),OQ!==OQ+0)throw OQ;G6(1,0)}}function fT0(v,h,f,m,s,C0,QQ){var JQ=R8();try{KJ0(v,h,f,m,s,C0,QQ)}catch(OQ){if(I8(JQ),OQ!==OQ+0)throw OQ;G6(1,0)}}function mT0(v,h,f,m,s,C0,QQ,JQ){var OQ=R8();try{MJ0(v,h,f,m,s,C0,QQ,JQ)}catch(hQ){if(I8(OQ),hQ!==hQ+0)throw hQ;G6(1,0)}}function uT0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6,h6){var K9=R8();try{zJ0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6,h6)}catch(V8){if(I8(K9),V8!==V8+0)throw V8;G6(1,0)}}function pT0(v,h,f,m,s){var C0=R8();try{return BJ0(v,h,f,m,s)}catch(QQ){if(I8(C0),QQ!==QQ+0)throw QQ;G6(1,0)}}function lT0(v,h,f,m,s){var C0=R8();try{QJ0(v,h,f,m,s)}catch(QQ){if(I8(C0),QQ!==QQ+0)throw QQ;G6(1,0)}}function dT0(v,h,f,m,s,C0,QQ,JQ){var OQ=R8();try{YJ0(v,h,f,m,s,C0,QQ,JQ)}catch(hQ){if(I8(OQ),hQ!==hQ+0)throw hQ;G6(1,0)}}function cT0(v){var h=R8();try{return LJ0(v)}catch(f){if(I8(h),f!==f+0)throw f;G6(1,0)}}function iT0(v,h,f){var m=R8();try{return OJ0(v,h,f)}catch(s){if(I8(m),s!==s+0)throw s;G6(1,0)}}function oT0(v,h){var f=R8();try{return kJ0(v,h)}catch(m){if(I8(f),m!==m+0)throw m;return G6(1,0),0n}}function nT0(v){var h=R8();try{return VJ0(v)}catch(f){if(I8(h),f!==f+0)throw f;return G6(1,0),0n}}function aT0(v,h,f,m){var s=R8();try{return PJ0(v,h,f,m)}catch(C0){if(I8(s),C0!==C0+0)throw C0;G6(1,0)}}function sT0(v,h,f,m,s){var C0=R8();try{return NJ0(v,h,f,m,s)}catch(QQ){if(I8(C0),QQ!==QQ+0)throw QQ;G6(1,0)}}function rT0(v,h,f,m,s,C0){var QQ=R8();try{return jJ0(v,h,f,m,s,C0)}catch(JQ){if(I8(QQ),JQ!==JQ+0)throw JQ;G6(1,0)}}function tT0(v,h,f,m,s,C0){var QQ=R8();try{return FJ0(v,h,f,m,s,C0)}catch(JQ){if(I8(QQ),JQ!==JQ+0)throw JQ;G6(1,0)}}function eT0(v,h,f,m,s,C0){var QQ=R8();try{return CJ0(v,h,f,m,s,C0)}catch(JQ){if(I8(QQ),JQ!==JQ+0)throw JQ;G6(1,0)}}function Qk0(v,h,f,m,s,C0,QQ,JQ){var OQ=R8();try{return DJ0(v,h,f,m,s,C0,QQ,JQ)}catch(hQ){if(I8(OQ),hQ!==hQ+0)throw hQ;G6(1,0)}}function Xk0(v,h,f,m,s){var C0=R8();try{return IJ0(v,h,f,m,s)}catch(QQ){if(I8(C0),QQ!==QQ+0)throw QQ;return G6(1,0),0n}}function Jk0(v,h,f,m){var s=R8();try{return RJ0(v,h,f,m)}catch(C0){if(I8(s),C0!==C0+0)throw C0;G6(1,0)}}function Yk0(v,h,f,m){var s=R8();try{return wJ0(v,h,f,m)}catch(C0){if(I8(s),C0!==C0+0)throw C0;G6(1,0)}}function Gk0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6,h6){var K9=R8();try{return EJ0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6,h6)}catch(V8){if(I8(K9),V8!==V8+0)throw V8;G6(1,0)}}function Wk0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6){var h6=R8();try{SJ0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6)}catch(K9){if(I8(h6),K9!==K9+0)throw K9;G6(1,0)}}function Hk0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6,h6,K9,V8,u7,WJ){var p7=R8();try{TJ0(v,h,f,m,s,C0,QQ,JQ,OQ,hQ,T6,h6,K9,V8,u7,WJ)}catch(wH){if(I8(p7),wH!==wH+0)throw wH;G6(1,0)}}function Bk0(v,h,f){var m=R8();try{return UJ0(v,h,f)}catch(s){if(I8(m),s!==s+0)throw s;return G6(1,0),0n}}function Ak0(v,h,f){var m=R8();try{return qJ0(v,h,f)}catch(s){if(I8(m),s!==s+0)throw s;G6(1,0)}}function Kk0(v,h,f){var m=R8();try{return $J0(v,h,f)}catch(s){if(I8(m),s!==s+0)throw s;G6(1,0)}}function zk0(v,h,f,m){var s=R8();try{ZJ0(v,h,f,m)}catch(C0){if(I8(s),C0!==C0+0)throw C0;G6(1,0)}}function qD(){if(0<DQ)bQ=qD;else if(K)R?.(J),LQ();else{for(var v=MQ;0<v.length;)v.shift()(J);0<DQ?bQ=qD:(J.calledRun=!0,g||(LQ(),R?.(J)))}}return K||(lW=await iQ(),qD()),J.PTR_SIZE=4,J.webgpuInit=(v)=>{let h=new WeakMap,f,m,s=1;J.webgpuRegisterDevice=(JQ)=>{if(m!==void 0)throw Error("another WebGPU EP inference session is being created.");if(JQ){var OQ=h.get(JQ);if(!OQ){let hQ=((T6,h6=0)=>{var K9=mX0(h6);return h6=fX0(h6,K9),F9[K9>>>0]=T6.queue,F9[h6>>>0]=T6,h6})(JQ,OQ=kX0(0));OQ=[s++,OQ,hQ],h.set(JQ,OQ)}return f=JQ,m=OQ[0],OQ}f=void 0,m=0};let C0=new Map;J.webgpuOnCreateSession=(JQ)=>{if(m!==void 0){var OQ=m;if(m=void 0,JQ){let hQ=Cw(OQ);C0.set(JQ,hQ),OQ===0&&v(f??W8(hQ))}f=void 0}},J.webgpuOnReleaseSession=(JQ)=>{C0.delete(JQ)};let QQ=Symbol("gpuBufferMetadata");J.webgpuRegisterBuffer=(JQ,OQ,hQ)=>{if(hQ)return JQ[QQ]=[hQ,NaN],hQ;if(hQ=JQ[QQ])return hQ[1]++,hQ[0];if((OQ=C0.get(OQ))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");return OQ=((T6,h6=0)=>(T6.mapState==="unmapped"||h0(),h6=_X0(h6),F9[h6>>>0]=T6,h6))(JQ,OQ),JQ[QQ]=[OQ,1],OQ},J.webgpuUnregisterBuffer=(JQ)=>{let OQ=JQ[QQ];if(!OQ)throw Error("Buffer is not registered");OQ[1]--,OQ[1]===0&&(TX0(OQ[0]),delete JQ[QQ])},J.webgpuGetBuffer=(JQ)=>W8(JQ),J.webgpuCreateDownloader=(JQ,OQ,hQ)=>{if((hQ=C0.get(hQ))===void 0)throw Error("Invalid session handle passed to webgpuRegisterBuffer");let T6=W8(hQ),h6=16*Math.ceil(Number(OQ)/16);return async()=>{let K9=T6.createBuffer({size:h6,usage:9});try{let V8=T6.createCommandEncoder();return V8.copyBufferToBuffer(JQ,0,K9,0,h6),T6.queue.submit([V8.finish()]),await K9.mapAsync(GPUMapMode.READ),K9.getMappedRange().slice(0,OQ)}finally{K9.destroy()}}},J.ad=(JQ,OQ)=>{var hQ=OQ.buffer;let{byteOffset:T6,byteLength:h6}=OQ;if(OQ=16*Math.ceil(Number(h6)/16),JQ=W8(JQ),!f){var K9=Cw(m);f=W8(K9)}let V8=(K9=f.createBuffer({mappedAtCreation:!0,size:OQ,usage:6})).getMappedRange();new Uint8Array(V8).set(new Uint8Array(hQ,T6,h6)),K9.unmap(),(hQ=f.createCommandEncoder()).copyBufferToBuffer(K9,0,JQ,0,OQ),f.queue.submit([hQ.finish()]),K9.destroy()}},J.webnnInit=(v)=>{let h=v[0];[J.le,J.jd,J.webnnEnsureTensor,J.Sd,J.webnnDownloadTensor,J.ke,J.webnnEnableTraceEvent]=v.slice(1),J.webnnReleaseTensorId=J.jd,J.webnnUploadTensor=J.Sd,J.webnnRegisterMLContext=J.ke,J.webnnOnRunStart=(f)=>h.onRunStart(f),J.webnnOnRunEnd=h.onRunEnd.bind(h),J.webnnOnReleaseSession=(f)=>{h.onReleaseSession(f)},J.webnnCreateMLTensorDownloader=(f,m)=>h.createMLTensorDownloader(f,m),J.webnnRegisterMLTensor=(f,m,s,C0)=>h.registerMLTensor(f,m,s,C0),J.webnnCreateMLContext=(f)=>h.createMLContext(f),J.webnnRegisterMLConstant=(f,m,s,C0,QQ,JQ)=>h.registerMLConstant(f,m,s,C0,QQ,J.Uc,JQ),J.webnnRegisterGraphInput=h.registerGraphInput.bind(h),J.webnnIsGraphInput=h.isGraphInput.bind(h),J.webnnRegisterGraphOutput=h.registerGraphOutput.bind(h),J.webnnIsGraphOutput=h.isGraphOutput.bind(h),J.webnnCreateTemporaryTensor=h.createTemporaryTensor.bind(h),J.webnnIsGraphInputOutputTypeSupported=h.isGraphInputOutputTypeSupported.bind(h)},m0?J:new Promise((v,h)=>{R=v,w=h})}var CR0,gC0,dVQ=q6(()=>{CR0=bC0,gC0=globalThis.self?.name?.startsWith("em-pthread"),gC0&&bC0()}),k60,W90,hC0,ZY,IR0,aC,_C0,fC0,y60,mC0,v60,RR0,x60,wR0,k90=q6(()=>{T90(),k60=typeof location>"u"?void 0:location.origin,W90=!0,hC0=()=>{if(W90)return new URL(new URL("ort.webgpu.bundle.min.mjs","file:///C:/mcp-tools-for-obsidian.ts").href,k60).href;return"file:///C:/mcp-tools-for-obsidian.ts"},ZY=hC0(),IR0=()=>{if(ZY&&!ZY.startsWith("blob:"))return ZY.substring(0,ZY.lastIndexOf("/")+1)},aC=(Q,J)=>{try{let G=J??ZY;return(G?new URL(Q,G):new URL(Q)).origin===k60}catch{return!1}},_C0=(Q,J)=>{let G=J??ZY;try{return(G?new URL(Q,G):new URL(Q)).href}catch{return}},fC0=(Q,J)=>`${J??"./"}${Q}`,y60=async(Q)=>{let J=await(await fetch(Q,{credentials:"same-origin"})).blob();return URL.createObjectURL(J)},mC0=async(Q)=>(await import(Q)).default,v60=(lVQ(),$R(PR0)).default,RR0=async()=>{if(!ZY)throw Error("Failed to load proxy worker: cannot determine the script source URL.");if(aC(ZY))return[void 0,v60()];let Q=await y60(ZY);return[Q,v60(Q)]},x60=(dVQ(),$R(jR0)).default,wR0=async(Q,J,G,H)=>{let K=x60&&!(Q||J);if(K)if(ZY)K=aC(ZY)||H&&!G;else if(H&&!G)K=!0;else throw Error("cannot determine the script source URL.");if(K)return[void 0,x60];{let z="ort-wasm-simd-threaded.asyncify.mjs",q=Q??_C0(z,J),F=G&&q&&!aC(q,J),D=F?await y60(q):q??fC0(z,J);return[F?D:void 0,await mC0(D)]}}}),b60,sC,jF,g60,uC0,pC0,lC0,y90,W9,zB=q6(()=>{k90(),sC=!1,jF=!1,g60=!1,uC0=()=>{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}},pC0=()=>{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}},lC0=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},y90=async(Q)=>{if(sC)return Promise.resolve();if(jF)throw Error("multiple calls to 'initializeWebAssembly()' detected.");if(g60)throw Error("previous call to 'initializeWebAssembly()' failed.");jF=!0;let{initTimeout:J,numThreads:G}=Q;if(Q.simd!==!1){if(Q.simd==="relaxed"){if(!lC0())throw Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!pC0())throw Error("WebAssembly SIMD is not supported in the current environment.")}let H=uC0();G>1&&!H&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+G+", 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."),Q.numThreads=G=1);let K=Q.wasmPaths,z=typeof K=="string"?K:void 0,q=K?.mjs,F=q?.href??q,D=K?.wasm,V=D?.href??D,O=Q.wasmBinary,[P,N]=await wR0(F,z,G>1,!!O||!!V),I=!1,R=[];if(J>0&&R.push(new Promise((w)=>{setTimeout(()=>{I=!0,w()},J)})),R.push(new Promise((w,E)=>{let T={numThreads:G};if(O)T.wasmBinary=O,T.locateFile=(y)=>y;else if(V||z)T.locateFile=(y)=>V??z+y;else if(F&&F.indexOf("blob:")!==0)T.locateFile=(y)=>new URL(y,F).href;else if(P){let y=IR0();y&&(T.locateFile=(x)=>y+x)}N(T).then((y)=>{jF=!1,sC=!0,b60=y,w(),P&&URL.revokeObjectURL(P)},(y)=>{jF=!1,g60=!0,E(y)})})),await Promise.race(R),I)throw Error(`WebAssembly backend initializing failed due to timeout: ${J}ms`)},W9=()=>{if(sC&&b60)return b60;throw Error("WebAssembly is not initialized yet.")}}),FY,FR,g6,v90=q6(()=>{zB(),FY=(Q,J)=>{let G=W9(),H=G.lengthBytesUTF8(Q)+1,K=G._malloc(H);return G.stringToUTF8(Q,K,H),J.push(K),K},FR=(Q,J,G,H)=>{if(typeof Q=="object"&&Q!==null){if(G.has(Q))throw Error("Circular reference in options");G.add(Q)}Object.entries(Q).forEach(([K,z])=>{let q=J?J+K:K;if(typeof z=="object")FR(z,q+".",G,H);else if(typeof z=="string"||typeof z=="number")H(q,z.toString());else if(typeof z=="boolean")H(q,z?"1":"0");else throw Error(`Can't handle extra config type: ${typeof z}`)})},g6=(Q)=>{let J=W9(),G=J.stackSave();try{let H=J.PTR_SIZE,K=J.stackAlloc(2*H);J._OrtGetLastError(K,K+H);let z=Number(J.getValue(K,H===4?"i32":"i64")),q=J.getValue(K+H,"*"),F=q?J.UTF8ToString(q):"";throw Error(`${Q} ERROR_CODE: ${z}, ERROR_MESSAGE: ${F}`)}finally{J.stackRestore(G)}}}),ER0,cVQ=q6(()=>{zB(),v90(),ER0=(Q)=>{let J=W9(),G=0,H=[],K=Q||{};try{if(Q?.logSeverityLevel===void 0)K.logSeverityLevel=2;else if(typeof Q.logSeverityLevel!="number"||!Number.isInteger(Q.logSeverityLevel)||Q.logSeverityLevel<0||Q.logSeverityLevel>4)throw Error(`log severity level is not valid: ${Q.logSeverityLevel}`);if(Q?.logVerbosityLevel===void 0)K.logVerbosityLevel=0;else if(typeof Q.logVerbosityLevel!="number"||!Number.isInteger(Q.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${Q.logVerbosityLevel}`);Q?.terminate===void 0&&(K.terminate=!1);let z=0;return Q?.tag!==void 0&&(z=FY(Q.tag,H)),G=J._OrtCreateRunOptions(K.logSeverityLevel,K.logVerbosityLevel,!!K.terminate,z),G===0&&g6("Can't create run options."),Q?.extra!==void 0&&FR(Q.extra,"",new WeakSet,(q,F)=>{let D=FY(q,H),V=FY(F,H);J._OrtAddRunConfigEntry(G,D,V)!==0&&g6(`Can't set a run config entry: ${q} - ${F}.`)}),[G,H]}catch(z){throw G!==0&&J._OrtReleaseRunOptions(G),H.forEach((q)=>J._free(q)),z}}}),dC0,cC0,iC0,rC,AH,oC0,SR0,iVQ=q6(()=>{zB(),v90(),dC0=(Q)=>{switch(Q){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw Error(`unsupported graph optimization level: ${Q}`)}},cC0=(Q)=>{switch(Q){case"sequential":return 0;case"parallel":return 1;default:throw Error(`unsupported execution mode: ${Q}`)}},iC0=(Q)=>{Q.extra||(Q.extra={}),Q.extra.session||(Q.extra.session={});let J=Q.extra.session;J.use_ort_model_bytes_directly||(J.use_ort_model_bytes_directly="1"),Q.executionProviders&&Q.executionProviders.some((G)=>(typeof G=="string"?G:G.name)==="webgpu")&&(Q.enableMemPattern=!1)},rC=(Q,J,G,H)=>{let K=FY(J,H),z=FY(G,H);W9()._OrtAddSessionConfigEntry(Q,K,z)!==0&&g6(`Can't set a session config entry: ${J} - ${G}.`)},AH=(Q,J,G,H)=>{let K=FY(J,H),z=FY(G,H);Q.push([K,z])},oC0=async(Q,J,G)=>{let H=J.executionProviders;for(let K of H){let z=typeof K=="string"?K:K.name,q=[];switch(z){case"webnn":if(z="WEBNN",typeof K!="string"){let P=K?.deviceType;P&&rC(Q,"deviceType",P,G)}break;case"webgpu":{z="WebGPU";let P;if(typeof K!="string"){let I=K;if(I.device)if(typeof GPUDevice<"u"&&I.device instanceof GPUDevice)P=I.device;else throw Error("Invalid GPU device set in WebGPU EP options.");let{enableGraphCapture:R}=J;if(typeof R=="boolean"&&R&&AH(q,"enableGraphCapture","1",G),typeof I.preferredLayout=="string"&&AH(q,"preferredLayout",I.preferredLayout,G),I.forceCpuNodeNames){let w=Array.isArray(I.forceCpuNodeNames)?I.forceCpuNodeNames:[I.forceCpuNodeNames];AH(q,"forceCpuNodeNames",w.join(`
`),G)}I.validationMode&&AH(q,"validationMode",I.validationMode,G)}let N=W9().webgpuRegisterDevice(P);if(N){let[I,R,w]=N;AH(q,"deviceId",I.toString(),G),AH(q,"webgpuInstance",R.toString(),G),AH(q,"webgpuDevice",w.toString(),G)}}break;case"wasm":case"cpu":continue;default:throw Error(`not supported execution provider: ${z}`)}let F=FY(z,G),D=q.length,V=0,O=0;if(D>0){V=W9()._malloc(D*W9().PTR_SIZE),G.push(V),O=W9()._malloc(D*W9().PTR_SIZE),G.push(O);for(let P=0;P<D;P++)W9().setValue(V+P*W9().PTR_SIZE,q[P][0],"*"),W9().setValue(O+P*W9().PTR_SIZE,q[P][1],"*")}await W9()._OrtAppendExecutionProvider(Q,F,V,O,D)!==0&&g6(`Can't append execution provider: ${z}.`)}},SR0=async(Q)=>{let J=W9(),G=0,H=[],K=Q||{};iC0(K);try{let z=dC0(K.graphOptimizationLevel??"all"),q=cC0(K.executionMode??"sequential"),F=typeof K.logId=="string"?FY(K.logId,H):0,D=K.logSeverityLevel??2;if(!Number.isInteger(D)||D<0||D>4)throw Error(`log severity level is not valid: ${D}`);let V=K.logVerbosityLevel??0;if(!Number.isInteger(V)||V<0||V>4)throw Error(`log verbosity level is not valid: ${V}`);let O=typeof K.optimizedModelFilePath=="string"?FY(K.optimizedModelFilePath,H):0;if(G=J._OrtCreateSessionOptions(z,!!K.enableCpuMemArena,!!K.enableMemPattern,q,!!K.enableProfiling,0,F,D,V,O),G===0&&g6("Can't create session options."),K.executionProviders&&await oC0(G,K,H),K.enableGraphCapture!==void 0){if(typeof K.enableGraphCapture!="boolean")throw Error(`enableGraphCapture must be a boolean value: ${K.enableGraphCapture}`);rC(G,"enableGraphCapture",K.enableGraphCapture.toString(),H)}if(K.freeDimensionOverrides)for(let[P,N]of Object.entries(K.freeDimensionOverrides)){if(typeof P!="string")throw Error(`free dimension override name must be a string: ${P}`);if(typeof N!="number"||!Number.isInteger(N)||N<0)throw Error(`free dimension override value must be a non-negative integer: ${N}`);let I=FY(P,H);J._OrtAddFreeDimensionOverride(G,I,N)!==0&&g6(`Can't set a free dimension override: ${P} - ${N}.`)}return K.extra!==void 0&&FR(K.extra,"",new WeakSet,(P,N)=>{rC(G,P,N,H)}),[G,H]}catch(z){throw G!==0&&J._OrtReleaseSessionOptions(G)!==0&&g6("Can't release session options."),H.forEach((q)=>J._free(q)),z}}}),YB,HR,FV,bF,DR,x90,b90,H90,EV=q6(()=>{YB=(Q)=>{switch(Q){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw Error(`unsupported data type: ${Q}`)}},HR=(Q)=>{switch(Q){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw Error(`unsupported data type: ${Q}`)}},FV=(Q,J)=>{let G=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,0.5,0.5][Q],H=typeof J=="number"?J:J.reduce((K,z)=>K*z,1);return G>0?Math.ceil(H*G):void 0},bF=(Q)=>{switch(Q){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 Error(`unsupported type: ${Q}`)}},DR=(Q)=>{switch(Q){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw Error(`unsupported logging level: ${Q}`)}},x90=(Q)=>Q==="float32"||Q==="float16"||Q==="int32"||Q==="int64"||Q==="uint32"||Q==="uint8"||Q==="bool"||Q==="uint4"||Q==="int4",b90=(Q)=>Q==="float32"||Q==="float16"||Q==="int32"||Q==="int64"||Q==="uint32"||Q==="uint64"||Q==="int8"||Q==="uint8"||Q==="bool"||Q==="uint4"||Q==="int4",H90=(Q)=>{switch(Q){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw Error(`unsupported data location: ${Q}`)}}}),g90,TR0=q6(()=>{T90(),g90=async(Q)=>{if(typeof Q=="string"){let J=await fetch(Q);if(!J.ok)throw Error(`failed to load external data file: ${Q}`);let G=J.headers.get("Content-Length"),H=G?parseInt(G,10):0;if(H<1073741824)return new Uint8Array(await J.arrayBuffer());{if(!J.body)throw Error(`failed to load external data file: ${Q}, no response body.`);let K=J.body.getReader(),z;try{z=new ArrayBuffer(H)}catch(F){if(F instanceof RangeError){let D=Math.ceil(H/65536);z=new WebAssembly.Memory({initial:D,maximum:D}).buffer}else throw F}let q=0;for(;;){let{done:F,value:D}=await K.read();if(F)break;let V=D.byteLength;new Uint8Array(z,q,V).set(D),q+=V}return new Uint8Array(z,0,H)}}else return Q instanceof Blob?new Uint8Array(await Q.arrayBuffer()):Q instanceof Uint8Array?Q:new Uint8Array(Q)}}),kR0,oVQ=q6(()=>{EV(),kR0=(Q,J)=>new(bF(J))(Q)}),nC0,aC0,sC0,rC0,yR0,tC0,aX,vR0=q6(()=>{EV(),nC0=["V","I","W","E","F"],aC0=(Q,J)=>{console.log(`[${nC0[Q]},${new Date().toISOString()}]${J}`)},yR0=(Q,J)=>{sC0=Q,rC0=J},tC0=(Q,J)=>{let G=DR(Q),H=DR(sC0);G>=H&&aC0(G,typeof J=="function"?J():J)},aX=(...Q)=>{rC0&&tC0(...Q)}}),h60,B90,_60,eC0,f60,QI0,m60,u60,p60,XI0,xR0,nVQ=q6(()=>{EV(),vR0(),h60=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),B90=(Q,J)=>{if(J==="int32")return Q;let G=h60.get(J);if(!G)throw Error(`WebNN backend does not support data type: ${J}`);let H=G/8;if(Q.byteLength%H!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${H}.`);let K=Q.byteLength/H,z=new(bF(J))(Q.buffer,Q.byteOffset,K);switch(J){case"int64":case"uint64":{let q=new Int32Array(K);for(let F=0;F<K;F++){let D=z[F];if(D>2147483647n||D<-2147483648n)throw Error("Can not convert int64 data to int32 - value out of range.");q[F]=Number(D)}return new Uint8Array(q.buffer)}case"int8":case"uint8":case"uint32":{if(J==="uint32"&&z.some((F)=>F>2147483647))throw Error("Can not convert uint32 data to int32 - value out of range.");let q=Int32Array.from(z,Number);return new Uint8Array(q.buffer)}default:throw Error(`Unsupported data conversion from ${J} to 'int32'`)}},_60=(Q,J)=>{if(J==="int32")return Q;if(Q.byteLength%4!==0)throw Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let G=Q.byteLength/4,H=new Int32Array(Q.buffer,Q.byteOffset,G);switch(J){case"int64":{let K=BigInt64Array.from(H,BigInt);return new Uint8Array(K.buffer)}case"uint64":{if(H.some((z)=>z<0))throw Error("Can not convert int32 data to uin64 - negative value found.");let K=BigUint64Array.from(H,BigInt);return new Uint8Array(K.buffer)}case"int8":{if(H.some((z)=>z<-128||z>127))throw Error("Can not convert int32 data to int8 - value out of range.");let K=Int8Array.from(H,Number);return new Uint8Array(K.buffer)}case"uint8":{if(H.some((K)=>K<0||K>255))throw Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(H,Number)}case"uint32":{if(H.some((z)=>z<0))throw Error("Can not convert int32 data to uint32 - negative value found.");let K=Uint32Array.from(H,Number);return new Uint8Array(K.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${J}`)}},eC0=1,f60=()=>eC0++,QI0=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),m60=(Q,J)=>{let G=h60.get(Q);if(!G)throw Error(`WebNN backend does not support data type: ${Q}`);return J.length>0?Math.ceil(J.reduce((H,K)=>H*K)*G/8):0},u60=class{constructor(Q){this.isDataConverted=!1;let{sessionId:J,context:G,tensor:H,dataType:K,shape:z,fallbackDataType:q}=Q;this.sessionId=J,this.mlContext=G,this.mlTensor=H,this.dataType=K,this.tensorShape=z,this.fallbackDataType=q}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return m60(this.dataType,this.tensorShape)}destroy(){aX("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(Q){this.mlContext.writeTensor(this.mlTensor,Q)}async read(Q){if(this.fallbackDataType){let J=await this.mlContext.readTensor(this.mlTensor),G=_60(new Uint8Array(J),this.dataType);if(Q){(Q instanceof ArrayBuffer?new Uint8Array(Q):new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength)).set(G);return}else return G.buffer}else return Q?this.mlContext.readTensor(this.mlTensor,Q):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(Q,J,G){return this.mlContext===Q&&this.dataType===J&&this.tensorShape.length===G.length&&this.tensorShape.every((H,K)=>H===G[K])}setIsDataConverted(Q){this.isDataConverted=Q}},p60=class{constructor(Q,J){this.tensorManager=Q,this.wrapper=J}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(Q,J,G,H){let K=this.tensorManager.getMLContext(Q),z=this.tensorManager.getMLOpSupportLimits(Q),q;if(!z?.input.dataTypes.includes(J)){if(q=QI0.get(J),!q||z?.input.dataTypes.includes(q))throw Error(`WebNN backend does not support data type: ${J}`);aX("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${J} to ${q}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(K,J,G))return this.wrapper.tensor;if(H){if(this.wrapper.byteLength!==m60(J,G))throw Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let F=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(Q,J,G,F,!0,!0,q),H&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(Q){let J=Q;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")J=B90(Q,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(Q.byteLength===this.wrapper.byteLength){this.wrapper.write(J);return}else aX("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(J):this.activeUpload=new Uint8Array(J)}async download(Q){if(this.activeUpload){let J=this.wrapper?.isDataConverted?_60(this.activeUpload,this.wrapper?.type):this.activeUpload;if(Q){Q instanceof ArrayBuffer?new Uint8Array(Q).set(J):new Uint8Array(Q.buffer,Q.byteOffset,Q.byteLength).set(J);return}else return J.buffer}if(!this.wrapper)throw Error("Tensor has not been created.");return Q?this.wrapper.read(Q):this.wrapper.read()}},XI0=class{constructor(Q){this.backend=Q,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(Q){let J=this.backend.getMLContext(Q);if(!J)throw Error("MLContext not found for session.");return J}getMLOpSupportLimits(Q){return this.backend.getMLOpSupportLimits(Q)}reserveTensorId(){let Q=f60();return this.tensorTrackersById.set(Q,new p60(this)),Q}releaseTensorId(Q){let J=this.tensorTrackersById.get(Q);J&&(this.tensorTrackersById.delete(Q),J.tensorWrapper&&this.releaseTensor(J.tensorWrapper))}async ensureTensor(Q,J,G,H,K){aX("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${J}, dataType: ${G}, shape: ${H}, copyOld: ${K}}`);let z=this.tensorTrackersById.get(J);if(!z)throw Error("Tensor not found.");return z.ensureTensor(Q,G,H,K)}upload(Q,J){let G=this.tensorTrackersById.get(Q);if(!G)throw Error("Tensor not found.");G.upload(J)}async download(Q,J){aX("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${Q}, dstBuffer: ${J?.byteLength}}`);let G=this.tensorTrackersById.get(Q);if(!G)throw Error("Tensor not found.");return G.download(J)}releaseTensorsForSession(Q){for(let J of this.freeTensors)J.sessionId===Q&&J.destroy();this.freeTensors=this.freeTensors.filter((J)=>J.sessionId!==Q)}registerTensor(Q,J,G,H){let K=this.getMLContext(Q),z=f60(),q=new u60({sessionId:Q,context:K,tensor:J,dataType:G,shape:H});return this.tensorTrackersById.set(z,new p60(this,q)),this.externalTensors.add(q),z}async getCachedTensor(Q,J,G,H,K,z,q){let F=this.getMLContext(Q);for(let[V,O]of this.freeTensors.entries())if(O.canReuseTensor(F,J,G)){aX("verbose",()=>`[WebNN] Reusing tensor {dataType: ${J}, ${q?`fallbackDataType: ${q},`:""} shape: ${G}`);let P=this.freeTensors.splice(V,1)[0];return P.sessionId=Q,P}aX("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${J}, ${q?`fallbackDataType: ${q},`:""} shape: ${G}}`);let D=await F.createTensor({dataType:q??J,shape:G,dimensions:G,usage:H,writable:K,readable:z});return new u60({sessionId:Q,context:F,tensor:D,dataType:J,shape:G,fallbackDataType:q})}releaseTensor(Q){this.externalTensors.has(Q)&&this.externalTensors.delete(Q),this.freeTensors.push(Q)}},xR0=(...Q)=>new XI0(...Q)}),bR0={};pF(bR0,{WebNNBackend:()=>gR0});var CF,JI0,gR0,aVQ=q6(()=>{EV(),zB(),oVQ(),nVQ(),vR0(),CF=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),JI0=(Q,J)=>{if(Q===J)return!0;if(Q===void 0||J===void 0)return!1;let G=Object.keys(Q).sort(),H=Object.keys(J).sort();return G.length===H.length&&G.every((K,z)=>K===H[z]&&Q[K]===J[K])},gR0=class{constructor(Q){this.tensorManager=xR0(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,yR0(Q.logLevel,!!Q.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error("No active session");return this.activeSessionId}onRunStart(Q){aX("verbose",()=>`[WebNN] onRunStart {sessionId: ${Q}}`),this.activeSessionId=Q}onRunEnd(Q){aX("verbose",()=>`[WebNN] onRunEnd {sessionId: ${Q}}`);let J=this.temporarySessionTensorIds.get(Q);if(J){for(let G of J)aX("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${G}}`),this.tensorManager.releaseTensorId(G);this.temporarySessionTensorIds.delete(Q),this.activeSessionId=void 0}}async createMLContext(Q){if(Q instanceof GPUDevice){let G=this.mlContextCache.findIndex((H)=>H.gpuDevice===Q);if(G!==-1)return this.mlContextCache[G].mlContext;{let H=await navigator.ml.createContext(Q);return this.mlContextCache.push({gpuDevice:Q,mlContext:H}),H}}else if(Q===void 0){let G=this.mlContextCache.findIndex((H)=>H.options===void 0&&H.gpuDevice===void 0);if(G!==-1)return this.mlContextCache[G].mlContext;{let H=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:H}),H}}let J=this.mlContextCache.findIndex((G)=>JI0(G.options,Q));if(J!==-1)return this.mlContextCache[J].mlContext;{let G=await navigator.ml.createContext(Q);return this.mlContextCache.push({options:Q,mlContext:G}),G}}registerMLContext(Q,J){this.mlContextBySessionId.set(Q,J);let G=this.sessionIdsByMLContext.get(J);G||(G=new Set,this.sessionIdsByMLContext.set(J,G)),G.add(Q),this.mlOpSupportLimitsBySessionId.has(Q)||this.mlOpSupportLimitsBySessionId.set(Q,J.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(Q,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(Q,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(Q){this.sessionGraphInputs.delete(Q),this.sessionGraphOutputs.delete(Q);let J=this.mlContextBySessionId.get(Q);if(!J)return;this.tensorManager.releaseTensorsForSession(Q),this.mlContextBySessionId.delete(Q),this.mlOpSupportLimitsBySessionId.delete(Q);let G=this.sessionIdsByMLContext.get(J);if(G.delete(Q),G.size===0){this.sessionIdsByMLContext.delete(J);let H=this.mlContextCache.findIndex((K)=>K.mlContext===J);H!==-1&&this.mlContextCache.splice(H,1)}}getMLContext(Q){return this.mlContextBySessionId.get(Q)}getMLOpSupportLimits(Q){return this.mlOpSupportLimitsBySessionId.get(Q)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(Q){aX("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${Q}}`),this.tensorManager.releaseTensorId(Q)}async ensureTensor(Q,J,G,H,K){let z=CF.get(G);if(!z)throw Error(`Unsupported ONNX data type: ${G}`);return this.tensorManager.ensureTensor(Q??this.currentSessionId,J,z,H,K)}async createTemporaryTensor(Q,J,G){aX("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${J}, shape: ${G}}`);let H=CF.get(J);if(!H)throw Error(`Unsupported ONNX data type: ${J}`);let K=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(Q,K,H,G,!1);let z=this.temporarySessionTensorIds.get(Q);return z?z.push(K):this.temporarySessionTensorIds.set(Q,[K]),K}uploadTensor(Q,J){if(!W9().shouldTransferToMLTensor)throw Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");aX("verbose",()=>`[WebNN] uploadTensor {tensorId: ${Q}, data: ${J.byteLength}}`),this.tensorManager.upload(Q,J)}async downloadTensor(Q,J){return this.tensorManager.download(Q,J)}createMLTensorDownloader(Q,J){return async()=>{let G=await this.tensorManager.download(Q);return kR0(G,J)}}registerMLTensor(Q,J,G,H){let K=CF.get(G);if(!K)throw Error(`Unsupported ONNX data type: ${G}`);let z=this.tensorManager.registerTensor(Q,J,K,H);return aX("verbose",()=>`[WebNN] registerMLTensor {tensor: ${J}, dataType: ${K}, dimensions: ${H}} -> {tensorId: ${z}}`),z}registerMLConstant(Q,J,G,H,K,z,q=!1){if(!z)throw Error("External mounted files are not available.");let F=Q;Q.startsWith("./")&&(F=Q.substring(2));let D=z.get(F);if(!D)throw Error(`File with name ${F} not found in preloaded files.`);if(J+G>D.byteLength)throw Error("Out of bounds: data offset and length exceed the external file data size.");let V=D.slice(J,J+G).buffer,O;switch(K.dataType){case"float32":O=new Float32Array(V);break;case"float16":O=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(V):new Uint16Array(V);break;case"int32":O=new Int32Array(V);break;case"uint32":O=new Uint32Array(V);break;case"int64":if(q){let P=B90(new Uint8Array(V),"int64");O=new Int32Array(P.buffer),K.dataType="int32"}else O=new BigInt64Array(V);break;case"uint64":O=new BigUint64Array(V);break;case"int8":O=new Int8Array(V);break;case"int4":case"uint4":case"uint8":O=new Uint8Array(V);break;default:throw Error(`Unsupported data type: ${K.dataType} in creating WebNN Constant from external data.`)}return aX("verbose",()=>`[WebNN] registerMLConstant {dataType: ${K.dataType}, shape: ${K.shape}}} ${q?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),H.constant(K,O)}registerGraphInput(Q){this.temporaryGraphInputs.push(Q)}registerGraphOutput(Q){this.temporaryGraphOutputs.push(Q)}isGraphInput(Q,J){let G=this.sessionGraphInputs.get(Q);return G?G.includes(J):!1}isGraphOutput(Q,J){let G=this.sessionGraphOutputs.get(Q);return G?G.includes(J):!1}isGraphInputOutputTypeSupported(Q,J,G=!0){let H=CF.get(YB(J)),K=this.mlOpSupportLimitsBySessionId.get(Q);return typeof H>"u"?!1:G?!!K?.input.dataTypes.includes(H):!!K?.output.dataTypes.includes(H)}flush(){}}}),YI0,h90,_90,KH,GI0,l60,MR,f90,m90,d60,u90,p90,l90,hR0=q6(()=>{KB(),cVQ(),iVQ(),EV(),zB(),v90(),TR0(),YI0=(Q,J)=>{W9()._OrtInit(Q,J)!==0&&g6("Can't initialize onnxruntime.")},h90=async(Q)=>{YI0(Q.wasm.numThreads,DR(Q.logLevel))},_90=async(Q,J)=>{W9().asyncInit?.();let G=Q.webgpu.adapter;if(J==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw Error("WebGPU is not supported in current environment");if(G){if(typeof G.limits!="object"||typeof G.features!="object"||typeof G.requestDevice!="function")throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let H=Q.webgpu.powerPreference;if(H!==void 0&&H!=="low-power"&&H!=="high-performance")throw Error(`Invalid powerPreference setting: "${H}"`);let K=Q.webgpu.forceFallbackAdapter;if(K!==void 0&&typeof K!="boolean")throw Error(`Invalid forceFallbackAdapter setting: "${K}"`);if(G=await navigator.gpu.requestAdapter({powerPreference:H,forceFallbackAdapter:K}),!G)throw Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(J==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw Error("WebNN is not supported in current environment");if(J==="webgpu"&&W9().webgpuInit((H)=>{Q.webgpu.device=H}),J==="webnn"){let H=new(aVQ(),$R(bR0)).WebNNBackend(Q);W9().webnnInit([H,()=>H.reserveTensorId(),(K)=>H.releaseTensorId(K),async(K,z,q,F,D)=>H.ensureTensor(K,z,q,F,D),(K,z)=>{H.uploadTensor(K,z)},async(K,z)=>H.downloadTensor(K,z),(K,z)=>H.registerMLContext(K,z),!!Q.trace])}},KH=new Map,GI0=(Q)=>{let J=W9(),G=J.stackSave();try{let H=J.PTR_SIZE,K=J.stackAlloc(2*H);J._OrtGetInputOutputCount(Q,K,K+H)!==0&&g6("Can't get session input/output count.");let z=H===4?"i32":"i64";return[Number(J.getValue(K,z)),Number(J.getValue(K+H,z))]}finally{J.stackRestore(G)}},l60=(Q,J)=>{let G=W9(),H=G.stackSave(),K=0;try{let z=G.PTR_SIZE,q=G.stackAlloc(2*z);G._OrtGetInputOutputMetadata(Q,J,q,q+z)!==0&&g6("Can't get session input/output metadata.");let F=Number(G.getValue(q,"*"));K=Number(G.getValue(q+z,"*"));let D=G.HEAP32[K/4];if(D===0)return[F,0];let V=G.HEAPU32[K/4+1],O=[];for(let P=0;P<V;P++){let N=Number(G.getValue(K+8+P*z,"*"));O.push(N!==0?G.UTF8ToString(N):Number(G.getValue(K+8+(P+V)*z,"*")))}return[F,D,O]}finally{G.stackRestore(H),K!==0&&G._OrtFree(K)}},MR=(Q)=>{let J=W9(),G=J._malloc(Q.byteLength);if(G===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${Q.byteLength}.`);return J.HEAPU8.set(Q,G),[G,Q.byteLength]},f90=async(Q,J)=>{let G,H,K=W9();Array.isArray(Q)?[G,H]=Q:Q.buffer===K.HEAPU8.buffer?[G,H]=[Q.byteOffset,Q.byteLength]:[G,H]=MR(Q);let z=0,q=0,F=0,D=[],V=[],O=[];try{if([q,D]=await SR0(J),J?.externalData&&K.mountExternalData){let b=[];for(let g of J.externalData){let l=typeof g=="string"?g:g.path;b.push(g90(typeof g=="string"?g:g.data).then((_)=>{K.mountExternalData(l,_)}))}await Promise.all(b)}for(let b of J?.executionProviders??[])if((typeof b=="string"?b:b.name)==="webnn"){if(K.shouldTransferToMLTensor=!1,typeof b!="string"){let g=b,l=g?.context,_=g?.gpuDevice,a=g?.deviceType,r=g?.powerPreference;l?K.currentContext=l:_?K.currentContext=await K.webnnCreateMLContext(_):K.currentContext=await K.webnnCreateMLContext({deviceType:a,powerPreference:r})}else K.currentContext=await K.webnnCreateMLContext();break}z=await K._OrtCreateSession(G,H,q),K.webgpuOnCreateSession?.(z),z===0&&g6("Can't create a session."),K.jsepOnCreateSession?.(),K.currentContext&&(K.webnnRegisterMLContext(z,K.currentContext),K.currentContext=void 0,K.shouldTransferToMLTensor=!0);let[P,N]=GI0(z),I=!!J?.enableGraphCapture,R=[],w=[],E=[],T=[],y=[];for(let b=0;b<P;b++){let[g,l,_]=l60(z,b);g===0&&g6("Can't get an input name."),V.push(g);let a=K.UTF8ToString(g);R.push(a),E.push(l===0?{name:a,isTensor:!1}:{name:a,isTensor:!0,type:HR(l),shape:_})}for(let b=0;b<N;b++){let[g,l,_]=l60(z,b+P);g===0&&g6("Can't get an output name."),O.push(g);let a=K.UTF8ToString(g);w.push(a),T.push(l===0?{name:a,isTensor:!1}:{name:a,isTensor:!0,type:HR(l),shape:_});{if(I&&J?.preferredOutputLocation===void 0){y.push("gpu-buffer");continue}let r=typeof J?.preferredOutputLocation=="string"?J.preferredOutputLocation:J?.preferredOutputLocation?.[a]??"cpu",f0=K.webnnIsGraphOutput;if(r==="cpu"&&f0&&f0(z,a)){y.push("ml-tensor-cpu-output");continue}if(r!=="cpu"&&r!=="cpu-pinned"&&r!=="gpu-buffer"&&r!=="ml-tensor")throw Error(`Not supported preferred output location: ${r}.`);if(I&&r!=="gpu-buffer")throw Error(`Not supported preferred output location: ${r}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);y.push(r)}}let x=null;return y.some((b)=>b==="gpu-buffer"||b==="ml-tensor"||b==="ml-tensor-cpu-output")&&(F=K._OrtCreateBinding(z),F===0&&g6("Can't create IO binding."),x={handle:F,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map((b)=>b==="ml-tensor-cpu-output"?"ml-tensor":b).map((b)=>H90(b))}),KH.set(z,[z,V,O,x,I,!1]),[z,R,w,E,T]}catch(P){throw V.forEach((N)=>K._OrtFree(N)),O.forEach((N)=>K._OrtFree(N)),F!==0&&K._OrtReleaseBinding(F)!==0&&g6("Can't release IO binding."),z!==0&&K._OrtReleaseSession(z)!==0&&g6("Can't release session."),P}finally{K._free(G),q!==0&&K._OrtReleaseSessionOptions(q)!==0&&g6("Can't release session options."),D.forEach((P)=>K._free(P)),K.unmountExternalData?.()}},m90=(Q)=>{let J=W9(),G=KH.get(Q);if(!G)throw Error(`cannot release session. invalid session id: ${Q}`);let[H,K,z,q,F]=G;q&&(F&&J._OrtClearBoundOutputs(q.handle)!==0&&g6("Can't clear bound outputs."),J._OrtReleaseBinding(q.handle)!==0&&g6("Can't release IO binding.")),J.jsepOnReleaseSession?.(Q),J.webnnOnReleaseSession?.(Q),J.webgpuOnReleaseSession?.(Q),K.forEach((D)=>J._OrtFree(D)),z.forEach((D)=>J._OrtFree(D)),J._OrtReleaseSession(H)!==0&&g6("Can't release session."),KH.delete(Q)},d60=async(Q,J,G,H,K,z,q=!1)=>{if(!Q){J.push(0);return}let F=W9(),D=F.PTR_SIZE,V=Q[0],O=Q[1],P=Q[3],N=P,I,R;if(V==="string"&&(P==="gpu-buffer"||P==="ml-tensor"))throw Error("String tensor is not supported on GPU.");if(q&&P!=="gpu-buffer")throw Error(`External buffer must be provided for input/output index ${z} when enableGraphCapture is true.`);if(P==="gpu-buffer"){let T=Q[2].gpuBuffer;R=FV(YB(V),O);{let y=F.webgpuRegisterBuffer;if(!y)throw Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');I=y(T,H)}}else if(P==="ml-tensor"){let T=Q[2].mlTensor;R=FV(YB(V),O);let y=F.webnnRegisterMLTensor;if(!y)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');I=y(H,T,YB(V),O)}else{let T=Q[2];if(Array.isArray(T)){R=D*T.length,I=F._malloc(R),G.push(I);for(let y=0;y<T.length;y++){if(typeof T[y]!="string")throw TypeError(`tensor data at index ${y} is not a string`);F.setValue(I+y*D,FY(T[y],G),"*")}}else{let{webnnIsGraphInput:y,webnnIsGraphOutput:x}=F;if(V!=="string"&&y&&x){let b=F.UTF8ToString(K);if(y(H,b)||x(H,b)){let g=YB(V);R=FV(g,O),N="ml-tensor";let{webnnCreateTemporaryTensor:l,webnnUploadTensor:_}=F;if(!l||!_)throw Error('Tensor location "ml-tensor" is not supported without using WebNN.');let a=await l(H,g,O);_(a,new Uint8Array(T.buffer,T.byteOffset,T.byteLength)),I=a}else R=T.byteLength,I=F._malloc(R),G.push(I),F.HEAPU8.set(new Uint8Array(T.buffer,T.byteOffset,R),I)}else R=T.byteLength,I=F._malloc(R),G.push(I),F.HEAPU8.set(new Uint8Array(T.buffer,T.byteOffset,R),I)}}let w=F.stackSave(),E=F.stackAlloc(4*O.length);try{O.forEach((y,x)=>F.setValue(E+x*D,y,D===4?"i32":"i64"));let T=F._OrtCreateTensor(YB(V),I,R,E,O.length,H90(N));T===0&&g6(`Can't create tensor for input/output. session=${H}, index=${z}.`),J.push(T)}finally{F.stackRestore(w)}},u90=async(Q,J,G,H,K,z)=>{let q=W9(),F=q.PTR_SIZE,D=KH.get(Q);if(!D)throw Error(`cannot run inference. invalid session id: ${Q}`);let V=D[0],O=D[1],P=D[2],N=D[3],I=D[4],R=D[5],w=J.length,E=H.length,T=0,y=[],x=[],b=[],g=[],l=[],_=q.stackSave(),a=q.stackAlloc(w*F),r=q.stackAlloc(w*F),f0=q.stackAlloc(E*F),t=q.stackAlloc(E*F);try{[T,y]=ER0(z),$H("wasm prepareInputOutputTensor");for(let n=0;n<w;n++)await d60(G[n],x,g,Q,O[J[n]],J[n],I);for(let n=0;n<E;n++)await d60(K[n],b,g,Q,P[H[n]],w+H[n],I);ZH("wasm prepareInputOutputTensor");for(let n=0;n<w;n++)q.setValue(a+n*F,x[n],"*"),q.setValue(r+n*F,O[J[n]],"*");for(let n=0;n<E;n++)q.setValue(f0+n*F,b[n],"*"),q.setValue(t+n*F,P[H[n]],"*");if(N&&!R){let{handle:n,outputPreferredLocations:c0,outputPreferredLocationsEncoded:WQ}=N;if(O.length!==w)throw Error(`input count from feeds (${w}) is expected to be always equal to model's input count (${O.length}).`);$H("wasm bindInputsOutputs");for(let R0=0;R0<w;R0++){let l0=J[R0];await q._OrtBindInput(n,O[l0],x[R0])!==0&&g6(`Can't bind input[${R0}] for session=${Q}.`)}for(let R0=0;R0<E;R0++){let l0=H[R0];K[R0]?.[3]?(l.push(b[R0]),q._OrtBindOutput(n,P[l0],b[R0],0)!==0&&g6(`Can't bind pre-allocated output[${R0}] for session=${Q}.`)):q._OrtBindOutput(n,P[l0],0,WQ[l0])!==0&&g6(`Can't bind output[${R0}] to ${c0[R0]} for session=${Q}.`)}ZH("wasm bindInputsOutputs"),KH.set(Q,[V,O,P,N,I,!0])}q.jsepOnRunStart?.(V),q.webnnOnRunStart?.(V);let p0;N?p0=await q._OrtRunWithBinding(V,N.handle,E,f0,T):p0=await q._OrtRun(V,r,a,w,t,E,f0,T),p0!==0&&g6("failed to call OrtRun().");let u0=[],d=[];$H("wasm ProcessOutputTensor");for(let n=0;n<E;n++){let c0=Number(q.getValue(f0+n*F,"*"));if(c0===b[n]||l.includes(b[n])){u0.push(K[n]),c0!==b[n]&&q._OrtReleaseTensor(c0)!==0&&g6("Can't release tensor.");continue}let WQ=q.stackSave(),R0=q.stackAlloc(4*F),l0=!1,d0,m0=0;try{q._OrtGetTensorData(c0,R0,R0+F,R0+2*F,R0+3*F)!==0&&g6(`Can't access output tensor data on index ${n}.`);let ZQ=F===4?"i32":"i64",LQ=Number(q.getValue(R0,ZQ));m0=q.getValue(R0+F,"*");let h0=q.getValue(R0+F*2,"*"),pQ=Number(q.getValue(R0+F*3,ZQ)),iQ=[];for(let MQ=0;MQ<pQ;MQ++)iQ.push(Number(q.getValue(h0+MQ*F,ZQ)));q._OrtFree(h0)!==0&&g6("Can't free memory for tensor dims.");let mQ=iQ.reduce((MQ,DQ)=>MQ*DQ,1);d0=HR(LQ);let AQ=N?.outputPreferredLocations[H[n]];if(d0==="string"){if(AQ==="gpu-buffer"||AQ==="ml-tensor")throw Error("String tensor is not supported on GPU.");let MQ=[];for(let DQ=0;DQ<mQ;DQ++){let bQ=q.getValue(m0+DQ*F,"*"),j8=q.getValue(m0+(DQ+1)*F,"*"),tQ=DQ===mQ-1?void 0:j8-bQ;MQ.push(q.UTF8ToString(bQ,tQ))}u0.push([d0,iQ,MQ,"cpu"])}else if(AQ==="gpu-buffer"&&mQ>0){let MQ=q.webgpuGetBuffer;if(!MQ)throw Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let DQ=MQ(m0),bQ=FV(LQ,mQ);if(bQ===void 0||!x90(d0))throw Error(`Unsupported data type: ${d0}`);l0=!0;{q.webgpuRegisterBuffer(DQ,Q,m0);let j8=q.webgpuCreateDownloader(DQ,bQ,Q);u0.push([d0,iQ,{gpuBuffer:DQ,download:async()=>{let tQ=await j8();return new(bF(d0))(tQ)},dispose:()=>{q._OrtReleaseTensor(c0)!==0&&g6("Can't release tensor.")}},"gpu-buffer"])}}else if(AQ==="ml-tensor"&&mQ>0){let{webnnEnsureTensor:MQ,webnnIsGraphInputOutputTypeSupported:DQ}=q;if(!MQ||!DQ)throw Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(FV(LQ,mQ)===void 0||!b90(d0))throw Error(`Unsupported data type: ${d0}`);if(!DQ(Q,d0,!1))throw Error(`preferredLocation "ml-tensor" for ${d0} output is not supported by current WebNN Context.`);let bQ=await MQ(Q,m0,LQ,iQ,!1);l0=!0,u0.push([d0,iQ,{mlTensor:bQ,download:q.webnnCreateMLTensorDownloader(m0,d0),dispose:()=>{q.webnnReleaseTensorId(m0),q._OrtReleaseTensor(c0)}},"ml-tensor"])}else if(AQ==="ml-tensor-cpu-output"&&mQ>0){let MQ=q.webnnCreateMLTensorDownloader(m0,d0)(),DQ=u0.length;l0=!0,d.push((async()=>{let bQ=[DQ,await MQ];return q.webnnReleaseTensorId(m0),q._OrtReleaseTensor(c0),bQ})()),u0.push([d0,iQ,[],"cpu"])}else{let MQ=bF(d0),DQ=new MQ(mQ);new Uint8Array(DQ.buffer,DQ.byteOffset,DQ.byteLength).set(q.HEAPU8.subarray(m0,m0+DQ.byteLength)),u0.push([d0,iQ,DQ,"cpu"])}}finally{q.stackRestore(WQ),d0==="string"&&m0&&q._free(m0),l0||q._OrtReleaseTensor(c0)}}N&&!I&&(q._OrtClearBoundOutputs(N.handle)!==0&&g6("Can't clear bound outputs."),KH.set(Q,[V,O,P,N,I,!1]));for(let[n,c0]of await Promise.all(d))u0[n][2]=c0;return ZH("wasm ProcessOutputTensor"),u0}finally{q.webnnOnRunEnd?.(V),q.stackRestore(_),G.forEach((p0)=>{p0&&p0[3]==="gpu-buffer"&&q.webgpuUnregisterBuffer(p0[2].gpuBuffer)}),K.forEach((p0)=>{p0&&p0[3]==="gpu-buffer"&&q.webgpuUnregisterBuffer(p0[2].gpuBuffer)}),x.forEach((p0)=>q._OrtReleaseTensor(p0)),b.forEach((p0)=>q._OrtReleaseTensor(p0)),g.forEach((p0)=>q._free(p0)),T!==0&&q._OrtReleaseRunOptions(T),y.forEach((p0)=>q._free(p0))}},p90=(Q)=>{let J=W9(),G=KH.get(Q);if(!G)throw Error("invalid session id");let H=G[0],K=J._OrtEndProfiling(H);K===0&&g6("Can't get an profile file name."),J._OrtFree(K)},l90=(Q)=>{let J=[];for(let G of Q){let H=G[2];!Array.isArray(H)&&"buffer"in H&&J.push(H.buffer)}return J}}),zH,iY,VV,IF,RF,tC,c60,eC,s3,r3,WI0,_R0,fR0,mR0,uR0,pR0,lR0,dR0,cR0=q6(()=>{KB(),hR0(),zB(),k90(),zH=()=>!!l9.wasm.proxy&&typeof document<"u",VV=!1,IF=!1,RF=!1,eC=new Map,s3=(Q,J)=>{let G=eC.get(Q);G?G.push(J):eC.set(Q,[J])},r3=()=>{if(VV||!IF||RF||!iY)throw Error("worker not ready")},WI0=(Q)=>{switch(Q.data.type){case"init-wasm":VV=!1,Q.data.err?(RF=!0,c60[1](Q.data.err)):(IF=!0,c60[0]()),tC&&(URL.revokeObjectURL(tC),tC=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let J=eC.get(Q.data.type);Q.data.err?J.shift()[1](Q.data.err):J.shift()[0](Q.data.out);break}default:}},_R0=async()=>{if(!IF){if(VV)throw Error("multiple calls to 'initWasm()' detected.");if(RF)throw Error("previous call to 'initWasm()' failed.");if(VV=!0,zH())return new Promise((Q,J)=>{iY?.terminate(),RR0().then(([G,H])=>{try{iY=H,iY.onerror=(z)=>J(z),iY.onmessage=WI0,c60=[Q,J];let K={type:"init-wasm",in:l9};!K.in.wasm.wasmPaths&&(G||W90)&&(K.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.asyncify.wasm","file:///C:/mcp-tools-for-obsidian.ts").href}),iY.postMessage(K),tC=G}catch(K){J(K)}},J)});try{await y90(l9.wasm),await h90(l9),IF=!0}catch(Q){throw RF=!0,Q}finally{VV=!1}}},fR0=async(Q)=>{if(zH())return r3(),new Promise((J,G)=>{s3("init-ep",[J,G]);let H={type:"init-ep",in:{epName:Q,env:l9}};iY.postMessage(H)});await _90(l9,Q)},mR0=async(Q)=>zH()?(r3(),new Promise((J,G)=>{s3("copy-from",[J,G]);let H={type:"copy-from",in:{buffer:Q}};iY.postMessage(H,[Q.buffer])})):MR(Q),uR0=async(Q,J)=>{if(zH()){if(J?.preferredOutputLocation)throw Error('session option "preferredOutputLocation" is not supported for proxy.');return r3(),new Promise((G,H)=>{s3("create",[G,H]);let K={type:"create",in:{model:Q,options:{...J}}},z=[];Q instanceof Uint8Array&&z.push(Q.buffer),iY.postMessage(K,z)})}else return f90(Q,J)},pR0=async(Q)=>{if(zH())return r3(),new Promise((J,G)=>{s3("release",[J,G]);let H={type:"release",in:Q};iY.postMessage(H)});m90(Q)},lR0=async(Q,J,G,H,K,z)=>{if(zH()){if(G.some((q)=>q[3]!=="cpu"))throw Error("input tensor on GPU is not supported for proxy.");if(K.some((q)=>q))throw Error("pre-allocated output tensor is not supported for proxy.");return r3(),new Promise((q,F)=>{s3("run",[q,F]);let D=G,V={type:"run",in:{sessionId:Q,inputIndices:J,inputs:D,outputIndices:H,options:z}};iY.postMessage(V,l90(D))})}else return u90(Q,J,G,H,K,z)},dR0=async(Q)=>{if(zH())return r3(),new Promise((J,G)=>{s3("end-profiling",[J,G]);let H={type:"end-profiling",in:Q};iY.postMessage(H)});p90(Q)}}),i60,HI0,iR0,sVQ=q6(()=>{KB(),cR0(),EV(),T90(),TR0(),i60=(Q,J)=>{switch(Q.location){case"cpu":return[Q.type,Q.dims,Q.data,"cpu"];case"gpu-buffer":return[Q.type,Q.dims,{gpuBuffer:Q.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Q.type,Q.dims,{mlTensor:Q.mlTensor},"ml-tensor"];default:throw Error(`invalid data location: ${Q.location} for ${J()}`)}},HI0=(Q)=>{switch(Q[3]){case"cpu":return new kG(Q[0],Q[2],Q[1]);case"gpu-buffer":{let J=Q[0];if(!x90(J))throw Error(`not supported data type: ${J} for deserializing GPU tensor`);let{gpuBuffer:G,download:H,dispose:K}=Q[2];return kG.fromGpuBuffer(G,{dataType:J,dims:Q[1],download:H,dispose:K})}case"ml-tensor":{let J=Q[0];if(!b90(J))throw Error(`not supported data type: ${J} for deserializing MLTensor tensor`);let{mlTensor:G,download:H,dispose:K}=Q[2];return kG.fromMLTensor(G,{dataType:J,dims:Q[1],download:H,dispose:K})}default:throw Error(`invalid data location: ${Q[3]}`)}},iR0=class{async fetchModelAndCopyToWasmMemory(Q){return mR0(await g90(Q))}async loadModel(Q,J){BB();let G;typeof Q=="string"?G=await this.fetchModelAndCopyToWasmMemory(Q):G=Q,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await uR0(G,J),AB()}async dispose(){return pR0(this.sessionId)}async run(Q,J,G){BB();let H=[],K=[];Object.entries(Q).forEach((P)=>{let N=P[0],I=P[1],R=this.inputNames.indexOf(N);if(R===-1)throw Error(`invalid input '${N}'`);H.push(I),K.push(R)});let z=[],q=[];Object.entries(J).forEach((P)=>{let N=P[0],I=P[1],R=this.outputNames.indexOf(N);if(R===-1)throw Error(`invalid output '${N}'`);z.push(I),q.push(R)});let F=H.map((P,N)=>i60(P,()=>`input "${this.inputNames[K[N]]}"`)),D=z.map((P,N)=>P?i60(P,()=>`output "${this.outputNames[q[N]]}"`):null),V=await lR0(this.sessionId,K,F,q,D,G),O={};for(let P=0;P<V.length;P++)O[this.outputNames[q[P]]]=z[P]??HI0(V[P]);return AB(),O}startProfiling(){}endProfiling(){dR0(this.sessionId)}}}),oR0={};pF(oR0,{OnnxruntimeWebAssemblyBackend:()=>K90,initializeFlags:()=>A90,wasmBackend:()=>nR0});var A90,K90,nR0,rVQ=q6(()=>{KB(),cR0(),sVQ(),A90=()=>{(typeof l9.wasm.initTimeout!="number"||l9.wasm.initTimeout<0)&&(l9.wasm.initTimeout=0);let Q=l9.wasm.simd;if(typeof Q!="boolean"&&Q!==void 0&&Q!=="fixed"&&Q!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Q}". Reset it to \`false\` and ignore SIMD feature checking.`),l9.wasm.simd=!1),typeof l9.wasm.proxy!="boolean"&&(l9.wasm.proxy=!1),typeof l9.wasm.trace!="boolean"&&(l9.wasm.trace=!1),typeof l9.wasm.numThreads!="number"||!Number.isInteger(l9.wasm.numThreads)||l9.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)l9.wasm.numThreads=1;else{let J=typeof navigator>"u"?EVQ("node:os").cpus().length:navigator.hardwareConcurrency;l9.wasm.numThreads=Math.min(4,Math.ceil((J||1)/2))}},K90=class{async init(Q){A90(),await _R0(),await fR0(Q)}async createInferenceSessionHandler(Q,J){let G=new iR0;return await G.loadModel(Q,J),G}},nR0=new K90});KB();KB();KB();var tVQ="1.26.0-dev.20260416-b7804b056c",eVQ=OR0;{let Q=(rVQ(),$R(oR0)).wasmBackend;GB("webgpu",Q,5),GB("webnn",Q,5),GB("cpu",Q,10),GB("wasm",Q,10)}Object.defineProperty(l9.versions,"web",{value:tVQ,enumerable:!0});async function aR0(Q){let J=Q.split("/").pop(),G;try{if(G=await I90(),G){let K=await G.match(Q);if(K)return K}}catch(K){g8.warn(`Failed to load ${J} from cache:`,K)}let H=await A6.fetch(Q);if(!H.ok)throw Error(`Failed to fetch ${J}: ${H.status} ${H.statusText}`);if(G)try{await G.put(Q,H.clone())}catch(K){g8.warn(`Failed to cache ${J}:`,K)}return H}async function QqQ(Q){let J=await aR0(Q);if(!J||typeof J==="string")return null;try{return await J.arrayBuffer()}catch(G){return g8.warn("Failed to read WASM binary:",G),null}}async function XqQ(Q){if(Y6.IS_SERVICE_WORKER_ENV||Y6.IS_CHROME_AVAILABLE)return Q;let J=await aR0(Q);if(!J||typeof J==="string")return null;try{let G=await J.text();G=G.replaceAll("globalThis.process?.versions?.node","false");let H=new Blob([G],{type:"text/javascript"});return URL.createObjectURL(H)}catch(G){return g8.warn("Failed to read WASM factory:",G),null}}var JqQ=Object.freeze({auto:null,gpu:null,cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:{name:"webnn",deviceType:"cpu"},"webnn-npu":{name:"webnn",deviceType:"npu"},"webnn-gpu":{name:"webnn",deviceType:"gpu"},"webnn-cpu":{name:"webnn",deviceType:"cpu"}});function sR0(Q){if(Q<=yG.DEBUG)return 0;else if(Q<=yG.INFO)return 2;else if(Q<=yG.WARNING)return 3;else if(Q<=yG.ERROR)return 3;else return 4}var YqQ={0:"verbose",1:"info",2:"warning",3:"error",4:"fatal"},nY=[],z90,NV,BI0=Symbol.for("onnxruntime");if(BI0 in globalThis)NV=globalThis[BI0];else if(Y6.IS_NODE_ENV){switch(NV=CVQ,process.platform){case"win32":nY.push("dml");break;case"linux":if(process.arch==="x64")nY.push("cuda");break;case"darwin":nY.push("coreml");break}nY.push("webgpu"),nY.push("cpu"),z90=["cpu"]}else{if(NV=JR0,Y6.IS_WEBNN_AVAILABLE)nY.push("webnn-npu","webnn-gpu","webnn-cpu","webnn");if(Y6.IS_WEBGPU_AVAILABLE)nY.push("webgpu");nY.push("wasm"),z90=["wasm"]}var GqQ=NV.InferenceSession;function WqQ(Q=null){if(!Q)return z90;switch(Q){case"auto":return nY;case"gpu":return nY.filter((J)=>["webgpu","cuda","dml","webnn-gpu"].includes(J))}if(nY.includes(Q))return[JqQ[Q]??Q];throw Error(`Unsupported device: "${Q}". Should be one of: ${nY.join(", ")}.`)}var AI0=Promise.resolve(),qV=null;async function HqQ(){if(qV)return qV;if(!(A6.useWasmCache&&typeof g7?.wasm?.wasmPaths==="object"&&g7?.wasm?.wasmPaths?.wasm&&g7?.wasm?.wasmPaths?.mjs)){if(Y6.IS_DENO_WEB_RUNTIME)throw Error("env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.");return qV=Promise.resolve(),qV}return qV=(async()=>{let J=g7.wasm.wasmPaths,G=!1;if(await Promise.all([J.wasm&&!TC0(J.wasm)?(async()=>{try{let H=await QqQ(kC0(J.wasm));if(H)g7.wasm.wasmBinary=H,G=!0}catch(H){g8.warn("Failed to pre-load WASM binary:",H)}})():Promise.resolve(),J.mjs&&!TC0(J.mjs)?(async()=>{try{let H=await XqQ(kC0(J.mjs));if(H)g7.wasm.wasmPaths.mjs=H}catch(H){g8.warn("Failed to pre-load WASM factory:",H)}})():Promise.resolve()]),!G)g7.wasm.wasmPaths.mjs=J.mjs})(),qV}async function rR0(Q,J,G){await HqQ();let H=sR0(A6.logLevel??yG.WARNING),K=()=>GqQ.create(Q,{logSeverityLevel:H,...J}),z=await(Y6.IS_WEB_ENV?AI0=AI0.then(K):K());return z.config=G,z}var KI0=Promise.resolve();async function tR0(Q,J){let G=()=>Q.run(J);return Y6.IS_WEB_ENV?KI0=KI0.then(G):G()}function eR0(Q){return Q instanceof NV.Tensor}var g7=NV?.env;function d90(){return g7?.wasm?.proxy}if(g7){let Q=function(J){let G=sR0(J);g7.logLevel=YqQ[G]};if(g7.wasm){if(!(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope)&&g7.versions?.web&&!g7.wasm.wasmPaths){let J=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${g7.versions.web}/dist/`;g7.wasm.wasmPaths=Y6.IS_SAFARI?{mjs:`${J}ort-wasm-simd-threaded.mjs`,wasm:`${J}ort-wasm-simd-threaded.wasm`}:{mjs:`${J}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${J}ort-wasm-simd-threaded.asyncify.wasm`}}g7.wasm.proxy=!1}if(g7.webgpu)g7.webgpu.powerPreference="high-performance";Q(A6.logLevel??yG.WARNING),A6.backends.onnx={...g7,setLogLevel:Q}}var VH=async(Q,J,G)=>{let H=await rR0(new Uint8Array(Q),J);return async(K)=>{let z=d90(),q=Object.fromEntries(Object.entries(K).map(([D,V])=>[D,(z?V.clone():V).ort_tensor])),F=await tR0(H,q);if(Array.isArray(G))return G.map((D)=>new PQ(F[D]));else return new PQ(F[G])}},jV=class{static session_options={};static get nearest_interpolate_4d(){if(!this._nearest_interpolate_4d)this._nearest_interpolate_4d=VH([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,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,21],this.session_options,"y");return this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){if(!this._bilinear_interpolate_4d)this._bilinear_interpolate_4d=VH([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");return this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){if(!this._bicubic_interpolate_4d)this._bicubic_interpolate_4d=VH([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");return this._bicubic_interpolate_4d}static get matmul(){if(!this._matmul)this._matmul=VH([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");return this._matmul}static get stft(){if(!this._stft)this._stft=VH([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");return this._stft}static get rfft(){if(!this._rfft)this._rfft=VH([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");return this._rfft}static get top_k(){if(!this._top_k)this._top_k=VH([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"]);return this._top_k}static get slice(){if(!this._slice)this._slice=VH([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,"y");return this._slice}},BqQ=Object.freeze({auto:"auto",gpu:"gpu",cpu:"cpu",wasm:"wasm",webgpu:"webgpu",cuda:"cuda",dml:"dml",coreml:"coreml",webnn:"webnn","webnn-npu":"webnn-npu","webnn-gpu":"webnn-gpu","webnn-cpu":"webnn-cpu"}),o60=Y6.IS_NODE_ENV?"cpu":"wasm";function Qw0(Q,J,{warn:G}={}){if(!Q)return o60;if(typeof Q==="string")return Q;if(Q.hasOwnProperty(J))return Q[J];if(G)G(`device not specified for "${J}". Using the default device (${o60}).`);return o60}var AqQ=function(){let Q;return async function(){if(Q===void 0)if(!Y6.IS_WEBGPU_AVAILABLE)Q=!1;else try{Q=(await navigator.gpu.requestAdapter()).features.has("shader-f16")}catch(J){Q=!1}return Q}}(),I7=Object.freeze({auto:"auto",fp32:"fp32",fp16:"fp16",q8:"q8",int8:"int8",uint8:"uint8",q4:"q4",bnb4:"bnb4",q4f16:"q4f16",q2:"q2",q2f16:"q2f16",q1:"q1",q1f16:"q1f16"}),zI0=I7.fp32,VI0=Object.freeze({[BqQ.wasm]:I7.q8}),LR=Object.freeze({[I7.fp32]:"",[I7.fp16]:"_fp16",[I7.int8]:"_int8",[I7.uint8]:"_uint8",[I7.q8]:"_quantized",[I7.q4]:"_q4",[I7.q2]:"_q2",[I7.q1]:"_q1",[I7.q4f16]:"_q4f16",[I7.q2f16]:"_q2f16",[I7.q1f16]:"_q1f16",[I7.bnb4]:"_bnb4"});function Xw0(Q,J,G,{configDtype:H=null,warn:K}={}){let z,q=!1;if(Q&&typeof Q!=="string")if(Q.hasOwnProperty(J))z=Q[J];else z=null,q=!0;else z=Q;let F;if(z===I7.auto){if(H){let D=typeof H==="string"?H:H?.[J];if(D&&D!==I7.auto&&I7.hasOwnProperty(D))return D}F=VI0[G]??zI0}else if(z&&I7.hasOwnProperty(z))F=z;else F=VI0[G]??zI0;if(q&&K)K(`dtype not specified for "${J}". Using the default dtype (${F}) for this device (${G}).`);return F}var gF=Object.freeze({float32:Float32Array,float16:typeof Float16Array<"u"?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),PQ=class Q{get dims(){return this.ort_tensor.dims}set dims(J){this.ort_tensor.dims=J}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}ort_tensor;constructor(...J){if(eR0(J[0]))this.ort_tensor=J[0];else this.ort_tensor=new j60(J[0],J[1],J[2]);return new Proxy(this,{get:(G,H)=>{if(typeof H==="string"){let K=Number(H);if(Number.isInteger(K))return G._getitem(K)}return G[H]},set:(G,H,K)=>{return G[H]=K}})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[J,...G]=this.dims;if(G.length>0){let H=G.reduce((K,z)=>K*z);for(let K=0;K<J;++K)yield this._subarray(K,H,G)}else yield*this.data}_getitem(J){let[G,...H]=this.dims;if(J=kW(J,G),H.length>0){let K=H.reduce((z,q)=>z*q);return this._subarray(J,K,H)}else return new Q(this.type,[this.data[J]],H)}indexOf(J){let G=this.data;for(let H=0;H<G.length;++H)if(G[H]==J)return H;return-1}_subarray(J,G,H){let K=J*G,z=(J+1)*G,q="subarray"in this.data?this.data.subarray(K,z):this.data.slice(K,z);return new Q(this.type,q,H)}item(){let J=this.data;if(J.length!==1)throw Error(`a Tensor with ${J.length} elements cannot be converted to Scalar`);return J[0]}tolist(){return KqQ(this.data,this.dims)}sigmoid(){return this.clone().sigmoid_()}sigmoid_(){let J=this.data;for(let G=0;G<J.length;++G)J[G]=1/(1+Math.exp(-J[G]));return this}map(J){return this.clone().map_(J)}map_(J){let G=this.data;for(let H=0;H<G.length;++H)G[H]=J(G[H],H,G);return this}mul(J){return this.clone().mul_(J)}mul_(J){let G=this.data;for(let H=0;H<G.length;++H)G[H]*=J;return this}div(J){return this.clone().div_(J)}div_(J){let G=this.data;for(let H=0;H<G.length;++H)G[H]/=J;return this}add(J){return this.clone().add_(J)}add_(J){let G=this.data;for(let H=0;H<G.length;++H)G[H]+=J;return this}sub(J){return this.clone().sub_(J)}sub_(J){let G=this.data;for(let H=0;H<G.length;++H)G[H]-=J;return this}clone(){return new Q(this.type,this.data.slice(),this.dims.slice())}slice(...J){let G=[],H=[];for(let O=0;O<this.dims.length;++O){let P=J[O];if(P===null||P===void 0)H.push([0,this.dims[O]]),G.push(this.dims[O]);else if(typeof P==="number")P=kW(P,this.dims[O],O),H.push([P,P+1]);else if(Array.isArray(P)&&P.length===2){let[N,I]=P;if(N=N===null?0:kW(N,this.dims[O],O,!1),I=I===null?this.dims[O]:kW(I,this.dims[O],O,!1),N>I)throw Error(`Invalid slice: ${P}`);let R=[Math.max(N,0),Math.min(I,this.dims[O])];H.push(R),G.push(R[1]-R[0])}else throw Error(`Invalid slice: ${P}`)}let K=H.map(([O,P])=>P-O),z=K.reduce((O,P)=>O*P),q=this.data,F=new q.constructor(z),D=this.stride(),V=!0;for(let O=1;O<K.length;++O)if(H[O][0]!==0||H[O][1]!==this.dims[O]){V=!1;break}if(V){let O=H[0][0]*D[0],P=H[0][1]*D[0];if(ArrayBuffer.isView(q))F.set(q.subarray(O,P));else if(Array.isArray(q)){let N=q.slice(O,P);for(let I=0;I<N.length;++I)F[I]=N[I]}else throw Error("Unsupported data type for slicing")}else for(let O=0;O<z;++O){let P=0;for(let N=K.length-1,I=O;N>=0;--N){let R=K[N];P+=(I%R+H[N][0])*D[N],I=Math.floor(I/R)}F[O]=q[P]}return new Q(this.type,F,G)}permute(...J){return zqQ(this,J)}transpose(...J){return this.permute(...J)}sum(J=null,G=!1){return this.norm(1,J,G)}norm(J="fro",G=null,H=!1){if(J==="fro")J=2;else if(typeof J==="string")throw Error(`Unsupported norm: ${J}`);let K=this.data,z=K instanceof BigInt64Array||K instanceof BigUint64Array;if(z&&J!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let q,F;if(z)q=(P,N)=>P+N,F=0n;else q=(P,N)=>P+N**J,F=0;if(G===null){let P=K.reduce(q,F);if(J!==1)P=P**(1/J);return new Q(this.type,[P],[])}let[D,V,O]=yF(q,this,G,H);if(J!==1)for(let P=0;P<V.length;++P)V[P]=V[P]**(1/J);return new Q(D,V,O)}normalize_(J=2,G=1){G=kW(G,this.dims.length);let H=this.norm(J,G,!0),K=this.data,z=H.data;for(let q=0;q<K.length;++q){let F=0;for(let D=this.dims.length-1,V=q,O=1;D>=0;--D){let P=this.dims[D];if(D!==G){let N=V%P;F+=N*O,O*=this.dims[D]}V=Math.floor(V/P)}K[q]/=z[F]}return this}normalize(J=2,G=1){return this.clone().normalize_(J,G)}stride(){return n60(this.dims)}squeeze(J=null){return new Q(this.type,this.data,qI0(this.dims,J))}squeeze_(J=null){return this.dims=qI0(this.dims,J),this}unsqueeze(J){return new Q(this.type,this.data,UI0(this.dims,J))}unsqueeze_(J){return this.dims=UI0(this.dims,J),this}flatten_(J=0,G=-1){G=(G+this.dims.length)%this.dims.length;let H=this.dims.slice(0,J),K=this.dims.slice(J,G+1),z=this.dims.slice(G+1);return this.dims=[...H,K.reduce((q,F)=>q*F,1),...z],this}flatten(J=0,G=-1){return this.clone().flatten_(J,G)}view(...J){let G=-1;for(let K=0;K<J.length;++K)if(J[K]===-1){if(G!==-1)throw Error("Only one dimension can be inferred");G=K}let H=this.data;if(G!==-1){let K=J.reduce((z,q,F)=>{return F!==G?z*q:z},1);J[G]=H.length/K}return new Q(this.type,H,J)}neg_(){let J=this.data;for(let G=0;G<J.length;++G)J[G]=-J[G];return this}neg(){return this.clone().neg_()}gt(J){let G=new Uint8Array(this.data.length),H=this.data;for(let K=0;K<H.length;++K)G[K]=H[K]>J?1:0;return new Q("bool",G,this.dims)}lt(J){let G=new Uint8Array(this.data.length),H=this.data;for(let K=0;K<H.length;++K)G[K]=H[K]<J?1:0;return new Q("bool",G,this.dims)}clamp_(J,G){let H=this.data;for(let K=0;K<H.length;++K)H[K]=Math.min(Math.max(H[K],J),G);return this}clamp(J,G){return this.clone().clamp_(J,G)}round_(){let J=this.data;for(let G=0;G<J.length;++G)J[G]=Math.round(J[G]);return this}round(){return this.clone().round_()}mean(J=null,G=!1){return c90(this,J,G)}min(J=null,G=!1){if(J===null){let q=G90(this.data)[0];return new Q(this.type,[q],[])}let[H,K,z]=yF((q,F)=>Math.min(q,F),this,J,G,1/0);return new Q(H,K,z)}max(J=null,G=!1){if(J===null){let q=D7(this.data)[0];return new Q(this.type,[q],[])}let[H,K,z]=yF((q,F)=>Math.max(q,F),this,J,G,-1/0);return new Q(H,K,z)}argmin(J=null,G=!1){if(J!==null)throw Error("`dim !== null` not yet implemented.");let H=G90(this.data)[1];return new Q("int64",[BigInt(H)],[])}argmax(J=null,G=!1){if(J!==null)throw Error("`dim !== null` not yet implemented.");let H=D7(this.data)[1];return new Q("int64",[BigInt(H)],[])}repeat(...J){if(J.length<this.dims.length)throw Error(`Number of dimensions of repeat dims (${J.length}) cannot be smaller than number of dimensions of tensor (${this.dims.length})`);if(J.every((O)=>O===1)){if(J.length===this.dims.length)return this.clone();let O=J.length-this.dims.length,P=Array(O).fill(1).concat(this.dims);return new Q(this.type,this.data.slice(),P)}let G=J.length-this.dims.length,H=Array(G).fill(1).concat(this.dims),K=H.map((O,P)=>O*J[P]),z=K.reduce((O,P)=>O*P,1),q=this.data,F=new q.constructor(z),D=n60(H),V=n60(K);for(let O=0;O<z;++O){let P=O,N=0;for(let I=0;I<K.length;++I){let R=Math.floor(P/V[I]);P=P%V[I];let w=R%H[I];N+=w*D[I]}F[O]=q[N]}return new Q(this.type,F,K)}tile(...J){if(J.length<this.dims.length){let G=this.dims.length-J.length;J=Array(G).fill(1).concat(J)}return this.repeat(...J)}to(J){if(this.type===J)return this;if(!gF.hasOwnProperty(J))throw Error(`Unsupported type: ${J}`);let G,H=["int64","uint64"].includes(this.type),K=["int64","uint64"].includes(J);if(H&&!K)G=Number;else if(!H&&K)if(["float16","float32","float64"].includes(this.type))G=(z)=>BigInt(Math.floor(z));else G=BigInt;else if(this.type==="float16"&&J=="float32"&&this.data instanceof Uint16Array)return new Q(J,jVQ(this.data),this.dims);return new Q(J,gF[J].from(this.data,G),this.dims)}};function KqQ(Q,J){let G=Q.length,H=J.reduce((z,q)=>z*q);if(G!==H)throw Error(`cannot reshape array of size ${G} into shape (${J})`);let K=Q;for(let z=J.length-1;z>=0;z--)K=K.reduce((q,F)=>{let D=q[q.length-1];if(D.length<J[z])D.push(F);else q.push([F]);return q},[[]]);return K[0]}function zqQ(Q,J){let[G,H]=FVQ(Q.data,Q.dims,J);return new PQ(Q.type,G,H)}function Jw0(Q,[J,G],H="bilinear",K=!1){let z=Q.dims.at(-3)??1,q=Q.dims.at(-2),F=Q.dims.at(-1),D=ZVQ(Q.data,[z,q,F],[J,G],H,K);return new PQ(Q.type,D,[z,J,G])}async function bG(Q,{size:J=null,mode:G="bilinear"}={}){if(Q.dims.length!==4)throw Error("`interpolate_4d` currently only supports 4D input.");if(!J)throw Error("`interpolate_4d` requires a `size` argument.");let H;if(J.length===2)H=[...Q.dims.slice(0,2),...J];else if(J.length===3)H=[Q.dims[0],...J];else if(J.length===4)H=J;else throw Error("`size` must be of length 2, 3, or 4.");let K;if(G==="nearest")K=await jV.nearest_interpolate_4d;else if(G==="bilinear")K=await jV.bilinear_interpolate_4d;else if(G==="bicubic")K=await jV.bicubic_interpolate_4d;else throw Error(`Unsupported mode: ${G}`);let z=new PQ("int64",new BigInt64Array(H.map(BigInt)),[H.length]);return await K({x:Q,s:z})}async function VqQ(Q,J){return await(await jV.matmul)({a:Q,b:J})}async function SV(Q,J){let G=await jV.top_k;if(J==null)J=Q.dims.at(-1);else J=Math.min(J,Q.dims.at(-1));return await G({x:Q,k:new PQ("int64",[BigInt(J)],[1])})}var AI=(Q)=>new PQ("int64",Q,[Q.length]);async function Yw0(Q,J,G,H,K){return await(await jV.slice)({x:Q,s:AI(J),e:AI(G),a:AI(H),t:AI(K??Array(H.length).fill(1))})}function qqQ(Q,J){let G=Q.data,H=J.data,K=[Q.dims[0],Q.dims[2]],z=new G.constructor(K[0]*K[1]),[q,F,D]=Q.dims,V=0;for(let O=0;O<q;++O){let P=O*D*F;for(let N=0;N<D;++N){let I=0,R=0,w=O*F,E=P+N;for(let y=0;y<F;++y){let x=Number(H[w+y]);R+=x,I+=G[E+y*D]*x}let T=I/R;z[V++]=T}}return new PQ(Q.type,z,K)}function qI0(Q,J){if(Q=Q.slice(),J===null)Q=Q.filter((G)=>G!==1);else if(typeof J==="number"){if(Q[J]===1)Q.splice(J,1)}else if(Array.isArray(J))Q=Q.filter((G,H)=>{return G!==1||!J.includes(H)});return Q}function UI0(Q,J){return J=kW(J,Q.length+1),Q=Q.slice(),Q.splice(J,0,1),Q}function kW(Q,J,G=null,H=!0){if(Q<-J||Q>=J)if(H)throw Error(`IndexError: index ${Q} is out of bounds for dimension${G===null?"":" "+G} with size ${J}`);else return Q<-J?0:J;if(Q<0)Q=(Q%J+J)%J;return Q}function T9(Q,J=0){J=kW(J,Q[0].dims.length);let G=Q[0].dims.slice();G[J]=Q.reduce((q,F)=>q+F.dims[J],0);let H=G.reduce((q,F)=>q*F,1),K=new Q[0].data.constructor(H),z=Q[0].type;if(J===0){let q=0;for(let F of Q){let D=F.data;K.set(D,q),q+=D.length}}else{let q=0;for(let F=0;F<Q.length;++F){let{data:D,dims:V}=Q[F];for(let O=0;O<D.length;++O){let P=0;for(let N=V.length-1,I=O,R=1;N>=0;--N){let w=V[N],E=I%w;if(N===J)E+=q;P+=E*R,R*=G[N],I=Math.floor(I/w)}K[P]=D[O]}q+=V[J]}}return new PQ(z,K,G)}function g5(Q,J=0){return T9(Q.map((G)=>G.unsqueeze(J)),J)}function yF(Q,J,G,H=!1,K=null){let{data:z,dims:q}=J;G=kW(G,q.length);let F=q.slice();F[G]=1;let D=new z.constructor(z.length/q[G]);if(K!==null)D.fill(K);for(let V=0;V<z.length;++V){let O=0;for(let P=q.length-1,N=V,I=1;P>=0;--P){let R=q[P];if(P!==G){let w=N%R;O+=w*I,I*=F[P]}N=Math.floor(N/R)}D[O]=Q(D[O],z[V],V,O)}if(!H)F.splice(G,1);return[J.type,D,F]}function UqQ(Q,J=null,G=1,H=!1){let{data:K,dims:z}=Q;if(J===null){let I=K.reduce((T,y)=>T+y,0)/K.length,R=Math.sqrt(K.reduce((T,y)=>T+(y-I)**2,0)/(K.length-G)),w=new PQ(Q.type,[I],[]);return[new PQ(Q.type,[R],[]),w]}J=kW(J,z.length);let q=c90(Q,J,H),F=q.data,[D,V,O]=yF((N,I,R,w)=>N+(I-F[w])**2,Q,J,H);for(let N=0;N<V.length;++N)V[N]=Math.sqrt(V[N]/(z[J]-G));return[new PQ(D,V,O),q]}function c90(Q,J=null,G=!1){let{dims:H,data:K}=Q;if(J===null){let D=K.reduce((V,O)=>V+O,0);return new PQ(Q.type,[D/K.length],[])}J=kW(J,H.length);let[z,q,F]=yF((D,V)=>D+V,Q,J,G);if(H[J]!==1)for(let D=0;D<q.length;++D)q[D]/=H[J];return new PQ(z,q,F)}function n60(Q){let J=Array(Q.length);for(let G=Q.length-1,H=1;G>=0;--G)J[G]=H,H*=Q[G];return J}function i90(Q,J,G,H){let K=Q.reduce((z,q)=>z*q,1);return new PQ(G,new H(K).fill(J),Q)}function sX(Q,J){let G,H;if(typeof J==="number")G="float32",H=Float32Array;else if(typeof J==="bigint")G="int64",H=BigInt64Array;else if(typeof J==="boolean")G="bool",H=Uint8Array;else throw Error(`Unsupported data type: ${typeof J}`);return i90(Q,J,G,H)}function V90(Q,J){return sX(Q.dims,J)}function oJ(Q){return i90(Q,1n,"int64",BigInt64Array)}function Gw0(Q){return oJ(Q.dims)}function Ww0(Q){return i90(Q,0n,"int64",BigInt64Array)}function Hw0(Q){return Ww0(Q.dims)}function $qQ(Q){let J=Q.reduce((G,H)=>G*H,1);return new PQ("float32",Float32Array.from({length:J},()=>C90.gauss()),Q)}function ZqQ(Q,J){if(Q.dims.length!==2)throw Error("The tensor must have 2 dimensions");if(Q.dims.at(-1)%8!==0)throw Error("The last dimension of the tensor must be a multiple of 8");if(!["binary","ubinary"].includes(J))throw Error("The precision must be either 'binary' or 'ubinary'");let G=J==="binary",H=G?"int8":"uint8",K=G?Int8Array:Uint8Array,z=Q.data,q=new K(z.length/8);for(let F=0;F<z.length;++F){let D=z[F]>0?1:0,V=Math.floor(F/8),O=F%8;if(q[V]|=D<<7-O,G&&O===0)q[V]-=128}return new PQ(H,q,[Q.dims[0],Q.dims[1]/8])}async function Bw0(Q){if(!Q)throw Error("modelId is required for get_tokenizer_files");if((await uF(Q,"tokenizer_config.json",{})).exists)return["tokenizer.json","tokenizer_config.json"];return[]}async function Aw0(Q,J){let G=await Bw0(Q);return await Promise.all(G.map((H)=>bW(Q,H,!0,J)))}function o90(Q){let J=Q.dims;switch(J.length){case 1:return Q.tolist();case 2:if(J[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return Q.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${J.length}.`)}}var FqQ=["bos_token","eos_token","unk_token","sep_token","pad_token","cls_token","mask_token"];function DqQ(Q,J,G,H){for(let K of Object.keys(Q)){let z=J-Q[K].length,q=G(K),F=Array(z).fill(q);Q[K]=H==="right"?yW(Q[K],F):yW(F,Q[K])}}function MqQ(Q,J){for(let G of Object.keys(Q))Q[G].length=J}function t3(Q,...J){for(let G of J){if(!Object.hasOwn(Q,G))continue;let H=Q[G];if(!H)continue;if(typeof H==="object")if(H.__type==="AddedToken")return H.content;else throw Error(`Unknown token: ${H}`);else return H}return null}function LqQ(Q){let J=[];for(let G of Q.get_added_tokens_decoder().values())if(G.special)J.push(G);return J}var x8=class extends nJ{return_token_type_ids=!1;padding_side="right";constructor(Q,J){super();if(this._tokenizerJSON=Q,this._tokenizerConfig=J,this._tokenizer=new YzQ(Q,J),this.config=J,this.padding_side=J.padding_side??this.padding_side,this.mask_token=t3(J,"mask_token"),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=t3(J,"pad_token","eos_token"),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=t3(J,"sep_token"),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=t3(J,"unk_token"),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=t3(J,"bos_token"),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=t3(J,"eos_token"),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=J.chat_template??null,Array.isArray(this.chat_template)){let H=Object.create(null);for(let{name:K,template:z}of this.chat_template){if(typeof K!=="string"||typeof z!=="string")throw Error('Chat template must be a list of objects with "name" and "template" properties');H[K]=z}this.chat_template=H}this._compiled_template_cache=new Map;let G=LqQ(this._tokenizer);this.all_special_ids=G.map((H)=>H.id),this.all_special_tokens=G.map((H)=>H.content)}static async from_pretrained(Q,{progress_callback:J=null,config:G=null,cache_dir:H=null,local_files_only:K=!1,revision:z="main"}={}){let q=await Aw0(Q,{progress_callback:J,config:G,cache_dir:H,local_files_only:K,revision:z});return new this(...q)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(Q){if(typeof Q==="string")return this._tokenizer.token_to_id(Q);else return Q.map((J)=>this._tokenizer.token_to_id(J))}_call(Q,J={}){let{text_pair:G=null,add_special_tokens:H=!0,padding:K=!1,return_token_type_ids:z=null}=J,{truncation:q=null,max_length:F=null}=J,D=J.return_tensor??!0,V=Array.isArray(Q),O;if(V){if(Q.length===0)throw Error("text array must be non-empty");if(G!==null){if(!Array.isArray(G))throw Error("text_pair must also be an array");else if(Q.length!==G.length)throw Error("text and text_pair must have the same length");O=Q.map((N,I)=>this._encode_plus(N,{text_pair:G[I],add_special_tokens:H,return_token_type_ids:z}))}else O=Q.map((N)=>this._encode_plus(N,{add_special_tokens:H,return_token_type_ids:z}))}else{if(Q===null||Q===void 0)throw Error("text may not be null or undefined");if(Array.isArray(G))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");O=[this._encode_plus(Q,{text_pair:G,add_special_tokens:H,return_token_type_ids:z})]}if(F===null)F=this.model_max_length;else if(q===null){if(K===!0)g8.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),F=this.model_max_length;else if(K===!1)g8.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."),q=!0}if(K===!0)F=Math.min(D7(O.map((N)=>N.input_ids.length))[0],F??1/0);if(F=Math.min(F,this.model_max_length??1/0),K||q){for(let N=0;N<O.length;++N)if(O[N].input_ids.length===F)continue;else if(O[N].input_ids.length>F){if(q)MqQ(O[N],F)}else if(K)DqQ(O[N],F,(I)=>I==="input_ids"?this.pad_token_id:0,this.padding_side)}let P={};if(D){if(!(K&&q)){if(O.some((I)=>{for(let R of Object.keys(I))if(I[R].length!==O[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.")}let N=[O.length,O[0].input_ids.length];for(let I of Object.keys(O[0]))P[I]=new PQ("int64",BigInt64Array.from(O.flatMap((R)=>R[I]).map(BigInt)),N)}else{for(let N of Object.keys(O[0]))P[N]=O.map((I)=>I[N]);if(!V)for(let N of Object.keys(P))P[N]=P[N][0]}return P}_encode_text(Q){if(Q===null)return null;return this._tokenizer.encode(Q).tokens}_encode_plus(Q,{text_pair:J=null,add_special_tokens:G=!0,return_token_type_ids:H=null}={}){let{ids:K,attention_mask:z,token_type_ids:q}=this._tokenizer.encode(Q,{text_pair:J,add_special_tokens:G,return_token_type_ids:H??this.return_token_type_ids});return{input_ids:K,attention_mask:z,...q?{token_type_ids:q}:{}}}tokenize(Q,{pair:J=null,add_special_tokens:G=!1}={}){return this._tokenizer.tokenize(Q,{text_pair:J,add_special_tokens:G})}encode(Q,{text_pair:J=null,add_special_tokens:G=!0,return_token_type_ids:H=null}={}){return this._tokenizer.encode(Q,{text_pair:J,add_special_tokens:G,return_token_type_ids:H}).ids}batch_decode(Q,J={}){if(Q instanceof PQ)Q=Q.tolist();return Q.map((G)=>this.decode(G,J))}decode(Q,J={}){if(Q instanceof PQ)Q=o90(Q);if(!Array.isArray(Q)||Q.length===0||!dBQ(Q[0]))throw Error("token_ids must be a non-empty array of integers.");return this.decode_single(Q,J)}decode_single(Q,{skip_special_tokens:J=!1,clean_up_tokenization_spaces:G=null}){return this._tokenizer.decode(Q,{skip_special_tokens:J,clean_up_tokenization_spaces:G})}get_chat_template({chat_template:Q=null,tools:J=null}={}){if(this.chat_template&&typeof this.chat_template==="object"){let G=this.chat_template;if(Q!==null&&Object.hasOwn(G,Q))Q=G[Q];else if(Q===null)if(J!==null&&"tool_use"in G)Q=G.tool_use;else if("default"in G)Q=G.default;else 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(G).sort()}.`)}else if(Q===null)if(this.chat_template)Q=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");return Q}apply_chat_template(Q,J={}){let{tools:G=null,documents:H=null,chat_template:K=null,add_generation_prompt:z=!1,tokenize:q=!0,padding:F=!1,truncation:D=!1,max_length:V=null,return_tensor:O=!0,return_dict:P=!0,tokenizer_kwargs:N={},...I}=J;if(K=this.get_chat_template({chat_template:K,tools:G}),typeof K!=="string")throw Error(`chat_template must be a string, but got ${typeof K}`);let R=this._compiled_template_cache.get(K);if(R===void 0)R=new tzQ(K),this._compiled_template_cache.set(K,R);let w=Object.create(null);for(let T of FqQ){let y=t3(this.config,T);if(y)w[T]=y}let E=R.render({messages:Q,add_generation_prompt:z,tools:G,documents:H,...w,...I});if(q){let T=this._call(E,{add_special_tokens:!1,padding:F,truncation:D,max_length:V,return_tensor:O,...N});return P?T:T.input_ids}return E}};function n90(Q,J,G,H){if(!("language_codes"in Q)||!Array.isArray(Q.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!("languageRegex"in Q)||!(Q.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!("lang_to_token"in Q)||typeof Q.lang_to_token!=="function")throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let{src_lang:K,tgt_lang:z}=H;if(!Q.language_codes.includes(z))throw Error(`Target language code "${z}" is not valid. Must be one of: {${Q.language_codes.join(", ")}}`);if(K!==void 0){if(!Q.language_codes.includes(K))throw Error(`Source language code "${K}" is not valid. Must be one of: {${Q.language_codes.join(", ")}}`);for(let q of Q._tokenizer.post_processor.config.single)if("SpecialToken"in q&&Q.languageRegex.test(q.SpecialToken.id)){q.SpecialToken.id=Q.lang_to_token(K);break}}return H.forced_bos_token_id=Q._tokenizer.token_to_id(Q.lang_to_token(z)),Q._call(J,G)}var Kw0={};IV(Kw0,{AlbertTokenizer:()=>OqQ,AutoTokenizer:()=>m6,BartTokenizer:()=>PqQ,BertTokenizer:()=>NqQ,BlenderbotSmallTokenizer:()=>jqQ,BlenderbotTokenizer:()=>CqQ,BloomTokenizer:()=>IqQ,CLIPTokenizer:()=>wqQ,CamembertTokenizer:()=>RqQ,CodeGenTokenizer:()=>SqQ,CodeLlamaTokenizer:()=>EqQ,CohereAsrTokenizer:()=>kqQ,CohereTokenizer:()=>TqQ,ConvBertTokenizer:()=>yqQ,DebertaTokenizer:()=>xqQ,DebertaV2Tokenizer:()=>vqQ,DistilBertTokenizer:()=>bqQ,ElectraTokenizer:()=>gqQ,EsmTokenizer:()=>hqQ,FalconTokenizer:()=>_qQ,GPT2Tokenizer:()=>uqQ,GPTNeoXTokenizer:()=>mqQ,GemmaTokenizer:()=>fqQ,HerbertTokenizer:()=>pqQ,LlamaTokenizer:()=>lqQ,M2M100Tokenizer:()=>dqQ,MBart50Tokenizer:()=>iqQ,MBartTokenizer:()=>zw0,MPNetTokenizer:()=>aqQ,MarianTokenizer:()=>cqQ,MgpstrTokenizer:()=>oqQ,MobileBertTokenizer:()=>nqQ,NllbTokenizer:()=>sqQ,NougatTokenizer:()=>rqQ,PreTrainedTokenizer:()=>x8,Qwen2Tokenizer:()=>tqQ,RoFormerTokenizer:()=>QUQ,RobertaTokenizer:()=>eqQ,SiglipTokenizer:()=>XUQ,SpeechT5Tokenizer:()=>JUQ,SqueezeBertTokenizer:()=>YUQ,T5Tokenizer:()=>GUQ,TokenizersBackend:()=>x8,VitsTokenizer:()=>HUQ,Wav2Vec2CTCTokenizer:()=>BUQ,WhisperTokenizer:()=>qUQ,XLMRobertaTokenizer:()=>UUQ,XLMTokenizer:()=>$UQ});var OqQ=class extends x8{return_token_type_ids=!0},PqQ=class extends x8{},NqQ=class extends x8{return_token_type_ids=!0},jqQ=class extends x8{},CqQ=class extends x8{},IqQ=class extends x8{},RqQ=class extends x8{},wqQ=class extends x8{},EqQ=class extends x8{},SqQ=class extends x8{},TqQ=class extends x8{},kqQ=class extends x8{},yqQ=class extends x8{return_token_type_ids=!0},vqQ=class extends x8{return_token_type_ids=!0},xqQ=class extends x8{return_token_type_ids=!0},bqQ=class extends x8{},gqQ=class extends x8{return_token_type_ids=!0},hqQ=class extends x8{},_qQ=class extends x8{},fqQ=class extends x8{},mqQ=class extends x8{},uqQ=class extends x8{},pqQ=class extends x8{return_token_type_ids=!0},lqQ=class extends x8{padding_side="left"},dqQ=class extends x8{constructor(Q,J){super(Q,J);this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter((G)=>this.languageRegex.test(G)).map((G)=>G.slice(2,-2)),this.lang_to_token=(G)=>`__${G}__`}_build_translation_inputs(Q,J,G){return n90(this,Q,J,G)}},cqQ=class extends x8{constructor(Q,J){super(Q,J);this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter((G)=>this.languageRegex.test(G)),g8.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(Q){if(Q===null)return null;let[J,...G]=Q.trim().split(this.languageRegex);if(G.length===0)return super._encode_text(J);else if(G.length===2){let[H,K]=G;if(!this.supported_language_codes.includes(H))g8.warn(`Unsupported language code "${H}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`);return yW([H],super._encode_text(K))}}},zw0=class extends x8{constructor(Q,J){super(Q,J);this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter((G)=>this.languageRegex.test(G)).map((G)=>G),this.lang_to_token=(G)=>G}_build_translation_inputs(Q,J,G){return n90(this,Q,J,G)}},iqQ=class extends zw0{},oqQ=class extends x8{},nqQ=class extends x8{return_token_type_ids=!0},aqQ=class extends x8{},sqQ=class extends x8{constructor(Q,J){super(Q,J);this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter((G)=>this.languageRegex.test(G)),this.lang_to_token=(G)=>G}_build_translation_inputs(Q,J,G){return n90(this,Q,J,G)}},rqQ=class extends x8{},tqQ=class extends x8{},eqQ=class extends x8{},QUQ=class extends x8{return_token_type_ids=!0},XUQ=class extends x8{},JUQ=class extends x8{},YUQ=class extends x8{return_token_type_ids=!0},GUQ=class extends x8{},WUQ=class extends _G{decode_chain(Q){let J="";for(let G=1;G<Q.length;G+=2)J+=Q[G];return[J]}},HUQ=class extends x8{constructor(Q,J){super(Q,J);this._tokenizer.decoder=new WUQ({type:"VitsDecoder"})}},BUQ=class extends x8{},Vw0=[["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"]],BR=new Map(Vw0),AUQ=new Map([...Vw0.map(([Q,J])=>[J,Q]),["burmese","my"],["valencian","ca"],["flemish","nl"],["haitian","ht"],["letzeburgesch","lb"],["pushto","ps"],["panjabi","pa"],["moldavian","ro"],["moldovan","ro"],["sinhalese","si"],["castilian","es"]]);function KUQ(Q){Q=Q.toLowerCase();let J=AUQ.get(Q);if(J===void 0){let G=Q.match(/^<\|([a-z]{2})\|>$/);if(G)Q=G[1];if(BR.has(Q))J=Q;else{let K=Q.length===2?BR.keys():BR.values();throw Error(`Language "${Q}" is not supported. Must be one of: ${JSON.stringify(Array.from(K))}`)}}return J}var zUQ="\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E",$I0=new RegExp(`^[${zUQ}]+$`,"gu"),VUQ=0.1,qUQ=class extends x8{get timestamp_begin(){return this._tokenizer.token_to_id("<|notimestamps|>")+1}_decode_asr(Q,{return_timestamps:J=!1,return_language:G=!1,time_precision:H=null,force_full_sequences:K=!0}={}){if(H===null)throw Error("Must specify time_precision");let z=null,q=J==="word";function F(){return{language:z,timestamp:[null,null],text:""}}let D=[],V=F(),O=0,P=this.timestamp_begin,I=P+1500,R=[],w=[],E=!1,T=null,y=new Set(this.all_special_ids);for(let g of Q){let l=g.tokens,_=q?g.token_timestamps:null,a=null,r=P;if("stride"in g){let[p0,u0,d]=g.stride;if(O-=u0,T=p0-d,u0)r=u0/H+P;if(d)for(let n=l.length-1;n>=0;--n){let c0=Number(l[n]);if(c0>=P){if(a!==null&&(c0-P)*H<T)break;a=c0}}}let f0=[],t=[];for(let p0=0;p0<l.length;++p0){let u0=Number(l[p0]);if(y.has(u0)){let d=this.decode([u0]),n=BR.get(d.slice(2,-2));if(n!==void 0){if(z!==null&&n!==z&&!J){R.push(f0);let c0=this.findLongestCommonSequence(R)[0],WQ=this.decode(c0);V.text=WQ,D.push(V),R=[],f0=[],V=F()}z=V.language=n}}else if(u0>=P&&u0<=I){let d=(u0-P)*H+O,n=SF(d,2);if(a!==null&&u0>=a)E=!0;else if(E||R.length>0&&u0<r)E=!1;else if(V.timestamp[0]===null)V.timestamp[0]=n;else if(n===V.timestamp[0]);else{if(V.timestamp[1]=n,R.push(f0),q)w.push(t);let[c0,WQ]=this.findLongestCommonSequence(R,w),R0=this.decode(c0);if(V.text=R0,q){if(V.words=this.collateWordTimestamps(c0,WQ,z),V.words.length>0&&V.timestamp[1]!==null){for(let l0 of V.words)if(l0.timestamp[1]>V.timestamp[1]&&V.timestamp[1]>=l0.timestamp[0])l0.timestamp[1]=V.timestamp[1]}}D.push(V),R=[],f0=[],w=[],t=[],V=F()}}else if(f0.push(u0),q){let d=SF(_[p0]+O,2),n;if(p0+1<_.length){n=SF(_[p0+1]+O,2);let c0=this.decode([u0]);if($I0.test(c0))n=SF(Math.min(d+H,n),2)}else n=null;t.push([d,n])}}if("stride"in g){let[p0,u0,d]=g.stride;O+=p0-d}if(f0.length>0){if(R.push(f0),q)w.push(t)}else if(R.every((p0)=>p0.length===0))V=F(),R=[],f0=[],w=[],t=[]}if(R.length>0){if(K&&J)throw Error("Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.");let[g,l]=this.findLongestCommonSequence(R,w),_=this.decode(g);if(V.text=_,q)V.words=this.collateWordTimestamps(g,l,z);D.push(V)}let x=Object.create(null),b=D.map((g)=>g.text).join("");if(J||G){for(let g=0;g<D.length;++g){let l=D[g];if(!J)delete l.timestamp;if(!G)delete l.language}if(q){let g=[];for(let l of D)for(let _ of l.words)g.push(_);x={chunks:g}}else x={chunks:D}}return[b,x]}findLongestCommonSequence(Q,J=null){let G=Q[0],H=G.length,K=[],z=Array.isArray(J)&&J.length>0,q=z?[]:null,F=z?J[0]:null;for(let D=1;D<Q.length;++D){let V=Q[D],O=0,P=[H,H,0,0],N=V.length;for(let x=1;x<H+N;++x){let b=Math.max(0,H-x),g=Math.min(H,H+N-x),l=G.slice(b,g),_=Math.max(0,x-H),a=Math.min(N,x),r=V.slice(_,a);if(l.length!==r.length)throw Error("There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.");let f0;if(z)f0=l.filter((u0,d)=>u0===r[d]&&F[b+d][0]-VUQ<=J[D][_+d][0]).length;else f0=l.filter((u0,d)=>u0===r[d]).length;let t=x/1e4,p0=f0/x+t;if(f0>1&&p0>O)O=p0,P=[b,g,_,a]}let[I,R,w,E]=P,T=Math.floor((R+I)/2),y=Math.floor((E+w)/2);if(z&&O===0&&H>0){let x=F[H-1][0],b=J[D].findIndex((g)=>g[0]>=x);y=b===-1?V.length:b}if(K.push(...G.slice(0,T)),G=V.slice(y),H=G.length,z)q.push(...F.slice(0,T)),F=J[D].slice(y)}if(K.push(...G),z)return q.push(...F),[K,q];else return[K,[]]}collateWordTimestamps(Q,J,G){let[H,K,z]=this.combineTokensIntoWords(Q,G),q=[];for(let F=0;F<H.length;++F){let D=z[F];q.push({text:H[F],timestamp:[J[D.at(0)][0],J[D.at(-1)][1]]})}return q}combineTokensIntoWords(Q,J,G=`"'“¡¿([{-`,H=`"'.。,!?::”)]}、`){J=J??"english";let K,z,q;if(["chinese","japanese","thai","lao","myanmar"].includes(J))[K,z,q]=this.splitTokensOnUnicode(Q);else[K,z,q]=this.splitTokensOnSpaces(Q);return this.mergePunctuations(K,z,q,G,H)}decode(Q,J){let G;if(J?.decode_with_timestamps){if(Q instanceof PQ)Q=o90(Q);G=this.decodeWithTimestamps(Q,J)}else G=super.decode(Q,J);return G}decodeWithTimestamps(Q,J){let G=J?.time_precision??0.02,H=this.all_special_ids.at(-1)+1,K=[[]];for(let z of Q)if(z=Number(z),z>=H){let q=((z-H)*G).toFixed(2);K.push(`<|${q}|>`),K.push([])}else K[K.length-1].push(z);return K=K.map((z)=>typeof z==="string"?z:super.decode(z,J)),K.join("")}splitTokensOnUnicode(Q){let J=this.decode(Q,{decode_with_timestamps:!0}),G="",H=[],K=[],z=[],q=[],F=[],D=0;for(let V=0;V<Q.length;++V){let O=Q[V];q.push(O),F.push(V);let P=this.decode(q,{decode_with_timestamps:!0});if(!P.includes("")||J[D+P.indexOf("")]==="")H.push(P),K.push(q),z.push(F),q=[],F=[],D+=P.length}return[H,K,z]}splitTokensOnSpaces(Q){let[J,G,H]=this.splitTokensOnUnicode(Q),K=[],z=[],q=[];for(let F=0;F<J.length;++F){let D=J[F],V=G[F],O=H[F],P=V[0]>=this._tokenizer.token_to_id("<|endoftext|>"),N=D.startsWith(" "),I=D.trim(),R=$I0.test(I);if(P||N||R||K.length===0)K.push(D),z.push(V),q.push(O);else{let w=K.length-1;K[w]+=D,z[w].push(...V),q[w].push(...O)}}return[K,z,q]}mergePunctuations(Q,J,G,H,K){let z=structuredClone(Q),q=structuredClone(J),F=structuredClone(G),D=z.length-2,V=z.length-1;while(D>=0){if(z[D].startsWith(" ")&&H.includes(z[D].trim()))z[V]=z[D]+z[V],q[V]=yW(q[D],q[V]),F[V]=yW(F[D],F[V]),z[D]="",q[D]=[],F[D]=[];else V=D;--D}D=0,V=1;while(V<z.length){if(!z[D].endsWith(" ")&&K.includes(z[V]))z[D]+=z[V],q[D]=yW(q[D],q[V]),F[D]=yW(F[D],F[V]),z[V]="",q[V]=[],F[V]=[];else D=V;++V}return[z.filter((O)=>O),q.filter((O)=>O.length>0),F.filter((O)=>O.length>0)]}},UUQ=class extends x8{},$UQ=class extends x8{return_token_type_ids=!0;constructor(Q,J){super(Q,J);g8.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},m6=class{static async from_pretrained(Q,{progress_callback:J=null,config:G=null,cache_dir:H=null,local_files_only:K=!1,revision:z="main"}={}){let[q,F]=await Aw0(Q,{progress_callback:J,config:G,cache_dir:H,local_files_only:K,revision:z}),D=F.tokenizer_class?.replace(/Fast$/,"")??"PreTrainedTokenizer",V=Kw0[D];if(!V)g8.warn(`Unknown tokenizer class "${D}", attempting to construct from base class.`),V=x8;return new V(q,F)}},SR="https://github.com/huggingface/transformers.js/issues/new/choose",a90="preprocessor_config.json",hF=a90,qw0="processor_config.json",Uw0="chat_template.jinja",u6=class extends nJ{static classes=["image_processor_class","tokenizer_class","feature_extractor_class"];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(Q,J,G){super();this.config=Q,this.components=J,this.chat_template=G}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(Q,J={}){if(!this.tokenizer)throw Error("Unable to apply chat template without a tokenizer.");return this.tokenizer.apply_chat_template(Q,{tokenize:!1,chat_template:this.chat_template??void 0,...J})}batch_decode(...Q){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.batch_decode(...Q)}decode(...Q){if(!this.tokenizer)throw Error("Unable to decode without a tokenizer.");return this.tokenizer.decode(...Q)}async _call(Q,...J){for(let G of[this.image_processor,this.feature_extractor,this.tokenizer])if(G)return G(Q,...J);throw Error("No image processor, feature extractor, or tokenizer found.")}static async from_pretrained(Q,J={}){let[G,H,K]=await Promise.all([this.uses_processor_config?bW(Q,qw0,!0,J):{},Promise.all(this.classes.filter((z)=>(z in this)).map(async(z)=>{let q=await this[z].from_pretrained(Q,J);return[z.replace(/_class$/,""),q]})).then(Object.fromEntries),this.uses_chat_template_file?R90(Q,Uw0,!0,J):null]);return new this(G,H,K)}},q90={};IV(q90,{ChatterboxProcessor:()=>uUQ,CohereAsrProcessor:()=>lUQ,Florence2Processor:()=>d$Q,Gemma3Processor:()=>c$Q,Gemma3nProcessor:()=>i$Q,Gemma4Processor:()=>o$Q,Glm46VProcessor:()=>n$Q,GraniteSpeechProcessor:()=>a$Q,GroundingDinoProcessor:()=>r$Q,Idefics3Processor:()=>PI0,JinaCLIPProcessor:()=>JZQ,Lfm2VlProcessor:()=>YZQ,LlavaProcessor:()=>GZQ,MgpstrProcessor:()=>WZQ,MoonshineProcessor:()=>HZQ,OwlViTProcessor:()=>BZQ,PaliGemmaProcessor:()=>KZQ,Phi3VProcessor:()=>VZQ,PixtralProcessor:()=>qZQ,Processor:()=>u6,PyAnnoteProcessor:()=>UZQ,Qwen2VLProcessor:()=>X10,Qwen2_5_VLProcessor:()=>ow0,Qwen3VLProcessor:()=>$ZQ,Sam2Processor:()=>aw0,Sam2VideoProcessor:()=>ZZQ,SamProcessor:()=>nw0,SmolVLMProcessor:()=>PI0,SpeechT5Processor:()=>FZQ,UltravoxProcessor:()=>DZQ,VLChatProcessor:()=>XZQ,VoxtralProcessor:()=>PZQ,VoxtralRealtimeProcessor:()=>CZQ,Wav2Vec2Processor:()=>IZQ,Wav2Vec2ProcessorWithLM:()=>RZQ,WhisperProcessor:()=>wZQ});var rX=class extends nJ{constructor(Q){super();this.config=Q}static async from_pretrained(Q,J={}){let G=await bW(Q,a90,!0,J);return new this(G)}};function EX(Q,J){if(!(Q instanceof Float32Array||Q instanceof Float64Array))throw Error(`${J} expects input to be a Float32Array or a Float64Array, but got ${Q?.constructor?.name??typeof Q} 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.`)}var s90={};IV(s90,{ASTFeatureExtractor:()=>wUQ,ChatterboxFeatureExtractor:()=>EUQ,ClapFeatureExtractor:()=>SUQ,CohereAsrFeatureExtractor:()=>kUQ,DacFeatureExtractor:()=>Nw0,EncodecFeatureExtractor:()=>Ow0,FeatureExtractor:()=>rX,Gemma3nAudioFeatureExtractor:()=>jw0,Gemma4AudioFeatureExtractor:()=>Cw0,GraniteSpeechFeatureExtractor:()=>yUQ,MoonshineFeatureExtractor:()=>vUQ,ParakeetFeatureExtractor:()=>Pw0,PyAnnoteFeatureExtractor:()=>Iw0,SeamlessM4TFeatureExtractor:()=>xUQ,SnacFeatureExtractor:()=>bUQ,SpeechT5FeatureExtractor:()=>gUQ,VoxtralRealtimeFeatureExtractor:()=>fUQ,Wav2Vec2FeatureExtractor:()=>hUQ,WeSpeakerFeatureExtractor:()=>_UQ,WhisperFeatureExtractor:()=>mUQ});async function Dw0(Q,J){if(Y6.IS_BROWSER_ENV){if(Y6.IS_WEBWORKER_ENV)throw Error("Unable to save a file from a Web Worker.");let G=URL.createObjectURL(J),H=document.createElement("a");H.href=G,H.download=Q,H.click(),H.remove(),URL.revokeObjectURL(G)}else if(Y6.IS_FS_AVAILABLE){let G=J.stream(),H=Zw0.Readable.fromWeb(G),K=$w0.default.createWriteStream(Q);await Fw0.pipeline(H,K)}else throw Error("Unable to save because filesystem is disabled in this environment.")}async function ZUQ(Q,J){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.");let G=await(await xF(Q)).arrayBuffer(),H=new AudioContext({sampleRate:J});if(typeof J>"u")g8.warn(`No sampling rate provided, using default of ${H.sampleRate}Hz.`);let K=await H.decodeAudioData(G),z;if(K.numberOfChannels===2){let q=Math.sqrt(2),F=K.getChannelData(0),D=K.getChannelData(1);z=new Float32Array(F.length);for(let V=0;V<K.length;++V)z[V]=q*(F[V]+D[V])/2}else z=K.getChannelData(0);return z}var FUQ=ZUQ;function Mw0(Q,J){if(Q<1)return new Float64Array;if(Q===1)return new Float64Array([1]);let G=1-J,H=2*Math.PI/(Q-1),K=new Float64Array(Q);for(let z=0;z<Q;++z)K[z]=J-G*Math.cos(z*H);return K}function ZI0(Q){return Mw0(Q,0.5)}function DUQ(Q){return Mw0(Q,0.54)}var MUQ={htk:(Q)=>2595*Math.log10(1+Q/700),kaldi:(Q)=>1127*Math.log(1+Q/700),slaney:(Q,J=1000,G=15,H=27/Math.log(6.4))=>Q>=J?G+Math.log(Q/J)*H:3*Q/200};function a60(Q,J="htk"){let G=MUQ[J];if(!G)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof Q==="number"?G(Q):Q.map((H)=>G(H))}var LUQ={htk:(Q)=>700*(10**(Q/2595)-1),kaldi:(Q)=>700*(Math.exp(Q/1127)-1),slaney:(Q,J=1000,G=15,H=Math.log(6.4)/27)=>Q>=G?J*Math.exp(H*(Q-G)):200*Q/3};function OUQ(Q,J="htk"){let G=LUQ[J];if(!G)throw Error('mel_scale should be one of "htk", "slaney" or "kaldi".');return typeof Q==="number"?G(Q):Q.map((H)=>G(H))}function PUQ(Q,J){let G=Float64Array.from({length:J.length-1},(q,F)=>J[F+1]-J[F]),H=Array.from({length:Q.length},()=>Array(J.length));for(let q=0;q<Q.length;++q){let F=H[q];for(let D=0;D<J.length;++D)F[D]=J[D]-Q[q]}let K=J.length-2,z=Array.from({length:K},()=>Array(Q.length));for(let q=0;q<Q.length;++q){let F=H[q];for(let D=0;D<K;++D){let V=-F[D]/G[D],O=F[D+2]/G[D+1];z[D][q]=Math.max(0,Math.min(V,O))}}return z}function FI0(Q,J,G){let H=(J-Q)/(G-1);return Float64Array.from({length:G},(K,z)=>Q+H*z)}function vW(Q,J,G,H,K,z=null,q="htk",F=!1){if(z!==null&&z!=="slaney")throw Error('norm must be one of null or "slaney"');if(Q<2)throw Error(`Require num_frequency_bins: ${Q} >= 2`);if(G>H)throw Error(`Require min_frequency: ${G} <= max_frequency: ${H}`);let D=a60(G,q),V=a60(H,q),O=FI0(D,V,J+2),P=OUQ(O,q),N;if(F){let R=K/((Q-1)*2);N=a60(Float64Array.from({length:Q},(w,E)=>E*R),q),P=O}else N=FI0(0,Math.floor(K/2),Q);let I=PUQ(N,P);if(z!==null&&z==="slaney")for(let R=0;R<J;++R){let w=I[R],E=2/(P[R+2]-P[R]);for(let T=0;T<Q;++T)w[T]*=E}return I}function NUQ(Q,J,G){let H=new Q.constructor(Q.length+J+G),K=Q.length-1;for(let z=0;z<Q.length;++z)H[J+z]=Q[z];for(let z=1;z<=J;++z)H[J-z]=Q[zR(z,K)];for(let z=1;z<=G;++z)H[K+J+z]=Q[zR(K-z,K)];return H}function Lw0(Q,J,G,H,K){if(G<=0)throw Error("reference must be greater than zero");if(H<=0)throw Error("min_value must be greater than zero");G=Math.max(H,G);let z=Math.log10(G);for(let q=0;q<Q.length;++q)Q[q]=J*Math.log10(Math.max(H,Q[q])-z);if(K!==null){if(K<=0)throw Error("db_range must be greater than zero");let q=D7(Q)[0]-K;for(let F=0;F<Q.length;++F)Q[F]=Math.max(Q[F],q)}return Q}function jUQ(Q,J=1,G=0.00001,H=null){return Lw0(Q,20,J,G,H)}function CUQ(Q,J=1,G=0.0000000001,H=null){return Lw0(Q,10,J,G,H)}async function gW(Q,J,G,H,{fft_length:K=null,power:z=1,center:q=!0,pad_mode:F="reflect",onesided:D=!0,preemphasis:V=null,preemphasis_htk_flavor:O=!0,mel_filters:P=null,mel_floor:N=0.0000000001,log_mel:I=null,max_log_mel:R=null,reference:w=1,min_value:E=0.0000000001,db_range:T=null,remove_dc_offset:y=null,min_num_frames:x=null,max_num_frames:b=null,do_pad:g=!0,transpose:l=!1,mel_offset:_=0,mel_floor_mode:a="clamp"}={}){let r=J.length;if(K===null)K=G;if(G>K)throw Error(`frame_length (${G}) may not be larger than fft_length (${K})`);if(r!==G)throw Error(`Length of the window (${r}) must equal frame_length (${G})`);if(H<=0)throw Error("hop_length must be greater than zero");if(z===null&&P!==null)throw 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(!O)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(q){let m0=Math.floor(G/2);switch(F){case"reflect":{Q=NUQ(Q,m0,m0);break}case"constant":{let ZQ=new Q.constructor(Q.length+2*m0);ZQ.set(Q,m0),Q=ZQ;break}case"semicausal":{let ZQ=new Q.constructor(Q.length+m0);ZQ.set(Q,m0),Q=ZQ;break}default:throw Error(`pad_mode="${F}" not implemented yet.`)}}let f0=Math.floor(1+Math.floor((Q.length-G)/H));if(x!==null&&f0<x)f0=x;let t=D?Math.floor(K/2)+1:K,p0=f0,u0=f0;if(b!==null)if(b>f0){if(g)u0=b}else u0=p0=b;let d=new LVQ(K),n=new Float64Array(K),c0=new Float64Array(d.outputBufferSize),WQ=new Float32Array(t*u0);for(let m0=0;m0<p0;++m0){let ZQ=m0*H,LQ=Math.min(Q.length-ZQ,G);if(LQ!==G)n.fill(0,0,G);for(let h0=0;h0<LQ;++h0)n[h0]=Q[ZQ+h0];if(y){let h0=0;for(let iQ=0;iQ<LQ;++iQ)h0+=n[iQ];let pQ=h0/LQ;for(let iQ=0;iQ<LQ;++iQ)n[iQ]-=pQ}if(V!==null){for(let h0=LQ-1;h0>=1;--h0)n[h0]-=V*n[h0-1];n[0]*=1-V}for(let h0=0;h0<J.length;++h0)n[h0]*=J[h0];d.realTransform(c0,n);for(let h0=0;h0<t;++h0){let pQ=h0<<1;WQ[h0*u0+m0]=c0[pQ]**2+c0[pQ+1]**2}}if(z!==null&&z!==2){let m0=z/2;for(let ZQ=0;ZQ<WQ.length;++ZQ)WQ[ZQ]**=m0}let R0=P.length,l0=await VqQ(new PQ("float32",P.flat(),[R0,t]),new PQ("float32",WQ,[t,u0]));if(l)l0=l0.transpose(1,0);let d0=l0.data;if(a==="add")for(let m0=0;m0<d0.length;++m0)d0[m0]=_+d0[m0]+N;else for(let m0=0;m0<d0.length;++m0)d0[m0]=_+Math.max(N,d0[m0]);if(z!==null&&I!==null){let m0=Math.min(d0.length,p0*R0);switch(I){case"log":for(let ZQ=0;ZQ<m0;++ZQ)d0[ZQ]=Math.log(d0[ZQ]);break;case"log10":for(let ZQ=0;ZQ<m0;++ZQ)d0[ZQ]=Math.log10(d0[ZQ]);break;case"log10_max_norm":{for(let h0=0;h0<m0;++h0)d0[h0]=Math.log10(d0[h0]);let LQ=(R??D7(d0)[0])-8;for(let h0=0;h0<m0;++h0)d0[h0]=(Math.max(d0[h0],LQ)+4)/4;break}case"dB":if(z===1)jUQ(d0,w,E,T);else if(z===2)CUQ(d0,w,E,T);else throw Error(`Cannot use log_mel option '${I}' with power ${z}`);break;default:throw Error(`log_mel must be one of null, 'log', 'log10', 'log10_max_norm', or 'dB'. Got '${I}'`)}}return l0}function m5(Q,J,{periodic:G=!0,frame_length:H=null,center:K=!0}={}){let z=G?Q+1:Q,q;switch(J){case"boxcar":q=new Float64Array(z).fill(1);break;case"hann":case"hann_window":q=ZI0(z);break;case"hamming":q=DUQ(z);break;case"povey":q=ZI0(z).map((V)=>Math.pow(V,0.85));break;default:throw Error(`Unknown window type ${J}.`)}if(G)q=q.subarray(0,Q);if(H===null||Q===H)return q;if(Q>H)throw Error(`Length of the window (${Q}) may not be larger than frame_length (${H})`);let F=new Float64Array(H),D=K?Math.floor((H-Q)/2):0;return F.set(q,D),F}function IUQ(Q,J){let G=Q.reduce((z,q)=>z+q.length,0),H=new ArrayBuffer(44),K=new DataView(H);return QR(K,0,"RIFF"),K.setUint32(4,36+G*4,!0),QR(K,8,"WAVE"),QR(K,12,"fmt "),K.setUint32(16,16,!0),K.setUint16(20,3,!0),K.setUint16(22,1,!0),K.setUint32(24,J,!0),K.setUint32(28,J*4,!0),K.setUint16(32,4,!0),K.setUint16(34,32,!0),QR(K,36,"data"),K.setUint32(40,G*4,!0),new Blob([H,...Q.map((z)=>z.buffer)],{type:"audio/wav"})}function QR(Q,J,G){for(let H=0;H<G.length;++H)Q.setUint8(J+H,G.charCodeAt(H))}var RUQ=class{constructor(Q,J){this.audio=Q,this.sampling_rate=J}get data(){if(Array.isArray(this.audio)){if(this.audio.length===0)return new Float32Array(0);if(this.audio.length===1)return this.audio[0];let Q=this.audio.reduce((H,K)=>H+K.length,0),J=new Float32Array(Q),G=0;for(let H of this.audio)J.set(H,G),G+=H.length;return J}else return this.audio}toBlob(){let Q=this.audio;if(Q instanceof Float32Array)Q=[Q];return IUQ(Q,this.sampling_rate)}async save(Q){return Dw0(Q,this.toBlob())}},wUQ=class extends rX{constructor(Q){super(Q);let J=this.config.sampling_rate,G=vW(257,this.config.num_mel_bins,20,Math.floor(J/2),J,null,"kaldi",!0);this.mel_filters=G,this.window=m5(400,"hann",{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(Q,J){return gW(Q,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,max_num_frames:J,transpose:!0})}async _call(Q){EX(Q,"ASTFeatureExtractor");let J=await this._extract_fbank_features(Q,this.config.max_length);if(this.config.do_normalize){let G=this.std*2,H=J.data;for(let K=0;K<H.length;++K)H[K]=(H[K]-this.mean)/G}return{input_values:J.unsqueeze_(0)}}},Ow0=class extends rX{async _call(Q){if(EX(Q,"EncodecFeatureExtractor"),Q instanceof Float64Array)Q=new Float32Array(Q);let J=this.config.feature_size;if(Q.length%J!==0)throw Error(`The length of the audio data must be a multiple of the number of channels (${J}).`);let G=[1,J,Q.length/J];return{input_values:new PQ("float32",Q,G)}}},EUQ=class extends rX{async _call(Q){if(EX(Q,"ChatterboxFeatureExtractor"),Q instanceof Float64Array)Q=new Float32Array(Q);let J=[1,Q.length];return{input_values:new PQ("float32",Q,J)}}},SUQ=class extends rX{constructor(Q){super(Q);this.mel_filters=vW(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=vW(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=m5(this.config.fft_window_size,"hann")}async _get_input_mel(Q,J,G,H){let K,z=!1,q=Q.length-J;if(q>0)if(G==="rand_trunc"){z=!0;let F=Math.floor(C90.random()*(q+1));Q=Q.subarray(F,F+J),K=await this._extract_fbank_features(Q,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${G}" not implemented`);else{if(q<0){let F=new Float64Array(J);if(F.set(Q),H==="repeat")for(let D=Q.length;D<J;D+=Q.length)F.set(Q.subarray(0,Math.min(Q.length,J-D)),D);else if(H==="repeatpad")for(let D=Q.length;D<-q;D+=Q.length)F.set(Q,D);Q=F}if(G==="fusion")throw Error(`Truncation strategy "${G}" not implemented`);K=await this._extract_fbank_features(Q,this.mel_filters_slaney,this.config.nb_max_samples)}return K.unsqueeze_(0)}async _extract_fbank_features(Q,J,G=null){return gW(Q,this.window,this.config.fft_window_size,this.config.hop_length,{power:2,mel_filters:J,log_mel:"dB",max_num_frames:G,do_pad:!1,transpose:!0})}async _call(Q,{max_length:J=null}={}){return EX(Q,"ClapFeatureExtractor"),{input_features:(await this._get_input_mel(Q,J??this.config.nb_max_samples,this.config.truncation,this.config.padding)).unsqueeze_(0)}}},TUQ=0.00001,Pw0=class extends rX{constructor(Q){super(Q);this.config.mel_filters??=vW(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,"slaney","slaney");let J=m5(this.config.win_length,"hann",{periodic:!1});this.window=new Float64Array(this.config.n_fft);let G=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(J,G)}async _extract_fbank_features(Q){let J=this.config.preemphasis;Q=new Float64Array(Q);for(let H=Q.length-1;H>=1;--H)Q[H]-=J*Q[H-1];return await gW(Q,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:"log",mel_floor:-1/0,pad_mode:"constant",center:!0,transpose:!0,mel_offset:0.00000005960464477539063})}async _call(Q){EX(Q,"ParakeetFeatureExtractor");let J=await this._extract_fbank_features(Q),G=Math.floor((Q.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),H=J.data;H.fill(0,G*J.dims[1]);let[K,z]=J.dims,q=new Float64Array(z),F=new Float64Array(z);for(let O=0;O<G;++O){let P=O*z;for(let N=0;N<z;++N){let I=H[P+N];q[N]+=I,F[N]+=I*I}}let D=G>1?G-1:1;for(let O=0;O<z;++O){let P=q[O]/G,N=(F[O]-G*P*P)/D,R=1/(Math.sqrt(N)+TUQ);for(let w=0;w<G;++w){let E=w*z+O;H[E]=(H[E]-P)*R}}let V=new BigInt64Array(K);return V.fill(1n,0,G),{input_features:J.unsqueeze_(0),attention_mask:new PQ("int64",V,[1,K])}}},kUQ=class extends Pw0{_apply_dither(Q){let J=this.config.dither??0;if(J<=0)return Q;let G=new ER(Q.length);for(let H=0;H<Q.length;++H)Q[H]+=J*G.gauss();return Q}split_audio(Q){let J=this.config.max_audio_clip_s??35,G=this.config.overlap_chunk_second??5,H=this.config.min_energy_window_samples??1600,K=this.config.sampling_rate,z=Math.max(1,Math.round(J*K)),q=Math.max(1,Math.round(G*K));if(Q.length<=z)return[Q];let F=[],D=0,V=Q.length;while(D<V){if(D+z>=V){F.push(Q.slice(D,V));break}let O=Math.max(D,D+z-q),P=Math.min(D+z,V),N;if(P<=O)N=D+z;else N=this._find_split_point_energy(Q,O,P,H);N=Math.max(D+1,Math.min(N,V)),F.push(Q.slice(D,N)),D=N}return F}_find_split_point_energy(Q,J,G,H){let K=G-J;if(K<=H)return Math.floor((J+G)/2);let z=1/0,q=J,F=K-H;for(let D=0;D<=F;D+=H){let V=0;for(let O=0;O<H;++O){let P=Q[J+D+O];V+=P*P}if(V=Math.sqrt(V/H),V<z)z=V,q=J+D}return q}async _call(Q){EX(Q,"CohereAsrFeatureExtractor");let J=new Float64Array(Q);return this._apply_dither(J),super._call(J)}},Nw0=class extends Ow0{},jw0=class extends rX{constructor(Q){super(Q);let{fft_length:J,feature_size:G,min_frequency:H,max_frequency:K,sampling_rate:z,frame_length:q}=this.config,F=vW(Math.floor(1+J/2),G,H,K,z,null,"htk",!1);this.mel_filters=F,this.window=m5(q,"hann")}async _extract_fbank_features(Q,J){return gW(Q,this.window,this.config.frame_length,this.config.hop_length,{fft_length:this.config.fft_length,center:!1,onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,remove_dc_offset:!1,transpose:!0})}async _call(Q,{max_length:J=480000,truncation:G=!0,padding:H=!0,pad_to_multiple_of:K=128}={}){if(EX(Q,"Gemma3nAudioFeatureExtractor"),G&&Q.length>J)Q=Q.slice(0,J);if(H&&Q.length%K!==0){let F=K-Q.length%K,D=new Float64Array(Q.length+F);if(D.set(Q),this.config.padding_value!==0)D.fill(this.config.padding_value,Q.length);Q=D}let z=await this._extract_fbank_features(Q,this.config.max_length),q=sX([1,z.dims[0]],!0);return{input_features:z.unsqueeze_(0),input_features_mask:q}}},Cw0=class extends jw0{async _extract_fbank_features(Q,J){let{frame_length:G,hop_length:H,fft_length:K}=this.config,z=Math.floor(G/2),q=Math.floor((Q.length+z-(G+1))/H)+1;return gW(Q,this.window,G,H,{fft_length:K,center:!0,pad_mode:"semicausal",onesided:!0,preemphasis:this.config.preemphasis,preemphasis_htk_flavor:this.config.preemphasis_htk_flavor,mel_filters:this.mel_filters,log_mel:"log",mel_floor:this.config.mel_floor,mel_floor_mode:"add",remove_dc_offset:!1,transpose:!0,max_num_frames:q})}async _call(Q,J={}){EX(Q,"Gemma4AudioFeatureExtractor");let G=Q.length,H=await super._call(Q,J),{input_features:K}=H,[,z,q]=K.dims,{frame_length:F,hop_length:D}=this.config,V=Math.floor(F/2),O=F+1,P=new Uint8Array(G+V+(J.pad_to_multiple_of??128));P.fill(1,V,V+G);let N=new Uint8Array(z);for(let R=0;R<z;++R)N[R]=P[R*D+O-1]?1:0;let I=K.data;for(let R=0;R<z;++R)if(!N[R])I.fill(0,R*q,(R+1)*q);return H.input_features_mask=new PQ("bool",N,[1,z]),H}},yUQ=class extends rX{constructor(Q){super(Q);let{n_fft:J,win_length:G,n_mels:H,sample_rate:K}=Q.melspec_kwargs;this.mel_filters=vW(Math.floor(1+J/2),H,0,K/2,K,null,"htk");let z=m5(G,"hann");this.window=new Float64Array(J);let q=Math.floor((J-G)/2);this.window.set(z,q)}async _call(Q){EX(Q,"GraniteSpeechFeatureExtractor");let{n_fft:J,hop_length:G,n_mels:H}=this.config.melspec_kwargs,K=1+Math.floor((Q.length-1)/G),z=K-K%2;return{input_features:(await gW(Q,this.window,J,G,{power:2,mel_filters:this.mel_filters,log_mel:"log10_max_norm",transpose:!0,max_num_frames:z,do_pad:!1})).view(-1,2*H).unsqueeze_(0)}}},vUQ=class extends rX{async _call(Q){if(EX(Q,"MoonshineFeatureExtractor"),Q instanceof Float64Array)Q=new Float32Array(Q);let J=[1,Q.length];return{input_values:new PQ("float32",Q,J)}}},Iw0=class extends rX{async _call(Q){if(EX(Q,"PyAnnoteFeatureExtractor"),Q instanceof Float64Array)Q=new Float32Array(Q);let J=[1,1,Q.length];return{input_values:new PQ("float32",Q,J)}}samples_to_frames(Q){return(Q-this.config.offset)/this.config.step}post_process_speaker_diarization(Q,J){let G=J/this.samples_to_frames(J)/this.config.sampling_rate,H=[];for(let K of Q.tolist()){let z=[],q=-1;for(let F=0;F<K.length;++F){let D=wX(K[F]),[V,O]=D7(D),[P,N]=[F,F+1];if(O!==q)q=O,z.push({id:O,start:P,end:N,score:V});else z.at(-1).end=N,z.at(-1).score+=V}H.push(z.map(({id:F,start:D,end:V,score:O})=>({id:F,start:D*G,end:V*G,confidence:O/(V-D)})))}return H}},xUQ=class extends rX{constructor(Q){super(Q);let J=this.config.sampling_rate,G=vW(257,this.config.num_mel_bins,20,Math.floor(J/2),J,null,"kaldi",!0);this.mel_filters=G,this.window=m5(400,"povey",{periodic:!1})}async _extract_fbank_features(Q,J){return Q=Q.map((G)=>G*32768),gW(Q,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,max_num_frames:J,transpose:!0})}async _call(Q,{padding:J=!0,pad_to_multiple_of:G=2,do_normalize_per_mel_bins:H=!0,return_attention_mask:K=!0}={}){EX(Q,"SeamlessM4TFeatureExtractor");let z=await this._extract_fbank_features(Q,this.config.max_length);if(H){let[I,R]=z.dims,w=z.data;for(let E=0;E<R;++E){let T=0;for(let g=0;g<I;++g)T+=w[g*R+E];let y=T/I,x=0;for(let g=0;g<I;++g)x+=(w[g*R+E]-y)**2;x/=I-1;let b=Math.sqrt(x+0.0000001);for(let g=0;g<I;++g){let l=g*R+E;w[l]=(w[l]-y)/b}}}let q;if(J){let[I,R]=z.dims,w=z.data,E=I%G;if(E>0){let T=new Float32Array(R*(I+E));T.set(w),T.fill(this.config.padding_value,w.length);let y=I+E;if(z=new PQ(z.type,T,[y,R]),K)q=new PQ("int64",new BigInt64Array(y),[1,y]),q.data.fill(1n,0,I)}}let[F,D]=z.dims,V=this.config.stride;if(F%V!==0)throw Error(`The number of frames (${F}) must be a multiple of the stride (${V}).`);let P=z.view(1,Math.floor(F/V),D*V),N={input_features:P};if(K){let I=P.dims[1],R=new BigInt64Array(I);if(q){let w=q.data;for(let E=1,T=0;E<F;E+=V,++T)R[T]=w[E]}else R.fill(1n);N.attention_mask=new PQ("int64",R,[1,I])}return N}},bUQ=class extends Nw0{},gUQ=class extends rX{},hUQ=class extends rX{_zero_mean_unit_var_norm(Q){let G=Q.reduce((K,z)=>K+z,0)/Q.length,H=Q.reduce((K,z)=>K+(z-G)**2,0)/Q.length;return Q.map((K)=>(K-G)/Math.sqrt(H+0.0000001))}async _call(Q){if(EX(Q,"Wav2Vec2FeatureExtractor"),Q instanceof Float64Array)Q=new Float32Array(Q);let J=Q;if(this.config.do_normalize)J=this._zero_mean_unit_var_norm(J);let G=[1,J.length];return{input_values:new PQ("float32",J,G),attention_mask:new PQ("int64",new BigInt64Array(J.length).fill(1n),G)}}},_UQ=class extends rX{constructor(Q){super(Q);let J=this.config.sampling_rate,G=vW(257,this.config.num_mel_bins,20,Math.floor(J/2),J,null,"kaldi",!0);this.mel_filters=G,this.window=m5(400,"hamming",{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(Q){return Q=Q.map((J)=>J*32768),gW(Q,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:0.97,mel_filters:this.mel_filters,log_mel:"log",mel_floor:0.0000001192092955078125,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(Q){EX(Q,"WeSpeakerFeatureExtractor");let J=(await this._extract_fbank_features(Q)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let G=J.mean(1).data,H=J.data,[K,z,q]=J.dims;for(let F=0;F<K;++F){let D=F*z*q,V=F*q;for(let O=0;O<z;++O){let P=D+O*q;for(let N=0;N<q;++N)H[P+N]-=G[V+N]}}}return{input_features:J}}},fUQ=class extends rX{constructor(Q){super(Q);this.config.mel_filters??=vW(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8000,this.config.sampling_rate,"slaney","slaney"),this.window=m5(this.config.n_fft,"hann")}async _extract_fbank_features(Q,{center:J=!0}={}){let{n_fft:G,hop_length:H,mel_filters:K,global_log_mel_max:z}=this.config,q=J?Math.floor(Q.length/H):Math.floor((Q.length-G)/H);return await gW(Q,this.window,G,H,{power:2,mel_filters:K,log_mel:"log10_max_norm",max_log_mel:z,center:J,max_num_frames:q,do_pad:!1})}async _call(Q,{center:J=!0}={}){return EX(Q,"VoxtralRealtimeFeatureExtractor"),{input_features:(await this._extract_fbank_features(Q,{center:J})).unsqueeze_(0)}}},mUQ=class extends rX{constructor(Q){super(Q);this.config.mel_filters??=vW(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,8000,this.config.sampling_rate,"slaney","slaney"),this.window=m5(this.config.n_fft,"hann")}async _extract_fbank_features(Q){return await gW(Q,this.window,this.config.n_fft,this.config.hop_length,{power:2,mel_filters:this.config.mel_filters,log_mel:"log10_max_norm",max_num_frames:Math.min(Math.floor(Q.length/this.config.hop_length),this.config.nb_max_frames)})}async _call(Q,{max_length:J=null}={}){EX(Q,"WhisperFeatureExtractor");let G,H=J??this.config.n_samples;if(Q.length>H){if(Q.length>this.config.n_samples)g8.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`.");G=Q.slice(0,H)}else G=new Float32Array(H),G.set(Q);return{input_features:(await this._extract_fbank_features(G)).unsqueeze_(0)}}},aY=class{static async from_pretrained(Q,J={}){let G=await bW(Q,a90,!0,J),H=G.feature_extractor_type,K=s90[H];if(!K)throw Error(`Unknown feature_extractor_type: '${H}'. Please report this at ${SR}.`);return new K(G)}},uUQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;async _call(Q,J=null){let G=this.tokenizer(Q),H=J?await this.feature_extractor(J):{};return{...G,...H}}},pUQ=new Set(["ja","zh"]),lUQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;static uses_processor_config=!0;get_decoder_prompt_ids(Q="en"){let J=["▁","<|startofcontext|>","<|startoftranscript|>","<|emo:undefined|>",`<|${Q}|>`,`<|${Q}|>`,"<|pnc|>","<|noitn|>","<|notimestamp|>","<|nodiarize|>"];return this.tokenizer.convert_tokens_to_ids(J)}static join_chunks(Q,J="en"){let G=Q.filter((z)=>z&&z.trim());if(G.length===0)return"";let H=pUQ.has(J)?"":" ";return[G[0].trimEnd(),...G.slice(1).map((z)=>z.trim())].join(H)}async _call(Q){return await this.feature_extractor(Q)}},XB,Rw0,qH;if(Y6.IS_WEB_ENV)XB=(Q,J)=>{if(!self.OffscreenCanvas)throw Error("OffscreenCanvas not supported by this environment.");return new self.OffscreenCanvas(Q,J)},qH=self.createImageBitmap,Rw0=self.ImageData;else if(OR.default)qH=async(Q)=>{let G=(await Q.metadata()).channels,{data:H,info:K}=await Q.rotate().raw().toBuffer({resolveWithObject:!0}),z=new gG(new Uint8ClampedArray(H),K.width,K.height,K.channels);if(G!==void 0&&G!==K.channels)z.convert(G);return z};else throw Error("Unable to load image processing library.");var dUQ={0:"nearest",1:"lanczos",2:"bilinear",3:"bicubic",4:"box",5:"hamming"},cUQ=new Map([["png","image/png"],["jpg","image/jpeg"],["jpeg","image/jpeg"],["gif","image/gif"]]),gG=class Q{constructor(J,G,H,K){this.data=J,this.width=G,this.height=H,this.channels=K}get size(){return[this.width,this.height]}static async read(J){if(J instanceof Q)return J;else if(typeof J==="string"||J instanceof URL)return await this.fromURL(J);else if(J instanceof Blob)return await this.fromBlob(J);else if(typeof HTMLCanvasElement<"u"&&J instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&J instanceof OffscreenCanvas)return this.fromCanvas(J);else throw Error(`Unsupported input type: ${typeof J}`)}static fromCanvas(J){if(!Y6.IS_WEB_ENV)throw Error("fromCanvas() is only supported in browser environments.");let H=J.getContext("2d").getImageData(0,0,J.width,J.height).data;return new Q(H,J.width,J.height,4)}static async fromURL(J){let G=await xF(J);if(G.status!==200)throw Error(`Unable to read image from "${J}" (${G.status} ${G.statusText})`);let H=await G.blob();return this.fromBlob(H)}static async fromBlob(J){if(Y6.IS_WEB_ENV){let G=await qH(J),H=XB(G.width,G.height).getContext("2d");return H.drawImage(G,0,0),new this(H.getImageData(0,0,G.width,G.height).data,G.width,G.height,4)}else{let G=OR.default(await J.arrayBuffer());return await qH(G)}}static fromTensor(J,G="CHW"){if(J.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${J.dims.length} dimensions.`);if(G==="CHW")J=J.transpose(1,2,0);else if(G==="HWC");else throw Error(`Unsupported channel format: ${G}`);if(!(J.data instanceof Uint8ClampedArray||J.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${J.type}`);switch(J.dims[2]){case 1:case 2:case 3:case 4:return new Q(J.data,J.dims[1],J.dims[0],J.dims[2]);default:throw Error(`Unsupported number of channels: ${J.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let J=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let G=0,H=0;G<this.data.length;G+=this.channels){let K=this.data[G],z=this.data[G+1],q=this.data[G+2];J[H++]=Math.round(0.2989*K+0.587*z+0.114*q)}break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(J,this.width,this.height,1)}rgb(){if(this.channels===3)return this;let J=new Uint8ClampedArray(this.width*this.height*3);switch(this.channels){case 1:for(let G=0,H=0;G<this.data.length;++G)J[H++]=this.data[G],J[H++]=this.data[G],J[H++]=this.data[G];break;case 4:for(let G=0,H=0;G<this.data.length;G+=4)J[H++]=this.data[G],J[H++]=this.data[G+1],J[H++]=this.data[G+2];break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(J,this.width,this.height,3)}rgba(){if(this.channels===4)return this;let J=new Uint8ClampedArray(this.width*this.height*4);switch(this.channels){case 1:for(let G=0,H=0;G<this.data.length;++G)J[H++]=this.data[G],J[H++]=this.data[G],J[H++]=this.data[G],J[H++]=255;break;case 3:for(let G=0,H=0;G<this.data.length;G+=3)J[H++]=this.data[G],J[H++]=this.data[G+1],J[H++]=this.data[G+2],J[H++]=255;break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this._update(J,this.width,this.height,4)}putAlpha(J){if(J.width!==this.width||J.height!==this.height)throw Error(`Expected mask size to be ${this.width}x${this.height}, but got ${J.width}x${J.height}`);if(J.channels!==1)throw Error(`Expected mask to have 1 channel, but got ${J.channels}`);let G=this.data,H=J.data,K=this.width*this.height;if(this.channels===3){let z=new Uint8ClampedArray(K*4);for(let q=0,F=0,D=0;q<K;++q)z[D++]=G[F++],z[D++]=G[F++],z[D++]=G[F++],z[D++]=H[q];return this._update(z,this.width,this.height,4)}else if(this.channels===4){for(let z=0;z<K;++z)G[4*z+3]=H[z];return this}throw Error(`Expected image to have 3 or 4 channels, but got ${this.channels}`)}async resize(J,G,{resample:H=2}={}){if(this.width===J&&this.height===G)return this;let K=dUQ[H]??H,z=KC0(J),q=KC0(G);if(z&&q)return this;else if(z)J=G/this.height*this.width;else if(q)G=J/this.width*this.height;if(Y6.IS_WEB_ENV){let F=this.channels,D=this.toCanvas(),V=XB(J,G).getContext("2d");return V.drawImage(D,0,0,J,G),new Q(V.getImageData(0,0,J,G).data,J,G,4).convert(F)}else{let F=this.toSharp();switch(K){case"box":case"hamming":if(K==="box"||K==="hamming")g8.warn(`Resampling method ${K} is not yet supported. Using bilinear instead.`),K="bilinear";case"nearest":case"bilinear":case"bicubic":F=F.affine([J/this.width,0,0,G/this.height],{interpolator:K});break;case"lanczos":F=F.resize({width:J,height:G,fit:"fill",kernel:"lanczos3"});break;default:throw Error(`Resampling method ${K} is not supported.`)}return await qH(F)}}async pad([J,G,H,K]){if(J=Math.max(J,0),G=Math.max(G,0),H=Math.max(H,0),K=Math.max(K,0),J===0&&G===0&&H===0&&K===0)return this;if(Y6.IS_WEB_ENV){let z=this.channels,q=this.toCanvas(),F=this.width+J+G,D=this.height+H+K,V=XB(F,D).getContext("2d");return V.drawImage(q,0,0,this.width,this.height,J,H,this.width,this.height),new Q(V.getImageData(0,0,F,D).data,F,D,4).convert(z)}else{let z=this.toSharp().extend({left:J,right:G,top:H,bottom:K});return await qH(z)}}async crop([J,G,H,K]){if(J=Math.max(J,0),G=Math.max(G,0),H=Math.min(H,this.width-1),K=Math.min(K,this.height-1),J===0&&G===0&&H===this.width-1&&K===this.height-1)return this;let z=H-J+1,q=K-G+1;if(Y6.IS_WEB_ENV){let F=this.channels,D=this.toCanvas(),V=XB(z,q).getContext("2d");return V.drawImage(D,J,G,z,q,0,0,z,q),new Q(V.getImageData(0,0,z,q).data,z,q,4).convert(F)}else{let F=this.toSharp().extract({left:J,top:G,width:z,height:q});return await qH(F)}}async center_crop(J,G){if(this.width===J&&this.height===G)return this;let H=(this.width-J)/2,K=(this.height-G)/2;if(Y6.IS_WEB_ENV){let z=this.channels,q=this.toCanvas(),F=XB(J,G).getContext("2d"),D=0,V=0,O=0,P=0;if(H>=0)D=H;else O=-H;if(K>=0)V=K;else P=-K;return F.drawImage(q,D,V,J,G,O,P,J,G),new Q(F.getImageData(0,0,J,G).data,J,G,4).convert(z)}else{let z=this.toSharp();if(H>=0&&K>=0)z=z.extract({left:Math.floor(H),top:Math.floor(K),width:J,height:G});else if(H<=0&&K<=0){let q=Math.floor(-K),F=Math.floor(-H);z=z.extend({top:q,left:F,right:J-this.width-F,bottom:G-this.height-q})}else{let q=[0,0],F=0;if(K<0)q[0]=Math.floor(-K),q[1]=G-this.height-q[0];else F=Math.floor(K);let D=[0,0],V=0;if(H<0)D[0]=Math.floor(-H),D[1]=J-this.width-D[0];else V=Math.floor(H);z=z.extend({top:q[0],bottom:q[1],left:D[0],right:D[1]}).extract({left:V,top:F,width:J,height:G})}return await qH(z)}}async toBlob(J="image/png",G=1){if(!Y6.IS_WEB_ENV)throw Error("toBlob() is only supported in browser environments.");return await this.toCanvas().convertToBlob({type:J,quality:G})}toTensor(J="CHW"){let G=new PQ("uint8",new Uint8Array(this.data),[this.height,this.width,this.channels]);if(J==="HWC");else if(J==="CHW")G=G.permute(2,0,1);else throw Error(`Unsupported channel format: ${J}`);return G}toCanvas(){if(!Y6.IS_WEB_ENV)throw Error("toCanvas() is only supported in browser environments.");let J=this.clone().rgba(),G=XB(J.width,J.height),H=new Rw0(J.data,J.width,J.height);return G.getContext("2d").putImageData(H,0,0),G}split(){let{data:J,width:G,height:H,channels:K}=this,z=J.constructor,q=J.length/K,F=Array.from({length:K},()=>new z(q));for(let D=0;D<q;++D){let V=K*D;for(let O=0;O<K;++O)F[O][D]=J[V+O]}return F.map((D)=>new Q(D,G,H,1))}_update(J,G,H,K=null){if(this.data=J,this.width=G,this.height=H,K!==null)this.channels=K;return this}clone(){return new Q(this.data.slice(),this.width,this.height,this.channels)}convert(J){if(this.channels===J)return this;switch(J){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(J){if(Y6.IS_WEB_ENV){if(Y6.IS_WEBWORKER_ENV)throw Error("Unable to save an image from a Web Worker.");let G=J.split(".").pop().toLowerCase(),H=cUQ.get(G)??"image/png",K=await this.toBlob(H);return Dw0(J,K)}else if(Y6.IS_FS_AVAILABLE)await this.toSharp().toFile(J);else throw Error("Unable to save the image because filesystem is disabled in this environment.")}toSharp(){if(Y6.IS_WEB_ENV)throw Error("toSharp() is only supported in server-side environments.");return OR.default(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}},vz8=gG.read.bind(gG);function DI0(Q,J,G=0,H=null){let K=Q/J,z=PVQ(K)*J;if(H!==null&&z>H)z=Math.floor(K)*J;if(z<G)z=Math.ceil(K)*J;return z}function MI0([Q,J],G){return[Math.max(Math.floor(Q/G),1)*G,Math.max(Math.floor(J/G),1)*G]}function ww0([Q,J,G,H]){return[Q-G/2,J-H/2,Q+G/2,J+H/2]}function TR(Q,J=0.5,G=null,H=!1){let{logits:K,pred_boxes:z}=Q,[q,F,D]=K.dims;if(G!==null&&G.length!==q)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let V=[];for(let O=0;O<q;++O){let P=G!==null?G[O]:null,N={boxes:[],classes:[],scores:[]},I=K[O],R=z[O];for(let w=0;w<F;++w){let E=I[w],T=[],y;if(H){y=E.sigmoid().data;for(let x=0;x<y.length;++x)if(y[x]>J)T.push(x)}else{let x=D7(E.data)[1];if(x===D-1)continue;if(y=wX(E.data),y[x]<J)continue;T.push(x)}for(let x of T){let b=R[w].data;if(b=ww0(b),P!==null)b=b.map((g,l)=>g*P[(l+1)%2]);N.boxes.push(b),N.classes.push(x),N.scores.push(y[x])}}V.push(N)}return V}function Ew0(Q,J=null){let G=Q.logits,H=G.dims[0];if(J!==null&&J.length!==H)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let K=[];for(let z=0;z<H;++z){let q=J!==null?J[z]:null,F=G[z];if(q!==null)F=Jw0(F,q,"bilinear",!1);let[D,V]=q??F.dims.slice(-2),O=new PQ("int32",new Int32Array(D*V),[D,V]),P=F[0].data,N=O.data;for(let w=1;w<F.dims[0];++w){let E=F[w].data;for(let T=0;T<E.length;++T)if(E[T]>P[T])P[T]=E[T],N[T]=w}let I=Array(F.dims[0]);for(let w=0;w<N.length;++w){let E=N[w];I[E]=E}let R=I.filter((w)=>w!==void 0);K.push({segmentation:O,labels:R})}return K}function iUQ(Q,J,G,H){let K=[],z=[],q=[];for(let F=0;F<Q.dims[0];++F){let D=Q[F],V=J[F],O=D7(D.data)[1];if(O===H)continue;let N=wX(D.data)[O];if(N>G)K.push(V),z.push(N),q.push(O)}return[K,z,q]}function oUQ(Q,J,G,H=0.5,K=0.8){let z=[],q=0,F=0,D=J[G].data;for(let O=0;O<Q.length;++O){if(Q[O]===G)z.push(O),++q;if(D[O]>=H)++F}let V=q>0&&F>0;if(V)V=q/F>K;return[V,z]}function nUQ(Q,J,G,H,K,z=null,q=null){let[F,D]=q??Q[0].dims,V=new PQ("int32",new Int32Array(F*D),[F,D]),O=[];if(q!==null)for(let w=0;w<Q.length;++w)Q[w]=Jw0(Q[w],q,"bilinear",!1);let P=new Int32Array(Q[0].data.length),N=new Float32Array(Q[0].data.length);for(let w=0;w<Q.length;++w){let E=J[w],T=Q[w].data;for(let y=0;y<T.length;++y)if(T[y]*=E,T[y]>N[y])P[y]=w,N[y]=T[y]}let I=0,R=V.data;for(let w=0;w<G.length;++w){let E=G[w],[T,y]=oUQ(P,Q,w,H,K);if(!T)continue;++I;for(let x of y)R[x]=I;O.push({id:I,label_id:E,score:J[w]})}return[V,O]}function r90(Q,J,G=28,H=3136,K=1003520,z=1){if(Q<G||J<G){let D=Math.max(G/Q,G/J);Q=Math.round(Q*D),J=Math.round(J*D)}if(Math.max(Q,J)/Math.min(Q,J)>200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(Q,J)/Math.min(Q,J)}`);let q=Math.round(Q/G)*G,F=Math.round(J/G)*G;if(z*q*F>K){let D=Math.sqrt(z*Q*J/K);q=Math.max(G,Math.floor(Q/D/G)*G),F=Math.max(G,Math.floor(J/D/G)*G)}else if(z*q*F<H){let D=Math.sqrt(H/(z*Q*J));q=Math.ceil(Q*D/G)*G,F=Math.ceil(J*D/G)*G}return[F,q]}function Sw0(Q,J=0.5,G=0.5,H=0.8,K=null,z=null){if(K===null)g8.warn("`label_ids_to_fuse` unset. No instance will be fused."),K=new Set;let q=Q.class_queries_logits??Q.logits,D=(Q.masks_queries_logits??Q.pred_masks).sigmoid(),[V,O,P]=q.dims;if(P-=1,z!==null&&z.length!==V)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let N=[];for(let I=0;I<V;++I){let R=z!==null?z[I]:null,w=q[I],E=D[I],[T,y,x]=iUQ(w,E,J,P);if(x.length===0){let[l,_]=R??E.dims.slice(-2),a=new PQ("int32",new Int32Array(l*_).fill(-1),[l,_]);N.push({segmentation:a,segments_info:[]});continue}let[b,g]=nUQ(T,y,x,G,H,K,R);N.push({segmentation:b,segments_info:g})}return N}function Tw0(Q,J=0.5,G=null){throw Error("`post_process_instance_segmentation` is not yet implemented.")}var p8=class extends nJ{constructor(Q){super();if(this.image_mean=Q.image_mean??Q.mean,this.image_std=Q.image_std??Q.std,this.resample=Q.resample??2,this.do_rescale=Q.do_rescale??!0,this.rescale_factor=Q.rescale_factor??0.00392156862745098,this.do_normalize=Q.do_normalize,this.do_thumbnail=Q.do_thumbnail,this.size=Q.size??Q.image_size,this.do_resize=Q.do_resize??this.size!==void 0,this.size_divisibility=Q.size_divisibility??Q.size_divisor,this.do_center_crop=Q.do_center_crop,this.crop_size=Q.crop_size,this.do_convert_rgb=Q.do_convert_rgb??!0,this.do_crop_margin=Q.do_crop_margin,this.pad_size=Q.pad_size,this.do_pad=Q.do_pad,this.min_pixels=Q.min_pixels,this.max_pixels=Q.max_pixels,this.do_pad&&!this.pad_size&&!this.size_divisibility&&this.size&&this.size.width!==void 0&&this.size.height!==void 0)this.pad_size=this.size;this.do_flip_channel_order=Q.do_flip_channel_order??!1,this.config=Q}async thumbnail(Q,J,G=2){let{height:H,width:K}=Q,z=J.height,q=J.width,F=Math.min(H,z),D=Math.min(K,q);if(F===H&&D===K)return Q;if(H>K)D=Math.floor(K*F/H);else if(K>H)F=Math.floor(H*D/K);return await Q.resize(D,F,{resample:G})}async crop_margin(Q,J=200){let G=Q.clone().grayscale(),H=G90(G.data)[0],z=D7(G.data)[0]-H;if(z===0)return Q;let q=J/255,F=G.width,D=G.height,V=0,O=0,P=G.data;for(let N=0;N<G.height;++N){let I=N*G.width;for(let R=0;R<G.width;++R)if((P[I+R]-H)/z<q)F=Math.min(F,R),D=Math.min(D,N),V=Math.max(V,R),O=Math.max(O,N)}return Q=await Q.crop([F,D,V,O]),Q}pad_image(Q,J,G,{mode:H="constant",center:K=!1,constant_values:z=0}={}){let[q,F,D]=J,V,O;if(typeof G==="number")V=G,O=G;else if(G==="square")V=O=Math.max(q,F);else V=G.width,O=G.height;if(V!==F||O!==q){let P=new Float32Array(V*O*D);if(Array.isArray(z))for(let R=0;R<P.length;++R)P[R]=z[R%D];else if(z!==0)P.fill(z);let[N,I]=K?[Math.floor((V-F)/2),Math.floor((O-q)/2)]:[0,0];for(let R=0;R<q;++R){let w=(R+I)*V,E=R*F;for(let T=0;T<F;++T){let y=(w+T+N)*D,x=(E+T)*D;for(let b=0;b<D;++b)P[y+b]=Q[x+b]}}if(H==="symmetric"){if(K)throw Error("`center` padding is not supported when `mode` is set to `symmetric`.");let R=q-1,w=F-1;for(let E=0;E<O;++E){let T=E*V,y=zR(E,R)*F;for(let x=0;x<V;++x){if(E<q&&x<F)continue;let b=(T+x)*D,g=(y+zR(x,w))*D;for(let l=0;l<D;++l)P[b+l]=Q[g+l]}}}Q=P,J=[O,V,D]}return[Q,J]}rescale(Q){for(let J=0;J<Q.length;++J)Q[J]=this.rescale_factor*Q[J]}get_resize_output_image_size(Q,J){let[G,H]=Q.size,K,z;if(this.do_thumbnail){let{height:q,width:F}=J;K=Math.min(q,F)}else if(Number.isInteger(J))K=J,z=this.config.max_size??K;else if(J!==void 0)K=J.shortest_edge,z=J.longest_edge;if(K!==void 0||z!==void 0){let q=K===void 0?1:Math.max(K/G,K/H),F=G*q,D=H*q,V=z===void 0?1:Math.min(z/F,z/D),O=Math.floor(Number((F*V).toFixed(2))),P=Math.floor(Number((D*V).toFixed(2)));if(this.size_divisibility!==void 0)[O,P]=MI0([O,P],this.size_divisibility);return[O,P]}else if(J!==void 0&&J.width!==void 0&&J.height!==void 0){let{width:q,height:F}=J;if(this.config.keep_aspect_ratio&&this.config.ensure_multiple_of){let D=F/H,V=q/G;if(Math.abs(1-V)<Math.abs(1-D))D=V;else V=D;F=DI0(D*H,this.config.ensure_multiple_of),q=DI0(V*G,this.config.ensure_multiple_of)}return[q,F]}else if(this.size_divisibility!==void 0)return MI0([G,H],this.size_divisibility);else throw Error(`Could not resize image due to unsupported \`this.size\` option in config: ${JSON.stringify(J)}`)}async resize(Q){let[J,G]=this.get_resize_output_image_size(Q,this.size);return await Q.resize(J,G,{resample:this.resample})}async preprocess(Q,{do_normalize:J=null,do_pad:G=null,do_convert_rgb:H=null,do_convert_grayscale:K=null,do_flip_channel_order:z=null}={}){if(this.do_crop_margin)Q=await this.crop_margin(Q);let[q,F]=Q.size;if(H??this.do_convert_rgb)Q=Q.rgb();else if(K)Q=Q.grayscale();if(this.do_resize)Q=await this.resize(Q);if(this.do_thumbnail)Q=await this.thumbnail(Q,this.size,this.resample);if(this.do_center_crop){let N,I;if(Number.isInteger(this.crop_size))N=this.crop_size,I=this.crop_size;else N=this.crop_size.width,I=this.crop_size.height;Q=await Q.center_crop(N,I)}let D=[Q.height,Q.width],V=Float32Array.from(Q.data),O=[Q.height,Q.width,Q.channels];if(this.do_rescale)this.rescale(V);if(J??this.do_normalize){let N=this.image_mean;if(!Array.isArray(this.image_mean))N=Array(Q.channels).fill(N);let I=this.image_std;if(!Array.isArray(this.image_std))I=Array(Q.channels).fill(I);if(N.length!==Q.channels||I.length!==Q.channels)throw Error(`When set to arrays, the length of \`image_mean\` (${N.length}) and \`image_std\` (${I.length}) must match the number of channels in the image (${Q.channels}).`);for(let R=0;R<V.length;R+=Q.channels)for(let w=0;w<Q.channels;++w)V[R+w]=(V[R+w]-N[w])/I[w]}if(G??this.do_pad){if(this.pad_size)[V,O]=this.pad_image(V,[Q.height,Q.width,Q.channels],this.pad_size);else if(this.size_divisibility){let N=Math.ceil(O[1]/this.size_divisibility)*this.size_divisibility,I=Math.ceil(O[0]/this.size_divisibility)*this.size_divisibility;[V,O]=this.pad_image(V,O,{width:N,height:I})}}if(z??this.do_flip_channel_order){if(O[2]!==3)throw Error("Flipping channel order is only supported for RGB images.");for(let N=0;N<V.length;N+=3){let I=V[N];V[N]=V[N+2],V[N+2]=I}}let P=new PQ("float32",V,O).permute(2,0,1);return{original_size:[F,q],reshaped_input_size:D,pixel_values:P}}async _call(Q,...J){if(!Array.isArray(Q))Q=[Q];let G=await Promise.all(Q.map((K)=>this.preprocess(K)));return{pixel_values:g5(G.map((K)=>K.pixel_values),0),original_sizes:G.map((K)=>K.original_size),reshaped_input_sizes:G.map((K)=>K.reshaped_input_size)}}static async from_pretrained(Q,J={}){let G=await bW(Q,hF,!0,J);return new this(G)}},PR={};IV(PR,{BeitFeatureExtractor:()=>aUQ,BitImageProcessor:()=>sUQ,CHMv2ImageProcessor:()=>tUQ,CLIPFeatureExtractor:()=>eUQ,CLIPImageProcessor:()=>kw0,ChineseCLIPFeatureExtractor:()=>rUQ,ConvNextFeatureExtractor:()=>Q$Q,ConvNextImageProcessor:()=>yw0,DINOv3ViTImageProcessor:()=>Y$Q,DPTFeatureExtractor:()=>W$Q,DPTImageProcessor:()=>bw0,DeiTFeatureExtractor:()=>X$Q,DeiTImageProcessor:()=>vw0,DetrFeatureExtractor:()=>J$Q,DetrImageProcessor:()=>xw0,DonutFeatureExtractor:()=>G$Q,DonutImageProcessor:()=>t90,EfficientNetImageProcessor:()=>H$Q,GLPNFeatureExtractor:()=>V$Q,Gemma3ImageProcessor:()=>B$Q,Gemma4ImageProcessor:()=>gw0,Glm46VImageProcessor:()=>z$Q,GroundingDinoImageProcessor:()=>q$Q,Idefics3ImageProcessor:()=>LI0,ImageFeatureExtractor:()=>p8,ImageProcessor:()=>p8,JinaCLIPImageProcessor:()=>$$Q,Lfm2VlImageProcessor:()=>L$Q,LlavaOnevisionImageProcessor:()=>O$Q,Mask2FormerImageProcessor:()=>N$Q,MaskFormerFeatureExtractor:()=>P$Q,MaskFormerImageProcessor:()=>e90,MobileNetV1FeatureExtractor:()=>j$Q,MobileNetV1ImageProcessor:()=>_w0,MobileNetV2FeatureExtractor:()=>C$Q,MobileNetV2ImageProcessor:()=>fw0,MobileNetV3FeatureExtractor:()=>I$Q,MobileNetV3ImageProcessor:()=>mw0,MobileNetV4FeatureExtractor:()=>R$Q,MobileNetV4ImageProcessor:()=>uw0,MobileViTFeatureExtractor:()=>w$Q,MobileViTImageProcessor:()=>pw0,NougatImageProcessor:()=>E$Q,OwlViTFeatureExtractor:()=>S$Q,OwlViTImageProcessor:()=>Q10,Owlv2ImageProcessor:()=>T$Q,Phi3VImageProcessor:()=>y$Q,PixtralImageProcessor:()=>v$Q,PvtImageProcessor:()=>x$Q,Qwen2VLImageProcessor:()=>hw0,RTDetrImageProcessor:()=>b$Q,Sam2ImageProcessor:()=>t60,Sam3ImageProcessor:()=>t60,SamImageProcessor:()=>t60,SapiensFeatureExtractor:()=>g$Q,SapiensImageProcessor:()=>lw0,SegformerFeatureExtractor:()=>h$Q,SegformerImageProcessor:()=>dw0,SiglipImageProcessor:()=>_$Q,SmolVLMImageProcessor:()=>LI0,Swin2SRImageProcessor:()=>f$Q,VLMImageProcessor:()=>U$Q,ViTFeatureExtractor:()=>m$Q,ViTImageProcessor:()=>cw0,VitMatteImageProcessor:()=>u$Q,VitPoseImageProcessor:()=>p$Q,YolosFeatureExtractor:()=>l$Q,YolosImageProcessor:()=>iw0});var aUQ=class extends p8{},sUQ=class extends p8{},rUQ=class extends p8{},tUQ=class extends p8{},kw0=class extends p8{},eUQ=class extends kw0{},yw0=class extends p8{constructor(Q){super(Q);this.crop_pct=this.config.crop_pct??0.875}async resize(Q){let J=this.size?.shortest_edge;if(J===void 0)throw Error("Size dictionary must contain 'shortest_edge' key.");if(J<384){let G=Math.floor(J/this.crop_pct),[H,K]=this.get_resize_output_image_size(Q,{shortest_edge:G});Q=await Q.resize(H,K,{resample:this.resample}),Q=await Q.center_crop(J,J)}else Q=await Q.resize(J,J,{resample:this.resample});return Q}},Q$Q=class extends yw0{},vw0=class extends p8{},X$Q=class extends vw0{},xw0=class extends p8{async _call(Q){let J=await super._call(Q),G=[J.pixel_values.dims[0],64,64],H=sX(G,1n);return{...J,pixel_mask:H}}post_process_object_detection(...Q){return TR(...Q)}post_process_panoptic_segmentation(...Q){return Sw0(...Q)}post_process_instance_segmentation(...Q){return Tw0(...Q)}},J$Q=class extends xw0{},Y$Q=class extends p8{},t90=class extends p8{pad_image(Q,J,G,H={}){let[K,z,q]=J,F=this.image_mean;if(!Array.isArray(this.image_mean))F=Array(q).fill(F);let D=this.image_std;if(!Array.isArray(D))D=Array(q).fill(F);let V=F.map((O,P)=>-O/D[P]);return super.pad_image(Q,J,G,{center:!0,constant_values:V,...H})}},G$Q=class extends t90{},bw0=class extends p8{},W$Q=class extends bw0{},H$Q=class extends p8{constructor(Q){super(Q);if(this.include_top=this.config.include_top??!0,this.include_top)this.image_std=this.image_std.map((J)=>J*J)}},B$Q=class extends p8{};function A$Q(Q,J,G,H,K){let z=H*G**2,q=Math.sqrt(z/(Q*J)),F=K*G,D=Math.floor(q*Q/F)*F,V=Math.floor(q*J/F)*F;if(D===0&&V===0)throw Error(`Attempting to resize to a 0 x 0 image. Resized height should be divisible by \`pooling_kernel_size * patch_size\`=${F}.`);let O=Math.floor(H/K**2)*F;if(D===0)D=F,V=Math.min(Math.floor(J/Q)*F,O);else if(V===0)V=F,D=Math.min(Math.floor(Q/J)*F,O);return[D,V]}function K$Q(Q,J,G,H,K,z,q){let F=Math.floor(J/K),D=Math.floor(G/K),V=F*D,O=K*K*H,P=new Float32Array(z*O),N=0;for(let w=0;w<F;++w)for(let E=0;E<D;++E)for(let T=0;T<K;++T){let y=(w*K+T)*G*H+E*K*H;for(let x=0;x<K;++x){let b=y+x*H;for(let g=0;g<H;++g)P[N++]=Q[b+g]}}let I=new BigInt64Array(z*2).fill(-1n),R=0;for(let w=0;w<F;++w)for(let E=0;E<D;++E)I[R++]=BigInt(E),I[R++]=BigInt(w);return{patches:new PQ("float32",P,[z,O]),positions:new PQ("int64",I,[z,2]),num_soft_tokens:Math.floor(V/q**2)}}var gw0=class extends nJ{constructor(Q){super();this.config=Q,this.patch_size=Q.patch_size??16,this.max_soft_tokens=Q.max_soft_tokens??280,this.pooling_kernel_size=Q.pooling_kernel_size??3,this.resample=Q.resample??3,this.rescale_factor=Q.rescale_factor??0.00392156862745098,this.do_rescale=Q.do_rescale??!0,this.do_resize=Q.do_resize??!0,this.do_convert_rgb=Q.do_convert_rgb??!0}async _call(Q){if(!Array.isArray(Q))Q=[Q];let{patch_size:J,pooling_kernel_size:G}=this,H=this.max_soft_tokens*G**2,K=[],z=[],q=[];for(let F of Q){if(this.do_convert_rgb)F=F.rgb();if(this.do_resize){let[N,I]=A$Q(F.height,F.width,J,H,G);if(N!==F.height||I!==F.width)F=await F.resize(I,N,{resample:this.resample})}let D=Float32Array.from(F.data);if(this.do_rescale)for(let N=0;N<D.length;++N)D[N]*=this.rescale_factor;let{patches:V,positions:O,num_soft_tokens:P}=K$Q(D,F.height,F.width,F.channels,J,H,G);K.push(V),z.push(O),q.push(P)}return{pixel_values:g5(K,0),image_position_ids:g5(z,0),num_soft_tokens_per_image:q}}},hw0=class extends p8{constructor(Q){super(Q);this.min_pixels=Q.min_pixels??Q.size?.shortest_edge,this.max_pixels=Q.max_pixels??Q.size?.longest_edge,this.patch_size=Q.patch_size,this.merge_size=Q.merge_size}get_resize_output_image_size(Q,J){let G=this.patch_size*this.merge_size;return r90(Q.height,Q.width,G,this.min_pixels,this.max_pixels)}async _call(Q,...J){let{pixel_values:G,original_sizes:H,reshaped_input_sizes:K}=await super._call(Q,...J),z=G,{temporal_patch_size:q,merge_size:F,patch_size:D}=this.config;if(z.dims[0]===1)z=T9(Array.from({length:q},()=>z),0);let V=z.dims[0]/q,O=z.dims[1],P=Math.floor(z.dims[2]/D),N=Math.floor(z.dims[3]/D),I=z.view(V,q,O,Math.floor(P/F),F,D,Math.floor(N/F),F,D).permute(0,3,6,4,7,2,1,5,8).view(V*P*N,O*q*D*D),R=new PQ("int64",[V,P,N],[1,3]);return{pixel_values:I,image_grid_thw:R,original_sizes:H,reshaped_input_sizes:K}}},z$Q=class extends hw0{get_resize_output_image_size(Q,J){let G=this.patch_size*this.merge_size,H=this.config.temporal_patch_size??2;return r90(Q.height,Q.width,G,this.min_pixels,this.max_pixels,H)}},V$Q=class extends p8{},q$Q=class extends p8{async _call(Q){let J=await super._call(Q),G=J.pixel_values.dims,H=oJ([G[0],G[2],G[3]]);return{...J,pixel_mask:H}}},LI0=class extends p8{constructor(Q){super(Q);this.do_image_splitting=Q.do_image_splitting??!0,this.max_image_size=Q.max_image_size}get_resize_for_vision_encoder(Q,J){let[G,H]=Q.dims.slice(-2),K=H/G;if(H>=G)H=Math.ceil(H/J)*J,G=Math.floor(H/K),G=Math.ceil(G/J)*J;else G=Math.ceil(G/J)*J,H=Math.floor(G*K),H=Math.ceil(H/J)*J;return{height:G,width:H}}async _call(Q,{do_image_splitting:J=null,return_row_col_info:G=!1}={}){let H;if(!Array.isArray(Q))H=[[Q]];else{if(Q.length===0||!Q[0])throw Error("No images provided.");if(!Array.isArray(Q[0]))H=[Q];else H=Q}let K=[],z=[],q=[],F=[],D=[];for(let E of H){let T=await Promise.all(E.map((b)=>this.preprocess(b)));F.push(...T.map((b)=>b.original_size)),D.push(...T.map((b)=>b.reshaped_input_size)),T.forEach((b)=>b.pixel_values.unsqueeze_(0));let{longest_edge:y}=this.max_image_size,x;if(J??this.do_image_splitting){let b=Array(T.length),g=Array(T.length);x=await Promise.all(T.map(async(l,_)=>{let a=this.get_resize_for_vision_encoder(l.pixel_values,y),r=await bG(l.pixel_values,{size:[a.height,a.width]}),{frames:f0,num_splits_h:t,num_splits_w:p0}=await this.split_image(r,this.max_image_size);return b[_]=t,g[_]=p0,T9(f0,0)})),z.push(b),q.push(g)}else{let b=[y,y];x=await Promise.all(T.map((g)=>bG(g.pixel_values,{size:b}))),z.push(Array(T.length).fill(0)),q.push(Array(T.length).fill(0))}K.push(T9(x,0))}let V=K.length,[O,P,N,I]=K[0].dims,R,w;if(V===1)R=K[0].unsqueeze_(0),w=sX([V,O,N,I],!0);else{let E=Math.max(...K.map((x)=>x.dims.at(0)));w=sX([V,E,N,I],!0);let T=w.data,y=E*N*I;for(let x=0;x<V;++x){let b=K[x].dims[0];if(b<E){K[x]=T9([K[x],sX([E-b,P,N,I],0)],0);let g=x*y+b*N*I,l=(x+1)*y;T.fill(!1,g,l)}}R=g5(K,0)}return{pixel_values:R,pixel_attention_mask:w,original_sizes:F,reshaped_input_sizes:D,...G?{rows:z,cols:q}:{}}}async split_image(Q,{longest_edge:J}){let G=J,H=J,K=[],[z,q]=Q.dims.slice(-2),F=0,D=0;if(z>G||q>H){F=Math.ceil(z/G),D=Math.ceil(q/H);let V=Math.ceil(z/F),O=Math.ceil(q/D);for(let I=0;I<F;++I)for(let R=0;R<D;++R){let w,E,T,y;if(I===F-1)E=z-V,y=z;else E=I*V,y=(I+1)*V;if(R===D-1)w=q-O,T=q;else w=R*O,T=(R+1)*O;let g=await Yw0(Q,[E,w],[y,T],[2,3]);K.push(g)}let P=G,N=H;if(z!==P||q!==N)Q=await bG(Q,{size:[P,N]})}return K.push(Q),{frames:K,num_splits_h:F,num_splits_w:D}}},U$Q=class extends p8{constructor(Q){super({do_pad:!0,pad_size:{width:Q.image_size,height:Q.image_size},...Q});this.constant_values=this.config.background_color.map((J)=>J*this.rescale_factor)}pad_image(Q,J,G,H){return super.pad_image(Q,J,G,{constant_values:this.constant_values,center:!0,...H})}},$$Q=class extends p8{constructor(Q){let{resize_mode:J,fill_color:G,interpolation:H,size:K,...z}=Q,q=J==="squash"?{width:K,height:K}:J==="shortest"?{shortest_edge:K}:{longest_edge:K},F=H==="bicubic"?3:2;super({...z,size:q,resample:F,do_center_crop:!0,crop_size:K,do_normalize:!0})}};function OI0(Q,J){return Math.round(Q/J)*J}function Z$Q(Q,J,G,H,K){let z=1/0,q=[1,1],F=G*H;for(let D of J){let V=Math.abs(Q-D[0]/D[1]);if(V<z)z=V,q=D;else if(V===z&&F>0.5*K*K*D[0]*D[1])q=D}return q}function F$Q(Q,J){let G=[],H=new Set;for(let K=Q;K<=J;++K)for(let z=1;z<=K;++z)for(let q=1;q<=K;++q){let F=z*q;if(F>=Q&&F<=J){let D=z<<16|q;if(!H.has(D))H.add(D),G.push([z,q])}}return G.sort((K,z)=>K[0]*K[1]-z[0]*z[1])}function D$Q(Q,J){let[G,H,K,z]=Q.dims,q=Math.floor(K/J),F=Math.floor(z/J),D=J*J*H,V=Q.data,O=new Float32Array(G*q*F*D),P=K*z;for(let N=0;N<G;++N){let I=N*H*P,R=N*q*F*D;for(let w=0;w<q;++w)for(let E=0;E<F;++E){let T=R+(w*F+E)*D;for(let y=0;y<J;++y){let x=(w*J+y)*z+E*J;for(let b=0;b<J;++b){let g=x+b;for(let l=0;l<H;++l)O[T++]=V[I+l*P+g]}}}}return new PQ("float32",O,[G,q*F,D])}function M$Q(Q,J){let[,G,H]=Q.dims,K=new BigInt64Array(J);K.fill(1n,0,G);let z=Q;if(G<J){let q=new Float32Array(J*H);q.set(Q.data),z=new PQ("float32",q,[1,J,H])}return{padded:z,mask:new PQ("int64",K,[J])}}var L$Q=class extends p8{constructor(Q){super(Q);this.downsample_factor=Q.downsample_factor??2,this.do_image_splitting=Q.do_image_splitting??!0,this.min_tiles=Q.min_tiles??2,this.max_tiles=Q.max_tiles??10,this.use_thumbnail=Q.use_thumbnail??!0,this.min_image_tokens=Q.min_image_tokens??64,this.max_image_tokens=Q.max_image_tokens??256,this.encoder_patch_size=Q.encoder_patch_size??Q.patch_size??16,this.tile_size=Q.tile_size??512,this.max_pixels_tolerance=Q.max_pixels_tolerance??2,this.return_row_col_info=Q.return_row_col_info??!1;let J=this.max_image_tokens*this.downsample_factor**2,G=this.do_image_splitting?(this.tile_size/this.encoder_patch_size)**2:0;this.max_num_patches=Math.max(J,G)}_is_image_too_large(Q,J){let G=this.encoder_patch_size*this.downsample_factor,H=Math.max(this.encoder_patch_size,OI0(Q,G)),K=Math.max(this.encoder_patch_size,OI0(J,G));return H*K>this.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(Q,J){let G=F$Q(this.min_tiles,this.max_tiles),[H,K]=Z$Q(J/Q,G,J,Q,this.tile_size);return{grid_width:H,grid_height:K,target_width:this.tile_size*H,target_height:this.tile_size*K}}async _call(Q,{return_row_col_info:J=null}={}){let G;if(!Array.isArray(Q))G=[[Q]];else if(!Array.isArray(Q[0]))G=[Q];else G=Q;let H=[],K=[],z=[],q=[],F=[],D=[];for(let O of G){let P=await Promise.all(O.map((N)=>this.preprocess(N,{do_pad:!1})));for(let{pixel_values:N}of P){let[,I,R]=N.dims,w=N.unsqueeze_(0),E=this.encoder_patch_size*this.downsample_factor,T=E**2,[y,x]=r90(Math.max(E,I),Math.max(E,R),E,this.min_image_tokens*T,this.max_image_tokens*T).map((r)=>Math.max(E,r)),b,g=1,l=1,_=this._is_image_too_large(I,R),a=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(_&&a){let{grid_width:r,grid_height:f0,target_width:t,target_height:p0}=this._get_grid_layout(I,R);g=f0,l=r;let u0=await bG(w,{size:[p0,t]});b=[];for(let d=0;d<f0;++d)for(let n=0;n<r;++n){let c0=d*this.tile_size,WQ=n*this.tile_size;b.push(u0.slice(null,null,[c0,c0+this.tile_size],[WQ,WQ+this.tile_size]))}if(this.use_thumbnail&&r*f0!==1)b.push(await bG(w,{size:[x,y]}))}else b=[await bG(w,{size:[x,y]})];for(let r of b){let[,,f0,t]=r.dims,p0=D$Q(r,this.encoder_patch_size),{padded:u0,mask:d}=M$Q(p0,this.max_num_patches);H.push(u0),K.push(d),z.push([Math.floor(f0/this.encoder_patch_size),Math.floor(t/this.encoder_patch_size)])}q.push(g),F.push(l),D.push([x,y])}}let V={pixel_values:T9(H,0),pixel_attention_mask:g5(K,0),spatial_shapes:new PQ("int64",BigInt64Array.from(z.flat(),BigInt),[z.length,2])};if(J??this.return_row_col_info)V.image_rows=q,V.image_cols=F,V.image_sizes=D;return V}},O$Q=class extends p8{},e90=class extends p8{post_process_panoptic_segmentation(...Q){return Sw0(...Q)}post_process_instance_segmentation(...Q){return Tw0(...Q)}},P$Q=class extends e90{},N$Q=class extends e90{},_w0=class extends p8{},j$Q=class extends _w0{},fw0=class extends p8{},C$Q=class extends fw0{},mw0=class extends p8{},I$Q=class extends mw0{},uw0=class extends p8{},R$Q=class extends uw0{},pw0=class extends p8{},w$Q=class extends pw0{},E$Q=class extends t90{},Q10=class extends p8{post_process_object_detection(...Q){return TR(...Q)}},S$Q=class extends Q10{},T$Q=class extends Q10{},$Y=336,k$Q=[2,3],{ceil:s60,floor:UV,sqrt:r60}=Math,y$Q=class extends p8{constructor(Q){super({...Q,do_normalize:!0,do_pad:!0,pad_size:"custom",do_convert_rgb:!0,do_resize:!0});this._num_crops=Q.num_crops}calc_num_image_tokens_from_image_size(Q,J){let{num_img_tokens:G}=this.config;return UV((UV(J/$Y)*UV(Q/$Y)+1)*G+1+(UV(J/$Y)+1)*r60(G))}get_resize_output_image_size(Q,J){let G=this._num_crops,[H,K]=Q.size,z=H/K,q=1;while(q*Math.ceil(q/z)<=G)q+=1;q-=1;let F=Math.floor(q*336),D=Math.floor(F/z);return[F,D]}pad_image(Q,J,G,H={}){let[K,z]=J,q=$Y*s60(K/$Y),F=$Y*s60(z/$Y),D=[1,1,1].map((V,O)=>(V-this.image_mean[O])/this.image_std[O]);return super.pad_image(Q,J,{width:F,height:q},{center:!0,constant_values:D,...H})}async _call(Q,{num_crops:J=null}={}){if(this._num_crops=J??=this.config.num_crops,J<4||r60(J)%1!==0)throw Error("num_crops must be a square number >= 4");if(!Array.isArray(Q))Q=[Q];let G=Q.length,H=await Promise.all(Q.map((P)=>this.preprocess(P))),K=H.map((P)=>P.original_size),z=H.map((P)=>P.reshaped_input_size),q=[];for(let{pixel_values:P}of H){P.unsqueeze_(0);let[N,I]=P.dims.slice(-2),R=await bG(P,{size:[$Y,$Y],mode:"bicubic"});if(J>0){let w=[],E=r60(J),T=UV(I/E),y=UV(N/E);for(let b=0;b<E;++b)for(let g=0;g<E;++g){let l,_,a,r;if(b===E-1)_=N-y,r=N;else _=b*y,r=(b+1)*y;if(g===E-1)l=I-T,a=I;else l=g*T,a=(g+1)*T;let p0=await Yw0(P,[_,l],[r,a],k$Q);w.push(p0)}let x=await bG(T9(w,0),{size:[$Y,$Y],mode:"bicubic"});q.push(T9([R,x],0))}else q.push(R)}let F=g5(q,0),D=z.map((P)=>P.map((N)=>$Y*s60(N/$Y))),V=new PQ("int64",D.flat(),[G,2]),O=D.map(([P,N])=>this.calc_num_image_tokens_from_image_size(N,P));return{pixel_values:F,original_sizes:K,reshaped_input_sizes:z,image_sizes:V,num_img_tokens:O}}},v$Q=class extends p8{get_resize_output_image_size(Q,J){let{longest_edge:G}=J;if(G===void 0)throw Error("size must contain 'longest_edge'");let[H,K]=Q.size,z=Math.max(H,K)/G,q=H,F=K;if(z>1)q=Math.floor(H/z),F=Math.floor(K/z);let{patch_size:D,spatial_merge_size:V}=this.config;if(!V)throw Error("config must contain 'spatial_merge_size'");let O=D*V,P=Math.floor((q-1)/O)+1,N=Math.floor((F-1)/O)+1;return[P*O,N*O]}},x$Q=class extends p8{},b$Q=class extends p8{post_process_object_detection(...Q){return TR(...Q)}},t60=class extends p8{reshape_input_points(Q,J,G,H=!1){Q=structuredClone(Q);let K=zC0(Q);if(K.length===3){if(!H)K=[1,...K];Q=[Q]}else if(K.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 z=0;z<Q.length;++z){let[q,F]=J[z],[D,V]=G[z],O=[V/F,D/q];for(let P=0;P<Q[z].length;++P)for(let N=0;N<Q[z][P].length;++N)for(let I=0;I<Q[z][P][N].length;++I)Q[z][P][N][I]*=O[I%2]}return new PQ("float32",Float32Array.from(Q.flat(1/0)),K)}add_input_labels(Q,J){let G=zC0(Q);if(G.length===2)G=[1,...G],Q=[Q];else if(G.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(G.some((H,K)=>H!==J.dims[K]))throw Error(`The first ${G.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new PQ("int64",Q.flat(1/0).map(BigInt),G)}async _call(Q,{input_points:J=null,input_labels:G=null,input_boxes:H=null}={}){let K=await super._call(Q);if(J)K.input_points=this.reshape_input_points(J,K.original_sizes,K.reshaped_input_sizes);if(G){if(!K.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");K.input_labels=this.add_input_labels(G,K.input_points)}if(H)K.input_boxes=this.reshape_input_points(H,K.original_sizes,K.reshaped_input_sizes,!0);return K}async post_process_masks(Q,J,G,{mask_threshold:H=0,binarize:K=!0,pad_size:z=null}={}){let q=[];z=z??this.pad_size??this.size;let F=[z.height,z.width];for(let D=0;D<J.length;++D){let V=J[D],O=G[D],P=await bG(Q[D],{mode:"bilinear",size:F});if(P=P.slice(null,null,[0,O[0]],[0,O[1]]),P=await bG(P,{mode:"bilinear",size:V}),K){let N=P.data,I=new Uint8Array(N.length);for(let R=0;R<N.length;++R)if(N[R]>H)I[R]=1;P=new PQ("bool",I,P.dims)}q.push(P)}return q}generate_crop_boxes(Q,J,{crop_n_layers:G=0,overlap_ratio:H=0.3413333333333333,points_per_crop:K=32,crop_n_points_downscale_factor:z=1}={}){}},lw0=class extends p8{post_process_semantic_segmentation(...Q){return Ew0(...Q)}},g$Q=class extends lw0{},dw0=class extends p8{post_process_semantic_segmentation(...Q){return Ew0(...Q)}},h$Q=class extends dw0{},_$Q=class extends p8{},f$Q=class extends p8{pad_image(Q,J,G,H={}){let[K,z,q]=J;return super.pad_image(Q,J,{width:z+(G-z%G)%G,height:K+(G-K%G)%G},{mode:"symmetric",center:!1,constant_values:-1,...H})}},cw0=class extends p8{},m$Q=class extends cw0{},u$Q=class extends p8{async _call(Q,J){if(!Array.isArray(Q))Q=[Q];if(!Array.isArray(J))J=[J];let G=await Promise.all(Q.map((z)=>this.preprocess(z))),H=await Promise.all(J.map((z)=>this.preprocess(z,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:g5(G.map((z,q)=>T9([z.pixel_values,H[q].pixel_values],0)),0),original_sizes:G.map((z)=>z.original_size),reshaped_input_sizes:G.map((z)=>z.reshaped_input_size)}}},p$Q=class extends p8{post_process_pose_estimation(Q,J,{threshold:G=null}={}){let H=Q.tolist(),[K,z,q,F]=Q.dims,D=[];for(let V=0;V<K;++V){let O=H[V],P=J[V],N=[];for(let I=0;I<P.length;++I){let R=P[I],w=[],E=[],T=[],y=R.at(-2)/F,x=R.at(-1)/q;for(let b=0;b<O.length;++b){let[g,l]=[0,0],_=0,a=-1/0,r=O[b];for(let t=0;t<r.length;++t){let p0=r[t];for(let u0=0;u0<p0.length;++u0){let d=p0[u0];_+=d,a=Math.max(a,d),g+=(u0+0.5)*d,l+=t*d}}if(G!=null&&a<G)continue;let f0=[y*g/_,x*l/_];w.push(f0),T.push(b),E.push(a)}N.push({bbox:R,scores:E,labels:T,keypoints:w})}D.push(N)}return D}},iw0=class extends p8{post_process_object_detection(...Q){return TR(...Q)}},l$Q=class extends iw0{},tX=class{static async from_pretrained(Q,J={}){let G=await bW(Q,hF,!0,J),H=G.image_processor_type??G.feature_extractor_type,K=PR[H?.replace(/Fast$/,"")];if(!K){if(H!==void 0)g8.warn(`Image processor type '${H}' not found, assuming base ImageProcessor. Please report this at ${SR}.`);K=p8}return new K(G)}},d$Q=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;constructor(Q,J,G){super(Q,J,G);let{tasks_answer_post_processing_type:H,task_prompts_without_inputs:K,task_prompts_with_input:z}=this.image_processor.config;this.tasks_answer_post_processing_type=new Map(Object.entries(H??{})),this.task_prompts_without_inputs=new Map(Object.entries(K??{})),this.task_prompts_with_input=new Map(Object.entries(z??{})),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=1000}construct_prompts(Q){if(typeof Q==="string")Q=[Q];let J=[];for(let G of Q)if(this.task_prompts_without_inputs.has(G))J.push(this.task_prompts_without_inputs.get(G));else{for(let[H,K]of this.task_prompts_with_input)if(G.includes(H)){J.push(K.replaceAll("{input}",G).replaceAll(H,""));break}if(J.length!==Q.length)J.push(G)}return J}post_process_generation(Q,J,G){let H=this.tasks_answer_post_processing_type.get(J)??"pure_text";Q=Q.replaceAll("<s>","").replaceAll("</s>","");let K;switch(H){case"pure_text":K=Q;break;case"description_with_bboxes":case"bboxes":case"phrase_grounding":case"ocr":let z=H==="ocr"?"quad_boxes":"bboxes",q=Q.matchAll(this.regexes[z]),F=[],D=[];for(let[V,O,...P]of q)F.push(O?O.trim():F.at(-1)??""),D.push(P.map((N,I)=>(Number(N)+0.5)/this.size_per_bin*G[I%2]));K={labels:F,[z]:D};break;default:throw Error(`Task "${J}" (of type "${H}") not yet implemented.`)}return{[J]:K}}async _call(Q,J=null,G={}){if(!Q&&!J)throw Error("Either text or images must be provided");let H=await this.image_processor(Q,G),K=J?this.tokenizer(this.construct_prompts(J),G):{};return{...H,...K}}},c$Q=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(Q,J,G){super(Q,J,G);this.image_seq_length=this.config.image_seq_length;let{boi_token:H,image_token:K,eoi_token:z}=this.tokenizer.config;this.boi_token=H,this.image_token=K,this.eoi_token=z;let q=K.repeat(this.image_seq_length);this.full_image_sequence=`
${H}${q}${z}
`}async _call(Q,J=null,G={}){if(typeof Q==="string")Q=[Q];let H;if(J)H=await this.image_processor(J,G),Q=Q.map((z)=>z.replaceAll(this.boi_token,this.full_image_sequence));return{...this.tokenizer(Q,G),...H}}},i$Q=class extends u6{static image_processor_class=tX;static feature_extractor_class=aY;static tokenizer_class=m6;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(Q,J,G){super(Q,J,G);this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:H,boa_token:K,audio_token:z,eoa_token:q,image_token_id:F,boi_token:D,image_token:V,eoi_token:O}=this.tokenizer.config;this.audio_token_id=H,this.boa_token=K,this.audio_token=z;let P=z.repeat(this.audio_seq_length);this.full_audio_sequence=`
${K}${P}${q}
`,this.image_token_id=F,this.boi_token=D,this.image_token=V;let N=V.repeat(this.image_seq_length);this.full_image_sequence=`
${D}${N}${O}
`}async _call(Q,J=null,G=null,H={}){if(typeof Q==="string")Q=[Q];let K;if(G)K=await this.feature_extractor(G,H),Q=Q.map((F)=>F.replaceAll(this.audio_token,this.full_audio_sequence));let z;if(J)z=await this.image_processor(J,H),Q=Q.map((F)=>F.replaceAll(this.image_token,this.full_image_sequence));return{...this.tokenizer(Q,H),...z,...K}}},o$Q=class extends u6{static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(Q,J,G){super(Q,J,G);this.audio_ms_per_token=this.config.audio_ms_per_token??40,this.audio_seq_length=this.config.audio_seq_length??750,this.image_seq_length=this.config.image_seq_length??280;let{audio_token:H,boa_token:K,eoa_token:z,image_token:q,boi_token:F,eoi_token:D}=this.tokenizer.config;this.audio_token=H,this.boa_token=K,this.eoa_token=z,this.image_token=q,this.boi_token=F,this.eoi_token=D}static async from_pretrained(Q,J={}){let[G,H,K]=await Promise.all([bW(Q,qw0,!0,J),m6.from_pretrained(Q,J),R90(Q,Uw0,!1,J)]),z={tokenizer:H};if(G.image_processor)z.image_processor=new gw0(G.image_processor);if(G.feature_extractor)z.feature_extractor=new Cw0(G.feature_extractor);return new this(G,z,K)}_compute_audio_num_tokens(Q,J){let G=Math.round(J*20/1000),H=Math.round(J*10/1000),K=Math.floor(G/2),z=Math.floor((Q+K-G-1)/H)+1;if(z<=0)return 0;for(let q=0;q<2;++q)z=Math.floor((z-1)/2)+1;return Math.min(z,this.audio_seq_length)}async _call(Q,J=null,G=null,H={}){if(typeof Q==="string")Q=[Q];let K;if(J){K=await this.image_processor(J,H);let q=K.num_soft_tokens_per_image,F=0;Q=Q.map((D)=>D.replaceAll(this.image_token,()=>`
${this.boi_token}${this.image_token.repeat(q[F++])}${this.eoi_token}
`))}let z;if(G){let q=Array.isArray(G)?G:[G];z=await this.feature_extractor(q[0],H);let F=this.feature_extractor.config.sampling_rate??16000,D=0;Q=Q.map((V)=>V.replaceAll(this.audio_token,()=>`
${this.boa_token}${this.audio_token.repeat(this._compute_audio_num_tokens(q[D++].length,F))}${this.eoa_token}
`))}return{...this.tokenizer(Q,H),...K,...z}}},X10=class extends u6{static image_processor_class=tX;static tokenizer_class=m6;static image_token="<|image_pad|>";async _call(Q,J=null,...G){if(!Array.isArray(Q))Q=[Q];let H,K;if(J)H=await this.image_processor(J),K=H.image_grid_thw;if(K){let q=this.image_processor.config.merge_size**2,F=0,D=this.constructor.image_token,V=K.tolist();Q=Q.map((O)=>{while(O.includes(D)){let P=Number(V[F++].reduce((N,I)=>N*I,1n));O=O.replace(D,"<|placeholder|>".repeat(Math.floor(P/q)))}return O.replaceAll("<|placeholder|>",D)})}return{...this.tokenizer(Q),...H}}},n$Q=class extends X10{static image_token="<|image|>"},a$Q=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;static uses_processor_config=!0;_get_num_audio_features(Q){let{hop_length:J}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:G,projector_downsample_rate:H}=this.feature_extractor.config,K=Math.floor(G/H),z=Math.floor(Q/J)+1,q=Math.floor(z/2);return Math.ceil(q/G)*K}async _call(Q,J=null,G={}){if(Array.isArray(Q))throw Error("Batched inputs are not supported yet.");let H={};if(J){let{input_features:z}=await this.feature_extractor(J);H.input_features=z;let q=this._get_num_audio_features(J.length),F=new Uint8Array(q).fill(1);H.input_features_mask=new PQ("bool",F,[1,q]);let D=this.config.audio_token??"<|audio|>";if(!Q.includes(D))throw Error(`The input text does not contain the audio token ${D}.`);Q=Q.replaceAll(D,D.repeat(q))}return{...this.tokenizer(Q,{add_special_tokens:!1,...G}),...H}}};function s$Q(Q,J){let H=Q.dims.at(-1)-1,K=Q.tolist();K.fill(!1,0,1),K.fill(!1,H);let z=J.tolist();return K.map((q,F)=>q?F:null).filter((q)=>q!==null).map((q)=>z[q])}var r$Q=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;async _call(Q,J,G={}){let H=Q?await this.image_processor(Q,G):{};return{...J?this.tokenizer(J,G):{},...H}}post_process_grounded_object_detection(Q,J,{box_threshold:G=0.25,text_threshold:H=0.25,target_sizes:K=null}={}){let{logits:z,pred_boxes:q}=Q,F=z.dims[0];if(K!==null&&K.length!==F)throw Error("Make sure that you pass in as many target sizes as the batch dimension of the logits");let D=z.dims.at(1),V=z.sigmoid(),O=V.max(-1).tolist(),P=q.tolist().map((I)=>I.map((R)=>ww0(R))),N=[];for(let I=0;I<F;++I){let R=K!==null?K[I]:null;if(R!==null)P[I]=P[I].map((x)=>x.map((b,g)=>b*R[(g+1)%2]));let w=O[I],E=[],T=[],y=[];for(let x=0;x<D;++x){let b=w[x];if(b<=G)continue;let g=P[I][x],l=V[I][x];E.push(b),y.push(g);let _=s$Q(l.gt(H),J[I]);T.push(_)}N.push({scores:E,boxes:y,labels:this.batch_decode(T)})}return N}};function t$Q(Q,J,G,H,K,z){let q="";for(let F=0;F<J;++F){for(let D=0;D<G;++D)q+=H+`<row_${F+1}_col_${D+1}>`+K.repeat(Q);q+=`
`}return q+=`
${H}${z}`+K.repeat(Q)+`${H}`,q}function e$Q(Q,J,G,H){return`${J}${H}`+G.repeat(Q)+`${J}`}function QZQ(Q,J,G,H,K,z){if(Q===0&&J===0)return e$Q(G,H,K,z);return t$Q(G,Q,J,H,K,z)}var PI0=class extends u6{static image_processor_class=tX;static tokenizer_class=m6;static uses_processor_config=!0;fake_image_token="<fake_token_around_image>";image_token="<image>";global_img_token="<global-img>";async _call(Q,J=null,G={}){G.return_row_col_info??=!0;let H;if(J)H=await this.image_processor(J,G);if(!Array.isArray(Q))Q=[Q];let K=H.rows??[Array(Q.length).fill(0)],z=H.cols??[Array(Q.length).fill(0)],q=this.config.image_seq_len,F=[],D=[];for(let O=0;O<Q.length;++O){let P=Q[O],N=K[O],I=z[O];F.push(iBQ(P,this.image_token));let R=N.map((T,y)=>QZQ(T,I[y],q,this.fake_image_token,this.image_token,this.global_img_token)),w=P.split(this.image_token);if(w.length===0)throw Error("The image token should be present in the text.");let E=w[0];for(let T=0;T<R.length;++T)E+=R[T]+w[T+1];D.push(E)}return{...this.tokenizer(D),...H}}},XZQ=class extends u6{static image_processor_class=tX;static tokenizer_class=m6;static uses_processor_config=!0;constructor(Q,J,G){super(Q,J,G);this.image_tag=this.config.image_tag,this.image_start_tag=this.config.image_start_tag,this.image_end_tag=this.config.image_end_tag,this.num_image_tokens=this.config.num_image_tokens}async _call(Q,{images:J=null,chat_template:G="default"}={}){if(!J)J=await Promise.all(Q.filter((w)=>w.images).flatMap((w)=>w.images).map((w)=>gG.read(w)));else if(!Array.isArray(J))J=[J];let H=this.tokenizer,K=H.apply_chat_template(Q,{tokenize:!1,add_generation_prompt:!0,chat_template:G}),z=(w)=>H.encode(w,{add_special_tokens:!1}),q=K.split(this.image_tag),F=q.length-1;if(J.length!==F)throw Error(`Number of images provided (${J.length}) does not match number of "${this.image_tag}" image tags (${F})`);let[D,V,O]=H.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),P=z(q[0]),N=Array(P.length).fill(!1);for(let w=1;w<q.length;++w){let E=Array(this.num_image_tokens).fill(D),T=z(q[w]);P=yW(P,[V],E,[O],T);let y=Array(this.num_image_tokens).fill(!0);N=yW(N,[!1],y,[!1],Array(T.length).fill(!1))}let I=[1,P.length],R={input_ids:new PQ("int64",P,I),attention_mask:new PQ("int64",Array(P.length).fill(1),I),images_seq_mask:new PQ("bool",N,I),images_emb_mask:new PQ("bool",Array(F*this.num_image_tokens).fill(!0),[1,F,this.num_image_tokens])};if(J&&J.length>0){let w=await this.image_processor(J);return w.pixel_values.unsqueeze_(0),{...R,...w}}return R}},JZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;async _call(Q=null,J=null,G={}){if(!Q&&!J)throw Error("Either text or images must be provided");let H=Q?this.tokenizer(Q,G):{},K=J?await this.image_processor(J,G):{};return{...H,...K}}},YZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;async _call(Q,J=null,G={}){let{image_rows:H,image_cols:K,image_sizes:z,...q}=await this.image_processor(Q,{...G,return_row_col_info:!0});if(J){let F=this.config.image_token??"<image>",{tile_size:D=512,downsample_factor:V=2,encoder_patch_size:O=16,use_thumbnail:P=!0}=this.image_processor.config,N=(y)=>Math.ceil(Math.floor(y/O)/V),I=N(D)**2,R=this.config.image_start_token??"<|image_start|>",w=this.config.image_end_token??"<|image_end|>",E=this.config.image_thumbnail??"<|img_thumbnail|>";if(!Array.isArray(J))J=[J];let T=0;J=J.map((y)=>{let x=y.split(F);return x[0]+x.slice(1).map((b)=>{let g=T++,[l,_]=z[g],a=H[g],r=K[g],f0=N(l)*N(_),t=R;if(a>1||r>1){let p0=F.repeat(I);for(let u0=0;u0<a;++u0)for(let d=0;d<r;++d)t+=`<|img_row_${u0+1}_col_${d+1}|>`+p0;if(P)t+=E+F.repeat(f0)}else t+=F.repeat(f0);return t+w+b}).join("")})}return{...q,...J?this.tokenizer(J,G):{}}}},GZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;static uses_processor_config=!0;async _call(Q,J=null,G={}){let H=await this.image_processor(Q,G);if(J){let[z,q]=H.pixel_values.dims.slice(-2),{image_token:F,patch_size:D,num_additional_image_tokens:V}=this.config,O=Math.floor(z/D)*Math.floor(q/D)+V;if(J=structuredClone(J),!Array.isArray(J))J=[J];for(let P=0;P<J.length;++P)J[P]=J[P].replace(F,F.repeat(O))}let K=J?this.tokenizer(J,G):{};return{...H,...K}}},NI0={char:["char_decode",1],bpe:["bpe_decode",2],wp:["wp_decode",102]},WZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;get char_tokenizer(){return this.components.char_tokenizer}get bpe_tokenizer(){return this.components.bpe_tokenizer}get wp_tokenizer(){return this.components.wp_tokenizer}_decode_helper(Q,J){if(!NI0.hasOwnProperty(J))throw Error(`Format ${J} is not supported.`);let[G,H]=NI0[J],K=this[G].bind(this),[z,q]=Q.dims,F=[],D=[],V=Q.tolist();for(let P=0;P<z;++P){let N=V[P],I=[],R=[];for(let E=1;E<q;++E){let[T,y]=D7(wX(N[E]));if(R.push(T),y==H)break;I.push(y)}let w=R.length>0?R.reduce((E,T)=>E*T,1):0;D.push(I),F.push(w)}return[K(D),F]}char_decode(Q){return this.char_tokenizer.batch_decode(Q).map((J)=>J.replaceAll(" ",""))}bpe_decode(Q){return this.bpe_tokenizer.batch_decode(Q)}wp_decode(Q){return this.wp_tokenizer.batch_decode(Q).map((J)=>J.replaceAll(" ",""))}batch_decode([Q,J,G]){let[H,K]=this._decode_helper(Q,"char"),[z,q]=this._decode_helper(J,"bpe"),[F,D]=this._decode_helper(G,"wp"),V=[],O=[];for(let P=0;P<H.length;++P){let[N,I]=D7([K[P],q[P],D[P]]);V.push([H[P],z[P],F[P]][I]),O.push(N)}return{generated_text:V,scores:O,char_preds:H,bpe_preds:z,wp_preds:F}}static async from_pretrained(...Q){let J=await super.from_pretrained(...Q),G=await m6.from_pretrained("Xenova/gpt2"),H=await m6.from_pretrained("Xenova/bert-base-uncased");return J.components={image_processor:J.image_processor,char_tokenizer:J.tokenizer,bpe_tokenizer:G,wp_tokenizer:H},J}async _call(Q,J=null){let G=await this.image_processor(Q);if(J)G.labels=this.tokenizer(J).input_ids;return G}},HZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;async _call(Q){return await this.feature_extractor(Q)}},BZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX},$V="<image>";function AZQ(Q,J,G,H,K){return`${H.repeat(G*K)}${J}${Q}
`}var KZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;static uses_processor_config=!1;async _call(Q,J=null,G={}){if(!J)g8.warn("You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."),J="";if(!Array.isArray(Q))Q=[Q];if(!Array.isArray(J))J=[J];let H=this.tokenizer.bos_token,K=this.image_processor.config.image_seq_length,z;if(J.some((D)=>D.includes($V)))z=J.map((D)=>{let V=D.replaceAll($V,$V.repeat(K)),O=V.lastIndexOf($V),P=O===-1?0:O+$V.length;return V.slice(0,P)+H+V.slice(P)+`
`});else g8.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),z=J.map((D)=>AZQ(D,H,K,$V,Q.length));let q=this.tokenizer(z,G);return{...await this.image_processor(Q,G),...q}}},jI0="<|image|>",zZQ=/<\|image_\d+\|>/g,VZQ=class extends u6{static image_processor_class=tX;static tokenizer_class=m6;async _call(Q,J=null,{padding:G=!0,truncation:H=!0,num_crops:K=null}={}){if(!Array.isArray(Q))Q=[Q];let z,q;if(J){q=await this.image_processor(J,{num_crops:K});let{num_img_tokens:F}=q,D=Q.map((O,P)=>O.split(zZQ).join(jI0.repeat(F[P])));z=this.tokenizer(D,{padding:G,truncation:H});let V=this.tokenizer._tokenizer.token_to_id(jI0);z.input_ids.map_((O)=>O==V?-O:O)}else z=this.tokenizer(Q);return{...z,...q}}},qZQ=class extends u6{static tokenizer_class=m6;static image_processor_class=tX;static uses_processor_config=!0;async _call(Q,J=null,G={}){let H=await this.image_processor(Q,G);if(J){let[z,q]=H.pixel_values.dims.slice(-2),{image_token:F,image_break_token:D,image_end_token:V,patch_size:O,spatial_merge_size:P}=this.config,N=O*P,I=Math.floor(z/N),R=Math.floor(q/N);if(J=structuredClone(J),!Array.isArray(J))J=[J];for(let w=0;w<J.length;++w){let E=F.repeat(R),T=E+D,y=E+V,x=T.repeat(I-1)+y;J[w]=J[w].replace(F,x)}}let K=J?this.tokenizer(J,G):{};return{...H,...K}}},UZQ=class extends u6{static feature_extractor_class=Iw0;async _call(Q){return await this.feature_extractor(Q)}post_process_speaker_diarization(...Q){return this.feature_extractor.post_process_speaker_diarization(...Q)}get sampling_rate(){return this.feature_extractor.config.sampling_rate}},ow0=class extends X10{},$ZQ=class extends ow0{},nw0=class extends u6{static image_processor_class=tX;async _call(...Q){return await this.image_processor(...Q)}post_process_masks(...Q){return this.image_processor.post_process_masks(...Q)}reshape_input_points(...Q){return this.image_processor.reshape_input_points(...Q)}},aw0=class extends nw0{},ZZQ=class extends aw0{},FZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;async _call(Q){return await this.feature_extractor(Q)}},DZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;static uses_processor_config=!0;async _call(Q,J=null,G={}){if(Array.isArray(Q))throw Error("Batched inputs are not supported yet.");let H={};if(J){let z=J.length,{input_features:q}=await this.feature_extractor(J,{...G,max_length:z}),F=Math.round(z/this.config.encoder_ds_factor+0.0001),D=1+Math.ceil(F/this.config.stack_factor);H.audio_token_len=[D],H.audio_values=q;let V=this.config.audio_placeholder;if(!Q.includes(V))throw Error(`The input text does not contain the image token ${V}.`);Q=Q.replaceAll(V,V.repeat(D))}return{...this.tokenizer(Q,{add_special_tokens:!1,...G}),...H}}},XR="[AUDIO]",MZQ="[BEGIN_AUDIO]",LZQ=375;function OZQ(Q,J){let G=[];for(let H=0;H<Q.length;H+=J)G.push(Q.subarray(H,Math.min(H+J,Q.length)));return G}var PZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;static uses_processor_config=!1;async _call(Q,J=null,G={}){if(Array.isArray(Q))throw Error("Batched inputs are not supported yet.");let H={};if(J){if(!Q.includes(XR))throw Error(`The input text does not contain the audio token ${XR}.`);if(!Array.isArray(J))J=[J];let z=Q.split(XR),q=z.length-1;if(q!==J.length)throw Error(`The number of audio inputs (${J.length}) does not match the number of audio tokens in the text (${q}).`);let F=this.feature_extractor.config.n_samples,D=J.map((I)=>OZQ(I,F)),V=D.map((I)=>I.length),O=D.flat(),P=(await Promise.all(O.map((I)=>this.feature_extractor(I,G)))).map((I)=>I.input_features);H.audio_values=P.length>1?T9(P,0):P[0];let N=z[0];for(let I=0;I<V.length;++I){N+=MZQ;for(let R=0;R<V[I];++R)N+=XR.repeat(LZQ);N+=z[I+1]}Q=N}return{...this.tokenizer(Q,{add_special_tokens:!1,...G}),...H}}},CI0=32,e60=6,JR=8,NZQ=10,jZQ=32,CZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;static uses_processor_config=!1;get num_mel_frames_first_audio_chunk(){return(e60+1)*JR}get num_samples_first_audio_chunk(){let{hop_length:Q,n_fft:J}=this.feature_extractor.config;return(this.num_mel_frames_first_audio_chunk-1)*Q+Math.floor(J/2)}get num_samples_per_audio_chunk(){let{hop_length:Q,n_fft:J}=this.feature_extractor.config;return JR*Q+J}get num_right_pad_tokens(){return e60+1+NZQ}get audio_length_per_tok(){return JR}get raw_audio_length_per_tok(){return JR*this.feature_extractor.config.hop_length}async _call(Q,{is_streaming:J=!1,is_first_audio_chunk:G=!0}={}){if(EX(Q,"VoxtralRealtimeProcessor"),!J&&!G)throw Error("In non-streaming mode (`is_streaming=false`), `is_first_audio_chunk` must be `true`.");if(G)if(J){let H=CI0*this.raw_audio_length_per_tok,K=new Float32Array(H+Q.length);K.set(Q,H);let z=await this.feature_extractor(K,{center:!0}),F=1+(CI0+e60),D=new BigInt64Array(F).fill(BigInt(jZQ));return D[0]=1n,{input_ids:new PQ("int64",D,[1,F]),...z}}else{let H=this.num_right_pad_tokens*this.raw_audio_length_per_tok,K=new Float32Array(Q.length+H);return K.set(Q),await this.feature_extractor(K,{center:!0})}else return await this.feature_extractor(Q,{center:!1})}},IZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;async _call(Q){return await this.feature_extractor(Q)}},RZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;async _call(Q){return await this.feature_extractor(Q)}},wZQ=class extends u6{static tokenizer_class=m6;static feature_extractor_class=aY;async _call(Q){return await this.feature_extractor(Q)}},EZQ=class{static async from_pretrained(Q,J={}){let G=await bW(Q,hF,!0,J),{image_processor_type:H,feature_extractor_type:K,processor_class:z}=G;if(z&&q90[z])return q90[z].from_pretrained(Q,J);if(!H&&!K)throw Error("No `image_processor_type` or `feature_extractor_type` found in the config.");let q={};if(H){let D=PR[H.replace(/Fast$/,"")];if(!D)throw Error(`Unknown image_processor_type: '${H}'.`);q.image_processor=new D(G)}if(K){let D=PR[K];if(D)q.image_processor=new D(G);else{let V=s90[K];if(!V)throw Error(`Unknown feature_extractor_type: '${K}'.`);q.feature_extractor=new V(G)}}return new u6({},q,null)}};async function SZQ(Q,J){return await bW(Q,"config.json",!0,J)}function DV(Q){let J={},G={};switch(Q.model_type){case"llava":case"paligemma":case"gemma3":case"florence2":case"llava_onevision":case"idefics3":case"granite_speech":case"ultravox":case"voxtral":case"voxtral_realtime":case"smolvlm":case"gemma3n":case"gemma4":case"lfm2_vl":case"chatterbox":case"lighton_ocr":case"glm_ocr":case"mistral3":case"qwen2_5_vl":case"qwen3_vl":case"qwen3_vl_moe":G=DV(Q.text_config);break;case"moondream1":G=DV(Q.phi_config);break;case"musicgen":G=DV(Q.decoder);break;case"multi_modality":G=DV(Q.language_config);break;case"gpt2":case"gptj":case"jais":case"codegen":case"gpt_bigcode":J.num_heads="n_head",J.num_layers="n_layer",J.hidden_size="n_embd";break;case"gpt_neox":case"stablelm":case"opt":case"falcon":case"modernbert-decoder":J.num_heads="num_attention_heads",J.num_layers="num_hidden_layers",J.hidden_size="hidden_size";break;case"gpt_oss":case"llama":case"llama4_text":case"nanochat":case"apertus":case"arcee":case"afmoe":case"lfm2":case"lfm2_moe":case"smollm3":case"olmo":case"olmo2":case"olmo3":case"mobilellm":case"granite":case"granitemoehybrid":case"cohere":case"cohere2":case"mistral":case"voxtral_realtime_text":case"voxtral_realtime_encoder":case"starcoder2":case"qwen2":case"qwen2_moe":case"qwen2_vl":case"qwen2_vl_text":case"qwen2_5_vl_text":case"qwen3_moe":case"qwen3_vl_text":case"qwen3_vl_moe_text":case"phi":case"phi3":case"phi3_v":case"llava_qwen2":J.num_heads="num_key_value_heads",J.num_layers="num_hidden_layers",J.hidden_size="hidden_size",J.num_attention_heads="num_attention_heads",J.dim_kv="head_dim";break;case"qwen3":case"solar_open":case"glm_ocr_text":case"gemma":case"gemma2":case"vaultgemma":case"gemma3_text":case"gemma3n_text":case"gemma4_text":case"glm":case"helium":case"ernie4_5":case"hunyuan_v1_dense":case"falcon_h1":case"nemotron_h":case"ministral":case"ministral3":J.num_heads="num_key_value_heads",J.num_layers="num_hidden_layers",J.dim_kv="head_dim";break;case"openelm":J.num_heads="num_kv_heads",J.num_layers="num_transformer_layers",J.dim_kv="head_dim";break;case"gpt_neo":case"donut-swin":J.num_heads="num_heads",J.num_layers="num_layers",J.hidden_size="hidden_size";break;case"bloom":J.num_heads="n_head",J.num_layers="n_layer",J.hidden_size="hidden_size";break;case"mpt":J.num_heads="n_heads",J.num_layers="n_layers",J.hidden_size="d_model";break;case"exaone":J.num_heads="num_key_value_heads",J.num_layers="num_layers",J.dim_kv="head_dim",J.num_attention_heads="num_attention_heads";break;case"youtu":case"deepseek_v3":case"glm_moe_dsa":case"mistral4":J.num_heads="num_key_value_heads",J.num_layers="num_hidden_layers",J.dim_kv="qk_head_dim",J.num_attention_heads="num_attention_heads";break;case"t5":case"mt5":case"longt5":J.num_decoder_layers="num_decoder_layers",J.num_decoder_heads="num_heads",J.decoder_dim_kv="d_kv",J.num_encoder_layers="num_layers",J.num_encoder_heads="num_heads",J.encoder_dim_kv="d_kv";break;case"bart":case"mbart":case"marian":case"whisper":case"lite-whisper":case"m2m_100":case"blenderbot":case"blenderbot-small":case"florence2_language":J.num_decoder_layers="decoder_layers",J.num_decoder_heads="decoder_attention_heads",J.decoder_hidden_size="d_model",J.num_encoder_layers="encoder_layers",J.num_encoder_heads="encoder_attention_heads",J.encoder_hidden_size="d_model";break;case"speecht5":J.num_decoder_layers="decoder_layers",J.num_decoder_heads="decoder_attention_heads",J.decoder_hidden_size="hidden_size",J.num_encoder_layers="encoder_layers",J.num_encoder_heads="encoder_attention_heads",J.encoder_hidden_size="hidden_size";break;case"trocr":J.num_encoder_layers=J.num_decoder_layers="decoder_layers",J.num_encoder_heads=J.num_decoder_heads="decoder_attention_heads",J.encoder_hidden_size=J.decoder_hidden_size="d_model";break;case"musicgen_decoder":J.num_encoder_layers=J.num_decoder_layers="num_hidden_layers",J.num_encoder_heads=J.num_decoder_heads="num_attention_heads",J.encoder_hidden_size=J.decoder_hidden_size="hidden_size";break;case"moonshine":J.num_decoder_layers="decoder_num_hidden_layers",J.num_decoder_heads="decoder_num_key_value_heads",J.num_encoder_layers="encoder_num_hidden_layers",J.num_encoder_heads="encoder_num_key_value_heads",J.encoder_hidden_size=J.decoder_hidden_size="hidden_size";break;case"cohere_asr":J.num_decoder_layers="num_hidden_layers",J.num_decoder_heads="num_key_value_heads",J.decoder_hidden_size="hidden_size",J.decoder_dim_kv="head_dim";let{num_hidden_layers:K,num_attention_heads:z,hidden_size:q}=Q.encoder_config;G={num_encoder_layers:K,num_encoder_heads:z,encoder_hidden_size:q,encoder_dim_kv:Q.head_dim};break;case"vision-encoder-decoder":let F=DV(Q.decoder),D="num_decoder_layers"in F,V=JX(Q,["model_type","is_encoder_decoder"]);if(D)V.num_decoder_layers=F.num_decoder_layers,V.num_decoder_heads=F.num_decoder_heads,V.decoder_hidden_size=F.decoder_hidden_size,V.num_encoder_layers=F.num_encoder_layers,V.num_encoder_heads=F.num_encoder_heads,V.encoder_hidden_size=F.encoder_hidden_size;else V.num_layers=F.num_layers,V.num_heads=F.num_heads,V.hidden_size=F.hidden_size;return V}let H={...G,...JX(Q,["model_type","multi_query","is_encoder_decoder"])};for(let K in J)H[K]=Q[J[K]];return H}function kR(Q,J){if(!(Q instanceof U90))Q=new U90(Q);let G=J?.prefix??"past_key_values",H=G==="present"?"present":"past",K=new Set;if(["lfm2","lfm2_moe"].includes(Q.model_type)){let{layer_types:z}=Q;for(let q=0;q<z.length;++q)if(z[q]==="full_attention")K.add(`${G}.${q}.key`),K.add(`${G}.${q}.value`);else if(z[q]==="conv")K.add(`${H}_conv.${q}`);else throw Error(`Unsupported layer type: ${z[q]}`);return K}else if(["granitemoehybrid","falcon_h1","nemotron_h"].includes(Q.model_type)){let z=Q,q=z.layer_types??z.layers_block_type,F=z.num_hidden_layers??q?.length;for(let D=0;D<F;++D){if(!q||q[D]==="mamba")K.add(`${H}_conv.${D}`),K.add(`${H}_ssm.${D}`);if(!q||q[D]==="attention")K.add(`${G}.${D}.key`),K.add(`${G}.${D}.value`)}return K}else if(["qwen3_next","qwen3_5_text","qwen3_5_moe_text","olmo_hybrid"].includes(Q.model_type)){let{layer_types:z}=Q;for(let q=0;q<z.length;++q)if(z[q]==="full_attention")K.add(`${G}.${q}.key`),K.add(`${G}.${q}.value`);else if(z[q]==="linear_attention"){if(Q.model_type==="olmo_hybrid")K.add(`${H}_conv.${q}.key`),K.add(`${H}_conv.${q}.value`),K.add(`${H}_conv.${q}.query`);else K.add(`${H}_conv.${q}`);K.add(`${H}_recurrent.${q}`)}else throw Error(`Unsupported layer type: ${z[q]}`);return K}else if(["gemma4","gemma4_text"].includes(Q.model_type)){let z=Q.model_type==="gemma4"?Q.text_config:Q,q=z.num_hidden_layers,F=z.num_kv_shared_layers??0,D=q-F;for(let V=0;V<D;++V)K.add(`${G}.${V}.key`),K.add(`${G}.${V}.value`);return K}else if(["lfm2_vl","qwen3_5","qwen3_5_moe","voxtral_realtime"].includes(Q.model_type)){let z;if(Q.model_type==="voxtral_realtime"&&J?.session_name==="audio_encoder")z=Q.audio_config;else z=Q.text_config;return kR(z,J)}return TZQ(Q,{prefix:G})}function TZQ(Q,{prefix:J="past_key_values"}={}){let G=new Set,H=Q.normalized_config;if(H.is_encoder_decoder&&"num_encoder_heads"in H&&"num_decoder_heads"in H)for(let K=0;K<H.num_decoder_layers;++K)G.add(`${J}.${K}.encoder.key`),G.add(`${J}.${K}.encoder.value`),G.add(`${J}.${K}.decoder.key`),G.add(`${J}.${K}.decoder.value`);else if(H.multi_query)for(let K=0;K<H.num_layers;++K)G.add(`${J}.${K}.key_value`);else for(let K=0;K<H.num_layers;++K)G.add(`${J}.${K}.key`),G.add(`${J}.${K}.value`);return G}var U90=class Q{model_type=null;is_encoder_decoder=!1;max_position_embeddings;"transformers.js_config";constructor(J){Object.assign(this,J),this.normalized_config=DV(this)}static async from_pretrained(J,{progress_callback:G=null,config:H=null,cache_dir:K=null,local_files_only:z=!1,revision:q="main"}={}){if(H&&!(H instanceof Q))H=new Q(H);let F=H??await SZQ(J,{progress_callback:G,config:H,cache_dir:K,local_files_only:z,revision:q});return new this(F)}},_F=class{static async from_pretrained(...Q){return U90.from_pretrained(...Q)}};function sw0(Q,J,G){if(!Q)return 0;if(typeof Q==="object"&&Q!==null){if(Q.hasOwnProperty(J))return+Q[J];if(Q.hasOwnProperty(G))return+Q[G];return 0}return+Q}function rw0(Q,J){let G=[];for(let H=0;H<J;++H)G.push(`${Q}_data${H===0?"":"_"+H}`);return G}async function kZQ(Q,J,G,H){let K=`${J}${H}.onnx`,z=`${G.subfolder??""}/${K}`;return await UR(Q,z,!0,G,Y6.IS_NODE_ENV)}async function yZQ(Q,J,G,H,K,z={}){let q=`${J}${G}.onnx`,F=Y6.IS_NODE_ENV,D=[],V=sw0(K,q,J);if(V>0){if(V>SC0)throw Error(`The number of external data chunks (${V}) exceeds the maximum allowed value (${SC0}).`);let O=rw0(q,V);for(let P of O){let N=`${H.subfolder??""}/${P}`;D.push(new Promise(async(I,R)=>{let w=await UR(Q,N,!0,H,F);I(w instanceof Uint8Array?{path:P,data:w}:P)}))}}else if(z.externalData!==void 0)D=z.externalData.map(async(O)=>{if(typeof O.data==="string"){let P=await UR(Q,O.data,!0,H);return{...O,data:P}}return O});return Promise.all(D)}async function vZQ(Q,J,G,H=!1,K=void 0){let z=G.config?.["transformers.js_config"]??{},q=Qw0(G.device??z.device,J,{warn:(y)=>g8.info(y)}),F=WqQ(q),D=z.device_config??{};if(D.hasOwnProperty(q))z={...z,...D[q]};let V=Xw0(G.dtype??z.dtype,J,q,{configDtype:z.dtype,warn:(y)=>g8.info(y)});if(!LR.hasOwnProperty(V))throw Error(`Invalid dtype: ${V}. Should be one of: ${Object.keys(I7).join(", ")}`);else if(q==="webgpu"&&!Y6.IS_NODE_ENV&&V===I7.fp16&&!await AqQ())throw Error(`The device (${q}) does not support fp16.`);let O=LR[V],P={...G.session_options};P.executionProviders??=F;let N=z.free_dimension_overrides;if(N)P.freeDimensionOverrides??=N;else if(q.startsWith("webnn")&&!P.freeDimensionOverrides)g8.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${q}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let I=kZQ(Q,J,G,O),R=G.use_external_data_format??z.use_external_data_format,w=await yZQ(Q,J,O,G,R,P);if(w.length>0&&(!Y6.IS_NODE_ENV||w.some((y)=>typeof y!=="string")))P.externalData=w;if(H&&q==="webgpu"){let y=kR(G.config,{prefix:"present",session_name:K});if(y.size>0&&!d90()){let x={};for(let b of y)x[b]="gpu-buffer";P.preferredOutputLocation=x}}return{buffer_or_path:await I,session_options:P,session_config:{dtype:V,device:q}}}async function xZQ(Q,J,G,H=void 0){return Object.fromEntries(await Promise.all(Object.keys(J).map(async(K)=>{let z=H?.[K]??!1,{buffer_or_path:q,session_options:F,session_config:D}=await vZQ(Q,J[K],G,z,K),V=await rR0(q,F,D);return[K,V]})))}function tw0(Q){for(let J in Q)if(eR0(Q[J]))Q[J]=new PQ(Q[J]);else if(typeof Q[J]==="object")tw0(Q[J]);return Q}async function E6(Q,J){let G=bZQ(Q,J);try{let H=Object.fromEntries(Object.entries(G).map(([z,q])=>{let F=q.ort_tensor;if(Y6.IS_NODE_ENV){if(typeof Float16Array<"u"&&F.cpuData instanceof Float16Array)F.cpuData=new Uint16Array(F.cpuData.buffer)}return[z,F]})),K=await tR0(Q,H);return tw0(K)}catch(H){let K=Object.fromEntries(Object.entries(G).map(([z,q])=>{let F={type:q.type,dims:q.dims,location:q.location};if(F.location!=="gpu-buffer")F.data=q.data;return[z,F]}));throw g8.error(`An error occurred during model execution: "${H}".`),g8.error("Inputs given to model:",K),H}}function bZQ(Q,J){let G=Object.create(null),H=[];for(let q of Q.inputNames){let F=J[q];if(!(F instanceof PQ)){H.push(q);continue}G[q]=d90()?F.clone():F}if(H.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${H.join(", ")}.`);let K=Object.keys(J).length,z=Q.inputNames.length;if(K>z){let q=Object.keys(J).filter((F)=>!Q.inputNames.includes(F));g8.warn(`WARNING: Too many inputs were provided (${K} > ${z}). The following inputs will be ignored: "${q.join(", ")}".`)}return G}var _7=class{},T8=class extends _7{constructor({logits:Q,...J}){super();this.logits=Q;let G=Object.values(J);if(G.length>0)this.attentions=G}},R7=class extends _7{constructor({logits:Q}){super();this.logits=Q}},f7=class extends _7{constructor({logits:Q}){super();this.logits=Q}},eX=class extends _7{constructor({start_logits:Q,end_logits:J}){super();this.start_logits=Q,this.end_logits=J}},VB=class extends _7{constructor({logits:Q}){super();this.logits=Q}},gZQ=class extends _7{constructor({alphas:Q}){super();this.alphas=Q}},mG=class extends nJ{_call(Q,J){throw Error("`_call` should be implemented in a subclass")}},hZQ=class extends nJ{_call(Q,J){throw Error("`_call` should be implemented in a subclass")}},$90=class extends nJ{constructor(){super();this.processors=[]}push(Q){this.processors.push(Q)}extend(Q){this.processors.push(...Q)}_call(Q,J){let G=J;for(let H of this.processors)G=H(Q,G);return G}[Symbol.iterator](){return this.processors.values()}},_ZQ=class extends mG{constructor(Q){super();this.bos_token_id=Q}_call(Q,J){for(let G=0;G<Q.length;++G)if(Q[G].length===1){let H=J[G].data;H.fill(-1/0),H[this.bos_token_id]=0}return J}},fZQ=class extends mG{constructor(Q,J){super();this.max_length=Q,this.eos_token_id=Array.isArray(J)?J:[J]}_call(Q,J){for(let G=0;G<Q.length;++G)if(Q[G].length===this.max_length-1){let H=J[G].data;H.fill(-1/0);for(let K of this.eos_token_id)H[K]=0}return J}},mZQ=class extends mG{constructor(Q){super();this.suppress_tokens=Q}_call(Q,J){for(let G=0;G<Q.length;++G){let H=J[G].data;for(let K of this.suppress_tokens)H[K]=-1/0}return J}},ew0=class extends mG{constructor(Q,J){super();this.begin_suppress_tokens=Q,this.begin_index=J}_call(Q,J){for(let G=0;G<Q.length;++G)if(Q[G].length===this.begin_index){let H=J[G].data;for(let K of this.begin_suppress_tokens)H[K]=-1/0}return J}},uZQ=class extends mG{constructor(Q,J){super();if(this.eos_token_id=Array.isArray(Q.eos_token_id)?Q.eos_token_id[0]:Q.eos_token_id,this.no_timestamps_token_id=Q.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=Q.max_initial_timestamp_index}_call(Q,J){for(let G=0;G<Q.length;++G){let H=J[G].data;if(H[this.no_timestamps_token_id]=-1/0,Q[G].length===this.begin_index){H.subarray(0,this.timestamp_begin).fill(-1/0);continue}let K=Q[G].slice(this.begin_index),z=K.length>=1&&K[K.length-1]>=this.timestamp_begin,q=K.length<2||K[K.length-2]>=this.timestamp_begin;if(z)if(q)H.subarray(this.timestamp_begin).fill(-1/0);else H.subarray(0,this.eos_token_id).fill(-1/0);if(Q[G].length===this.begin_index&&this.max_initial_timestamp_index!==null){let O=this.timestamp_begin+this.max_initial_timestamp_index;H.subarray(O+1).fill(-1/0)}let F=DVQ(H),D=Math.log(F.subarray(this.timestamp_begin).map(Math.exp).reduce((O,P)=>O+P)),V=D7(F.subarray(0,this.timestamp_begin))[0];if(D>V)H.subarray(0,this.timestamp_begin).fill(-1/0)}return J}},pZQ=class extends mG{constructor(Q){super();this.no_repeat_ngram_size=Q}getNgrams(Q){let J=Q.length,G=[];for(let K=0;K<J+1-this.no_repeat_ngram_size;++K){let z=[];for(let q=0;q<this.no_repeat_ngram_size;++q)z.push(Q[K+q]);G.push(z.map(Number))}let H=new Map;for(let K of G){let z=K.slice(0,K.length-1),q=JSON.stringify(z),F=H.get(q)??[];F.push(K[K.length-1]),H.set(q,F)}return H}getGeneratedNgrams(Q,J){let G=J.slice(J.length+1-this.no_repeat_ngram_size,J.length);return Q.get(JSON.stringify(G.map(Number)))??[]}calcBannedNgramTokens(Q){let J=[];if(Q.length+1<this.no_repeat_ngram_size)return J;else{let G=this.getNgrams(Q);return this.getGeneratedNgrams(G,Q)}}_call(Q,J){for(let G=0;G<Q.length;++G){let H=J[G].data,K=this.calcBannedNgramTokens(Q[G]);for(let z of K)H[z]=-1/0}return J}},lZQ=class extends mG{constructor(Q){super();this.penalty=Q}_call(Q,J){for(let G=0;G<Q.length;++G){let H=J[G].data;for(let K of new Set(Q[G])){let z=Number(K);if(H[z]<0)H[z]*=this.penalty;else H[z]/=this.penalty}}return J}},dZQ=class extends mG{constructor(Q,J){super();this.min_length=Q,this.eos_token_id=Array.isArray(J)?J:[J]}_call(Q,J){for(let G=0;G<Q.length;++G)if(Q[G].length<this.min_length){let H=J[G].data;for(let K of this.eos_token_id)H[K]=-1/0}return J}},cZQ=class extends mG{constructor(Q,J,G){super();this.prompt_length_to_skip=Q,this.min_new_tokens=J,this.eos_token_id=Array.isArray(G)?G:[G]}_call(Q,J){for(let G=0;G<Q.length;++G)if(Q[G].length-this.prompt_length_to_skip<this.min_new_tokens){let K=J[G].data;for(let z of this.eos_token_id)K[z]=-1/0}return J}},iZQ=class extends mG{constructor(Q,J){super();this.bad_words_ids=Q,this.eos_token_id=Array.isArray(J)?J:[J]}_call(Q,J){for(let G=0;G<Q.length;++G){let H=J[G].data,K=Q[G];for(let z of this.bad_words_ids){if(K.length<z.length-1)continue;let q=!0;for(let F=1;F<=z.length-1;++F)if(z.at(-F-1)!=K.at(-F)){q=!1;break}if(q)H[z.at(-1)]=-1/0}}return J}},oZQ=class extends mG{constructor(Q){super();if(Q<=1)throw Error(`Require guidance scale >1 to use the classifier free guidance processor, got guidance scale ${Q}.`);this.guidance_scale=Q}_call(Q,J){if(J.dims[0]!==2*Q.length)throw 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 ${Q.length} for the input ids.`);let G=Q.length,H=J.slice([0,G],null),K=J.slice([G,J.dims[0]],null);for(let z=0;z<K.data.length;++z)K.data[z]+=(H.data[z]-K.data[z])*this.guidance_scale;return K}},nZQ=class extends hZQ{constructor(Q){super();if(typeof Q!=="number"||Q<=0){let J=`\`temperature\` (=${Q}) must be a strictly positive float, otherwise your next token scores will be invalid.`;if(Q===0)J+=" If you're looking for greedy decoding strategies, set `do_sample=false`."}this.temperature=Q}_call(Q,J){let G=J.data;for(let H=0;H<G.length;++H)G[H]/=this.temperature;return J}};var Q20=class{max_length=20;max_new_tokens=null;min_length=0;min_new_tokens=null;early_stopping=!1;max_time=null;do_sample=!1;num_beams=1;num_beam_groups=1;penalty_alpha=null;use_cache=!0;temperature=1;top_k=50;top_p=1;typical_p=1;epsilon_cutoff=0;eta_cutoff=0;diversity_penalty=0;repetition_penalty=1;encoder_repetition_penalty=1;length_penalty=1;no_repeat_ngram_size=0;bad_words_ids=null;force_words_ids=null;renormalize_logits=!1;constraints=null;forced_bos_token_id=null;forced_eos_token_id=null;remove_invalid_values=!1;exponential_decay_length_penalty=null;suppress_tokens=null;streamer=null;begin_suppress_tokens=null;forced_decoder_ids=null;guidance_scale=null;num_return_sequences=1;output_attentions=!1;output_hidden_states=!1;output_scores=!1;return_dict_in_generate=!1;pad_token_id=null;bos_token_id=null;eos_token_id=null;encoder_no_repeat_ngram_size=0;decoder_start_token_id=null;generation_kwargs={};constructor(Q){Object.assign(this,JX(Q,Object.getOwnPropertyNames(this)))}},yR=class extends nJ{_call(Q,J){throw Error("StoppingCriteria needs to be subclassed")}},X20=class Q extends nJ{constructor(){super();this.criteria=[]}push(J){this.criteria.push(J)}extend(J){if(J instanceof Q)J=J.criteria;else if(J instanceof yR)J=[J];this.criteria.push(...J)}_call(J,G){let H=Array(J.length).fill(!1);for(let K of this.criteria){let z=K(J,G);for(let q=0;q<H.length;++q)H[q]||=z[q]}return H}[Symbol.iterator](){return this.criteria.values()}},aZQ=class extends yR{constructor(Q,J=null){super();this.max_length=Q,this.max_position_embeddings=J}_call(Q){return Q.map((J)=>J.length>=this.max_length)}},sZQ=class extends yR{constructor(Q){super();if(!Array.isArray(Q))Q=[Q];this.eos_token_id=Q}_call(Q,J){return Q.map((G)=>{let H=G.at(-1);return this.eos_token_id.some((K)=>H==K)})}};var vR=class extends nJ{constructor(Q){super();this.generation_config=Q}async _call(Q){return this.sample(Q)}async sample(Q){throw Error("sample should be implemented in subclasses.")}getLogits(Q,J){let G=Q.dims.at(-1),H=Q.data;if(J===-1)H=H.slice(-G);else{let K=J*G;H=H.slice(K,K+G)}return H}randomSelect(Q){return QVQ(Q)}static getSampler(Q){if(Q.do_sample)return new tZQ(Q);else if(Q.num_beams>1)return new eZQ(Q);else{if(Q.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${Q.num_return_sequences}.`);return new rZQ(Q)}}},rZQ=class extends vR{async sample(Q){let J=D7(Q.data)[1];return[[BigInt(J),0]]}},tZQ=class extends vR{async sample(Q){let J=Q.dims.at(-1);if(this.generation_config.top_k>0)J=Math.min(this.generation_config.top_k,J);let[G,H]=await SV(Q,J),K=wX(G.data);return Array.from({length:this.generation_config.num_beams},()=>{let z=this.randomSelect(K);return[H.data[z],Math.log(K[z])]})}},eZQ=class extends vR{async sample(Q){let J=Q.dims.at(-1);if(this.generation_config.top_k>0)J=Math.min(this.generation_config.top_k,J);let[G,H]=await SV(Q,J),K=wX(G.data);return Array.from({length:this.generation_config.num_beams},(z,q)=>{return[H.data[q],Math.log(K[q])]})}},QFQ=class{constructor(Q){if(!Q)return;for(let J in Q){if(J in this)throw TypeError(`Key "${J}" conflicts with an existing property on DynamicCache`);let G=Q[J];if(!(G instanceof PQ))throw TypeError(`Expected a Tensor for key "${J}", got ${typeof G}`);this[J]=G}}get_seq_length(){let Q=this;if(Object.keys(Q).length===0)return 0;for(let J in Q)if(J.startsWith("past_key_values."))return Q[J].dims.at(-2);throw Error("Unable to determine sequence length from the cache.")}update(Q){for(let J in Q){let G=this[J],H=Q[J];if(G&&G!==H&&G.location==="gpu-buffer")G.dispose();this[J]=H}}async dispose(){let Q=[];for(let J of Object.values(this))if(J.location==="gpu-buffer")Q.push(J.dispose());await Promise.all(Q)}},J10=QFQ,RQ={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,VoxtralRealtime:16},x5={[RQ.DecoderOnly]:{sessions:(Q,J)=>({model:J.model_file_name??"model"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.DecoderOnlyWithoutHead]:{sessions:(Q,J)=>({model:J.model_file_name??"model"})},[RQ.Seq2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.Vision2Seq]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.Musicgen]:{sessions:()=>({model:"text_encoder",decoder_model_merged:"decoder_model_merged",encodec_decode:"encodec_decode"}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.EncoderDecoder]:{sessions:()=>({model:"encoder_model",decoder_model_merged:"decoder_model_merged"}),cache_sessions:{decoder_model_merged:!0}},[RQ.MaskGeneration]:{sessions:()=>({model:"vision_encoder",prompt_encoder_mask_decoder:"prompt_encoder_mask_decoder"})},[RQ.ImageTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(Q,J,G)=>{let H={...x5[RQ.ImageTextToText].text_only_sessions};if(!G)H.vision_encoder="vision_encoder";if(Q.is_encoder_decoder)H.model="encoder_model";return H},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.AudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(Q,J,G)=>{let H={...x5[RQ.AudioTextToText].text_only_sessions};if(!G)H.audio_encoder="audio_encoder";return H},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.ImageAudioTextToText]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(Q,J,G)=>{let H={...x5[RQ.ImageAudioTextToText].text_only_sessions};if(!G)H.audio_encoder="audio_encoder",H.vision_encoder="vision_encoder";return H},optional_configs:{generation_config:"generation_config.json"}},[RQ.Phi3V]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"model",vision_encoder:"vision_encoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.MultiModality]:{sessions:()=>({prepare_inputs_embeds:"prepare_inputs_embeds",model:"language_model",lm_head:"lm_head",gen_head:"gen_head",gen_img_embeds:"gen_img_embeds",image_decode:"image_decode"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.AutoEncoder]:{sessions:()=>({encoder_model:"encoder_model",decoder_model:"decoder_model"})},[RQ.Supertonic]:{sessions:()=>({text_encoder:"text_encoder",latent_denoiser:"latent_denoiser",voice_decoder:"voice_decoder"})},[RQ.Chatterbox]:{sessions:()=>({embed_tokens:"embed_tokens",speech_encoder:"speech_encoder",model:"language_model",conditional_decoder:"conditional_decoder"}),cache_sessions:{model:!0},optional_configs:{generation_config:"generation_config.json"}},[RQ.VoxtralRealtime]:{text_only_sessions:{embed_tokens:"embed_tokens",decoder_model_merged:"decoder_model_merged"},sessions:(Q,J,G)=>{let H={...x5[RQ.VoxtralRealtime].text_only_sessions};if(!G)H.audio_encoder="audio_encoder";return H},cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:"generation_config.json"}},default:{sessions:(Q,J)=>({model:J.model_file_name??"model"})}};function XFQ(Q){return x5[Q]?.text_only_sessions??null}function JFQ(Q,J,G={}){let H=x5[Q]??x5.default;return{sessions:H.sessions(J,G,G.textOnly??!1),cache_sessions:H.cache_sessions,optional_configs:H.optional_configs}}function J20(Q,{warn:J=!0}={}){let G=Q.architectures||[];for(let H of G){let K=b5.get(H);if(K!==void 0)return K}if(Q.model_type){let H=b5.get(Q.model_type);if(H!==void 0)return H;for(let K of Object.values(MV))if(K.has(Q.model_type)){let z=b5.get(K.get(Q.model_type));if(z!==void 0)return z}}if(J){let H=G.length>0?G.join(", "):"(none)";g8.warn(`[resolve_model_type] Architecture(s) not found in MODEL_TYPE_MAPPING: [${H}] for model type '${Q.model_type}'. Falling back to EncoderOnly (single model.onnx file). If you encounter issues, please report at: ${SR}`)}return RQ.EncoderOnly}function Y20(Q,{config:J=null,cache_dir:G=null,local_files_only:H=!1,revision:K="main"}={}){if(J!==null)return _F.from_pretrained(Q,{config:J,cache_dir:G,local_files_only:H,revision:K});let z=JSON.stringify([Q,G,H,K]);return sI0(z,()=>_F.from_pretrained(Q,{config:J,cache_dir:G,local_files_only:H,revision:K}))}async function G20(Q,{config:J=null,dtype:G=null,device:H=null,model_file_name:K=null}={}){J=await Y20(Q,{config:J});let z=["config.json"],q=J["transformers.js_config"]??{},F=q.use_external_data_format,D="onnx",V=H??q.device,O=G??q.dtype,P=J20(J),N=(w,E=null)=>{E=E??w;let T=Qw0(V,w),y=Xw0(O,w,T),x=LR[y]??"",b=`${E}${x}.onnx`,g=D?`${D}/${b}`:b;z.push(g);let l=sw0(F,b,w);for(let _ of rw0(b,l)){let a=D?`${D}/${_}`:_;z.push(a)}},{sessions:I,optional_configs:R}=JFQ(P,J,{model_file_name:K});for(let[w,E]of Object.entries(I))N(w,E);if(R)for(let w of Object.values(R))z.push(w);return z}var MV=null;function YFQ(Q){MV=Q}function Z90(Q){if(Q instanceof PQ)return Q;if(Q.length===0)throw Error("items must be non-empty");if(Array.isArray(Q[0])){if(Q.some((J)=>J.length!==Q[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 PQ("int64",BigInt64Array.from(Q.flat().map((J)=>BigInt(J))),[Q.length,Q[0].length])}else return new PQ("int64",BigInt64Array.from(Q.map((J)=>BigInt(J))),[1,Q.length])}function W20(Q){return new PQ("bool",[Q],[1])}var II0={[RQ.DecoderOnly]:{can_generate:!0,forward:h5,prepare_inputs:vF},[RQ.DecoderOnlyWithoutHead]:{can_generate:!1,forward:h5,prepare_inputs:vF},[RQ.Seq2Seq]:{can_generate:!0,forward:YR,prepare_inputs:NR},[RQ.Vision2Seq]:{can_generate:!0,forward:YR,prepare_inputs:NR},[RQ.Musicgen]:{can_generate:!0,forward:YR},[RQ.EncoderDecoder]:{can_generate:!1,forward:YR},[RQ.ImageTextToText]:{can_generate:!0,forward:BFQ,prepare_inputs:GR},[RQ.AudioTextToText]:{can_generate:!0,forward:HFQ,prepare_inputs:GR},[RQ.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:GR},[RQ.Phi3V]:{can_generate:!0,prepare_inputs:GR},[RQ.MultiModality]:{can_generate:!0},[RQ.AutoEncoder]:{can_generate:!1,forward:GFQ},[RQ.Chatterbox]:{can_generate:!0,forward:FH},[RQ.VoxtralRealtime]:{can_generate:!0,prepare_inputs:vF},default:{can_generate:!1,forward:FH}};function RI0(Q,J){let G=b5.get(Q),H=!1,K=J?.architectures?.[0];if(K&&K!==Q&&Q?.endsWith("ForCausalLM")&&K.endsWith("ForConditionalGeneration")){let F=b5.get(K);if(F!==void 0)G=F,H=!0}let z=II0[G]??II0.default,q=x5[G]??x5.default;return{typeConfig:{...z,...q},textOnly:H,modelType:G}}var b5=new Map,Y10=new Map,CV=new Map,s0=class extends nJ{main_input_name="input_ids";forward_params=["input_ids","attention_mask"];_return_dict_in_generate_keys=null;constructor(Q,J,G){super();this.config=Q,this.sessions=J,this.configs=G;let H=CV.get(this.constructor),{typeConfig:K}=RI0(H,Q);if(this.can_generate=K.can_generate,this._forward=K.forward,this._prepare_inputs_for_generation=K.prepare_inputs,this.can_generate)this.forward_params.push("past_key_values");this.custom_config=this.config["transformers.js_config"]??{}}async dispose(){let Q=[];for(let J of Object.values(this.sessions))Q.push(J.release?.());return await Promise.all(Q)}static async from_pretrained(Q,{progress_callback:J=null,config:G=null,cache_dir:H=null,local_files_only:K=!1,revision:z="main",model_file_name:q=null,subfolder:F="onnx",device:D=null,dtype:V=null,use_external_data_format:O=null,session_options:P={}}={}){let N={progress_callback:J,config:G,cache_dir:H,local_files_only:K,revision:z,model_file_name:q,subfolder:F,device:D,dtype:V,use_external_data_format:O,session_options:P},I=CV.get(this);G=N.config=await _F.from_pretrained(Q,N);let{typeConfig:R,textOnly:w,modelType:E}=RI0(I,G);if(E===void 0){let b=I??G?.model_type;if(b!=="custom")g8.warn(`Model type for '${b}' not found, assuming encoder-only architecture. Please report this at ${SR}.`)}if(J&&!(J instanceof J90)){let b={};try{let g=await G20(Q,{config:G,dtype:V,device:D,model_file_name:q});(await Promise.all(g.map((_)=>uF(Q,_,N)))).forEach((_,a)=>{if(_.exists){let r=g[a]==="config.json";b[g[a]]={loaded:r?_.size??0:0,total:_.size??0}}})}catch(g){g8.warn(`Unable to fetch model file metadata for total progress tracking: ${g}`)}if(Object.keys(b).length>0)N.progress_callback=new J90(J,b)}let T=R.sessions(G,N,w),y=[xZQ(Q,T,N,R.cache_sessions)];if(R.optional_configs)y.push(KFQ(Q,R.optional_configs,N));let x=await Promise.all(y);return new this(G,...x)}async _call(Q){return await this.forward(Q)}async forward(Q){return await this._forward(this,Q)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(Q,J,G=null){let H=new $90;if(Q.repetition_penalty!==null&&Q.repetition_penalty!==1)H.push(new lZQ(Q.repetition_penalty));if(Q.no_repeat_ngram_size!==null&&Q.no_repeat_ngram_size>0)H.push(new pZQ(Q.no_repeat_ngram_size));if(Q.bad_words_ids!==null)H.push(new iZQ(Q.bad_words_ids,Q.eos_token_id));if(Q.min_length!==null&&Q.eos_token_id!==null&&Q.min_length>0)H.push(new dZQ(Q.min_length,Q.eos_token_id));if(Q.min_new_tokens!==null&&Q.eos_token_id!==null&&Q.min_new_tokens>0)H.push(new cZQ(J,Q.min_new_tokens,Q.eos_token_id));if(Q.forced_bos_token_id!==null)H.push(new _ZQ(Q.forced_bos_token_id));if(Q.forced_eos_token_id!==null)H.push(new fZQ(Q.max_length,Q.forced_eos_token_id));if(Q.suppress_tokens!==null)H.push(new mZQ(Q.suppress_tokens));if(Q.begin_suppress_tokens!==null){let K=J>1||Q.forced_bos_token_id===null?J:J+1;H.push(new ew0(Q.begin_suppress_tokens,K))}if(Q.guidance_scale!==null&&Q.guidance_scale>1)H.push(new oZQ(Q.guidance_scale));if(Q.temperature===0&&Q.do_sample)g8.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),Q.do_sample=!1;if(Q.do_sample){if(Q.temperature!==null&&Q.temperature!==1)H.push(new nZQ(Q.temperature))}if(G!==null)H.extend(G);return H}_prepare_generation_config(Q,J,G=Q20){let H={...this.config};for(let z of["decoder","generator","text_config"])if(z in H)Object.assign(H,H[z]);let K=new G(H);if(Object.assign(K,this.generation_config??{}),Q)Object.assign(K,Q);if(J)Object.assign(K,JX(J,Object.getOwnPropertyNames(K)));return K}_get_stopping_criteria(Q,J=null){let G=new X20;if(Q.max_length!==null)G.push(new aZQ(Q.max_length,this.config.max_position_embeddings??null));if(Q.eos_token_id!==null)G.push(new sZQ(Q.eos_token_id));if(J)G.extend(J);return G}_validate_model_class(){if(!this.can_generate){let Q=[MV.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,MV.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,MV.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,MV.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),J=CV.get(this.constructor),G=new Set,H=this.config.model_type;for(let z of Q){let q=z?.get(H);if(q)G.add(q)}let K=`The current model class (${J}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;if(G.size>0)K+=` Please use the following class instead: ${[...G].join(", ")}`;throw Error(K)}}prepare_inputs_for_generation(...Q){if(!this._prepare_inputs_for_generation)throw Error("prepare_inputs_for_generation is not implemented for this model.");return this._prepare_inputs_for_generation(this,...Q)}_update_model_kwargs_for_generation({generated_input_ids:Q,outputs:J,model_inputs:G,is_encoder_decoder:H}){if(G.past_key_values=F90(J,G.past_key_values),G.input_ids=new PQ("int64",Q.flat(),[Q.length,1]),!H)G.attention_mask=T9([G.attention_mask,oJ([G.attention_mask.dims[0],1])],1);else if("decoder_attention_mask"in G)G.decoder_attention_mask=T9([G.decoder_attention_mask,oJ([G.decoder_attention_mask.dims[0],1])],1);return G.position_ids=null,G}_prepare_model_inputs({inputs:Q,bos_token_id:J,model_kwargs:G}){let H=JX(G,this.forward_params),K=this.main_input_name;if(K in H){if(Q)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else H[K]=Q;return{inputs_tensor:H[K],model_inputs:H,model_input_name:K}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:Q,model_inputs:J,model_input_name:G,generation_config:H}){if(this.sessions.model.inputNames.includes("inputs_embeds")&&!J.inputs_embeds&&"_prepare_inputs_embeds"in this){let{input_ids:z,pixel_values:q,attention_mask:F,...D}=J,V=await this._prepare_inputs_embeds(J);J={...D,...JX(V,["inputs_embeds","attention_mask"])}}let{last_hidden_state:K}=await FH(this,J);if(H.guidance_scale!==null&&H.guidance_scale>1){if(K=T9([K,V90(K,0)],0),"attention_mask"in J)J.attention_mask=T9([J.attention_mask,Hw0(J.attention_mask)],0)}else if(J.decoder_input_ids){let z=Z90(J.decoder_input_ids).dims[0];if(z!==K.dims[0]){if(K.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${K.dims[0]}) than the decoder inputs (${z}).`);K=T9(Array.from({length:z},()=>K),0)}}return J.encoder_outputs=K,J}_prepare_decoder_input_ids_for_generation({batch_size:Q,model_input_name:J,model_kwargs:G,decoder_start_token_id:H,bos_token_id:K,generation_config:z}){let{decoder_input_ids:q,...F}=G;if(!(q instanceof PQ)){if(!q)if(H??=K,this.config.model_type==="musicgen")q=Array.from({length:Q*this.config.decoder.num_codebooks},()=>[H]);else if(Array.isArray(H)){if(H.length!==Q)throw Error(`\`decoder_start_token_id\` expcted to have length ${Q} but got ${H.length}`);q=H}else q=Array.from({length:Q},()=>[H]);else if(!Array.isArray(q[0]))q=Array.from({length:Q},()=>q);q=Z90(q)}return F.decoder_attention_mask=Gw0(q),{input_ids:q,model_inputs:F}}async generate({inputs:Q=null,generation_config:J=null,logits_processor:G=null,stopping_criteria:H=null,streamer:K=null,...z}){this._validate_model_class(),J=this._prepare_generation_config(J,z);let{inputs_tensor:q,model_inputs:F,model_input_name:D}=this._prepare_model_inputs({inputs:Q,model_kwargs:z}),V=this.config.is_encoder_decoder;if(!V);else if(!("encoder_outputs"in F))F=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:q,model_inputs:F,model_input_name:D,generation_config:J});let O;if(V)({input_ids:O,model_inputs:F}=this._prepare_decoder_input_ids_for_generation({batch_size:F[D].dims.at(0),model_input_name:D,model_kwargs:F,decoder_start_token_id:J.decoder_start_token_id,bos_token_id:J.bos_token_id,generation_config:J}));else O=F[D];let P=O.dims.at(-1);if(J.max_new_tokens!==null)J.max_length=P+J.max_new_tokens;let N=this._get_logits_processor(J,P,G),I=this._get_stopping_criteria(J,H),R=F[D].dims.at(0),w=vR.getSampler(J),E=Array(R).fill(0),T=O.tolist();if(K)K.put(T);let y,x={},b={};while(!0){if(F=this.prepare_inputs_for_generation(T,F,J),y=await this.forward(F),J.return_dict_in_generate){if(J.output_attentions){let u0=WFQ(y);for(let d in u0){if(!(d in x))x[d]=[];x[d].push(u0[d])}}else if(this._return_dict_in_generate_keys)Object.assign(b,JX(y,this._return_dict_in_generate_keys))}let r=y.logits.slice(null,-1,null).to("float32"),f0=N(T,r),t=[];for(let u0=0;u0<f0.dims.at(0);++u0){let d=f0[u0],n=await w(d);for(let[c0,WQ]of n){let R0=BigInt(c0);E[u0]+=WQ,T[u0].push(R0),t.push([R0]);break}}if(K)K.put(t);if(I(T).every((u0)=>u0))break;F=this._update_model_kwargs_for_generation({generated_input_ids:t,outputs:y,model_inputs:F,is_encoder_decoder:V})}if(K)K.end();let g=new PQ("int64",T.flat(),[T.length,T[0].length]),l=F90(y,F.past_key_values),_=new Set(Object.values(l));for(let r of Object.values(y))if(r.location==="gpu-buffer"&&!_.has(r))r.dispose();if(!(("past_key_values"in z)||J.return_dict_in_generate))await l.dispose();if(J.return_dict_in_generate)return{sequences:g,past_key_values:l,...x,...b};return g}async _encode_input(Q,J,G){if(!Object.hasOwn(this.sessions,Q))throw Error(`Model does not have a ${Q} session.`);let H=this.sessions[Q];return(await E6(H,JX(J,H.inputNames)))[G]}async encode_image(Q){return this._encode_input("vision_encoder",Q,"image_features")}async encode_text(Q){return this._encode_input("embed_tokens",Q,"inputs_embeds")}async encode_audio(Q){return this._encode_input("audio_encoder",Q,"audio_features")}};async function YR(Q,J){let{encoder_outputs:G,input_ids:H,decoder_input_ids:K,decoder_attention_mask:z,...q}=J;if(!G){let F=JX(J,Q.sessions.model.inputNames);G=(await FH(Q,F)).last_hidden_state}if(q.input_ids=K,q.encoder_hidden_states=G,Q.sessions.decoder_model_merged.inputNames.includes("encoder_attention_mask"))q.encoder_attention_mask=J.attention_mask;if(z&&!q.attention_mask)q.attention_mask=z;return await h5(Q,q,!0)}async function FH(Q,J){let G=Q.sessions.model,H=JX(J,G.inputNames);if(G.inputNames.includes("inputs_embeds")&&!H.inputs_embeds){if(!J.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");H.inputs_embeds=await Q.encode_text({input_ids:J.input_ids})}if(G.inputNames.includes("token_type_ids")&&!H.token_type_ids){if(!H.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");H.token_type_ids=Hw0(H.input_ids)}if(G.inputNames.includes("pixel_mask")&&!H.pixel_mask){if(!H.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let K=H.pixel_values.dims;H.pixel_mask=oJ([K[0],K[2],K[3]])}return await E6(G,H)}async function GFQ(Q,J){let G=await Q.encode(J);return await Q.decode(G)}function F90(Q,J){let G=Object.create(null);for(let H in Q)if(H.startsWith("present")){let K=H.replace("present_ssm","past_ssm").replace("present_conv","past_conv").replace("present_recurrent","past_recurrent").replace("present","past_key_values");if(H.includes("encoder")&&J)G[K]=J[K];else G[K]=Q[H]}if(J)return J.update(G),J;return new J10(G)}function WFQ(Q){let J={};for(let G of["cross_attentions","encoder_attentions","decoder_attentions"])for(let H in Q)if(H.startsWith(G)){if(!(G in J))J[G]=[];J[G].push(Q[H])}return J}function H20(Q,J){return Q.map((G)=>{if(typeof G==="number")return G;return J[G]??0})}function G10(Q,J,G){if(G&&Object.keys(G).length>0)return Object.assign(J,G),G;let H=Q.sessions.decoder_model_merged??Q.sessions.model,K=(J[Q.main_input_name]??J.attention_mask)?.dims?.[0]??1,z=kR(Q.config),q=Q.config?.normalized_config?.num_heads,F={batch_size:K};if(typeof q==="number")F["batch_size x num_heads"]=K*q;let D=Object.create(null);for(let V of H.inputMetadata){if(!z.has(V.name))continue;let O=H20(V.shape,F),P=O.reduce((R,w)=>R*w,1),N=gF[V.type],I=new PQ(V.type,new N(P),O);J[V.name]=I,D[V.name]=I}if(G)return G.update(D),G;return new J10(D)}async function h5(Q,J,G=!1){let H=Q.sessions[G?"decoder_model_merged":"model"],{past_key_values:K,...z}=J;if(H.inputNames.includes("use_cache_branch"))z.use_cache_branch=W20(K!=null&&Object.keys(K).length>0);if(H.inputNames.includes("position_ids")&&z.attention_mask&&!z.position_ids){let F=["paligemma","gemma3_text","gemma3"].includes(Q.config.model_type)?1:0;z.position_ids=AFQ(z,K,F)}if(H.inputNames.includes("num_logits_to_keep")&&!z.num_logits_to_keep)z.num_logits_to_keep=new PQ("int64",[0n],[]);G10(Q,z,K);let q=JX(z,H.inputNames);return await E6(H,q)}async function B20(Q,{encode_function:J,merge_function:G,modality_input_names:H,modality_output_name:K,input_ids:z=null,attention_mask:q=null,position_ids:F=null,inputs_embeds:D=null,past_key_values:V=null,generation_config:O=null,logits_processor:P=null,...N}){if(!D){D=await Q.encode_text({input_ids:z,...N});let R=JX(N,H);if(Object.keys(R).length>0){if(z.dims[1]!==1){let w=await J({...R,...N});({inputs_embeds:D,attention_mask:q}=G({[K]:w,inputs_embeds:D,input_ids:z,attention_mask:q}))}else if(V&&z.dims[1]===1){let w=z.dims[1],E=V.get_seq_length();q=T9([oJ([z.dims[0],E]),q.slice(null,[q.dims[1]-w,q.dims[1]])],1)}}}if(!F){if(["qwen2_vl","qwen2_vl_text","qwen2_5_vl","qwen2_5_vl_text","qwen3_vl","qwen3_vl_text","qwen3_vl_moe","qwen3_vl_moe_text","qwen3_5","qwen3_5_text","qwen3_5_moe","qwen3_5_moe_text","glm_ocr","glm_ocr_text"].includes(Q.config.model_type)){let{image_grid_thw:R,video_grid_thw:w}=N;[F]=Q.get_rope_index(z,R,w,q)}}return await h5(Q,{inputs_embeds:D,past_key_values:V,attention_mask:q,position_ids:F,generation_config:O,logits_processor:P},!0)}async function HFQ(Q,J){return await B20(Q,{...J,modality_input_names:["audio_values","input_features"],modality_output_name:"audio_features",encode_function:Q.encode_audio.bind(Q),merge_function:Q._merge_input_ids_with_audio_features.bind(Q)})}async function BFQ(Q,J){return await B20(Q,{...J,modality_input_names:["pixel_values"],modality_output_name:"image_features",encode_function:Q.encode_image.bind(Q),merge_function:Q._merge_input_ids_with_image_features.bind(Q)})}function A20(Q,J=0){let[G,H]=Q.dims,K=Q.data,z=new BigInt64Array(K.length);for(let q=0;q<G;++q){let F=q*H,D=BigInt(J);for(let V=0;V<H;++V){let O=F+V;if(K[O]===0n)z[O]=BigInt(1);else z[O]=D,D+=K[O]}}return{data:z,dims:Q.dims}}function AFQ(Q,J=null,G=0){let{input_ids:H,inputs_embeds:K,attention_mask:z}=Q,{data:q,dims:F}=A20(z,G),D=new PQ("int64",q,F);if(J){let V=-(H??K).dims.at(1);D=D.slice(null,[V,null])}return D}function vF(Q,J,G,H){let K=G.past_key_values?G.past_key_values.get_seq_length():0;if((Q.sessions.decoder_model_merged??Q.sessions.model)?.inputNames.includes("num_logits_to_keep")&&!G.num_logits_to_keep)G.num_logits_to_keep=new PQ("int64",[1n],[]);if(!G.attention_mask){let q;for(let F of["input_ids","inputs_embeds","position_ids"])if(G[F]){q=G[F].dims;break}if(!q)throw Error("attention_mask is not provided, and unable to infer its shape from model inputs.");G.attention_mask=oJ([q[0],K+q[1]])}if(G.past_key_values){let{input_ids:q,attention_mask:F}=G;if(F&&F.dims[1]>q.dims[1]);else if(K<q.dims[1])G.input_ids=q.slice(null,[K,null])}return G}function NR(Q,J,G,H){if(G.past_key_values)J=J.map((K)=>[K.at(-1)]);return{...G,decoder_input_ids:Z90(J)}}function GR(Q,...J){if(Q.config.is_encoder_decoder)return NR(Q,...J);else return vF(Q,...J)}function K20({modality_token_id:Q,inputs_embeds:J,modality_features:G,input_ids:H,attention_mask:K}){let z=H.tolist().map((V)=>V.reduce((O,P,N)=>{if(P==Q)O.push(N);return O},[])),q=z.reduce((V,O)=>V+O.length,0),F=G.dims[0];if(q!==F)throw Error(`Number of tokens and features do not match: tokens: ${q}, features ${F}`);let D=0;for(let V=0;V<z.length;++V){let O=z[V],P=J[V];for(let N=0;N<O.length;++N)P[O[N]].data.set(G[D++].data)}return{inputs_embeds:J,attention_mask:K}}function W10({image_token_id:Q,inputs_embeds:J,image_features:G,input_ids:H,attention_mask:K}){return K20({modality_token_id:Q,inputs_embeds:J,modality_features:G,input_ids:H,attention_mask:K})}function z20({audio_token_id:Q,inputs_embeds:J,audio_features:G,input_ids:H,attention_mask:K}){return K20({modality_token_id:Q,inputs_embeds:J,modality_features:G,input_ids:H,attention_mask:K})}async function KFQ(Q,J,G){return Object.fromEntries(await Promise.all(Object.keys(J).map(async(H)=>{let K=await bW(Q,J[H],!1,G);return[H,K]})))}var H10={};IV(H10,{ASTForAudioClassification:()=>PFQ,ASTModel:()=>OFQ,ASTPreTrainedModel:()=>z10,AfmoeForCausalLM:()=>DFQ,AfmoeModel:()=>FFQ,AfmoePreTrainedModel:()=>A10,AlbertForMaskedLM:()=>UFQ,AlbertForQuestionAnswering:()=>qFQ,AlbertForSequenceClassification:()=>VFQ,AlbertModel:()=>zFQ,AlbertPreTrainedModel:()=>lF,ApertusForCausalLM:()=>ZFQ,ApertusModel:()=>$FQ,ApertusPreTrainedModel:()=>B10,ArceeForCausalLM:()=>LFQ,ArceeModel:()=>MFQ,ArceePreTrainedModel:()=>K10,BartForConditionalGeneration:()=>jFQ,BartForSequenceClassification:()=>CFQ,BartModel:()=>NFQ,BartPretrainedModel:()=>xR,BeitForImageClassification:()=>RFQ,BeitModel:()=>IFQ,BeitPreTrainedModel:()=>V10,BertForMaskedLM:()=>EFQ,BertForQuestionAnswering:()=>kFQ,BertForSequenceClassification:()=>SFQ,BertForTokenClassification:()=>TFQ,BertModel:()=>wFQ,BertPreTrainedModel:()=>TV,BlenderbotForConditionalGeneration:()=>vFQ,BlenderbotModel:()=>yFQ,BlenderbotPreTrainedModel:()=>q10,BlenderbotSmallForConditionalGeneration:()=>bFQ,BlenderbotSmallModel:()=>xFQ,BlenderbotSmallPreTrainedModel:()=>U10,BloomForCausalLM:()=>hFQ,BloomModel:()=>gFQ,BloomPreTrainedModel:()=>$10,CHMv2ForDepthEstimation:()=>cFQ,CHMv2PreTrainedModel:()=>$20,CLIPModel:()=>oFQ,CLIPPreTrainedModel:()=>qB,CLIPSegForImageSegmentation:()=>tFQ,CLIPSegModel:()=>rFQ,CLIPSegPreTrainedModel:()=>Z10,CLIPTextModel:()=>nFQ,CLIPTextModelWithProjection:()=>D20,CLIPVisionModel:()=>aFQ,CLIPVisionModelWithProjection:()=>sFQ,CamembertForMaskedLM:()=>fFQ,CamembertForQuestionAnswering:()=>pFQ,CamembertForSequenceClassification:()=>mFQ,CamembertForTokenClassification:()=>uFQ,CamembertModel:()=>_FQ,CamembertPreTrainedModel:()=>kV,ChatterboxModel:()=>q20,ChatterboxPreTrainedModel:()=>V20,ChineseCLIPModel:()=>dFQ,ChineseCLIPPreTrainedModel:()=>U20,ClapAudioModelWithProjection:()=>F20,ClapModel:()=>iFQ,ClapPreTrainedModel:()=>bR,ClapTextModelWithProjection:()=>Z20,CodeGenForCausalLM:()=>QDQ,CodeGenModel:()=>eFQ,CodeGenPreTrainedModel:()=>F10,Cohere2ForCausalLM:()=>GDQ,Cohere2Model:()=>YDQ,Cohere2PreTrainedModel:()=>M10,CohereAsrForConditionalGeneration:()=>HDQ,CohereAsrModel:()=>WDQ,CohereAsrPreTrainedModel:()=>L10,CohereForCausalLM:()=>JDQ,CohereModel:()=>XDQ,CoherePreTrainedModel:()=>D10,ConvBertForMaskedLM:()=>ADQ,ConvBertForQuestionAnswering:()=>VDQ,ConvBertForSequenceClassification:()=>KDQ,ConvBertForTokenClassification:()=>zDQ,ConvBertModel:()=>BDQ,ConvBertPreTrainedModel:()=>yV,ConvNextForImageClassification:()=>UDQ,ConvNextModel:()=>qDQ,ConvNextPreTrainedModel:()=>O10,ConvNextV2ForImageClassification:()=>ZDQ,ConvNextV2Model:()=>$DQ,ConvNextV2PreTrainedModel:()=>P10,DFineForObjectDetection:()=>LDQ,DFineModel:()=>MDQ,DFinePreTrainedModel:()=>j10,DINOv3ConvNextModel:()=>cDQ,DINOv3ConvNextPreTrainedModel:()=>R20,DINOv3ViTModel:()=>iDQ,DINOv3ViTPreTrainedModel:()=>w20,DPTForDepthEstimation:()=>QMQ,DPTModel:()=>eDQ,DPTPreTrainedModel:()=>S10,DacDecoderModel:()=>P20,DacDecoderOutput:()=>L20,DacEncoderModel:()=>O20,DacEncoderOutput:()=>M20,DacModel:()=>ODQ,DacPreTrainedModel:()=>gR,DebertaForMaskedLM:()=>NDQ,DebertaForQuestionAnswering:()=>IDQ,DebertaForSequenceClassification:()=>jDQ,DebertaForTokenClassification:()=>CDQ,DebertaModel:()=>PDQ,DebertaPreTrainedModel:()=>vV,DebertaV2ForMaskedLM:()=>SDQ,DebertaV2ForQuestionAnswering:()=>yDQ,DebertaV2ForSequenceClassification:()=>TDQ,DebertaV2ForTokenClassification:()=>kDQ,DebertaV2Model:()=>EDQ,DebertaV2PreTrainedModel:()=>xV,DecisionTransformerModel:()=>vDQ,DecisionTransformerPreTrainedModel:()=>N20,DeepseekV3ForCausalLM:()=>wDQ,DeepseekV3Model:()=>RDQ,DeepseekV3PreTrainedModel:()=>C10,DeiTForImageClassification:()=>bDQ,DeiTModel:()=>xDQ,DeiTPreTrainedModel:()=>I10,DepthAnythingForDepthEstimation:()=>gDQ,DepthAnythingPreTrainedModel:()=>j20,DepthProForDepthEstimation:()=>hDQ,DepthProPreTrainedModel:()=>C20,DetrForObjectDetection:()=>fDQ,DetrForSegmentation:()=>mDQ,DetrModel:()=>_DQ,DetrObjectDetectionOutput:()=>R10,DetrPreTrainedModel:()=>hR,DetrSegmentationOutput:()=>I20,Dinov2ForImageClassification:()=>pDQ,Dinov2Model:()=>uDQ,Dinov2PreTrainedModel:()=>w10,Dinov2WithRegistersForImageClassification:()=>dDQ,Dinov2WithRegistersModel:()=>lDQ,Dinov2WithRegistersPreTrainedModel:()=>E10,DistilBertForMaskedLM:()=>rDQ,DistilBertForQuestionAnswering:()=>sDQ,DistilBertForSequenceClassification:()=>nDQ,DistilBertForTokenClassification:()=>aDQ,DistilBertModel:()=>oDQ,DistilBertPreTrainedModel:()=>bV,DonutSwinModel:()=>tDQ,DonutSwinPreTrainedModel:()=>E20,EdgeTamModel:()=>VNQ,EfficientNetForImageClassification:()=>JMQ,EfficientNetModel:()=>XMQ,EfficientNetPreTrainedModel:()=>T10,ElectraForMaskedLM:()=>GMQ,ElectraForQuestionAnswering:()=>BMQ,ElectraForSequenceClassification:()=>WMQ,ElectraForTokenClassification:()=>HMQ,ElectraModel:()=>YMQ,ElectraPreTrainedModel:()=>gV,Ernie4_5ForCausalLM:()=>KMQ,Ernie4_5Model:()=>AMQ,Ernie4_5PretrainedModel:()=>k10,EsmForMaskedLM:()=>VMQ,EsmForSequenceClassification:()=>qMQ,EsmForTokenClassification:()=>UMQ,EsmModel:()=>zMQ,EsmPreTrainedModel:()=>cF,EuroBertForMaskedLM:()=>ZMQ,EuroBertForSequenceClassification:()=>FMQ,EuroBertForTokenClassification:()=>DMQ,EuroBertModel:()=>$MQ,EuroBertPreTrainedModel:()=>iF,ExaoneForCausalLM:()=>LMQ,ExaoneModel:()=>MMQ,ExaonePreTrainedModel:()=>y10,FalconForCausalLM:()=>PMQ,FalconH1ForCausalLM:()=>jMQ,FalconH1Model:()=>NMQ,FalconH1PreTrainedModel:()=>x10,FalconModel:()=>OMQ,FalconPreTrainedModel:()=>v10,FastViTForImageClassification:()=>IMQ,FastViTModel:()=>CMQ,FastViTPreTrainedModel:()=>b10,Florence2ForConditionalGeneration:()=>RMQ,Florence2PreTrainedModel:()=>S20,GLPNForDepthEstimation:()=>lMQ,GLPNModel:()=>pMQ,GLPNPreTrainedModel:()=>l10,GPT2LMHeadModel:()=>eMQ,GPT2Model:()=>tMQ,GPT2PreTrainedModel:()=>n10,GPTBigCodeForCausalLM:()=>cMQ,GPTBigCodeModel:()=>dMQ,GPTBigCodePreTrainedModel:()=>d10,GPTJForCausalLM:()=>XLQ,GPTJModel:()=>QLQ,GPTJPreTrainedModel:()=>a10,GPTNeoForCausalLM:()=>oMQ,GPTNeoModel:()=>iMQ,GPTNeoPreTrainedModel:()=>c10,GPTNeoXForCausalLM:()=>aMQ,GPTNeoXModel:()=>nMQ,GPTNeoXPreTrainedModel:()=>i10,Gemma2ForCausalLM:()=>TMQ,Gemma2Model:()=>SMQ,Gemma2PreTrainedModel:()=>h10,Gemma3ForCausalLM:()=>xMQ,Gemma3ForConditionalGeneration:()=>y20,Gemma3Model:()=>vMQ,Gemma3PreTrainedModel:()=>k20,Gemma3nForCausalLM:()=>bMQ,Gemma3nForConditionalGeneration:()=>_R,Gemma3nPreTrainedModel:()=>v20,Gemma4ForCausalLM:()=>gMQ,Gemma4ForConditionalGeneration:()=>_10,GemmaForCausalLM:()=>EMQ,GemmaModel:()=>wMQ,GemmaPreTrainedModel:()=>g10,GlmForCausalLM:()=>_MQ,GlmModel:()=>hMQ,GlmMoeDsaForCausalLM:()=>mMQ,GlmMoeDsaModel:()=>fMQ,GlmMoeDsaPreTrainedModel:()=>m10,GlmOcrForConditionalGeneration:()=>uMQ,GlmPreTrainedModel:()=>f10,GptOssForCausalLM:()=>rMQ,GptOssModel:()=>sMQ,GptOssPreTrainedModel:()=>o10,GraniteForCausalLM:()=>YLQ,GraniteModel:()=>JLQ,GraniteMoeHybridForCausalLM:()=>WLQ,GraniteMoeHybridModel:()=>GLQ,GraniteMoeHybridPreTrainedModel:()=>r10,GranitePreTrainedModel:()=>s10,GraniteSpeechForConditionalGeneration:()=>HLQ,GroundingDinoForObjectDetection:()=>BLQ,GroundingDinoPreTrainedModel:()=>_20,GroupViTModel:()=>ALQ,GroupViTPreTrainedModel:()=>f20,HeliumForCausalLM:()=>zLQ,HeliumModel:()=>KLQ,HeliumPreTrainedModel:()=>e10,HieraForImageClassification:()=>qLQ,HieraModel:()=>VLQ,HieraPreTrainedModel:()=>Q70,HubertForCTC:()=>LLQ,HubertForSequenceClassification:()=>OLQ,HubertModel:()=>MLQ,HubertPreTrainedModel:()=>DLQ,HunYuanDenseV1ForCausalLM:()=>NLQ,HunYuanDenseV1Model:()=>PLQ,HunYuanDenseV1PreTrainedModel:()=>X70,IJepaForImageClassification:()=>CLQ,IJepaModel:()=>jLQ,IJepaPreTrainedModel:()=>J70,Idefics3ForConditionalGeneration:()=>m20,JAISLMHeadModel:()=>RLQ,JAISModel:()=>ILQ,JAISPreTrainedModel:()=>Y70,JinaCLIPModel:()=>wLQ,JinaCLIPPreTrainedModel:()=>fR,JinaCLIPTextModel:()=>u20,JinaCLIPVisionModel:()=>ELQ,Lfm2ForCausalLM:()=>TLQ,Lfm2Model:()=>SLQ,Lfm2MoeForCausalLM:()=>vLQ,Lfm2MoeModel:()=>yLQ,Lfm2MoePreTrainedModel:()=>W70,Lfm2PreTrainedModel:()=>G70,Lfm2VlForConditionalGeneration:()=>xLQ,LightOnOcrForConditionalGeneration:()=>kLQ,LiteWhisperForConditionalGeneration:()=>yjQ,Llama4ForCausalLM:()=>hLQ,Llama4PreTrainedModel:()=>p20,LlamaForCausalLM:()=>gLQ,LlamaModel:()=>bLQ,LlamaPreTrainedModel:()=>H70,LlavaForConditionalGeneration:()=>_5,LlavaOnevisionForConditionalGeneration:()=>_5,LlavaPreTrainedModel:()=>T20,LlavaQwen2ForCausalLM:()=>yMQ,LongT5ForConditionalGeneration:()=>fLQ,LongT5Model:()=>_LQ,LongT5PreTrainedModel:()=>B70,M2M100ForConditionalGeneration:()=>uLQ,M2M100Model:()=>mLQ,M2M100PreTrainedModel:()=>A70,MBartForCausalLM:()=>aLQ,MBartForConditionalGeneration:()=>oLQ,MBartForSequenceClassification:()=>nLQ,MBartModel:()=>iLQ,MBartPreTrainedModel:()=>oF,MPNetForMaskedLM:()=>bOQ,MPNetForQuestionAnswering:()=>_OQ,MPNetForSequenceClassification:()=>gOQ,MPNetForTokenClassification:()=>hOQ,MPNetModel:()=>xOQ,MPNetPreTrainedModel:()=>hV,MT5ForConditionalGeneration:()=>pOQ,MT5Model:()=>uOQ,MT5PreTrainedModel:()=>L70,MarianMTModel:()=>lLQ,MarianModel:()=>pLQ,MarianPreTrainedModel:()=>K70,MaskFormerForInstanceSegmentation:()=>cLQ,MaskFormerModel:()=>dLQ,MaskFormerPreTrainedModel:()=>z70,Metric3DForDepthEstimation:()=>sLQ,Metric3DPreTrainedModel:()=>l20,Metric3Dv2ForDepthEstimation:()=>rLQ,Metric3Dv2PreTrainedModel:()=>d20,MgpstrForSceneTextRecognition:()=>tLQ,MgpstrModelOutput:()=>c20,MgpstrPreTrainedModel:()=>i20,MimiDecoderModel:()=>s20,MimiDecoderOutput:()=>n20,MimiEncoderModel:()=>a20,MimiEncoderOutput:()=>o20,MimiModel:()=>eLQ,MimiPreTrainedModel:()=>mR,Mistral4ForCausalLM:()=>YOQ,Mistral4Model:()=>JOQ,Mistral4PreTrainedModel:()=>q70,MistralForCausalLM:()=>XOQ,MistralModel:()=>QOQ,MistralPreTrainedModel:()=>V70,MobileBertForMaskedLM:()=>WOQ,MobileBertForQuestionAnswering:()=>BOQ,MobileBertForSequenceClassification:()=>HOQ,MobileBertModel:()=>GOQ,MobileBertPreTrainedModel:()=>nF,MobileLLMForCausalLM:()=>KOQ,MobileLLMModel:()=>AOQ,MobileLLMPreTrainedModel:()=>U70,MobileNetV1ForImageClassification:()=>VOQ,MobileNetV1ForSemanticSegmentation:()=>qOQ,MobileNetV1Model:()=>zOQ,MobileNetV1PreTrainedModel:()=>uR,MobileNetV2ForImageClassification:()=>$OQ,MobileNetV2ForSemanticSegmentation:()=>ZOQ,MobileNetV2Model:()=>UOQ,MobileNetV2PreTrainedModel:()=>pR,MobileNetV3ForImageClassification:()=>DOQ,MobileNetV3ForSemanticSegmentation:()=>MOQ,MobileNetV3Model:()=>FOQ,MobileNetV3PreTrainedModel:()=>lR,MobileNetV4ForImageClassification:()=>OOQ,MobileNetV4ForSemanticSegmentation:()=>POQ,MobileNetV4Model:()=>LOQ,MobileNetV4PreTrainedModel:()=>dR,MobileViTForImageClassification:()=>jOQ,MobileViTModel:()=>NOQ,MobileViTPreTrainedModel:()=>$70,MobileViTV2ForImageClassification:()=>IOQ,MobileViTV2Model:()=>COQ,MobileViTV2PreTrainedModel:()=>Z70,ModernBertDecoderForCausalLM:()=>kOQ,ModernBertDecoderModel:()=>TOQ,ModernBertDecoderPreTrainedModel:()=>F70,ModernBertForMaskedLM:()=>wOQ,ModernBertForSequenceClassification:()=>EOQ,ModernBertForTokenClassification:()=>SOQ,ModernBertModel:()=>ROQ,ModernBertPreTrainedModel:()=>aF,Moondream1ForConditionalGeneration:()=>kMQ,MoonshineForConditionalGeneration:()=>vOQ,MoonshineModel:()=>yOQ,MoonshinePreTrainedModel:()=>D70,MptForCausalLM:()=>mOQ,MptModel:()=>fOQ,MptPreTrainedModel:()=>M70,MultiModalityCausalLM:()=>lOQ,MultiModalityPreTrainedModel:()=>r20,MusicgenForCausalLM:()=>cOQ,MusicgenForConditionalGeneration:()=>t20,MusicgenModel:()=>dOQ,MusicgenPreTrainedModel:()=>O70,NanoChatForCausalLM:()=>oOQ,NanoChatModel:()=>iOQ,NanoChatPreTrainedModel:()=>P70,NemotronHForCausalLM:()=>aOQ,NemotronHModel:()=>nOQ,NemotronHPreTrainedModel:()=>N70,NeoBertForMaskedLM:()=>rOQ,NeoBertForQuestionAnswering:()=>QPQ,NeoBertForSequenceClassification:()=>tOQ,NeoBertForTokenClassification:()=>eOQ,NeoBertModel:()=>sOQ,NeoBertPreTrainedModel:()=>_V,NomicBertModel:()=>XPQ,NomicBertPreTrainedModel:()=>e20,OPTForCausalLM:()=>ZPQ,OPTModel:()=>$PQ,OPTPreTrainedModel:()=>S70,Olmo2ForCausalLM:()=>WPQ,Olmo2Model:()=>GPQ,Olmo2PreTrainedModel:()=>C70,Olmo3ForCausalLM:()=>BPQ,Olmo3Model:()=>HPQ,Olmo3PreTrainedModel:()=>I70,OlmoForCausalLM:()=>YPQ,OlmoHybridForCausalLM:()=>KPQ,OlmoHybridModel:()=>APQ,OlmoHybridPreTrainedModel:()=>R70,OlmoModel:()=>JPQ,OlmoPreTrainedModel:()=>j70,OpenAIPrivacyFilterForTokenClassification:()=>VPQ,OpenAIPrivacyFilterModel:()=>zPQ,OpenAIPrivacyFilterPreTrainedModel:()=>w70,OpenELMForCausalLM:()=>UPQ,OpenELMModel:()=>qPQ,OpenELMPreTrainedModel:()=>E70,OwlViTForObjectDetection:()=>LPQ,OwlViTModel:()=>MPQ,OwlViTPreTrainedModel:()=>k70,Owlv2ForObjectDetection:()=>DPQ,Owlv2Model:()=>FPQ,Owlv2PreTrainedModel:()=>T70,PaliGemmaForConditionalGeneration:()=>OPQ,ParakeetForCTC:()=>PPQ,ParakeetPreTrainedModel:()=>QE0,PatchTSMixerForPrediction:()=>jPQ,PatchTSMixerModel:()=>NPQ,PatchTSMixerPreTrainedModel:()=>y70,PatchTSTForPrediction:()=>IPQ,PatchTSTModel:()=>CPQ,PatchTSTPreTrainedModel:()=>v70,Phi3ForCausalLM:()=>SPQ,Phi3Model:()=>EPQ,Phi3PreTrainedModel:()=>b70,Phi3VForCausalLM:()=>JE0,Phi3VPreTrainedModel:()=>XE0,PhiForCausalLM:()=>wPQ,PhiModel:()=>RPQ,PhiPreTrainedModel:()=>x70,PreTrainedModel:()=>s0,PvtForImageClassification:()=>kPQ,PvtModel:()=>TPQ,PvtPreTrainedModel:()=>g70,PyAnnoteForAudioFrameClassification:()=>vPQ,PyAnnoteModel:()=>yPQ,PyAnnotePreTrainedModel:()=>h70,Qwen2ForCausalLM:()=>bPQ,Qwen2Model:()=>xPQ,Qwen2MoeForCausalLM:()=>hPQ,Qwen2MoeModel:()=>gPQ,Qwen2MoePreTrainedModel:()=>f70,Qwen2PreTrainedModel:()=>_70,Qwen2VLForCausalLM:()=>b20,Qwen2VLForConditionalGeneration:()=>u10,Qwen2VLPreTrainedModel:()=>x20,Qwen2_5_VLForCausalLM:()=>g20,Qwen2_5_VLForConditionalGeneration:()=>p10,Qwen3ForCausalLM:()=>fPQ,Qwen3Model:()=>_PQ,Qwen3MoeForCausalLM:()=>uPQ,Qwen3MoeModel:()=>mPQ,Qwen3MoePreTrainedModel:()=>u70,Qwen3NextForCausalLM:()=>lPQ,Qwen3NextModel:()=>pPQ,Qwen3NextPreTrainedModel:()=>p70,Qwen3PreTrainedModel:()=>m70,Qwen3VLForCausalLM:()=>YE0,Qwen3VLForConditionalGeneration:()=>l70,Qwen3VLMoeForCausalLM:()=>cPQ,Qwen3VLMoeForConditionalGeneration:()=>dPQ,Qwen3_5ForCausalLM:()=>GE0,Qwen3_5ForConditionalGeneration:()=>d70,Qwen3_5MoeForCausalLM:()=>oPQ,Qwen3_5MoeForConditionalGeneration:()=>iPQ,RFDetrForObjectDetection:()=>rPQ,RFDetrModel:()=>sPQ,RFDetrObjectDetectionOutput:()=>WE0,RFDetrPreTrainedModel:()=>i70,RTDetrForObjectDetection:()=>DDQ,RTDetrModel:()=>FDQ,RTDetrObjectDetectionOutput:()=>dF,RTDetrPreTrainedModel:()=>N10,RTDetrV2ForObjectDetection:()=>KNQ,RTDetrV2Model:()=>ANQ,RTDetrV2ObjectDetectionOutput:()=>HE0,RTDetrV2PreTrainedModel:()=>o70,ResNetForImageClassification:()=>aPQ,ResNetModel:()=>nPQ,ResNetPreTrainedModel:()=>c70,RoFormerForMaskedLM:()=>GNQ,RoFormerForQuestionAnswering:()=>BNQ,RoFormerForSequenceClassification:()=>WNQ,RoFormerForTokenClassification:()=>HNQ,RoFormerModel:()=>YNQ,RoFormerPreTrainedModel:()=>mV,RobertaForMaskedLM:()=>ePQ,RobertaForQuestionAnswering:()=>JNQ,RobertaForSequenceClassification:()=>QNQ,RobertaForTokenClassification:()=>XNQ,RobertaModel:()=>tPQ,RobertaPreTrainedModel:()=>fV,Sam2ImageSegmentationOutput:()=>KE0,Sam2Model:()=>n70,Sam2PreTrainedModel:()=>zE0,Sam3TrackerModel:()=>qNQ,SamImageSegmentationOutput:()=>BE0,SamModel:()=>zNQ,SamPreTrainedModel:()=>AE0,SapiensForDepthEstimation:()=>$NQ,SapiensForNormalEstimation:()=>ZNQ,SapiensForSemanticSegmentation:()=>UNQ,SapiensPreTrainedModel:()=>cR,SegformerForImageClassification:()=>DNQ,SegformerForSemanticSegmentation:()=>MNQ,SegformerModel:()=>FNQ,SegformerPreTrainedModel:()=>iR,SiglipModel:()=>LNQ,SiglipPreTrainedModel:()=>a70,SiglipTextModel:()=>VE0,SiglipVisionModel:()=>ONQ,SmolLM3ForCausalLM:()=>NNQ,SmolLM3Model:()=>PNQ,SmolLM3PreTrainedModel:()=>s70,SmolVLMForConditionalGeneration:()=>jNQ,SnacDecoderModel:()=>UE0,SnacEncoderModel:()=>qE0,SnacModel:()=>CNQ,SnacPreTrainedModel:()=>oR,SolarOpenForCausalLM:()=>RNQ,SolarOpenModel:()=>INQ,SolarOpenPreTrainedModel:()=>r70,SpeechT5ForSpeechToText:()=>ENQ,SpeechT5ForTextToSpeech:()=>SNQ,SpeechT5HifiGan:()=>TNQ,SpeechT5Model:()=>wNQ,SpeechT5PreTrainedModel:()=>nR,SqueezeBertForMaskedLM:()=>yNQ,SqueezeBertForQuestionAnswering:()=>xNQ,SqueezeBertForSequenceClassification:()=>vNQ,SqueezeBertModel:()=>kNQ,SqueezeBertPreTrainedModel:()=>sF,StableLmForCausalLM:()=>gNQ,StableLmModel:()=>bNQ,StableLmPreTrainedModel:()=>t70,Starcoder2ForCausalLM:()=>_NQ,Starcoder2Model:()=>hNQ,Starcoder2PreTrainedModel:()=>e70,StyleTextToSpeech2Model:()=>fNQ,StyleTextToSpeech2PreTrainedModel:()=>$E0,SupertonicForConditionalGeneration:()=>FE0,SupertonicPreTrainedModel:()=>ZE0,Swin2SRForImageSuperResolution:()=>dNQ,Swin2SRModel:()=>lNQ,Swin2SRPreTrainedModel:()=>QX0,SwinForImageClassification:()=>uNQ,SwinForSemanticSegmentation:()=>pNQ,SwinModel:()=>mNQ,SwinPreTrainedModel:()=>aR,T5ForConditionalGeneration:()=>iNQ,T5Model:()=>cNQ,T5PreTrainedModel:()=>XX0,TableTransformerForObjectDetection:()=>nNQ,TableTransformerModel:()=>oNQ,TableTransformerObjectDetectionOutput:()=>DE0,TableTransformerPreTrainedModel:()=>JX0,TrOCRForCausalLM:()=>aNQ,TrOCRPreTrainedModel:()=>ME0,UltravoxModel:()=>t10,UltravoxPreTrainedModel:()=>h20,UniSpeechForCTC:()=>rNQ,UniSpeechForSequenceClassification:()=>tNQ,UniSpeechModel:()=>sNQ,UniSpeechPreTrainedModel:()=>sR,UniSpeechSatForAudioFrameClassification:()=>JjQ,UniSpeechSatForCTC:()=>QjQ,UniSpeechSatForSequenceClassification:()=>XjQ,UniSpeechSatModel:()=>eNQ,UniSpeechSatPreTrainedModel:()=>rF,VaultGemmaForCausalLM:()=>GjQ,VaultGemmaModel:()=>YjQ,VaultGemmaPreTrainedModel:()=>YX0,ViTForImageClassification:()=>BjQ,ViTMAEModel:()=>AjQ,ViTMAEPreTrainedModel:()=>LE0,ViTMSNForImageClassification:()=>zjQ,ViTMSNModel:()=>KjQ,ViTMSNPreTrainedModel:()=>WX0,ViTModel:()=>HjQ,ViTPreTrainedModel:()=>GX0,VisionEncoderDecoderModel:()=>WjQ,VitMatteForImageMatting:()=>VjQ,VitMattePreTrainedModel:()=>OE0,VitPoseForPoseEstimation:()=>qjQ,VitPosePreTrainedModel:()=>PE0,VitsModel:()=>UjQ,VitsModelOutput:()=>NE0,VitsPreTrainedModel:()=>jE0,VoxtralForConditionalGeneration:()=>$jQ,VoxtralRealtimeForConditionalGeneration:()=>IE0,VoxtralRealtimePreTrainedModel:()=>CE0,Wav2Vec2BertForCTC:()=>NjQ,Wav2Vec2BertForSequenceClassification:()=>jjQ,Wav2Vec2BertModel:()=>PjQ,Wav2Vec2BertPreTrainedModel:()=>rR,Wav2Vec2ForAudioFrameClassification:()=>FLQ,Wav2Vec2ForCTC:()=>$LQ,Wav2Vec2ForSequenceClassification:()=>ZLQ,Wav2Vec2Model:()=>ULQ,Wav2Vec2PreTrainedModel:()=>DH,WavLMForAudioFrameClassification:()=>EjQ,WavLMForCTC:()=>IjQ,WavLMForSequenceClassification:()=>RjQ,WavLMForXVector:()=>wjQ,WavLMModel:()=>CjQ,WavLMPreTrainedModel:()=>uV,WeSpeakerResNetModel:()=>SjQ,WeSpeakerResNetPreTrainedModel:()=>wE0,WhisperForConditionalGeneration:()=>EE0,WhisperModel:()=>kjQ,WhisperPreTrainedModel:()=>HX0,XLMForQuestionAnswering:()=>hjQ,XLMForSequenceClassification:()=>bjQ,XLMForTokenClassification:()=>gjQ,XLMModel:()=>vjQ,XLMPreTrainedModel:()=>pV,XLMRobertaForMaskedLM:()=>fjQ,XLMRobertaForQuestionAnswering:()=>pjQ,XLMRobertaForSequenceClassification:()=>mjQ,XLMRobertaForTokenClassification:()=>ujQ,XLMRobertaModel:()=>_jQ,XLMRobertaPreTrainedModel:()=>lV,XLMWithLMHeadModel:()=>xjQ,XVectorOutput:()=>RE0,YolosForObjectDetection:()=>djQ,YolosModel:()=>ljQ,YolosObjectDetectionOutput:()=>SE0,YolosPreTrainedModel:()=>BX0,YoutuForCausalLM:()=>ijQ,YoutuModel:()=>cjQ,YoutuPreTrainedModel:()=>AX0});var lF=class extends s0{},zFQ=class extends lF{},VFQ=class extends lF{async _call(Q){return new T8(await super._call(Q))}},qFQ=class extends lF{async _call(Q){return new eX(await super._call(Q))}},UFQ=class extends lF{async _call(Q){return new f7(await super._call(Q))}},B10=class extends s0{},$FQ=class extends B10{},ZFQ=class extends B10{},A10=class extends s0{},FFQ=class extends A10{},DFQ=class extends A10{},K10=class extends s0{},MFQ=class extends K10{},LFQ=class extends K10{},z10=class extends s0{},OFQ=class extends z10{},PFQ=class extends z10{},xR=class extends s0{},NFQ=class extends xR{},jFQ=class extends xR{},CFQ=class extends xR{async _call(Q){return new T8(await super._call(Q))}},V10=class extends s0{},IFQ=class extends V10{},RFQ=class extends V10{async _call(Q){return new T8(await super._call(Q))}},TV=class extends s0{},wFQ=class extends TV{},EFQ=class extends TV{async _call(Q){return new f7(await super._call(Q))}},SFQ=class extends TV{async _call(Q){return new T8(await super._call(Q))}},TFQ=class extends TV{async _call(Q){return new R7(await super._call(Q))}},kFQ=class extends TV{async _call(Q){return new eX(await super._call(Q))}},q10=class extends s0{},yFQ=class extends q10{},vFQ=class extends q10{},U10=class extends s0{},xFQ=class extends U10{},bFQ=class extends U10{},$10=class extends s0{},gFQ=class extends $10{},hFQ=class extends $10{},kV=class extends s0{},_FQ=class extends kV{},fFQ=class extends kV{async _call(Q){return new f7(await super._call(Q))}},mFQ=class extends kV{async _call(Q){return new T8(await super._call(Q))}},uFQ=class extends kV{async _call(Q){return new R7(await super._call(Q))}},pFQ=class extends kV{async _call(Q){return new eX(await super._call(Q))}},lFQ=4299n,wI0=6561n,V20=class extends s0{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","audio_values","exaggeration","audio_features","audio_tokens","speaker_embeddings","speaker_features","past_key_values"];main_input_name="input_ids";_return_dict_in_generate_keys=["audio_tokens","speaker_embeddings","speaker_features"]},q20=class extends V20{async encode_speech(Q){return E6(this.sessions.speech_encoder,{audio_values:Q})}async forward({input_ids:Q=null,attention_mask:J=null,audio_values:G=null,exaggeration:H=null,position_ids:K=null,inputs_embeds:z=null,past_key_values:q=null,generation_config:F=null,logits_processor:D=null,audio_features:V=null,audio_tokens:O=null,speaker_embeddings:P=null,speaker_features:N=null,...I}){let R;if(!z){let E=this.sessions.embed_tokens.inputNames,T={input_ids:Q};if(E.includes("exaggeration")){if(!(H instanceof PQ)){let y=Q.dims[0];if(H==null)H=sX([y],0.5);else if(typeof H==="number")H=sX([y],H);else if(Array.isArray(H))H=new PQ("float32",H,[y]);else throw Error("Unsupported type for `exaggeration` input")}T.exaggeration=H}if(E.includes("position_ids"))T.position_ids=K;if({inputs_embeds:z}=await E6(this.sessions.embed_tokens,T),V&&O&&P&&N)R={audio_features:V,audio_tokens:O,speaker_embeddings:P,speaker_features:N};if(R||G)R??=await this.encode_speech(G),z=T9([R.audio_features,z],1),J=oJ([z.dims[0],z.dims[1]]);else{let y=z.dims[1];if(!q||y!==1)throw Error("Incorrect state encountered during generation.");let x=q.get_seq_length();J=oJ([z.dims[0],x+y])}}return{...await h5(this,{inputs_embeds:z,past_key_values:q,attention_mask:J,generation_config:F,logits_processor:D},!1),...R}}prepare_inputs_for_generation(Q,J,G){if(!J.position_ids&&this.sessions.embed_tokens.inputNames.includes("position_ids"))if(J.input_ids.dims[1]===1){let H=Array.from({length:Q.length},(K,z)=>Q[z].length-Q[z].findLastIndex((q)=>q==wI0)-1);J.position_ids=new PQ("int64",H,[Q.length,1])}else{let K=J.input_ids.tolist().map((z)=>{let q=0;return z.map((F)=>F>=wI0?0:q++)});J.position_ids=new PQ("int64",K.flat(),J.input_ids.dims)}if(J.input_ids.dims[1]===1)delete J.audio_values,delete J.audio_features,delete J.audio_tokens,delete J.speaker_embeddings,delete J.speaker_features;return vF(this,Q,J,G)}async generate(Q){let{sequences:J,audio_tokens:G,speaker_embeddings:H,speaker_features:K}=await super.generate({...Q,return_dict_in_generate:!0}),z=J.slice(null,[Q.input_ids.dims[1],-1]),q=sX([z.dims[0],3],lFQ),F=T9([G,z,q],1),{waveform:D}=await E6(this.sessions.conditional_decoder,{speech_tokens:F,speaker_features:K,speaker_embeddings:H});return D}},U20=class extends s0{},dFQ=class extends U20{},$20=class extends s0{},cFQ=class extends $20{},bR=class extends s0{},iFQ=class extends bR{},Z20=class extends bR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"text_model"})}},F20=class extends bR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"audio_model"})}},qB=class extends s0{},oFQ=class extends qB{},nFQ=class extends qB{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"text_model"})}},D20=class extends qB{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"text_model"})}},aFQ=class extends qB{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"vision_model"})}},sFQ=class extends qB{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"vision_model"})}},Z10=class extends s0{},rFQ=class extends Z10{},tFQ=class extends Z10{},F10=class extends s0{},eFQ=class extends F10{},QDQ=class extends F10{},D10=class extends s0{},XDQ=class extends D10{},JDQ=class extends D10{},M10=class extends s0{},YDQ=class extends M10{},GDQ=class extends M10{},L10=class extends s0{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","decoder_input_ids","decoder_attention_mask","past_key_values"]},WDQ=class extends L10{},HDQ=class extends L10{},yV=class extends s0{},BDQ=class extends yV{},ADQ=class extends yV{async _call(Q){return new f7(await super._call(Q))}},KDQ=class extends yV{async _call(Q){return new T8(await super._call(Q))}},zDQ=class extends yV{async _call(Q){return new R7(await super._call(Q))}},VDQ=class extends yV{async _call(Q){return new eX(await super._call(Q))}},O10=class extends s0{},qDQ=class extends O10{},UDQ=class extends O10{async _call(Q){return new T8(await super._call(Q))}},P10=class extends s0{},$DQ=class extends P10{},ZDQ=class extends P10{async _call(Q){return new T8(await super._call(Q))}},N10=class extends s0{},FDQ=class extends N10{},DDQ=class extends N10{async _call(Q){return new dF(await super._call(Q))}},dF=class extends _7{constructor({logits:Q,pred_boxes:J}){super();this.logits=Q,this.pred_boxes=J}},j10=class extends s0{},MDQ=class extends j10{},LDQ=class extends j10{async _call(Q){return new dF(await super._call(Q))}},M20=class extends _7{constructor({audio_codes:Q}){super();this.audio_codes=Q}},L20=class extends _7{constructor({audio_values:Q}){super();this.audio_values=Q}},gR=class extends s0{main_input_name="input_values";forward_params=["input_values"]},ODQ=class extends gR{async encode(Q){return new M20(await E6(this.sessions.encoder_model,Q))}async decode(Q){return new L20(await E6(this.sessions.decoder_model,Q))}},O20=class extends gR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"encoder_model"})}},P20=class extends gR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"decoder_model"})}},vV=class extends s0{},PDQ=class extends vV{},NDQ=class extends vV{async _call(Q){return new f7(await super._call(Q))}},jDQ=class extends vV{async _call(Q){return new T8(await super._call(Q))}},CDQ=class extends vV{async _call(Q){return new R7(await super._call(Q))}},IDQ=class extends vV{async _call(Q){return new eX(await super._call(Q))}},C10=class extends s0{},RDQ=class extends C10{},wDQ=class extends C10{},xV=class extends s0{},EDQ=class extends xV{},SDQ=class extends xV{async _call(Q){return new f7(await super._call(Q))}},TDQ=class extends xV{async _call(Q){return new T8(await super._call(Q))}},kDQ=class extends xV{async _call(Q){return new R7(await super._call(Q))}},yDQ=class extends xV{async _call(Q){return new eX(await super._call(Q))}},N20=class extends s0{},vDQ=class extends N20{},I10=class extends s0{},xDQ=class extends I10{},bDQ=class extends I10{async _call(Q){return new T8(await super._call(Q))}},j20=class extends s0{},gDQ=class extends j20{},C20=class extends s0{},hDQ=class extends C20{},hR=class extends s0{},_DQ=class extends hR{},fDQ=class extends hR{async _call(Q){return new R10(await super._call(Q))}},mDQ=class extends hR{async _call(Q){return new I20(await super._call(Q))}},R10=class extends _7{constructor({logits:Q,pred_boxes:J}){super();this.logits=Q,this.pred_boxes=J}},I20=class extends _7{constructor({logits:Q,pred_boxes:J,pred_masks:G}){super();this.logits=Q,this.pred_boxes=J,this.pred_masks=G}},w10=class extends s0{},uDQ=class extends w10{},pDQ=class extends w10{async _call(Q){return new T8(await super._call(Q))}},E10=class extends s0{},lDQ=class extends E10{},dDQ=class extends E10{async _call(Q){return new T8(await super._call(Q))}},R20=class extends s0{},cDQ=class extends R20{},w20=class extends s0{},iDQ=class extends w20{},bV=class extends s0{},oDQ=class extends bV{},nDQ=class extends bV{async _call(Q){return new T8(await super._call(Q))}},aDQ=class extends bV{async _call(Q){return new R7(await super._call(Q))}},sDQ=class extends bV{async _call(Q){return new eX(await super._call(Q))}},rDQ=class extends bV{async _call(Q){return new f7(await super._call(Q))}},E20=class extends s0{},tDQ=class extends E20{},S10=class extends s0{},eDQ=class extends S10{},QMQ=class extends S10{},T10=class extends s0{},XMQ=class extends T10{},JMQ=class extends T10{async _call(Q){return new T8(await super._call(Q))}},gV=class extends s0{},YMQ=class extends gV{},GMQ=class extends gV{async _call(Q){return new f7(await super._call(Q))}},WMQ=class extends gV{async _call(Q){return new T8(await super._call(Q))}},HMQ=class extends gV{async _call(Q){return new R7(await super._call(Q))}},BMQ=class extends gV{async _call(Q){return new eX(await super._call(Q))}},k10=class extends s0{},AMQ=class extends k10{},KMQ=class extends k10{},cF=class extends s0{},zMQ=class extends cF{},VMQ=class extends cF{async _call(Q){return new f7(await super._call(Q))}},qMQ=class extends cF{async _call(Q){return new T8(await super._call(Q))}},UMQ=class extends cF{async _call(Q){return new R7(await super._call(Q))}},iF=class extends s0{},$MQ=class extends iF{},ZMQ=class extends iF{async _call(Q){return new f7(await super._call(Q))}},FMQ=class extends iF{async _call(Q){return new T8(await super._call(Q))}},DMQ=class extends iF{async _call(Q){return new R7(await super._call(Q))}},y10=class extends s0{},MMQ=class extends y10{},LMQ=class extends y10{},v10=class extends s0{},OMQ=class extends v10{},PMQ=class extends v10{},x10=class extends s0{},NMQ=class extends x10{},jMQ=class extends x10{},b10=class extends s0{},CMQ=class extends b10{},IMQ=class extends b10{async _call(Q){return new T8(await super._call(Q))}},S20=class extends s0{forward_params=["input_ids","inputs_embeds","attention_mask","pixel_values","encoder_outputs","decoder_input_ids","decoder_inputs_embeds","decoder_attention_mask","past_key_values"];main_input_name="inputs_embeds"},RMQ=class extends S20{_merge_input_ids_with_image_features({inputs_embeds:Q,image_features:J,input_ids:G,attention_mask:H}){return{inputs_embeds:T9([J,Q],1),attention_mask:T9([oJ(J.dims.slice(0,2)),H],1)}}async _prepare_inputs_embeds({input_ids:Q,pixel_values:J,inputs_embeds:G,attention_mask:H}){if(!Q&&!J)throw Error("Either `input_ids` or `pixel_values` should be provided.");let K,z;if(Q)K=await this.encode_text({input_ids:Q});if(J)z=await this.encode_image({pixel_values:J});if(K&&z)({inputs_embeds:G,attention_mask:H}=this._merge_input_ids_with_image_features({inputs_embeds:K,image_features:z,input_ids:Q,attention_mask:H}));else G=K||z;return{inputs_embeds:G,attention_mask:H}}async forward({input_ids:Q,pixel_values:J,attention_mask:G,decoder_input_ids:H,decoder_attention_mask:K,encoder_outputs:z,past_key_values:q,inputs_embeds:F,decoder_inputs_embeds:D}){if(!F)({inputs_embeds:F,attention_mask:G}=await this._prepare_inputs_embeds({input_ids:Q,pixel_values:J,inputs_embeds:F,attention_mask:G}));if(!z){let{last_hidden_state:O}=await FH(this,{inputs_embeds:F,attention_mask:G});z=O}if(!D){if(!H)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");D=await this.encode_text({input_ids:H})}return await h5(this,{inputs_embeds:D,attention_mask:K,encoder_attention_mask:G,encoder_hidden_states:z,past_key_values:q},!0)}},g10=class extends s0{},wMQ=class extends g10{},EMQ=class extends g10{},h10=class extends s0{},SMQ=class extends h10{},TMQ=class extends h10{},T20=class extends s0{forward_params=["input_ids","attention_mask","pixel_values","position_ids","past_key_values"]},_5=class extends T20{_merge_input_ids_with_image_features(Q){let J=Q.image_features.dims.at(-1),G=Q.image_features.view(-1,J);return W10({image_token_id:this.config.image_token_index??this.config.image_token_id,...Q,image_features:G})}},kMQ=class extends _5{},yMQ=class extends _5{},k20=class extends s0{},vMQ=class extends k20{},y20=class extends _5{},xMQ=class extends y20{},v20=class extends s0{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","input_features","input_features_mask","past_key_values"]},_R=class extends v20{async forward({input_ids:Q=null,attention_mask:J=null,pixel_values:G=null,input_features:H=null,input_features_mask:K=null,position_ids:z=null,inputs_embeds:q=null,per_layer_inputs:F=null,past_key_values:D=null,generation_config:V=null,logits_processor:O=null,...P}){if(!q||!F){if({inputs_embeds:q,per_layer_inputs:F}=await E6(this.sessions.embed_tokens,{input_ids:Q}),Q.dims[1]!==1){if(G){let{image_features:I}=await this._encode_vision({pixel_values:G,...P});({inputs_embeds:q,attention_mask:J}=this._merge_input_ids_with_image_features({image_features:I,inputs_embeds:q,input_ids:Q,attention_mask:J}))}if(H){let{audio_features:I}=await E6(this.sessions.audio_encoder,{input_features:H,input_features_mask:K});({inputs_embeds:q,attention_mask:J}=this._merge_input_ids_with_audio_features({audio_features:I,inputs_embeds:q,input_ids:Q,attention_mask:J}))}}}return await h5(this,{inputs_embeds:q,per_layer_inputs:F,past_key_values:D,attention_mask:J,position_ids:z,generation_config:V,logits_processor:O},!0)}_encode_vision(Q){return E6(this.sessions.vision_encoder,{pixel_values:Q.pixel_values})}_merge_input_ids_with_image_features(Q){let J=Q.image_features.dims.at(-1),G=Q.image_features.view(-1,J);return W10({image_token_id:this.config.image_token_id,...Q,image_features:G})}_merge_input_ids_with_audio_features(Q){let J=Q.audio_features.dims.at(-1),G=Q.audio_features.view(-1,J);return z20({audio_token_id:this.config.audio_token_id,...Q,audio_features:G})}},bMQ=class extends _R{},_10=class extends _R{forward_params=["input_ids","attention_mask","inputs_embeds","per_layer_inputs","position_ids","pixel_values","image_position_ids","input_features","input_features_mask","past_key_values"];_encode_vision(Q){return E6(this.sessions.vision_encoder,{pixel_values:Q.pixel_values,pixel_position_ids:Q.image_position_ids})}},gMQ=class extends _10{},f10=class extends s0{},hMQ=class extends f10{},_MQ=class extends f10{},m10=class extends s0{},fMQ=class extends m10{},mMQ=class extends m10{},x20=class extends s0{forward_params=["input_ids","attention_mask","position_ids","past_key_values","pixel_values","image_grid_thw"]},u10=class extends x20{image_grid_thw_name="grid_thw";_get_text_only_rope_index(Q,J){if(J){let{data:G,dims:H}=A20(J),K=BigInt64Array.from({length:3*G.length},(q,F)=>G[F%G.length]),z=Array.from({length:H[0]},(q,F)=>D7(G.subarray(H[1]*F,H[1]*(F+1)))[0]+1n+BigInt(H[1]));return[new PQ("int64",K,[3,...H]),new PQ("int64",z,[z.length,1])]}else{let[G,H]=Q.dims,K=BigInt64Array.from({length:3*G*H},(z,q)=>BigInt(Math.floor(q%H/G)));return[new PQ("int64",K,[3,...Q.dims]),Ww0([G,1])]}}_reorder_and_write_positions(Q,J,G,H){let K=Q.reduce((D,V)=>D+V.length,0),z=Array(K),q=0;for(let D=0;D<3;++D)for(let V of Q){let O=V.length/3;for(let P=D*O;P<(D+1)*O;++P)z[q++]=V[P]}let F=0;for(let D=0;D<J.length;++D)if(J[D]==1){for(let V=0;V<3;++V)G[V][H][D]=z[V*K/3+F];++F}return z}_get_multimodal_rope_positions({filtered_ids:Q,image_grid_thw_list:J,video_grid_thw_list:G,spatial_merge_size:H,state:K}){let{image_token_id:z,video_token_id:q,vision_start_token_id:F}=this.config,D=Q,O=D.reduce((T,y,x)=>{if(y==F)T.push(x);return T},[]).map((T)=>D[T+1]),P=O.filter((T)=>T==z).length,N=O.filter((T)=>T==q).length,I=[],R=0,w=P,E=N;for(let T=0;T<O.length;++T){let y=D.findIndex((d0,m0)=>m0>R&&d0==z),x=D.findIndex((d0,m0)=>m0>R&&d0==q),b=w>0&&y!==-1?y:D.length+1,g=E>0&&x!==-1?x:D.length+1,l,_,a,r;if(b<g)[_,a,r]=J[K.image_index],++K.image_index,--w,l=b;else[_,a,r]=G[K.video_index],++K.video_index,--E,l=g;let[f0,t,p0]=[Number(_),Math.floor(Number(a)/H),Math.floor(Number(r)/H)],u0=l-R,d=I.length>0?D7(I.at(-1))[0]+1:0;I.push(Array.from({length:3*u0},(d0,m0)=>d+m0%u0));let n=u0+d,c0=f0*t*p0,WQ=Array.from({length:c0},(d0,m0)=>n+Math.floor(m0/(t*p0))),R0=Array.from({length:c0},(d0,m0)=>n+Math.floor(m0/p0)%t),l0=Array.from({length:c0},(d0,m0)=>n+m0%p0);I.push([WQ,R0,l0].flat()),R=l+c0}if(R<D.length){let T=I.length>0?D7(I.at(-1))[0]+1:0,y=D.length-R;I.push(Array.from({length:3*y},(x,b)=>T+b%y))}return I}get_rope_index(Q,J,G,H){let{vision_config:K}=this.config,z=K.spatial_merge_size??2;if(J||G){let q=Q.tolist();if(!H)H=Gw0(Q);let F=H.tolist(),D=Array.from({length:3},()=>Array.from({length:Q.dims[0]},()=>Array.from({length:Q.dims[1]},()=>0))),V=J?J.tolist():[],O=G?G.tolist():[],P={image_index:0,video_index:0},N=[];for(let I=0;I<q.length;++I){let R=q[I].filter((T,y)=>F[I][y]==1),w=this._get_multimodal_rope_positions({filtered_ids:R,image_grid_thw_list:V,video_grid_thw_list:O,spatial_merge_size:z,state:P}),E=this._reorder_and_write_positions(w,F[I],D,I);N.push(D7(E)[0]+1-q[I].length)}return[new PQ("int64",D.flat(1/0),[3,Q.dims[0],Q.dims[1]]),new PQ("int64",N,[N.length,1])]}else return this._get_text_only_rope_index(Q,H)}async encode_image({pixel_values:Q,image_grid_thw:J}){return(await E6(this.sessions.vision_encoder,{pixel_values:Q,[this.image_grid_thw_name]:J})).image_features}_merge_input_ids_with_image_features(Q){return W10({image_token_id:this.config.image_token_id,...Q})}prepare_inputs_for_generation(Q,J,G){if(!J.attention_mask||J.position_ids)return J;if(!(this.sessions.decoder_model_merged??this.sessions.model).inputNames.includes("position_ids"))return J;if(!J.past_key_values)[J.position_ids,J.rope_deltas]=this.get_rope_index(J.input_ids,J.image_grid_thw,J.video_grid_thw,J.attention_mask);else{J.pixel_values=null;let K=J.past_key_values.get_seq_length();if(K<J.input_ids.dims[1]){let[z,q]=this.get_rope_index(J.input_ids,J.image_grid_thw,J.video_grid_thw,J.attention_mask);J.rope_deltas=q,J.position_ids=z.slice(null,null,[K,null]),J.input_ids=J.input_ids.slice(null,[K,null])}else{if(!J.rope_deltas)[,J.rope_deltas]=this.get_rope_index(J.input_ids,J.image_grid_thw,J.video_grid_thw,J.attention_mask);let z=BigInt(K),q=J.rope_deltas.map((F)=>z+F);J.position_ids=g5([q,q,q],0)}}return J}},b20=class extends u10{},p10=class extends u10{image_grid_thw_name="image_grid_thw"},g20=class extends b20{image_grid_thw_name="image_grid_thw"},uMQ=class extends p10{get_vision_position_ids(Q,J,G,H){let K=Math.floor(J[0]/G),z=Math.floor(J[1]/H),q=Math.floor(J[2]/H),F=z*q*K,D=Array.from({length:F},()=>Q),V=Array.from({length:F},(P,N)=>Q+Math.floor(N/(q*K))),O=Array.from({length:F},(P,N)=>Q+N%q);return[...D,...V,...O]}_get_multimodal_rope_positions({filtered_ids:Q,image_grid_thw_list:J,video_grid_thw_list:G,spatial_merge_size:H,state:K}){let{image_token_id:z}=this.config,q=[],F=0,D=Q[0]==z?1:0;for(let P=1;P<=Q.length;++P){let N=P<Q.length?Q[P]==z?1:0:-1;if(N!==D)q.push([D,F,P]),F=P,D=N}let V=0,O=[];for(let[P,N,I]of q)if(P===0){let R=I-N;O.push(Array.from({length:3*R},(w,E)=>V+E%R)),V+=R}else{let R=J[K.image_index++].map(Number),w=R[0];O.push(this.get_vision_position_ids(V,R,w,H)),V+=Math.max(R[1],R[2])/H}return O}},l10=class extends s0{},pMQ=class extends l10{},lMQ=class extends l10{},d10=class extends s0{},dMQ=class extends d10{},cMQ=class extends d10{},c10=class extends s0{},iMQ=class extends c10{},oMQ=class extends c10{},i10=class extends s0{},nMQ=class extends i10{},aMQ=class extends i10{},o10=class extends s0{},sMQ=class extends o10{},rMQ=class extends o10{},n10=class extends s0{},tMQ=class extends n10{},eMQ=class extends n10{},a10=class extends s0{},QLQ=class extends a10{},XLQ=class extends a10{},s10=class extends s0{},JLQ=class extends s10{},YLQ=class extends s10{},r10=class extends s0{},GLQ=class extends r10{},WLQ=class extends r10{},h20=class extends s0{forward_params=["input_ids","attention_mask","position_ids","audio_values","past_key_values"]},t10=class extends h20{_merge_input_ids_with_audio_features(Q){let J=Q.audio_features.dims.at(-1),G=Q.audio_features.view(-1,J);return z20({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...Q,audio_features:G})}},HLQ=class extends t10{forward_params=["input_ids","attention_mask","input_features","past_key_values"]},_20=class extends s0{},BLQ=class extends _20{},f20=class extends s0{},ALQ=class extends f20{},e10=class extends s0{},KLQ=class extends e10{},zLQ=class extends e10{},Q70=class extends s0{},VLQ=class extends Q70{},qLQ=class extends Q70{async _call(Q){return new T8(await super._call(Q))}},DH=class extends s0{},ULQ=class extends DH{},$LQ=class extends DH{async _call(Q){return new VB(await super._call(Q))}},ZLQ=class extends DH{async _call(Q){return new T8(await super._call(Q))}},FLQ=class extends DH{async _call(Q){return new R7(await super._call(Q))}},DLQ=class extends s0{},MLQ=class extends DH{},LLQ=class extends DH{async _call(Q){return new VB(await super._call(Q))}},OLQ=class extends DH{async _call(Q){return new T8(await super._call(Q))}},X70=class extends s0{},PLQ=class extends X70{},NLQ=class extends X70{},m20=class extends _5{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","position_ids","past_key_values"]},J70=class extends s0{},jLQ=class extends J70{},CLQ=class extends J70{async _call(Q){return new T8(await super._call(Q))}},Y70=class extends s0{},ILQ=class extends Y70{},RLQ=class extends Y70{},fR=class extends s0{},wLQ=class extends fR{async forward(Q){let J=!Q.input_ids,G=!Q.pixel_values;if(J&&G)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(J)Q.input_ids=oJ([Q.pixel_values.dims[0],1]);if(G){let{image_size:D}=this.config.vision_config;Q.pixel_values=sX([0,3,D,D],0)}let{text_embeddings:H,image_embeddings:K,l2norm_text_embeddings:z,l2norm_image_embeddings:q}=await super.forward(Q),F={};if(!J)F.text_embeddings=H,F.l2norm_text_embeddings=z;if(!G)F.image_embeddings=K,F.l2norm_image_embeddings=q;return F}},u20=class extends fR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"text_model"})}},ELQ=class extends fR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"vision_model"})}},G70=class extends s0{},SLQ=class extends G70{},TLQ=class extends G70{},kLQ=class extends _5{},W70=class extends s0{},yLQ=class extends W70{},vLQ=class extends W70{},xLQ=class extends _5{forward_params=["input_ids","attention_mask","pixel_values","pixel_attention_mask","spatial_shapes","position_ids","past_key_values"]},H70=class extends s0{},bLQ=class extends H70{},gLQ=class extends H70{},p20=class extends s0{},hLQ=class extends p20{},B70=class extends s0{},_LQ=class extends B70{},fLQ=class extends B70{},A70=class extends s0{},mLQ=class extends A70{},uLQ=class extends A70{},K70=class extends s0{},pLQ=class extends K70{},lLQ=class extends K70{},z70=class extends s0{},dLQ=class extends z70{},cLQ=class extends z70{},oF=class extends s0{},iLQ=class extends oF{},oLQ=class extends oF{},nLQ=class extends oF{async _call(Q){return new T8(await super._call(Q))}},aLQ=class extends oF{},l20=class extends s0{},sLQ=class extends l20{},d20=class extends s0{},rLQ=class extends d20{},c20=class extends _7{constructor({char_logits:Q,bpe_logits:J,wp_logits:G}){super();this.char_logits=Q,this.bpe_logits=J,this.wp_logits=G}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},i20=class extends s0{},tLQ=class extends i20{async _call(Q){return new c20(await super._call(Q))}},o20=class extends _7{constructor({audio_codes:Q}){super();this.audio_codes=Q}},n20=class extends _7{constructor({audio_values:Q}){super();this.audio_values=Q}},mR=class extends s0{main_input_name="input_values";forward_params=["input_values"]},eLQ=class extends mR{async encode(Q){return new o20(await E6(this.sessions.encoder_model,Q))}async decode(Q){return new n20(await E6(this.sessions.decoder_model,Q))}},a20=class extends mR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"encoder_model"})}},s20=class extends mR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"decoder_model"})}},V70=class extends s0{},QOQ=class extends V70{},XOQ=class extends V70{},q70=class extends s0{},JOQ=class extends q70{},YOQ=class extends q70{},nF=class extends s0{},GOQ=class extends nF{},WOQ=class extends nF{async _call(Q){return new f7(await super._call(Q))}},HOQ=class extends nF{async _call(Q){return new T8(await super._call(Q))}},BOQ=class extends nF{async _call(Q){return new eX(await super._call(Q))}},U70=class extends s0{},AOQ=class extends U70{},KOQ=class extends U70{},uR=class extends s0{},zOQ=class extends uR{},VOQ=class extends uR{async _call(Q){return new T8(await super._call(Q))}},qOQ=class extends uR{},pR=class extends s0{},UOQ=class extends pR{},$OQ=class extends pR{async _call(Q){return new T8(await super._call(Q))}},ZOQ=class extends pR{},lR=class extends s0{},FOQ=class extends lR{},DOQ=class extends lR{async _call(Q){return new T8(await super._call(Q))}},MOQ=class extends lR{},dR=class extends s0{},LOQ=class extends dR{},OOQ=class extends dR{async _call(Q){return new T8(await super._call(Q))}},POQ=class extends dR{},$70=class extends s0{},NOQ=class extends $70{},jOQ=class extends $70{async _call(Q){return new T8(await super._call(Q))}},Z70=class extends s0{},COQ=class extends Z70{},IOQ=class extends Z70{async _call(Q){return new T8(await super._call(Q))}},aF=class extends s0{},ROQ=class extends aF{},wOQ=class extends aF{async _call(Q){return new f7(await super._call(Q))}},EOQ=class extends aF{async _call(Q){return new T8(await super._call(Q))}},SOQ=class extends aF{async _call(Q){return new R7(await super._call(Q))}},F70=class extends s0{},TOQ=class extends F70{},kOQ=class extends F70{},D70=class extends s0{requires_attention_mask=!1;main_input_name="input_values";forward_params=["input_values","decoder_input_ids","past_key_values"]},yOQ=class extends D70{},vOQ=class extends D70{},hV=class extends s0{},xOQ=class extends hV{},bOQ=class extends hV{async _call(Q){return new f7(await super._call(Q))}},gOQ=class extends hV{async _call(Q){return new T8(await super._call(Q))}},hOQ=class extends hV{async _call(Q){return new R7(await super._call(Q))}},_OQ=class extends hV{async _call(Q){return new eX(await super._call(Q))}},M70=class extends s0{},fOQ=class extends M70{},mOQ=class extends M70{},L70=class extends s0{},uOQ=class extends L70{},pOQ=class extends L70{},r20=class extends s0{},lOQ=class extends r20{forward_params=["input_ids","pixel_values","images_seq_mask","images_emb_mask","attention_mask","position_ids","past_key_values"];constructor(...Q){super(...Q);this._generation_mode="text"}async forward(Q){let J=this._generation_mode??"text",G;if(J==="text"||!Q.past_key_values){let F=this.sessions.prepare_inputs_embeds,D=JX(Q,F.inputNames);G=await E6(F,D)}else{let F=this.sessions.gen_img_embeds,D=JX({image_ids:Q.input_ids},F.inputNames);G=await E6(F,D)}let H={...Q,...G},K=await h5(this,H),z=this.sessions[J==="text"?"lm_head":"gen_head"];if(!z)throw Error(`Unable to find "${z}" generation head`);let q=await E6(z,JX(K,z.inputNames));return{...G,...K,...q}}prepare_inputs_for_generation(Q,J,G){let H=!!J.past_key_values;if(G.guidance_scale!==null&&G.guidance_scale>1)if(H)J.input_ids=T9([J.input_ids,J.input_ids],0);else J.input_ids=T9([J.input_ids,V90(J.input_ids,BigInt(G.pad_token_id))],0),J.attention_mask=T9([J.attention_mask,V90(J.attention_mask,0n)],0);if(H||!J.pixel_values)J.pixel_values=sX([0,0,3,384,384],1);if(H)J.images_seq_mask=new PQ("bool",[,].fill(!0).fill(!1,0,1),[1,1]),J.images_emb_mask=new PQ("bool",[].fill(!1),[1,1,0]);return J}async generate(Q){return this._generation_mode="text",super.generate(Q)}async generate_images(Q){this._generation_mode="image";let J=(Q.inputs??Q[this.main_input_name]).dims[1],H=(await super.generate(Q)).slice(null,[J,null]),K=this.sessions.image_decode,{decoded_image:z}=await E6(K,{generated_tokens:H}),q=z.add_(1).mul_(127.5).clamp_(0,255).to("uint8"),F=[];for(let D of q){let V=gG.fromTensor(D);F.push(V)}return F}},O70=class extends s0{},dOQ=class extends O70{},cOQ=class extends O70{},t20=class extends s0{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"];_apply_and_filter_by_delay_pattern_mask(Q){let[J,G]=Q.dims,H=this.config.decoder.num_codebooks,K=G-H,z=0;for(let D=0;D<Q.size;++D){if(Q.data[D]==this.config.decoder.pad_token_id)continue;let V=D%G,O=Math.floor(D/G)%H,P=V-O;if(P>0&&P<=K)Q.data[z++]=Q.data[D]}let q=Math.floor(J/H),F=z/(q*H);return new PQ(Q.type,Q.data.slice(0,z),[q,H,F])}prepare_inputs_for_generation(Q,J,G){let H=BigInt(this.config.decoder.pad_token_id),K=structuredClone(Q);for(let z=0;z<K.length;++z)for(let q=0;q<K[z].length;++q)if(z%this.config.decoder.num_codebooks>=q)K[z][q]=H;if(G.guidance_scale!==null&&G.guidance_scale>1)K=K.concat(K);return NR(this,K,J,G)}async generate(Q){let J=await super.generate(Q),G=this._apply_and_filter_by_delay_pattern_mask(J).unsqueeze_(0),{audio_values:H}=await E6(this.sessions.encodec_decode,{audio_codes:G});return H}},P70=class extends s0{},iOQ=class extends P70{},oOQ=class extends P70{},N70=class extends s0{},nOQ=class extends N70{},aOQ=class extends N70{},_V=class extends s0{},sOQ=class extends _V{},rOQ=class extends _V{async _call(Q){return new f7(await super._call(Q))}},tOQ=class extends _V{async _call(Q){return new T8(await super._call(Q))}},eOQ=class extends _V{async _call(Q){return new R7(await super._call(Q))}},QPQ=class extends _V{async _call(Q){return new eX(await super._call(Q))}},e20=class extends s0{},XPQ=class extends e20{},j70=class extends s0{},JPQ=class extends j70{},YPQ=class extends j70{},C70=class extends s0{},GPQ=class extends C70{},WPQ=class extends C70{},I70=class extends s0{},HPQ=class extends I70{},BPQ=class extends I70{},R70=class extends s0{},APQ=class extends R70{},KPQ=class extends R70{},w70=class extends s0{},zPQ=class extends w70{},VPQ=class extends w70{async _call(Q){return new T8(await super._call(Q))}},E70=class extends s0{},qPQ=class extends E70{},UPQ=class extends E70{},S70=class extends s0{},$PQ=class extends S70{},ZPQ=class extends S70{},T70=class extends s0{},FPQ=class extends T70{},DPQ=class extends T70{},k70=class extends s0{},MPQ=class extends k70{},LPQ=class extends k70{},OPQ=class extends _5{},QE0=class extends s0{},PPQ=class extends QE0{async _call(Q){return new VB(await super._call(Q))}},y70=class extends s0{},NPQ=class extends y70{},jPQ=class extends y70{},v70=class extends s0{},CPQ=class extends v70{},IPQ=class extends v70{},x70=class extends s0{},RPQ=class extends x70{},wPQ=class extends x70{},b70=class extends s0{},EPQ=class extends b70{},SPQ=class extends b70{},XE0=class extends s0{forward_params=["input_ids","inputs_embeds","attention_mask","position_ids","pixel_values","image_sizes","past_key_values"]},JE0=class extends XE0{async forward({input_ids:Q=null,attention_mask:J=null,pixel_values:G=null,image_sizes:H=null,position_ids:K=null,inputs_embeds:z=null,past_key_values:q=null,generation_config:F=null,logits_processor:D=null,...V}){if(!z){let P;if(G&&Q.dims[1]!==1){if(!H)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:P}=await E6(this.sessions.vision_encoder,{pixel_values:G,image_sizes:H}))}else{let N=this.config.normalized_config.hidden_size;P=new PQ("float32",[],[0,N])}({inputs_embeds:z}=await E6(this.sessions.prepare_inputs_embeds,{input_ids:Q,image_features:P}))}return await h5(this,{inputs_embeds:z,past_key_values:q,attention_mask:J,position_ids:K,generation_config:F,logits_processor:D},!1)}},g70=class extends s0{},TPQ=class extends g70{},kPQ=class extends g70{async _call(Q){return new T8(await super._call(Q))}},h70=class extends s0{},yPQ=class extends h70{},vPQ=class extends h70{async _call(Q){return new R7(await super._call(Q))}},_70=class extends s0{},xPQ=class extends _70{},bPQ=class extends _70{},f70=class extends s0{},gPQ=class extends f70{},hPQ=class extends f70{},m70=class extends s0{},_PQ=class extends m70{},fPQ=class extends m70{},u70=class extends s0{},mPQ=class extends u70{},uPQ=class extends u70{},p70=class extends s0{},pPQ=class extends p70{},lPQ=class extends p70{},l70=class extends p10{},YE0=class extends g20{},dPQ=class extends l70{},cPQ=class extends YE0{},d70=class extends l70{},GE0=class extends d70{},iPQ=class extends d70{},oPQ=class extends GE0{},c70=class extends s0{},nPQ=class extends c70{},aPQ=class extends c70{async _call(Q){return new T8(await super._call(Q))}},i70=class extends s0{},sPQ=class extends i70{},rPQ=class extends i70{async _call(Q){return new WE0(await super._call(Q))}},WE0=class extends dF{},fV=class extends s0{},tPQ=class extends fV{},ePQ=class extends fV{async _call(Q){return new f7(await super._call(Q))}},QNQ=class extends fV{async _call(Q){return new T8(await super._call(Q))}},XNQ=class extends fV{async _call(Q){return new R7(await super._call(Q))}},JNQ=class extends fV{async _call(Q){return new eX(await super._call(Q))}},mV=class extends s0{},YNQ=class extends mV{},GNQ=class extends mV{async _call(Q){return new f7(await super._call(Q))}},WNQ=class extends mV{async _call(Q){return new T8(await super._call(Q))}},HNQ=class extends mV{async _call(Q){return new R7(await super._call(Q))}},BNQ=class extends mV{async _call(Q){return new eX(await super._call(Q))}},o70=class extends s0{},ANQ=class extends o70{},KNQ=class extends o70{async _call(Q){return new HE0(await super._call(Q))}},HE0=class extends dF{},BE0=class extends _7{constructor({iou_scores:Q,pred_masks:J}){super();this.iou_scores=Q,this.pred_masks=J}},AE0=class extends s0{},zNQ=class extends AE0{async get_image_embeddings({pixel_values:Q}){return await FH(this,{pixel_values:Q})}async forward(Q){if(!Q.image_embeddings||!Q.image_positional_embeddings)Q={...Q,...await this.get_image_embeddings(Q)};else Q={...Q};Q.input_labels??=oJ(Q.input_points.dims.slice(0,-1));let J={image_embeddings:Q.image_embeddings,image_positional_embeddings:Q.image_positional_embeddings};if(Q.input_points)J.input_points=Q.input_points;if(Q.input_labels)J.input_labels=Q.input_labels;if(Q.input_boxes)J.input_boxes=Q.input_boxes;return await E6(this.sessions.prompt_encoder_mask_decoder,J)}async _call(Q){return new BE0(await super._call(Q))}},KE0=class extends _7{constructor({iou_scores:Q,pred_masks:J,object_score_logits:G}){super();this.iou_scores=Q,this.pred_masks=J,this.object_score_logits=G}},zE0=class extends s0{},n70=class extends zE0{async get_image_embeddings({pixel_values:Q}){return await FH(this,{pixel_values:Q})}async forward(Q){let{num_feature_levels:J}=this.config.vision_config;if(Array.from({length:J},(z,q)=>`image_embeddings.${q}`).some((z)=>!Q[z]))Q={...Q,...await this.get_image_embeddings(Q)};else Q={...Q};if(Q.input_points){if(Q.input_boxes&&Q.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let z=Q.input_points.dims;Q.input_labels??=oJ(z.slice(0,-1)),Q.input_boxes??=sX([z[0],0,4],0)}else if(Q.input_boxes){let z=Q.input_boxes.dims;Q.input_labels=sX([z[0],z[1],0],-1n),Q.input_points=sX([z[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let H=this.sessions.prompt_encoder_mask_decoder,K=JX(Q,H.inputNames);return await E6(H,K)}async _call(Q){return new KE0(await super._call(Q))}},VNQ=class extends n70{},qNQ=class extends n70{},cR=class extends s0{},UNQ=class extends cR{},$NQ=class extends cR{},ZNQ=class extends cR{},iR=class extends s0{},FNQ=class extends iR{},DNQ=class extends iR{},MNQ=class extends iR{},a70=class extends s0{},LNQ=class extends a70{},VE0=class extends a70{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"text_model"})}},ONQ=class extends qB{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"vision_model"})}},s70=class extends s0{},PNQ=class extends s70{},NNQ=class extends s70{},jNQ=class extends m20{},oR=class extends s0{main_input_name="input_values";forward_params=["input_values"]},CNQ=class extends oR{async encode(Q){return await E6(this.sessions.encoder_model,Q)}async decode(Q){return await E6(this.sessions.decoder_model,Q)}},qE0=class extends oR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"encoder_model"})}},UE0=class extends oR{static async from_pretrained(Q,J={}){return super.from_pretrained(Q,{...J,model_file_name:J.model_file_name??"decoder_model"})}},r70=class extends s0{},INQ=class extends r70{},RNQ=class extends r70{},nR=class extends s0{},wNQ=class extends nR{},ENQ=class extends nR{},SNQ=class extends nR{async generate_speech(Q,J,{threshold:G=0.5,minlenratio:H=0,maxlenratio:K=20,vocoder:z=null}={}){let q={input_ids:Q},{encoder_outputs:F,encoder_attention_mask:D}=await FH(this,q),V=F.dims[1]/this.config.reduction_factor,O=Math.floor(V*K),P=Math.floor(V*H),N=this.config.num_mel_bins,I=[],R=null,w=null,E=0;while(!0){++E;let x=W20(!!w),b;if(w)b=w.output_sequence_out;else b=new PQ("float32",new Float32Array(N),[1,1,N]);let g={use_cache_branch:x,output_sequence:b,encoder_attention_mask:D,speaker_embeddings:J,encoder_hidden_states:F};G10(this,g,R),w=await E6(this.sessions.decoder_model_merged,g),R=F90(w,R);let{prob:l,spectrum:_}=w;if(I.push(_),E>=P&&(Array.from(l.data).filter((a)=>a>=G).length>0||E>=O))break}let T=T9(I),{waveform:y}=await E6(z.sessions.model,{spectrogram:T});return{spectrogram:T,waveform:y}}},TNQ=class extends s0{main_input_name="spectrogram"},sF=class extends s0{},kNQ=class extends sF{},yNQ=class extends sF{async _call(Q){return new f7(await super._call(Q))}},vNQ=class extends sF{async _call(Q){return new T8(await super._call(Q))}},xNQ=class extends sF{async _call(Q){return new eX(await super._call(Q))}},t70=class extends s0{},bNQ=class extends t70{},gNQ=class extends t70{},e70=class extends s0{},hNQ=class extends e70{},_NQ=class extends e70{},$E0=class extends s0{},fNQ=class extends $E0{},ZE0=class extends s0{},FE0=class extends ZE0{async generate_speech({input_ids:Q,attention_mask:J,style:G,num_inference_steps:H=5,speed:K=1.05}){let{sampling_rate:z,chunk_compress_factor:q,base_chunk_size:F,latent_dim:D}=this.config,{last_hidden_state:V,durations:O}=await E6(this.sessions.text_encoder,{input_ids:Q,attention_mask:J,style:G}),P=O.div(K).mul_(z),N=F*q,I=P.data,R=Int32Array.from(I,(r)=>Math.ceil(r/N)),w=Math.max(...R),E=Q.dims[0],T=new BigInt64Array(E*w);for(let r=0;r<E;++r)T.fill(1n,r*w,r*w+R[r]);let y=new PQ("int64",T,[E,w]),x=D*q,b=x*w,g=$qQ([E,x,w]),l=g.data;for(let r=0;r<E;++r){if(R[r]===w)continue;for(let f0=0;f0<x;++f0)l.fill(0,r*b+f0*w+R[r],r*b+(f0+1)*w)}let _=sX([E],H);for(let r=0;r<H;++r){let f0=sX([E],r);({denoised_latents:g}=await E6(this.sessions.latent_denoiser,{style:G,noisy_latents:g,latent_mask:y,encoder_outputs:V,attention_mask:J,timestep:f0,num_inference_steps:_}))}let{waveform:a}=await E6(this.sessions.voice_decoder,{latents:g});return{waveform:a,durations:P}}},aR=class extends s0{},mNQ=class extends aR{},uNQ=class extends aR{async _call(Q){return new T8(await super._call(Q))}},pNQ=class extends aR{},QX0=class extends s0{},lNQ=class extends QX0{},dNQ=class extends QX0{},XX0=class extends s0{forward_params=["input_ids","attention_mask","encoder_outputs","decoder_input_ids","decoder_attention_mask","past_key_values"]},cNQ=class extends XX0{},iNQ=class extends XX0{},JX0=class extends s0{},oNQ=class extends JX0{},nNQ=class extends JX0{async _call(Q){return new DE0(await super._call(Q))}},DE0=class extends R10{},ME0=class extends s0{},aNQ=class extends ME0{},sR=class extends s0{},sNQ=class extends sR{},rNQ=class extends sR{async _call(Q){return new VB(await super._call(Q))}},tNQ=class extends sR{async _call(Q){return new T8(await super._call(Q))}},rF=class extends s0{},eNQ=class extends rF{},QjQ=class extends rF{async _call(Q){return new VB(await super._call(Q))}},XjQ=class extends rF{async _call(Q){return new T8(await super._call(Q))}},JjQ=class extends rF{async _call(Q){return new R7(await super._call(Q))}},YX0=class extends s0{},YjQ=class extends YX0{},GjQ=class extends YX0{},WjQ=class extends s0{main_input_name="pixel_values";forward_params=["pixel_values","decoder_input_ids","encoder_hidden_states","past_key_values"]},GX0=class extends s0{},HjQ=class extends GX0{},BjQ=class extends GX0{async _call(Q){return new T8(await super._call(Q))}},LE0=class extends s0{},AjQ=class extends LE0{},WX0=class extends s0{},KjQ=class extends WX0{},zjQ=class extends WX0{async _call(Q){return new T8(await super._call(Q))}},OE0=class extends s0{},VjQ=class extends OE0{async _call(Q){return new gZQ(await super._call(Q))}},PE0=class extends s0{},qjQ=class extends PE0{},NE0=class extends _7{constructor({waveform:Q,spectrogram:J}){super();this.waveform=Q,this.spectrogram=J}},jE0=class extends s0{},UjQ=class extends jE0{async _call(Q){return new NE0(await super._call(Q))}},$jQ=class extends t10{},EI0=2,ZjQ=1,Q90=new WeakMap;function FjQ(Q,J){let{text_config:G,audio_config:H}=Q.config,K=Q.sessions.audio_encoder,{num_mel_bins:z,hidden_size:q}=H,F=z+q,D=new J10,V=kR(H),O={batch_size:1},P="float32";for(let w of K.inputMetadata){if(w.name==="past_padding_cache"){P=w.type;continue}if(!V.has(w.name))continue;let E=H20(w.shape,O),T=E.reduce((x,b)=>x*b,1),y=gF[w.type];D[w.name]=new PQ(w.type,new y(T),E)}let N=gF[P],I=new PQ(P,new N(F*EI0),[1,F,EI0]),R=J[Symbol.asyncIterator]?.()??J[Symbol.iterator]?.();if(!R)throw Error("input_features must be iterable or async iterable");return{encoder_session:K,enc_kv_cache:D,enc_padding_cache:I,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:R,text_hidden_size:G.hidden_size}}async function DjQ(Q,J){let G=J.dims[2],H=Math.floor((ZjQ+G-3)/2)+1,K=new PQ("int64",BigInt64Array.from({length:H},(O,P)=>BigInt(Q.enc_past_seq_len+P)),[1,H]),z=Q.enc_past_seq_len+H,q=oJ([1,z]),{audio_embeds:F,present_padding_cache:D,...V}=await E6(Q.encoder_session,{input_features:J,attention_mask:q,position_ids:K,past_padding_cache:Q.enc_padding_cache,...Q.enc_kv_cache});if(Q.enc_padding_cache.location==="gpu-buffer")Q.enc_padding_cache.dispose();Q.enc_padding_cache=D;for(let O in V)if(O.startsWith("present.")){let P=O.replace("present","past_key_values"),N=Q.enc_kv_cache[P];if(N?.location==="gpu-buffer")N.dispose();Q.enc_kv_cache[P]=V[O]}return Q.enc_past_seq_len=z,F}async function MjQ(Q,J){while(Q.audio_embed_total_tokens<J&&!Q.stream_exhausted){let G=await Q.chunks_iter.next();if(G.done){Q.stream_exhausted=!0;break}let H=await DjQ(Q,G.value);Q.audio_embed_queue.push({data:H.data,tokens:H.dims[1]}),Q.audio_embed_total_tokens+=H.dims[1]}}function LjQ(Q,J,G){if(Q.audio_embed_queue.length===0)return;let H=J.data,K=0,z=G;while(z>0&&Q.audio_embed_queue.length>0){let q=Q.audio_embed_queue[0],F=q.tokens-Q.audio_queue_offset,D=Math.min(z,F),V=Q.audio_queue_offset*Q.text_hidden_size;for(let O=0;O<D*Q.text_hidden_size;++O)H[K*Q.text_hidden_size+O]+=q.data[V+O];if(K+=D,z-=D,Q.audio_queue_offset+=D,Q.audio_queue_offset>=q.tokens)Q.audio_embed_queue.shift(),Q.audio_queue_offset=0}Q.audio_consumed+=G-z}var OjQ=class extends yR{constructor(Q){super();this._s=Q}_call(Q){let J=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return Q.map(()=>J)}},CE0=class extends s0{forward_params=["input_ids","attention_mask","position_ids","past_key_values"]},IE0=class extends CE0{async forward({input_ids:Q,past_key_values:J,...G}){let H=Q.dims[1],K=Q90.get(this);if(K)await MjQ(K,K.audio_consumed+H);let{inputs_embeds:z}=await E6(this.sessions.embed_tokens,{input_ids:Q});if(K)LjQ(K,z,H);let q={inputs_embeds:z,...G};G10(this,q,J);let F=this.sessions.decoder_model_merged,D=JX(q,F.inputNames);return await E6(F,D)}async generate({input_features:Q,stopping_criteria:J,...G}){if(!Q)throw Error("input_features (generator/iterable) must be provided");let H=FjQ(this,Q);Q90.set(this,H);let K=new X20;if(K.push(new OjQ(H)),J)K.extend(J);try{return await super.generate({...G,stopping_criteria:K})}finally{H.enc_kv_cache.dispose(),Q90.delete(this)}}},rR=class extends s0{},PjQ=class extends rR{},NjQ=class extends rR{async _call(Q){return new VB(await super._call(Q))}},jjQ=class extends rR{async _call(Q){return new T8(await super._call(Q))}},RE0=class extends _7{constructor({logits:Q,embeddings:J}){super();this.logits=Q,this.embeddings=J}},uV=class extends s0{},CjQ=class extends uV{},IjQ=class extends uV{async _call(Q){return new VB(await super._call(Q))}},RjQ=class extends uV{async _call(Q){return new T8(await super._call(Q))}},wjQ=class extends uV{async _call(Q){return new RE0(await super._call(Q))}},EjQ=class extends uV{async _call(Q){return new R7(await super._call(Q))}},wE0=class extends s0{},SjQ=class extends wE0{},TjQ=class extends Q20{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},HX0=class extends s0{requires_attention_mask=!1;main_input_name="input_features";forward_params=["input_features","attention_mask","decoder_input_ids","decoder_attention_mask","past_key_values"]},kjQ=class extends HX0{},EE0=class extends HX0{_prepare_generation_config(Q,J){return super._prepare_generation_config(Q,J,TjQ)}_retrieve_init_tokens(Q){let J=[Q.decoder_start_token_id],G=Q.language,H=Q.task;if(Q.is_multilingual){if(!G)g8.warn("No language specified - defaulting to English (en)."),G="en";let z=`<|${KUQ(G)}|>`;J.push(Q.lang_to_id[z]),J.push(Q.task_to_id[H??"transcribe"])}else if(G||H)throw 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.");if(!Q.return_timestamps&&Q.no_timestamps_token_id&&J.at(-1)!==Q.no_timestamps_token_id)J.push(Q.no_timestamps_token_id);else if(Q.return_timestamps&&J.at(-1)===Q.no_timestamps_token_id)g8.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),J.pop();return J.filter((K)=>K!=null)}async generate({inputs:Q=null,generation_config:J=null,logits_processor:G=null,stopping_criteria:H=null,...K}){J=this._prepare_generation_config(J,K);let z=K.decoder_input_ids instanceof PQ?o90(K.decoder_input_ids):K.decoder_input_ids??this._retrieve_init_tokens(J);if(J.return_timestamps)G??=new $90,G.push(new uZQ(J,z));if(J.begin_suppress_tokens)G??=new $90,G.push(new ew0(J.begin_suppress_tokens,z.length));if(J.return_token_timestamps){if(!J.alignment_heads)throw Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");if(J.task==="translate")g8.warn("Token-level timestamps may not be reliable for task 'translate'.");J.output_attentions=!0,J.return_dict_in_generate=!0}if(J.return_timestamps&&!K.max_new_tokens)return this._generate_with_seek({inputs:Q,generation_config:J,logits_processor:G,init_tokens:z,kwargs:K});let q=await super.generate({inputs:Q,generation_config:J,logits_processor:G,decoder_input_ids:z,...K});if(J.return_token_timestamps)q.token_timestamps=this._extract_token_timestamps(q,J.alignment_heads,J.num_frames,0.02,z.length);return q}async _generate_with_seek({inputs:Q,generation_config:J,logits_processor:G,init_tokens:H,kwargs:K}){let z=J.no_timestamps_token_id+1,q=Array.isArray(J.eos_token_id)?J.eos_token_id[0]:J.eos_token_id,F=J.return_token_timestamps,D=Q,V=D.dims[2],O=2,N=2*this.config.max_source_positions,I=0,R=[],w=[];while(I<V){let T=Math.min(I+N,V),y=D.slice(null,null,[I,T]),x,b=y.dims[2];if(b<N){let c0=D.dims[1],WQ=new Float32Array(c0*N),R0=y.data;for(let l0=0;l0<c0;++l0)WQ.set(R0.subarray(l0*b,(l0+1)*b),l0*N);x=new PQ("float32",WQ,[1,c0,N])}else x=y;if(G){for(let c0 of G)if("begin_index"in c0)c0.begin_index=H.length}let g=await super.generate({inputs:x,generation_config:J,logits_processor:G,decoder_input_ids:H,...K}),_=(F?g.sequences:g)[0].tolist().map(Number).slice(H.length),a;if(F){g.token_timestamps=this._extract_token_timestamps(g,J.alignment_heads,Math.floor((T-I)/2),0.02,H.length);let c0=I/2*0.02;a=g.token_timestamps[0].tolist().slice(H.length).map((WQ)=>WQ+c0)}if(_.length>0&&_.at(-1)===q)_.pop();if(_.length===0)break;let r=_.map((c0)=>c0>=z),f0=_.length>=2&&r[_.length-1]&&!r[_.length-2],t=[];for(let c0=0;c0<_.length-1;++c0)if(r[c0]&&r[c0+1])t.push(c0+1);let p0,u0=_.length;if(t.length>0)if(f0)p0=T-I;else{let c0=t.at(-1);p0=(_[c0-1]-z)*2,u0=c0}else p0=T-I;let d=Math.floor(I/2),n=z+1500;for(let c0=0;c0<u0;++c0)if(_[c0]>=z)_[c0]=Math.min(_[c0]+d,n);if(R.push(..._.slice(0,u0)),a)w.push(...a.slice(0,u0));I+=p0}R.push(q);let E=[...H,...R];if(F){let T=new PQ("int64",E.map(BigInt),[1,E.length]),y=[...Array(H.length).fill(0),...w,0],x=new PQ("float32",new Float32Array(y),[1,y.length]);return{sequences:T,token_timestamps:x}}return new PQ("int64",E.map(BigInt),[1,E.length])}_extract_token_timestamps(Q,J,G=null,H=0.02,K=0){if(!Q.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");if(G==null)g8.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 z=this.config.median_filter_width;if(z===void 0)g8.warn("Model config has no `median_filter_width`, using default value of 7."),z=7;let q=Q.cross_attentions,F=Array.from({length:this.config.decoder_layers},(E,T)=>T9(q.map((y)=>y[T]),2)),D=g5(J.map(([E,T])=>{if(E>=F.length)throw Error(`Layer index ${E} is out of bounds for cross attentions (length ${F.length}).`);return G?F[E].slice(null,T,null,[0,G]):F[E].slice(null,T)})).transpose(1,0,2,3),[V,O]=UqQ(D,-2,0,!0),P=D.clone();for(let E=0;E<P.dims[0];++E){let T=P[E];for(let y=0;y<T.dims[0];++y){let x=T[y],b=V[E][y][0].data,g=O[E][y][0].data;for(let l=0;l<x.dims[0];++l){let _=x[l].data;for(let a=0;a<_.length;++a)_[a]=(_[a]-g[a])/b[a];_.set(OVQ(_,z))}}}let N=K>0?P.slice(null,null,[K,P.dims[2]],null):P,I=[c90(N,1)],R=Q.sequences.dims,w=new PQ("float32",new Float32Array(R[0]*R[1]),R);for(let E=0;E<R[0];++E){let T=I[E].neg().squeeze_(0),[y,x]=NVQ(T.tolist()),b=Array.from({length:y.length-1},(a,r)=>y[r+1]-y[r]),g=yW([1],b).map((a)=>!!a),l=[];for(let a=0;a<g.length;++a)if(g[a])l.push(x[a]*H);let _=Array(K).fill(0);if(_.push(...l),l.length>0)_.push(l.at(-1));w[E].data.set(_)}return w}},yjQ=class extends EE0{},pV=class extends s0{},vjQ=class extends pV{},xjQ=class extends pV{async _call(Q){return new f7(await super._call(Q))}},bjQ=class extends pV{async _call(Q){return new T8(await super._call(Q))}},gjQ=class extends pV{async _call(Q){return new R7(await super._call(Q))}},hjQ=class extends pV{async _call(Q){return new eX(await super._call(Q))}},lV=class extends s0{},_jQ=class extends lV{},fjQ=class extends lV{async _call(Q){return new f7(await super._call(Q))}},mjQ=class extends lV{async _call(Q){return new T8(await super._call(Q))}},ujQ=class extends lV{async _call(Q){return new R7(await super._call(Q))}},pjQ=class extends lV{async _call(Q){return new eX(await super._call(Q))}},BX0=class extends s0{},ljQ=class extends BX0{},djQ=class extends BX0{async _call(Q){return new SE0(await super._call(Q))}},SE0=class extends _7{constructor({logits:Q,pred_boxes:J}){super();this.logits=Q,this.pred_boxes=J}},AX0=class extends s0{},cjQ=class extends AX0{},ijQ=class extends AX0{},ojQ=new Map([["bert","BertModel"],["eurobert","EuroBertModel"],["neobert","NeoBertModel"],["modernbert","ModernBertModel"],["nomic_bert","NomicBertModel"],["roformer","RoFormerModel"],["electra","ElectraModel"],["esm","EsmModel"],["convbert","ConvBertModel"],["camembert","CamembertModel"],["deberta","DebertaModel"],["deberta-v2","DebertaV2Model"],["mpnet","MPNetModel"],["albert","AlbertModel"],["distilbert","DistilBertModel"],["roberta","RobertaModel"],["xlm","XLMModel"],["xlm-roberta","XLMRobertaModel"],["clap","ClapModel"],["clip","CLIPModel"],["clipseg","CLIPSegModel"],["chinese_clip","ChineseCLIPModel"],["siglip","SiglipModel"],["jina_clip","JinaCLIPModel"],["mobilebert","MobileBertModel"],["squeezebert","SqueezeBertModel"],["wav2vec2","Wav2Vec2Model"],["wav2vec2-bert","Wav2Vec2BertModel"],["unispeech","UniSpeechModel"],["unispeech-sat","UniSpeechSatModel"],["hubert","HubertModel"],["wavlm","WavLMModel"],["audio-spectrogram-transformer","ASTModel"],["vits","VitsModel"],["pyannote","PyAnnoteModel"],["wespeaker-resnet","WeSpeakerResNetModel"],["detr","DetrModel"],["rt_detr","RTDetrModel"],["rt_detr_v2","RTDetrV2Model"],["rf_detr","RFDetrModel"],["d_fine","DFineModel"],["table-transformer","TableTransformerModel"],["vit","ViTModel"],["ijepa","IJepaModel"],["pvt","PvtModel"],["vit_msn","ViTMSNModel"],["vit_mae","ViTMAEModel"],["groupvit","GroupViTModel"],["fastvit","FastViTModel"],["mobilevit","MobileViTModel"],["mobilevitv2","MobileViTV2Model"],["owlvit","OwlViTModel"],["owlv2","Owlv2Model"],["beit","BeitModel"],["deit","DeiTModel"],["hiera","HieraModel"],["convnext","ConvNextModel"],["convnextv2","ConvNextV2Model"],["dinov2","Dinov2Model"],["dinov2_with_registers","Dinov2WithRegistersModel"],["dinov3_vit","DINOv3ViTModel"],["dinov3_convnext","DINOv3ConvNextModel"],["resnet","ResNetModel"],["swin","SwinModel"],["swin2sr","Swin2SRModel"],["donut-swin","DonutSwinModel"],["yolos","YolosModel"],["dpt","DPTModel"],["glpn","GLPNModel"],["hifigan","SpeechT5HifiGan"],["efficientnet","EfficientNetModel"],["decision_transformer","DecisionTransformerModel"],["patchtst","PatchTSTModel"],["patchtsmixer","PatchTSMixerModel"],["mobilenet_v1","MobileNetV1Model"],["mobilenet_v2","MobileNetV2Model"],["mobilenet_v3","MobileNetV3Model"],["mobilenet_v4","MobileNetV4Model"],["maskformer","MaskFormerModel"],["mgp-str","MgpstrForSceneTextRecognition"],["style_text_to_speech_2","StyleTextToSpeech2Model"],["openai_privacy_filter","OpenAIPrivacyFilterModel"]]),njQ=new Map([["t5","T5Model"],["longt5","LongT5Model"],["mt5","MT5Model"],["bart","BartModel"],["mbart","MBartModel"],["marian","MarianModel"],["whisper","WhisperModel"],["cohere_asr","CohereAsrModel"],["m2m_100","M2M100Model"],["blenderbot","BlenderbotModel"],["blenderbot-small","BlenderbotSmallModel"]]),ajQ=new Map([["mimi","MimiModel"],["dac","DacModel"],["snac","SnacModel"]]),sjQ=new Map([["bloom","BloomModel"],["jais","JAISModel"],["gpt2","GPT2Model"],["gpt_oss","GptOssModel"],["gptj","GPTJModel"],["gpt_bigcode","GPTBigCodeModel"],["gpt_neo","GPTNeoModel"],["gpt_neox","GPTNeoXModel"],["codegen","CodeGenModel"],["llama","LlamaModel"],["apertus","ApertusModel"],["nanochat","NanoChatModel"],["arcee","ArceeModel"],["afmoe","AfmoeModel"],["lfm2","Lfm2Model"],["lfm2_moe","Lfm2MoeModel"],["smollm3","SmolLM3Model"],["exaone","ExaoneModel"],["olmo","OlmoModel"],["olmo2","Olmo2Model"],["olmo3","Olmo3Model"],["olmo_hybrid","OlmoHybridModel"],["mobilellm","MobileLLMModel"],["granite","GraniteModel"],["granitemoehybrid","GraniteMoeHybridModel"],["cohere","CohereModel"],["cohere2","Cohere2Model"],["gemma","GemmaModel"],["gemma2","Gemma2Model"],["vaultgemma","VaultGemmaModel"],["gemma3_text","Gemma3Model"],["helium","HeliumModel"],["glm","GlmModel"],["glm_moe_dsa","GlmMoeDsaModel"],["openelm","OpenELMModel"],["qwen2","Qwen2Model"],["qwen2_moe","Qwen2MoeModel"],["qwen3","Qwen3Model"],["qwen3_moe","Qwen3MoeModel"],["qwen3_next","Qwen3NextModel"],["phi","PhiModel"],["phi3","Phi3Model"],["mpt","MptModel"],["opt","OPTModel"],["mistral","MistralModel"],["mistral4","Mistral4Model"],["ministral","MinistralModel"],["ministral3","Ministral3Model"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2Model"],["deepseek_v3","DeepseekV3Model"],["falcon","FalconModel"],["falcon_h1","FalconH1Model"],["nemotron_h","NemotronHModel"],["solar_open","SolarOpenModel"],["stablelm","StableLmModel"],["modernbert-decoder","ModernBertDecoderModel"],["hunyuan_v1_dense","HunYuanDenseV1Model"],["youtu","YoutuModel"]]),TE0=new Map([["speecht5","SpeechT5ForSpeechToText"],["whisper","WhisperForConditionalGeneration"],["lite-whisper","LiteWhisperForConditionalGeneration"],["moonshine","MoonshineForConditionalGeneration"],["cohere_asr","CohereAsrForConditionalGeneration"]]),kE0=new Map([["speecht5","SpeechT5ForTextToSpeech"]]),yE0=new Map([["vits","VitsModel"],["musicgen","MusicgenForConditionalGeneration"],["supertonic","SupertonicForConditionalGeneration"]]),vE0=new Map([["bert","BertForSequenceClassification"],["eurobert","EuroBertForSequenceClassification"],["neobert","NeoBertForSequenceClassification"],["modernbert","ModernBertForSequenceClassification"],["roformer","RoFormerForSequenceClassification"],["electra","ElectraForSequenceClassification"],["esm","EsmForSequenceClassification"],["convbert","ConvBertForSequenceClassification"],["camembert","CamembertForSequenceClassification"],["deberta","DebertaForSequenceClassification"],["deberta-v2","DebertaV2ForSequenceClassification"],["mpnet","MPNetForSequenceClassification"],["albert","AlbertForSequenceClassification"],["distilbert","DistilBertForSequenceClassification"],["roberta","RobertaForSequenceClassification"],["xlm","XLMForSequenceClassification"],["xlm-roberta","XLMRobertaForSequenceClassification"],["bart","BartForSequenceClassification"],["mbart","MBartForSequenceClassification"],["mobilebert","MobileBertForSequenceClassification"],["squeezebert","SqueezeBertForSequenceClassification"]]),xE0=new Map([["bert","BertForTokenClassification"],["eurobert","EuroBertForTokenClassification"],["neobert","NeoBertForTokenClassification"],["modernbert","ModernBertForTokenClassification"],["roformer","RoFormerForTokenClassification"],["electra","ElectraForTokenClassification"],["esm","EsmForTokenClassification"],["convbert","ConvBertForTokenClassification"],["camembert","CamembertForTokenClassification"],["deberta","DebertaForTokenClassification"],["deberta-v2","DebertaV2ForTokenClassification"],["mpnet","MPNetForTokenClassification"],["distilbert","DistilBertForTokenClassification"],["roberta","RobertaForTokenClassification"],["xlm","XLMForTokenClassification"],["xlm-roberta","XLMRobertaForTokenClassification"],["openai_privacy_filter","OpenAIPrivacyFilterForTokenClassification"]]),bE0=new Map([["t5","T5ForConditionalGeneration"],["longt5","LongT5ForConditionalGeneration"],["mt5","MT5ForConditionalGeneration"],["bart","BartForConditionalGeneration"],["mbart","MBartForConditionalGeneration"],["marian","MarianMTModel"],["m2m_100","M2M100ForConditionalGeneration"],["blenderbot","BlenderbotForConditionalGeneration"],["blenderbot-small","BlenderbotSmallForConditionalGeneration"]]),gE0=new Map([["bloom","BloomForCausalLM"],["gpt2","GPT2LMHeadModel"],["gpt_oss","GptOssForCausalLM"],["jais","JAISLMHeadModel"],["gptj","GPTJForCausalLM"],["gpt_bigcode","GPTBigCodeForCausalLM"],["gpt_neo","GPTNeoForCausalLM"],["gpt_neox","GPTNeoXForCausalLM"],["codegen","CodeGenForCausalLM"],["llama","LlamaForCausalLM"],["nanochat","NanoChatForCausalLM"],["apertus","ApertusForCausalLM"],["llama4_text","Llama4ForCausalLM"],["arcee","ArceeForCausalLM"],["afmoe","AfmoeForCausalLM"],["lfm2","Lfm2ForCausalLM"],["lfm2_moe","Lfm2MoeForCausalLM"],["smollm3","SmolLM3ForCausalLM"],["exaone","ExaoneForCausalLM"],["olmo","OlmoForCausalLM"],["olmo2","Olmo2ForCausalLM"],["olmo3","Olmo3ForCausalLM"],["olmo_hybrid","OlmoHybridForCausalLM"],["mobilellm","MobileLLMForCausalLM"],["granite","GraniteForCausalLM"],["granitemoehybrid","GraniteMoeHybridForCausalLM"],["cohere","CohereForCausalLM"],["cohere2","Cohere2ForCausalLM"],["gemma","GemmaForCausalLM"],["gemma2","Gemma2ForCausalLM"],["vaultgemma","VaultGemmaForCausalLM"],["gemma3_text","Gemma3ForCausalLM"],["gemma3","Gemma3ForCausalLM"],["helium","HeliumForCausalLM"],["glm","GlmForCausalLM"],["glm_moe_dsa","GlmMoeDsaForCausalLM"],["openelm","OpenELMForCausalLM"],["qwen2","Qwen2ForCausalLM"],["qwen2_moe","Qwen2MoeForCausalLM"],["qwen3","Qwen3ForCausalLM"],["qwen3_moe","Qwen3MoeForCausalLM"],["qwen3_next","Qwen3NextForCausalLM"],["qwen2_vl","Qwen2VLForCausalLM"],["qwen2_5_vl","Qwen2_5_VLForCausalLM"],["qwen3_vl","Qwen3VLForCausalLM"],["qwen3_vl_moe","Qwen3VLMoeForCausalLM"],["qwen3_5","Qwen3_5ForCausalLM"],["qwen3_5_text","Qwen3_5ForCausalLM"],["qwen3_5_moe","Qwen3_5MoeForCausalLM"],["gemma3n","Gemma3nForCausalLM"],["gemma4","Gemma4ForCausalLM"],["phi","PhiForCausalLM"],["phi3","Phi3ForCausalLM"],["mpt","MptForCausalLM"],["opt","OPTForCausalLM"],["mbart","MBartForCausalLM"],["mistral","MistralForCausalLM"],["mistral4","Mistral4ForCausalLM"],["ministral","MinistralForCausalLM"],["ministral3","Ministral3ForCausalLM"],["ernie4_5","Ernie4_5ForCausalLM"],["starcoder2","Starcoder2ForCausalLM"],["deepseek_v3","DeepseekV3ForCausalLM"],["falcon","FalconForCausalLM"],["falcon_h1","FalconH1ForCausalLM"],["nemotron_h","NemotronHForCausalLM"],["trocr","TrOCRForCausalLM"],["solar_open","SolarOpenForCausalLM"],["stablelm","StableLmForCausalLM"],["modernbert-decoder","ModernBertDecoderForCausalLM"],["hunyuan_v1_dense","HunYuanDenseV1ForCausalLM"],["youtu","YoutuForCausalLM"],["phi3_v","Phi3VForCausalLM"]]),rjQ=new Map([["multi_modality","MultiModalityCausalLM"]]),hE0=new Map([["bert","BertForMaskedLM"],["eurobert","EuroBertForMaskedLM"],["neobert","NeoBertForMaskedLM"],["modernbert","ModernBertForMaskedLM"],["roformer","RoFormerForMaskedLM"],["electra","ElectraForMaskedLM"],["esm","EsmForMaskedLM"],["convbert","ConvBertForMaskedLM"],["camembert","CamembertForMaskedLM"],["deberta","DebertaForMaskedLM"],["deberta-v2","DebertaV2ForMaskedLM"],["mpnet","MPNetForMaskedLM"],["albert","AlbertForMaskedLM"],["distilbert","DistilBertForMaskedLM"],["roberta","RobertaForMaskedLM"],["xlm","XLMWithLMHeadModel"],["xlm-roberta","XLMRobertaForMaskedLM"],["mobilebert","MobileBertForMaskedLM"],["squeezebert","SqueezeBertForMaskedLM"]]),_E0=new Map([["bert","BertForQuestionAnswering"],["neobert","NeoBertForQuestionAnswering"],["roformer","RoFormerForQuestionAnswering"],["electra","ElectraForQuestionAnswering"],["convbert","ConvBertForQuestionAnswering"],["camembert","CamembertForQuestionAnswering"],["deberta","DebertaForQuestionAnswering"],["deberta-v2","DebertaV2ForQuestionAnswering"],["mpnet","MPNetForQuestionAnswering"],["albert","AlbertForQuestionAnswering"],["distilbert","DistilBertForQuestionAnswering"],["roberta","RobertaForQuestionAnswering"],["xlm","XLMForQuestionAnswering"],["xlm-roberta","XLMRobertaForQuestionAnswering"],["mobilebert","MobileBertForQuestionAnswering"],["squeezebert","SqueezeBertForQuestionAnswering"]]),fE0=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"]]),mE0=new Map([["llava","LlavaForConditionalGeneration"],["llava_onevision","LlavaOnevisionForConditionalGeneration"],["moondream1","Moondream1ForConditionalGeneration"],["florence2","Florence2ForConditionalGeneration"],["qwen2_vl","Qwen2VLForConditionalGeneration"],["qwen2_5_vl","Qwen2_5_VLForConditionalGeneration"],["qwen3_vl","Qwen3VLForConditionalGeneration"],["qwen3_vl_moe","Qwen3VLMoeForConditionalGeneration"],["qwen3_5","Qwen3_5ForConditionalGeneration"],["qwen3_5_moe","Qwen3_5MoeForConditionalGeneration"],["lfm2_vl","Lfm2VlForConditionalGeneration"],["idefics3","Idefics3ForConditionalGeneration"],["smolvlm","SmolVLMForConditionalGeneration"],["paligemma","PaliGemmaForConditionalGeneration"],["llava_qwen2","LlavaQwen2ForCausalLM"],["gemma3","Gemma3ForConditionalGeneration"],["gemma3n","Gemma3nForConditionalGeneration"],["gemma4","Gemma4ForConditionalGeneration"],["mistral3","Mistral3ForConditionalGeneration"],["lighton_ocr","LightOnOcrForConditionalGeneration"],["glm_ocr","GlmOcrForConditionalGeneration"]]),uE0=new Map([["granite_speech","GraniteSpeechForConditionalGeneration"],["ultravox","UltravoxModel"],["voxtral","VoxtralForConditionalGeneration"],["voxtral_realtime","VoxtralRealtimeForConditionalGeneration"]]),tjQ=new Map([["vision-encoder-decoder","VisionEncoderDecoderModel"]]),pE0=new Map([["vit","ViTForImageClassification"],["ijepa","IJepaForImageClassification"],["pvt","PvtForImageClassification"],["vit_msn","ViTMSNForImageClassification"],["fastvit","FastViTForImageClassification"],["mobilevit","MobileViTForImageClassification"],["mobilevitv2","MobileViTV2ForImageClassification"],["beit","BeitForImageClassification"],["deit","DeiTForImageClassification"],["hiera","HieraForImageClassification"],["convnext","ConvNextForImageClassification"],["convnextv2","ConvNextV2ForImageClassification"],["dinov2","Dinov2ForImageClassification"],["dinov2_with_registers","Dinov2WithRegistersForImageClassification"],["resnet","ResNetForImageClassification"],["swin","SwinForImageClassification"],["segformer","SegformerForImageClassification"],["efficientnet","EfficientNetForImageClassification"],["mobilenet_v1","MobileNetV1ForImageClassification"],["mobilenet_v2","MobileNetV2ForImageClassification"],["mobilenet_v3","MobileNetV3ForImageClassification"],["mobilenet_v4","MobileNetV4ForImageClassification"]]),lE0=new Map([["detr","DetrForObjectDetection"],["rt_detr","RTDetrForObjectDetection"],["rt_detr_v2","RTDetrV2ForObjectDetection"],["rf_detr","RFDetrForObjectDetection"],["d_fine","DFineForObjectDetection"],["table-transformer","TableTransformerForObjectDetection"],["yolos","YolosForObjectDetection"]]),dE0=new Map([["owlvit","OwlViTForObjectDetection"],["owlv2","Owlv2ForObjectDetection"],["grounding-dino","GroundingDinoForObjectDetection"]]),LV=new Map([["detr","DetrForSegmentation"],["clipseg","CLIPSegForImageSegmentation"]]),cE0=new Map([["segformer","SegformerForSemanticSegmentation"],["sapiens","SapiensForSemanticSegmentation"],["swin","SwinForSemanticSegmentation"],["mobilenet_v1","MobileNetV1ForSemanticSegmentation"],["mobilenet_v2","MobileNetV2ForSemanticSegmentation"],["mobilenet_v3","MobileNetV3ForSemanticSegmentation"],["mobilenet_v4","MobileNetV4ForSemanticSegmentation"]]),iE0=new Map([["detr","DetrForSegmentation"],["maskformer","MaskFormerForInstanceSegmentation"]]),oE0=new Map([["sam","SamModel"],["sam2","Sam2Model"],["edgetam","EdgeTamModel"],["sam3_tracker","Sam3TrackerModel"]]),nE0=new Map([["wav2vec2","Wav2Vec2ForCTC"],["wav2vec2-bert","Wav2Vec2BertForCTC"],["unispeech","UniSpeechForCTC"],["unispeech-sat","UniSpeechSatForCTC"],["wavlm","WavLMForCTC"],["hubert","HubertForCTC"],["parakeet_ctc","ParakeetForCTC"]]),aE0=new Map([["wav2vec2","Wav2Vec2ForSequenceClassification"],["wav2vec2-bert","Wav2Vec2BertForSequenceClassification"],["unispeech","UniSpeechForSequenceClassification"],["unispeech-sat","UniSpeechSatForSequenceClassification"],["wavlm","WavLMForSequenceClassification"],["hubert","HubertForSequenceClassification"],["audio-spectrogram-transformer","ASTForAudioClassification"]]),sE0=new Map([["wavlm","WavLMForXVector"]]),rE0=new Map([["unispeech-sat","UniSpeechSatForAudioFrameClassification"],["wavlm","WavLMForAudioFrameClassification"],["wav2vec2","Wav2Vec2ForAudioFrameClassification"],["pyannote","PyAnnoteForAudioFrameClassification"]]),tE0=new Map([["vitmatte","VitMatteForImageMatting"]]),ejQ=new Map([["patchtst","PatchTSTForPrediction"],["patchtsmixer","PatchTSMixerForPrediction"]]),eE0=new Map([["swin2sr","Swin2SRForImageSuperResolution"]]),QS0=new Map([["chmv2","CHMv2ForDepthEstimation"],["dpt","DPTForDepthEstimation"],["depth_anything","DepthAnythingForDepthEstimation"],["glpn","GLPNForDepthEstimation"],["sapiens","SapiensForDepthEstimation"],["depth_pro","DepthProForDepthEstimation"],["metric3d","Metric3DForDepthEstimation"],["metric3dv2","Metric3Dv2ForDepthEstimation"]]),XS0=new Map([["sapiens","SapiensForNormalEstimation"]]),JS0=new Map([["vitpose","VitPoseForPoseEstimation"]]),YS0=new Map([["clip","CLIPVisionModelWithProjection"],["siglip","SiglipVisionModel"],["jina_clip","JinaCLIPVisionModel"]]),GS0=[[ojQ,RQ.EncoderOnly],[njQ,RQ.EncoderDecoder],[sjQ,RQ.DecoderOnlyWithoutHead],[ajQ,RQ.AutoEncoder],[vE0,RQ.EncoderOnly],[xE0,RQ.EncoderOnly],[bE0,RQ.Seq2Seq],[TE0,RQ.Seq2Seq],[gE0,RQ.DecoderOnly],[rjQ,RQ.MultiModality],[hE0,RQ.EncoderOnly],[_E0,RQ.EncoderOnly],[fE0,RQ.Vision2Seq],[mE0,RQ.ImageTextToText],[uE0,RQ.AudioTextToText],[pE0,RQ.EncoderOnly],[LV,RQ.EncoderOnly],[iE0,RQ.EncoderOnly],[cE0,RQ.EncoderOnly],[tE0,RQ.EncoderOnly],[ejQ,RQ.EncoderOnly],[eE0,RQ.EncoderOnly],[QS0,RQ.EncoderOnly],[XS0,RQ.EncoderOnly],[JS0,RQ.EncoderOnly],[lE0,RQ.EncoderOnly],[dE0,RQ.EncoderOnly],[oE0,RQ.MaskGeneration],[nE0,RQ.EncoderOnly],[aE0,RQ.EncoderOnly],[kE0,RQ.Seq2Seq],[yE0,RQ.EncoderOnly],[sE0,RQ.EncoderOnly],[rE0,RQ.EncoderOnly],[YS0,RQ.EncoderOnly]];for(let[Q,J]of GS0)for(let G of Q.values()){b5.set(G,J);let H=H10[G];CV.set(H,G),Y10.set(G,H)}var QCQ=[["MusicgenForConditionalGeneration",t20,RQ.Musicgen],["Phi3VForCausalLM",JE0,RQ.Phi3V],["CLIPTextModelWithProjection",D20,RQ.EncoderOnly],["SiglipTextModel",VE0,RQ.EncoderOnly],["JinaCLIPTextModel",u20,RQ.EncoderOnly],["ClapTextModelWithProjection",Z20,RQ.EncoderOnly],["ClapAudioModelWithProjection",F20,RQ.EncoderOnly],["DacEncoderModel",O20,RQ.EncoderOnly],["DacDecoderModel",P20,RQ.EncoderOnly],["MimiEncoderModel",a20,RQ.EncoderOnly],["MimiDecoderModel",s20,RQ.EncoderOnly],["SnacEncoderModel",qE0,RQ.EncoderOnly],["SnacDecoderModel",UE0,RQ.EncoderOnly],["Gemma3nForConditionalGeneration",_R,RQ.ImageAudioTextToText],["Gemma4ForConditionalGeneration",_10,RQ.ImageAudioTextToText],["SupertonicForConditionalGeneration",FE0,RQ.Supertonic],["ChatterboxModel",q20,RQ.Chatterbox],["VoxtralRealtimeForConditionalGeneration",IE0,RQ.VoxtralRealtime]];for(let[Q,J,G]of QCQ)b5.set(Q,G),CV.set(J,Q),Y10.set(Q,J);var WS0=new Map([["modnet",LV],["birefnet",LV],["isnet",LV],["ben",LV]]);for(let[Q,J]of WS0.entries())J.set(Q,"PreTrainedModel"),b5.set(Q,RQ.EncoderOnly),Y10.set(Q,s0);var XCQ=new Set(WS0.keys());b5.set("PreTrainedModel",RQ.EncoderOnly);CV.set(s0,"PreTrainedModel");var p6={MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES:vE0,MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES:xE0,MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES:kE0,MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES:yE0,MODEL_FOR_MASKED_LM_MAPPING_NAMES:hE0,MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES:_E0,MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES:pE0,MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES:LV,MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES:cE0,MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES:iE0,MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES:lE0,MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES:dE0,MODEL_FOR_MASK_GENERATION_MAPPING_NAMES:oE0,MODEL_FOR_CTC_MAPPING_NAMES:nE0,MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES:aE0,MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES:sE0,MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES:rE0,MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES:tjQ,MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES:tE0,MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES:eE0,MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES:QS0,MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES:XS0,MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES:JS0,MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES:YS0,MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES:mE0,MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES:uE0,MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES:bE0,MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES:TE0,MODEL_FOR_CAUSAL_LM_MAPPING_NAMES:gE0,MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES:fE0};YFQ(p6);var l6=class{static MODEL_CLASS_MAPPINGS=null;static BASE_IF_FAIL=!1;static supports(Q){if(!this.MODEL_CLASS_MAPPINGS)return!1;for(let J of this.MODEL_CLASS_MAPPINGS)if(J.has(Q))return!0;return this.BASE_IF_FAIL}static async from_pretrained(Q,{progress_callback:J=null,config:G=null,cache_dir:H=null,local_files_only:K=!1,revision:z="main",model_file_name:q=null,subfolder:F="onnx",device:D=null,dtype:V=null,use_external_data_format:O=null,session_options:P={}}={}){let N={progress_callback:J,config:G,cache_dir:H,local_files_only:K,revision:z,model_file_name:q,subfolder:F,device:D,dtype:V,use_external_data_format:O,session_options:P};if(N.config=await _F.from_pretrained(Q,N),!this.MODEL_CLASS_MAPPINGS)throw Error("`MODEL_CLASS_MAPPINGS` not implemented for this type of `AutoClass`: "+this.name);let{model_type:I}=N.config;for(let R of this.MODEL_CLASS_MAPPINGS){let w=R.get(I);if(!w){for(let E of R.values())if(E[0]===I){w=E;break}if(!w)continue}return await H10[w].from_pretrained(Q,N)}if(this.BASE_IF_FAIL){if(!XCQ.has(I))g8.warn(`Unknown model class "${I}", attempting to construct from base class.`);return await s0.from_pretrained(Q,N)}else throw Error(`Unsupported model type: ${I}`)}},kF=class extends l6{static MODEL_CLASS_MAPPINGS=GS0.map((Q)=>Q[0]);static BASE_IF_FAIL=!0},SI0=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},JCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},X90=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},YCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},GCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},WCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},HCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},BCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},ACQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},KCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},zCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},TI0=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},kI0=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},yI0=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},VCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},qCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]},xz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]},UCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_CTC_MAPPING_NAMES]},$CQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]},bz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]},gz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]},ZCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]},hz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]},FCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},DCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]},_z8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]},fz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]},MCQ=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},mz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]},uz8=class extends l6{static MODEL_CLASS_MAPPINGS=[p6.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]};async function uG(Q){if(!Array.isArray(Q))Q=[Q];return await Promise.all(Q.map((J)=>gG.read(J)))}async function OV(Q,J){if(!Array.isArray(Q))Q=[Q];return await Promise.all(Q.map((G)=>{if(typeof G==="string"||G instanceof URL)return FUQ(G,J);else if(G instanceof Float64Array)return new Float32Array(G);return G}))}function D90(Q,J){if(J)Q=Q.map((q)=>q|0);let[G,H,K,z]=Q;return{xmin:G,ymin:H,xmax:K,ymax:z}}var W7=class extends nJ{constructor({task:Q,model:J,tokenizer:G=null,processor:H=null}){super();this.task=Q,this.model=J,this.tokenizer=G,this.processor=H}async dispose(){await this.model.dispose()}},LCQ=class extends W7{async _call(Q,{top_k:J=1}={}){let G=this.tokenizer(Q,{padding:!0,truncation:!0}),H=await this.model(G),{problem_type:K,id2label:z}=this.model.config,q=K==="multi_label_classification"?(D)=>D.sigmoid():(D)=>new PQ("float32",wX(D.data),D.dims),F=[];for(let D of H.logits){let V=q(D),O=await SV(V,J),P=O[0].tolist(),I=O[1].tolist().map((R,w)=>({label:z?z[R]:`LABEL_${R}`,score:P[w]}));if(J===1)F.push(...I);else F.push(I)}return Array.isArray(Q)||J===1?F:F[0]}},OCQ=class extends W7{async _call(Q,{ignore_labels:J=["O"],aggregation_strategy:G="none"}={}){if(G!=="none"&&G!=="simple")throw Error(`Invalid aggregation_strategy: "${G}". Must be one of "none" or "simple".`);let H=Array.isArray(Q),K=this.tokenizer(H?Q:[Q],{padding:!0,truncation:!0}),q=(await this.model(K)).logits,F=this.model.config.id2label,D=[];for(let V=0;V<q.dims[0];++V){let O=K.input_ids[V].tolist(),P=q[V],N=[];for(let I=0;I<P.dims[0];++I){let R=P[I],w=D7(R.data)[1],E=F?F[w]:`LABEL_${w}`;if(J.includes(E))continue;let T=this.tokenizer.decode([O[I]],{skip_special_tokens:!0});if(T==="")continue;let y=wX(R.data);N.push({entity:E,score:y[w],index:I,word:T})}D.push(G==="simple"?NCQ(N,O,this.tokenizer):N)}return H?D:D[0]}};function PCQ(Q){let J=Q[0];return Q[1]==="-"&&(J==="B"||J==="I"||J==="E"||J==="S")?[J,Q.slice(2)]:["I",Q]}function NCQ(Q,J,G){let H=[],K=null;for(let z=0;z<Q.length;++z){let[q,F]=PCQ(Q[z].entity);if(K===F&&q!=="B"&&q!=="S"){if(H[H.length-1].end=z+1,q==="E")K=null}else H.push({tag:F,start:z,end:z+1}),K=q==="S"?null:F}return H.map(({tag:z,start:q,end:F})=>{let D=0,V=[];for(let O=q;O<F;++O)D+=Q[O].score,V.push(J[Q[O].index]);return{entity_group:z,score:D/(F-q),word:G.decode(V,{skip_special_tokens:!0})}})}var jCQ=class extends W7{async _call(Q,J,{top_k:G=1}={}){let H=this.tokenizer(Q,{text_pair:J,padding:!0,truncation:!0}),K=Array.isArray(Q),{start_logits:z,end_logits:q}=await this.model(H),F=H.input_ids.tolist(),D=H.attention_mask.tolist(),{all_special_ids:V,sep_token_id:O}=this.tokenizer,P=[];for(let N=0;N<z.dims[0];++N){let I=F[N],R=I.findIndex((g)=>g==O),w=z[N].tolist(),E=q[N].tolist();for(let g=1;g<w.length;++g)if(D[N]==0||g<=R||V.findIndex((l)=>l==I[g])!==-1)w[g]=-1/0,E[g]=-1/0;let T=wX(w).map((g,l)=>[g,l]),y=wX(E).map((g,l)=>[g,l]);T[0][0]=0,y[0][0]=0;let x=cBQ(T,y).filter((g)=>g[0][1]<=g[1][1]).map((g)=>[g[0][1],g[1][1],g[0][0]*g[1][0]]).sort((g,l)=>l[2]-g[2]),b=[];for(let g=0;g<Math.min(x.length,G);++g){let[l,_,a]=x[g],r=I.slice(l,_+1),f0=this.tokenizer.decode(r,{skip_special_tokens:!0});b.push({answer:f0,score:a})}if(G===1)P.push(...b);else P.push(b)}return K?P:P[0]}},CCQ=class extends W7{async _call(Q,{top_k:J=5}={}){let{mask_token_id:G,mask_token:H}=this.tokenizer,K=this.tokenizer(Q,{padding:!0,truncation:!0}),{logits:z}=await this.model(K),q=[],F=K.input_ids.tolist();for(let D=0;D<F.length;++D){let V=F[D],O=V.findIndex((w)=>w==G);if(O===-1)throw Error(`Mask token (${H}) not found in text.`);let P=z[D][O],N=await SV(new PQ("float32",wX(P.data),P.dims),J),I=N[0].tolist(),R=N[1].tolist();q.push(R.map((w,E)=>{let T=V.slice();return T[O]=w,{score:I[E],token:Number(w),token_str:this.tokenizer.decode([w]),sequence:this.tokenizer.decode(T,{skip_special_tokens:!0})}}))}return Array.isArray(Q)?q:q[0]}},KX0=class extends W7{_default_generation_config={max_new_tokens:256};_key="generated_text";async _call(Q,J={}){if(!Array.isArray(Q))Q=[Q];if(this.model.config.prefix)Q=Q.map((F)=>this.model.config.prefix+F);let G=this.model.config.task_specific_params;if(G&&G[this.task]){if(G[this.task].prefix)Q=Q.map((F)=>G[this.task].prefix+F)}let H=this.tokenizer,K={padding:!0,truncation:!0},z;if(this.task==="translation"&&"_build_translation_inputs"in H)z=H._build_translation_inputs(Q,K,J);else z=H(Q,K);let q=await this.model.generate({...z,...this._default_generation_config,...J});return H.batch_decode(q,{skip_special_tokens:!0}).map((F)=>({[this._key]:F}))}},ICQ=class extends KX0{_key="summary_text"},RCQ=class extends KX0{_key="translation_text"};function vI0(Q){return Array.isArray(Q)&&Q.every((J)=>("role"in J)&&("content"in J))}var wCQ=class extends W7{_default_generation_config={max_new_tokens:256};async _call(Q,J={}){let{add_special_tokens:G,return_full_text:H,tools:K,documents:z,chat_template:q,tokenizer_encode_kwargs:F,...D}=J,V=!1,O=!1,P=G??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,N=F,I;if(typeof Q==="string")I=Q=[Q];else if(Array.isArray(Q)&&Q.every((b)=>typeof b==="string"))V=!0,I=Q;else{if(vI0(Q))Q=[Q];else if(Array.isArray(Q)&&Q.every(vI0))V=!0;else throw Error("Input must be a string, an array of strings, a Chat, or an array of Chats");O=!0;let b={tokenize:!1,add_generation_prompt:!0,...JX({tools:K,documents:z,chat_template:q},["tools","documents","chat_template"]),...N};I=Q.map((g)=>this.tokenizer.apply_chat_template(g,b)),P=!1,N=void 0}let R=O?!1:H??!0;this.tokenizer.padding_side="left";let w=this.tokenizer(I,{add_special_tokens:P,padding:!0,truncation:!0,...N}),E=await this.model.generate({...w,...this._default_generation_config,...D}),T=this.tokenizer.batch_decode(E,{skip_special_tokens:!0}),y;if(!R&&w.input_ids.dims.at(-1)>0)y=this.tokenizer.batch_decode(w.input_ids,{skip_special_tokens:!0}).map((b)=>b.length);let x=Array.from({length:Q.length},(b)=>[]);for(let b=0;b<T.length;++b){let g=Math.floor(b/E.dims[0]*Q.length);if(y)T[b]=T[b].slice(y[g]);x[g].push({generated_text:O?[...Q[g],{role:"assistant",content:T[b]}]:T[b]})}return!V&&x.length===1?x[0]:x}},ECQ=class extends W7{constructor(Q){super(Q);if(this.label2id=Object.fromEntries(Object.entries(this.model.config.label2id).map(([J,G])=>[J.toLowerCase(),G])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0)g8.warn("Could not find 'entailment' in label2id mapping. Using 2 as entailment_id."),this.entailment_id=2;if(this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0)g8.warn("Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id."),this.contradiction_id=0}async _call(Q,J,{hypothesis_template:G="This example is {}.",multi_label:H=!1}={}){let K=Array.isArray(Q);if(!K)Q=[Q];if(!Array.isArray(J))J=[J];let z=J.map((D)=>G.replace("{}",D)),q=H||J.length===1,F=[];for(let D of Q){let V=[];for(let N of z){let I=this.tokenizer(D,{text_pair:N,padding:!0,truncation:!0}),R=await this.model(I);if(q)V.push([R.logits.data[this.contradiction_id],R.logits.data[this.entailment_id]]);else V.push(R.logits.data[this.entailment_id])}let P=(q?V.map((N)=>wX(N)[1]):wX(V)).map((N,I)=>[N,I]).sort((N,I)=>I[0]-N[0]);F.push({sequence:D,labels:P.map((N)=>J[N[1]]),scores:P.map((N)=>N[0])})}return K?F:F[0]}},SCQ=class extends W7{async _call(Q,{top_k:J=5}={}){let G=this.processor.feature_extractor.config.sampling_rate,H=await OV(Q,G),K=this.model.config.id2label,z=[];for(let q of H){let F=await this.processor(q),V=(await this.model(F)).logits[0],O=await SV(new PQ("float32",wX(V.data),V.dims),J),P=O[0].tolist(),I=O[1].tolist().map((R,w)=>({label:K?K[R]:`LABEL_${R}`,score:P[w]}));z.push(I)}return Array.isArray(Q)?z:z[0]}},TCQ=class extends W7{async _call(Q,J,{hypothesis_template:G="This is a sound of {}."}={}){let H=!Array.isArray(Q);if(H)Q=[Q];let K=J.map((V)=>G.replace("{}",V)),z=this.tokenizer(K,{padding:!0,truncation:!0}),q=this.processor.feature_extractor.config.sampling_rate,F=await OV(Q,q),D=[];for(let V of F){let O=await this.processor(V),P=await this.model({...z,...O}),N=wX(P.logits_per_audio.data);D.push([...N].map((I,R)=>({score:I,label:J[R]})))}return H?D[0]:D}},kCQ=class extends W7{_default_generation_config={};async _call(Q,J={}){switch(J={...this._default_generation_config,...J},this.model.config.model_type){case"whisper":case"lite-whisper":return this._call_whisper(Q,J);case"wav2vec2":case"wav2vec2-bert":case"unispeech":case"unispeech-sat":case"hubert":case"parakeet_ctc":return this._call_wav2vec2(Q,J);case"moonshine":return this._call_moonshine(Q,J);case"cohere_asr":return this._call_cohere_asr(Q,J);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(Q,J){if(J.language)g8.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".');if(J.task)g8.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let G=!Array.isArray(Q),H=G?[Q]:Q,K=this.processor.feature_extractor.config.sampling_rate,z=await OV(H,K),q=[];for(let F of z){let D=await this.processor(F),O=(await this.model(D)).logits[0],P=[];for(let I of O)P.push(D7(I.data)[1]);let N=this.tokenizer.decode(P,{skip_special_tokens:!0}).trim();q.push({text:N})}return G?q[0]:q}async _call_whisper(Q,J){let G=J.return_timestamps??!1,H=J.chunk_length_s??0,K=J.force_full_sequences??!1,z=J.stride_length_s??null,q={...J};if(G==="word")q.return_token_timestamps=!0,q.return_timestamps=!0;let F=!Array.isArray(Q),D=F?[Q]:Q,V=this.processor.feature_extractor.config,O=V.chunk_length/this.model.config.max_source_positions,P=V.hop_length,N=V.sampling_rate,I=await OV(D,N),R=[];for(let w of I){let E=[];if(H>0){if(z===null)z=H/6;else if(H<=z)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let x=N*H,b=N*z,g=x-2*b,l=0;while(!0){let _=l+x,a=w.subarray(l,_),r=await this.processor(a),f0=l===0,t=_>=w.length;if(E.push({stride:[a.length,f0?0:b,t?0:b],input_features:r.input_features,is_last:t}),t)break;l+=g}}else E=[{stride:[w.length,0,0],input_features:(await this.processor(w)).input_features,is_last:!0}];for(let x of E){q.num_frames=Math.floor(x.stride[0]/P);let b=await this.model.generate({inputs:x.input_features,...q});if(G==="word"){let g=b.sequences.tolist()[0],l=b.token_timestamps.tolist()[0],_=this.tokenizer.timestamp_begin,a=Math.max(g.findIndex((r)=>Number(r)>=_),0);x.tokens=g.slice(a),x.token_timestamps=l.slice(a).map((r)=>SF(r,2))}else x.tokens=b[0].tolist();x.stride=x.stride.map((g)=>g/N)}let[T,y]=this.tokenizer._decode_asr(E,{time_precision:O,return_timestamps:G,force_full_sequences:K});R.push({text:T,...y})}return F?R[0]:R}async _call_moonshine(Q,J){let G=!Array.isArray(Q),H=G?[Q]:Q,K=this.processor.feature_extractor.config.sampling_rate,z=await OV(H,K),q=[];for(let F of z){let D=await this.processor(F),V=Math.floor(F.length/K)*6,O=await this.model.generate({max_new_tokens:V,...J,...D}),P=this.processor.batch_decode(O,{skip_special_tokens:!0})[0];q.push({text:P})}return G?q[0]:q}async _call_cohere_asr(Q,J){let G=!Array.isArray(Q),H=G?[Q]:Q,K=this.processor.feature_extractor,z=K.config.sampling_rate,q=await OV(H,z),F=J.language??"en",D=this.processor.get_decoder_prompt_ids(F),V=[];for(let O of q){let P=K.split_audio(O),N=[];for(let R of P){let w=await this.processor(R),E=await this.model.generate({...w,decoder_input_ids:D,...J}),T=this.tokenizer.decode(E[0].tolist(),{skip_special_tokens:!0}).trim();N.push(T)}let I=this.processor.constructor.join_chunks(N,F);V.push({text:I})}return G?V[0]:V}},yCQ=class extends W7{DEFAULT_VOCODER_ID="Xenova/speecht5_hifigan";constructor(Q){super(Q);this.vocoder=Q.vocoder??null}async _prepare_speaker_embeddings(Q,J){if(typeof Q==="string"||Q instanceof URL)Q=new Float32Array(await(await A6.fetch(Q)).arrayBuffer());if(Q instanceof Float32Array)Q=new PQ("float32",Q,[Q.length]);else if(!(Q instanceof PQ))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(J>1){if(Q.dims[0]===1)Q=Q.repeat(J,1);else if(Q.dims[0]!==J)throw Error(`Expected speaker embeddings batch size to be 1 or ${J}, but got ${Q.dims[0]}.`)}return Q}_postprocess_waveform(Q,J,G,H=null){let K=J.data,[z,q]=J.dims,F=H?H.data:null,D=[];for(let V=0;V<z;++V){let O=F?Math.min(Math.ceil(F[V]),q):q,P=V*q;D.push(new RUQ(K.slice(P,P+O),G))}return Array.isArray(Q)?D:D[0]}async _call(Q,J){if(this.processor)return this._call_text_to_spectrogram(Q,J);else if(this.model.config.model_type==="supertonic")return this._call_supertonic(Q,J);else return this._call_text_to_waveform(Q)}async _call_supertonic(Q,{speaker_embeddings:J,num_inference_steps:G,speed:H}){if(!J)throw Error("Speaker embeddings must be provided for Supertonic models.");let{sampling_rate:K,style_dim:z}=this.model.config,q=this.tokenizer(Q,{padding:!0,truncation:!0}),F=q.input_ids.dims[0];J=await this._prepare_speaker_embeddings(J,F),J=J.view(F,-1,z);let{waveform:D,durations:V}=await this.model.generate_speech({...q,style:J,num_inference_steps:G,speed:H});return this._postprocess_waveform(Q,D,K,V)}async _call_text_to_waveform(Q){let J=this.tokenizer(Q,{padding:!0,truncation:!0}),{waveform:G}=await this.model(J),H=this.model.config.sampling_rate;return this._postprocess_waveform(Q,G,H)}async _call_text_to_spectrogram(Q,{speaker_embeddings:J}){if(!this.vocoder)g8.info("No vocoder specified, using default HifiGan vocoder."),this.vocoder=await kF.from_pretrained(this.DEFAULT_VOCODER_ID,{dtype:"fp32"});let{input_ids:G}=this.tokenizer(Q,{padding:!0,truncation:!0}),H=G.dims[0];J=await this._prepare_speaker_embeddings(J,H),J=J.view(H,-1);let{waveform:K}=await this.model.generate_speech(G,J,{vocoder:this.vocoder}),z=this.processor.feature_extractor.config.sampling_rate;return this._postprocess_waveform(Q,K,z)}},vCQ=class extends W7{async _call(Q,J={}){let G=Array.isArray(Q),H=await uG(Q),{pixel_values:K}=await this.processor(H),z=[];for(let q of K){q.dims=[1,...q.dims];let F=await this.model.generate({inputs:q,...J}),D=this.tokenizer.batch_decode(F,{skip_special_tokens:!0}).map((V)=>({generated_text:V.trim()}));z.push(D)}return G?z:z[0]}},xCQ=class extends W7{async _call(Q,{top_k:J=5}={}){let G=await uG(Q),{pixel_values:H}=await this.processor(G),K=await this.model({pixel_values:H}),{id2label:z}=this.model.config,q=[];for(let F of K.logits){let D=await SV(new PQ("float32",wX(F.data),F.dims),J),V=D[0].tolist(),P=D[1].tolist().map((N,I)=>({label:z?z[N]:`LABEL_${N}`,score:V[I]}));q.push(P)}return Array.isArray(Q)?q:q[0]}},xI0={panoptic:"post_process_panoptic_segmentation",instance:"post_process_instance_segmentation",semantic:"post_process_semantic_segmentation"},HS0=class extends W7{async _call(Q,{threshold:J=0.5,mask_threshold:G=0.5,overlap_mask_area_threshold:H=0.8,label_ids_to_fuse:K=null,target_sizes:z=null,subtask:q=null}={}){if(Array.isArray(Q)&&Q.length!==1)throw Error("Image segmentation pipeline currently only supports a batch size of 1.");let D=await uG(Q),V=D.map((T)=>[T.height,T.width]),O=await this.processor(D),{inputNames:P,outputNames:N}=this.model.sessions.model;if(!P.includes("pixel_values")){if(P.length!==1)throw Error(`Expected a single input name, but got ${P.length} inputs: ${P}.`);let T=P[0];if(T in O)throw Error(`Input name ${T} already exists in the inputs.`);O[T]=O.pixel_values}let I=await this.model(O),R=null;if(q!==null)R=xI0[q];else if(this.processor.image_processor){for(let[T,y]of Object.entries(xI0))if(y in this.processor.image_processor){R=this.processor.image_processor[y].bind(this.processor.image_processor),q=T;break}}let w=this.model.config.id2label,E=[];if(!q){let y=I[N[0]];for(let x=0;x<V.length;++x){let b=V[x],g=y[x];if(g.data.some((_)=>_<-0.00001||_>1.00001))g.sigmoid_();let l=await gG.fromTensor(g.mul_(255).to("uint8")).resize(b[1],b[0]);E.push({label:null,score:null,mask:l})}}else if(q==="panoptic"||q==="instance"){let T=R(I,J,G,H,K,z??V)[0],y=T.segmentation;for(let x of T.segments_info){let b=new Uint8ClampedArray(y.data.length);for(let l=0;l<y.data.length;++l)if(y.data[l]===x.id)b[l]=255;let g=new gG(b,y.dims[1],y.dims[0],1);E.push({score:x.score,label:w[x.label_id],mask:g})}}else if(q==="semantic"){let{segmentation:T,labels:y}=R(I,z??V)[0];for(let x of y){let b=new Uint8ClampedArray(T.data.length);for(let l=0;l<T.data.length;++l)if(T.data[l]===x)b[l]=255;let g=new gG(b,T.dims[1],T.dims[0],1);E.push({score:null,label:w[x],mask:g})}}else throw Error(`Subtask ${q} not supported.`);return E}},bCQ=class extends HS0{async _call(Q,J={}){let G=await uG(Q),H=await super._call(Q,J),K=G.map((z,q)=>{let F=z.clone();return F.putAlpha(H[q].mask),F});return Array.isArray(Q)?K:K[0]}},gCQ=class extends W7{async _call(Q,J,{hypothesis_template:G="This is a photo of {}"}={}){let H=Array.isArray(Q),K=await uG(Q),z=J.map((P)=>G.replace("{}",P)),q=this.tokenizer(z,{padding:this.model.config.model_type==="siglip"?"max_length":!0,truncation:!0}),{pixel_values:F}=await this.processor(K),D=await this.model({...q,pixel_values:F}),V=this.model.config.model_type==="siglip"?(P)=>P.sigmoid().data:(P)=>wX(P.data),O=[];for(let P of D.logits_per_image){let I=[...V(P)].map((R,w)=>({score:R,label:J[w]}));I.sort((R,w)=>w.score-R.score),O.push(I)}return H?O:O[0]}},hCQ=class extends W7{async _call(Q,{threshold:J=0.9,percentage:G=!1}={}){let H=Array.isArray(Q);if(H&&Q.length!==1)throw Error("Object detection pipeline currently only supports a batch size of 1.");let K=await uG(Q),z=G?null:K.map((N)=>[N.height,N.width]),{pixel_values:q,pixel_mask:F}=await this.processor(K),D=await this.model({pixel_values:q,pixel_mask:F}),V=this.processor.image_processor.post_process_object_detection(D,J,z),{id2label:O}=this.model.config,P=V.map((N)=>N.boxes.map((I,R)=>({score:N.scores[R],label:O[N.classes[R]],box:D90(I,!G)})));return H?P:P[0]}},_CQ=class extends W7{async _call(Q,J,{threshold:G=0.1,top_k:H=null,percentage:K=!1}={}){let z=Array.isArray(Q),q=await uG(Q),F=this.tokenizer(J,{padding:!0,truncation:!0}),D=await this.processor(q),V=[];for(let O=0;O<q.length;++O){let P=q[O],N=K?null:[[P.height,P.width]],I=D.pixel_values[O].unsqueeze_(0),R=await this.model({...F,pixel_values:I}),w;if("post_process_grounded_object_detection"in this.processor){let E=this.processor.post_process_grounded_object_detection(R,F.input_ids,{box_threshold:G,text_threshold:G,target_sizes:N})[0];w=E.boxes.map((T,y)=>({score:E.scores[y],label:E.labels[y],box:D90(T,!K)}))}else{let E=this.processor.image_processor.post_process_object_detection(R,G,N,!0)[0];w=E.boxes.map((T,y)=>({score:E.scores[y],label:J[E.classes[y]],box:D90(T,!K)}))}if(w.sort((E,T)=>T.score-E.score),H!==null)w=w.slice(0,H);V.push(w)}return z?V:V[0]}},fCQ=class extends W7{_default_generation_config={max_new_tokens:256};async _call(Q,J,G={}){if(Array.isArray(Q)){if(Q.length!==1)throw Error("Document Question Answering pipeline currently only supports a batch size of 1.");Q=Q[0]}let H=(await uG(Q))[0],{pixel_values:K}=await this.processor(H),z=`<s_docvqa><s_question>${J}</s_question><s_answer>`,q=this.tokenizer(z,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,F=await this.model.generate({inputs:K,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:q,...this._default_generation_config,...G}),V=this.tokenizer.batch_decode(F)[0].match(/<s_answer>(.*?)<\/s_answer>/),O=null;if(V&&V.length>=2)O=V[1].trim();return[{answer:O}]}},mCQ=class extends W7{async _call(Q){let J=await uG(Q),G=await this.processor(J),H=await this.model(G),K=[];for(let z of H.reconstruction){let q=z.squeeze().clamp_(0,1).mul_(255).round_().to("uint8");K.push(gG.fromTensor(q))}return Array.isArray(Q)?K:K[0]}},uCQ=class extends W7{async _call(Q){let J=await uG(Q),G=await this.processor(J),{predicted_depth:H}=await this.model(G),K=[];for(let z=0;z<J.length;++z){let q=H[z],[F,D]=q.dims.slice(-2),[V,O]=J[z].size,P=(await bG(q.view(1,1,F,D),{size:[O,V],mode:"bilinear"})).view(O,V),N=P.min().item(),I=P.max().item(),R=P.sub(N).div_(I-N).mul_(255).to("uint8").unsqueeze(0),w=gG.fromTensor(R);K.push({predicted_depth:P,depth:w})}return Array.isArray(Q)?K:K[0]}},pCQ=class extends W7{async _call(Q,{pooling:J="none",normalize:G=!1,quantize:H=!1,precision:K="binary"}={}){let z=this.tokenizer(Q,{padding:!0,truncation:!0}),q=await this.model(z),F=q.last_hidden_state??q.logits??q.token_embeddings;switch(J){case"none":break;case"mean":F=qqQ(F,z.attention_mask);break;case"first_token":case"cls":F=F.slice(null,0);break;case"last_token":case"eos":F=F.slice(null,-1);break;default:throw Error(`Pooling method '${J}' not supported.`)}if(G)F=F.normalize(2,-1);if(H)F=ZqQ(F,K);return F}},lCQ=class extends W7{async _call(Q,{pool:J=null}={}){let G=await uG(Q),{pixel_values:H}=await this.processor(G),K=await this.model({pixel_values:H}),z;if(J){if(!("pooler_output"in K))throw Error("No pooled output was returned. Make sure the model has a 'pooler' layer when using the 'pool' option.");z=K.pooler_output}else z=K.last_hidden_state??K.logits??K.image_embeds;return z}},jR=Object.freeze({"text-classification":{pipeline:LCQ,model:SI0,default:{model:"Xenova/distilbert-base-uncased-finetuned-sst-2-english"},type:"text"},"token-classification":{pipeline:OCQ,model:JCQ,default:{model:"Xenova/bert-base-multilingual-cased-ner-hrl"},type:"text"},"question-answering":{pipeline:jCQ,model:ACQ,default:{model:"Xenova/distilbert-base-cased-distilled-squad"},type:"text"},"fill-mask":{pipeline:CCQ,model:BCQ,default:{model:"onnx-community/ettin-encoder-32m-ONNX",dtype:"fp32"},type:"text"},summarization:{pipeline:ICQ,model:X90,default:{model:"Xenova/distilbart-cnn-6-6"},type:"text"},translation:{pipeline:RCQ,model:X90,default:{model:"Xenova/t5-small"},type:"text"},"text2text-generation":{pipeline:KX0,model:X90,default:{model:"Xenova/flan-t5-small"},type:"text"},"text-generation":{pipeline:wCQ,model:HCQ,default:{model:"onnx-community/Qwen3-0.6B-ONNX",dtype:"q4"},type:"text"},"zero-shot-classification":{pipeline:ECQ,model:SI0,default:{model:"Xenova/distilbert-base-uncased-mnli"},type:"text"},"audio-classification":{pipeline:SCQ,model:$CQ,default:{model:"Xenova/wav2vec2-base-superb-ks"},type:"audio"},"zero-shot-audio-classification":{pipeline:TCQ,model:kF,default:{model:"Xenova/clap-htsat-unfused"},type:"multimodal"},"automatic-speech-recognition":{pipeline:kCQ,model:[YCQ,UCQ],default:{model:"Xenova/whisper-tiny.en"},type:"multimodal"},"text-to-audio":{pipeline:yCQ,model:[WCQ,GCQ],default:{model:"onnx-community/Supertonic-TTS-ONNX",dtype:"fp32"},type:"text"},"image-to-text":{pipeline:vCQ,model:KCQ,default:{model:"Xenova/vit-gpt2-image-captioning"},type:"multimodal"},"image-classification":{pipeline:xCQ,model:zCQ,default:{model:"Xenova/vit-base-patch16-224"},type:"multimodal"},"image-segmentation":{pipeline:HS0,model:[TI0,kI0,yI0],default:{model:"Xenova/detr-resnet-50-panoptic"},type:"multimodal"},"background-removal":{pipeline:bCQ,model:[TI0,kI0,yI0],default:{model:"Xenova/modnet"},type:"image"},"zero-shot-image-classification":{pipeline:gCQ,model:kF,default:{model:"Xenova/clip-vit-base-patch32"},type:"multimodal"},"object-detection":{pipeline:hCQ,model:VCQ,default:{model:"Xenova/detr-resnet-50"},type:"multimodal"},"zero-shot-object-detection":{pipeline:_CQ,model:qCQ,default:{model:"Xenova/owlvit-base-patch32"},type:"multimodal"},"document-question-answering":{pipeline:fCQ,model:ZCQ,default:{model:"Xenova/donut-base-finetuned-docvqa"},type:"multimodal"},"image-to-image":{pipeline:mCQ,model:FCQ,default:{model:"Xenova/swin2SR-classical-sr-x2-64"},type:"image"},"depth-estimation":{pipeline:uCQ,model:DCQ,default:{model:"onnx-community/depth-anything-v2-small"},type:"image"},"feature-extraction":{pipeline:pCQ,model:kF,default:{model:"onnx-community/all-MiniLM-L6-v2-ONNX",dtype:"fp32"},type:"text"},"image-feature-extraction":{pipeline:lCQ,model:[MCQ,kF],default:{model:"onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX",dtype:"fp32"},type:"image"}}),BS0=Object.freeze({"sentiment-analysis":"text-classification",ner:"token-classification",asr:"automatic-speech-recognition","text-to-speech":"text-to-audio",embeddings:"feature-extraction"});async function dCQ(Q){if(!Q)throw Error("modelId is required");return(await uF(Q,hF,{})).exists?[hF]:[]}async function cCQ(Q,{config:J=null,dtype:G=null,device:H=null,model_file_name:K=null,include_tokenizer:z=!0,include_processor:q=!0}={}){let F=await G20(Q,{config:J,dtype:G,device:H,model_file_name:K});if(z){let D=await Bw0(Q);F.push(...D)}if(q){let D=await dCQ(Q);F.push(...D)}return F}async function iCQ(Q,J,G={}){Q=BS0[Q]??Q;let H=jR[Q];if(!H)throw Error(`Unsupported pipeline task: ${Q}. Must be one of [${Object.keys(jR).join(", ")}]`);let{type:K}=H,F=await cCQ(J,{...G,include_tokenizer:K!=="audio"&&K!=="image",include_processor:K!=="text"});if(Q==="text-generation"){let D=await Y20(J,G),V=J20(D),O=XFQ(V);if(O){let P=Object.values(O).map((N)=>`onnx/${N}`);return F.filter((N)=>!N.startsWith("onnx/")||P.some((I)=>N.startsWith(I)))}}return F}async function zX0(Q,J=null,{progress_callback:G=null,config:H=null,cache_dir:K=null,local_files_only:z=!1,revision:q="main",device:F=null,dtype:D=null,subfolder:V="onnx",use_external_data_format:O=null,model_file_name:P=null,session_options:N={}}={}){Q=BS0[Q]??Q;let I=jR[Q.split("_",1)[0]];if(!I)throw Error(`Unsupported pipeline: ${Q}. Must be one of [${Object.keys(jR)}]`);if(!J){if(J=I.default.model,g8.info(`No model specified. Using default model: "${J}".`),!D&&I.default.dtype)D=I.default.dtype}let R=await iCQ(Q,J,{device:F,dtype:D}),w={};if(G)(await Promise.all(R.map(async(t)=>uF(J,t)))).forEach((t,p0)=>{if(t.exists)w[R[p0]]={loaded:0,total:t.size??0}});let E={progress_callback:G?new J90(G,w):void 0,config:H,cache_dir:K,local_files_only:z,revision:q,device:F,dtype:D,subfolder:V,use_external_data_format:O,model_file_name:P,session_options:N},T=R.includes("tokenizer.json"),y=R.includes("preprocessor_config.json"),x=I.model,b;if(Array.isArray(x)){let f0=H??await _F.from_pretrained(J,E),{model_type:t}=f0,p0=x.find((u0)=>u0.supports(t));if(!p0)throw Error(`Unsupported model type "${t}" for task "${Q}". None of the candidate model classes support this type.`);b=p0.from_pretrained(J,{...E,config:f0})}else b=x.from_pretrained(J,E);let[g,l,_]=await Promise.all([T?m6.from_pretrained(J,E):null,y?EZQ.from_pretrained(J,E):null,b]),a={task:Q,model:_};if(g)a.tokenizer=g;if(l)a.processor=l;return UH(G,{status:"ready",task:Q,model:J}),new I.pipeline(a)}var pz8=Y6.IS_PROCESS_AVAILABLE?(Q)=>process.stdout.write(Q):(Q)=>console.log(Q);var lz8=Object.keys(LR);/*! Bundled license information:
onnxruntime-web/dist/ort.webgpu.bundle.min.mjs:
(*!
* ONNX Runtime Web v1.26.0-dev.20260416-b7804b056c
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*)
*/var oCQ="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.26.0/dist/",AS0=!1,KS0=!1;function zS0(Q){if(Q.backends?.onnx?.wasm)Q.backends.onnx.wasm.wasmPaths=oCQ;else SQ.warn("onnxEnv: expected WASM backend shape not found — CDN paths not configured");if(typeof navigator<"u")Q.useBrowserCache=!0}function VX0(){if(AS0)return;AS0=!0;let Q=A6;if(zS0(Q),Q.backends?.onnx?.wasm)Q.backends.onnx.wasm.numThreads=1}function VS0(){if(KS0)return;KS0=!0,zS0(A6)}class qS0{opts;pipeline=null;loadPromise=null;cache=new Map;idleTimer=null;constructor(Q){this.opts=Q}isLoaded(){return this.pipeline!==null}async embed(Q){this.touchIdle();let J=this.cache.get(Q);if(J)return this.cache.delete(Q),this.cache.set(Q,J),J;let G=(async()=>{let K=await(await this.ensurePipeline())(Q,{pooling:"mean",normalize:!0,truncation:!0,max_length:this.opts.maxInputTokens});return new Float32Array(K.data)})();return this.cacheSet(Q,G),G}async embedBatch(Q){if(this.touchIdle(),Q.length===0)return[];let J=Array(Q.length),G=new Map;Q.forEach((K,z)=>{let q=this.cache.get(K);if(q)J[z]=q;else{let F=G.get(K);if(F)F.push(z);else G.set(K,[z])}});let H=Array.from(G.entries());for(let K=0;K<H.length;K+=8){let z=H.slice(K,K+8),q=z.map(([D])=>D),F=(async()=>{let V=await(await this.ensurePipeline())(q,{pooling:"mean",normalize:!0,truncation:!0,max_length:this.opts.maxInputTokens}),O=V.dims?.length===2&&typeof V.dims[1]==="number"?V.dims[1]:V.data.length/q.length;if(!Number.isInteger(O))throw Error(`embedBatch: cannot infer row stride (data ${V.data.length}, batch ${q.length})`);return q.map((P,N)=>new Float32Array(V.data.subarray(N*O,(N+1)*O)))})();z.forEach(([,D],V)=>{let O=F.then((P)=>{let N=P[V];if(!N)throw Error("embedBatch: missing row in batch result");return N});for(let P of D)J[P]=O})}return Promise.all(J)}async unload(){if(this.pipeline=null,this.loadPromise=null,this.cache.clear(),this.idleTimer)window.clearTimeout(this.idleTimer),this.idleTimer=null}async ensurePipeline(){if(this.pipeline)return this.pipeline;if(!this.loadPromise){let Q=this.opts.model??"Xenova/all-MiniLM-L6-v2";this.loadPromise=this.opts.pipelineFactory(Q).then((J)=>{return this.pipeline=J,J})}return this.loadPromise}cacheSet(Q,J){let G=this.opts.cacheSize??32;if(this.cache.size>=G){let H=this.cache.keys().next().value;if(H!==void 0)this.cache.delete(H)}this.cache.set(Q,J)}touchIdle(){if(this.opts.unloadWhenIdle!==!0)return;if(this.idleTimer)window.clearTimeout(this.idleTimer);this.idleTimer=window.setTimeout(()=>{this.pipeline=null,this.loadPromise=null,this.idleTimer=null},this.opts.idleMs??60000)}}function US0(Q){return new qS0(Q)}var qX0=null;function UX0(Q=typeof navigator<"u"?navigator:void 0){if(!qX0)qX0=(async()=>{let J=await nCQ(Q);return SQ.info("semantic-search: backend resolved",{backend:J}),J})();return qX0}async function nCQ(Q){if(!Q?.gpu)return VX0(),"wasm";try{if(await Q.gpu.requestAdapter()!==null)return VS0(),"webgpu"}catch{}return VX0(),"wasm"}async function tR(Q,J,G){if(await UX0()==="webgpu")return await zX0("feature-extraction",Q,{device:"webgpu",progress_callback:J});return await zX0("feature-extraction",Q,{device:"cpu",progress_callback:J,...G?.dtype!==void 0?{dtype:G.dtype}:{}})}var $S0=256;class ZS0{embedder;providerKey="native-minilm-l6-v2";dimensions=384;maxInputTokens=256;constructor(Q){this.embedder=Q}getMaxInputTokens(){return Promise.resolve(256)}getModelSizeBytes(){return 25000000}async isAvailable(){return!0}async embed(Q,J){return this.embedder.embedBatch(Q)}}function FS0(Q){return new ZS0(Q)}var UB=4,aCQ=384;class DS0{opts;records=new Map;fileIndex=new Map;dirty=!1;fileMtimes=new Map;mtimeDirty=!1;initialized=!1;vectorDim;sentinelPath;mtimesPath;metaPath;constructor(Q){this.opts=Q;this.vectorDim=Q.vectorDim??aCQ,this.sentinelPath=`${Q.indexPath}.writing`;let J=Q.indexPath.split("/").slice(0,-1).join("/");this.mtimesPath=J?`${J}/mtimes.json`:"mtimes.json",this.metaPath=J?`${J}/embeddings.meta.json`:"embeddings.meta.json"}async probe(){if(await this.opts.adapter.exists(this.sentinelPath))return null;try{if(await this.opts.adapter.exists(this.metaPath)){let Q=JSON.parse(await this.opts.adapter.read(this.metaPath));if(typeof Q.version==="number"&&typeof Q.recordCount==="number")return{version:Q.version,recordCount:Q.recordCount}}}catch{}try{if(!await this.opts.adapter.exists(this.opts.indexPath))return null;let Q=JSON.parse(await this.opts.adapter.read(this.opts.indexPath));if(typeof Q.version!=="number")return null;return{version:Q.version,recordCount:Q.records?.length??0}}catch{return null}}async init(){if(this.initialized)return;if(await this.opts.adapter.exists(this.sentinelPath)){SQ.warn("embedding store was mid-write, discarding and rebuilding"),await this.removeSentinel(),this.initialized=!0,this.dirty=!0,this.fileMtimes.clear(),this.mtimeDirty=!0;return}if(!await this.opts.adapter.exists(this.opts.indexPath)){this.initialized=!0,this.dirty=!1;return}let J;try{let q=await this.opts.adapter.read(this.opts.indexPath);J=JSON.parse(q)}catch(q){SQ.warn("embedding index unreadable, starting fresh",{error:q instanceof Error?q.message:String(q)}),this.initialized=!0,this.dirty=!0;return}if(J.version!==UB){SQ.warn("embedding index format version mismatch, re-indexing",{expected:UB,found:J.version}),this.initialized=!0,this.dirty=!0;return}if(!await this.opts.adapter.exists(this.opts.binPath)||J.records.length===0){this.initialized=!0,this.dirty=!1;return}let H=await this.opts.adapter.readBinary(this.opts.binPath),K=new Float32Array(H),z=!1;for(let q of J.records){if(q.byteOffset<0||q.byteLength<0||q.byteOffset%4!==0||q.byteLength%4!==0||q.byteOffset+q.byteLength>H.byteLength){SQ.warn("embedding record out of bounds, skipping",{chunkId:q.chunkId,byteOffset:q.byteOffset,byteLength:q.byteLength,bufByteLength:H.byteLength}),z=!0;continue}let F=q.byteOffset/4,D=q.byteLength/4,V=new Float32Array(K.subarray(F,F+D));this.records.set(q.chunkId,{chunkId:q.chunkId,filePath:q.filePath,offset:q.offset,heading:q.heading,contentHash:q.contentHash,vector:V});let O=this.fileIndex.get(q.filePath);if(!O)O=new Set,this.fileIndex.set(q.filePath,O);O.add(q.chunkId)}this.initialized=!0,this.dirty=z,await this.loadMtimes()}async loadMtimes(){try{if(!await this.opts.adapter.exists(this.mtimesPath))return;let Q=JSON.parse(await this.opts.adapter.read(this.mtimesPath));for(let[J,G]of Object.entries(Q))if(typeof G==="number")this.fileMtimes.set(J,G)}catch(Q){SQ.warn("mtimes sidecar unreadable, ignoring",{error:Q instanceof Error?Q.message:String(Q)})}}size(){return this.records.size}hasRecords(Q){let J=this.fileIndex.get(Q);return J!==void 0&&J.size>0}mtimeFor(Q){return this.fileMtimes.get(Q)}setMtime(Q,J){if(this.fileMtimes.get(Q)===J)return;this.fileMtimes.set(Q,J),this.mtimeDirty=!0}async upsert(Q){if(!this.initialized)await this.init();for(let J of Q){if(J.vector.length!==this.vectorDim)throw Error(`embedding dim mismatch: chunkId=${J.chunkId} expected ${this.vectorDim} got ${J.vector.length}`);let G=this.records.get(J.chunkId);if(G&&G.filePath!==J.filePath){let K=this.fileIndex.get(G.filePath);if(K){if(K.delete(J.chunkId),K.size===0)this.fileIndex.delete(G.filePath)}}this.records.set(J.chunkId,J);let H=this.fileIndex.get(J.filePath);if(!H)H=new Set,this.fileIndex.set(J.filePath,H);H.add(J.chunkId)}this.dirty=!0}async delete(Q){if(!this.initialized)await this.init();if(this.fileMtimes.delete(Q))this.mtimeDirty=!0;let J=this.fileIndex.get(Q);if(!J||J.size===0)return;for(let G of J)this.records.delete(G);this.fileIndex.delete(Q),this.dirty=!0}recordsFor(Q){let J=this.fileIndex.get(Q);if(!J)return[];let G=[];for(let H of J){let K=this.records.get(H);if(K)G.push(K)}return G}async*scan(){if(!this.initialized)await this.init();for(let Q of this.records.values())yield Q}async flush(){if(!this.dirty){if(this.mtimeDirty)await this.flushMtimes();return}let Q=this.opts.binPath.split("/").slice(0,-1).join("/");if(Q)await this.opts.adapter.mkdir(Q);let J=Array.from(this.records.values()),G=0;for(let D of J)G+=D.vector.length;let H=new Float32Array(G),K=[],z=0;for(let D of J){let V=z*4,O=D.vector.length*4;H.set(D.vector,z),z+=D.vector.length,K.push({chunkId:D.chunkId,filePath:D.filePath,offset:D.offset,heading:D.heading,contentHash:D.contentHash,byteOffset:V,byteLength:O})}let q=H.buffer.slice(H.byteOffset,H.byteOffset+H.byteLength);await this.opts.adapter.write(this.sentinelPath,"1"),await this.opts.adapter.writeBinary(this.opts.binPath,q);let F={version:UB,records:K};if(await this.opts.adapter.write(this.opts.indexPath,JSON.stringify(F)),this.mtimeDirty)await this.flushMtimes();await this.opts.adapter.write(this.metaPath,JSON.stringify({version:UB,recordCount:this.records.size})),await this.removeSentinel(),this.dirty=!1}async flushMtimes(){let Q=this.mtimesPath.split("/").slice(0,-1).join("/");if(Q)await this.opts.adapter.mkdir(Q);await this.opts.adapter.write(this.mtimesPath,JSON.stringify(Object.fromEntries(this.fileMtimes))),this.mtimeDirty=!1}async removeSentinel(){try{if(await this.opts.adapter.exists(this.sentinelPath))await this.opts.adapter.remove(this.sentinelPath)}catch(Q){SQ.warn("could not remove embedding store sentinel",{error:Q instanceof Error?Q.message:String(Q)})}}async close(){await this.flush(),this.records.clear(),this.fileIndex.clear(),this.fileMtimes.clear(),this.dirty=!1,this.mtimeDirty=!1,this.initialized=!1}}function MS0(Q){return new DS0(Q)}class LS0{adapter;baseDir;stores=new Map;ready=new Set;constructor(Q,J){this.adapter=Q;this.baseDir=J}storeFor(Q,J){let G=this.stores.get(Q);if(G)return G;let H=MS0({adapter:this.adapter,binPath:`${this.baseDir}/${Q}/embeddings.bin`,indexPath:`${this.baseDir}/${Q}/embeddings.index.json`,vectorDim:J});return this.stores.set(Q,H),H}markReady(Q){this.ready.add(Q)}isReady(Q){return this.ready.has(Q)}async close(Q){let J=this.stores.get(Q);if(!J)return;await J.close(),this.stores.delete(Q),this.ready.delete(Q)}async closeAll(){let Q=Array.from(this.stores.keys());await Promise.all(Q.map((J)=>this.close(J)))}}function OS0(Q,J){return new LS0(Q,J)}async function PS0(Q,J){let G=`${J}/embeddings.bin`;try{if(!await Q.exists(G))return;let H=`${J}/embeddings.index.json`,K=`${J}/embeddings/native-minilm-l6-v2`,z=`${K}/.migrating`;if(await Q.exists(z))return;let q=await Q.readBinary(G);if(await Q.mkdir(K),await Q.write(z,""),await Q.writeBinary(`${K}/embeddings.bin`,q),await Q.remove(G),await Q.exists(H)){let F=await Q.read(H);await Q.write(`${K}/embeddings.index.json`,F),await Q.remove(H)}await Q.remove(z),SQ.info("semantic-search: v1 flat store migrated to per-provider directory",{pluginDir:J})}catch(H){SQ.warn("v1 flat store migration failed; store will be re-indexed",{pluginDir:J,error:H instanceof Error?H.message:String(H)})}}var sCQ=8;class NS0{opts;providerKey;dimensions;maxInputTokens;pipeline=null;loadPromise=null;resolvedMaxTokens=null;constructor(Q){this.opts=Q;this.providerKey=Q.providerKey,this.dimensions=Q.dimensions,this.maxInputTokens=Q.maxInputTokensByBackend.wasm}getMaxInputTokens(){if(!this.resolvedMaxTokens)this.resolvedMaxTokens=UX0().then((Q)=>this.opts.maxInputTokensByBackend[Q]);return this.resolvedMaxTokens}getModelSizeBytes(){return this.opts.modelSizeBytes}async isAvailable(){return!0}async embed(Q,J){if(Q.length===0)return[];let G=await this.ensurePipeline(),H=await this.getMaxInputTokens(),K=this.opts.batchSize??sCQ,z=[];for(let q=0;q<Q.length;q+=K){let F=Q.slice(q,q+K).map((O)=>this.opts.taskPrompt(O,J)),D=await G(F,{pooling:"mean",normalize:!0,truncation:!0,max_length:H}),V=D.dims?.length===2&&typeof D.dims[1]==="number"?D.dims[1]:this.opts.dimensions;for(let O=0;O<F.length;O++)z.push(new Float32Array(D.data.subarray(O*V,(O+1)*V)))}return z}async ensurePipeline(){if(this.pipeline)return this.pipeline;if(!this.loadPromise)this.loadPromise=this.opts.pipelineFactory(this.opts.modelId).then((Q)=>{return this.pipeline=Q,Q}).catch((Q)=>{throw this.loadPromise=null,Q});return this.loadPromise}}function eR(Q){return new NS0(Q)}function jS0(Q){return eR({modelId:"onnx-community/embeddinggemma-300m-ONNX",providerKey:"embedding-gemma-300m",dimensions:768,maxInputTokensByBackend:{wasm:512,webgpu:2048},modelSizeBytes:190000000,taskPrompt:(J,G)=>G==="query"?"task: search result | query: "+J:"title: none | text: "+J,pipelineFactory:Q,batchSize:4})}function CS0(Q){return eR({modelId:"Xenova/multilingual-e5-base",providerKey:"multilingual-e5-base",dimensions:768,maxInputTokensByBackend:{wasm:512,webgpu:512},modelSizeBytes:60000000,taskPrompt:(J,G)=>(G==="query"?"query: ":"passage: ")+J,pipelineFactory:Q})}async function IS0(Q,J=50){let G=Q.getMarkdownFiles().slice(0,J),H=0,K=0;for(let z of G){let q;try{q=await Q.read(z.path)}catch{continue}H+=q.length;for(let F=0;F<q.length;F++)if(q.charCodeAt(F)>127)K++}return H===0?0:K/H}var rCQ=512,tCQ=64,eCQ=20,QIQ=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;function Qw(Q){if(!Q)return 0;return Q.split(/\s+/).filter((J)=>J.length>0).length}async function dV(Q){let J=new TextEncoder().encode(Q),G=await crypto.subtle.digest("SHA-256",J),H=new Uint8Array(G),K="";for(let z=0;z<8;z++)K+=H[z].toString(16).padStart(2,"0");return K}function XIQ(Q){let J=Q.match(QIQ);if(!J)return{frontmatter:null,body:Q,bodyOffset:0};return{frontmatter:J[1]??"",body:Q.slice(J[0].length),bodyOffset:J[0].length}}function JIQ(Q,J){let G=Q.split(/(\r?\n)/),H=[],K={heading:null,text:"",offset:J},z=J;for(let q=0;q<G.length;q+=2){let F=G[q]??"",D=G[q+1]??"",V=F.trimEnd(),O=V.match(/^# (.+)$/),P=V.match(/^## (.+)$/),N=O?.[1]??P?.[1]??null;if(N!==null){if(K.text.length>0)H.push(K);K={heading:N,text:F+D,offset:z}}else K.text+=F+D;z+=F.length+D.length}if(K.text.length>0)H.push(K);return H}function YIQ(Q){let J=Q.text.split(/(\r?\n)/),G=[],H={heading:Q.heading,text:"",offset:Q.offset},K=Q.offset;for(let z=0;z<J.length;z+=2){let q=J[z]??"",F=J[z+1]??"",V=q.trimEnd().match(/^### (.+)$/);if(V!==null){if(H.text.length>0)G.push(H);H={heading:V[1]??null,text:q+F,offset:K}}else H.text+=q+F;K+=q.length+F.length}if(H.text.length>0)G.push(H);return G.length>1?G:[Q]}function GIQ(Q,J){let G=Q.split(`
`),H=!1,K=0;for(let z=0;z<G.length;z++)if((G[z]??"").startsWith("```"))if(!H)H=!0,K=z;else{let F=G.slice(K,z+1).join(`
`);if(Qw(F)>J)return!0;H=!1}return!1}function RS0(Q,J,G,H){let K="",z=Q;if(J!==null){let O=Q.indexOf(`
`);if(O!==-1)K=Q.slice(0,O+1),z=Q.slice(O+1)}let q=z.split(/(\s+)/),F=[];for(let O=0;O<q.length;O++)if((q[O]??"").trim().length>0)F.push(O);if(F.length<=G)return[K+z];let D=[],V=Math.max(1,G-H);for(let O=0;O<F.length;O+=V){let P=Math.min(O+G,F.length),N=F[O];if(N===void 0)break;let I=P>=F.length?q.length:F[P]??q.length,R=q.slice(N,I).join("");if(D.push(K+R),P>=F.length)break}return D}async function WIQ(Q,J,G,H,K){let z=Q.text.trimEnd(),q=Qw(z);if(q<H)return;if(q<=J){K.push({id:String(K.length),text:z,heading:Q.heading,offset:Q.offset,contentHash:await dV(z)});return}if(GIQ(z,J)){SQ.debug("embedding chunker: oversized code fence kept atomic",{heading:Q.heading,tokens:q}),K.push({id:String(K.length),text:z,heading:Q.heading,offset:Q.offset,contentHash:await dV(z)});return}let F=YIQ(Q);if(F.length>1){for(let V of F){let O=V.text.trimEnd(),P=Qw(O);if(P<H)continue;if(P<=J)K.push({id:String(K.length),text:O,heading:V.heading,offset:V.offset,contentHash:await dV(O)});else{let N=RS0(O,V.heading,J,G);for(let I of N)K.push({id:String(K.length),text:I,heading:V.heading,offset:V.offset,contentHash:await dV(I)})}}return}let D=RS0(z,Q.heading,J,G);for(let V of D)K.push({id:String(K.length),text:V,heading:Q.heading,offset:Q.offset,contentHash:await dV(V)})}function HIQ(Q){let G=Q.trimEnd().split(/(?<=[.!?])\s+/);return G[G.length-1]?.trim()??""}function $X0(Q){return async(J)=>{let G=await Q(J);return G.map((H,K)=>{if(K===0)return H;let z=G[K-1];if(z.id==="#frontmatter")return H;let q=HIQ(z.text);if(!q)return H;return{...H,text:q+`
`+H.text}})}}async function BIQ(Q,J={}){let G=J.maxTokens??rCQ,H=J.overlapTokens??tCQ,K=J.minTokens??eCQ,{frontmatter:z,body:q,bodyOffset:F}=XIQ(Q),D=null;if(z!==null){let P=z.trim();if(Qw(P)>=K)D={id:"#frontmatter",text:P,heading:null,offset:0,contentHash:await dV(P)}}let V=JIQ(q,F),O=[];for(let P of V)await WIQ(P,G,H,K,O);return D?[D,...O]:O}var AIQ=16,KIQ=64;function ZX0(Q){let J=!1;return async(G)=>{let H=await Q.getMaxInputTokens(),K=Math.max(KIQ,H-AIQ);if(!J)J=!0,SQ.info("semantic-search: chunker bound to provider",{providerKey:Q.providerKey,maxInputTokens:H,chunkMaxTokens:K});return BIQ(G,{maxTokens:K})}}var zIQ=2000,VIQ=5000;class wS0{timers=new Map;inFlight=new Map;unsubs=[];running=!1;flushTimer=null;flushInFlight=null;debounceMs;flushDebounceMs;opts;constructor(Q){this.debounceMs=Q.debounceMs??zIQ,this.flushDebounceMs=Q.flushDebounceMs??VIQ,this.opts={...Q,chunker:$X0(Q.chunker)}}async start(Q={}){if(this.running)return;if(this.running=!0,await this.opts.store.init(),this.unsubs.push(this.opts.vault.on("modify",(J)=>this.schedule(J)),this.opts.vault.on("create",(J)=>this.schedule(J)),this.opts.vault.on("delete",(J)=>this.schedule(J))),Q.initialRebuild!==!1)await this.rebuildAll({force:!1})}async stop(){this.running=!1;for(let Q of this.timers.values())window.clearTimeout(Q);this.timers.clear();for(let Q of this.unsubs)Q();this.unsubs=[],await Promise.all(this.inFlight.values()),await this.drainFlush()}isExcluded(Q){return this.opts.isExcluded?.(Q)??!1}async rebuildAll(Q={}){let J=Q.force??!0;if(!await this.opts.embedder.isAvailable()){SQ.warn("live indexer: embedding provider not available, skipping rebuild");return}await this.opts.store.init();let G=this.opts.vault.getMarkdownFiles().filter((K)=>!this.isExcluded(K.path));SQ.info("live indexer: rebuildAll starting",{providerKey:this.opts.embedder.providerKey,fileCount:G.length,force:J});let H=0;for(let K of G){if(!J&&K.mtime!==void 0&&K.mtime===this.opts.store.mtimeFor(K.path)&&this.opts.store.hasRecords(K.path)){H++;continue}await this.processFile(K.path,K.mtime)}SQ.info("live indexer: rebuildAll finished",{providerKey:this.opts.embedder.providerKey,fileCount:G.length,skippedUnchanged:H})}async flush(){let Q=Array.from(this.timers.entries());for(let[,J]of Q)window.clearTimeout(J);this.timers.clear(),await Promise.all(Q.map(async([J])=>{await this.processFile(J)})),await Promise.all(this.inFlight.values()),await this.drainFlush()}pending(){return this.timers.size}schedule(Q){if(!this.running)return;if(this.isExcluded(Q))return;let J=this.timers.get(Q);if(J)window.clearTimeout(J);let G=window.setTimeout(()=>{this.timers.delete(Q),this.processFile(Q).catch((H)=>{SQ.error("live indexer: process failed",{path:Q,error:H instanceof Error?H.message:String(H)})})},this.debounceMs);this.timers.set(Q,G)}async processFile(Q,J){let G=this.inFlight.get(Q),H=(async()=>{if(G)await G.catch(()=>{});await this.doProcessFile(Q,J)})();this.inFlight.set(Q,H);try{await H,this.scheduleFlush()}finally{if(this.inFlight.get(Q)===H)this.inFlight.delete(Q)}}async doProcessFile(Q,J){await TS0(this.opts,Q,J)}scheduleFlush(){if(this.flushTimer)window.clearTimeout(this.flushTimer);this.flushTimer=window.setTimeout(()=>{this.flushTimer=null,this.flushInFlight=this.runFlush()},this.flushDebounceMs)}async runFlush(){let Q=Date.now();try{await this.opts.store.flush(),SQ.info("live indexer: flush completed",{providerKey:this.opts.embedder.providerKey,durationMs:Date.now()-Q})}catch(J){SQ.error("live indexer: flush failed",{providerKey:this.opts.embedder.providerKey,error:J instanceof Error?J.message:String(J)})}finally{this.flushInFlight=null}}async drainFlush(){if(this.flushTimer)window.clearTimeout(this.flushTimer),this.flushTimer=null,this.flushInFlight=this.runFlush();if(this.flushInFlight)await this.flushInFlight}}function FX0(Q){return new wS0(Q)}var qIQ=300000;class ES0{timer=null;running=!1;cycleInFlight=null;lastSeenMtime=new Map;bypassPersistedMtime=!1;intervalMs;opts;constructor(Q){this.intervalMs=Q.intervalMs??qIQ,this.opts={...Q,chunker:$X0(Q.chunker)}}async start(Q={}){if(this.running)return;if(this.running=!0,Q.initialRebuild!==!1)await this.runCycle();this.timer=window.setInterval(()=>{if(this.cycleInFlight)return;this.runCycle().catch((J)=>{SQ.error("low-power indexer: cycle failed",{error:J instanceof Error?J.message:String(J)})})},this.intervalMs)}async stop(){if(this.running=!1,this.timer)window.clearInterval(this.timer),this.timer=null;if(this.cycleInFlight)await this.cycleInFlight}isExcluded(Q){return this.opts.isExcluded?.(Q)??!1}async rebuildAll(Q={}){let J=Q.force??!0;if(!await this.opts.embedder.isAvailable()){SQ.warn("low-power indexer: embedding provider not available, skipping rebuild");return}if(J)this.lastSeenMtime.clear(),this.bypassPersistedMtime=!0;try{await this.runCycle()}finally{this.bypassPersistedMtime=!1}}async flush(){await this.runCycle()}pending(){return this.cycleInFlight?1:0}async runCycle(){if(this.cycleInFlight){await this.cycleInFlight;return}let Q=(async()=>{await this.opts.store.init();let J=this.opts.vault.getMarkdownFiles(),G=new Set;for(let H of J){if(G.add(H.path),this.isExcluded(H.path))continue;let K=this.bypassPersistedMtime||!this.opts.store.hasRecords(H.path)?void 0:this.opts.store.mtimeFor(H.path),z=this.lastSeenMtime.get(H.path)??K,q=H.mtime??Number.POSITIVE_INFINITY;if(z!==void 0&&q<=z)continue;if(await TS0(this.opts,H.path,H.mtime),H.mtime!==void 0)this.lastSeenMtime.set(H.path,H.mtime)}for(let H of Array.from(this.lastSeenMtime.keys()))if(!G.has(H))await this.opts.store.delete(H),this.lastSeenMtime.delete(H);await this.opts.store.flush()})();this.cycleInFlight=Q;try{await Q}finally{this.cycleInFlight=null}}}function SS0(Q){return new ES0(Q)}async function TS0(Q,J,G){let H=G??Q.vault.getFileMtime?.(J),K;try{K=await Q.vault.read(J)}catch(P){if(Q.vault.getMarkdownFiles().some((I)=>I.path===J)){SQ.warn("live indexer: read failed but path still in vault",{path:J,error:P instanceof Error?P.message:String(P)});return}await Q.store.delete(J);return}let z=await Q.chunker(K);if(z.length===0){await Q.store.delete(J);return}let q=new Map;for(let P of Q.store.recordsFor(J))q.set(P.contentHash,P);let F=Array(z.length),D=[],V=new Map;if(z.forEach((P,N)=>{let I=q.get(P.contentHash);if(I){F[N]=I.vector;return}let R=V.get(P.contentHash);if(R)R.push(N);else V.set(P.contentHash,[N]),D.push(P.text)}),D.length>0){let P=await Q.embedder.embed(D,"document"),N=0;for(let I of V.values()){let R=P[N++];for(let w of I)F[w]=R}}let O=z.map((P,N)=>{let I=F[N];if(!I)throw Error(`indexer: missing embedding for chunk ${J}#${P.id} (batch result misaligned)`);return{chunkId:`${J}#${P.id}`,filePath:J,offset:P.offset,heading:P.heading,contentHash:P.contentHash,vector:I}});if(UIQ(O,Q.store.recordsFor(J))){if(H!==void 0)Q.store.setMtime(J,H);return}if(await Q.store.delete(J),await Q.store.upsert(O),H!==void 0)Q.store.setMtime(J,H)}function UIQ(Q,J){let G=new Map;for(let H of J)G.set(H.chunkId,H);if(G.size!==Q.length)return!1;return Q.every((H)=>{let K=G.get(H.chunkId);return K!==void 0&&K.contentHash===H.contentHash&&K.offset===H.offset&&K.heading===H.heading})}function $IQ(Q){return Q instanceof $B.TFile&&Q.extension==="md"}async function kS0(Q){let J={exists:(g)=>Q.app.vault.adapter.exists(g),read:(g)=>Q.app.vault.adapter.read(g),write:(g,l)=>Q.app.vault.adapter.write(g,l),readBinary:(g)=>Q.app.vault.adapter.readBinary(g),writeBinary:(g,l)=>Q.app.vault.adapter.writeBinary(g,l),remove:(g)=>Q.app.vault.adapter.remove(g),mkdir:(g)=>Q.app.vault.adapter.mkdir(g)},G={getMarkdownFiles:()=>Q.app.vault.getMarkdownFiles().map((g)=>({path:g.path,mtime:g.stat?.mtime})),read:async(g)=>{let l=Q.app.vault.getAbstractFileByPath(g);if(!(l instanceof $B.TFile))throw Error(`semantic-search: not a file: ${g}`);return Q.app.vault.cachedRead(l)},getFileMtime:(g)=>{let l=Q.app.vault.getAbstractFileByPath(g);return l instanceof $B.TFile?l.stat?.mtime:void 0},on:(g,l)=>{let _=Q.app.vault.on(g,(a)=>{if($IQ(a))l(a.path)});return()=>Q.app.vault.offref(_)}},H=ij(Q.app),K=async(g,l,_)=>{let a=Q.app.vault.getAbstractFileByPath(g);if(!(a instanceof $B.TFile))return"";return(await Q.app.vault.cachedRead(a)).slice(l,l+_)},z=Q.manifest.dir??`.obsidian/plugins/${Q.manifest.id}`;await PS0(J,z);let q=`${z}/embeddings`,F=OS0(J,q),{staleKeys:D,probedCounts:V}=await FIQ(F,J,q);if(D.length>0){let g=D.length;Q.app.workspace.onLayoutReady(()=>{new $B.Notice(`MCP Tools: Semantic search index format upgraded (${g} provider${g>1?"s":""} migrated). Rebuilding automatically.`,8000)})}let O=VU({innerFactory:tR}),P=await new n9(Q).readSlice("semanticSearch")??{},N=US0({pipelineFactory:O.factory,maxInputTokens:$S0,unloadWhenIdle:P.unloadModelWhenIdle===!0}),I=FS0(N),R=F.storeFor("native-minilm-l6-v2",384);F.markReady("native-minilm-l6-v2");let w=VU({innerFactory:tR,dtype:"q8"}),E=jS0(w.factory),T=VU({innerFactory:tR,dtype:"q8"}),y=CS0(T.factory),x={"embedding-gemma-300m":E,"multilingual-e5-base":y},b=await SK0(Q,{factoryDeps:{plugin:Q,embedder:N,store:R,excerptResolver:K,registry:F,embeddingProviders:x}});if(b.success){let g=b.state;g.downloader=O,g.store=R,g.registry=F,g.probedCounts=V;let l=ZX0(I),_=g.settings.indexingMode==="low-power"?SS0({vault:G,chunker:l,embedder:I,store:R,isExcluded:H}):FX0({vault:G,chunker:l,embedder:I,store:R,isExcluded:H});g.indexer=_;let a=!1;g.startIndexerIfNeeded=()=>{if(a)return;a=!0,_.start().catch((d)=>{SQ.error("semantic-search: indexer start failed",{error:d instanceof Error?d.message:String(d)})})},IS0(G).then((d)=>{if(d>0.3&&g.settings.provider!=="embedding-gemma"&&g.settings.provider!=="multilingual-e5-base")g.autoSuggestProvider="embedding-gemma-300m"}).catch(()=>{});let r={native:"native-minilm-l6-v2",auto:"native-minilm-l6-v2","embedding-gemma":"embedding-gemma-300m","multilingual-e5-base":"multilingual-e5-base"};g.dlcIndexers=new Map;let f0=(d)=>{let n=x[d];if(!n)return null;let c0=F.storeFor(d,n.dimensions);return FX0({vault:G,chunker:ZX0(n),embedder:n,store:c0,isExcluded:H})},t=new Set;g.startRebuildFor=(d)=>{if(t.has(d))return;t.add(d);let n=d,c0=x[n];if(!c0){t.delete(d);return}let WQ=g.dlcIndexers?.get(d),R0=WQ??f0(n);if(!R0){t.delete(d);return}if(!WQ)g.dlcIndexers?.set(d,R0);(WQ?R0.rebuildAll():R0.start()).then(async()=>{if(await F.storeFor(d,c0.dimensions).flush(),F.markReady(d),g.pendingProvider===d)g.pendingProvider=null;if(g.chooser)g.provider=g.chooser(g.settings)}).catch((d0)=>{SQ.error("semantic-search: DLC rebuild failed",{providerKey:d,error:d0 instanceof Error?d0.message:String(d0)})}).finally(()=>{t.delete(d)})};let p0=(d)=>{if(g.dlcIndexers?.has(d))return;let n=f0(d);if(!n)return;g.dlcIndexers?.set(d,n),Q.app.workspace.onLayoutReady(()=>{n.start({initialRebuild:!1}).catch((c0)=>{SQ.error("semantic-search: DLC auto-subscribe failed",{providerKey:d,error:c0 instanceof Error?c0.message:String(c0)})})})};for(let d of["embedding-gemma-300m","multilingual-e5-base"])if(r[g.settings.provider]===d&&F.isReady(d))p0(d);let u0=r[g.settings.provider];if(u0&&D.includes(u0))Q.app.workspace.onLayoutReady(()=>{if(u0==="native-minilm-l6-v2")g.startIndexerIfNeeded?.();else g.startRebuildFor?.(u0)});return g.teardown=async()=>{if(a)try{await _.stop()}catch{}if(g.dlcIndexers){for(let[d,n]of g.dlcIndexers)try{await n.stop()}catch(c0){SQ.warn("semantic-search: DLC indexer stop failed",{providerKey:d,error:c0 instanceof Error?c0.message:String(c0)})}g.dlcIndexers.clear()}try{await N.unload()}catch{}try{await F.closeAll()}catch{}},g}else SQ.error("Semantic search setup failed",{error:b.error});return}var ZIQ={"native-minilm-l6-v2":384,"embedding-gemma-300m":768,"multilingual-e5-base":768};async function FIQ(Q,J,G){let H=[],K={};for(let z of jK0){let q=await Q.storeFor(z,ZIQ[z]).probe();if(!q)continue;if(q.version<UB)H.push(z);else if(q.version===UB&&q.recordCount>0)Q.markReady(z),K[z]=q.recordCount}for(let z of H){let q=`${G}/${z}`;try{await J.remove(`${q}/embeddings.bin`),await J.remove(`${q}/embeddings.index.json`),await J.remove(`${q}/embeddings.index.json.writing`).catch(()=>{}),await J.remove(`${q}/mtimes.json`).catch(()=>{}),await J.remove(`${q}/embeddings.meta.json`).catch(()=>{})}catch(F){SQ.warn("semantic-search: failed to wipe stale index directory",{dir:q,error:F instanceof Error?F.message:String(F)})}}return{staleKeys:H,probedCounts:K}}class DX0 extends Xw.Plugin{mcpTransportState;promptsState;semanticSearchState;smartSearch;async checkCommandPermission(Q){return q30({app:this.app,store:new n9(this)},Q)}async onload(){await gj0(this);let Q=await AF(this);if(Q.success){this.mcpTransportState=Q.state;let J=await uj0(Q.state.mcp.promptRegistry,this.app);if(J.success)this.promptsState=J.state;else SQ.error("Prompts feature setup failed",{error:J.error})}else new Xw.Notice(`MCP Connector: ${Q.error}`),SQ.error("MCP transport setup failed",{error:Q.error});try{this.semanticSearchState=await kS0(this)}catch(J){SQ.error("Semantic search wiring failed",{error:J instanceof Error?J.message:String(J)})}yS0.lastValueFrom(yK0(this)).then((J)=>{if(this.smartSearch=J.api,this.smartSearch)SQ.info("Smart Connections detected — `search_vault_smart` can use it");else SQ.debug("Smart Connections not installed — `search_vault_smart` falls back to the native provider unless reconfigured")}).catch((J)=>{SQ.debug("Smart Connections load skipped",{error:J instanceof Error?J.message:String(J)})}),SQ.info("MCP Tools Plugin loaded")}async onunload(){if(this.promptsState)pj0(this.promptsState),this.promptsState=void 0;if(this.mcpTransportState)await KF(this.mcpTransportState),this.mcpTransportState=void 0;if(this.semanticSearchState)await TK0(this.semanticSearchState),this.semanticSearchState=void 0}}
/* nosourcemap */