From b2c6efdf536b15e015ea86fc00ac329b8b159dbc Mon Sep 17 00:00:00 2001 From: Leane Schlundt Date: Wed, 11 Sep 2024 09:45:29 +0200 Subject: [PATCH 1/9] Fix wrong sketch opacity by using sketch layer Use a sketch layer like in Draw.js. --- .../assets/js/ol/MagicSamInteraction.js | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/resources/assets/js/ol/MagicSamInteraction.js b/src/resources/assets/js/ol/MagicSamInteraction.js index 46757db..a72c7d3 100644 --- a/src/resources/assets/js/ol/MagicSamInteraction.js +++ b/src/resources/assets/js/ol/MagicSamInteraction.js @@ -8,6 +8,7 @@ import VectorSource from '@biigle/ol/source/Vector'; import {InferenceSession, Tensor} from "onnxruntime-web"; import {linearRingContainsXY} from '@biigle/ol/geom/flat/contains'; import {throttle} from '../import'; +import Style from '@biigle/ol/style/Style'; const LONG_SIDE_LENGTH = 1024; @@ -41,16 +42,24 @@ class MagicSamInteraction extends PointerInteraction { this.throttleInterval = options.throttleInterval || 1000; this.sketchFeature = null; - this.sketchSource = options.source; + this.source = options.source; - if (this.sketchSource === undefined) { - this.sketchSource = new VectorSource(); + if (this.source === undefined) { + this.source = new VectorSource(); this.map.addLayer(new VectorLayer({ - source: this.sketchSource, + source: this.source, zIndex: 200, })); } + let sketchLayer = new VectorLayer({ + source: new VectorSource(), + map: this.map, + zIndex: 200, + }); + + this.sketchSource = sketchLayer.getSource() + this.sketchStyle = options.style === undefined ? null : options.style; this.MASK_INPUT_TENSOR = new Tensor( @@ -161,8 +170,8 @@ class MagicSamInteraction extends PointerInteraction { */ toggleActive() { if (!this.getActive() && this.sketchFeature) { - if (this.sketchSource.hasFeature(this.sketchFeature)) { - this.sketchSource.removeFeature(this.sketchFeature); + if (this.source.hasFeature(this.sketchFeature)) { + this.source.removeFeature(this.sketchFeature); } this.sketchFeature = null; } @@ -246,6 +255,7 @@ class MagicSamInteraction extends PointerInteraction { // This happens if the sketch feature was newly created (above) or if an annotation // was created from the feature (which may also remove the sketch from its source). if (!this.sketchSource.hasFeature(this.sketchFeature)) { + this.sketchSource.clear(); this.sketchSource.addFeature(this.sketchFeature); } } From a64150605f060a088c353dac7d01960ac91c518b Mon Sep 17 00:00:00 2001 From: Leane Schlundt Date: Wed, 11 Sep 2024 10:11:07 +0200 Subject: [PATCH 2/9] Commit npm run prod --- src/public/assets/scripts/main.js | 41240 +++++++++++++++++++++++++++- src/public/assets/styles/main.css | 105 +- src/public/mix-manifest.json | 12 +- 3 files changed, 41348 insertions(+), 9 deletions(-) diff --git a/src/public/assets/scripts/main.js b/src/public/assets/scripts/main.js index 127745e..8534715 100644 --- a/src/public/assets/scripts/main.js +++ b/src/public/assets/scripts/main.js @@ -1,2 +1,41238 @@ -/*! For license information please see main.js.LICENSE.txt */ -(()=>{var __webpack_modules__={645:(t,e,n)=>{"use strict";var r=biigle.$require("annotations.stores.canvasMixins"),i=biigle.$require("echo"),o=biigle.$require("events"),s=biigle.$require("keyboard"),a=biigle.$require("messages"),u=a.handleErrorResponse,l=biigle.$require("annotations.components.settingsTabPlugins"),c=biigle.$require("annotations.stores.styles"),h=biigle.$require("utils.throttle");function d(t,e,n,r,i,o,s,a){var u,l="function"==typeof t?t.options:t;if(e&&(l.render=e,l.staticRenderFns=n,l._compiled=!0),r&&(l.functional=!0),o&&(l._scopeId="data-v-"+o),s?(u=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),i&&i.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(s)},l._ssrRegister=u):i&&(u=a?function(){i.call(this,(l.functional?this.parent:this).$root.$options.shadowRoot)}:i),u)if(l.functional){l._injectStyles=u;var c=l.render;l.render=function(t,e){return u.call(e),c(t,e)}}else{var h=l.beforeCreate;l.beforeCreate=h?[].concat(h,u):[u]}return{exports:t,options:l}}const f=d({props:{settings:{type:Object,required:!0}},data:function(){return{steps:[2e3,1e3,500,200,100],stepNames:["slower","slow","medium","fast","faster"],stepIndex:2}},computed:{stepName:function(){return this.stepNames[this.stepIndex]}},watch:{stepIndex:function(t){var e=this.steps[t];o.$emit("settings.samThrottleInterval",e),this.settings.set("samRefreshRateStep",t)}},created:function(){this.settings.has("samRefreshRateStep")&&(this.stepIndex=this.settings.get("samRefreshRateStep"))}},undefined,undefined,!1,null,null,null).exports;l&&(l.magicSam=f);const p=Vue.resource("api/v1/images{/id}/sam-embedding");const g=class{constructor(t){this.propagationStopped,this.defaultPrevented,this.type=t,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}},m="propertychange";const y=class{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}};function b(t,e){return t>e?1:t0?i-1:i}return r-1}if(n>0){for(let n=1;n0)}removeEventListener(t,e){if(!this.listeners_)return;const n=this.listeners_[t];if(!n)return;const r=n.indexOf(e);-1!==r&&(this.pendingRemovals_&&t in this.pendingRemovals_?(n[r]=S,++this.pendingRemovals_[t]):(n.splice(r,1),0===n.length&&delete this.listeners_[t]))}},P="change";function C(t,e,n,r,i){if(r&&r!==t&&(n=n.bind(r)),i){const r=n;n=function(){t.removeEventListener(e,n),r.apply(this,arguments)}}const o={target:t,type:e,listener:n};return t.addEventListener(e,n),o}function D(t,e,n,r){return C(t,e,n,r,!0)}function k(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),E(t))}class R extends A{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent(P)}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const n=t.length,r=new Array(n);for(let i=0;i0}}else if(t.type==Z){const n=this.handleDownEvent(t);this.handlingDownUpSequence=n,e=this.stopDown(n)}else t.type==K&&this.handleMoveEvent(t);return!e}handleMoveEvent(t){}handleUpEvent(t){return!1}stopDown(t){return t}updateTrackedPointers_(t){t.activePointers&&(this.targetPointers=t.activePointers)}};new Array(6);function tt(t,e){const n=e[0],r=e[1];return e[0]=t[0]*n+t[2]*r+t[4],e[1]=t[1]*n+t[3]*r+t[5],e}function et(t,e,n,r,i,o,s,a){const u=Math.sin(o),l=Math.cos(o);return t[0]=r*l,t[1]=i*u,t[2]=-r*u,t[3]=i*l,t[4]=s*r*l-a*r*u+e,t[5]=s*i*u+a*i*l+n,t}function nt(t,e){const n=(r=e)[0]*r[3]-r[1]*r[2];var r;B(0!==n,"Transformation matrix cannot be inverted");const i=e[0],o=e[1],s=e[2],a=e[3],u=e[4],l=e[5];return t[0]=a/n,t[1]=-o/n,t[2]=-s/n,t[3]=i/n,t[4]=(s*l-a*u)/n,t[5]=-(i*l-o*u)/n,t}const rt=[1e6,1e6,1e6,1e6,2,2];function it(t){return"matrix("+t.map(((t,e)=>Math.round(t*rt[e])/rt[e])).join(", ")+")"}const ot=0,st=1,at=2,ut=4,lt=8,ct=16;function ht(t,e,n){return n?(n[0]=t[0]-e,n[1]=t[1]-e,n[2]=t[2]+e,n[3]=t[3]+e,n):[t[0]-e,t[1]-e,t[2]+e,t[3]+e]}function dt(t,e,n){let r,i;return r=ei&&(u|=ut),ao&&(u|=at),u===ot&&(u=st),u}function yt(t,e,n,r,i){return i?(i[0]=t,i[1]=e,i[2]=n,i[3]=r,i):[t,e,n,r]}function bt(t){return yt(1/0,1/0,-1/0,-1/0,t)}function _t(t,e){const n=t[0],r=t[1];return yt(n,r,n,r,e)}function vt(t,e,n,r,i){return Tt(bt(i),t,e,n,r)}function wt(t,e){return t[0]==e[0]&&t[2]==e[2]&&t[1]==e[1]&&t[3]==e[3]}function xt(t,e){e[0]t[2]&&(t[2]=e[0]),e[1]t[3]&&(t[3]=e[1])}function Tt(t,e,n,r,i){for(;n=e[0]&&t[1]<=e[3]&&t[3]>=e[1]}function Mt(t){return t[2]1){const e=t[2]-t[0],n=t[3]-t[1];for(let o=0;o=n[2])){const e=kt(n),i=Math.floor((r[0]-n[0])/e)*e;t[0]-=i,t[2]-=i}return t}const $t={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};const Nt=class{constructor(t){this.code_=t.code,this.units_=t.units,this.extent_=void 0!==t.extent?t.extent:null,this.worldExtent_=void 0!==t.worldExtent?t.worldExtent:null,this.axisOrientation_=void 0!==t.axisOrientation?t.axisOrientation:"enu",this.global_=void 0!==t.global&&t.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=t.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=t.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||$t[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(t){this.global_=t,this.canWrapX_=!(!t||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(t){this.defaultTileGrid_=t}setExtent(t){this.extent_=t,this.canWrapX_=!(!this.global_||!t)}setWorldExtent(t){this.worldExtent_=t}setGetPointResolution(t){this.getPointResolutionFunc_=t}getPointResolutionFunc(){return this.getPointResolutionFunc_}},jt=6378137,Bt=Math.PI*jt,Ut=[-Bt,-Bt,Bt,Bt],Vt=[-180,-85,180,85],zt=jt*Math.log(Math.tan(Math.PI/2));class Gt extends Nt{constructor(t){super({code:t,units:"m",extent:Ut,global:!0,worldExtent:Vt,getPointResolution:function(t,e){return t/Math.cosh(e[1]/jt)}})}}const Wt=[new Gt("EPSG:3857"),new Gt("EPSG:102100"),new Gt("EPSG:102113"),new Gt("EPSG:900913"),new Gt("http://www.opengis.net/def/crs/EPSG/0/3857"),new Gt("http://www.opengis.net/gml/srs/epsg.xml#3857")];function Ht(t,e,n){const r=t.length;n=n>1?n:2,void 0===e&&(e=n>2?t.slice():new Array(r));for(let i=0;izt?n=zt:n<-zt&&(n=-zt),e[i+1]=n}return e}function qt(t,e,n){const r=t.length;n=n>1?n:2,void 0===e&&(e=n>2?t.slice():new Array(r));for(let i=0;i=0;--r)if(t[r]!=e[r]){n=!1;break}return n}function ne(t,e){if(e.canWrapX()){const n=kt(e.getExtent()),r=function(t,e,n){const r=e.getExtent();let i=0;e.canWrapX()&&(t[0]r[2])&&(n=n||kt(r),i=Math.floor((t[0]-r[0])/n));return i}(t,e,n);r&&(t[0]-=r*n)}return t}const re={info:1,warn:2,error:3,none:4};let ie=re.info;let oe=!0;function se(t){oe=!(void 0===t||t)}function ae(t,e){if(void 0!==e)for(let n=0,r=t.length;n=-180&&t[0]<=180&&t[1]>=-90&&t[1]<=90&&(oe=!1,function(...t){ie>re.warn||console.warn(...t)}("Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.")),t)}function we(t,e){return ye?me(t,e,ye):t}function xe(t,e){return ye?me(t,ye,e):t}function Te(t,e){if(!ye)return t;const n=ce(e).getMetersPerUnit(),r=ye.getMetersPerUnit();return n&&r?t*n/r:t}var Se,Oe,Ee;function Ie(t,e,n,r,i,o){o=o||[];let s=0;for(let a=e;a{if(!n)return this.getSimplifiedGeometry(e);const r=this.clone();return r.applyTransform(n),r.getSimplifiedGeometry(e)}))}simplifyTransformed(t,e){return this.simplifyTransformedInternal(this.getRevision(),t,e)}clone(){return F()}closestPointXY(t,e,n,r){return F()}containsXY(t,e){const n=this.getClosestPoint([t,e]);return n[0]===t&&n[1]===e}getClosestPoint(t,e){return e=e||[NaN,NaN],this.closestPointXY(t[0],t[1],e,1/0),e}intersectsCoordinate(t){return this.containsXY(t[0],t[1])}computeExtent(t){return F()}getExtent(t){if(this.extentRevision_!=this.getRevision()){const t=this.computeExtent(this.extent_);(isNaN(t[0])||isNaN(t[1]))&&bt(t),this.extentRevision_=this.getRevision()}return function(t,e){return e?(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e):t}(this.extent_,t)}rotate(t,e){F()}scale(t,e,n){F()}simplify(t){return this.getSimplifiedGeometry(t*t)}getSimplifiedGeometry(t){return F()}getType(){return F()}applyTransform(t){F()}intersectsExtent(t){return F()}translate(t,e){F()}transform(t,e){const n=ce(t),r="tile-pixels"==n.getUnits()?function(t,r,i){const o=n.getExtent(),s=n.getWorldExtent(),a=Pt(s)/Pt(o);return et(Pe,s[0],s[3],a,-a,0,0,0),Ie(t,0,t.length,i,Pe,r),pe(n,e)(t,r,i)}:pe(n,e);return this.applyTransform(r),this}};function De(t){let e;return"XY"==t?e=2:"XYZ"==t||"XYM"==t?e=3:"XYZM"==t&&(e=4),e}const ke=class extends Ce{constructor(){super(),this.layout="XY",this.stride=2,this.flatCoordinates}computeExtent(t){return vt(this.flatCoordinates,0,this.flatCoordinates.length,this.stride,t)}getCoordinates(){return F()}getFirstCoordinate(){return this.flatCoordinates.slice(0,this.stride)}getFlatCoordinates(){return this.flatCoordinates}getLastCoordinate(){return this.flatCoordinates.slice(this.flatCoordinates.length-this.stride)}getLayout(){return this.layout}getSimplifiedGeometry(t){if(this.simplifiedGeometryRevision!==this.getRevision()&&(this.simplifiedGeometryMaxMinSquaredTolerance=0,this.simplifiedGeometryRevision=this.getRevision()),t<0||0!==this.simplifiedGeometryMaxMinSquaredTolerance&&t<=this.simplifiedGeometryMaxMinSquaredTolerance)return this;const e=this.getSimplifiedGeometryInternal(t);return e.getFlatCoordinates().length1?(n=i,r=o):u>0&&(n+=s*u,r+=a*u)}return Fe(t,e,n,r)}function Fe(t,e,n,r){const i=n-t,o=r-e;return i*i+o*o}function Le(t,e){const n=t%e;return n*e<0?n+e:n}function $e(t,e,n){return t+n*(e-t)}function Ne(t,e){const n=Math.pow(10,e);return Math.round(t*n)/n}function je(t,e,n,r,i,o,s){const a=t[e],u=t[e+1],l=t[n]-a,c=t[n+1]-u;let h;if(0===l&&0===c)h=e;else{const d=((i-a)*l+(o-u)*c)/(l*l+c*c);if(d>1)h=n;else{if(d>0){for(let i=0;ii&&(i=a),o=n,s=r}return i}function Ue(t,e,n,r,i){for(let o=0,s=n.length;o0;){const n=l.pop(),o=l.pop();let s=0;const a=t[o],h=t[o+1],d=t[n],f=t[n+1];for(let e=o+r;es&&(c=e,s=n)}s>i&&(u[(c-e)/r]=1,o+r0&&p>d)&&(f<0&&g0&&g>f)?(a=n,u=h):(o[s++]=a,o[s++]=u,l=a,c=u,a=n,u=h)}return o[s++]=a,o[s++]=u,s}function Ke(t,e,n,r,i,o,s,a){for(let u=0,l=n.length;uo&&(n-a)*(o-u)-(i-a)*(r-u)>0&&s++:r<=o&&(n-a)*(o-u)-(i-a)*(r-u)<0&&s--,a=n,u=r}return 0!==s}function ln(t,e,n,r,i,o){if(0===n.length)return!1;if(!un(t,e,n[0],r,i,o))return!1;for(let e=1,s=n.length;ey&&(l=(c+h)/2,ln(t,e,n,r,l,p)&&(m=l,y=i)),c=h}return isNaN(m)&&(m=i[o]),s?(s.push(m,p,y),s):[m,p,y]}function hn(t,e,n,r,i){const o=Tt([1/0,1/0,-1/0,-1/0],t,e,n,r);return!!Rt(i,o)&&(!!pt(i,o)||(o[0]>=i[0]&&o[2]<=i[2]||(o[1]>=i[1]&&o[3]<=i[3]||function(t,e,n,r,i){let o;for(e+=r;e=s&&g<=u),r||!(o&ut)||i&ut||(m=f-(d-u)*p,r=m>=a&&m<=l),r||!(o<)||i<||(g=d-(f-a)/p,r=g>=s&&g<=u),r||!(o&ct)||i&ct||(m=f-(d-s)*p,r=m>=a&&m<=l)}return r}(i,t,e)})))))}function dn(t,e,n,r,i){if(!function(t,e,n,r,i){return!!(hn(t,e,n,r,i)||un(t,e,n,r,i[0],i[1])||un(t,e,n,r,i[0],i[3])||un(t,e,n,r,i[2],i[1])||un(t,e,n,r,i[2],i[3]))}(t,e,n[0],r,i))return!1;if(1===n.length)return!0;for(let e=1,o=n.length;e0}function gn(t,e,n,r,i){i=void 0!==i&&i;for(let o=0,s=n.length;of&&(d=(f+d)/2,f=d),p>g&&(p=(g+p)/2,g=p);let m=Re(r[0],d,f),y=Re(r[1],p,g);if(s&&n&&i){const t=30*i;m+=-t*Math.log(1+Math.max(0,d-r[0])/t)+t*Math.log(1+Math.max(0,r[0]-f)/t),y+=-t*Math.log(1+Math.max(0,p-r[1])/t)+t*Math.log(1+Math.max(0,r[1]-g)/t)}return[m,y]}}function Nn(t){return t}function jn(t,e,n,r){const i=kt(e)/n[0],o=Pt(e)/n[1];return r?Math.min(t,Math.max(i,o)):Math.min(t,Math.min(i,o))}function Bn(t,e,n){let r=Math.min(t,e);return r*=Math.log(1+50*Math.max(0,t/e-1))/50+1,n&&(r=Math.max(r,n),r/=Math.log(1+50*Math.max(0,n/t-1))/50+1),Re(r,n/2,2*e)}function Un(t,e,n,r,i){return n=void 0===n||n,function(o,s,a,u){if(void 0!==o){const s=r?jn(t,r,a,i):t;return n&&u?Bn(o,s,e):Re(o,e,s)}}}function Vn(t){if(void 0!==t)return 0}function zn(t){if(void 0!==t)return t}function Gn(t){const e=void 0===t?5*Math.PI/180:t;return function(t,n){return n||void 0===t?t:Math.abs(t)<=e?0:t}}function Wn(t){return 1-function(t){return Math.pow(t,3)}(1-t)}function Hn(t){return 3*t*t-2*t*t*t}function qn(t,e){setTimeout((function(){t(e)}),0)}function Xn(t){return!(t.sourceCenter&&t.targetCenter&&!ee(t.sourceCenter,t.targetCenter))&&(t.sourceResolution===t.targetResolution&&t.sourceRotation===t.targetRotation)}function Yn(t,e,n,r,i){const o=Math.cos(-i);let s=Math.sin(-i),a=t[0]*o-t[1]*s,u=t[1]*o+t[0]*s;a+=(e[0]/2-n[0])*r,u+=(n[1]-e[1]/2)*r,s=-s;return[a*o-u*s,u*o+a*s]}const Kn=class extends j{constructor(t){super(),this.on,this.once,this.un,t=Object.assign({},t),this.hints_=[0,0],this.animations_=[],this.updateAnimationKey_,this.projection_=de(t.projection,"EPSG:3857"),this.viewportSize_=[100,100],this.targetCenter_=null,this.targetResolution_,this.targetRotation_,this.nextCenter_=null,this.nextResolution_,this.nextRotation_,this.cancelAnchor_=void 0,t.projection&&se(),t.center&&(t.center=ve(t.center,this.projection_)),t.extent&&(t.extent=xe(t.extent,this.projection_)),this.applyOptions_(t)}applyOptions_(t){const e=Object.assign({},t);for(const t in Ln)delete e[t];this.setProperties(e,!0);const n=function(t){let e,n,r;const i=28,o=2;let s=void 0!==t.minZoom?t.minZoom:0,a=void 0!==t.maxZoom?t.maxZoom:i;const u=void 0!==t.zoomFactor?t.zoomFactor:o,l=void 0!==t.multiWorld&&t.multiWorld,c=void 0===t.smoothResolutionConstraint||t.smoothResolutionConstraint,h=void 0!==t.showFullExtent&&t.showFullExtent,d=de(t.projection,"EPSG:3857"),f=d.getExtent();let p=t.constrainOnlyCenter,g=t.extent;l||g||!d.isGlobal()||(p=!1,g=f);if(void 0!==t.resolutions){const i=t.resolutions;n=i[s],r=void 0!==i[a]?i[a]:i[i.length-1],e=t.constrainResolution?function(t,e,n,r){return e=void 0===e||e,function(i,o,s,a){if(void 0!==i){const u=t[0],l=t[t.length-1],c=n?jn(u,n,s,r):u;if(a)return e?Bn(i,c,l):Re(i,l,c);const h=Math.min(c,i),d=Math.floor(_(t,h,o));return t[d]>c&&d1&&"function"==typeof arguments[n-1]&&(e=arguments[n-1],--n);let r=0;for(;r0}getInteracting(){return this.hints_[Fn]>0}cancelAnimations(){let t;this.setHint(Mn,-this.hints_[Mn]);for(let e=0,n=this.animations_.length;e=0;--n){const r=this.animations_[n];let i=!0;for(let n=0,o=r.length;n0?s/o.duration:1;a>=1?(o.complete=!0,a=1):i=!1;const u=o.easing(a);if(o.sourceCenter){const t=o.sourceCenter[0],e=o.sourceCenter[1],n=o.targetCenter[0],r=o.targetCenter[1];this.nextCenter_=o.targetCenter;const i=t+u*(n-t),s=e+u*(r-e);this.targetCenter_=[i,s]}if(o.sourceResolution&&o.targetResolution){const t=1===u?o.targetResolution:o.sourceResolution+u*(o.targetResolution-o.sourceResolution);if(o.anchor){const e=this.getViewportSize_(this.getRotation()),n=this.constraints_.resolution(t,0,e,!0);this.targetCenter_=this.calculateCenterZoom(n,o.anchor)}this.nextResolution_=o.targetResolution,this.targetResolution_=t,this.applyTargetState_(!0)}if(void 0!==o.sourceRotation&&void 0!==o.targetRotation){const t=1===u?Le(o.targetRotation+Math.PI,2*Math.PI)-Math.PI:o.sourceRotation+u*(o.targetRotation-o.sourceRotation);if(o.anchor){const e=this.constraints_.rotation(t,!0);this.targetCenter_=this.calculateCenterRotate(e,o.anchor)}this.nextRotation_=o.targetRotation,this.targetRotation_=t}if(this.applyTargetState_(!0),e=!0,!o.complete)break}if(i){this.animations_[n]=null,this.setHint(Mn,-1),this.nextCenter_=null,this.nextResolution_=NaN,this.nextRotation_=NaN;const t=r[0].callback;t&&qn(t,!0)}}this.animations_=this.animations_.filter(Boolean),e&&void 0===this.updateAnimationKey_&&(this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_.bind(this)))}calculateCenterRotate(t,e){let n;const r=this.getCenterInternal();var i,o;return void 0!==r&&(n=[r[0]-e[0],r[1]-e[1]],function(t,e){const n=Math.cos(e),r=Math.sin(e),i=t[0]*n-t[1]*r,o=t[1]*n+t[0]*r;t[0]=i,t[1]=o}(n,t-this.getRotation()),o=e,(i=n)[0]+=+o[0],i[1]+=+o[1]),n}calculateCenterZoom(t,e){let n;const r=this.getCenterInternal(),i=this.getResolution();if(void 0!==r&&void 0!==i){n=[e[0]-t*(e[0]-r[0])/i,e[1]-t*(e[1]-r[1])/i]}return n}getViewportSize_(t){const e=this.viewportSize_;if(t){const n=e[0],r=e[1];return[Math.abs(n*Math.cos(t))+Math.abs(r*Math.sin(t)),Math.abs(n*Math.sin(t))+Math.abs(r*Math.cos(t))]}return e}setViewportSize(t){this.viewportSize_=Array.isArray(t)?t.slice():[100,100],this.getAnimating()||this.resolveConstraints(0)}getCenter(){const t=this.getCenterInternal();return t?_e(t,this.getProjection()):t}getCenterInternal(){return this.get(Ln.CENTER)}getConstraints(){return this.constraints_}getConstrainResolution(){return this.get("constrainResolution")}getHints(t){return void 0!==t?(t[0]=this.hints_[0],t[1]=this.hints_[1],t):this.hints_.slice()}calculateExtent(t){return we(this.calculateExtentInternal(t),this.getProjection())}calculateExtentInternal(t){t=t||this.getViewportSizeMinusPadding_();const e=this.getCenterInternal();B(e,"The view center is not defined");const n=this.getResolution();B(void 0!==n,"The view resolution is not defined");const r=this.getRotation();return B(void 0!==r,"The view rotation is not defined"),At(e,n,r,t)}getMaxResolution(){return this.maxResolution_}getMinResolution(){return this.minResolution_}getMaxZoom(){return this.getZoomForResolution(this.minResolution_)}setMaxZoom(t){this.applyOptions_(this.getUpdatedOptions_({maxZoom:t}))}getMinZoom(){return this.getZoomForResolution(this.maxResolution_)}setMinZoom(t){this.applyOptions_(this.getUpdatedOptions_({minZoom:t}))}setConstrainResolution(t){this.applyOptions_(this.getUpdatedOptions_({constrainResolution:t}))}getProjection(){return this.projection_}getResolution(){return this.get(Ln.RESOLUTION)}getResolutions(){return this.resolutions_}getResolutionForExtent(t,e){return this.getResolutionForExtentInternal(xe(t,this.getProjection()),e)}getResolutionForExtentInternal(t,e){e=e||this.getViewportSizeMinusPadding_();const n=kt(t)/e[0],r=Pt(t)/e[1];return Math.max(n,r)}getResolutionForValueFunction(t){t=t||2;const e=this.getConstrainedResolution(this.maxResolution_),n=this.minResolution_,r=Math.log(e/n)/Math.log(t);return function(n){return e/Math.pow(t,n*r)}}getRotation(){return this.get(Ln.ROTATION)}getValueForResolutionFunction(t){const e=Math.log(t||2),n=this.getConstrainedResolution(this.maxResolution_),r=this.minResolution_,i=Math.log(n/r)/e;return function(t){return Math.log(n/t)/e/i}}getViewportSizeMinusPadding_(t){let e=this.getViewportSize_(t);const n=this.padding_;return n&&(e=[e[0]-n[1]-n[3],e[1]-n[0]-n[2]]),e}getState(){const t=this.getProjection(),e=this.getResolution(),n=this.getRotation();let r=this.getCenterInternal();const i=this.padding_;if(i){const t=this.getViewportSizeMinusPadding_();r=Yn(r,this.getViewportSize_(),[t[0]/2+i[3],t[1]/2+i[0]],e,n)}return{center:r.slice(0),projection:void 0!==t?t:null,resolution:e,nextCenter:this.nextCenter_,nextResolution:this.nextResolution_,nextRotation:this.nextRotation_,rotation:n,zoom:this.getZoom()}}getViewStateAndExtent(){return{viewState:this.getState(),extent:this.calculateExtent()}}getZoom(){let t;const e=this.getResolution();return void 0!==e&&(t=this.getZoomForResolution(e)),t}getZoomForResolution(t){let e,n,r=this.minZoom_||0;if(this.resolutions_){const i=_(this.resolutions_,t,1);r=i,e=this.resolutions_[i],n=i==this.resolutions_.length-1?2:e/this.resolutions_[i+1]}else e=this.maxResolution_,n=this.zoomFactor_;return r+Math.log(e/t)/Math.log(n)}getResolutionForZoom(t){if(this.resolutions_){if(this.resolutions_.length<=1)return 0;const e=Re(Math.floor(t),0,this.resolutions_.length-2),n=this.resolutions_[e]/this.resolutions_[e+1];return this.resolutions_[e]/Math.pow(n,Re(t-e,0,1))}return this.maxResolution_/Math.pow(this.zoomFactor_,t-this.minZoom_)}fit(t,e){let n;if(B(Array.isArray(t)||"function"==typeof t.getSimplifiedGeometry,"Invalid extent or geometry provided as `geometry`"),Array.isArray(t)){B(!Mt(t),"Cannot fit empty extent provided as `geometry`");n=_n(xe(t,this.getProjection()))}else if("Circle"===t.getType()){const e=xe(t.getExtent(),this.getProjection());n=_n(e),n.rotate(this.getRotation(),It(e))}else{const e=be();n=e?t.clone().transform(e,this.getProjection()):t}this.fitInternal(n,e)}rotatedExtentForGeometry(t){const e=this.getRotation(),n=Math.cos(e),r=Math.sin(-e),i=t.getFlatCoordinates(),o=t.getStride();let s=1/0,a=1/0,u=-1/0,l=-1/0;for(let t=0,e=i.length;t{this.dispatchEvent("sourceready")}),0))),this.changed()}getFeatures(t){return this.renderer_?this.renderer_.getFeatures(t):Promise.resolve([])}getData(t){return this.renderer_&&this.rendered?this.renderer_.getData(t):null}isVisible(t){let e;const n=this.getMapInternal();let r;!t&&n&&(t=n.getView()),e=t instanceof Kn?{viewState:t.getState(),extent:t.calculateExtent()}:t,!e.layerStatesArray&&n&&(e.layerStatesArray=n.getLayerGroup().getLayerStatesArray()),r=e.layerStatesArray?e.layerStatesArray.find((t=>t.layer===this)):this.getLayerState();const i=this.getExtent();return function(t,e){if(!t.visible)return!1;const n=e.resolution;if(n=t.maxResolution)return!1;const r=e.zoom;return r>t.minZoom&&r<=t.maxZoom}(r,e.viewState)&&(!i||Rt(i,e.extent))}getAttributions(t){if(!this.isVisible(t))return[];let e;const n=this.getSource();if(n&&(e=n.getAttributions()),!e)return[];let r=e(t instanceof Kn?t.getViewStateAndExtent():t);return Array.isArray(r)||(r=[r]),r}render(t,e){const n=this.getRenderer();return n.prepareFrame(t)?(this.rendered=!0,n.renderFrame(t,e)):null}unrender(){this.rendered=!1}getDeclutter(){}renderDeclutter(t,e){}renderDeferred(t){const e=this.getRenderer();e&&e.renderDeferred(t)}setMapInternal(t){t||this.unrender(),this.set(Pn,t)}getMapInternal(){return this.get(Pn)}setMap(t){this.mapPrecomposeKey_&&(k(this.mapPrecomposeKey_),this.mapPrecomposeKey_=null),t||this.changed(),this.mapRenderKey_&&(k(this.mapRenderKey_),this.mapRenderKey_=null),t&&(this.mapPrecomposeKey_=C(t,Rn,(function(t){const e=t.frameState.layerStatesArray,n=this.getLayerState(!1);B(!e.some((function(t){return t.layer===n.layer})),"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both."),e.push(n)}),this),this.mapRenderKey_=C(this,P,t.render,t),this.changed())}setSource(t){this.set(An,t)}getRenderer(){return this.renderer_||(this.renderer_=this.createRenderer()),this.renderer_}hasRenderer(){return!!this.renderer_}createRenderer(){return null}disposeInternal(){this.renderer_&&(this.renderer_.dispose(),delete this.renderer_),this.setSource(null),super.disposeInternal()}};var Jn=n(582);const Qn=0,tr=1,er=2,nr=3;function rr(t,e){return Array.isArray(t)?t:(void 0===e?e=[t,t]:(e[0]=t,e[1]=t),e)}class ir{constructor(t){this.opacity_=t.opacity,this.rotateWithView_=t.rotateWithView,this.rotation_=t.rotation,this.scale_=t.scale,this.scaleArray_=rr(t.scale),this.displacement_=t.displacement,this.declutterMode_=t.declutterMode}clone(){const t=this.getScale();return new ir({opacity:this.getOpacity(),scale:Array.isArray(t)?t.slice():t,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getOpacity(){return this.opacity_}getRotateWithView(){return this.rotateWithView_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getDisplacement(){return this.displacement_}getDeclutterMode(){return this.declutterMode_}getAnchor(){return F()}getImage(t){return F()}getHitDetectionImage(){return F()}getPixelRatio(t){return 1}getImageState(){return F()}getImageSize(){return F()}getOrigin(){return F()}getSize(){return F()}setDisplacement(t){this.displacement_=t}setOpacity(t){this.opacity_=t}setRotateWithView(t){this.rotateWithView_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=rr(t)}listenImageChange(t){F()}load(){F()}unlistenImageChange(t){F()}ready(){return Promise.resolve()}}const or=ir,sr={name:"rgb",min:[0,0,0],max:[255,255,255],channel:["red","green","blue"],alias:["RGB"]};var ar={name:"xyz",min:[0,0,0],channel:["X","Y","Z"],alias:["XYZ","ciexyz","cie1931"],whitepoint:{2:{A:[109.85,100,35.585],C:[98.074,100,118.232],D50:[96.422,100,82.521],D55:[95.682,100,92.149],D65:[95.045592705167,100,108.9057750759878],D75:[94.972,100,122.638],F2:[99.187,100,67.395],F7:[95.044,100,108.755],F11:[100.966,100,64.37],E:[100,100,100]},10:{A:[111.144,100,35.2],C:[97.285,100,116.145],D50:[96.72,100,81.427],D55:[95.799,100,90.926],D65:[94.811,100,107.304],D75:[94.416,100,120.641],F2:[103.28,100,69.026],F7:[95.792,100,107.687],F11:[103.866,100,65.627],E:[100,100,100]}}};ar.max=ar.whitepoint[2].D65,ar.rgb=function(t,e){e=e||ar.whitepoint[2].E;var n,r,i,o=t[0]/e[0],s=t[1]/e[1],a=t[2]/e[2];return r=-.96924363628087*o+1.87596750150772*s+.041555057407175*a,i=.055630079696993*o+-.20397695888897*s+1.056971514242878*a,n=(n=3.240969941904521*o+-1.537383177570093*s+-.498610760293*a)>.0031308?1.055*Math.pow(n,1/2.4)-.055:n*=12.92,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:r*=12.92,i=i>.0031308?1.055*Math.pow(i,1/2.4)-.055:i*=12.92,[255*(n=Math.min(Math.max(0,n),1)),255*(r=Math.min(Math.max(0,r),1)),255*(i=Math.min(Math.max(0,i),1))]},sr.xyz=function(t,e){var n=t[0]/255,r=t[1]/255,i=t[2]/255,o=.21263900587151*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.71516867876775*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)+.072192315360733*(i=i>.04045?Math.pow((i+.055)/1.055,2.4):i/12.92),s=.019330818715591*n+.11919477979462*r+.95053215224966*i;return[(.41239079926595*n+.35758433938387*r+.18048078840183*i)*(e=e||ar.whitepoint[2].E)[0],o*e[1],s*e[2]]};const ur=ar,lr={name:"luv",min:[0,-134,-140],max:[100,224,122],channel:["lightness","u","v"],alias:["LUV","cieluv","cie1976"],xyz:function(t,e,n){var r,i,o,s,a,u,l,c,h;if(o=t[0],s=t[1],a=t[2],0===o)return[0,0,0];return e=e||"D65",n=n||2,r=s/(13*o)+4*(l=ur.whitepoint[n][e][0])/(l+15*(c=ur.whitepoint[n][e][1])+3*(h=ur.whitepoint[n][e][2]))||0,i=a/(13*o)+9*c/(l+15*c+3*h)||0,[9*(u=o>8?c*Math.pow((o+16)/116,3):c*o*.0011070564598794539)*r/(4*i)||0,u,u*(12-3*r-20*i)/(4*i)||0]}};ur.luv=function(t,e,n){var r,i,o,s,a,u,l,c,h,d,f;e=e||"D65",n=n||2,d=4*(l=ur.whitepoint[n][e][0])/(l+15*(c=ur.whitepoint[n][e][1])+3*(h=ur.whitepoint[n][e][2])),f=9*c/(l+15*c+3*h),r=4*(s=t[0])/(s+15*(a=t[1])+3*(u=t[2]))||0,i=9*a/(s+15*a+3*u)||0;var p=a/c;return[o=p<=.008856451679035631?903.2962962962961*p:116*Math.pow(p,1/3)-16,13*o*(r-d),13*o*(i-f)]};var cr={name:"lchuv",channel:["lightness","chroma","hue"],alias:["LCHuv","cielchuv"],min:[0,0,0],max:[100,100,360],luv:function(t){var e,n=t[0],r=t[1];return e=t[2]/360*2*Math.PI,[n,r*Math.cos(e),r*Math.sin(e)]},xyz:function(t){return lr.xyz(cr.luv(t))}};const hr=cr;lr.lchuv=function(t){var e=t[0],n=t[1],r=t[2],i=Math.sqrt(n*n+r*r),o=360*Math.atan2(r,n)/2/Math.PI;return o<0&&(o+=360),[e,i,o]},ur.lchuv=function(t){return lr.lchuv(ur.luv(t))};const dr={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},fr=function(t){var e,n,r=[],i=1;if("number"==typeof t)return{space:"rgb",values:[t>>>16,(65280&t)>>>8,255&t],alpha:1};if("number"==typeof t)return{space:"rgb",values:[t>>>16,(65280&t)>>>8,255&t],alpha:1};if(t=String(t).toLowerCase(),dr[t])r=dr[t].slice(),n="rgb";else if("transparent"===t)i=0,n="rgb",r=[0,0,0];else if("#"===t[0]){var o=t.slice(1),s=o.length;i=1,s<=4?(r=[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)],4===s&&(i=parseInt(o[3]+o[3],16)/255)):(r=[parseInt(o[0]+o[1],16),parseInt(o[2]+o[3],16),parseInt(o[4]+o[5],16)],8===s&&(i=parseInt(o[6]+o[7],16)/255)),r[0]||(r[0]=0),r[1]||(r[1]=0),r[2]||(r[2]=0),n="rgb"}else if(e=/^((?:rgba?|hs[lvb]a?|hwba?|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms|oklch|oklab|color))\s*\(([^\)]*)\)/.exec(t)){var a=e[1],u="cmyk"===(n=a.replace(/a$/,""))?4:"gray"===n?1:3;r=e[2].trim().split(/\s*[,\/]\s*|\s+/),"color"===n&&(n=r.shift()),r=r.map((function(t,e){if("%"===t[t.length-1])return t=parseFloat(t)/100,3===e?t:"rgb"===n?255*t:"h"===n[0]?100*t:"l"!==n[0]||e?"lab"===n?125*t:"lch"===n?e<2?150*t:360*t:"o"!==n[0]||e?"oklab"===n?.4*t:"oklch"===n?e<2?.4*t:360*t:t:t:100*t;if("h"===n[e]||2===e&&"h"===n[n.length-1]){if(void 0!==pr[t])return pr[t];if(t.endsWith("deg"))return parseFloat(t);if(t.endsWith("turn"))return 360*parseFloat(t);if(t.endsWith("grad"))return 360*parseFloat(t)/400;if(t.endsWith("rad"))return 180*parseFloat(t)/Math.PI}return"none"===t?0:parseFloat(t)})),i=r.length>u?r.pop():1}else/[0-9](?:\s|\/|,)/.test(t)&&(r=t.match(/([0-9]+)/g).map((function(t){return parseFloat(t)})),n=t.match(/([a-z])/gi)?.join("")?.toLowerCase()||"rgb");return{space:n,values:r,alpha:i}};var pr={red:0,orange:60,yellow:120,green:180,blue:240,purple:300};const gr={name:"hsl",min:[0,0,0],max:[360,100,100],channel:["hue","saturation","lightness"],alias:["HSL"],rgb:function(t){var e,n,r,i,o,s=t[0]/360,a=t[1]/100,u=t[2]/100,l=0;if(0===a)return[o=255*u,o,o];for(e=2*u-(n=u<.5?u*(1+a):u+a-u*a),i=[0,0,0];l<3;)(r=s+1/3*-(l-1))<0?r++:r>1&&r--,o=6*r<1?e+6*(n-e)*r:2*r<1?n:3*r<2?e+(n-e)*(2/3-r)*6:e,i[l++]=255*o;return i}};sr.hsl=function(t){var e,n,r=t[0]/255,i=t[1]/255,o=t[2]/255,s=Math.min(r,i,o),a=Math.max(r,i,o),u=a-s;return a===s?e=0:r===a?e=(i-o)/u:i===a?e=2+(o-r)/u:o===a&&(e=4+(r-i)/u),(e=Math.min(60*e,360))<0&&(e+=360),n=(s+a)/2,[e,100*(a===s?0:n<=.5?u/(a+s):u/(2-a-s)),100*n]};const mr={};let yr=0;function br(t){if(4===t.length)return t;const e=t.slice();return e[3]=1,e}function _r(t){const e=ur.lchuv(sr.xyz(t));return e[3]=t[3],e}function vr(t){if(mr.hasOwnProperty(t))return mr[t];if(yr>=1024){let t=0;for(const e in mr)0==(3&t++)&&(delete mr[e],--yr)}const e=function(t){var e;Array.isArray(t)&&t.raw&&(t=String.raw(...arguments)),t instanceof Number&&(t=+t);var n=fr(t);if(!n.space)return[];const r="h"===n.space[0]?gr.min:sr.min,i="h"===n.space[0]?gr.max:sr.max;return(e=Array(3))[0]=Math.min(Math.max(n.values[0],r[0]),i[0]),e[1]=Math.min(Math.max(n.values[1],r[1]),i[1]),e[2]=Math.min(Math.max(n.values[2],r[2]),i[2]),"h"===n.space[0]&&(e=gr.rgb(e)),e.push(Math.min(Math.max(n.alpha,0),1)),e}(t);if(4!==e.length)throw new Error('Failed to parse "'+t+'" as color');for(const n of e)if(isNaN(n))throw new Error('Failed to parse "'+t+'" as color');return xr(e),mr[t]=e,++yr,e}function wr(t){return Array.isArray(t)?t:vr(t)}function xr(t){return t[0]=Re(t[0]+.5|0,0,255),t[1]=Re(t[1]+.5|0,0,255),t[2]=Re(t[2]+.5|0,0,255),t[3]=Re(t[3],0,1),t}function Tr(t){let e=t[0];e!=(0|e)&&(e=e+.5|0);let n=t[1];n!=(0|n)&&(n=n+.5|0);let r=t[2];r!=(0|r)&&(r=r+.5|0);return"rgba("+e+","+n+","+r+","+(void 0===t[3]?1:Math.round(1e3*t[3])/1e3)+")"}const Sr="undefined"!=typeof navigator&&void 0!==navigator.userAgent?navigator.userAgent.toLowerCase():"",Or=(Sr.includes("firefox"),Sr.includes("safari")&&!Sr.includes("chrom")&&(Sr.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(Sr)),Sr.includes("webkit")&&Sr.includes("edge"),Sr.includes("macintosh"),"undefined"!=typeof devicePixelRatio&&devicePixelRatio,"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&self instanceof WorkerGlobalScope),Er="undefined"!=typeof Image&&Image.prototype.decode;!function(){let t=!1;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("_",null,e),window.removeEventListener("_",null,e)}catch(t){}}();function Ir(t,e,n,r){let i;return i=n&&n.length?n.shift():Or?new OffscreenCanvas(t||300,e||300):document.createElement("canvas"),t&&(i.width=t),e&&(i.height=e),i.getContext("2d",r)}let Ar;function Pr(){return Ar||(Ar=Ir(1,1)),Ar}function Cr(t,e){return e&&(t.src=e),t.src&&Er?new Promise(((e,n)=>t.decode().then((()=>e(t))).catch((r=>t.complete&&t.width?e(t):n(r))))):function(t,e){return new Promise(((n,r)=>{function i(){s(),n(t)}function o(){s(),r(new Error("Image load error"))}function s(){t.removeEventListener("load",i),t.removeEventListener("error",o)}t.addEventListener("load",i),t.addEventListener("error",o),e&&(t.src=e)}))}(t)}class Dr{constructor(){this.cache_={},this.patternCache_={},this.cacheSize_=0,this.maxCacheSize_=32}clear(){this.cache_={},this.patternCache_={},this.cacheSize_=0}canExpireCache(){return this.cacheSize_>this.maxCacheSize_}expire(){if(this.canExpireCache()){let t=0;for(const e in this.cache_){const n=this.cache_[e];0!=(3&t++)||n.hasListener()||(delete this.cache_[e],delete this.patternCache_[e],--this.cacheSize_)}}}get(t,e,n){const r=kr(t,e,n);return r in this.cache_?this.cache_[r]:null}getPattern(t,e,n){const r=kr(t,e,n);return r in this.patternCache_?this.patternCache_[r]:null}set(t,e,n,r,i){const o=kr(t,e,n),s=o in this.cache_;this.cache_[o]=r,i&&(r.getImageState()===Qn&&r.load(),r.getImageState()===tr?r.ready().then((()=>{this.patternCache_[o]=Pr().createPattern(r.getImage(1),"repeat")})):this.patternCache_[o]=Pr().createPattern(r.getImage(1),"repeat")),s||++this.cacheSize_}setSize(t){this.maxCacheSize_=t,this.expire()}}function kr(t,e,n){return e+":"+t+":"+(n?wr(n):"null")}const Rr=new Dr;let Mr=null;class Fr extends A{constructor(t,e,n,r,i){super(),this.hitDetectionImage_=null,this.image_=t,this.crossOrigin_=n,this.canvas_={},this.color_=i,this.imageState_=void 0===r?Qn:r,this.size_=t&&t.width&&t.height?[t.width,t.height]:null,this.src_=e,this.tainted_,this.ready_=null}initializeImage_(){this.image_=new Image,null!==this.crossOrigin_&&(this.image_.crossOrigin=this.crossOrigin_)}isTainted_(){if(void 0===this.tainted_&&this.imageState_===er){Mr||(Mr=Ir(1,1,void 0,{willReadFrequently:!0})),Mr.drawImage(this.image_,0,0);try{Mr.getImageData(0,0,1,1),this.tainted_=!1}catch(t){Mr=null,this.tainted_=!0}}return!0===this.tainted_}dispatchChangeEvent_(){this.dispatchEvent(P)}handleImageError_(){this.imageState_=nr,this.dispatchChangeEvent_()}handleImageLoad_(){this.imageState_=er,this.size_=[this.image_.width,this.image_.height],this.dispatchChangeEvent_()}getImage(t){return this.image_||this.initializeImage_(),this.replaceColor_(t),this.canvas_[t]?this.canvas_[t]:this.image_}getPixelRatio(t){return this.replaceColor_(t),this.canvas_[t]?t:1}getImageState(){return this.imageState_}getHitDetectionImage(){if(this.image_||this.initializeImage_(),!this.hitDetectionImage_)if(this.isTainted_()){const t=this.size_[0],e=this.size_[1],n=Ir(t,e);n.fillRect(0,0,t,e),this.hitDetectionImage_=n.canvas}else this.hitDetectionImage_=this.image_;return this.hitDetectionImage_}getSize(){return this.size_}getSrc(){return this.src_}load(){if(this.imageState_===Qn){this.image_||this.initializeImage_(),this.imageState_=tr;try{void 0!==this.src_&&(this.image_.src=this.src_)}catch(t){this.handleImageError_()}this.image_ instanceof HTMLImageElement&&Cr(this.image_,this.src_).then((t=>{this.image_=t,this.handleImageLoad_()})).catch(this.handleImageError_.bind(this))}}replaceColor_(t){if(!this.color_||this.canvas_[t]||this.imageState_!==er)return;const e=this.image_,n=document.createElement("canvas");n.width=Math.ceil(e.width*t),n.height=Math.ceil(e.height*t);const r=n.getContext("2d");var i;r.scale(t,t),r.drawImage(e,0,0),r.globalCompositeOperation="multiply",r.fillStyle="string"==typeof(i=this.color_)?i:Tr(i),r.fillRect(0,0,n.width/t,n.height/t),r.globalCompositeOperation="destination-in",r.drawImage(e,0,0),this.canvas_[t]=n}ready(){return this.ready_||(this.ready_=new Promise((t=>{this.imageState_===er||this.imageState_===nr?t():this.addEventListener(P,(function e(){this.imageState_!==er&&this.imageState_!==nr||(this.removeEventListener(P,e),t())}))}))),this.ready_}}function Lr(t,e,n,r,i,o){let s=void 0===e?void 0:Rr.get(e,n,i);return s||(s=new Fr(t,t&&"src"in t?t.src||void 0:e,n,r,i),Rr.set(e,n,i,s,o)),o&&s&&!Rr.getPattern(e,n,i)&&Rr.set(e,n,i,s,o),s}function $r(t){return t?Array.isArray(t)?Tr(t):"object"==typeof t&&"src"in t?function(t){if(!t.offset||!t.size)return Rr.getPattern(t.src,"anonymous",t.color);const e=t.src+":"+t.offset,n=Rr.getPattern(e,void 0,t.color);if(n)return n;const r=Rr.get(t.src,"anonymous",null);if(r.getImageState()!==er)return null;const i=Ir(t.size[0],t.size[1]);return i.drawImage(r.getImage(1),t.offset[0],t.offset[1],t.size[0],t.size[1],0,0,t.size[0],t.size[1]),Lr(i.canvas,e,void 0,er,t.color,!0),Rr.getPattern(e,void 0,t.color)}(t):t:null}const Nr=new RegExp(["^\\s*(?=(?:(?:[-a-z]+\\s*){0,2}(italic|oblique))?)","(?=(?:(?:[-a-z]+\\s*){0,2}(small-caps))?)","(?=(?:(?:[-a-z]+\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)","(?:(?:normal|\\1|\\2|\\3)\\s*){0,3}((?:xx?-)?","(?:small|large)|medium|smaller|larger|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx]))","(?:\\s*\\/\\s*(normal|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx])?))","?\\s*([-,\\\"\\'\\sa-z]+?)\\s*$"].join(""),"i"),jr=["style","variant","weight","size","lineHeight","family"],Br=function(t){const e=t.match(Nr);if(!e)return null;const n={lineHeight:"normal",size:"1.2em",style:"normal",weight:"normal",variant:"normal"};for(let t=0,r=jr.length;tMath.max(e,ri(t,n))),0);return n[e]=r,r}function oi(t,e,n,r,i,o,s,a,u,l,c){t.save(),1!==n&&(void 0===t.globalAlpha?t.globalAlpha=t=>t.globalAlpha*=n:t.globalAlpha*=n),e&&t.transform.apply(t,e),r.contextInstructions?(t.translate(u,l),t.scale(c[0],c[1]),function(t,e){const n=t.contextInstructions;for(let t=0,r=n.length;tthis.imageState_=er)),this.render()}clone(){const t=this.getScale(),e=new si({fill:this.getFill()?this.getFill().clone():void 0,points:this.getPoints(),radius:this.getRadius(),radius2:this.getRadius2(),angle:this.getAngle(),stroke:this.getStroke()?this.getStroke().clone():void 0,rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(t)?t.slice():t,displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()});return e.setOpacity(this.getOpacity()),e}getAnchor(){const t=this.size_,e=this.getDisplacement(),n=this.getScaleArray();return[t[0]/2-e[0]/n[0],t[1]/2+e[1]/n[1]]}getAngle(){return this.angle_}getFill(){return this.fill_}setFill(t){this.fill_=t,this.render()}getHitDetectionImage(){return this.hitDetectionCanvas_||(this.hitDetectionCanvas_=this.createHitDetectionCanvas_(this.renderOptions_)),this.hitDetectionCanvas_}getImage(t){let e=this.canvases_[t];if(!e){const n=this.renderOptions_,r=Ir(n.size*t,n.size*t);this.draw_(n,r,t),e=r.canvas,this.canvases_[t]=e}return e}getPixelRatio(t){return t}getImageSize(){return this.size_}getImageState(){return this.imageState_}getOrigin(){return this.origin_}getPoints(){return this.points_}getRadius(){return this.radius_}getRadius2(){return this.radius2_}getSize(){return this.size_}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t,this.render()}listenImageChange(t){}load(){}unlistenImageChange(t){}calculateLineJoinSize_(t,e,n){if(0===e||this.points_===1/0||"bevel"!==t&&"miter"!==t)return e;let r=this.radius_,i=void 0===this.radius2_?r:this.radius2_;if(r{this.patternImage_=null})),e.getImageState()===Qn&&e.load(),e.getImageState()===tr&&(this.patternImage_=e)}this.color_=t}loading(){return!!this.patternImage_}ready(){return this.patternImage_?this.patternImage_.ready():Promise.resolve()}}const hi=ci;class di{constructor(t){t=t||{},this.color_=void 0!==t.color?t.color:null,this.lineCap_=t.lineCap,this.lineDash_=void 0!==t.lineDash?t.lineDash:null,this.lineDashOffset_=t.lineDashOffset,this.lineJoin_=t.lineJoin,this.miterLimit_=t.miterLimit,this.width_=t.width}clone(){const t=this.getColor();return new di({color:Array.isArray(t)?t.slice():t||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(t){this.color_=t}setLineCap(t){this.lineCap_=t}setLineDash(t){this.lineDash_=t}setLineDashOffset(t){this.lineDashOffset_=t}setLineJoin(t){this.lineJoin_=t}setMiterLimit(t){this.miterLimit_=t}setWidth(t){this.width_=t}}const fi=di;class pi{constructor(t){t=t||{},this.geometry_=null,this.geometryFunction_=yi,void 0!==t.geometry&&this.setGeometry(t.geometry),this.fill_=void 0!==t.fill?t.fill:null,this.image_=void 0!==t.image?t.image:null,this.renderer_=void 0!==t.renderer?t.renderer:null,this.hitDetectionRenderer_=void 0!==t.hitDetectionRenderer?t.hitDetectionRenderer:null,this.stroke_=void 0!==t.stroke?t.stroke:null,this.text_=void 0!==t.text?t.text:null,this.zIndex_=t.zIndex}clone(){let t=this.getGeometry();return t&&"object"==typeof t&&(t=t.clone()),new pi({geometry:t??void 0,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer()??void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(t){this.renderer_=t}setHitDetectionRenderer(t){this.hitDetectionRenderer_=t}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(t){this.fill_=t}getImage(){return this.image_}setImage(t){this.image_=t}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t}getText(){return this.text_}setText(t){this.text_=t}getZIndex(){return this.zIndex_}setGeometry(t){"function"==typeof t?this.geometryFunction_=t:"string"==typeof t?this.geometryFunction_=function(e){return e.get(t)}:t?void 0!==t&&(this.geometryFunction_=function(){return t}):this.geometryFunction_=yi,this.geometry_=t}setZIndex(t){this.zIndex_=t}}let gi=null;function mi(t,e){if(!gi){const t=new hi({color:"rgba(255,255,255,0.4)"}),e=new fi({color:"#3399CC",width:1.25});gi=[new pi({image:new li({fill:t,stroke:e,radius:5}),fill:t,stroke:e})]}return gi}function yi(t){return t.getGeometry()}const bi=pi;function _i(t,e,n,r){return void 0!==n&&void 0!==r?[n/t,r/e]:void 0!==n?n/t:void 0!==r?r/e:1}class vi extends or{constructor(t){const e=void 0!==(t=t||{}).opacity?t.opacity:1,n=void 0!==t.rotation?t.rotation:0,r=void 0!==t.scale?t.scale:1,i=void 0!==t.rotateWithView&&t.rotateWithView;super({opacity:e,rotation:n,scale:r,displacement:void 0!==t.displacement?t.displacement:[0,0],rotateWithView:i,declutterMode:t.declutterMode}),this.anchor_=void 0!==t.anchor?t.anchor:[.5,.5],this.normalizedAnchor_=null,this.anchorOrigin_=void 0!==t.anchorOrigin?t.anchorOrigin:"top-left",this.anchorXUnits_=void 0!==t.anchorXUnits?t.anchorXUnits:"fraction",this.anchorYUnits_=void 0!==t.anchorYUnits?t.anchorYUnits:"fraction",this.crossOrigin_=void 0!==t.crossOrigin?t.crossOrigin:null;const o=void 0!==t.img?t.img:null;let s,a=t.src;if(B(!(void 0!==a&&o),"`image` and `src` cannot be provided at the same time"),void 0!==a&&0!==a.length||!o||(a=o.src||$(o)),B(void 0!==a&&a.length>0,"A defined and non-empty `src` or `image` must be provided"),B(!((void 0!==t.width||void 0!==t.height)&&void 0!==t.scale),"`width` or `height` cannot be provided together with `scale`"),void 0!==t.src?s=Qn:void 0!==o&&(s="complete"in o?o.complete?o.src?er:Qn:tr:er),this.color_=void 0!==t.color?wr(t.color):null,this.iconImage_=Lr(o,a,this.crossOrigin_,s,this.color_),this.offset_=void 0!==t.offset?t.offset:[0,0],this.offsetOrigin_=void 0!==t.offsetOrigin?t.offsetOrigin:"top-left",this.origin_=null,this.size_=void 0!==t.size?t.size:null,void 0!==t.width||void 0!==t.height){let e,n;if(t.size)[e,n]=t.size;else{const r=this.getImage(1);if(r.width&&r.height)e=r.width,n=r.height;else if(r instanceof HTMLImageElement){this.initialOptions_=t;const e=()=>{if(this.unlistenImageChange(e),!this.initialOptions_)return;const n=this.iconImage_.getSize();this.setScale(_i(n[0],n[1],t.width,t.height))};return void this.listenImageChange(e)}}void 0!==e&&this.setScale(_i(e,n,t.width,t.height))}}clone(){let t,e,n;return this.initialOptions_?(e=this.initialOptions_.width,n=this.initialOptions_.height):(t=this.getScale(),t=Array.isArray(t)?t.slice():t),new vi({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||void 0,crossOrigin:this.crossOrigin_,offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,opacity:this.getOpacity(),rotateWithView:this.getRotateWithView(),rotation:this.getRotation(),scale:t,width:e,height:n,size:null!==this.size_?this.size_.slice():void 0,src:this.getSrc(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getAnchor(){let t=this.normalizedAnchor_;if(!t){t=this.anchor_;const e=this.getSize();if("fraction"==this.anchorXUnits_||"fraction"==this.anchorYUnits_){if(!e)return null;t=this.anchor_.slice(),"fraction"==this.anchorXUnits_&&(t[0]*=e[0]),"fraction"==this.anchorYUnits_&&(t[1]*=e[1])}if("top-left"!=this.anchorOrigin_){if(!e)return null;t===this.anchor_&&(t=this.anchor_.slice()),"top-right"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[0]=-t[0]+e[0]),"bottom-left"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[1]=-t[1]+e[1])}this.normalizedAnchor_=t}const e=this.getDisplacement(),n=this.getScaleArray();return[t[0]-e[0]/n[0],t[1]+e[1]/n[1]]}setAnchor(t){this.anchor_=t,this.normalizedAnchor_=null}getColor(){return this.color_}getImage(t){return this.iconImage_.getImage(t)}getPixelRatio(t){return this.iconImage_.getPixelRatio(t)}getImageSize(){return this.iconImage_.getSize()}getImageState(){return this.iconImage_.getImageState()}getHitDetectionImage(){return this.iconImage_.getHitDetectionImage()}getOrigin(){if(this.origin_)return this.origin_;let t=this.offset_;if("top-left"!=this.offsetOrigin_){const e=this.getSize(),n=this.iconImage_.getSize();if(!e||!n)return null;t=t.slice(),"top-right"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[0]=n[0]-e[0]-t[0]),"bottom-left"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[1]=n[1]-e[1]-t[1])}return this.origin_=t,this.origin_}getSrc(){return this.iconImage_.getSrc()}getSize(){return this.size_?this.size_:this.iconImage_.getSize()}getWidth(){const t=this.getScaleArray();return this.size_?this.size_[0]*t[0]:this.iconImage_.getImageState()==er?this.iconImage_.getSize()[0]*t[0]:void 0}getHeight(){const t=this.getScaleArray();return this.size_?this.size_[1]*t[1]:this.iconImage_.getImageState()==er?this.iconImage_.getSize()[1]*t[1]:void 0}setScale(t){delete this.initialOptions_,super.setScale(t)}listenImageChange(t){this.iconImage_.addEventListener(P,t)}load(){this.iconImage_.load()}unlistenImageChange(t){this.iconImage_.removeEventListener(P,t)}ready(){return this.iconImage_.ready()}}const wi=vi;class xi{constructor(t){t=t||{},this.font_=t.font,this.rotation_=t.rotation,this.rotateWithView_=t.rotateWithView,this.scale_=t.scale,this.scaleArray_=rr(void 0!==t.scale?t.scale:1),this.text_=t.text,this.textAlign_=t.textAlign,this.justify_=t.justify,this.repeat_=t.repeat,this.textBaseline_=t.textBaseline,this.fill_=void 0!==t.fill?t.fill:new hi({color:"#333"}),this.maxAngle_=void 0!==t.maxAngle?t.maxAngle:Math.PI/4,this.placement_=void 0!==t.placement?t.placement:"point",this.overflow_=!!t.overflow,this.stroke_=void 0!==t.stroke?t.stroke:null,this.offsetX_=void 0!==t.offsetX?t.offsetX:0,this.offsetY_=void 0!==t.offsetY?t.offsetY:0,this.backgroundFill_=t.backgroundFill?t.backgroundFill:null,this.backgroundStroke_=t.backgroundStroke?t.backgroundStroke:null,this.padding_=void 0===t.padding?null:t.padding,this.declutterMode_=t.declutterMode}clone(){const t=this.getScale();return new xi({font:this.getFont(),placement:this.getPlacement(),repeat:this.getRepeat(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(t)?t.slice():t,text:this.getText(),textAlign:this.getTextAlign(),justify:this.getJustify(),textBaseline:this.getTextBaseline(),fill:this.getFill()?this.getFill().clone():void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),backgroundFill:this.getBackgroundFill()?this.getBackgroundFill().clone():void 0,backgroundStroke:this.getBackgroundStroke()?this.getBackgroundStroke().clone():void 0,padding:this.getPadding()||void 0,declutterMode:this.getDeclutterMode()})}getOverflow(){return this.overflow_}getFont(){return this.font_}getMaxAngle(){return this.maxAngle_}getPlacement(){return this.placement_}getRepeat(){return this.repeat_}getOffsetX(){return this.offsetX_}getOffsetY(){return this.offsetY_}getFill(){return this.fill_}getRotateWithView(){return this.rotateWithView_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getStroke(){return this.stroke_}getText(){return this.text_}getTextAlign(){return this.textAlign_}getJustify(){return this.justify_}getTextBaseline(){return this.textBaseline_}getBackgroundFill(){return this.backgroundFill_}getBackgroundStroke(){return this.backgroundStroke_}getPadding(){return this.padding_}getDeclutterMode(){return this.declutterMode_}setOverflow(t){this.overflow_=t}setFont(t){this.font_=t}setMaxAngle(t){this.maxAngle_=t}setOffsetX(t){this.offsetX_=t}setOffsetY(t){this.offsetY_=t}setPlacement(t){this.placement_=t}setRepeat(t){this.repeat_=t}setRotateWithView(t){this.rotateWithView_=t}setFill(t){this.fill_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=rr(void 0!==t?t:1)}setStroke(t){this.stroke_=t}setText(t){this.text_=t}setTextAlign(t){this.textAlign_=t}setJustify(t){this.justify_=t}setTextBaseline(t){this.textBaseline_=t}setBackgroundFill(t){this.backgroundFill_=t}setBackgroundStroke(t){this.backgroundStroke_=t}setPadding(t){this.padding_=t}}const Ti=xi;let Si=0;const Oi=1<void 0!==e?function(t){switch(t){case"string":return Ii;case"color":return Ai;case"number":return Ei;case"boolean":return Oi;case"number[]":return Pi;default:throw new Error(`Unrecognized type hint: ${t}`)}}(e.value):Di),Fo(1,2),(function(t,e){const n=Bi(t[1],e);if(!(n instanceof $i))throw new Error("Expected a literal argument for get operation");if("string"!=typeof n.value)throw new Error("Expected a string argument for get operation");if(e.properties.add(n.value),3===t.length){const r=Bi(t[2],e);return[n,r]}return[n]})),[Vi]:jo((([t])=>t.type),Fo(1,1),(function(t,e,n,r){const i=t[1];if("string"!=typeof i)throw new Error("Expected a string argument for var operation");if(e.variables.add(i),!("variables"in e.style)||void 0===e.style.variables[i])return[new $i(Di,i)];const o=Bi(e.style.variables[i],e);if(o.value=i,r&&!Fi(r,o.type))throw new Error(`The variable ${i} has type ${Mi(o.type)} but the following type was expected: ${Mi(r)}`);return[o]})),[Po]:jo(Ei|Ii,Mo,(function(t,e){e.featureId=!0})),[zi]:jo(Ii,Fo(2,1/0),Lo(Di)),[Gi]:jo(Ii,Mo,(function(t,e){e.geometryType=!0})),[Xi]:jo(Ei,Mo),[Yi]:jo(Ei,Mo),[Ki]:jo(Ei,Mo),[Wi]:jo(Oi,Fo(2,1/0),Lo(Oi)),[Hi]:jo(Oi,Fo(2,1/0),Lo(Oi)),[qi]:jo(Oi,Fo(1,1),Lo(Oi)),[Zi]:jo(Oi,Fo(2,2),Lo(Di),$o),[Ji]:jo(Oi,Fo(2,2),Lo(Di),$o),[Qi]:jo(Oi,Fo(2,2),Lo(Di),$o),[to]:jo(Oi,Fo(2,2),Lo(Di),$o),[eo]:jo(Oi,Fo(2,2),Lo(Di),$o),[no]:jo(Oi,Fo(2,2),Lo(Di),$o),[ro]:jo((t=>{let e=Ei|Ai;for(let n=0;n{let e=Di;for(let n=1;n{let e=Di;for(let n=2;n{let e=Ai|Ei;for(let n=3;n{let e=Di;for(let n=1;n2===t.length?Pi|Ci:3===t.length||4===t.length?Pi|Ai:Pi),Fo(1,1/0),Lo(Ei)),[Ao]:jo(Ai,Fo(1,4),Lo(Ei)),[Co]:jo(Ei,Fo(1,3),Lo(Ei)),[Do]:jo(Ai,Fo(2,2),(function(t,e){const n=Bi(t[1],e,Ei);if(n.type!==Ei)throw new Error(`The first argument of palette must be an number, got ${Mi(n.type)} instead`);const r=t[2];if(!Array.isArray(r))throw new Error("The second argument of palette must be an array");const i=new Array(r.length);for(let t=0;te){throw new Error(`Expected ${e===1/0?`${t} or more`:`${t} to ${e}`} arguments for ${i}, got ${o}`)}}}function Lo(t){return function(e,n){const r=e[0],i=e.length-1,o=new Array(i);for(let s=0;s{for(let e=0;e{for(let e=0;et.properties[n];case Vi:return t=>t.variables[n];default:throw new Error(`Unsupported accessor operator ${t.operator}`)}}(t);case Po:return t=>t.featureId;case Gi:return t=>t.geometryType;case zi:{const n=t.args.map((t=>Vo(t,e)));return t=>"".concat(...n.map((e=>e(t).toString())))}case Xi:return t=>t.resolution;case Wi:case Hi:case vo:case So:case qi:return function(t,e){const n=t.operator,r=t.args.length,i=new Array(r);for(let n=0;n{for(let e=0;e{for(let e=0;e{const e=i[0](t),n=i[1](t),r=i[2](t);return e>=n&&e<=r};case So:return t=>{const e=i[0](t);for(let n=1;n!i[0](t);default:throw new Error(`Unsupported logical operator ${n}`)}}(t,e);case Zi:case Ji:case eo:case no:case Qi:case to:return function(t,e){const n=t.operator,r=Vo(t.args[0],e),i=Vo(t.args[1],e);switch(n){case Zi:return t=>r(t)===i(t);case Ji:return t=>r(t)!==i(t);case eo:return t=>r(t)r(t)<=i(t);case Qi:return t=>r(t)>i(t);case to:return t=>r(t)>=i(t);default:throw new Error(`Unsupported comparison operator ${n}`)}}(t,e);case ro:case io:case oo:case so:case ao:case uo:case lo:case co:case ho:case fo:case po:case go:case mo:case yo:case bo:return function(t,e){const n=t.operator,r=t.args.length,i=new Array(r);for(let n=0;n{let e=1;for(let n=0;ni[0](t)/i[1](t);case oo:return t=>{let e=0;for(let n=0;ni[0](t)-i[1](t);case ao:return t=>{const e=i[0](t),n=i[1](t);if(er?r:e};case uo:return t=>i[0](t)%i[1](t);case lo:return t=>Math.pow(i[0](t),i[1](t));case co:return t=>Math.abs(i[0](t));case ho:return t=>Math.floor(i[0](t));case fo:return t=>Math.ceil(i[0](t));case po:return t=>Math.round(i[0](t));case go:return t=>Math.sin(i[0](t));case mo:return t=>Math.cos(i[0](t));case yo:return 2===r?t=>Math.atan2(i[0](t),i[1](t)):t=>Math.atan(i[0](t));case bo:return t=>Math.sqrt(i[0](t));default:throw new Error(`Unsupported numeric operator ${n}`)}}(t,e);case To:return function(t,e){const n=t.args.length,r=new Array(n);for(let i=0;i{for(let e=0;e{const e=r[0](t);for(let i=1;i{const e=r[0](t),i=r[1](t);let o,s;for(let a=2;a=i)return 2===a?u:l?Go(e,i,o,s,n,u):zo(e,i,o,s,n,u);o=n,s=u}return s}}(t,e);case ko:return function(t,e){const n=t.operator,r=t.args.length,i=new Array(r);for(let n=0;n{const n=i[0](e);return t.args[0].type===Ai?Tr(n):n.toString()};throw new Error(`Unsupported convert operator ${n}`)}(t,e);default:throw new Error(`Unsupported operator ${n}`)}}function zo(t,e,n,r,i,o){const s=i-n;if(0===s)return r;const a=e-n;return r+(1===t?a/s:(Math.pow(t,a)-1)/(Math.pow(t,s)-1))*(o-r)}function Go(t,e,n,r,i,o){if(0===i-n)return r;const s=_r(r),a=_r(o);let u=a[2]-s[2];u>180?u-=360:u<-180&&(u+=360);return xr(function(t){const e=ur.rgb(hr.xyz(t));return e[3]=t[3],e}([zo(t,e,n,s[0],i,a[0]),zo(t,e,n,s[1],i,a[1]),s[2]+zo(t,e,n,0,i,u),zo(t,e,n,r[3],i,o[3])]))}function Wo(t){return!0}function Ho(t){const e=ji(),n=function(t,e){const n=t.length,r=new Array(n);for(let i=0;i4)throw new Error(`Expected a color with 3 or 4 values for ${e}`);return n}function fs(t,e){const n=ls(t,e);if(2!==n.length)throw new Error(`Expected an array of two numbers for ${e}`);return n}const ps="renderOrder";const gs=class extends Zn{constructor(t){t=t||{};const e=Object.assign({},t);delete e.style,delete e.renderBuffer,delete e.updateWhileAnimating,delete e.updateWhileInteracting,super(e),this.declutter_=t.declutter?String(t.declutter):void 0,this.renderBuffer_=void 0!==t.renderBuffer?t.renderBuffer:100,this.style_=null,this.styleFunction_=void 0,this.setStyle(t.style),this.updateWhileAnimating_=void 0!==t.updateWhileAnimating&&t.updateWhileAnimating,this.updateWhileInteracting_=void 0!==t.updateWhileInteracting&&t.updateWhileInteracting}getDeclutter(){return this.declutter_}getFeatures(t){return super.getFeatures(t)}getRenderBuffer(){return this.renderBuffer_}getRenderOrder(){return this.get(ps)}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}getUpdateWhileAnimating(){return this.updateWhileAnimating_}getUpdateWhileInteracting(){return this.updateWhileInteracting_}renderDeclutter(t,e){const n=this.getDeclutter();n in t.declutter==!1&&(t.declutter[n]=new Jn(9)),this.getRenderer().renderDeclutter(t,e)}setRenderOrder(t){this.set(ps,t)}setStyle(t){this.style_=void 0===t?mi:t;const e=function(t){if(void 0===t)return mi;if(!t)return null;if("function"==typeof t)return t;if(t instanceof bi)return t;if(!Array.isArray(t))return qo([t]);if(0===t.length)return[];const e=t.length,n=t[0];if(n instanceof bi){const n=new Array(e);for(let r=0;ra&&(this.instructions.push([ws.CUSTOM,a,l,t,n,Ze,i]),this.hitDetectionInstructions.push([ws.CUSTOM,a,l,t,r||n,Ze,i]));break;case"Point":u=t.getFlatCoordinates(),this.coordinates.push(u[0],u[1]),l=this.coordinates.length,this.instructions.push([ws.CUSTOM,a,l,t,n,void 0,i]),this.hitDetectionInstructions.push([ws.CUSTOM,a,l,t,r||n,void 0,i])}this.endGeometry(e)}beginGeometry(t,e,n){this.beginGeometryInstruction1_=[ws.BEGIN_GEOMETRY,e,0,t,n],this.instructions.push(this.beginGeometryInstruction1_),this.beginGeometryInstruction2_=[ws.BEGIN_GEOMETRY,e,0,t,n],this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)}finish(){return{instructions:this.instructions,hitDetectionInstructions:this.hitDetectionInstructions,coordinates:this.coordinates}}reverseHitDetectionInstructions(){const t=this.hitDetectionInstructions;let e;t.reverse();const n=t.length;let r,i,o=-1;for(e=0;ethis.maxLineWidth&&(this.maxLineWidth=n.lineWidth,this.bufferedMaxExtent_=null)}else n.strokeStyle=void 0,n.lineCap=void 0,n.lineDash=null,n.lineDashOffset=void 0,n.lineJoin=void 0,n.lineWidth=void 0,n.miterLimit=void 0}createFill(t){const e=t.fillStyle,n=[ws.SET_FILL_STYLE,e];return"string"!=typeof e&&n.push(t.fillPatternScale),n}applyStroke(t){this.instructions.push(this.createStroke(t))}createStroke(t){return[ws.SET_STROKE_STYLE,t.strokeStyle,t.lineWidth*this.pixelRatio,t.lineCap,t.lineJoin,t.miterLimit,this.applyPixelRatio(t.lineDash),t.lineDashOffset*this.pixelRatio]}updateFillStyle(t,e){const n=t.fillStyle;"string"==typeof n&&t.currentFillStyle==n||(void 0!==n&&this.instructions.push(e.call(this,t)),t.currentFillStyle=n)}updateStrokeStyle(t,e){const n=t.strokeStyle,r=t.lineCap,i=t.lineDash,o=t.lineDashOffset,s=t.lineJoin,a=t.lineWidth,u=t.miterLimit;(t.currentStrokeStyle!=n||t.currentLineCap!=r||i!=t.currentLineDash&&!x(t.currentLineDash,i)||t.currentLineDashOffset!=o||t.currentLineJoin!=s||t.currentLineWidth!=a||t.currentMiterLimit!=u)&&(void 0!==n&&e.call(this,t),t.currentStrokeStyle=n,t.currentLineCap=r,t.currentLineDash=i,t.currentLineDashOffset=o,t.currentLineJoin=s,t.currentLineWidth=a,t.currentMiterLimit=u)}endGeometry(t){this.beginGeometryInstruction1_[2]=this.instructions.length,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length,this.beginGeometryInstruction2_=null;const e=[ws.END_GEOMETRY,t];this.instructions.push(e),this.hitDetectionInstructions.push(e)}getBufferedMaxExtent(){if(!this.bufferedMaxExtent_&&(this.bufferedMaxExtent_=(t=this.maxExtent,e?(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e):t.slice()),this.maxLineWidth>0)){const t=this.resolution*(this.maxLineWidth+1)/2;ht(this.bufferedMaxExtent_,t,this.bufferedMaxExtent_)}var t,e;return this.bufferedMaxExtent_}};const Ss=class extends Ts{constructor(t,e,n,r){super(t,e,n,r),this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.anchorX_=void 0,this.anchorY_=void 0,this.height_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.scale_=void 0,this.width_=void 0,this.declutterMode_=void 0,this.declutterImageWithText_=void 0}drawPoint(t,e,n){if(!this.image_||this.maxExtent&&!ft(this.maxExtent,t.getFlatCoordinates()))return;this.beginGeometry(t,e,n);const r=t.getFlatCoordinates(),i=t.getStride(),o=this.coordinates.length,s=this.appendFlatPointCoordinates(r,i);this.instructions.push([ws.DRAW_IMAGE,o,s,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([ws.DRAW_IMAGE,o,s,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(e)}drawMultiPoint(t,e,n){if(!this.image_)return;this.beginGeometry(t,e,n);const r=t.getFlatCoordinates(),i=[];for(let e=0,n=r.length;e=t){const e=(t-a+h)/h,d=$e(n,l,e),f=$e(r,c,e);u.push(d,f),o.push(u),u=[d,f],a==t&&(s+=i),a=0}else if(a0&&o.push(u),o}function As(t,e,n,r,i){let o,s,a,u,l,c,h,d,f,p,g=n,m=n,y=0,b=0,_=n;for(s=n;st&&(b>y&&(y=b,g=_,m=s),b=0,_=s-i)),a=u,h=f,d=p),l=n,c=r}return b+=u,b>y?[_,s]:[g,m]}const Ps={left:0,center:.5,right:1,top:0,middle:.5,hanging:.2,alphabetic:.8,ideographic:.8,bottom:1};const Cs=class extends Ts{constructor(t,e,n,r){super(t,e,n,r),this.labels_=null,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=void 0,this.textRotation_=0,this.textFillState_=null,this.fillStates={},this.fillStates["#000"]={fillStyle:Vr},this.textStrokeState_=null,this.strokeStates={},this.textState_={},this.textStates={},this.textKey_="",this.fillKey_="",this.strokeKey_="",this.declutterMode_=void 0,this.declutterImageWithText_=void 0}finish(){const t=super.finish();return t.textStates=this.textStates,t.fillStates=this.fillStates,t.strokeStates=this.strokeStates,t}drawText(t,e,n){const r=this.textFillState_,i=this.textStrokeState_,o=this.textState_;if(""===this.text_||!o||!r&&!i)return;const s=this.coordinates;let a=s.length;const u=t.getType();let l=null,c=t.getStride();if("line"!==o.placement||"LineString"!=u&&"MultiLineString"!=u&&"Polygon"!=u&&"MultiPolygon"!=u){let r=o.overflow?null:[];switch(u){case"Point":case"MultiPoint":l=t.getFlatCoordinates();break;case"LineString":l=t.getFlatMidpoint();break;case"Circle":l=t.getCenter();break;case"MultiLineString":l=t.getFlatMidpoints(),c=2;break;case"Polygon":l=t.getFlatInteriorPoint(),o.overflow||r.push(l[2]/this.resolution),c=3;break;case"MultiPolygon":const e=t.getFlatInteriorPoints();l=[];for(let t=0,n=e.length;t{const r=s[2*(t+n)]===l[n*c]&&s[2*(t+n)+1]===l[n*c+1];return r||--t,r}))}this.saveTextStates_(),(o.backgroundFill||o.backgroundStroke)&&(this.setFillStrokeStyle(o.backgroundFill,o.backgroundStroke),o.backgroundFill&&this.updateFillStyle(this.state,this.createFill),o.backgroundStroke&&(this.updateStrokeStyle(this.state,this.applyStroke),this.hitDetectionInstructions.push(this.createStroke(this.state)))),this.beginGeometry(t,e,n);let h=o.padding;if(h!=Yr&&(o.scale[0]<0||o.scale[1]<0)){let t=o.padding[0],e=o.padding[1],n=o.padding[2],r=o.padding[3];o.scale[0]<0&&(e=-e,r=-r),o.scale[1]<0&&(t=-t,n=-n),h=[t,e,n,r]}const d=this.pixelRatio;this.instructions.push([ws.DRAW_IMAGE,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[1,1],NaN,this.declutterMode_,this.declutterImageWithText_,h==Yr?Yr:h.map((function(t){return t*d})),!!o.backgroundFill,!!o.backgroundStroke,this.text_,this.textKey_,this.strokeKey_,this.fillKey_,this.textOffsetX_,this.textOffsetY_,r]);const f=1/d,p=this.state.fillStyle;o.backgroundFill&&(this.state.fillStyle=Vr,this.hitDetectionInstructions.push(this.createFill(this.state))),this.hitDetectionInstructions.push([ws.DRAW_IMAGE,a,i,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[f,f],NaN,this.declutterMode_,this.declutterImageWithText_,h,!!o.backgroundFill,!!o.backgroundStroke,this.text_,this.textKey_,this.strokeKey_,this.fillKey_?Vr:this.fillKey_,this.textOffsetX_,this.textOffsetY_,r]),o.backgroundFill&&(this.state.fillStyle=p,this.hitDetectionInstructions.push(this.createFill(this.state))),this.endGeometry(e)}else{if(!Rt(this.maxExtent,t.getExtent()))return;let r;if(l=t.getFlatCoordinates(),"LineString"==u)r=[l.length];else if("MultiLineString"==u)r=t.getEnds();else if("Polygon"==u)r=t.getEnds().slice(0,1);else if("MultiPolygon"==u){const e=t.getEndss();r=[];for(let t=0,n=e.length;t{const o=this.loadedTileCallback.bind(this,n,r);return t.forEachLoadedTile(e,r,i,o)}}forEachFeatureAtCoordinate(t,e,n,r,i){}getLayer(){return this.layer_}handleFontsChanged(){}handleImageChange_(t){const e=t.target;e.getState()!==er&&e.getState()!==nr||this.renderIfReadyAndVisible()}loadImage(t){let e=t.getState();return e!=er&&e!=nr&&t.addEventListener(P,this.boundHandleImageChange_),e==Qn&&(t.load(),e=t.getState()),e==er}renderIfReadyAndVisible(){const t=this.getLayer();t&&t.getVisible()&&"ready"===t.getSourceState()&&t.changed()}renderDeferred(t){}disposeInternal(){delete this.layer_,super.disposeInternal()}};const Ms=class extends g{constructor(t,e,n,r){super(t),this.inversePixelTransform=e,this.frameState=n,this.context=r}};const Fs=class{constructor(){this.instructions_=[],this.zIndex=0,this.offset_=0,this.context_=new Proxy(Pr(),{get:(t,e)=>{if("function"==typeof Pr()[e])return this.instructions_[this.zIndex+this.offset_]||(this.instructions_[this.zIndex+this.offset_]=[]),this.instructions_[this.zIndex+this.offset_].push(e),this.pushMethodArgs_},set:(t,e,n)=>(this.instructions_[this.zIndex+this.offset_]||(this.instructions_[this.zIndex+this.offset_]=[]),this.instructions_[this.zIndex+this.offset_].push(e,n),!0)})}pushMethodArgs_=(...t)=>(this.instructions_[this.zIndex+this.offset_].push(t),this);pushFunction(t){this.instructions_[this.zIndex+this.offset_].push(t)}getContext(){return this.context_}draw(t){this.instructions_.forEach((e=>{for(let n=0,r=e.length;nt[2]}else I=v>O;const A=Math.PI,P=[],C=x+r===e;let D;if(m=0,y=T,d=t[e=x],f=t[e+1],C){b(),D=Math.atan2(f-g,d-p),I&&(D+=D>0?-A:A);const t=(O+v)/2,e=(E+w)/2;return P[0]=[t,e,(S-o)/2,D,i],P}for(let t=0,h=(i=i.replace(/\n/g," ")).length;t0?-A:A),void 0!==D){let t=v-D;if(t+=t>A?-2*A:t<-A?2*A:0,Math.abs(t)>s)return null}D=v;const w=t;let x=0;for(;t0&&t.push("\n",""),t.push(e,""),t}const Ks=class{constructor(t,e,n,r,i){this.overlaps=n,this.pixelRatio=e,this.resolution=t,this.alignAndScaleFill_,this.instructions=r.instructions,this.coordinates=r.coordinates,this.coordinateCache_={},this.renderedTransform_=[1,0,0,1,0,0],this.hitDetectionInstructions=r.hitDetectionInstructions,this.pixelCoordinates_=null,this.viewRotation_=0,this.fillStates=r.fillStates||{},this.strokeStates=r.strokeStates||{},this.textStates=r.textStates||{},this.widths_={},this.labels_={},this.zIndexContext_=i?new Fs:null}getZIndexContext(){return this.zIndexContext_}createLabel(t,e,n,r){const i=t+e+n+r;if(this.labels_[i])return this.labels_[i];const o=r?this.strokeStates[r]:null,s=n?this.fillStates[n]:null,a=this.textStates[e],u=this.pixelRatio,l=[a.scale[0]*u,a.scale[1]*u],c=Array.isArray(t),h=a.justify?Ps[a.justify]:Xs(Array.isArray(t)?t[0]:t,a.textAlign||qr),d=r&&o.lineWidth?o.lineWidth:0,f=c?t:t.split("\n").reduce(Ys,[]),{width:p,height:g,widths:m,heights:y,lineWidths:b}=function(t,e){const n=[],r=[],i=[];let o=0,s=0,a=0,u=0;for(let l=0,c=e.length;l<=c;l+=2){const h=e[l];if("\n"===h||l===c){o=Math.max(o,s),i.push(s),s=0,a+=u,u=0;continue}const d=e[l+1]||t.font,f=ri(d,h);n.push(f),s+=f;const p=ei(d);r.push(p),u=Math.max(u,p)}return{width:o,height:a,widths:n,heights:r,lineWidths:i}}(a,f),_=p+d,v=[],w=(_+2)*l[0],x=(g+d)*l[1],T={width:w<0?Math.floor(w):Math.ceil(w),height:x<0?Math.floor(x):Math.ceil(x),contextInstructions:v};1==l[0]&&1==l[1]||v.push("scale",l),r&&(v.push("strokeStyle",o.strokeStyle),v.push("lineWidth",d),v.push("lineCap",o.lineCap),v.push("lineJoin",o.lineJoin),v.push("miterLimit",o.miterLimit),v.push("setLineDash",[o.lineDash]),v.push("lineDashOffset",o.lineDashOffset)),n&&v.push("fillStyle",s.fillStyle),v.push("textBaseline","middle"),v.push("textAlign","center");const S=.5-h;let O=h*_+S*d;const E=[],I=[];let A,P=0,C=0,D=0,k=0;for(let t=0,e=f.length;tt?t-u:i,_=o+l>e?e-l:o,v=f[3]+b*h[0]+f[1],w=f[0]+_*h[1]+f[2],x=m-f[3],T=y-f[0];let S;return(p||0!==c)&&(Vs[0]=x,Ws[0]=x,Vs[1]=T,zs[1]=T,zs[0]=x+v,Gs[0]=zs[0],Gs[1]=T+w,Ws[1]=Gs[1]),0!==c?(S=et([1,0,0,1,0,0],n,r,1,1,c,-n,-r),tt(S,Vs),tt(S,zs),tt(S,Gs),tt(S,Ws),yt(Math.min(Vs[0],zs[0],Gs[0],Ws[0]),Math.min(Vs[1],zs[1],Gs[1],Ws[1]),Math.max(Vs[0],zs[0],Gs[0],Ws[0]),Math.max(Vs[1],zs[1],Gs[1],Ws[1]),Us)):yt(Math.min(x,x+v),Math.min(T,T+w),Math.max(x,x+v),Math.max(T,T+w),Us),d&&(m=Math.round(m),y=Math.round(y)),{drawImageX:m,drawImageY:y,drawImageW:b,drawImageH:_,originX:u,originY:l,declutterBox:{minX:Us[0],minY:Us[1],maxX:Us[2],maxY:Us[3],value:g},canvasTransform:S,scale:h}}replayImageOrLabel_(t,e,n,r,i,o,s){const a=!(!o&&!s),u=r.declutterBox,l=s?s[2]*r.scale[0]/2:0;return u.minX-l<=e[0]&&u.maxX+l>=0&&u.minY-l<=e[1]&&u.maxY+l>=0&&(a&&this.replayTextBackground_(t,Vs,zs,Gs,Ws,o,s),oi(t,r.canvasTransform,i,n,r.originX,r.originY,r.drawImageW,r.drawImageH,r.drawImageX,r.drawImageY,r.scale)),!0}fill_(t){const e=this.alignAndScaleFill_;if(e){const n=tt(this.renderedTransform_,[0,0]),r=512*this.pixelRatio;t.save(),t.translate(n[0]%r,n[1]%r),1!==e&&t.scale(e,e),t.rotate(this.viewRotation_)}t.fill(),e&&t.restore()}setStrokeStyle_(t,e){t.strokeStyle=e[1],t.lineWidth=e[2],t.lineCap=e[3],t.lineJoin=e[4],t.miterLimit=e[5],t.lineDashOffset=e[7],t.setLineDash(e[6])}drawLabelWithPointPlacement_(t,e,n,r){const i=this.textStates[e],o=this.createLabel(t,e,r,n),s=this.strokeStates[n],a=this.pixelRatio,u=Xs(Array.isArray(t)?t[0]:t,i.textAlign||qr),l=Ps[i.textBaseline||Xr],c=s&&s.lineWidth?s.lineWidth:0;return{label:o,anchorX:u*(o.width/a-2*i.scale[0])+2*(.5-u)*c,anchorY:l*o.height/a+2*(.5-l)*c}}execute_(t,e,n,r,i,o,s,a){const u=this.zIndexContext_;let l;var c,h;this.pixelCoordinates_&&x(n,this.renderedTransform_)?l=this.pixelCoordinates_:(this.pixelCoordinates_||(this.pixelCoordinates_=[]),l=Ie(this.coordinates,0,this.coordinates.length,2,n,this.pixelCoordinates_),c=this.renderedTransform_,h=n,c[0]=h[0],c[1]=h[1],c[2]=h[2],c[3]=h[3],c[4]=h[4],c[5]=h[5]);let d=0;const f=r.length;let p,g,m,y,b,_,v,w,T,S,O,E,I,A=0,P=0,C=0,D=null,k=null;const R=this.coordinateCache_,M=this.viewRotation_,F=Math.round(1e12*Math.atan2(-n[1],n[0]))/1e12,L={context:t,pixelRatio:this.pixelRatio,resolution:this.resolution,rotation:M},$=this.instructions!=r||this.overlaps?0:200;let N,j,B,U;for(;d$&&(this.fill_(t),P=0),C>$&&(t.stroke(),C=0),P||C||(t.beginPath(),b=NaN,_=NaN),++d;break;case ws.CIRCLE:A=n[1];const r=l[A],c=l[A+1],h=l[A+2]-r,f=l[A+3]-c,x=Math.sqrt(h*h+f*f);t.moveTo(r+x,c),t.arc(r,c,x,0,2*Math.PI,!0),++d;break;case ws.ELLIPSE:A=n[1],p=n[2];const V=l[A],z=l[A+1],G=l[A+2],W=l[A+3],H=l[A+4],q=l[A+5],X=l[A+6],Y=l[A+7];if(p-A==8){const e=.2761424*(H-V),n=.2761424*(q-z),r=.2761424*(X-G),i=.2761424*(Y-W);t.moveTo(V,z),t.bezierCurveTo(V-r,z-i,G-e,W-n,G,W),t.bezierCurveTo(G+e,W+n,H-r,q-i,H,q),t.bezierCurveTo(H+r,q+i,X+e,Y+n,X,Y),t.bezierCurveTo(X-e,Y-n,V+r,z+i,V,z)}++d;break;case ws.CLOSE_PATH:t.closePath(),++d;break;case ws.CUSTOM:A=n[1],p=n[2];const K=n[3],Z=n[4],J=n[5];L.geometry=K,L.feature=N,d in R||(R[d]=[]);const Q=R[d];J?J(l,A,p,2,Q):(Q[0]=l[A],Q[1]=l[A+1],Q.length=2),u&&(u.zIndex=n[6]),Z(Q,L),++d;break;case ws.DRAW_IMAGE:A=n[1],p=n[2],T=n[3],g=n[4],m=n[5];let tt=n[6];const et=n[7],nt=n[8],rt=n[9],it=n[10];let ot=n[11];const st=n[12];let at=n[13];y=n[14]||"declutter";const ut=n[15];if(!T&&n.length>=20){S=n[19],O=n[20],E=n[21],I=n[22];const t=this.drawLabelWithPointPlacement_(S,O,E,I);T=t.label,n[3]=T;const e=n[23];g=(t.anchorX-e)*this.pixelRatio,n[4]=g;const r=n[24];m=(t.anchorY-r)*this.pixelRatio,n[5]=m,tt=T.height,n[6]=tt,at=T.width,n[13]=at}let lt,ct,ht,dt;n.length>25&&(lt=n[25]),n.length>17?(ct=n[16],ht=n[17],dt=n[18]):(ct=Yr,ht=!1,dt=!1),it&&F?ot+=M:it||F||(ot-=M);let ft=0;for(;A!Js.includes(t)));const ta={};const ea=class{constructor(t,e,n,r,i,o,s){this.maxExtent_=t,this.overlaps_=r,this.pixelRatio_=n,this.resolution_=e,this.renderBuffer_=o,this.executorsByZIndex_={},this.hitDetectionContext_=null,this.hitDetectionTransform_=[1,0,0,1,0,0],this.renderedContext_=null,this.deferredZIndexContexts_={},this.createExecutors_(i,s)}clip(t,e){const n=this.getClipCoords(e);t.beginPath(),t.moveTo(n[0],n[1]),t.lineTo(n[2],n[3]),t.lineTo(n[4],n[5]),t.lineTo(n[6],n[7]),t.clip()}createExecutors_(t,e){for(const n in t){let r=this.executorsByZIndex_[n];void 0===r&&(r={},this.executorsByZIndex_[n]=r);const i=t[n];for(const t in i){const n=i[t];r[t]=new Ks(this.resolution_,this.pixelRatio_,this.overlaps_,n,e)}}}hasExecutors(t){for(const e in this.executorsByZIndex_){const n=this.executorsByZIndex_[e];for(let e=0,r=t.length;en)break;let a=r[s];a||(a=[],r[s]=a),a.push(4*((t+i)*e+(t+o))+3),i>0&&a.push(4*((t-i)*e+(t+o))+3),o>0&&(a.push(4*((t+i)*e+(t-o))+3),i>0&&a.push(4*((t-i)*e+(t-o))+3))}const i=[];for(let t=0,e=r.length;t0){if(!o||"none"===n||"Image"!==d&&"Text"!==d||o.includes(t)){const n=(h[u]-3)/4,o=r-n%s,a=r-(n/s|0),l=i(t,e,o*o+a*a);if(l)return l}l.clearRect(0,0,s,s);break}}const p=Object.keys(this.executorsByZIndex_).map(Number);let g,m,y,_,v;for(p.sort(b),g=p.length-1;g>=0;--g){const t=p[g].toString();for(y=this.executorsByZIndex_[t],m=Zs.length-1;m>=0;--m)if(d=Zs[m],_=y[d],void 0!==_&&(v=_.executeHitDetection(l,a,n,f,c),v))return v}}getClipCoords(t){const e=this.maxExtent_;if(!e)return null;const n=e[0],r=e[1],i=e[2],o=e[3],s=[n,r,n,o,i,o,i,r];return Ie(s,0,8,2,t,s),s}isEmpty(){return I(this.executorsByZIndex_)}execute(t,e,n,r,i,o,s){const a=Object.keys(this.executorsByZIndex_).map(Number);a.sort(b),o=o||Zs;const u=Zs.length;let l,c,h,d,f;for(s&&a.reverse(),l=0,c=a.length;ld.execute(t,e,n,r,i,s))):d.execute(f,e,n,r,i,s),p&&f.restore(),o){o.offset();const t=a[l]*u+h;this.deferredZIndexContexts_[t]||(this.deferredZIndexContexts_[t]=[]),this.deferredZIndexContexts_[t].push(o)}}}}this.renderedContext_=t}getDeferredZIndexContexts(){return this.deferredZIndexContexts_}getRenderedContext(){return this.renderedContext_}renderDeferred(){const t=this.deferredZIndexContexts_,e=Object.keys(t).map(Number).sort(b);for(let n=0,r=e.length;n{t.draw(this.renderedContext_),t.clear()})),t[e[n]].length=0}};const na=class extends xs{constructor(t,e,n,r,i,o,s){super(),this.context_=t,this.pixelRatio_=e,this.extent_=n,this.transform_=r,this.transformRotation_=r?Ne(Math.atan2(r[1],r[0]),10):0,this.viewRotation_=i,this.squaredTolerance_=o,this.userTransform_=s,this.contextFillState_=null,this.contextStrokeState_=null,this.contextTextState_=null,this.fillState_=null,this.strokeState_=null,this.image_=null,this.imageAnchorX_=0,this.imageAnchorY_=0,this.imageHeight_=0,this.imageOpacity_=0,this.imageOriginX_=0,this.imageOriginY_=0,this.imageRotateWithView_=!1,this.imageRotation_=0,this.imageScale_=[0,0],this.imageWidth_=0,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=!1,this.textRotation_=0,this.textScale_=[0,0],this.textFillState_=null,this.textStrokeState_=null,this.textState_=null,this.pixelCoordinates_=[],this.tmpLocalTransform_=[1,0,0,1,0,0]}drawImages_(t,e,n,r){if(!this.image_)return;const i=Ie(t,e,n,r,this.transform_,this.pixelCoordinates_),o=this.context_,s=this.tmpLocalTransform_,a=o.globalAlpha;1!=this.imageOpacity_&&(o.globalAlpha=a*this.imageOpacity_);let u=this.imageRotation_;0===this.transformRotation_&&(u-=this.viewRotation_),this.imageRotateWithView_&&(u+=this.viewRotation_);for(let t=0,e=i.length;tt*this.pixelRatio_)),lineDashOffset:(i||0)*this.pixelRatio_,lineJoin:void 0!==o?o:Wr,lineWidth:(void 0!==s?s:1)*this.pixelRatio_,miterLimit:void 0!==a?a:10,strokeStyle:$r(t||Hr)}}else this.strokeState_=null}setImageStyle(t){let e;if(!t||!(e=t.getSize()))return void(this.image_=null);const n=t.getPixelRatio(this.pixelRatio_),r=t.getAnchor(),i=t.getOrigin();this.image_=t.getImage(this.pixelRatio_),this.imageAnchorX_=r[0]*n,this.imageAnchorY_=r[1]*n,this.imageHeight_=e[1]*n,this.imageOpacity_=t.getOpacity(),this.imageOriginX_=i[0],this.imageOriginY_=i[1],this.imageRotateWithView_=t.getRotateWithView(),this.imageRotation_=t.getRotation();const o=t.getScaleArray();this.imageScale_=[o[0]*this.pixelRatio_/n,o[1]*this.pixelRatio_/n],this.imageWidth_=e[0]*n}setTextStyle(t){if(t){const e=t.getFill();if(e){const t=e.getColor();this.textFillState_={fillStyle:$r(t||Vr)}}else this.textFillState_=null;const n=t.getStroke();if(n){const t=n.getColor(),e=n.getLineCap(),r=n.getLineDash(),i=n.getLineDashOffset(),o=n.getLineJoin(),s=n.getWidth(),a=n.getMiterLimit();this.textStrokeState_={lineCap:void 0!==e?e:zr,lineDash:r||Gr,lineDashOffset:i||0,lineJoin:void 0!==o?o:Wr,lineWidth:void 0!==s?s:1,miterLimit:void 0!==a?a:10,strokeStyle:$r(t||Hr)}}else this.textStrokeState_=null;const r=t.getFont(),i=t.getOffsetX(),o=t.getOffsetY(),s=t.getRotateWithView(),a=t.getRotation(),u=t.getScaleArray(),l=t.getText(),c=t.getTextAlign(),h=t.getTextBaseline();this.textState_={font:void 0!==r?r:Ur,textAlign:void 0!==c?c:qr,textBaseline:void 0!==h?h:Xr},this.text_=void 0!==l?Array.isArray(l)?l.reduce(((t,e,n)=>t+(n%2?" ":e)),""):l:"",this.textOffsetX_=void 0!==i?this.pixelRatio_*i:0,this.textOffsetY_=void 0!==o?this.pixelRatio_*o:0,this.textRotateWithView_=void 0!==s&&s,this.textRotation_=void 0!==a?a:0,this.textScale_=[this.pixelRatio_*u[0],this.pixelRatio_*u[1]]}else this.text_=""}},ra=.5;const ia={Point:function(t,e,n,r,i,o){const s=n.getImage(),a=n.getText(),u=a&&a.getText(),l=o&&s&&u?{}:void 0;if(s){if(s.getImageState()!=er)return;const o=t.getBuilder(n.getZIndex(),"Image");o.setImageStyle(s,l),o.drawPoint(e,r,i)}if(u){const o=t.getBuilder(n.getZIndex(),"Text");o.setTextStyle(a,l),o.drawText(e,r,i)}},LineString:function(t,e,n,r,i){const o=n.getStroke();if(o){const s=t.getBuilder(n.getZIndex(),"LineString");s.setFillStrokeStyle(null,o),s.drawLineString(e,r,i)}const s=n.getText();if(s&&s.getText()){const o=t.getBuilder(n.getZIndex(),"Text");o.setTextStyle(s),o.drawText(e,r,i)}},Polygon:ca,MultiPoint:function(t,e,n,r,i,o){const s=n.getImage(),a=s&&0!==s.getOpacity(),u=n.getText(),l=u&&u.getText(),c=o&&a&&l?{}:void 0;if(a){if(s.getImageState()!=er)return;const o=t.getBuilder(n.getZIndex(),"Image");o.setImageStyle(s,c),o.drawMultiPoint(e,r,i)}if(l){const o=t.getBuilder(n.getZIndex(),"Text");o.setTextStyle(u,c),o.drawText(e,r,i)}},MultiLineString:function(t,e,n,r,i){const o=n.getStroke();if(o){const s=t.getBuilder(n.getZIndex(),"LineString");s.setFillStrokeStyle(null,o),s.drawMultiLineString(e,r,i)}const s=n.getText();if(s&&s.getText()){const o=t.getBuilder(n.getZIndex(),"Text");o.setTextStyle(s),o.drawText(e,r,i)}},MultiPolygon:function(t,e,n,r,i){const o=n.getFill(),s=n.getStroke();if(s||o){const a=t.getBuilder(n.getZIndex(),"Polygon");a.setFillStrokeStyle(o,s),a.drawMultiPolygon(e,r,i)}const a=n.getText();if(a&&a.getText()){const o=t.getBuilder(n.getZIndex(),"Text");o.setTextStyle(a),o.drawText(e,r,i)}},GeometryCollection:function(t,e,n,r,i,o){const s=e.getGeometriesArray();let a,u;for(a=0,u=s.length;a0;return h&&Promise.all(u).then((()=>i(null))),function(t,e,n,r,i,o,s){const a=n.getGeometryFunction()(e);if(!a)return;const u=a.simplifyTransformed(r,i);if(n.getRenderer())la(t,u,n,e,s);else{(0,ia[u.getType()])(t,u,n,e,s,o)}}(t,e,n,r,o,s,a),h}function la(t,e,n,r,i){if("GeometryCollection"==e.getType()){const o=e.getGeometries();for(let e=0,s=o.length;e{if(this.frameState&&!this.hitDetectionImageData_&&!this.animatingOrInteracting_){const t=this.frameState.size.slice(),e=this.renderedCenter_,n=this.renderedResolution_,r=this.renderedRotation_,i=this.renderedProjection_,o=this.wrappedRenderedExtent_,s=this.getLayer(),a=[],u=t[0]*ra,l=t[1]*ra;a.push(this.getRenderTransform(e,n,r,ra,u,l,0).slice());const c=s.getSource(),h=i.getExtent();if(c.getWrapX()&&i.canWrapX()&&!pt(h,o)){let t=o[0];const i=kt(h);let s,c=0;for(;th[2];)++c,s=i*c,a.push(this.getRenderTransform(e,n,r,ra,u,l,s).slice()),t-=i}const d=be();this.hitDetectionImageData_=function(t,e,n,r,i,o,s,a,u){const l=u?we(i,u):i,c=Ir(t[0]*ra,t[1]*ra);c.imageSmoothingEnabled=!1;const h=c.canvas,d=new na(c,ra,i,null,s,a,u?fe(be(),u):null),f=n.length,p=Math.floor(16777215/f),g={};for(let t=1;t<=f;++t){const e=n[t-1],i=e.getStyleFunction()||r;if(!i)continue;let s=i(e,o);if(!s)continue;Array.isArray(s)||(s=[s]);const a=(t*p).toString(16).padStart(7,"#00000");for(let t=0,n=s.length;tc=r.forEachFeatureAtCoordinate(t,o,s,n,l,d&&e.declutter[d]?e.declutter[d].all().map((t=>t.value)):null))),c}handleFontsChanged(){const t=this.getLayer();t.getVisible()&&this.replayGroup_&&t.changed()}handleStyleImageChange_(t){this.renderIfReadyAndVisible()}prepareFrame(t){const e=this.getLayer(),n=e.getSource();if(!n)return!1;const r=t.viewHints[Mn],i=t.viewHints[Fn],o=e.getUpdateWhileAnimating(),s=e.getUpdateWhileInteracting();if(this.ready&&!o&&r||!s&&i)return this.animatingOrInteracting_=!0,!0;this.animatingOrInteracting_=!1;const a=t.extent,u=t.viewState,l=u.projection,c=u.resolution,h=t.pixelRatio,d=e.getRevision(),f=e.getRenderBuffer();let p=e.getRenderOrder();void 0===p&&(p=oa);const g=u.center.slice(),m=ht(a,f*c),y=m.slice(),b=[m.slice()],_=l.getExtent();if(n.getWrapX()&&l.canWrapX()&&!pt(_,t.extent)){const t=kt(_),e=Math.max(kt(m)/2,t);m[0]=_[0]-e,m[2]=_[2]+e,ne(g,l);const n=Lt(b[0],l);n[0]<_[0]&&n[2]<_[2]?b.push([n[0]+t,n[1],n[2]+t,n[3]]):n[0]>_[0]&&n[2]>_[2]&&b.push([n[0]-t,n[1],n[2]-t,n[3]])}if(this.ready&&this.renderedResolution_==c&&this.renderedRevision_==d&&this.renderedRenderOrder_==p&&this.renderedFrameDeclutter_===!!t.declutter&&pt(this.wrappedRenderedExtent_,m))return x(this.renderedExtent_,y)||(this.hitDetectionImageData_=null,this.renderedExtent_=y),this.renderedCenter_=g,this.replayGroupChanged=!1,!0;this.replayGroup_=null;const v=new ks(aa(c,h),m,c,h),w=be();let T;if(w){for(let t=0,e=b.length;t{let r;const i=t.getStyleFunction()||e.getStyleFunction();if(i&&(r=i(t,c)),r){const e=this.renderFeature(t,S,r,v,T,this.getLayer().getDeclutter(),n);O=O&&!e}},I=we(m,l),A=n.getFeaturesInExtent(I);p&&A.sort(p);for(let t=0,e=A.length;t0;)this.pop()}extend(t){for(let e=0,n=t.length;ethis.getLength())throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e),this.array_.splice(t,0,e),this.updateLength_(),this.dispatchEvent(new ma(fa,e,t))}pop(){return this.removeAt(this.getLength()-1)}push(t){this.unique_&&this.assertUnique_(t);const e=this.getLength();return this.insertAt(e,t),this.getLength()}remove(t){const e=this.array_;for(let n=0,r=e.length;n=this.getLength())return;const e=this.array_[t];return this.array_.splice(t,1),this.updateLength_(),this.dispatchEvent(new ma(pa,e,t)),e}setAt(t,e){if(t>=this.getLength())return void this.insertAt(t,e);if(t<0)throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e,t);const n=this.array_[t];this.array_[t]=e,this.dispatchEvent(new ma(pa,n,t)),this.dispatchEvent(new ma(fa,e,t))}updateLength_(){this.set(ga,this.array_.length)}assertUnique_(t,e){for(let n=0,r=this.array_.length;n>1),i=+n(t[r],e),i<0?o=r+1:(s=r,a=!i);return a?o:~o}(c,h);d<0?(u=(h-c[-d-2])/(c[-d-1]-c[-d-2]),a=e+(-d-2)*r):a=e+d*r}s=s>1?s:2,o=o||new Array(s);for(let e=0;e{if(t===this.squaredTolerance_)return this.simplifiedGeometry_;this.simplifiedGeometry_=this.clone(),e&&this.simplifiedGeometry_.applyTransform(e);const n=this.simplifiedGeometry_.getFlatCoordinates();let r;switch(this.type_){case"LineString":n.length=He(n,0,this.simplifiedGeometry_.flatCoordinates_.length,this.simplifiedGeometry_.stride_,t,n,0),r=[n.length];break;case"MultiLineString":r=[],n.length=qe(n,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,t,n,0,r);break;case"Polygon":r=[],n.length=Ke(n,0,this.simplifiedGeometry_.ends_,this.simplifiedGeometry_.stride_,Math.sqrt(t),n,0,r)}return r&&(this.simplifiedGeometry_=new wa(this.type_,n,r,2,this.properties_,this.id_)),this.squaredTolerance_=t,this.simplifiedGeometry_})),this}}wa.prototype.getFlatCoordinates=wa.prototype.getOrientedFlatCoordinates;const xa=wa;function Ta(t){return t?Array.isArray(t)?function(e){return t}:"function"==typeof t?t:function(e){return[t]}:null}const Sa=class extends j{constructor(t){super(),this.projection=ce(t.projection),this.attributions_=Ta(t.attributions),this.attributionsCollapsible_=void 0===t.attributionsCollapsible||t.attributionsCollapsible,this.loading=!1,this.state_=void 0!==t.state?t.state:"ready",this.wrapX_=void 0!==t.wrapX&&t.wrapX,this.interpolate_=!!t.interpolate,this.viewResolver=null,this.viewRejector=null;const e=this;this.viewPromise_=new Promise((function(t,n){e.viewResolver=t,e.viewRejector=n}))}getAttributions(){return this.attributions_}getAttributionsCollapsible(){return this.attributionsCollapsible_}getProjection(){return this.projection}getResolutions(t){return null}getView(){return this.viewPromise_}getState(){return this.state_}getWrapX(){return this.wrapX_}getInterpolate(){return this.interpolate_}refresh(){this.changed()}setAttributions(t){this.attributions_=Ta(t),this.changed()}setState(t){this.state_=t,this.changed()}},Oa="addfeature",Ea="changefeature",Ia="clear",Aa="removefeature",Pa="featuresloadstart",Ca="featuresloadend",Da="featuresloaderror";function ka(t,e){return[[-1/0,-1/0,1/0,1/0]]}let Ra=!1;function Ma(t,e){return function(n,r,i,o,s){const a=this;!function(t,e,n,r,i,o,s){const a=new XMLHttpRequest;a.open("GET","function"==typeof t?t(n,r,i):t,!0),"arraybuffer"==e.getType()&&(a.responseType="arraybuffer"),a.withCredentials=Ra,a.onload=function(t){if(!a.status||a.status>=200&&a.status<300){const t=e.getType();try{let r;"text"==t||"json"==t?r=a.responseText:"xml"==t?r=a.responseXML||a.responseText:"arraybuffer"==t&&(r=a.response),r?o(e.readFeatures(r,{extent:n,featureProjection:i}),e.readProjection(r)):s()}catch{s()}}else s()},a.onerror=s,a.send()}(t,e,n,r,i,(function(t,e){a.addFeatures(t),void 0!==o&&o(t)}),s||S)}}class Fa extends g{constructor(t,e,n){super(t),this.feature=e,this.features=n}}const La=class extends Sa{constructor(t){super({attributions:(t=t||{}).attributions,interpolate:!0,projection:void 0,state:"ready",wrapX:void 0===t.wrapX||t.wrapX}),this.on,this.once,this.un,this.loader_=S,this.format_=t.format,this.overlaps_=void 0===t.overlaps||t.overlaps,this.url_=t.url,void 0!==t.loader?this.loader_=t.loader:void 0!==this.url_&&(B(this.format_,"`format` must be set when `url` is set"),this.loader_=Ma(this.url_,this.format_)),this.strategy_=void 0!==t.strategy?t.strategy:ka;const e=void 0===t.useSpatialIndex||t.useSpatialIndex;let n,r;this.featuresRtree_=e?new ba:null,this.loadedExtentsRtree_=new ba,this.loadingExtentsCount_=0,this.nullGeometryFeatures_={},this.idIndex_={},this.uidIndex_={},this.featureChangeKeys_={},this.featuresCollection_=null,Array.isArray(t.features)?r=t.features:t.features&&(n=t.features,r=n.getArray()),e||void 0!==n||(n=new ya(r)),void 0!==r&&this.addFeaturesInternal(r),void 0!==n&&this.bindFeaturesCollection_(n)}addFeature(t){this.addFeatureInternal(t),this.changed()}addFeatureInternal(t){const e=$(t);if(!this.addToIndex_(e,t))return void(this.featuresCollection_&&this.featuresCollection_.remove(t));this.setupChangeEvents_(e,t);const n=t.getGeometry();if(n){const e=n.getExtent();this.featuresRtree_&&this.featuresRtree_.insert(e,t)}else this.nullGeometryFeatures_[e]=t;this.dispatchEvent(new Fa(Oa,t))}setupChangeEvents_(t,e){e instanceof xa||(this.featureChangeKeys_[t]=[C(e,P,this.handleFeatureChange_,this),C(e,m,this.handleFeatureChange_,this)])}addToIndex_(t,e){let n=!0;if(void 0!==e.getId()){const t=String(e.getId());if(t in this.idIndex_)if(e instanceof xa){const r=this.idIndex_[t];r instanceof xa?Array.isArray(r)?r.push(e):this.idIndex_[t]=[r,e]:n=!1}else n=!1;else this.idIndex_[t]=e}return n&&(B(!(t in this.uidIndex_),"The passed `feature` was already added to the source"),this.uidIndex_[t]=e),n}addFeatures(t){this.addFeaturesInternal(t),this.changed()}addFeaturesInternal(t){const e=[],n=[],r=[];for(let e=0,r=t.length;e{e||(e=!0,this.addFeature(t.element),e=!1)})),t.addEventListener(pa,(t=>{e||(e=!0,this.removeFeature(t.element),e=!1)})),this.featuresCollection_=t}clear(t){if(t){for(const t in this.featureChangeKeys_){this.featureChangeKeys_[t].forEach(k)}this.featuresCollection_||(this.featureChangeKeys_={},this.idIndex_={},this.uidIndex_={})}else if(this.featuresRtree_){const t=t=>{this.removeFeatureInternal(t)};this.featuresRtree_.forEach(t);for(const t in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[t])}this.featuresCollection_&&this.featuresCollection_.clear(),this.featuresRtree_&&this.featuresRtree_.clear(),this.nullGeometryFeatures_={};const e=new Fa(Ia);this.dispatchEvent(e),this.changed()}forEachFeature(t){if(this.featuresRtree_)return this.featuresRtree_.forEach(t);this.featuresCollection_&&this.featuresCollection_.forEach(t)}forEachFeatureAtCoordinateDirect(t,e){const n=[t[0],t[1],t[0],t[1]];return this.forEachFeatureInExtent(n,(function(n){const r=n.getGeometry();if(r instanceof xa||r.intersectsCoordinate(t))return e(n)}))}forEachFeatureInExtent(t,e){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(t,e);this.featuresCollection_&&this.featuresCollection_.forEach(e)}forEachFeatureIntersectingExtent(t,e){return this.forEachFeatureInExtent(t,(function(n){const r=n.getGeometry();if(r instanceof xa||r.intersectsExtent(t)){const t=e(n);if(t)return t}}))}getFeaturesCollection(){return this.featuresCollection_}getFeatures(){let t;return this.featuresCollection_?t=this.featuresCollection_.getArray().slice(0):this.featuresRtree_&&(t=this.featuresRtree_.getAll(),I(this.nullGeometryFeatures_)||w(t,Object.values(this.nullGeometryFeatures_))),t}getFeaturesAtCoordinate(t){const e=[];return this.forEachFeatureAtCoordinateDirect(t,(function(t){e.push(t)})),e}getFeaturesInExtent(t,e){if(this.featuresRtree_){if(!(e&&e.canWrapX()&&this.getWrapX()))return this.featuresRtree_.getInExtent(t);const n=function(t,e,n){if(e.canWrapX()){const r=e.getExtent();if(!isFinite(t[0])||!isFinite(t[2]))return[[r[0],t[1],r[2],t[3]]];Lt(t,e);const i=kt(r);if(kt(t)>i&&!n)return[[r[0],t[1],r[2],t[3]]];if(t[0]r[2])return[[t[0],t[1],r[2],t[3]],[r[0],t[1],t[2]-i,t[3]]]}return[t]}(t,e);return[].concat(...n.map((t=>this.featuresRtree_.getInExtent(t))))}return this.featuresCollection_?this.featuresCollection_.getArray().slice(0):[]}getClosestFeatureToCoordinate(t,e){const n=t[0],r=t[1];let i=null;const o=[NaN,NaN];let s=1/0;const a=[-1/0,-1/0,1/0,1/0];return e=e||T,this.featuresRtree_.forEachInExtent(a,(function(t){if(e(t)){const e=t.getGeometry(),u=s;if(s=e instanceof xa?0:e.closestPointXY(n,r,o,s),s{--this.loadingExtentsCount_,this.dispatchEvent(new Fa(Ca,void 0,t))}),(()=>{--this.loadingExtentsCount_,this.dispatchEvent(new Fa(Da))})),r.insert(o,{extent:o.slice()}))}this.loading=!(this.loader_.length<4)&&this.loadingExtentsCount_>0}refresh(){this.clear(!0),this.loadedExtentsRtree_.clear(),super.refresh()}removeLoadedExtent(t){const e=this.loadedExtentsRtree_;let n;e.forEachInExtent(t,(function(e){if(wt(e.extent,t))return n=e,!0})),n&&e.remove(n)}removeFeatures(t){const e=[];for(let n=0,r=t.length;n0&&this.changed()}removeFeature(t){if(!t)return;this.removeFeatureInternal(t)&&this.changed()}removeFeatureInternal(t){const e=$(t);if(!(e in this.uidIndex_))return;e in this.nullGeometryFeatures_?delete this.nullGeometryFeatures_[e]:this.featuresRtree_&&this.featuresRtree_.remove(t);this.featureChangeKeys_[e]?.forEach(k),delete this.featureChangeKeys_[e];const n=t.getId();if(void 0!==n){const e=n.toString(),r=this.idIndex_[e];r===t?delete this.idIndex_[e]:Array.isArray(r)&&(r.splice(r.indexOf(t),1),1===r.length&&(this.idIndex_[e]=r[0]))}return delete this.uidIndex_[e],this.hasListener(Aa)&&this.dispatchEvent(new Fa(Aa,t)),t}removeFromIdIndex_(t){let e=!1;for(const n in this.idIndex_){const r=this.idIndex_[n];if(t instanceof xa&&Array.isArray(r)&&r.includes(t))r.splice(r.indexOf(t),1);else if(this.idIndex_[n]===t){delete this.idIndex_[n],e=!0;break}}return e}setLoader(t){this.loader_=t}setUrl(t){B(this.format_,"`format` must be set when `url` is set"),this.url_=t,this.setLoader(Ma(t,this.format_))}};var $a=n(736);function Na(t){return Na="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Na(t)}function ja(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=new Array(e);n0?1:0})),u={data:new Uint8Array(a),width:s,height:o,bounds:{minX:0,maxX:s,minY:0,maxY:o}},l=G().traceContours(u).filter((function(t){return!t.inner})).filter((function(e){return function(t,e){var n=t.points.flatMap((function(t){return[t.x,t.y]})),r=Ga(e,2),i=r[0],o=r[1];return un(n,0,n.length,2,i,o)}(e,t)})).shift();if(l){this.simplifyTolerant>0&&(l=G().simplifyContours([l],this.simplifyTolerant,this.simplifyCount).shift());var c=l.points.map((function(t){return[t.x,t.y]})).map((function(t){var e=Ga(t,2),r=e[0],i=e[1];return[r/n.imageSamScale,i/n.imageSamScale]})).map((function(t){var e=Ga(t,2),n=e[0],i=e[1];return[n,r-i]}));this.sketchFeature?this.sketchFeature.getGeometry().setCoordinates([c]):(this.sketchFeature=new V(new bn([c])),this.sketchStyle&&this.sketchFeature.setStyle(this.sketchStyle)),this.sketchSource.hasFeature(this.sketchFeature)||this.sketchSource.addFeature(this.sketchFeature)}}}}])&&ja(e.prototype,n),r&&ja(e,r),Object.defineProperty(e,"prototype",{writable:!1}),o}(Q);var qa,Xa,Ya;const Ka=d({data:function(){return{loadingMagicSam:!1,loadingMagicSamTakesLong:!1,throttleInterval:1e3}},computed:{isMagicSamming:function(){return"magicSam"===this.interactionMode},magicSamButtonClass:function(){return this.loadingMagicSamTakesLong?"loading-magic-sam-long":""},magicSamButtonTitle:function(){return this.loadingMagicSamTakesLong?"Preparing the magic for this image":"Draw a polygon using the magic SAM tool 𝗭"}},methods:{setThrottleInterval:function(t){this.throttleInterval=t,qa&&qa.setThrottleInterval(t)},startLoadingMagicSam:function(){this.loadingMagicSam=!0},finishLoadingMagicSam:function(){this.loadingMagicSam=!1,this.loadingMagicSamTakesLong=!1},toggleMagicSam:function(){this.isMagicSamming?this.resetInteractionMode():this.canAdd&&!this.image.tiled&&(qa||this.initMagicSamInteraction(),this.interactionMode="magicSam")},handleSamEmbeddingRequestSuccess:function(t){this.image.id===Ya&&(null!==t.body.url?this.handleSamEmbeddingAvailable(t.body):this.loadingMagicSamTakesLong=!0)},handleSamEmbeddingRequestFailure:function(t){this.resetInteractionMode(),this.finishLoadingMagicSam(),u(t)},handleSamEmbeddingAvailable:function(t){var e=this;this.loadingMagicSam&&this.image.id===Ya&&Xa!==this.image.id&&(Xa=this.image.id,qa.updateEmbedding(this.image,t.url).then(this.finishLoadingMagicSam).then((function(){e.isMagicSamming&&qa.setActive(!0)})))},handleSamEmbeddingFailed:function(){this.loadingMagicSam&&(a.danger("Could not load the image embedding."),this.finishLoadingMagicSam(),this.resetInteractionMode())},initMagicSamInteraction:function(){(qa=new Ha({map:this.map,source:this.annotationSource,style:c.editing,indicatorPointStyle:c.editing,indicatorCrossStyle:c.cross,onnxUrl:biigle.$require("magic-sam.onnx-url"),simplifyTolerant:.1,throttleInterval:this.throttleInterval})).on("drawend",this.handleNewFeature),qa.setActive(!1),this.map.addInteraction(qa)}},watch:{image:function(t){this.loadingMagicSam&&Ya!==t.id&&(this.finishLoadingMagicSam(),this.resetInteractionMode()),this.isMagicSamming&&this.resetInteractionMode()},isMagicSamming:function(t){t?this.hasSelectedLabel?Xa!==this.image.id?this.loadingMagicSam||(Ya=this.image.id,this.startLoadingMagicSam(),p.save({id:this.image.id},{}).then(this.handleSamEmbeddingRequestSuccess,this.handleSamEmbeddingRequestFailure)):qa.setActive(!0):this.requireSelectedLabel():qa.setActive(!1)},canAdd:{handler:function(t){t?s.on("z",this.toggleMagicSam,0,this.listenerSet):s.off("z",this.toggleMagicSam,0,this.listenerSet)},immediate:!0}},created:function(){o.$on("settings.samThrottleInterval",this.setThrottleInterval),i.getInstance().private("user-".concat(this.userId)).listen(".Biigle\\Modules\\MagicSam\\Events\\EmbeddingAvailable",this.handleSamEmbeddingAvailable).listen(".Biigle\\Modules\\MagicSam\\Events\\EmbeddingFailed",this.handleSamEmbeddingFailed)}},undefined,undefined,!1,null,null,null).exports;r.push(Ka)},98:function(t,e){var n="undefined"!=typeof self?self:this,r=function(){function t(){this.fetch=!1,this.DOMException=n.DOMException}return t.prototype=n,new t}();!function(t){!function(e){var n="URLSearchParams"in t,r="Symbol"in t&&"iterator"in Symbol,i="FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),o="FormData"in t,s="ArrayBuffer"in t;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(t){return t&&a.indexOf(Object.prototype.toString.call(t))>-1};function l(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function c(t){return"string"!=typeof t&&(t=String(t)),t}function h(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return r&&(e[Symbol.iterator]=function(){return e}),e}function d(t){this.map={},t instanceof d?t.forEach((function(t,e){this.append(e,t)}),this):Array.isArray(t)?t.forEach((function(t){this.append(t[0],t[1])}),this):t&&Object.getOwnPropertyNames(t).forEach((function(e){this.append(e,t[e])}),this)}function f(t){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}function p(t){return new Promise((function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}}))}function g(t){var e=new FileReader,n=p(e);return e.readAsArrayBuffer(t),n}function m(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function y(){return this.bodyUsed=!1,this._initBody=function(t){var e;this._bodyInit=t,t?"string"==typeof t?this._bodyText=t:i&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:o&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:n&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():s&&i&&((e=t)&&DataView.prototype.isPrototypeOf(e))?(this._bodyArrayBuffer=m(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(t)||u(t))?this._bodyArrayBuffer=m(t):this._bodyText=t=Object.prototype.toString.call(t):this._bodyText="",this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):n&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var t=f(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var t,e,n,r=f(this);if(r)return r;if(this._bodyBlob)return t=this._bodyBlob,e=new FileReader,n=p(e),e.readAsText(t),n;if(this._bodyArrayBuffer)return Promise.resolve(function(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r-1?r:n),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&i)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(i)}function v(t){var e=new FormData;return t.trim().split("&").forEach((function(t){if(t){var n=t.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(r),decodeURIComponent(i))}})),e}function w(t,e){e||(e={}),this.type="default",this.status=void 0===e.status?200:e.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new d(e.headers),this.url=e.url||"",this._initBody(t)}_.prototype.clone=function(){return new _(this,{body:this._bodyInit})},y.call(_.prototype),y.call(w.prototype),w.prototype.clone=function(){return new w(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new d(this.headers),url:this.url})},w.error=function(){var t=new w(null,{status:0,statusText:""});return t.type="error",t};var x=[301,302,303,307,308];w.redirect=function(t,e){if(-1===x.indexOf(e))throw new RangeError("Invalid status code");return new w(null,{status:e,headers:{location:t}})},e.DOMException=t.DOMException;try{new e.DOMException}catch(t){e.DOMException=function(t,e){this.message=t,this.name=e;var n=Error(t);this.stack=n.stack},e.DOMException.prototype=Object.create(Error.prototype),e.DOMException.prototype.constructor=e.DOMException}function T(t,n){return new Promise((function(r,o){var s=new _(t,n);if(s.signal&&s.signal.aborted)return o(new e.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function u(){a.abort()}a.onload=function(){var t,e,n={status:a.status,statusText:a.statusText,headers:(t=a.getAllResponseHeaders()||"",e=new d,t.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(t){var n=t.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();e.append(r,i)}})),e)};n.url="responseURL"in a?a.responseURL:n.headers.get("X-Request-URL");var i="response"in a?a.response:a.responseText;r(new w(i,n))},a.onerror=function(){o(new TypeError("Network request failed"))},a.ontimeout=function(){o(new TypeError("Network request failed"))},a.onabort=function(){o(new e.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&i&&(a.responseType="blob"),s.headers.forEach((function(t,e){a.setRequestHeader(e,t)})),s.signal&&(s.signal.addEventListener("abort",u),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",u)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}T.polyfill=!0,t.fetch||(t.fetch=T,t.Headers=d,t.Request=_,t.Response=w),e.Headers=d,e.Request=_,e.Response=w,e.fetch=T,Object.defineProperty(e,"__esModule",{value:!0})}({})}(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;(e=i.fetch).default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,t.exports=e},252:(t,e,n)=>{t=n.nmd(t);var r,i=((r={}).floodFill=function(t,e,n,r,i,o){return o?function(t,e,n,r,i){var o,s,a,u,l,c,h,d,f,p,g=t.data,m=t.width,y=t.height,b=t.bytes,_=-1,v=m+1,w=-1,x=y+1,T=n*m+e,S=new Uint8Array(m*y),O=new Uint8Array(i||m*y);if(1===O[T])return null;var E=[g[T*=b],g[T+1],g[T+2],g[T+3]],I=[{y:n,left:e-1,right:e+1,dir:1}];do{for(p=!1,s=(u=I.shift()).left+1;sr||o<-r||(o=g[T+1]-E[1])>r||o<-r||(o=g[T+2]-E[2])>r||o<-r))){for(c=s-1;c>-1&&(T=(d=h+c)*b,1!==O[d])&&(S[d]=1,O[d]=1,c--,!((o=g[T]-E[0])>r||o<-r))&&!((o=g[T+1]-E[1])>r||o<-r)&&!((o=g[T+2]-E[2])>r||o<-r););for(l=s+1;lr||o<-r))&&!((o=g[T+1]-E[1])>r||o<-r)&&!((o=g[T+2]-E[2])>r||o<-r););c_&&(_=l-1),(a=u.y-u.dir)>=0&&a=0&&aw&&(w=u.y))}while(I.length>0);return{data:S,width:t.width,height:t.height,bounds:{minX:v,minY:x,maxX:_,maxY:w}}}(t,e,n,r,i):function(t,e,n,r,i){var o,s,a,u,l,c,h,d,f,p,g=t.data,m=t.width,y=t.height,b=t.bytes,_=-1,v=m+1,w=-1,x=y+1,T=n*m+e,S=new Uint8Array(m*y),O=new Uint8Array(i||m*y);if(1===O[T])return null;var E=[g[T*=b],g[T+1],g[T+2],g[T+3]],I=[{y:n,left:e-1,right:e+1,dir:1}];do{for(p=!1,s=(u=I.shift()).left+1;sr||o<-r||(o=g[T+1]-E[1])>r||o<-r||(o=g[T+2]-E[2])>r||o<-r)){for(p=!0,S[h+s]=1,O[h+s]=1,c=s-1;c>-1&&(T=(d=h+c)*b,1!==O[d])&&!((o=g[T]-E[0])>r||o<-r)&&!((o=g[T+1]-E[1])>r||o<-r)&&!((o=g[T+2]-E[2])>r||o<-r);)S[d]=1,O[d]=1,c--;for(l=s+1;lr||o<-r)&&!((o=g[T+1]-E[1])>r||o<-r)&&!((o=g[T+2]-E[2])>r||o<-r);)S[f]=1,O[f]=1,l++;c_&&(_=l-1),(a=u.y-u.dir)>=0&&a=0&&aw&&(w=u.y))}while(I.length>0);return{data:S,width:t.width,height:t.height,bounds:{minX:v,minY:x,maxX:_,maxY:w}}}(t,e,n,r,i)},r.gaussBlur=function(t,e){var n,r,i,o,s,a,u,l=2*e+1,c=e*e,h=new Float32Array(l),d=0,f=t.width,p=t.height,g=t.data,m=t.bounds.minX,y=t.bounds.maxX,b=t.bounds.minY,_=t.bounds.maxY;for(n=0;n0?e-o:0;n0?e-s:0;n.5?1:0}return{data:x,width:f,height:p,bounds:{minX:m,minY:b,maxX:y,maxY:_}}},r.gaussBlurOnlyBorder=function(t,e,n){var r,i,o,s,a,u,l,c,h,d,f=function(t,e,n){var r,i,o,s,a,u,l,c=t.width,h=t.height,d=t.data,f=new Uint8Array(d),p=t.bounds.minX,g=t.bounds.maxX,m=t.bounds.minY,y=t.bounds.maxY,b=c*h,_=new Uint8Array(b),v=[],w=Math.max(p,1),x=Math.min(g,c-2),T=Math.max(m,1),S=Math.min(y,h-2);if(n&&n.length>0)for(a=0;a0?e-r:0;i0?e-s:0;i0?e-l:0;s.5)E[a]=1,lx&&(x=l),cS&&(S=c);else{for(d=A-c0?e-c:0;s.5?(E[a]=1,lx&&(x=l),cS&&(S=c)):E[a]=0}}return{data:E,width:b,height:_,bounds:{minX:w,minY:T,maxX:x,maxY:S}}},r.createBorderMask=function(t){var e,n,r,i,o,s=t.width,a=t.height,u=t.data,l=t.bounds.minX,c=t.bounds.maxX,h=t.bounds.minY,d=t.bounds.maxY,f=c-l+1,p=d-h+1,g=new Uint8Array(f*p),m=Math.max(l,1),y=Math.min(c,s-2),b=Math.max(h,1),_=Math.min(d,a-2);for(n=b;n<_+1;n++)for(e=m;e=Math.sqrt(y*y+b*b)?y:y>=Math.sqrt(m*m+b*b)?m:Math.abs((v*w.x-_*w.y+x.x*T.y-T.x*x.y)/b))>f&&(p=r,f=g);f>e&&(c.push(p),h.push({first:d.first,last:p}),h.push({first:p,last:d.last}))}}while(h.length>0);for(l=[],u=c.length,c.sort((function(t,e){return t-e})),o=0;o{},226:(t,e,n)=>{"use strict";n.r(e),n.d(e,{InferenceSession:()=>p,Tensor:()=>d,env:()=>s,registerBackend:()=>o});const r={},i=[],o=(t,e,n)=>{if(!e||"function"!=typeof e.init||"function"!=typeof e.createSessionHandler)throw new TypeError("not a valid backend");{const o=r[t];if(void 0===o)r[t]={backend:e,priority:n};else{if(o.priority>n)return;if(o.priority===n&&o.backend!==e)throw new Error(`cannot register backend "${t}" using priority ${n}`)}if(n>=0){const e=i.indexOf(t);-1!==e&&i.splice(e,1);for(let e=0;e{let e=1;for(let n=0;n{const i=document.createElement("canvas"),o=i.getContext("2d");if(!t||!o)return r();const s=new Image;s.crossOrigin="Anonymous",s.src=t,s.onload=()=>{i.width=s.width,i.height=s.height,o.drawImage(s,0,0,i.width,i.height);const t=o.getImageData(0,0,i.width,i.height);if(void 0!==e){if(void 0!==e.height&&e.height!==i.height)throw new Error("Image input config height doesn't match ImageBitmap height");if(a.height=i.height,void 0!==e.width&&e.width!==i.width)throw new Error("Image input config width doesn't match ImageBitmap width");a.width=i.width}else a.height=i.height,a.width=i.width;n(h.bufferToTensor(t.data,a))}}));throw new Error("Input data provided is not supported - aborted tensor creation")}{const n="RGBA";let r,i;if(void 0!==e&&void 0!==e.resizedWidth&&void 0!==e.resizedHeight?(r=e.resizedHeight,i=e.resizedWidth):(r=t.height,i=t.width),void 0!==e){if(a=e,void 0!==e.bitmapFormat&&e.bitmapFormat!==n)throw new Error("Image input config format must be RGBA for ImageData");a.bitmapFormat="RGBA"}else a.bitmapFormat="RGBA";if(a.height=r,a.width=i,void 0!==e){const e=document.createElement("canvas");e.width=i,e.height=r;const n=e.getContext("2d");if(null==n)throw new Error("Can not access image data");n.putImageData(t,0,0),s=n.getImageData(0,0,i,r).data}else s=t.data}}if(void 0!==s)return h.bufferToTensor(s,a);throw new Error("Input data provided is not supported - aborted tensor creation")}toImageData(t){var e,n;const r=document.createElement("canvas").getContext("2d");let i;if(null==r)throw new Error("Can not access image data");{const o=this.dims[3],s=this.dims[2],a=this.dims[1],u=void 0!==t&&void 0!==t.format?t.format:"RGB",l=void 0!==t&&void 0!==(null===(e=t.norm)||void 0===e?void 0:e.mean)?t.norm.mean:255,c=void 0!==t&&void 0!==(null===(n=t.norm)||void 0===n?void 0:n.bias)?t.norm.bias:0,h=s*o;if(void 0!==t){if(void 0!==t.height&&t.height!==s)throw new Error("Image output config height doesn't match tensor height");if(void 0!==t.width&&t.width!==o)throw new Error("Image output config width doesn't match tensor width");if(void 0!==t.format&&4===a&&"RGBA"!==t.format||3===a&&"RGB"!==t.format&&"BGR"!==t.format)throw new Error("Tensor format doesn't match input tensor dims")}const d=4;let f=0,p=1,g=2,m=3,y=0,b=h,_=2*h,v=-1;"RGBA"===u?(y=0,b=h,_=2*h,v=3*h):"RGB"===u?(y=0,b=h,_=2*h):"RBG"===u&&(y=0,_=h,b=2*h),i=r.createImageData(o,s);for(let t=0;t=r.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${r.byteLength}).`);if(u=t.byteLength-i,"number"==typeof n){if(u=n,!Number.isSafeInteger(u))throw new RangeError("'byteLength' must be an integer.");if(u<=0||i+u>r.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${r.byteLength-i}].`);if("object"==typeof o&&null!==o)a=o;else if(void 0!==o)throw new TypeError("'options' must be an object.")}else if(void 0!==n)throw new TypeError("'byteLength' must be a number.")}else if(void 0!==e)throw new TypeError("'options' must be an object.");s=new Uint8Array(r,i,u)}}const u=(a.executionProviders||[]).map((t=>"string"==typeof t?t:t.name)),l=await(async t=>{const e=0===t.length?i:t,n=[];for(const t of e){const e=r[t];if(e){if(e.initialized)return e.backend;if(e.aborted)continue;const r=!!e.initPromise;try{return r||(e.initPromise=e.backend.init()),await e.initPromise,e.initialized=!0,e.backend}catch(i){r||n.push({name:t,err:i}),e.aborted=!0}finally{delete e.initPromise}}}throw new Error(`no available backend found. ERR: ${n.map((t=>`[${t.name}] ${t.err}`)).join(", ")}`)})(u),c=await l.createSessionHandler(s,a);return new f(c)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}}const p=f},736:(module,__unused_webpack_exports,__webpack_require__)=>{var process=__webpack_require__(155),e;self,e=__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(t,e,n)=>{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return k.buffer!=M&&H(k.buffer),F}function i(){return k.buffer!=M&&H(k.buffer),L}function o(){return k.buffer!=M&&H(k.buffer),$}function s(){return k.buffer!=M&&H(k.buffer),N}function a(){return k.buffer!=M&&H(k.buffer),j}var u,l,c;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){l=t,c=e}));var h,d,f,p,g,m,y=Object.assign({},u),b="./this.program",_=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,x="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,T=u.ENVIRONMENT_IS_PTHREAD||!1,S="";function O(t){return u.locateFile?u.locateFile(t,S):S+t}if(x){let e;S=w?n(908).dirname(S)+"/":"//",m=()=>{g||(p=n(1384),g=n(908))},h=function(t,e){return m(),t=g.normalize(t),p.readFileSync(t,e?void 0:"utf8")},f=t=>((t=h(t,!0)).buffer||(t=new Uint8Array(t)),t),d=(t,e,n)=>{m(),t=g.normalize(t),p.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof lt||C("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(9925)}catch(t){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),t}n.g.Worker=e.Worker}else(v||w)&&(w?S=self.location.href:"undefined"!=typeof document&&document.currentScript&&(S=document.currentScript.src),r&&(S=r),S=0!==S.indexOf("blob:")?S.substr(0,S.replace(/[?#].*/,"").lastIndexOf("/")+1):"",x||(h=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(f=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),d=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));x&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var E=console.log.bind(console),I=console.warn.bind(console);x&&(m(),E=t=>p.writeSync(1,t+"\n"),I=t=>p.writeSync(2,t+"\n"));var A,P=u.print||E,C=u.printErr||I;Object.assign(u,y),y=null,u.thisProgram&&(b=u.thisProgram),u.quit&&(_=u.quit),u.wasmBinary&&(A=u.wasmBinary);var D=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&ot("no native wasm support detected");var k,R,M,F,L,$,N,j,B=!1,U="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function V(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function z(t,e){return(t>>>=0)?V(i(),t,e):""}function G(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var o=0;o=s&&(s=65536+((1023&s)<<10)|1023&t.charCodeAt(++o)),127>=s){if(n>=r)break;e[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;e[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;e[n++>>>0]=224|s>>12}else{if(n+3>=r)break;e[n++>>>0]=240|s>>18,e[n++>>>0]=128|s>>12&63}e[n++>>>0]=128|s>>6&63}e[n++>>>0]=128|63&s}}return e[n>>>0]=0,n-i}function W(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function H(t){M=t,u.HEAP8=F=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=$=new Int32Array(t),u.HEAPU8=L=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=N=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=j=new Float64Array(t)}T&&(M=u.buffer);var q=u.INITIAL_MEMORY||16777216;if(T)k=u.wasmMemory,M=u.buffer;else if(u.wasmMemory)k=u.wasmMemory;else if(!((k=new WebAssembly.Memory({initial:q/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw C("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");k&&(M=k.buffer),q=M.byteLength,H(M);var X,Y=[],K=[],Z=[],J=[];function Q(){return D||!1}function tt(){var t=u.preRun.shift();Y.unshift(t)}var et,nt=0,rt=null,it=null;function ot(t){throw T?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),C(t="Aborted("+t+")"),B=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),c(t),t}function st(){return et.startsWith("data:application/octet-stream;base64,")}function at(){var t=et;try{if(t==et&&A)return new Uint8Array(A);if(f)return f(t);throw"both async and sync fetching of the wasm failed"}catch(t){ot(t)}}et="ort-wasm-threaded.wasm",st()||(et=O(et));var ut={};function lt(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function ct(t){(t=pt.Vb[t])||ot(),pt.mc(t)}function ht(t){var e=pt.Cc();if(!e)return 6;pt.ac.push(e),pt.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function dt(t){if(T)return Xt(1,1,t);Q()||(pt.oc(),u.onExit&&u.onExit(t),B=!0),_(t,new lt(t))}function ft(t,e){if(!e&&T)throw yt(t),"unwind";Q()||T||(be(),gt(Z),ye(0),ie[1].length&&oe(1,10),ie[2].length&&oe(2,10),pt.oc()),dt(t)}var pt={Yb:[],ac:[],qc:[],Vb:{},fc:function(){T&&pt.Ec()},Pc:function(){},Ec:function(){pt.receiveObjectTransfer=pt.Gc,pt.threadInitTLS=pt.pc,pt.setExitStatus=pt.nc,D=!1},nc:function(){},oc:function(){for(var t of Object.values(pt.Vb))pt.mc(t);for(t of pt.Yb)t.terminate();pt.Yb=[]},mc:function(t){var e=t.Ub;delete pt.Vb[e],pt.Yb.push(t),pt.ac.splice(pt.ac.indexOf(t),1),t.Ub=0,Te(e)},Gc:function(){},pc:function(){pt.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(pt.Bc=t.Ub),n.targetThread&&n.targetThread!=pe()){var i=pt.Vb[n.Qc];i?i.postMessage(n,n.transferList):C('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?Vt(n.queue):"spawnThread"===r?ht(n):"cleanupThread"===r?ct(n.thread):"killThread"===r?(n=n.thread,r=pt.Vb[n],delete pt.Vb[n],r.terminate(),Te(n),pt.ac.splice(pt.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?pt.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?P("Thread "+n.threadId+": "+n.text):"printErr"===r?C("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&C("worker sent an unknown command "+r);pt.Bc=void 0},t.onerror=t=>{throw C("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},x&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||r,wasmMemory:k,wasmModule:R})},yc:function(){var t=O("ort-wasm-threaded.worker.js");pt.Yb.push(new Worker(t))},Cc:function(){return 0==pt.Yb.length&&(pt.yc(),pt.Fc(pt.Yb[0])),pt.Yb.pop()}};function gt(t){for(;0>2>>>0];t=o()[t+48>>2>>>0],Ee(e,e-t),Ae(e)};var bt=[];function _t(t){var e=bt[t];return e||(t>=bt.length&&(bt.length=t+1),bt[t]=e=X.get(t)),e}u.invokeEntryPoint=function(t,e){t=_t(t)(e),Q()?pt.nc(t):Se(t)};var vt,wt,xt=[],Tt=0,St=0;function Ot(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){s()[this.Sb+4>>2>>>0]=t},this.bc=function(){return s()[this.Sb+4>>2>>>0]},this.wc=function(t){s()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return s()[this.Sb+8>>2>>>0]},this.rc=function(){o()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(o(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(o(),this.Sb>>2,1)},this.cc=function(t){s()[this.Sb+16>>2>>>0]=t},this.tc=function(){return s()[this.Sb+16>>2>>>0]},this.vc=function(){if(De(this.bc()))return s()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Et(t){return me(new Ot(t).Sb)}function It(t,e,n,r){return T?Xt(3,1,t,e,n,r):At(t,e,n,r)}function At(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return C("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return T&&0===i.length?It(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:i},T?(t.Oc="spawnThread",postMessage(t,i),0):ht(t))}function Pt(t,e,n){return T?Xt(4,1,t,e,n):0}function Ct(t,e){if(T)return Xt(5,1,t,e)}function Dt(t,e){if(T)return Xt(6,1,t,e)}function kt(t,e,n){if(T)return Xt(7,1,t,e,n)}function Rt(t,e,n){return T?Xt(8,1,t,e,n):0}function Mt(t,e){if(T)return Xt(9,1,t,e)}function Ft(t,e,n){if(T)return Xt(10,1,t,e,n)}function Lt(t,e,n,r){if(T)return Xt(11,1,t,e,n,r)}function $t(t,e,n,r){if(T)return Xt(12,1,t,e,n,r)}function Nt(t,e,n,r){if(T)return Xt(13,1,t,e,n,r)}function jt(t){if(T)return Xt(14,1,t)}function Bt(t,e){if(T)return Xt(15,1,t,e)}function Ut(t,e,n){if(T)return Xt(16,1,t,e,n)}function Vt(t){Atomics.store(o(),t>>2,1),pe()&&xe(t),Atomics.compareExchange(o(),t>>2,1,0)}function zt(t){return s()[t>>>2]+4294967296*o()[t+4>>>2]}function Gt(t,e,n,r,i,o){return T?Xt(17,1,t,e,n,r,i,o):-52}function Wt(t,e,n,r,i,o){if(T)return Xt(18,1,t,e,n,r,i,o)}function Ht(t){var n=W(t)+1,r=ge(n);return r&&G(t,e(),r,n),r}function qt(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}if(T)return Xt(19,1,t,e,n);var i=(new Date).getFullYear(),a=new Date(i,0,1),u=new Date(i,6,1);i=a.getTimezoneOffset();var l=u.getTimezoneOffset(),c=Math.max(i,l);o()[t>>2>>>0]=60*c,o()[e>>2>>>0]=Number(i!=l),t=r(a),e=r(u),t=Ht(t),e=Ht(e),l>2>>>0]=t,s()[n+4>>2>>>0]=e):(s()[n>>2>>>0]=e,s()[n+4>>2>>>0]=t)}function Xt(t,e){var n=arguments.length-2,r=arguments;return mt((()=>{for(var i=Pe(8*n),o=i>>3,s=0;s>>0]=u}return we(t,n,i,e)}))}u.executeNotifiedProxyingQueue=Vt,wt=x?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:T?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var Yt,Kt=[],Zt={};function Jt(){if(!Yt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:b||"./this.program"};for(t in Zt)void 0===Zt[t]?delete e[t]:e[t]=Zt[t];var n=[];for(t in e)n.push(t+"="+e[t]);Yt=n}return Yt}function Qt(t,n){if(T)return Xt(20,1,t,n);var r=0;return Jt().forEach((function(i,o){var a=n+r;for(o=s()[t+4*o>>2>>>0]=a,a=0;a>0>>>0]=i.charCodeAt(a);e()[o>>0>>>0]=0,r+=i.length+1})),0}function te(t,e){if(T)return Xt(21,1,t,e);var n=Jt();s()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),s()[e>>2>>>0]=r,0}function ee(t){return T?Xt(22,1,t):52}function ne(t,e,n,r){return T?Xt(23,1,t,e,n,r):52}function re(t,e,n,r,i){return T?Xt(24,1,t,e,n,r,i):70}var ie=[null,[],[]];function oe(t,e){var n=ie[t];0===e||10===e?((1===t?P:C)(V(n,0)),n.length=0):n.push(e)}function se(t,e,n,r){if(T)return Xt(25,1,t,e,n,r);for(var o=0,a=0;a>2>>>0],l=s()[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);o+=l}return s()[r>>2>>>0]=o,0}var ae=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var le=[31,29,31,30,31,30,31,31,30,31,30,31],ce=[31,28,31,30,31,30,31,31,30,31,30,31];function he(t,n,r,i){function s(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=l(new Date(t.getFullYear(),0,4)),n=l(n),0>=u(e,t)?0>=u(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var h=o()[i+40>>2>>>0];for(var d in i={Lc:o()[i>>2>>>0],Kc:o()[i+4>>2>>>0],dc:o()[i+8>>2>>>0],jc:o()[i+12>>2>>>0],ec:o()[i+16>>2>>>0],Xb:o()[i+20>>2>>>0],Tb:o()[i+24>>2>>>0],Wb:o()[i+28>>2>>>0],Rc:o()[i+32>>2>>>0],Jc:o()[i+36>>2>>>0],Mc:h?z(h):""},r=z(r),h={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(d,"g"),h[d]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(d in h={"%a":function(t){return f[t.Tb].substring(0,3)},"%A":function(t){return f[t.Tb]},"%b":function(t){return p[t.ec].substring(0,3)},"%B":function(t){return p[t.ec]},"%C":function(t){return a((t.Xb+1900)/100|0,2)},"%d":function(t){return a(t.jc,2)},"%e":function(t){return s(t.jc,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return a(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return a(t.Lc,2)},"%t":function(){return"\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return a(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return a(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return a(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\0\0"),h)r.includes(d)&&(r=r.replace(new RegExp(d,"g"),h[d](i)));return d=function(t){var e=Array(W(t)+1);return G(t,e,0,e.length),e}(r=r.replace(/\0\0/g,"%")),d.length>n?0:(function(t,n){e().set(t,n>>>0)}(d,t),d.length-1)}pt.fc();var de=[null,dt,yt,It,Pt,Ct,Dt,kt,Rt,Mt,Ft,Lt,$t,Nt,jt,Bt,Ut,Gt,Wt,qt,Qt,te,ee,ne,re,se],fe={b:function(t){return ge(t+24)+24},n:function(t){return(t=new Ot(t)).uc()||(t.hc(!0),Tt--),t.ic(!1),xt.push(t),t.sc(),t.vc()},ma:function(t){throw C("Unexpected exception thrown, this is not properly supported - aborting"),B=!0,t},x:function(){Oe(0);var t=xt.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&_t(e)(t.Zb),Et(t.Zb)}St=0},e:function(){var t=St;if(!t)return ae=0;var e=new Ot(t);e.cc(t);var n=e.bc();if(!n)return ae=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;iVt(r)));else if(T)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=pt.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*zt(t)),o()[e>>2>>>0]=t.getUTCSeconds(),o()[e+4>>2>>>0]=t.getUTCMinutes(),o()[e+8>>2>>>0]=t.getUTCHours(),o()[e+12>>2>>>0]=t.getUTCDate(),o()[e+16>>2>>>0]=t.getUTCMonth(),o()[e+20>>2>>>0]=t.getUTCFullYear()-1900,o()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,o()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*zt(t)),o()[e>>2>>>0]=t.getSeconds(),o()[e+4>>2>>>0]=t.getMinutes(),o()[e+8>>2>>>0]=t.getHours(),o()[e+12>>2>>>0]=t.getDate(),o()[e+16>>2>>>0]=t.getMonth(),o()[e+20>>2>>>0]=t.getFullYear()-1900,o()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;o()[e+28>>2>>>0]=r,o()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),o()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(o()[t+20>>2>>>0]+1900,o()[t+16>>2>>>0],o()[t+12>>2>>>0],o()[t+8>>2>>>0],o()[t+4>>2>>>0],o()[t>>2>>>0],0),n=o()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),s=new Date(e.getFullYear(),6,1).getTimezoneOffset(),a=i.getTimezoneOffset(),u=Math.min(a,s);return 0>n?o()[t+32>>2>>>0]=Number(s!=a&&u==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,o()[t+28>>2>>>0]=n,o()[t>>2>>>0]=e.getSeconds(),o()[t+4>>2>>>0]=e.getMinutes(),o()[t+8>>2>>>0]=e.getHours(),o()[t+12>>2>>>0]=e.getDate(),o()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Gt,Ba:Wt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,qt(e,n,r))},y:function(){ot("")},U:function(){if(!x&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,x&&(t="warning: "+t),C(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){i().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return x?n(3993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Kt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:de[t]).apply(null,Kt)},qa:function(t){var e=i().length;if((t>>>=0)<=e||4294901760=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var o=Math;r=Math.max(t,r),o=o.min.call(o,4294901760,r+(65536-r%65536)%65536);t:{try{k.grow(o-M.byteLength+65535>>>16),H(k.buffer);var s=1;break t}catch(t){}s=void 0}if(s)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:te,J:ft,I:ee,S:ne,ga:re,R:se,d:function(){return ae},na:function t(r,i){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(x)try{var e=n(Object(function(){var t=new Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>ot("randomDevice")}());for(var o=0;o>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ie();try{return _t(t)(e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},ja:function(t,e,n){var r=Ie();try{return _t(t)(e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},K:function(t){var e=Ie();try{return _t(t)()}catch(t){if(Ae(e),t!==t+0)throw t;Oe(1,0)}},f:function(t,e){var n=Ie();try{return _t(t)(e)}catch(t){if(Ae(n),t!==t+0)throw t;Oe(1,0)}},P:function(t,e,n){var r=Ie();try{return _t(t)(e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},Q:function(t,e,n){var r=Ie();try{return _t(t)(e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},k:function(t,e,n){var r=Ie();try{return _t(t)(e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},p:function(t,e,n,r){var i=Ie();try{return _t(t)(e,n,r)}catch(t){if(Ae(i),t!==t+0)throw t;Oe(1,0)}},q:function(t,e,n,r,i){var o=Ie();try{return _t(t)(e,n,r,i)}catch(t){if(Ae(o),t!==t+0)throw t;Oe(1,0)}},N:function(t,e,n,r,i,o){var s=Ie();try{return _t(t)(e,n,r,i,o)}catch(t){if(Ae(s),t!==t+0)throw t;Oe(1,0)}},s:function(t,e,n,r,i,o){var s=Ie();try{return _t(t)(e,n,r,i,o)}catch(t){if(Ae(s),t!==t+0)throw t;Oe(1,0)}},w:function(t,e,n,r,i,o,s){var a=Ie();try{return _t(t)(e,n,r,i,o,s)}catch(t){if(Ae(a),t!==t+0)throw t;Oe(1,0)}},L:function(t,e,n,r,i,o,s,a){var u=Ie();try{return _t(t)(e,n,r,i,o,s,a)}catch(t){if(Ae(u),t!==t+0)throw t;Oe(1,0)}},E:function(t,e,n,r,i,o,s,a,u,l,c,h){var d=Ie();try{return _t(t)(e,n,r,i,o,s,a,u,l,c,h)}catch(t){if(Ae(d),t!==t+0)throw t;Oe(1,0)}},aa:function(t,e,n,r,i,o,s,a){var u=Ie();try{return Be(t,e,n,r,i,o,s,a)}catch(t){if(Ae(u),t!==t+0)throw t;Oe(1,0)}},_:function(t,e,n,r,i,o,s){var a=Ie();try{return Re(t,e,n,r,i,o,s)}catch(t){if(Ae(a),t!==t+0)throw t;Oe(1,0)}},Z:function(t,e,n,r,i){var o=Ie();try{return Ue(t,e,n,r,i)}catch(t){if(Ae(o),t!==t+0)throw t;Oe(1,0)}},ca:function(t,e,n,r){var i=Ie();try{return Ne(t,e,n,r)}catch(t){if(Ae(i),t!==t+0)throw t;Oe(1,0)}},$:function(t){var e=Ie();try{return ke(t)}catch(t){if(Ae(e),t!==t+0)throw t;Oe(1,0)}},ba:function(t,e){var n=Ie();try{return je(t,e)}catch(t){if(Ae(n),t!==t+0)throw t;Oe(1,0)}},Y:function(t,e,n){var r=Ie();try{return Me(t,e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},g:function(t){var e=Ie();try{_t(t)()}catch(t){if(Ae(e),t!==t+0)throw t;Oe(1,0)}},r:function(t,e){var n=Ie();try{_t(t)(e)}catch(t){if(Ae(n),t!==t+0)throw t;Oe(1,0)}},i:function(t,e,n){var r=Ie();try{_t(t)(e,n)}catch(t){if(Ae(r),t!==t+0)throw t;Oe(1,0)}},ha:function(t,e,n,r){var i=Ie();try{_t(t)(e,n,r)}catch(t){if(Ae(i),t!==t+0)throw t;Oe(1,0)}},m:function(t,e,n,r){var i=Ie();try{_t(t)(e,n,r)}catch(t){if(Ae(i),t!==t+0)throw t;Oe(1,0)}},v:function(t,e,n,r,i){var o=Ie();try{_t(t)(e,n,r,i)}catch(t){if(Ae(o),t!==t+0)throw t;Oe(1,0)}},u:function(t,e,n,r,i,o){var s=Ie();try{_t(t)(e,n,r,i,o)}catch(t){if(Ae(s),t!==t+0)throw t;Oe(1,0)}},O:function(t,e,n,r,i,o,s){var a=Ie();try{_t(t)(e,n,r,i,o,s)}catch(t){if(Ae(a),t!==t+0)throw t;Oe(1,0)}},A:function(t,e,n,r,i,o,s,a){var u=Ie();try{_t(t)(e,n,r,i,o,s,a)}catch(t){if(Ae(u),t!==t+0)throw t;Oe(1,0)}},ka:function(t,e,n,r,i,o,s,a,u){var l=Ie();try{_t(t)(e,n,r,i,o,s,a,u)}catch(t){if(Ae(l),t!==t+0)throw t;Oe(1,0)}},C:function(t,e,n,r,i,o,s,a,u,l,c){var h=Ie();try{_t(t)(e,n,r,i,o,s,a,u,l,c)}catch(t){if(Ae(h),t!==t+0)throw t;Oe(1,0)}},D:function(t,e,n,r,i,o,s,a,u,l,c,h,d,f,p,g){var m=Ie();try{_t(t)(e,n,r,i,o,s,a,u,l,c,h,d,f,p,g)}catch(t){if(Ae(m),t!==t+0)throw t;Oe(1,0)}},fa:function(t,e,n,r,i,o,s,a){var u=Ie();try{Fe(t,e,n,r,i,o,s,a)}catch(t){if(Ae(u),t!==t+0)throw t;Oe(1,0)}},da:function(t,e,n,r,i,o,s,a,u,l,c,h){var d=Ie();try{$e(t,e,n,r,i,o,s,a,u,l,c,h)}catch(t){if(Ae(d),t!==t+0)throw t;Oe(1,0)}},ea:function(t,e,n,r,i,o){var s=Ie();try{Le(t,e,n,r,i,o)}catch(t){if(Ae(s),t!==t+0)throw t;Oe(1,0)}},o:function(t){return t},a:k||u.wasmMemory,G:function(t){ae=t},la:he,z:function(t,e,n,r){return he(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,pt.qc.push(u.asm.sb),X=u.asm.ub,K.unshift(u.asm.Va),R=e,T||(nt--,u.monitorRunDependencies&&u.monitorRunDependencies(nt),0==nt&&(null!==rt&&(clearInterval(rt),rt=null),it&&(t=it,it=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!A&&(v||w)){if("function"==typeof fetch&&!et.startsWith("file://"))return fetch(et,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+et+"'";return t.arrayBuffer()})).catch((function(){return at()}));if(d)return new Promise((function(t,e){d(et,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return at()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){C("failed to asynchronously prepare wasm: "+t),ot(t)}))}var r={a:fe};if(T||(nt++,u.monitorRunDependencies&&u.monitorRunDependencies(nt)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return C("Module.instantiateWasm callback failed with error: "+t),!1}(A||"function"!=typeof WebAssembly.instantiateStreaming||st()||et.startsWith("file://")||x||"function"!=typeof fetch?n(e):fetch(et,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return C("wasm streaming compile failed: "+t),C("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(c)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var pe=u._pthread_self=function(){return(pe=u._pthread_self=u.asm.ob).apply(null,arguments)},ge=u._malloc=function(){return(ge=u._malloc=u.asm.pb).apply(null,arguments)},me=u._free=function(){return(me=u._free=u.asm.qb).apply(null,arguments)},ye=u._fflush=function(){return(ye=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var be=u.___funcs_on_exit=function(){return(be=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},_e=u.__emscripten_thread_init=function(){return(_e=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},xe=u.__emscripten_proxy_execute_task_queue=function(){return(xe=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Te=u.__emscripten_thread_free_data=function(){return(Te=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Se=u.__emscripten_thread_exit=function(){return(Se=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Oe=u._setThrew=function(){return(Oe=u._setThrew=u.asm.Bb).apply(null,arguments)},Ee=u._emscripten_stack_set_limits=function(){return(Ee=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ie=u.stackSave=function(){return(Ie=u.stackSave=u.asm.Db).apply(null,arguments)},Ae=u.stackRestore=function(){return(Ae=u.stackRestore=u.asm.Eb).apply(null,arguments)},Pe=u.stackAlloc=function(){return(Pe=u.stackAlloc=u.asm.Fb).apply(null,arguments)},Ce=u.___cxa_can_catch=function(){return(Ce=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},De=u.___cxa_is_pointer_type=function(){return(De=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},ke=u.dynCall_j=function(){return(ke=u.dynCall_j=u.asm.Ib).apply(null,arguments)},Re=u.dynCall_iiiiij=function(){return(Re=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},Me=u.dynCall_jii=function(){return(Me=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Fe=u.dynCall_viiiiij=function(){return(Fe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Le=u.dynCall_vjji=function(){return(Le=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},$e=u.dynCall_viiijjjii=function(){return($e=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ne=u.dynCall_iij=function(){return(Ne=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},je=u.dynCall_ji=function(){return(je=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},Be=u.dynCall_iiiiiij=function(){return(Be=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Ue=u.dynCall_iiij=function(){return(Ue=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function Ve(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!B)&&(T||gt(K),l(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!T)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();J.unshift(t)}gt(J)}}if(!(0{var r,i=(r=(r="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,i,o;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){i=t,o=e}));var s,a,u,l,c,h,d=Object.assign({},e),f="./this.program",p=(t,e)=>{throw e},g="object"==typeof window,m="function"==typeof importScripts,y="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,b="";y?(b=m?n(908).dirname(b)+"/":"//",h=()=>{c||(l=n(1384),c=n(908))},s=function(t,e){return h(),t=c.normalize(t),l.readFileSync(t,e?void 0:"utf8")},u=t=>((t=s(t,!0)).buffer||(t=new Uint8Array(t)),t),a=(t,e,n)=>{h(),t=c.normalize(t),l.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(x||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},m&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),a=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var _,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,d),d=null,e.thisProgram&&(f=e.thisProgram),e.quit&&(p=e.quit),e.wasmBinary&&(_=e.wasmBinary);var x=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&q("no native wasm support detected");var T,S,O,E,I,A,P=!1,C="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function D(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(i=224==(240&i)?(15&i)<<12|o<<6|s:(7&i)<<18|o<<12|s<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function k(t,e){return(t>>>=0)?D(E,t,e):""}function R(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var o=0;o=s&&(s=65536+((1023&s)<<10)|1023&t.charCodeAt(++o)),127>=s){if(n>=r)break;e[n++>>>0]=s}else{if(2047>=s){if(n+1>=r)break;e[n++>>>0]=192|s>>6}else{if(65535>=s){if(n+2>=r)break;e[n++>>>0]=224|s>>12}else{if(n+3>=r)break;e[n++>>>0]=240|s>>18,e[n++>>>0]=128|s>>12&63}e[n++>>>0]=128|s>>6&63}e[n++>>>0]=128|63&s}}return e[n>>>0]=0,n-i}function M(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function F(){var t=T.buffer;S=t,e.HEAP8=O=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=I=new Int32Array(t),e.HEAPU8=E=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=A=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var L,$=[],N=[],j=[],B=[],U=0;function V(){var t=e.preRun.shift();$.unshift(t)}var z,G=0,W=null,H=null;function q(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),P=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),o(t),t}function X(){return z.startsWith("data:application/octet-stream;base64,")}if(z="ort-wasm.wasm",!X()){var Y=z;z=e.locateFile?e.locateFile(Y,b):b+Y}function K(){var t=z;try{if(t==z&&_)return new Uint8Array(_);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){q(t)}}function Z(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function J(t){for(;0>2>>>0]=t},this.Eb=function(){return A[this.zb+4>>2>>>0]},this.Sb=function(t){A[this.zb+8>>2>>>0]=t},this.Wb=function(){return A[this.zb+8>>2>>>0]},this.Tb=function(){I[this.zb>>2>>>0]=0},this.Ib=function(t){O[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=O[this.zb+12>>0>>>0]},this.Jb=function(t){O[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=O[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){I[this.zb>>2>>>0]+=1},this.Xb=function(){var t=I[this.zb>>2>>>0];return I[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){A[this.zb+16>>2>>>0]=t},this.Ob=function(){return A[this.zb+16>>2>>>0]},this.Qb=function(){if(At(this.Eb()))return A[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function rt(t){return vt(new nt(t).zb)}var it=[];function ot(t){var e=it[t];return e||(t>=it.length&&(it.length=t+1),it[t]=e=L.get(t)),e}function st(t){var e=M(t)+1,n=_t(e);return n&&R(t,O,n,e),n}var at={};function ut(){if(!lt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:f||"./this.program"};for(t in at)void 0===at[t]?delete e[t]:e[t]=at[t];var n=[];for(t in e)n.push(t+"="+e[t]);lt=n}return lt}var lt,ct=[null,[],[]];function ht(t,e){var n=ct[t];0===e||10===e?((1===t?v:w)(D(n,0)),n.length=0):n.push(e)}var dt=0;function ft(t){return 0==t%4&&(0!=t%100||0==t%400)}var pt=[31,29,31,30,31,30,31,31,30,31,30,31],gt=[31,28,31,30,31,30,31,31,30,31,30,31];function mt(t,e,n,r){function i(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=a(new Date(t.getFullYear(),0,4)),n=a(n),0>=s(e,t)?0>=s(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var l=I[r+40>>2>>>0];for(var c in r={$b:I[r>>2>>>0],Zb:I[r+4>>2>>>0],Gb:I[r+8>>2>>>0],Kb:I[r+12>>2>>>0],Hb:I[r+16>>2>>>0],Cb:I[r+20>>2>>>0],Ab:I[r+24>>2>>>0],Bb:I[r+28>>2>>>0],bc:I[r+32>>2>>>0],Yb:I[r+36>>2>>>0],ac:l?k(l):""},n=k(n),l={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(c,"g"),l[c]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(c in l={"%a":function(t){return h[t.Ab].substring(0,3)},"%A":function(t){return h[t.Ab]},"%b":function(t){return d[t.Hb].substring(0,3)},"%B":function(t){return d[t.Hb]},"%C":function(t){return o((t.Cb+1900)/100|0,2)},"%d":function(t){return o(t.Kb,2)},"%e":function(t){return i(t.Kb,2," ")},"%g":function(t){return u(t).toString().substring(2)},"%G":function(t){return u(t)},"%H":function(t){return o(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return o(t.$b,2)},"%t":function(){return"\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return o(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&ft(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&ft(t.Cb%400-1))&&e++}return o(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return o(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),l)n.includes(c)&&(n=n.replace(new RegExp(c,"g"),l[c](r)));return c=function(t){var e=Array(M(t)+1);return R(t,e,0,e.length),e}(n=n.replace(/\0\0/g,"%")),c.length>e?0:(O.set(c,t>>>0),c.length-1)}var yt={a:function(t){return _t(t+24)+24},m:function(t){return(t=new nt(t)).Pb()||(t.Ib(!0),tt--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),P=!0,t},w:function(){Tt(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&ot(e)(t.Db),rt(t.Db)}et=0},d:function(){var t=et;if(!t)return dt=0;var e=new nt(t);e.Fb(t);var n=e.Eb();if(!n)return dt=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i>>2]+4294967296*I[t+4>>>2])),I[e>>2>>>0]=t.getUTCSeconds(),I[e+4>>2>>>0]=t.getUTCMinutes(),I[e+8>>2>>>0]=t.getUTCHours(),I[e+12>>2>>>0]=t.getUTCDate(),I[e+16>>2>>>0]=t.getUTCMonth(),I[e+20>>2>>>0]=t.getUTCFullYear()-1900,I[e+24>>2>>>0]=t.getUTCDay(),I[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(A[t>>>2]+4294967296*I[t+4>>>2])),I[e>>2>>>0]=t.getSeconds(),I[e+4>>2>>>0]=t.getMinutes(),I[e+8>>2>>>0]=t.getHours(),I[e+12>>2>>>0]=t.getDate(),I[e+16>>2>>>0]=t.getMonth(),I[e+20>>2>>>0]=t.getFullYear()-1900,I[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);I[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,I[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),I[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(I[t+20>>2>>>0]+1900,I[t+16>>2>>>0],I[t+12>>2>>>0],I[t+8>>2>>>0],I[t+4>>2>>>0],I[t>>2>>>0],0),n=I[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),s=i.getTimezoneOffset(),a=Math.min(s,o);return 0>n?I[t+32>>2>>>0]=Number(o!=s&&a==r):0>2>>>0]=e.getDay(),I[t+28>>2>>>0]=(e.getTime()-i.getTime())/864e5|0,I[t>>2>>>0]=e.getSeconds(),I[t+4>>2>>>0]=e.getMinutes(),I[t+8>>2>>>0]=e.getHours(),I[t+12>>2>>>0]=e.getDate(),I[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}var i=(new Date).getFullYear(),o=new Date(i,0,1),s=new Date(i,6,1);i=o.getTimezoneOffset();var a=s.getTimezoneOffset();I[t>>2>>>0]=60*Math.max(i,a),I[e>>2>>>0]=Number(i!=a),t=r(o),e=r(s),t=st(t),e=st(e),a>2>>>0]=t,A[n+4>>2>>>0]=e):(A[n>>2>>>0]=e,A[n+4>>2>>>0]=t)}(e,n,r))},B:function(){q("")},ma:function(){return 4294901760},I:y?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){E.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=E.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var i=Math;r=Math.max(t,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);t:{try{T.grow(i-S.byteLength+65535>>>16),F();var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,i){var o=e+n;for(i=A[t+4*i>>2>>>0]=o,o=0;o>0>>>0]=r.charCodeAt(o);O[i>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();A[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),A[e>>2>>>0]=r,0},ba:function(t){x||0>2>>>0],a=A[e+4>>2>>>0];e+=8;for(var u=0;u>>0]);i+=a}return A[r>>2>>>0]=i,0},c:function(){return dt},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(y)try{var e=n(Object(function(){var t=new Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>q("randomDevice")}());for(var i=0;i>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},fa:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},J:function(t){var e=St();try{return ot(t)()}catch(t){if(Ot(e),t!==t+0)throw t;Tt(1,0)}},e:function(t,e){var n=St();try{return ot(t)(e)}catch(t){if(Ot(n),t!==t+0)throw t;Tt(1,0)}},N:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},O:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},j:function(t,e,n){var r=St();try{return ot(t)(e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},o:function(t,e,n,r){var i=St();try{return ot(t)(e,n,r)}catch(t){if(Ot(i),t!==t+0)throw t;Tt(1,0)}},p:function(t,e,n,r,i){var o=St();try{return ot(t)(e,n,r,i)}catch(t){if(Ot(o),t!==t+0)throw t;Tt(1,0)}},M:function(t,e,n,r,i,o){var s=St();try{return ot(t)(e,n,r,i,o)}catch(t){if(Ot(s),t!==t+0)throw t;Tt(1,0)}},r:function(t,e,n,r,i,o){var s=St();try{return ot(t)(e,n,r,i,o)}catch(t){if(Ot(s),t!==t+0)throw t;Tt(1,0)}},v:function(t,e,n,r,i,o,s){var a=St();try{return ot(t)(e,n,r,i,o,s)}catch(t){if(Ot(a),t!==t+0)throw t;Tt(1,0)}},K:function(t,e,n,r,i,o,s,a){var u=St();try{return ot(t)(e,n,r,i,o,s,a)}catch(t){if(Ot(u),t!==t+0)throw t;Tt(1,0)}},D:function(t,e,n,r,i,o,s,a,u,l,c,h){var d=St();try{return ot(t)(e,n,r,i,o,s,a,u,l,c,h)}catch(t){if(Ot(d),t!==t+0)throw t;Tt(1,0)}},X:function(t,e,n,r,i,o,s,a){var u=St();try{return $t(t,e,n,r,i,o,s,a)}catch(t){if(Ot(u),t!==t+0)throw t;Tt(1,0)}},V:function(t,e,n,r,i,o,s){var a=St();try{return Ct(t,e,n,r,i,o,s)}catch(t){if(Ot(a),t!==t+0)throw t;Tt(1,0)}},U:function(t,e,n,r,i){var o=St();try{return Nt(t,e,n,r,i)}catch(t){if(Ot(o),t!==t+0)throw t;Tt(1,0)}},Z:function(t,e,n,r){var i=St();try{return Ft(t,e,n,r)}catch(t){if(Ot(i),t!==t+0)throw t;Tt(1,0)}},W:function(t){var e=St();try{return Pt(t)}catch(t){if(Ot(e),t!==t+0)throw t;Tt(1,0)}},Y:function(t,e){var n=St();try{return Lt(t,e)}catch(t){if(Ot(n),t!==t+0)throw t;Tt(1,0)}},T:function(t,e,n){var r=St();try{return Dt(t,e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},f:function(t){var e=St();try{ot(t)()}catch(t){if(Ot(e),t!==t+0)throw t;Tt(1,0)}},q:function(t,e){var n=St();try{ot(t)(e)}catch(t){if(Ot(n),t!==t+0)throw t;Tt(1,0)}},h:function(t,e,n){var r=St();try{ot(t)(e,n)}catch(t){if(Ot(r),t!==t+0)throw t;Tt(1,0)}},da:function(t,e,n,r){var i=St();try{ot(t)(e,n,r)}catch(t){if(Ot(i),t!==t+0)throw t;Tt(1,0)}},l:function(t,e,n,r){var i=St();try{ot(t)(e,n,r)}catch(t){if(Ot(i),t!==t+0)throw t;Tt(1,0)}},t:function(t,e,n,r,i){var o=St();try{ot(t)(e,n,r,i)}catch(t){if(Ot(o),t!==t+0)throw t;Tt(1,0)}},u:function(t,e,n,r,i,o){var s=St();try{ot(t)(e,n,r,i,o)}catch(t){if(Ot(s),t!==t+0)throw t;Tt(1,0)}},x:function(t,e,n,r,i,o,s){var a=St();try{ot(t)(e,n,r,i,o,s)}catch(t){if(Ot(a),t!==t+0)throw t;Tt(1,0)}},z:function(t,e,n,r,i,o,s,a){var u=St();try{ot(t)(e,n,r,i,o,s,a)}catch(t){if(Ot(u),t!==t+0)throw t;Tt(1,0)}},ga:function(t,e,n,r,i,o,s,a,u){var l=St();try{ot(t)(e,n,r,i,o,s,a,u)}catch(t){if(Ot(l),t!==t+0)throw t;Tt(1,0)}},A:function(t,e,n,r,i,o,s,a,u,l,c){var h=St();try{ot(t)(e,n,r,i,o,s,a,u,l,c)}catch(t){if(Ot(h),t!==t+0)throw t;Tt(1,0)}},C:function(t,e,n,r,i,o,s,a,u,l,c,h,d,f,p,g){var m=St();try{ot(t)(e,n,r,i,o,s,a,u,l,c,h,d,f,p,g)}catch(t){if(Ot(m),t!==t+0)throw t;Tt(1,0)}},aa:function(t,e,n,r,i,o,s,a){var u=St();try{kt(t,e,n,r,i,o,s,a)}catch(t){if(Ot(u),t!==t+0)throw t;Tt(1,0)}},_:function(t,e,n,r,i,o,s,a,u,l,c,h){var d=St();try{Mt(t,e,n,r,i,o,s,a,u,l,c,h)}catch(t){if(Ot(d),t!==t+0)throw t;Tt(1,0)}},$:function(t,e,n,r,i,o){var s=St();try{Rt(t,e,n,r,i,o)}catch(t){if(Ot(s),t!==t+0)throw t;Tt(1,0)}},n:function(t){return t},F:function(t){dt=t},ha:mt,y:function(t,e,n,r){return mt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,T=e.asm.Ka,F(),L=e.asm.ib,N.unshift(e.asm.La),G--,e.monitorRunDependencies&&e.monitorRunDependencies(G),0==G&&(null!==W&&(clearInterval(W),W=null),H&&(t=H,H=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!_&&(g||m)){if("function"==typeof fetch&&!z.startsWith("file://"))return fetch(z,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+z+"'";return t.arrayBuffer()})).catch((function(){return K()}));if(a)return new Promise((function(t,e){a(z,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return K()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),q(t)}))}var i={a:yt};if(G++,e.monitorRunDependencies&&e.monitorRunDependencies(G),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(_||"function"!=typeof WebAssembly.instantiateStreaming||X()||z.startsWith("file://")||y||"function"!=typeof fetch?r(n):fetch(z,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(o)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var bt,_t=e._malloc=function(){return(_t=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},xt=e.___funcs_on_exit=function(){return(xt=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Tt=e._setThrew=function(){return(Tt=e._setThrew=e.asm.jb).apply(null,arguments)},St=e.stackSave=function(){return(St=e.stackSave=e.asm.kb).apply(null,arguments)},Ot=e.stackRestore=function(){return(Ot=e.stackRestore=e.asm.lb).apply(null,arguments)},Et=e.stackAlloc=function(){return(Et=e.stackAlloc=e.asm.mb).apply(null,arguments)},It=e.___cxa_can_catch=function(){return(It=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},At=e.___cxa_is_pointer_type=function(){return(At=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Pt=e.dynCall_j=function(){return(Pt=e.dynCall_j=e.asm.pb).apply(null,arguments)},Ct=e.dynCall_iiiiij=function(){return(Ct=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Dt=e.dynCall_jii=function(){return(Dt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},kt=e.dynCall_viiiiij=function(){return(kt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},Rt=e.dynCall_vjji=function(){return(Rt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Mt=e.dynCall_viiijjjii=function(){return(Mt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Ft=e.dynCall_iij=function(){return(Ft=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Lt=e.dynCall_ji=function(){return(Lt=e.dynCall_ji=e.asm.wb).apply(null,arguments)},$t=e.dynCall_iiiiiij=function(){return($t=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},Nt=e.dynCall_iiij=function(){return(Nt=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function jt(){function t(){if(!bt&&(bt=!0,e.calledRun=!0,!P)){if(J(N),i(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();B.unshift(t)}J(B)}}if(!(0{"use strict";t.exports=function(t,e){for(var n=new Array(arguments.length-1),r=0,i=2,o=!0;i{"use strict";var n=e;n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&"="===t.charAt(e);)++n;return Math.ceil(3*t.length)/4-n};for(var r=new Array(64),i=new Array(123),o=0;o<64;)i[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;n.encode=function(t,e,n){for(var i,o=null,s=[],a=0,u=0;e>2],i=(3&l)<<4,u=1;break;case 1:s[a++]=r[i|l>>4],i=(15&l)<<2,u=2;break;case 2:s[a++]=r[i|l>>6],s[a++]=r[63&l],u=0}a>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,s)),a=0)}return u&&(s[a++]=r[i],s[a++]=61,1===u&&(s[a++]=61)),o?(a&&o.push(String.fromCharCode.apply(String,s.slice(0,a))),o.join("")):String.fromCharCode.apply(String,s.slice(0,a))};var s="invalid encoding";n.decode=function(t,e,n){for(var r,o=n,a=0,u=0;u1)break;if(void 0===(l=i[l]))throw Error(s);switch(a){case 0:r=l,a=1;break;case 1:e[n++]=r<<2|(48&l)>>4,r=l,a=2;break;case 2:e[n++]=(15&r)<<4|(60&l)>>2,r=l,a=3;break;case 3:e[n++]=(3&r)<<6|l,a=0}}if(1===a)throw Error(s);return n-o},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},9211:t=>{"use strict";function e(){this._listeners={}}t.exports=e,e.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this},e.prototype.off=function(t,e){if(void 0===t)this._listeners={};else if(void 0===e)this._listeners[t]=[];else for(var n=this._listeners[t],r=0;r{"use strict";function e(t){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),n=new Uint8Array(e.buffer),r=128===n[3];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function o(t,r,i){e[0]=t,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function s(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],e[0]}function a(t,r){return n[3]=t[r],n[2]=t[r+1],n[1]=t[r+2],n[0]=t[r+3],e[0]}t.writeFloatLE=r?i:o,t.writeFloatBE=r?o:i,t.readFloatLE=r?s:a,t.readFloatBE=r?a:s}():function(){function e(t,e,n,r){var i=e<0?1:0;if(i&&(e=-e),0===e)t(1/e>0?0:2147483648,n,r);else if(isNaN(e))t(2143289344,n,r);else if(e>34028234663852886e22)t((i<<31|2139095040)>>>0,n,r);else if(e<11754943508222875e-54)t((i<<31|Math.round(e/1401298464324817e-60))>>>0,n,r);else{var o=Math.floor(Math.log(e)/Math.LN2);t((i<<31|o+127<<23|8388607&Math.round(e*Math.pow(2,-o)*8388608))>>>0,n,r)}}function s(t,e,n){var r=t(e,n),i=2*(r>>31)+1,o=r>>>23&255,s=8388607&r;return 255===o?s?NaN:i*(1/0):0===o?1401298464324817e-60*i*s:i*Math.pow(2,o-150)*(s+8388608)}t.writeFloatLE=e.bind(null,n),t.writeFloatBE=e.bind(null,r),t.readFloatLE=s.bind(null,i),t.readFloatBE=s.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),n=new Uint8Array(e.buffer),r=128===n[7];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function o(t,r,i){e[0]=t,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function s(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],n[4]=t[r+4],n[5]=t[r+5],n[6]=t[r+6],n[7]=t[r+7],e[0]}function a(t,r){return n[7]=t[r],n[6]=t[r+1],n[5]=t[r+2],n[4]=t[r+3],n[3]=t[r+4],n[2]=t[r+5],n[1]=t[r+6],n[0]=t[r+7],e[0]}t.writeDoubleLE=r?i:o,t.writeDoubleBE=r?o:i,t.readDoubleLE=r?s:a,t.readDoubleBE=r?a:s}():function(){function e(t,e,n,r,i,o){var s=r<0?1:0;if(s&&(r=-r),0===r)t(0,i,o+e),t(1/r>0?0:2147483648,i,o+n);else if(isNaN(r))t(0,i,o+e),t(2146959360,i,o+n);else if(r>17976931348623157e292)t(0,i,o+e),t((s<<31|2146435072)>>>0,i,o+n);else{var a;if(r<22250738585072014e-324)t((a=r/5e-324)>>>0,i,o+e),t((s<<31|a/4294967296)>>>0,i,o+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),t(4503599627370496*(a=r*Math.pow(2,-u))>>>0,i,o+e),t((s<<31|u+1023<<20|1048576*a&1048575)>>>0,i,o+n)}}}function s(t,e,n,r,i){var o=t(r,i+e),s=t(r,i+n),a=2*(s>>31)+1,u=s>>>20&2047,l=4294967296*(1048575&s)+o;return 2047===u?l?NaN:a*(1/0):0===u?5e-324*a*l:a*Math.pow(2,u-1075)*(l+4503599627370496)}t.writeDoubleLE=e.bind(null,n,0,4),t.writeDoubleBE=e.bind(null,r,4,0),t.readDoubleLE=s.bind(null,i,0,4),t.readDoubleBE=s.bind(null,o,4,0)}(),t}function n(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function r(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function i(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}t.exports=e(e)},7199:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}module.exports=inquire},6662:t=>{"use strict";t.exports=function(t,e,n){var r=n||8192,i=r>>>1,o=null,s=r;return function(n){if(n<1||n>i)return t(n);s+n>r&&(o=t(r),s=0);var a=e.call(o,s,s+=n);return 7&s&&(s=1+(7|s)),a}}},4997:(t,e)=>{"use strict";var n=e;n.length=function(t){for(var e=0,n=0,r=0;r191&&r<224?o[s++]=(31&r)<<6|63&t[e++]:r>239&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,o[s++]=55296+(r>>10),o[s++]=56320+(1023&r)):o[s++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],s>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),s=0);return i?(s&&i.push(String.fromCharCode.apply(String,o.slice(0,s))),i.join("")):String.fromCharCode.apply(String,o.slice(0,s))},n.write=function(t,e,n){for(var r,i,o=n,s=0;s>6|192,e[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(s+1)))?(r=65536+((1023&r)<<10)+(1023&i),++s,e[n++]=r>>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128);return n-o}},3442:(t,e)=>{"use strict";e.__esModule=!0;var n=function(){function t(e){if(!e)throw new TypeError("Invalid argument; `value` has no value.");this.value=t.EMPTY,e&&t.isGuid(e)&&(this.value=e)}return t.isGuid=function(e){var n=e.toString();return e&&(e instanceof t||t.validator.test(n))},t.create=function(){return new t([t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-"))},t.createEmpty=function(){return new t("emptyguid")},t.parse=function(e){return new t(e)},t.raw=function(){return[t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-")},t.gen=function(t){for(var e="",n=0;n{t.exports=n;var e=null;try{e=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(t){}function n(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function r(t){return!0===(t&&t.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},o={};function s(t,e){var n,r,s;return e?(s=0<=(t>>>=0)&&t<256)&&(r=o[t])?r:(n=u(t,(0|t)<0?-1:0,!0),s&&(o[t]=n),n):(s=-128<=(t|=0)&&t<128)&&(r=i[t])?r:(n=u(t,t<0?-1:0,!1),s&&(i[t]=n),n)}function a(t,e){if(isNaN(t))return e?y:m;if(e){if(t<0)return y;if(t>=f)return x}else{if(t<=-p)return T;if(t+1>=p)return w}return t<0?a(-t,e).neg():u(t%d|0,t/d|0,e)}function u(t,e,r){return new n(t,e,r)}n.fromInt=s,n.fromNumber=a,n.fromBits=u;var l=Math.pow;function c(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return m;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return c(t.substring(1),e,n).neg();for(var i=a(l(n,8)),o=m,s=0;s>>0:this.low},S.toNumber=function(){return this.unsigned?(this.high>>>0)*d+(this.low>>>0):this.high*d+(this.low>>>0)},S.toString=function(t){if((t=t||10)<2||36>>0).toString(t);if((o=u).isZero())return c+s;for(;c.length<6;)c="0"+c;s=""+c+s}},S.getHighBits=function(){return this.high},S.getHighBitsUnsigned=function(){return this.high>>>0},S.getLowBits=function(){return this.low},S.getLowBitsUnsigned=function(){return this.low>>>0},S.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<=0},S.isOdd=function(){return 1==(1&this.low)},S.isEven=function(){return 0==(1&this.low)},S.equals=function(t){return r(t)||(t=h(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&this.high===t.high&&this.low===t.low},S.eq=S.equals,S.notEquals=function(t){return!this.eq(t)},S.neq=S.notEquals,S.ne=S.notEquals,S.lessThan=function(t){return this.comp(t)<0},S.lt=S.lessThan,S.lessThanOrEqual=function(t){return this.comp(t)<=0},S.lte=S.lessThanOrEqual,S.le=S.lessThanOrEqual,S.greaterThan=function(t){return this.comp(t)>0},S.gt=S.greaterThan,S.greaterThanOrEqual=function(t){return this.comp(t)>=0},S.gte=S.greaterThanOrEqual,S.ge=S.greaterThanOrEqual,S.compare=function(t){if(r(t)||(t=h(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},S.comp=S.compare,S.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(b)},S.neg=S.negate,S.add=function(t){r(t)||(t=h(t));var e=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,s=t.high>>>16,a=65535&t.high,l=t.low>>>16,c=0,d=0,f=0,p=0;return f+=(p+=o+(65535&t.low))>>>16,d+=(f+=i+l)>>>16,c+=(d+=n+a)>>>16,c+=e+s,u((f&=65535)<<16|(p&=65535),(c&=65535)<<16|(d&=65535),this.unsigned)},S.subtract=function(t){return r(t)||(t=h(t)),this.add(t.neg())},S.sub=S.subtract,S.multiply=function(t){if(this.isZero())return m;if(r(t)||(t=h(t)),e)return u(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return m;if(this.eq(T))return t.isOdd()?T:m;if(t.eq(T))return this.isOdd()?T:m;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(g)&&t.lt(g))return a(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,o=this.low>>>16,s=65535&this.low,l=t.high>>>16,c=65535&t.high,d=t.low>>>16,f=65535&t.low,p=0,y=0,b=0,_=0;return b+=(_+=s*f)>>>16,y+=(b+=o*f)>>>16,b&=65535,y+=(b+=s*d)>>>16,p+=(y+=i*f)>>>16,y&=65535,p+=(y+=o*d)>>>16,y&=65535,p+=(y+=s*c)>>>16,p+=n*f+i*d+o*c+s*l,u((b&=65535)<<16|(_&=65535),(p&=65535)<<16|(y&=65535),this.unsigned)},S.mul=S.multiply,S.divide=function(t){if(r(t)||(t=h(t)),t.isZero())throw Error("division by zero");var n,i,o;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?u((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?y:m;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return y;if(t.gt(this.shru(1)))return _;o=y}else{if(this.eq(T))return t.eq(b)||t.eq(v)?T:t.eq(T)?b:(n=this.shr(1).div(t).shl(1)).eq(m)?t.isNegative()?b:v:(i=this.sub(t.mul(n)),o=n.add(i.div(t)));if(t.eq(T))return this.unsigned?y:m;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=m}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var s=Math.ceil(Math.log(n)/Math.LN2),c=s<=48?1:l(2,s-48),d=a(n),f=d.mul(t);f.isNegative()||f.gt(i);)f=(d=a(n-=c,this.unsigned)).mul(t);d.isZero()&&(d=b),o=o.add(d),i=i.sub(f)}return o},S.div=S.divide,S.modulo=function(t){return r(t)||(t=h(t)),e?u((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},S.mod=S.modulo,S.rem=S.modulo,S.not=function(){return u(~this.low,~this.high,this.unsigned)},S.and=function(t){return r(t)||(t=h(t)),u(this.low&t.low,this.high&t.high,this.unsigned)},S.or=function(t){return r(t)||(t=h(t)),u(this.low|t.low,this.high|t.high,this.unsigned)},S.xor=function(t){return r(t)||(t=h(t)),u(this.low^t.low,this.high^t.high,this.unsigned)},S.shiftLeft=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?u(this.low<>>32-t,this.unsigned):u(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):u(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},S.shr=S.shiftRight,S.shiftRightUnsigned=function(t){if(r(t)&&(t=t.toInt()),0==(t&=63))return this;var e=this.high;return t<32?u(this.low>>>t|e<<32-t,e>>>t,this.unsigned):u(32===t?e:e>>>t-32,0,this.unsigned)},S.shru=S.shiftRightUnsigned,S.shr_u=S.shiftRightUnsigned,S.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},S.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},S.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},S.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},S.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},n.fromBytes=function(t,e,r){return r?n.fromBytesLE(t,e):n.fromBytesBE(t,e)},n.fromBytesLE=function(t,e){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},n.fromBytesBE=function(t,e){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},1446:(t,e,n)=>{"use strict";var r,i,o,s=n(2100),a=s.Reader,u=s.Writer,l=s.util,c=s.roots.default||(s.roots.default={});c.onnx=((o={}).Version=(r={},(i=Object.create(r))[r[0]="_START_VERSION"]=0,i[r[1]="IR_VERSION_2017_10_10"]=1,i[r[2]="IR_VERSION_2017_10_30"]=2,i[r[3]="IR_VERSION_2017_11_3"]=3,i[r[4]="IR_VERSION_2019_1_22"]=4,i[r[5]="IR_VERSION"]=5,i),o.AttributeProto=function(){function t(t){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.name=t.string();break;case 21:r.refAttrName=t.string();break;case 13:r.docString=t.string();break;case 20:r.type=t.int32();break;case 2:r.f=t.float();break;case 3:r.i=t.int64();break;case 4:r.s=t.bytes();break;case 5:r.t=c.onnx.TensorProto.decode(t,t.uint32());break;case 6:r.g=c.onnx.GraphProto.decode(t,t.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos>>0,t.i.high>>>0).toNumber())),null!=t.s&&("string"==typeof t.s?l.base64.decode(t.s,e.s=l.newBuffer(l.base64.length(t.s)),0):t.s.length&&(e.s=t.s)),null!=t.t){if("object"!=typeof t.t)throw TypeError(".onnx.AttributeProto.t: object expected");e.t=c.onnx.TensorProto.fromObject(t.t)}if(null!=t.g){if("object"!=typeof t.g)throw TypeError(".onnx.AttributeProto.g: object expected");e.g=c.onnx.GraphProto.fromObject(t.g)}if(t.floats){if(!Array.isArray(t.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");e.floats=[];for(var n=0;n>>0,t.ints[n].high>>>0).toNumber())}if(t.strings){if(!Array.isArray(t.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(e.strings=[],n=0;n>>0,t.i.high>>>0).toNumber():t.i),null!=t.s&&t.hasOwnProperty("s")&&(n.s=e.bytes===String?l.base64.encode(t.s,0,t.s.length):e.bytes===Array?Array.prototype.slice.call(t.s):t.s),null!=t.t&&t.hasOwnProperty("t")&&(n.t=c.onnx.TensorProto.toObject(t.t,e)),null!=t.g&&t.hasOwnProperty("g")&&(n.g=c.onnx.GraphProto.toObject(t.g,e)),t.floats&&t.floats.length){n.floats=[];for(var i=0;i>>0,t.ints[i].high>>>0).toNumber():t.ints[i];if(t.strings&&t.strings.length)for(n.strings=[],i=0;i>>3){case 1:r.name=t.string();break;case 2:r.type=c.onnx.TypeProto.decode(t,t.uint32());break;case 3:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.name&&t.hasOwnProperty("name")&&!l.isString(t.name))return"name: string expected";if(null!=t.type&&t.hasOwnProperty("type")){var e=c.onnx.TypeProto.verify(t.type);if(e)return"type."+e}return null!=t.docString&&t.hasOwnProperty("docString")&&!l.isString(t.docString)?"docString: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.ValueInfoProto)return t;var e=new c.onnx.ValueInfoProto;if(null!=t.name&&(e.name=String(t.name)),null!=t.type){if("object"!=typeof t.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");e.type=c.onnx.TypeProto.fromObject(t.type)}return null!=t.docString&&(e.docString=String(t.docString)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.name="",n.type=null,n.docString=""),null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.type&&t.hasOwnProperty("type")&&(n.type=c.onnx.TypeProto.toObject(t.type,e)),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.NodeProto=function(){function t(t){if(this.input=[],this.output=[],this.attribute=[],t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(t.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(t.string());break;case 3:r.name=t.string();break;case 4:r.opType=t.string();break;case 7:r.domain=t.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(c.onnx.AttributeProto.decode(t,t.uint32()));break;case 6:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.input&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(var e=0;e>>3){case 1:r.irVersion=t.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(c.onnx.OperatorSetIdProto.decode(t,t.uint32()));break;case 2:r.producerName=t.string();break;case 3:r.producerVersion=t.string();break;case 4:r.domain=t.string();break;case 5:r.modelVersion=t.int64();break;case 6:r.docString=t.string();break;case 7:r.graph=c.onnx.GraphProto.decode(t,t.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(c.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.irVersion&&t.hasOwnProperty("irVersion")&&!(l.isInteger(t.irVersion)||t.irVersion&&l.isInteger(t.irVersion.low)&&l.isInteger(t.irVersion.high)))return"irVersion: integer|Long expected";if(null!=t.opsetImport&&t.hasOwnProperty("opsetImport")){if(!Array.isArray(t.opsetImport))return"opsetImport: array expected";for(var e=0;e>>0,t.irVersion.high>>>0).toNumber())),t.opsetImport){if(!Array.isArray(t.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");e.opsetImport=[];for(var n=0;n>>0,t.modelVersion.high>>>0).toNumber())),null!=t.docString&&(e.docString=String(t.docString)),null!=t.graph){if("object"!=typeof t.graph)throw TypeError(".onnx.ModelProto.graph: object expected");e.graph=c.onnx.GraphProto.fromObject(t.graph)}if(t.metadataProps){if(!Array.isArray(t.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(e.metadataProps=[],n=0;n>>0,t.irVersion.high>>>0).toNumber():t.irVersion),null!=t.producerName&&t.hasOwnProperty("producerName")&&(n.producerName=t.producerName),null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&(n.producerVersion=t.producerVersion),null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&("number"==typeof t.modelVersion?n.modelVersion=e.longs===String?String(t.modelVersion):t.modelVersion:n.modelVersion=e.longs===String?l.Long.prototype.toString.call(t.modelVersion):e.longs===Number?new l.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber():t.modelVersion),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.graph&&t.hasOwnProperty("graph")&&(n.graph=c.onnx.GraphProto.toObject(t.graph,e)),t.opsetImport&&t.opsetImport.length){n.opsetImport=[];for(var i=0;i>>3){case 1:r.key=t.string();break;case 2:r.value=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.key&&t.hasOwnProperty("key")&&!l.isString(t.key)?"key: string expected":null!=t.value&&t.hasOwnProperty("value")&&!l.isString(t.value)?"value: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.StringStringEntryProto)return t;var e=new c.onnx.StringStringEntryProto;return null!=t.key&&(e.key=String(t.key)),null!=t.value&&(e.value=String(t.value)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.key="",n.value=""),null!=t.key&&t.hasOwnProperty("key")&&(n.key=t.key),null!=t.value&&t.hasOwnProperty("value")&&(n.value=t.value),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o.TensorAnnotation=function(){function t(t){if(this.quantParameterTensorNames=[],t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.tensorName=t.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(c.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorName&&t.hasOwnProperty("tensorName")&&!l.isString(t.tensorName))return"tensorName: string expected";if(null!=t.quantParameterTensorNames&&t.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(t.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var e=0;e>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(c.onnx.NodeProto.decode(t,t.uint32()));break;case 2:r.name=t.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(c.onnx.TensorProto.decode(t,t.uint32()));break;case 10:r.docString=t.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(c.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(c.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(c.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(c.onnx.TensorAnnotation.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.node&&t.hasOwnProperty("node")){if(!Array.isArray(t.node))return"node: array expected";for(var e=0;e>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos>>0,t.dims[n].high>>>0).toNumber())}if(null!=t.dataType&&(e.dataType=0|t.dataType),null!=t.segment){if("object"!=typeof t.segment)throw TypeError(".onnx.TensorProto.segment: object expected");e.segment=c.onnx.TensorProto.Segment.fromObject(t.segment)}if(t.floatData){if(!Array.isArray(t.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(e.floatData=[],n=0;n>>0,t.int64Data[n].high>>>0).toNumber())}if(null!=t.name&&(e.name=String(t.name)),null!=t.docString&&(e.docString=String(t.docString)),null!=t.rawData&&("string"==typeof t.rawData?l.base64.decode(t.rawData,e.rawData=l.newBuffer(l.base64.length(t.rawData)),0):t.rawData.length&&(e.rawData=t.rawData)),t.externalData){if(!Array.isArray(t.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(e.externalData=[],n=0;n>>0,t.uint64Data[n].high>>>0).toNumber(!0))}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),e.defaults&&(n.dataType=0,n.segment=null,n.name="",e.bytes===String?n.rawData="":(n.rawData=[],e.bytes!==Array&&(n.rawData=l.newBuffer(n.rawData))),n.docString="",n.dataLocation=e.enums===String?"DEFAULT":0),t.dims&&t.dims.length){n.dims=[];for(var r=0;r>>0,t.dims[r].high>>>0).toNumber():t.dims[r]}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&(n.dataType=t.dataType),null!=t.segment&&t.hasOwnProperty("segment")&&(n.segment=c.onnx.TensorProto.Segment.toObject(t.segment,e)),t.floatData&&t.floatData.length)for(n.floatData=[],r=0;r>>0,t.int64Data[r].high>>>0).toNumber():t.int64Data[r];if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.rawData&&t.hasOwnProperty("rawData")&&(n.rawData=e.bytes===String?l.base64.encode(t.rawData,0,t.rawData.length):e.bytes===Array?Array.prototype.slice.call(t.rawData):t.rawData),t.doubleData&&t.doubleData.length)for(n.doubleData=[],r=0;r>>0,t.uint64Data[r].high>>>0).toNumber(!0):t.uint64Data[r];if(null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),t.externalData&&t.externalData.length)for(n.externalData=[],r=0;r>>3){case 1:r.begin=t.int64();break;case 2:r.end=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.begin&&t.hasOwnProperty("begin")&&!(l.isInteger(t.begin)||t.begin&&l.isInteger(t.begin.low)&&l.isInteger(t.begin.high))?"begin: integer|Long expected":null!=t.end&&t.hasOwnProperty("end")&&!(l.isInteger(t.end)||t.end&&l.isInteger(t.end.low)&&l.isInteger(t.end.high))?"end: integer|Long expected":null},t.fromObject=function(t){if(t instanceof c.onnx.TensorProto.Segment)return t;var e=new c.onnx.TensorProto.Segment;return null!=t.begin&&(l.Long?(e.begin=l.Long.fromValue(t.begin)).unsigned=!1:"string"==typeof t.begin?e.begin=parseInt(t.begin,10):"number"==typeof t.begin?e.begin=t.begin:"object"==typeof t.begin&&(e.begin=new l.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber())),null!=t.end&&(l.Long?(e.end=l.Long.fromValue(t.end)).unsigned=!1:"string"==typeof t.end?e.end=parseInt(t.end,10):"number"==typeof t.end?e.end=t.end:"object"==typeof t.end&&(e.end=new l.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults){if(l.Long){var r=new l.Long(0,0,!1);n.begin=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.begin=e.longs===String?"0":0;l.Long?(r=new l.Long(0,0,!1),n.end=e.longs===String?r.toString():e.longs===Number?r.toNumber():r):n.end=e.longs===String?"0":0}return null!=t.begin&&t.hasOwnProperty("begin")&&("number"==typeof t.begin?n.begin=e.longs===String?String(t.begin):t.begin:n.begin=e.longs===String?l.Long.prototype.toString.call(t.begin):e.longs===Number?new l.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber():t.begin),null!=t.end&&t.hasOwnProperty("end")&&("number"==typeof t.end?n.end=e.longs===String?String(t.end):t.end:n.end=e.longs===String?l.Long.prototype.toString.call(t.end):e.longs===Number?new l.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber():t.end),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),t.DataLocation=function(){var t={},e=Object.create(t);return e[t[0]="DEFAULT"]=0,e[t[1]="EXTERNAL"]=1,e}(),t}(),o.TensorShapeProto=function(){function t(t){if(this.dim=[],t)for(var e=Object.keys(t),n=0;n>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(c.onnx.TensorShapeProto.Dimension.decode(t,t.uint32()))):t.skipType(7&i)}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.dim&&t.hasOwnProperty("dim")){if(!Array.isArray(t.dim))return"dim: array expected";for(var e=0;e>>3){case 1:r.dimValue=t.int64();break;case 2:r.dimParam=t.string();break;case 3:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";var e={};if(null!=t.dimValue&&t.hasOwnProperty("dimValue")&&(e.value=1,!(l.isInteger(t.dimValue)||t.dimValue&&l.isInteger(t.dimValue.low)&&l.isInteger(t.dimValue.high))))return"dimValue: integer|Long expected";if(null!=t.dimParam&&t.hasOwnProperty("dimParam")){if(1===e.value)return"value: multiple values";if(e.value=1,!l.isString(t.dimParam))return"dimParam: string expected"}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!l.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.TensorShapeProto.Dimension)return t;var e=new c.onnx.TensorShapeProto.Dimension;return null!=t.dimValue&&(l.Long?(e.dimValue=l.Long.fromValue(t.dimValue)).unsigned=!1:"string"==typeof t.dimValue?e.dimValue=parseInt(t.dimValue,10):"number"==typeof t.dimValue?e.dimValue=t.dimValue:"object"==typeof t.dimValue&&(e.dimValue=new l.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber())),null!=t.dimParam&&(e.dimParam=String(t.dimParam)),null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.dimValue&&t.hasOwnProperty("dimValue")&&("number"==typeof t.dimValue?n.dimValue=e.longs===String?String(t.dimValue):t.dimValue:n.dimValue=e.longs===String?l.Long.prototype.toString.call(t.dimValue):e.longs===Number?new l.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber():t.dimValue,e.oneofs&&(n.value="dimValue")),null!=t.dimParam&&t.hasOwnProperty("dimParam")&&(n.dimParam=t.dimParam,e.oneofs&&(n.value="dimParam")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),t}(),o.TypeProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.tensorType=c.onnx.TypeProto.Tensor.decode(t,t.uint32());break;case 6:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorType&&t.hasOwnProperty("tensorType")){var e=c.onnx.TypeProto.Tensor.verify(t.tensorType);if(e)return"tensorType."+e}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!l.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof c.onnx.TypeProto)return t;var e=new c.onnx.TypeProto;if(null!=t.tensorType){if("object"!=typeof t.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");e.tensorType=c.onnx.TypeProto.Tensor.fromObject(t.tensorType)}return null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.tensorType&&t.hasOwnProperty("tensorType")&&(n.tensorType=c.onnx.TypeProto.Tensor.toObject(t.tensorType,e),e.oneofs&&(n.value="tensorType")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t.Tensor=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.elemType=t.int32();break;case 2:r.shape=c.onnx.TensorShapeProto.decode(t,t.uint32());break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.elemType&&t.hasOwnProperty("elemType")&&!l.isInteger(t.elemType))return"elemType: integer expected";if(null!=t.shape&&t.hasOwnProperty("shape")){var e=c.onnx.TensorShapeProto.verify(t.shape);if(e)return"shape."+e}return null},t.fromObject=function(t){if(t instanceof c.onnx.TypeProto.Tensor)return t;var e=new c.onnx.TypeProto.Tensor;if(null!=t.elemType&&(e.elemType=0|t.elemType),null!=t.shape){if("object"!=typeof t.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");e.shape=c.onnx.TensorShapeProto.fromObject(t.shape)}return e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.elemType=0,n.shape=null),null!=t.elemType&&t.hasOwnProperty("elemType")&&(n.elemType=t.elemType),null!=t.shape&&t.hasOwnProperty("shape")&&(n.shape=c.onnx.TensorShapeProto.toObject(t.shape,e)),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),t}(),o.OperatorSetIdProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.domain=t.string();break;case 2:r.version=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof a||(t=new a(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.domain&&t.hasOwnProperty("domain")&&!l.isString(t.domain)?"domain: string expected":null!=t.version&&t.hasOwnProperty("version")&&!(l.isInteger(t.version)||t.version&&l.isInteger(t.version.low)&&l.isInteger(t.version.high))?"version: integer|Long expected":null},t.fromObject=function(t){if(t instanceof c.onnx.OperatorSetIdProto)return t;var e=new c.onnx.OperatorSetIdProto;return null!=t.domain&&(e.domain=String(t.domain)),null!=t.version&&(l.Long?(e.version=l.Long.fromValue(t.version)).unsigned=!1:"string"==typeof t.version?e.version=parseInt(t.version,10):"number"==typeof t.version?e.version=t.version:"object"==typeof t.version&&(e.version=new l.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults)if(n.domain="",l.Long){var r=new l.Long(0,0,!1);n.version=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.version=e.longs===String?"0":0;return null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.version&&t.hasOwnProperty("version")&&("number"==typeof t.version?n.version=e.longs===String?String(t.version):t.version:n.version=e.longs===String?l.Long.prototype.toString.call(t.version):e.longs===Number?new l.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber():t.version),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,s.util.toJSONOptions)},t}(),o),t.exports=c},2100:(t,e,n)=>{"use strict";t.exports=n(9482)},9482:(t,e,n)=>{"use strict";var r=e;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=i,i()},1408:(t,e,n)=>{"use strict";t.exports=u;var r,i=n(9693),o=i.LongBits,s=i.utf8;function a(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function u(t){this.buf=t,this.pos=0,this.len=t.length}var l,c="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new u(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new u(t);throw Error("illegal buffer")},h=function(){return i.Buffer?function(t){return(u.create=function(t){return i.Buffer.isBuffer(t)?new r(t):c(t)})(t)}:c};function d(){var t=new o(0,0),e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw a(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw a(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function f(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw a(this,8);return new o(f(this.buf,this.pos+=4),f(this.buf,this.pos+=4))}u.create=h(),u.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,u.prototype.uint32=(l=4294967295,function(){if(l=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return l;if(l=(l|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return l;if((this.pos+=5)>this.len)throw this.pos=this.len,a(this,10);return l}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw a(this,4);return f(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw a(this,4);return 0|f(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw a(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},u.prototype.double=function(){if(this.pos+8>this.len)throw a(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},u.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw a(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?new this.buf.constructor(0):this._slice.call(this.buf,e,n)},u.prototype.string=function(){var t=this.bytes();return s.read(t,0,t.length)},u.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw a(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw a(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},u._configure=function(t){r=t,u.create=h(),r._configure();var e=i.Long?"toLong":"toNumber";i.merge(u.prototype,{int64:function(){return d.call(this)[e](!1)},uint64:function(){return d.call(this)[e](!0)},sint64:function(){return d.call(this).zzDecode()[e](!1)},fixed64:function(){return p.call(this)[e](!0)},sfixed64:function(){return p.call(this)[e](!1)}})}},593:(t,e,n)=>{"use strict";t.exports=o;var r=n(1408);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(t){r.call(this,t)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},o._configure()},5054:t=>{"use strict";t.exports={}},5994:(t,e,n)=>{"use strict";e.Service=n(7948)},7948:(t,e,n)=>{"use strict";t.exports=i;var r=n(9693);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(e),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function t(e,n,i,o,s){if(!o)throw TypeError("request must be specified");var a=this;if(!s)return r.asPromise(t,a,e,n,i,o);if(a.rpcImpl)try{return a.rpcImpl(e,n[a.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(t,n){if(t)return a.emit("error",t,e),s(t);if(null!==n){if(!(n instanceof i))try{n=i[a.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return a.emit("error",t,e),s(t)}return a.emit("data",n,e),s(null,n)}a.end(!0)}))}catch(t){return a.emit("error",t,e),void setTimeout((function(){s(t)}),0)}else setTimeout((function(){s(Error("already ended"))}),0)},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(t,e,n)=>{"use strict";t.exports=i;var r=n(9693);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var s=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return o;var e=t<0;e&&(t=-t);var n=t>>>0,r=(t-n)/4294967296>>>0;return e&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):o},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=1+~this.lo>>>0,n=~this.hi>>>0;return e||(n=n+1>>>0),-(e+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var a=String.prototype.charCodeAt;i.fromHash=function(t){return t===s?o:new i((a.call(t,0)|a.call(t,1)<<8|a.call(t,2)<<16|a.call(t,3)<<24)>>>0,(a.call(t,4)|a.call(t,5)<<8|a.call(t,6)<<16|a.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},9693:function(t,e,n){"use strict";var r=e;function i(t,e,n){for(var r=Object.keys(e),i=0;i0)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r._Buffer_allocUnsafe(t):new r.Array(t):r.Buffer?r._Buffer_from(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){var n=r.LongBits.fromHash(t);return r.Long?r.Long.fromBits(n.lo,n.hi,e):n.toNumber(Boolean(e))},r.merge=i,r.lcFirst=function(t){return t.charAt(0).toLowerCase()+t.substring(1)},r.newError=o,r.ProtocolError=o("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n-1;--n)if(1===e[t[n]]&&void 0!==this[t[n]]&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n{"use strict";t.exports=h;var r,i=n(9693),o=i.LongBits,s=i.base64,a=i.utf8;function u(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}function l(){}function c(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function h(){this.len=0,this.head=new u(l,0,0),this.tail=this.head,this.states=null}var d=function(){return i.Buffer?function(){return(h.create=function(){return new r})()}:function(){return new h}};function f(t,e,n){e[n]=255&t}function p(t,e){this.len=t,this.next=void 0,this.val=e}function g(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function m(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}h.create=d(),h.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(h.alloc=i.pool(h.alloc,i.Array.prototype.subarray)),h.prototype._push=function(t,e,n){return this.tail=this.tail.next=new u(t,e,n),this.len+=e,this},p.prototype=Object.create(u.prototype),p.prototype.fn=function(t,e,n){for(;t>127;)e[n++]=127&t|128,t>>>=7;e[n]=t},h.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new p((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},h.prototype.int32=function(t){return t<0?this._push(g,10,o.fromNumber(t)):this.uint32(t)},h.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},h.prototype.uint64=function(t){var e=o.from(t);return this._push(g,e.length(),e)},h.prototype.int64=h.prototype.uint64,h.prototype.sint64=function(t){var e=o.from(t).zzEncode();return this._push(g,e.length(),e)},h.prototype.bool=function(t){return this._push(f,1,t?1:0)},h.prototype.fixed32=function(t){return this._push(m,4,t>>>0)},h.prototype.sfixed32=h.prototype.fixed32,h.prototype.fixed64=function(t){var e=o.from(t);return this._push(m,4,e.lo)._push(m,4,e.hi)},h.prototype.sfixed64=h.prototype.fixed64,h.prototype.float=function(t){return this._push(i.float.writeFloatLE,4,t)},h.prototype.double=function(t){return this._push(i.float.writeDoubleLE,8,t)};var y=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r>>0;if(!e)return this._push(f,1,0);if(i.isString(t)){var n=h.alloc(e=s.length(t));s.decode(t,n,0),t=n}return this.uint32(e)._push(y,e,t)},h.prototype.string=function(t){var e=a.length(t);return e?this.uint32(e)._push(a.write,e,t):this._push(f,1,0)},h.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new u(l,0,0),this.len=0,this},h.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(l,0,0),this.len=0),this},h.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},h.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},h._configure=function(t){r=t,h.create=d(),r._configure()}},3155:(t,e,n)=>{"use strict";t.exports=o;var r=n(1173);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(){r.call(this)}function s(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r>>0;return this.uint32(e),e&&this._push(o.writeBytesBuffer,e,t),this},o.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this._push(s,e,t),this},o._configure()},7714:(t,e,n)=>{"use strict";e.R=void 0;const r=n(6919),i=n(7448);e.R=new class{async init(){}async createSessionHandler(t,e){const n=new r.Session(e);return await n.loadModel(t),new i.OnnxjsSessionHandler(n)}}},4200:(t,e,n)=>{"use strict";e.c8=e.rX=void 0;const r=n(1670),i=n(5381),o=n(2157),s=n(2306);e.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=!0),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=!1),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const t="undefined"==typeof navigator?(0,i.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},e.c8=new class{async init(){(0,e.rX)(),await(0,o.initWasm)()}async createSessionHandler(t,e){const n=new s.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(t,e),Promise.resolve(n)}}},6018:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||r(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),i(n(1670),e);const o=n(1670);{const t=n(7714).R;(0,o.registerBackend)("webgl",t,-10)}{const t=n(4200).c8;(0,o.registerBackend)("cpu",t,10),(0,o.registerBackend)("wasm",t,10),(0,o.registerBackend)("xnnpack",t,9)}},246:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createAttributeWithCacheKey=void 0;class n{constructor(t){Object.assign(this,t)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((t=>`${this[t]}`)).join(";")),this._cacheKey}}e.createAttributeWithCacheKey=t=>new n(t)},7778:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Attribute=void 0;const r=n(1446),i=n(9395),o=n(9162),s=n(2517);var a=i.onnxruntime.experimental.fbs;class u{constructor(t){if(this._attributes=new Map,null!=t){for(const e of t)e instanceof r.onnx.AttributeProto?this._attributes.set(e.name,[u.getValue(e),u.getType(e)]):e instanceof a.Attribute&&this._attributes.set(e.name(),[u.getValue(e),u.getType(e)]);if(this._attributes.sizeo.Tensor.fromProto(t)));if(t instanceof a.Attribute)return n.map((t=>o.Tensor.fromOrtTensor(t)))}if(e===r.onnx.AttributeProto.AttributeType.STRING&&t instanceof r.onnx.AttributeProto){const t=n;return(0,s.decodeUtf8String)(t)}return e===r.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof r.onnx.AttributeProto?n.map(s.decodeUtf8String):n}static getValueNoCheck(t){return t instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case r.onnx.AttributeProto.AttributeType.INT:return t.i;case r.onnx.AttributeProto.AttributeType.STRING:return t.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case r.onnx.AttributeProto.AttributeType.INTS:return t.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case a.AttributeType.FLOAT:return t.f();case a.AttributeType.INT:return t.i();case a.AttributeType.STRING:return t.s();case a.AttributeType.TENSOR:return t.t();case a.AttributeType.GRAPH:return t.g();case a.AttributeType.FLOATS:return t.floatsArray();case a.AttributeType.INTS:{const e=[];for(let n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.resolveBackend=e.backend=void 0;const r=n(5038),i=new Map;async function o(t){const n=e.backend;if(void 0!==n[t]&&function(t){const e=t;return"initialize"in e&&"function"==typeof e.initialize&&"createSessionHandler"in e&&"function"==typeof e.createSessionHandler&&"dispose"in e&&"function"==typeof e.dispose}(n[t])){const e=n[t];let r=e.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return i.set(t,e),e}}e.backend={webgl:new r.WebGLBackend},e.resolveBackend=async function t(e){if(!e)return t(["webgl"]);{const t="string"==typeof e?[e]:e;for(const e of t){const t=i.get(e);if(t)return t;const n=await o(e);if(n)return n}}throw new Error("no available backend to use")}},5038:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLBackend=void 0;const r=n(1670),i=n(6231),o=n(6416),s=n(7305);e.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(t){r.env.webgl.contextId=t}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(t){r.env.webgl.matmulMaxBatchSize=t}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(t){r.env.webgl.textureCacheMode=t}get pack(){return r.env.webgl.pack}set pack(t){r.env.webgl.pack=t}get async(){return r.env.webgl.async}set async(t){r.env.webgl.async=t}initialize(){try{return this.glContext=(0,s.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=!1),"boolean"!=typeof this.async&&(this.async=!1),i.Logger.setWithEnv(r.env),i.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(t){return i.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${t}`),!1}}createSessionHandler(t){return new o.WebGLSessionHandler(this,t)}dispose(){this.glContext.dispose()}}},5107:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CoordsGlslLib=void 0;const r=n(2517),i=n(8520),o=n(5060),s=n(7859),a=n(9390);class u extends i.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ")}}coordsToOffset(){return{coordsToOffset:new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ")}}getOutputSamplingSnippet(){const t=this.context.outputTextureLayout;return t.isPacked?this.getPackedOutputSamplingSnippet(t):this.getUnpackedOutputSamplingSnippet(t)}getPackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},s="getOutputCoords";switch(e.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputPacked1DCoords(e,n);break;case 2:r[s]=this.getOutputPacked2DCoords(e,n);break;case 3:r[s]=this.getOutputPacked3DCoords(e,n);break;default:r[s]=this.getOutputPackedNDCoords(e,n)}const a=`\n void setOutput(vec4 val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = val;\n }\n `;return r.floatTextureSetRGBA=new i.GlslLibRoutine(a),r}getUnpackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},s="getOutputCoords";switch(e.length){case 0:r[s]=this.getOutputScalarCoords();break;case 1:r[s]=this.getOutputUnpacked1DCoords(e,n);break;case 2:r[s]=this.getOutputUnpacked2DCoords(e,n);break;case 3:r[s]=this.getOutputUnpacked3DCoords(e,n);break;case 4:r[s]=this.getOutputUnpacked4DCoords(e,n);break;case 5:r[s]=this.getOutputUnpacked5DCoords(e,n);break;case 6:r[s]=this.getOutputUnpacked6DCoords(e,n);break;default:throw new Error(`Unsupported output dimensionality: ${e.length}`)}const a=`\n void setOutput(float val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n }\n `;return r.floatTextureSetR=new i.GlslLibRoutine(a),r}getOutputScalarCoords(){return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ")}getOutputPacked1DCoords(t,e){const n=e;let r="";return 1===n[0]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.y * ${n[1]}.0);\n }\n `,new i.GlslLibRoutine(r)):1===n[1]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.x * ${n[0]}.0);\n }\n `,new i.GlslLibRoutine(r)):(r=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n }\n `,new i.GlslLibRoutine(r))}getOutputPacked2DCoords(t,e){let n="";if(r.ArrayUtil.arraysEqual(t,e))return n=`\n ivec2 getOutputCoords() {\n return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]}));\n }\n `,new i.GlslLibRoutine(n);const o=e,s=Math.ceil(t[1]/2);return n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${o[0]}, ${o[1]}));\n\n int index = resTexRC.y * ${o[0]} + resTexRC.x;\n\n // reverse r and c order for packed texture\n int r = imod(index, ${s}) * 2;\n int c = 2 * (index / ${s});\n\n return ivec2(r, c);\n }\n `,new i.GlslLibRoutine(n)}getOutputPacked3DCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[2]/2),o=r*Math.ceil(t[1]/2),s=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec3(b, r, c);\n }\n `;return new i.GlslLibRoutine(s)}getOutputPackedNDCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2);let s=o,a="",u="b, r, c";for(let e=2;e=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d"],a=o.map(((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`)).join("");return n=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec3(r, c, d);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked4DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d","d2"],a=o.map(((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`)).join("");return n=`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec4(r, c, d, d2);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked5DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d","d2","d3"],a=o.map(((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`)).join("");return n=`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec5(r, c, d, d2, d3);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked6DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const s=["r","c","d","d2","d3","d4"],a=o.map(((t,e)=>`int ${s[e]} = index / ${t}; ${e===o.length-1?`int ${s[e+1]} = index - ${s[e]} * ${t}`:`index -= ${s[e]} * ${t}`};`)).join("");return n=`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${a}\n return ivec6(r, c, d, d2, d3, d4);\n }\n `,new i.GlslLibRoutine(n)}getCommonUtilFuncs(){const t={};let e="uvFromFlat";t[e]=new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "),e="packedUVfrom1D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="packedUVfrom2D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="packedUVfrom3D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="sampleTexture";const n=(0,o.getGlsl)(this.context.glContext.version);return t[e]=new i.GlslLibRoutine(`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }`),t}getInputsSamplingSnippets(){const t={},e=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach(((n,r)=>{const i=this.context.inputTextureLayouts[r],o=(0,a.generateShaderFuncNameFromInputSamplerName)(n);i.isPacked?t[o]=this.getPackedSamplerFromInput(o,n,i):t[o]=this.getUnpackedSamplerFromInput(o,n,i);const s=(0,a.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);i.unpackedShape.length<=e.unpackedShape.length&&(i.isPacked?t[s]=this.getPackedSamplerAtOutputCoords(s,i,e,n):t[s]=this.getUnpackedSamplerAtOutputCoords(s,i,e,n))})),t}getPackedSamplerAtOutputCoords(t,e,n,o){const s=e.unpackedShape,u=n.unpackedShape,l=o,c=(0,a.generateShaderFuncNameFromInputSamplerName)(l),h=s.length,d=u.length,f=r.BroadcastUtil.getBroadcastDims(s,u),p=(0,a.getCoordsDataType)(d),g=d-h;let m;const y=(0,a.getGlChannels)();m=0===h?"":d<2&&f.length>=1?"coords = 0;":f.map((t=>`coords.${y[t+g]} = 0;`)).join("\n");let b="";b=d<2&&h>0?"coords":s.map(((t,e)=>`coords.${y[e+g]}`)).join(", ");let _="return outputValue;";const v=1===r.ShapeUtil.size(s),w=1===r.ShapeUtil.size(u);if(1!==h||v||w){if(v&&!w)_=1===d?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(f.length){const t=h-2,e=h-1;f.indexOf(t)>-1&&f.indexOf(e)>-1?_="return vec4(outputValue.x);":f.indexOf(t)>-1?_="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":f.indexOf(e)>-1&&(_="return vec4(outputValue.xx, outputValue.zz);")}}else _="\n return vec4(outputValue.xy, outputValue.xy);\n ";const x=`\n vec4 ${t}() {\n ${p} coords = getOutputCoords();\n \n int lastDim = coords.${y[d-1]};\n coords.${y[d-1]} = coords.${y[d-2]};\n coords.${y[d-2]} = lastDim;\n \n ${m}\n vec4 outputValue = ${c}(${b});\n ${_}\n }\n `;return new i.GlslLibRoutine(x,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(t,e,n,o){const s=[n.width,n.height],u=[e.width,e.height],l=e.unpackedShape.length,c=n.unpackedShape.length,h=e.unpackedShape,d=n.unpackedShape,f=(0,a.generateShaderFuncNameFromInputSamplerName)(o);if(l===c&&r.ArrayUtil.arraysEqual(u,s)){const e=`\n float ${t}() {\n return sampleTexture(${o}, TexCoords);\n }\n `;return new i.GlslLibRoutine(e,["coordinates.sampleTexture"])}const p=(0,a.getCoordsDataType)(c),g=r.BroadcastUtil.getBroadcastDims(h,d),m=c-l;let y;const b=(0,a.getGlChannels)();y=0===l?"":c<2&&g.length>=1?"coords = 0;":g.map((t=>`coords.${b[t+m]} = 0;`)).join("\n");let _="";_=c<2&&l>0?"coords":e.unpackedShape.map(((t,e)=>`coords.${b[e+m]}`)).join(", ");const v=`\n float ${t}() {\n ${p} coords = getOutputCoords();\n ${y}\n return ${f}(${_});\n }\n `;return new i.GlslLibRoutine(v,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(t,e,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(t,e);case 1:return this.getPackedSampler1D(t,e,n);case 2:return this.getPackedSampler2D(t,e,n);case 3:return this.getPackedSampler3D(t,e,n);default:return this.getPackedSamplerND(t,e,n)}}getUnpackedSamplerFromInput(t,e,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(t,e,n);case 1:return this.getUnpackedSampler1D(t,e,n);case 2:return this.getUnpackedSampler2D(t,e,n);case 3:return this.getUnpackedSampler3D(t,e,n);case 4:return this.getUnpackedSampler4D(t,e,n);case 5:return this.getUnpackedSampler5D(t,e,n);case 6:return this.getUnpackedSampler6D(t,e,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(t,e){const n=`\n vec4 ${t}() {\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, halfCR);\n }\n `;return new i.GlslLibRoutine(n)}getPackedSampler1D(t,e,n){const r=[n.width,n.height],s=[r[1],r[0]],a=(0,o.getGlsl)(this.context.glContext.version),u=`vec4 ${t}(int index) {\n vec2 uv = packedUVfrom1D(\n ${s[0]}, ${s[1]}, index);\n return ${a.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(u,["coordinates.packedUVfrom1D"])}getPackedSampler2D(t,e,n){const s=n.unpackedShape,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=a[0],c=a[1];if(null!=a&&r.ArrayUtil.arraysEqual(s,a)){const n=`vec4 ${t}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${l}.0);\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(n)}const h=a,d=Math.ceil(s[1]/2),f=`vec4 ${t}(int row, int col) {\n vec2 uv = packedUVfrom2D(${h[1]}, ${h[0]}, ${d}, row, col);\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(f,["coordinates.packedUVfrom2D"])}getPackedSampler3D(t,e,n){const r=n.unpackedShape,s=[n.width,n.height],u=[s[0],s[1]],l=(0,o.getGlsl)(this.context.glContext.version);if(1===r[0]){const o=r.slice(1),s=[1,2],u=(0,a.squeezeInputShape)(r,o),l=["b","row","col"],c=JSON.parse(JSON.stringify(n));c.unpackedShape=u;const h=this.getPackedSamplerFromInput(t,e,c),d=`${h.routineBody}\n vec4 ${t}(int b, int row, int col) {\n return ${t}(${(0,a.getSqueezedParams)(l,s)});\n } `;return new i.GlslLibRoutine(d,h.dependencies)}const c=u[0],h=u[1],d=Math.ceil(r[2]/2),f=`vec4 ${t}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${h}, ${c}, ${d*Math.ceil(r[1]/2)}, ${d}, b, row, col);\n return ${l.texture2D}(${e}, uv);}`;return new i.GlslLibRoutine(f,["coordinates.packedUVfrom3D"])}getPackedSamplerND(t,e,n){const r=n.unpackedShape,s=r.length,a=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),l=[a[0],a[1]],c=l[1],h=l[0],d=Math.ceil(r[s-1]/2);let f=d*Math.ceil(r[s-2]/2),p="int b, int row, int col",g=`b * ${f} + (row / 2) * ${d} + (col / 2)`;for(let t=2;t{const r=this.context.inputTextureLayouts[n],o=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let s=`_${e}`;t[s]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!1),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),s+="_T",t[s]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!0),[`shapeUtils.indicesToOffset${s}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])})),t}getValueFromSingle(t,e,n,r,i){let s=`_${t}`;return i&&(s+="_T"),`\n float ${s}(int m[${e}]) {\n int offset = indicesToOffset${s}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n float value = getColorAsFloat(${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords));\n return value;\n }\n `}getPackedValueFrom(t,e,n,r,i){let s=`_${t}_Pack`;return i&&(s+="_T"),`\n vec4 ${s}(int m[${e}]) {\n int offset = indicesToOffset_${t}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords);\n }\n `}}e.CoordsGlslLib=u},8520:(t,e)=>{"use strict";var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TopologicalSortGlslRoutines=e.GlslLibRoutineNode=e.GlslLibRoutine=e.GlslLib=e.GlslContext=e.FunctionType=void 0,(n=e.FunctionType||(e.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",e.GlslContext=class{constructor(t,e,n,r){this.glContext=t,this.programInfo=e,this.inputTextureLayouts=n,this.outputTextureLayout=r}},e.GlslLib=class{constructor(t){this.context=t}},e.GlslLibRoutine=class{constructor(t,e){this.routineBody=t,this.dependencies=e}},e.GlslLibRoutineNode=class{constructor(t,e,n){this.name=t,this.dependencies=n||[],e&&(this.routineBody=e)}addDependency(t){t&&this.dependencies.push(t)}},e.TopologicalSortGlslRoutines=class{static returnOrderedNodes(t){if(!t||0===t.length)return[];if(1===t.length)return t;const e=new Set,n=new Set,r=new Array;return this.createOrderedNodes(t,e,n,r),r}static createOrderedNodes(t,e,n,r){for(let i=0;i0)for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EncodingGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ")}}encodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n highp vec4 encode(highp float f) {\n highp float F = abs(f);\n highp float Sign = step(0.0,-f);\n highp float Exponent = floor(log2(F));\n highp float Mantissa = (exp2(- Exponent) * F);\n Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n highp vec4 rgba;\n rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));\n rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n ${t}\n rgba = rgba / 255.0; // values need to be normalized to [0,1]\n return rgba;\n }\n `)}}decodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n highp float decode(highp vec4 rgba) {\n rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n ${t}\n highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n return Result;\n }\n `)}}static isLittleEndian(){const t=new ArrayBuffer(4),e=new Uint32Array(t),n=new Uint8Array(t);if(e[0]=3735928559,239===n[0])return!0;if(222===n[0])return!1;throw new Error("unknown endianness")}}e.EncodingGlslLib=i},9894:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FragColorGlslLib=void 0;const r=n(8520),i=n(5060);class o extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const t=(0,i.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n void setFragColor(float value) {\n ${t.output} = encode(value);\n }\n `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ",["encoding.decode"])}}}e.FragColorGlslLib=o},2848:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;e.replaceInlines=function(t){const e={};let r;for(;null!==(r=n.exec(t));){const t=r[3].split(",").map((t=>{const e=t.trim().split(" ");return e&&2===e.length?{type:e[0],name:e[1]}:null})).filter((t=>null!==t));e[r[2]]={params:t,body:r[4]}}for(const n in e){const i="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),o=new RegExp(i,"gm");for(;null!==(r=o.exec(t));){const i=r[1],o=r[2],s=r[3].split(","),a=i?`${i} ${o};`:"";let u=e[n].body,l="";e[n].params.forEach(((t,e)=>{t&&(l+=`${t.type} ${t.name} = ${s[e]};\n`)})),u=`${l}\n ${u}`,u=u.replace("return",`${o} = `);const c=`\n ${a}\n {\n ${u}\n }\n `;t=t.replace(r[0],c)}}return t.replace(n,"")}},8879:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GlslPreprocessor=void 0;const r=n(8520),i=n(2848),o=n(5483),s=n(5060);e.GlslPreprocessor=class{constructor(t,e,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(t,e,n,i),Object.keys(o.glslRegistry).forEach((t=>{const e=new o.glslRegistry[t](this.context);this.libs[t]=e}));const s=this.glslLibRoutineDependencyGraph;for(const t in this.libs){const e=this.libs[t].getFunctions();for(const n in e){const i=t+"."+n;let o;s[i]?(o=s[i],o.routineBody=e[n].routineBody):(o=new r.GlslLibRoutineNode(i,e[n].routineBody),s[i]=o);const a=e[n].dependencies;if(a)for(let t=0;t{const r=n.split(".")[1];-1!==t.indexOf(r)&&e.push(this.glslLibRoutineDependencyGraph[n])})),r.TopologicalSortGlslRoutines.returnOrderedNodes(e)}getUniforms(t,e){const n=[];if(t)for(const e of t)n.push(`uniform sampler2D ${e};`);if(e)for(const t of e)n.push(`uniform ${t.type} ${t.name}${t.arrayLength?`[${t.arrayLength}]`:""};`);return n.join("\n")}}},5483:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.glslRegistry=void 0;const r=n(5107),i=n(7341),o=n(9894),s=n(2655),a=n(3891);e.glslRegistry={encoding:i.EncodingGlslLib,fragcolor:o.FragColorGlslLib,vec:a.VecGlslLib,shapeUtils:s.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},2655:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ShapeUtilsGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const t=this.context.outputTextureLayout.shape.length,e={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=t){const i=o.length,s=t-i,a=`bcastIndices_${n}`;let u="";for(let t=0;t{const o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>t)){const i=o.length,s=t-i,a=`bcastMatmulIndices_${n}`;let u="";for(let t=0;t{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`indicesToOffset_${e}`;t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s)),u=`indicesToOffset_${e}_T`,t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,a,s.slice().reverse()))})),t}static indexToOffsetSingle(t,e,n){let r="";for(let t=e-1;t>=0;--t)r+=`\n offset += indices[${t}] * ${n[t]};\n `;return`\n int ${t}(int indices[${e}]) {\n int offset = 0;\n ${r}\n return offset;\n }\n `}offsetToIndices(){const t={};return this.context.programInfo.inputNames.forEach(((e,n)=>{const o=this.context.inputTextureLayouts[n].shape,s=this.context.inputTextureLayouts[n].strides,a=o.length;let u=`offsetToIndices_${e}`;t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s)),u=`offsetToIndices_${e}_T`,t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,a,s.slice().reverse()))})),t}static offsetToIndicesSingle(t,e,n){const r=[];for(let t=0;t{const i=this.context.inputTextureLayouts[n].shape,o=i.length,s=`incrementIndices_${e}`;let a="";for(let t=0;t= 0; --i) {\n if(i > axis) continue;\n indices[i] += 1;\n if(indices[i] < shape[i]) {\n break;\n }\n indices[i] = 0;\n }\n }\n `;t[s]=new r.GlslLibRoutine(u)})),t}}e.ShapeUtilsGlslLib=i},5060:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultFragShaderMain=e.getFragShaderPreamble=e.getVertexShaderSource=e.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function i(t){return 1===t?n:r}e.getGlsl=i,e.getVertexShaderSource=function(t){const e=i(t);return`${e.version}\n precision highp float;\n ${e.attribute} vec3 position;\n ${e.attribute} vec2 textureCoord;\n\n ${e.varyingVertex} vec2 TexCoords;\n\n void main()\n {\n gl_Position = vec4(position, 1.0);\n TexCoords = textureCoord;\n }`},e.getFragShaderPreamble=function(t){const e=i(t);return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFrag} vec2 TexCoords;\n ${e.outputDeclaration}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n // Custom vector types to handle higher dimenalities.\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n `},e.getDefaultFragShaderMain=function(t,e){return`\n void main() {\n int indices[${e}];\n toVec(TexCoords, indices);\n vec4 result = vec4(process(indices));\n ${i(t).output} = result;\n }\n `}},3891:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VecGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const t=this.context.outputTextureLayout.shape.length,e={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const i in e){const o=`${i}Vec`;let s="";for(let n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLInferenceHandler=void 0;const r=n(6231),i=n(9162),o=n(2517),s=n(2403),a=n(7019),u=n(8710),l=n(5611),c=n(4057),h=n(2039);e.WebGLInferenceHandler=class{constructor(t){this.session=t,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(t,e){return(0,c.calculateTextureWidthAndHeight)(this.session.layoutStrategy,t,e)}executeProgram(t,e){if(e.length{const n=e.map((t=>`${t.unpackedShape.join(",")};${t.width}x${t.height}`)).join("_");let r=t.name;return t.cacheHint&&(r+="["+t.cacheHint+"]"),r+=":"+n,r})(t,n);let i=this.session.programManager.getArtifact(r);const o=i?i.programInfo:"function"==typeof t.get?t.get():t,s=(0,c.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o.output.dims,o.output.textureType),a=this.createTextureData(s,o.output.type);return i||(i=this.session.programManager.build(o,n,a),this.session.programManager.setArtifact(r,i)),this.runProgram(i,n,a),a}run(t,e){return this.executeProgram(t,e).tensor}runProgram(t,e,n){for(let n=0;nthis.readTexture(s)),(async t=>this.readTextureAsync(s)),void 0,o),texture:n});return this.setTextureData(s.tensor.dataId,s,t.isPacked),s}getTextureData(t,e=!1){return this.session.isInitializer(t)?this.session.getTextureData(t,e):e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){this.session.isInitializer(t)?this.session.setTextureData(t,e,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(t,e)}isTextureLayoutCached(t,e=!1){return!!this.getTextureData(t.dataId,e)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((t=>this.session.textureManager.releaseTexture(t))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((t=>this.session.textureManager.releaseTexture(t))),this.unpackedTextureDataCache=new Map}readTexture(t){return t.isPacked?this.readTexture(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}async readTextureAsync(t){return t.isPacked?this.readTextureAsync(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}pack(t){return this.executeProgram((0,s.createPackProgramInfoLoader)(this,t.tensor),[t.tensor])}unpack(t){return this.executeProgram((0,l.createUnpackProgramInfoLoader)(this,t.tensor),[t.tensor])}}},1640:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WEBGL_OP_RESOLVE_RULES=void 0;const s=n(2898),a=o(n(7839)),u=n(4196),l=n(2069),c=n(8138),h=n(9663),d=n(5193),f=n(7992),p=n(1253),g=n(4776),m=n(6572),y=n(3346),b=n(5623),_=n(2870),v=n(2143),w=n(4939),x=n(718),T=n(2268),S=n(8117),O=n(2278),E=n(5524),I=n(5975),A=n(3933),P=n(6558),C=n(5723),D=n(3738),k=o(n(4909)),R=n(8428),M=n(9793);e.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",a.add],["And","","7+",a.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",v.averagePool,v.parseAveragePoolAttributes],["BatchNormalization","","7+",s.batchNormalization,s.parseBatchNormalizationAttributes],["Cast","","6+",u.cast,u.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",l.concat,l.parseConcatAttributes],["Conv","","1+",c.conv,c.parseConvAttributes],["ConvTranspose","","1+",h.convTranspose,h.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",a.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",d.depthToSpace,d.parseDepthToSpaceAttributes],["Equal","","7+",a.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",f.flatten,f.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",c.conv,c.parseConvAttributes],["Gather","","1+",p.gather,p.parseGatherAttributes],["Gemm","","7-10",g.gemm,g.parseGemmAttributesV7],["Gemm","","11+",g.gemm,g.parseGemmAttributesV11],["GlobalAveragePool","","1+",v.globalAveragePool,v.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",v.globalMaxPool],["Greater","","7+",a.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",m.imageScaler,m.parseImageScalerAttributes],["InstanceNormalization","","6+",y.instanceNormalization,y.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",a.less],["Log","","6+",k.log],["MatMul","","1+",b.matMul,b.parseMatMulAttributes],["MaxPool","","1+",v.maxPool,v.parseMaxPoolAttributes],["Mul","","7+",a.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",a.or],["Pad","","2-10",_.padV2,_.parsePadAttributesV2],["Pad","","11+",_.padV11,_.parsePadAttributesV11],["Pow","","7+",a.pow],["PRelu","","7+",a.pRelu],["ReduceLogSum","","1+",w.reduceLogSum,w.parseReduceAttributes],["ReduceMax","","1+",w.reduceMax,w.parseReduceAttributes],["ReduceMean","","1+",w.reduceMean,w.parseReduceAttributes],["ReduceMin","","1+",w.reduceMin,w.parseReduceAttributes],["ReduceProd","","1+",w.reduceProd,w.parseReduceAttributes],["ReduceSum","","1-12",w.reduceSum,w.parseReduceAttributes],["ReduceSumSquare","","1+",w.reduceLogSumSquare,w.parseReduceAttributes],["Relu","","6+",k.relu],["Reshape","","5+",x.reshape],["Resize","","10",T.resize,T.parseResizeAttributesV10],["Resize","","11+",T.resize,T.parseResizeAttributesV11],["Shape","","1+",S.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",O.sliceV10],["Slice","","1-9",O.slice,O.parseSliceAttributes],["Softmax","","1-12",E.softmax,E.parseSoftmaxAttributes],["Softmax","","13+",E.softmaxV13,E.parseSoftmaxAttributesV13],["Split","","2-12",I.split,I.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",A.squeeze,A.parseSqueezeAttributes],["Squeeze","","13+",A.squeezeV13],["Sub","","7+",a.sub],["Sum","","6+",P.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",C.tile],["Transpose","","1+",D.transpose,D.parseTransposeAttributes],["Upsample","","7-8",M.upsample,M.parseUpsampleAttributesV7],["Upsample","","9",M.upsample,M.parseUpsampleAttributesV9],["Unsqueeze","","1-12",R.unsqueeze,R.parseUnsqueezeAttributes],["Unsqueeze","","13+",R.unsqueezeV13],["Xor","","7+",a.xor]]},2898:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseBatchNormalizationAttributes=e.batchNormalization=void 0;const r=n(246),i=n(5060),o=n(2039),s={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};e.batchNormalization=(t,e,n)=>(u(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(t,e,n)}),e)]),e.parseBatchNormalizationAttributes=t=>{const e=t.attributes.getFloat("epsilon",1e-5),n=t.attributes.getFloat("momentum",.9),i=t.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:e,momentum:n,spatial:i})};const a=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),a=e[0].dims.length,[u,l]=t.calculateTextureWidthAndHeight(e[1].dims,o.TextureType.unpacked),c=`\n float process(int[${a}] indices) {\n vec2 position = offsetToCoords(indices[1], ${u}, ${l});\n float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n float b = getColorAsFloat(${r.texture2D}(B, position));\n\n return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n }`;return Object.assign(Object.assign({},s),{output:{dims:e[0].dims,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:c})},u=t=>{if(!t||5!==t.length)throw new Error("BatchNormalization requires 5 inputs.");const e=t[0],n=t[1],r=t[2],i=t[3],o=t[4];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==i.dims.length||1!==o.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1]||o.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==i.type&&"float64"!==i.type||"float32"!==o.type&&"float64"!==o.type)throw new Error("invalid input tensor types.")}},7839:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.xor=e.sub=e.pRelu=e.pow=e.or=e.mul=e.less=e.greater=e.equal=e.div=e.and=e.add=e.glslPRelu=e.glslPow=e.glslXor=e.glslOr=e.glslAnd=e.glslLess=e.glslGreater=e.glslEqual=e.glslSub=e.glslMul=e.glslDiv=e.glslAdd=void 0;const r=n(2517),i=n(8520),o=n(5060),s=n(2039);function a(){const t="add_";return{body:"\n float add_(float a, float b) {\n return a + b;\n }\n vec4 add_(vec4 v1, vec4 v2) {\n return v1 + v2;\n }\n ",name:t,type:i.FunctionType.ValueBased}}function u(){const t="div_";return{body:"\n float div_(float a, float b) {\n return a / b;\n }\n vec4 div_(vec4 v1, vec4 v2) {\n return v1 / v2;\n }\n ",name:t,type:i.FunctionType.ValueBased}}function l(){const t="mul_";return{body:"\n float mul_(float a, float b) {\n return a * b;\n }\n vec4 mul_(vec4 v1, vec4 v2) {\n return v1 * v2;\n }\n ",name:t,type:i.FunctionType.ValueBased}}function c(){const t="sub_";return{body:"\n float sub_(float a, float b) {\n return a - b;\n }\n vec4 sub_(vec4 v1, vec4 v2) {\n return v1 - v2;\n }\n ",name:t,type:i.FunctionType.ValueBased}}function h(){const t="equal_";return{body:`\n float ${t}(float a, float b) {\n return float(a == b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4(equal(v1, v2));\n }\n `,name:t,type:i.FunctionType.ValueBased}}function d(){const t="greater_";return{body:`\n float ${t}(float a, float b) {\n return float(a > b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4( v1.r > v2.r ,\n v1.g > v2.g,\n v1.b > v2.b,\n v1.a > v2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function f(){const t="less_";return{body:`\n float ${t}(float a, float b) {\n return float(a < b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4( v1.r < v2.r ,\n v1.g < v2.g,\n v1.b < v2.b,\n v1.a < v2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function p(){const t="and_";return{body:"\n float and_(float a, float b) {\n return float( bool(a) && bool(b) );\n }\n vec4 and_(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r && b2.r ,\n b1.g && b2.g,\n b1.b && b2.b,\n b1.a && b2.a );\n }\n ",name:t,type:i.FunctionType.ValueBased}}function g(){const t="or_";return{body:"\n float or_(float a, float b) {\n return float( bool(a) || bool(b) );\n }\n vec4 or_(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r || b2.r ,\n b1.g || b2.g,\n b1.b || b2.b,\n b1.a || b2.a );\n }\n ",name:t,type:i.FunctionType.ValueBased}}function m(){const t="xor_";return{body:"\n float xor_(float a, float b) {\n return float( bool(a) ^^ bool(b) );\n }\n vec4 xor_(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r ^^ b2.r ,\n b1.g ^^ b2.g,\n b1.b ^^ b2.b,\n b1.a ^^ b2.a );\n }\n ",name:t,type:i.FunctionType.ValueBased}}function y(){return function(t){const e="pow_";return{body:"\n float pow_(float a, float b) {\n return pow(a, b);\n }\n vec4 pow_(vec4 v1, vec4 v2) {\n return pow(v1, v2);\n }\n ",name:e,type:i.FunctionType.ValueBased}}()}function b(){const t="prelu_";return{body:`\n float ${t}(float a, float b) {\n return a < 0.0 ? a * b: a;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4(\n v1.r < 0.0 ? v1.r * v2.r: v1.r,\n v1.g < 0.0 ? v1.g * v2.g: v1.g,\n v1.b < 0.0 ? v1.b * v2.b: v1.b,\n v1.a < 0.0 ? v1.a * v2.a: v1.a\n );\n }\n `,name:t,type:i.FunctionType.ValueBased}}e.glslAdd=a,e.glslDiv=u,e.glslMul=l,e.glslSub=c,e.glslEqual=h,e.glslGreater=d,e.glslLess=f,e.glslAnd=p,e.glslOr=g,e.glslXor=m,e.glslPow=y,e.glslPRelu=b;const _=(t,e,n,r=e[0].type,i)=>{const o=t.session.pack?s.TextureType.packed:s.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>v(t,e,n,r)}},v=(t,e,n,i=e[0].type)=>{const a=t.session.pack?s.TextureType.packed:s.TextureType.unpacked,u=!r.ShapeUtil.areEqual(e[0].dims,e[1].dims);let l=e[0].dims;const c=t.session.pack;if(u){const s=r.BroadcastUtil.calcShape(e[0].dims,e[1].dims,!1);if(!s)throw new Error("Can't perform binary op on the given tensors");l=s;const u=l.length,h=0!==e[0].dims.length?e[0].dims.length:1,d=0!==e[1].dims.length?e[1].dims.length:1,f=0!==e[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",p=0!==e[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",g=(0,o.getGlsl)(t.session.backend.glContext.version),m=c?`\n ${n.body}\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n vec4 result = ${n.name}(a, b);\n ${g.output} = result;\n }`:`\n ${n.body}\n float process(int indices[${u}]) {\n int aindices[${h}];\n int bindices[${d}];\n ${f}\n ${p}\n return ${n.name}(_A(aindices), _B(bindices));\n }`;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:l,type:i,textureType:a},shaderSource:m,hasMain:c}}const h=(0,o.getGlsl)(t.session.backend.glContext.version),d=`\n ${n.body}\n void main() {\n vec4 v1 = ${h.texture2D}(A, TexCoords);\n vec4 v2 = ${h.texture2D}(B, TexCoords);\n vec4 result = ${n.name}(v1, v2);\n ${h.output} = result;\n }\n `;return{name:n.name,inputNames:["A","B"],inputTypes:[a,a],output:{dims:e[0].dims,type:i,textureType:a},shaderSource:d,hasMain:!0}};e.add=(t,e)=>[t.run(_(t,e,a()),e)],e.and=(t,e)=>[t.run(_(t,e,p(),"bool"),e)],e.div=(t,e)=>[t.run(_(t,e,u()),e)],e.equal=(t,e)=>[t.run(_(t,e,h(),"bool"),e)],e.greater=(t,e)=>[t.run(_(t,e,d(),"bool"),e)],e.less=(t,e)=>[t.run(_(t,e,f(),"bool"),e)],e.mul=(t,e)=>[t.run(_(t,e,l()),e)],e.or=(t,e)=>[t.run(_(t,e,g(),"bool"),e)],e.pow=(t,e)=>[t.run(_(t,e,y()),e)],e.pRelu=(t,e)=>[t.run(_(t,e,b()),e)],e.sub=(t,e)=>[t.run(_(t,e,c()),e)],e.xor=(t,e)=>[t.run(_(t,e,m(),"bool"),e)]},4196:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseCastAttributes=e.cast=void 0;const r=n(2517);e.cast=(t,e,n)=>(i(e),[t.cast(e[0],n)]),e.parseCastAttributes=t=>r.ProtoUtil.tensorDataTypeFromProto(t.attributes.getInt("to"));const i=t=>{if(!t||1!==t.length)throw new Error("Cast requires 1 input.");if("string"===t[0].type)throw new Error("Invalid input type.")}},1163:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedConcatProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827);e.createPackedConcatProgramInfoLoader=(t,e,n)=>{const u=(l=e.length,c=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:l},((t,e)=>`X${e}`)),inputTypes:Array(l).fill(i.TextureType.packed),cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const l=n[0].dims.slice();if(u>=l.length||u<-1*l.length)throw new Error("axis specified for concat doesn't match input dimensionality");u<0&&(u=l.length+u);const c=l.slice(0);for(let t=1;tt.dims)),m=(0,o.getGlChannels)(h),y=new Array(g.length-1);y[0]=g[0][u];for(let t=1;t= ${y[t-1]}) {\n return getChannel(\n getX${t}(${a(m,b,e)}),\n vec2(${a(_,b,e)}));\n }`}const x=y.length,T=y[y.length-1];w+=`\n return getChannel(\n getX${x}(${a(m,b,T)}),\n vec2(${a(_,b,T)}));`;const S=(0,r.getGlsl)(t.session.backend.glContext.version),O=`\n ${p}\n float getValue(${m.map((t=>"int "+t))}) {\n ${w}\n }\n\n void main() {\n ${f} coords = getOutputCoords();\n int lastDim = coords.${m[h-1]};\n coords.${m[h-1]} = coords.${m[h-2]};\n coords.${m[h-2]} = lastDim;\n\n vec4 result = vec4(getValue(${d}), 0., 0., 0.);\n\n ${d[h-1]} = ${d[h-1]} + 1;\n if (${d[h-1]} < ${c[h-1]}) {\n result.g = getValue(${d});\n }\n\n ${d[h-2]} = ${d[h-2]} + 1;\n if (${d[h-2]} < ${c[h-2]}) {\n result.a = getValue(${d});\n }\n\n ${d[h-1]} = ${d[h-1]} - 1;\n if (${d[h-2]} < ${c[h-2]} &&\n ${d[h-1]} < ${c[h-1]}) {\n result.b = getValue(${d});\n }\n ${S.output} = result;\n }\n `;return Object.assign(Object.assign({},e),{output:{dims:c,type:n[0].type,textureType:i.TextureType.packed},shaderSource:O,hasMain:!0})})(t,u,e,n.axis)})};const a=(t,e,n)=>{const r=t.indexOf(e);return t.map(((t,e)=>e===r?`${t} - ${n}`:t)).join()}},2069:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConcatAttributes=e.concat=void 0;const r=n(246),i=n(2039),o=n(1163);e.concat=(t,e,n)=>(h(e),t.session.pack&&e[0].dims.length>1?[t.run((0,o.createPackedConcatProgramInfoLoader)(t,e,n),e)]:[t.run(s(t,e,n),e)]);const s=(t,e,n)=>{const r=(o=e.length,s=n.cacheKey,{name:"Concat",inputNames:Array.from({length:o},((t,e)=>`X${e}`)),inputTypes:Array(o).fill(i.TextureType.unpacked),cacheHint:s});var o,s;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice();if(r>=o.length||r<-1*o.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=o.length+r);const s=o.slice(0);for(let t=1;t`int getTextureWhereDataResides(int index) {\n ${t.map(((t,e)=>`if(index<${t}) {return ${e};}\n`)).join("")}\n }`,u=t=>a(t),l=(t,e)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let e=0;e{const e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis")});const h=t=>{if(!t||t.length<1)throw new Error("too few inputs");const e=t[0].type,n=t[0].dims.length;if("string"===e)throw new Error("string tensor is not supported yet");for(const r of t){if(r.type!==e)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},4770:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(6231),i=n(5060),o=n(2039),s=n(8138),a=n(2823);e.createUnpackedGroupedConvProgramInfoLoader=(t,e,n)=>{const u=(l=e.length>2,c=n.cacheKey,{name:"GroupedConv",inputNames:l?["X","W","Bias"]:["X","W"],inputTypes:l?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:c});var l,c;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const l=e.length>2?"value += getBias(output_channel);":"",c=e[0].dims.slice(),h=e[1].dims.slice(),d=h[0]/u.group;r.Logger.verbose("GroupedConv",`autpPad:${u.autoPad}, dilations:${u.dilations}, group:${u.group}, kernelShape:${u.kernelShape}, pads:${u.pads}, strides:${u.strides}`);const f=(0,s.calculateOutputShape)(c,h,u.dilations,u.pads,u.strides),p=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:g,applyActivation:m}=(0,a.getActivationSnippet)(u),y=`\n const ivec2 strides = ivec2(${u.strides[0]}, ${u.strides[1]});\n const ivec2 pads = ivec2(${u.pads[0]}, ${u.pads[1]});\n ${g}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n ivec2 xRCCorner = coords.zw * strides - pads;\n int group_id = output_channel / ${d};\n\n float value = 0.0;\n for (int wInChannel = 0; wInChannel < ${h[1]}; wInChannel++) {\n int input_channel = group_id * ${h[1]} + wInChannel;\n for (int wHeight = 0; wHeight < ${h[2]}; wHeight++) {\n int xHeight = xRCCorner.x + wHeight * ${u.dilations[0]};\n\n if (xHeight < 0 || xHeight >= ${c[2]}) {\n continue;\n }\n\n for (int wWidth = 0; wWidth < ${h[3]}; wWidth++) {\n int xWidth = xRCCorner.y + wWidth * ${u.dilations[1]};\n if (xWidth < 0 || xWidth >= ${c[3]}) {\n continue;\n }\n\n float xVal = getX(batch, input_channel, xWidth, xHeight);\n float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n value += xVal*wVal;\n }\n }\n }\n ${l}\n ${m}\n ${p.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:f,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:y,hasMain:!0})})(t,e,u,n)})}},1386:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.conv2DPacked=e.conv2DPackedPointwise=void 0;const r=n(8138),i=n(8555),o=n(708);e.conv2DPackedPointwise=(t,e,n)=>{const i=e[0].dims,s=e[1].dims,a=(0,r.calculateOutputShape)(i,s,n.dilations,n.pads,n.strides),u=t.reshapePacked(e[0],[i[1],i[2]*i[3]]),l=t.reshapePacked(e[1],[s[0],s[1]]),c=e.length>2?[l,u,e[2]]:[l,u],h=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,c,n),c);return t.reshapePacked(h,a)},e.conv2DPacked=(t,e,n)=>{const s=e[0].dims,a=e[1].dims,u=(0,r.calculateOutputShape)(s,a,n.dilations,n.pads,n.strides),l=t.run((0,i.createPackedIm2ColProgramInfoLoader)(t,e[0],e[1],u,n),[e[0]]),c=t.reshapePacked(e[1],[a[0],a[1]*a[2]*a[3]]),h=3===e.length?[c,l,e[2]]:[c,l],d=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,h,n),h);return t.reshapePacked(d,u)}},9663:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvTransposeAttributes=e.convTranspose=void 0;const r=n(246),i=n(5060),o=n(2039),s=n(2823),a=(t,e,n,r,i,o)=>(t-1)*e+n+(r-1)*i+1-o,u=(t,e,n,r,i)=>{const o=Math.floor(t/2);"SAME_UPPER"===e?(n[r]=o,n[i]=t-o):"SAME_LOWER"===e&&(n[r]=t-o,n[i]=o)};e.convTranspose=(t,e,n)=>(d(e,n),l(t,e,n));const l=(t,e,n)=>{const r=h(n,e);return[c(t,e,r)]},c=(t,e,n)=>t.run(((t,e,n)=>{const r=(a=e.length>2,u=n.cacheKey,{name:"ConvTranspose",inputNames:a?["X","W","B"]:["X","W"],inputTypes:a?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:u});var a,u;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const a=e.length>2?"getB(output_channel)":"0.0",u=e[0].dims,l=e[1].dims,c=l[1],h=l[0]/r.group,d=[e[0].dims[0],e[1].dims[1]*r.group,...r.outputShape],f=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:p,applyActivation:g}=(0,s.getActivationSnippet)(r),m=`\n const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n ${p}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n\n ivec2 loc = coords.zw + pads;\n\n int group_id = output_channel / ${c};\n int wOutChannel = output_channel - group_id * ${c};\n\n float value = ${a};\n for (int inChannelOffset = 0; inChannelOffset < ${h}; inChannelOffset++) {\n int input_channel = group_id * ${h} + inChannelOffset;\n for (int wWOff = 0; wWOff < ${l[2]}; wWOff++) {\n for (int wHOff = 0; wHOff < ${l[3]}; wHOff++) {\n ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n ivec2 wLoc = loc - wOff;\n ivec2 wLocIn = wLoc / strides;\n if (\n wLocIn * strides == wLoc &&\n wLocIn.x >= 0 && wLocIn.x < ${u[2]} &&\n wLocIn.y >= 0 && wLocIn.y < ${u[3]}\n ) {\n float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n value += xVal * wVal;\n }\n }\n }\n }\n ${g}\n ${f.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:d,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:m,hasMain:!0})})(t,e,r,n)})})(t,e,n),e),h=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t{const c=t.length-2,h=0===l.length;for(let d=0;d{const e=t.attributes,n=(0,s.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),a=e.getInt("group",1),u=e.getInts("kernel_shape",[]),l=e.getInts("output_padding",[0,0]),c=e.getInts("output_shape",[]),h=e.getInts("pads",[0,0,0,0]),d=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:a,kernelShape:u,outputPadding:l,outputShape:c,pads:h,strides:d},n))};const d=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=t[1].dims[1]*e.group;if(3===t.length&&(1!==t[2].dims.length||t[2].dims[0]!==n))throw new Error("invalid bias");const r=t[0].dims.length-2;if(e.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(e.strides.length!==r)throw new Error(`strides should be ${r}D`);if(e.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(e.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==e.outputShape.length&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvAttributes=e.conv=e.calculateOutputShape=void 0;const r=n(246),i=n(2517),o=n(4770),s=n(1386),a=n(9828),u=n(2823),l=n(3248),c=n(5623);e.calculateOutputShape=(t,e,n,r,i)=>{const o=t[0],s=t.slice(2),a=s.length,u=e[0],l=e.slice(2).map(((t,e)=>t+(t-1)*(n[e]-1))),c=s.map(((t,e)=>t+r[e]+r[e+a])).map(((t,e)=>Math.floor((t-l[e]+i[e])/i[e])));return[o,u].concat(...c)},e.conv=(t,e,n)=>(g(e,n),h(t,e,n));const h=(t,e,n)=>{const r=p(n,e),i=t.session.pack,a=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[t.run((0,o.createUnpackedGroupedConvProgramInfoLoader)(t,e,r),e)]:a&&i?[d(t,e,r)]:i&&4===e[0].dims.length&&1===e[0].dims[0]&&!a?[(0,s.conv2DPacked)(t,e,r)]:[f(t,e,r)]},d=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),a=t.reshapeUnpacked(n[0],[i[1],i[2]*i[3]]),u=t.reshapeUnpacked(n[1],[o[0],o[1]]),l=n.length>2?[u,a,n[2]]:[u,a],h=t.run((0,c.createMatmulProgramInfoLoader)(l,r),l);return t.reshapeUnpacked(h,s)},f=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,s=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),u=t.run((0,l.createIm2ColProgramInfoLoader)(t,n[0],n[1],s,r),[n[0]]),c=3===n.length?[u,n[1],n[2]]:[u,n[1]];return t.run((0,a.createDotProductProgramInfoLoader)(t,n,s,r),c)},p=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t{const e=t.attributes,n=(0,u.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),s=e.getInt("group",1),a=e.getInts("kernel_shape",[]),l=e.getInts("pads",[0,0,0,0]),c=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:s,kernelShape:a,pads:l,strides:c},n))};const g=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[1]*e.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===t.length&&(1!==t[2].dims.length||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");const n=t[0].dims.length-2;if(e.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(e.strides.length!==n)throw new Error(`strides should be ${n}D`);if(e.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("Conv input(bias) should be float tensor")}},5193:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseDepthToSpaceAttributes=e.depthToSpace=void 0;const r=n(3738);e.depthToSpace=(t,e,n)=>{i(e);const o=n.blocksize,s=o*o,a="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],u="DCR"===n.mode?[e[0].dims[0],o,o,e[0].dims[1]/s,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/s,o,o,e[0].dims[2],e[0].dims[3]],l=t.reshapeUnpacked(e[0],u),c={perm:a,cacheKey:`${a}`},[h]=(0,r.transpose)(t,[l],c),d=[e[0].dims[0],e[0].dims[1]/s,e[0].dims[2]*o,e[0].dims[3]*o];return[t.reshapeUnpacked(h,d)]},e.parseDepthToSpaceAttributes=t=>{const e=t.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);const n=t.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:e}};const i=t=>{if(1!==t.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`);if("string"===t[0].type||4!==t[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createDotProductProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),s=n(2823),a=n(3248);e.createDotProductProgramInfoLoader=(t,e,n,u)=>{const l=((t,e)=>({name:"ConvDotProduct",inputNames:t?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:t?[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.packedLastDimension],cacheKey:e.activationCacheKey}))(e.length>2,u);return Object.assign(Object.assign({},l),{get:()=>((t,e,n,u,l)=>{const c=n[0].dims,h=n[1].dims,d=[h[0],Math.ceil(c[1]*h[2]*h[3]/4)],f=(0,a.calculateIm2ColDims)(c,h,u),[p,g]=t.calculateTextureWidthAndHeight(d,o.TextureType.packedLastDimension),m=r.ShapeUtil.computeStrides(f),[y,b]=t.calculateTextureWidthAndHeight(f,o.TextureType.packedLastDimension),_=u.length,v=n.length<3?"0.0":"_B(b)",w=Math.ceil(c[1]*h[2]*h[3]/4),{activationFunction:x,applyActivation:T}=(0,s.getActivationSnippet)(l),S=(0,i.getGlsl)(t.session.backend.glContext.version),O=`\n${x}\nfloat process(int indices[${_}]) {\n int b[1];\n b[0] = indices[1];\n int im2col[4];\n im2col[0] = indices[0];\n im2col[1] = indices[2];\n im2col[2] = indices[3];\n int im2colOffset = im2col[0] * ${m[0]} + im2col[1] * ${m[1]} + im2col[2] * ${m[2]};\n int kernelOffset = indices[1] * ${d[1]};\n float value = ${v};\n for (int i = 0; i < ${w}; ++i) {\n vec2 im2colCoords = offsetToCoords(im2colOffset, ${y}, ${b});\n vec2 kernelCoords = offsetToCoords(kernelOffset, ${p}, ${g});\n value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords));\n ++im2colOffset;\n ++kernelOffset;\n }\n ${T}\n return value;\n}`;return Object.assign(Object.assign({},e),{output:{dims:u,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:O})})(t,l,e,n,u)})}},7992:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseFlattenAttributes=e.flatten=void 0;const r=n(2517);e.flatten=(t,e,n)=>{i(e,n);const o=r.ShapeUtil.flattenShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.parseFlattenAttributes=t=>t.attributes.getInt("axis",1);const i=(t,e)=>{if(!t||1!==t.length)throw new Error("Flatten requires 1 input.");const n=t[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(e<-n||e>n)throw new Error("Invalid axis");if("string"===t[0].type)throw new Error("string tensor is not supported.")}},2823:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseInternalActivationAttributes=e.getActivationSnippet=void 0;const r=n(2517),i=n(4909);e.getActivationSnippet=function(t){let e;switch(t.activation){case"Relu":e=(0,i.glslRelu)();break;case"Sigmoid":e=(0,i.glslSigmoid)();break;case"Clip":e=(0,i.glslClip)(t.clipMin,t.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=e.name;return{activationFunction:e.body,applyActivation:`value = ${n}_(value);`}},e.parseInternalActivationAttributes=t=>{const e=t.getString("activation","");if("Clip"===e){const[n,i]=t.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:e,clipMax:i,clipMin:n,activationCacheKey:`${e}:${n},${i}`}}return{activation:e,activationCacheKey:e}}},1253:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseGatherAttributes=e.gather=void 0;const r=n(246),i=n(782),o=n(2517),s=n(2039);e.gather=(t,e,n)=>(l(e,n.axis),[t.run(u(t,e,n),e)]),e.parseGatherAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",0)});const a={name:"Gather",inputNames:["A","B"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},u=(t,e,n)=>{const r=Object.assign(Object.assign({},a),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const i=n[0].dims.slice(),a=n[1].dims.slice(),u=new Array(i.length+a.length-1);r=o.ShapeUtil.normalizeAxis(r,i.length);const l=[];for(let t=0;t{if(!t||2!==t.length)throw new Error("Gather requires 2 inputs.");const n=t[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(e<-n||e>n-1)throw new Error("Invalid axis.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invaid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invaid input type.")}},4776:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseGemmAttributesV11=e.parseGemmAttributesV7=e.gemm=void 0;const r=n(246),i=n(2517),o=n(2039);e.gemm=(t,e,n)=>(l(e,n),[t.run(a(e,n),e)]);const s=(t,e)=>{const n=0!==t.attributes.getInt("transA",0),i=0!==t.attributes.getInt("transB",0),o=t.attributes.getFloat("alpha",1),s=t.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:i,alpha:o,beta:s,isOptionalC:e})};e.parseGemmAttributesV7=t=>s(t,!1),e.parseGemmAttributesV11=t=>s(t,!0);const a=(t,e)=>{const n={name:"Gemm",inputNames:3===t.length?["A","B","C"]:["A","B"],inputTypes:3===t.length?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],key:e.cacheKey};return Object.assign(Object.assign({},n),{get:()=>u(n,t,e)})},u=(t,e,n)=>{const r=e[0].dims.slice(),s=e[1].dims.slice(),[a,u]=i.GemmUtil.getShapeOfGemmResult(r,n.transA,s,n.transB,3===e.length?e[2].dims:void 0),l=[a,u];if(!l)throw new Error("Can't use gemm on the given tensors");let c=r[r.length-1],h="";n.transA&&(c=r[0]),n.transA&&n.transB?h="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?h="value += _A_T(a) * _B(b);":!n.transA&&n.transB?h="value += _A(a) * _B_T(b);":n.transA||n.transB||(h="value += _A(a) * _B(b);");const d=l.length,f=`\n float process(int indices[${d}]) {\n int a[${d}];\n int b[${d}];\n ${3===e.length?`int c[${e[2].dims.length}];`:""}\n\n copyVec(indices, a);\n copyVec(indices, b);\n ${3===e.length?"bcastIndices_C(indices, c);":""}\n\n float value = 0.0;\n for (int k=0; k<${c}; ++k) {\n a[${d-1}] = k;\n b[${d-2}] = k;\n ${h}\n }\n\n value = value * alpha;\n ${3===e.length?"value += beta * _C(c);":""}\n return value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:l,type:e[0].type,textureType:o.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:f})},l=(t,e)=>{if(!t)throw new Error("Input is missing");if(e.isOptionalC&&(t.length<2||t.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&3!==t.length)throw new Error("Gemm requires 3 inputs");if(3===t.length&&1!==t[2].dims.length&&2!==t[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type||3===t.length&&"float32"!==t[2].type&&"float64"!==t[2].type)throw new Error("Invalid input type.");if(t[0].type!==t[1].type||3===t.length&&t[0].type!==t[2].type)throw new Error("Input types are mismatched")}},8555:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedIm2ColProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(2827);e.createPackedIm2ColProgramInfoLoader=(t,e,n,s,a)=>{const u=(l=a.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[i.TextureType.packed],cacheHint:l});var l;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,s,a,u)=>{const l=n.dims,c=s.dims,h=a.length,d=[c[1]*c[2]*c[3],a[2]*a[3]],f=c[2]*c[3],p=(0,o.unpackFromChannel)(),g=(0,r.getGlsl)(t.session.backend.glContext.version);let m="";for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)m+=`\n blockIndex = rc.x + ${e};\n pos = rc.y + ${t};\n\n if(blockIndex < ${d[1]} && pos < ${d[0]}) {\n offsetY = int(blockIndex / (${a[h-1]})) * ${u.strides[0]} -\n ${u.pads[0]};\n d0 = offsetY + ${u.dilations[0]} * (imod(pos, ${f}) / ${c[2]});\n\n if(d0 < ${l[2]} && d0 >= 0) {\n offsetX = imod(blockIndex, ${a[h-1]}) * ${u.strides[1]} -\n ${u.pads[1]};\n d1 = offsetX + ${u.dilations[1]} * imod(imod(pos, ${f}), ${c[2]});\n\n if(d1 < ${l[3]} && d1 >= 0) {\n\n ch = int(float(pos)/ ${f}.);\n innerDims = vec2(d0, d1);\n result[${2*t+e}] = getChannel(\n getA(0, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n\n `;const y=`\n ${p}\n\n void main() {\n ivec2 rc = getOutputCoords();\n vec4 result = vec4(0.0);\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n ${m}\n ${g.output} = result;\n }\n `;return Object.assign(Object.assign({},e),{output:{dims:d,type:n.type,textureType:i.TextureType.packed},shaderSource:y,hasMain:!0})})(t,u,e,n,s,a)})}},3248:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.calculateIm2ColDims=e.createIm2ColProgramInfoLoader=void 0;const r=n(2039);e.createIm2ColProgramInfoLoader=(t,n,i,o,s)=>{const a=(u=s.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:u});var u;return Object.assign(Object.assign({},a),{get:()=>((t,n,i,o,s,a)=>{const u=i.dims,l=o.dims,c=s.length,h=(0,e.calculateIm2ColDims)(u,l,s,4),d=`\n const int XC = ${u[1]};\n const int XH = ${u[2]};\n const int XW = ${u[3]};\n const int KH = ${a.kernelShape[0]};\n const int KW = ${a.kernelShape[1]};\n const int dilationH = ${a.dilations[0]};\n const int dilationW = ${a.dilations[1]};\n const int strideH = ${a.strides[0]};\n const int strideW = ${a.strides[1]};\n const int padH = ${a.pads[0]};\n const int padW = ${a.pads[1]};\n const int KHKW = KH*KW;\n const int XCKHKW = XC * KHKW;\n const int outputChannels = 4;\n vec4 process(int indices[${c}]) {\n int b = indices[0]; // batch size\n int oh = indices[1] * strideH - padH; //output height\n int ow = indices[2] * strideW - padW; //output width\n int p = indices[3] * outputChannels; //patch\n vec4 value = vec4(0.0);\n for(int i=0; i < outputChannels; ++i) {\n if(p < XCKHKW) {\n int patchC = p / KHKW;\n int patchH = (p - patchC*KHKW) / KW;\n int patchW = (p - patchC*KHKW) - patchH * KW;\n int xh2 = oh + patchH * dilationH;\n int xw2 = ow + patchW * dilationW;\n int x[${u.length}];\n x[0] = b;\n x[1] = patchC;\n x[2] = xh2;\n x[3] = xw2;\n if(xh2 >= 0 &&\n xh2 < XH &&\n xw2 >= 0 &&\n xw2 < XW) {\n value[i] = _X(x);\n }\n }\n ++p;\n }\n return value;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:h,type:i.type,textureType:r.TextureType.packedLastDimension},shaderSource:d})})(0,a,n,i,o,s)})},e.calculateIm2ColDims=(t,e,n,r=4)=>[n[0],n[2],n[3],Math.ceil(t[1]*e[2]*e[3]/r)]},6572:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseImageScalerAttributes=e.imageScaler=void 0;const r=n(246),i=n(2039);e.imageScaler=(t,e,n)=>(u(e),[t.run(s(t,e,n),e)]),e.parseImageScalerAttributes=t=>{const e=t.attributes.getFloat("scale"),n=t.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:e,bias:n})};const o={name:"ImageScaler",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=(t,e,n)=>{const r=Object.assign(Object.assign({},o),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice(),s=o.length,u=`\n ${a(r.bias.length)}\n float process(int indices[${s}]) {\n return _X(indices) * scale + getBias(bias, indices[1]);\n }`;return Object.assign(Object.assign({},e),{output:{dims:o,type:n[0].type,textureType:i.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:u})})(0,r,e,n)})},a=t=>{const e=[`float getBias(float bias[${t}], int channel) {`];for(let n=0;n{if(!t||1!==t.length)throw new Error("ImageScaler requires 1 input.");if(4!==t[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")}},3346:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseInstanceNormalizationAttributes=e.instanceNormalization=void 0;const r=n(5060),i=n(2039);e.instanceNormalization=(t,e,n)=>{l(e);const r=t.run(s(e[0]),e);return[t.run(u(t,e[0],n,r.dims),[e[0],r,e[1],e[2]])]},e.parseInstanceNormalizationAttributes=t=>t.attributes.getFloat("epsilon",1e-5);const o={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},s=t=>Object.assign(Object.assign({},o),{get:()=>((t,e)=>{const n=e.dims.slice(),r=n[1],o=n[2]*n[3],s=[n[0],r],a=`\n vec4 process(int[2] indices) {\n vec4 v = vec4(0.0);\n int a[4];\n a[0] = indices[0];\n a[1] = indices[1];\n float temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += x;\n }\n }\n float mean = temp / float(${o});\n temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += (x - mean) * (x - mean);\n }\n }\n v.r = mean;\n v.g = temp / float(${o});\n\n return v;\n }`;return Object.assign(Object.assign({},t),{output:{dims:s,type:e.type,textureType:i.TextureType.packedLastDimension},shaderSource:a})})(o,t)}),a={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked,i.TextureType.unpacked]},u=(t,e,n,o)=>{const s=Object.assign(Object.assign({},a),{cacheHint:`${n}`});return Object.assign(Object.assign({},s),{get:()=>((t,e,n,o,s)=>{const a=(0,r.getGlsl)(t.session.backend.glContext.version),[u,l]=t.calculateTextureWidthAndHeight(s,i.TextureType.packedLastDimension),[c,h]=[u/4,l],d=`\n vec4 get_MeanAndVariance(int[2] mv) {\n int offset = indicesToOffset_MeanAndVariance(mv);\n vec2 coords = offsetToCoords(offset, ${c}, ${h});\n return ${a.texture2D}(MeanAndVariance, coords);\n }\n\n float process(int[4] indices) {\n int mv[2];\n mv[0] = indices[0];\n mv[1] = indices[1];\n vec4 mean_and_variance = get_MeanAndVariance(mv);\n float mean = mean_and_variance.r;\n float variance = mean_and_variance.g;\n\n int sb[1];\n sb[0] = indices[1];\n float scale = _Scale(sb);\n float b = _B(sb);\n\n return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n }`;return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:o}],shaderSource:d})})(t,s,e,n,o)})},l=t=>{if(!t||3!==t.length)throw new Error("InstanceNormalization requires 3 inputs.");const e=t[0],n=t[1],r=t[2];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==t[0].dims.length)throw new Error("Only support 4-D input shape.")}},708:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedMatmulProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),s=n(9390),a=n(2823),u=n(5623);e.createPackedMatmulProgramInfoLoader=(t,e,n)=>{const l=(c=e.length>2,h=n.activationCacheKey,{name:"MatMul (packed)",inputNames:c?["A","B","Bias"]:["A","B"],inputTypes:c?[o.TextureType.packed,o.TextureType.packed,o.TextureType.packed]:[o.TextureType.packed,o.TextureType.packed],cacheHint:h});var c,h;return Object.assign(Object.assign({},l),{get:()=>((t,e,n,l)=>{const c=n.length>2,h=c?"value += getBiasForMatmul();":"",d=n[0].dims,f=n[1].dims,p=r.BroadcastUtil.calcShape(d,f,!0),g=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!p)throw new Error("Can't use matmul on the given tensors");const m=d[d.length-1],y=Math.ceil(m/2),b=d.length,_=f.length,v=(0,i.getGlsl)(t.session.backend.glContext.version),w=(0,s.getCoordsDataType)(p.length),x=p.length,T=(0,s.getGlChannels)(),{activationFunction:S,applyActivation:O}=(0,a.getActivationSnippet)(l),E=c?`${(0,u.getBiasForMatmul)(w,T,n[2].dims,p,!0)}`:"",I=g?`${function(t,e,n,i){let o=[],s=[];const a=n[0].dims,u=n[1].dims,l=a.length,c=u.length,h=i.length,d=h-l,f=h-c;o=a.map(((t,n)=>`coords.${e[n+d]}`)),o[l-1]="i*2",o.join(", "),s=u.map(((t,n)=>`coords.${e[n+f]}`)),s[c-2]="i*2",s.join(", ");const p=r.BroadcastUtil.getBroadcastDims(a,i),g=r.BroadcastUtil.getBroadcastDims(u,i),m=p.map((t=>`coords.${e[t+d]} = 0;`)).join("\n"),y=g.map((t=>`coords.${e[t+f]} = 0;`)).join("\n"),b=`int lastDim = coords.${e[h-1]};\n coords.${e[h-1]} = coords.${e[h-2]};\n coords.${e[h-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n ${t} coords = getOutputCoords();\n ${b}\n ${m}\n vec4 outputValue = getA(${o});\n return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n ${t} coords = getOutputCoords();\n ${b}\n ${y}\n vec4 outputValue = getB(${s});\n return outputValue;\n}`}(w,T,n,p)}`:"",A=g?"getAAtOutCoordsMatmul(i)":`getA(${function(t,e){let n="";for(let r=0;r{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBiasForMatmul=e.createMatmulProgramInfoLoader=e.parseMatMulAttributes=e.matMul=void 0;const r=n(2517),i=n(2039),o=n(9390),s=n(2823),a=n(708);function u(t,e){const n=(a=t.length>2,u=e.activationCacheKey,{name:"MatMul",inputNames:a?["A","B","Bias"]:["A","B"],inputTypes:a?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:u});var a,u;return Object.assign(Object.assign({},n),{get:()=>function(t,e,n){const a=e[0].dims,u=e[1].dims,l=r.BroadcastUtil.calcShape(a,u,!0);if(!l)throw new Error("Can't use matmul on the given tensors");const h=(0,o.getCoordsDataType)(l.length),d=(0,o.getGlChannels)(),{activationFunction:f,applyActivation:p}=(0,s.getActivationSnippet)(n),g=e.length>2,m=g?"value += getBiasForMatmul();":"",y=g?`${c(h,d,e[2].dims,l,!1)}`:"",b=l.length,_=a.length,v=u.length,w=`\n ${f}\n ${y}\n float process(int indices[${b}]) {\n int a[${_}];\n int b[${v}];\n bcastMatmulIndices_A(indices, a);\n bcastMatmulIndices_B(indices, b);\n\n float value;\n for (int k=0; k<${a[a.length-1]}; ++k) {\n a[${_-1}] = k;\n b[${v-2}] = k;\n value += _A(a) * _B(b);\n }\n ${m}\n ${p}\n return value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:l,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:w})}(n,t,e)})}e.matMul=(t,e,n)=>(l(e),t.session.pack?[t.run((0,a.createPackedMatmulProgramInfoLoader)(t,e,n),e)]:[t.run(u(e,n),e)]),e.parseMatMulAttributes=t=>(0,s.parseInternalActivationAttributes)(t.attributes),e.createMatmulProgramInfoLoader=u;const l=t=>{if(!t||2!==t.length)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type)throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function c(t,e,n,i,o){let s="";const a=n.length,u=i.length,l=u-a;s=u<2&&a>0?"coords":n.map(((t,n)=>`coords.${e[n+l]}`)).join(", ");const c=r.BroadcastUtil.getBroadcastDims(n,i).map((t=>`coords.${e[t+l]} = 0;`)).join("\n");let h="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(h="vec4(outputValue.x)"),o?`\nvec4 getBiasForMatmul() {\n ${t} coords = getOutputCoords();\n ${c}\n vec4 outputValue = getBias(${s});\n return ${h};\n}`:`\nfloat getBiasForMatmul() {\n ${t} coords = getOutputCoords();\n ${c}\n return getBias(coords.x);\n}`}e.getBiasForMatmul=c},2403:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827),a={name:"pack",inputNames:["A"],inputTypes:[i.TextureType.unpackedReversed]};e.createPackProgramInfoLoader=(t,e)=>Object.assign(Object.assign({},a),{get:()=>((t,e)=>{const n=(0,r.getGlsl)(t.session.backend.glContext.version),u=e.dims,l=u.length,c=e.dims.length,h=(0,o.getCoordsDataType)(c),d=(0,s.getChannels)("rc",c),f=(p=c,g=d,m=u[u.length-2],y=u[u.length-1],0===p||1===p?"":`\n int r = ${g[p-2]};\n int c = ${g[p-1]};\n int rp1 = ${g[p-2]} + 1;\n int cp1 = ${g[p-1]} + 1;\n bool rEdge = rp1 >= ${y};\n bool cEdge = cp1 >= ${m};\n `);var p,g,m,y;let b;b=0===l?[1,1]:1===l?[u[0],1]:[u[c-1],u[c-2]];const _=function(t,e,n){if(0===t)return"false";if(1===t)return`rc > ${e[0]}`;let r="";for(let i=t-2;i= ${e[i-t+2]}`,i= ${t[0]} ? 0. : getA(rc + 1),\n 0, 0`;let r="";if(n>2)for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.unpackFromChannel=e.getChannels=e.getVecChannels=void 0;const r=n(9390);function i(t,e){return(0,r.getGlChannels)(e).map((e=>`${t}.${e}`))}e.getVecChannels=i,e.getChannels=function(t,e){return 1===e?[t]:i(t,e)},e.unpackFromChannel=function(){return"\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "}},2870:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parsePadAttributesV11=e.padV11=e.parsePadAttributesV2=e.padV2=void 0;const r=n(246),i=n(2517),o=n(5060),s=n(2039),a={name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};e.padV2=(t,e,n)=>(c(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>l(t,e[0],n)}),e)]),e.parsePadAttributesV2=t=>{const e=t.attributes.getString("mode","constant"),n=t.attributes.getFloat("value",0),i=t.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:e,value:n,pads:i})},e.padV11=(t,n,r)=>{h(n);const i=u(t,n,r);return(0,e.padV2)(t,[n[0]],i)},e.parsePadAttributesV11=t=>t.attributes.getString("mode","constant");const u=(t,e,n)=>{if(!t.session.isInitializer(e[1].dataId)||e.length>=3&&!t.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");const i=Array.from(e[1].integerData),o=e.length>=3?e[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:i,value:o})},l=(t,e,n)=>{const r=i.ShapeUtil.padShape(e.dims.slice(),n.pads),o=r.length,a=`\n ${d(t,e,n)}\n float process(int[${o}] indices) {\n return padA(indices);\n }`;return{name:"Pad",inputNames:["A"],inputTypes:[s.TextureType.unpacked],output:{dims:r,type:e.type,textureType:s.TextureType.unpacked},shaderSource:a}},c=t=>{if(!t||1!==t.length)throw new Error("Pad requires 1 input");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},h=t=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==t[1].type)throw new Error("Invalid input type.");if(t.length>=3&&"string"===t[2].type)throw new Error("Invalid input type.")},d=(t,e,n)=>{const r=(0,o.getGlsl)(t.session.backend.glContext.version),[a,u]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),l=i.ShapeUtil.computeStrides(e.dims);switch(n.mode){case"constant":return f(r,e.dims,l,a,u,n.pads,n.value);case"reflect":return p(r,e.dims,l,a,u,n.pads);case"edge":return g(r,e.dims,l,a,u,n.pads);default:throw new Error("Invalid mode")}},f=(t,e,n,r,i,o,s)=>{const a=e.length;let u="";for(let t=a-1;t>=0;--t)u+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) return constant;\n if (k >= ${e[t]}) return constant;\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${a}]) {\n const float constant = float(${s});\n int offset = 0;\n int k = 0;\n ${u}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `},p=(t,e,n,r,i,o)=>{const s=e.length;let a="";for(let t=s-1;t>=0;--t)a+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) { k = -k; }\n {\n const int _2n_1 = ${2*(e[t]-1)};\n k = int( mod( float(k), float(_2n_1) ) ) ;\n if(k >= ${e[t]}) { k = _2n_1 - k; }\n }\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `},g=(t,e,n,r,i,o)=>{const s=e.length;let a="";for(let t=s-1;t>=0;--t)a+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) k = 0;\n if (k >= ${e[t]}) k = ${e[t]-1};\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${s}]) {\n int offset = 0;\n int k = 0;\n ${a}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `}},2143:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.globalMaxPool=e.parseMaxPoolAttributes=e.maxPool=e.parseGlobalAveragePoolAttributes=e.globalAveragePool=e.parseAveragePoolAttributes=e.averagePool=void 0;const r=n(246),i=n(2517),o=n(2039);e.averagePool=(t,e,n)=>{h(e);const r={name:"AveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>s(e,r,!1,n)}),e)]},e.parseAveragePoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=0!==t.attributes.getInt("count_include_pad",0),o=t.attributes.getInts("kernel_shape"),s=t.attributes.getInts("strides",[]),a=t.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:i,kernelShape:o,strides:s,pads:a})};const s=(t,e,n,r)=>{const[s,a]=u(t,r,n),l=i.ShapeUtil.size(s.kernelShape);let c="";s.countIncludePad?c+=`value /= float(${l});`:c+=`value /= float(${l} - pad);`;const h=`\n ${d(t[0].dims,s,"value += _X(x);",c,"0.0")}\n `;return Object.assign(Object.assign({},e),{output:{dims:a,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:h})};e.globalAveragePool=(t,e,n)=>{h(e);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[t.run(Object.assign(Object.assign({},r),{get:()=>s(e,r,!0,n)}),e)]},e.parseGlobalAveragePoolAttributes=t=>{const e=0!==t.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},e.maxPool=(t,e,n)=>{h(e);const r={name:"MaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>a(e,r,!1,n)}),e)]},e.parseMaxPoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=t.attributes.getInts("kernel_shape"),o=t.attributes.getInts("strides",[]),s=t.attributes.getInts("pads",[]),a=t.attributes.getInt("storage_order",0),u=t.attributes.getInts("dilations",[]);if(0!==a)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:o,pads:s,storageOrder:a,dilations:u})};const a=(t,e,n,r)=>{const[i,s]=u(t,r,n),a=`\n ${d(t[0].dims,i,"\n value = max(_X(x), value);\n ","","-1e5")}\n `;return Object.assign(Object.assign({},e),{output:{dims:s,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:a})},u=(t,e,n)=>{const r=t[0].dims.slice(),o=Object.hasOwnProperty.call(e,"dilations"),s=e.kernelShape.slice(),a=e.strides.slice(),u=o?e.dilations.slice():[],l=e.pads.slice();i.PoolConvUtil.adjustPoolAttributes(n,r,s,a,u,l);const c=i.PoolConvUtil.computePoolOutputShape(n,r,a,u,s,l,e.autoPad),h=Object.assign({},e);return o?Object.assign(h,{kernelShape:s,strides:a,pads:l,dilations:u,cacheKey:e.cacheKey}):Object.assign(h,{kernelShape:s,strides:a,pads:l,cacheKey:e.cacheKey}),[h,c]},l={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},c={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.globalMaxPool=(t,e)=>(h(e),[t.run(Object.assign(Object.assign({},c),{get:()=>a(e,c,!0,l)}),e)]);const h=t=>{if(!t||1!==t.length)throw new Error("Pool ops requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},d=(t,e,n,r,o)=>{const s=t.length;if(e.kernelShape.length<=2){const i=e.kernelShape[e.kernelShape.length-1],a=e.strides[e.strides.length-1],u=e.pads[e.pads.length/2-1],l=e.pads[e.pads.length-1],c=t[s-1];let h="",d="",f="";if(h=u+l!==0?`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n if (x[${s} - 1] < 0 || x[${s} - 1] >= ${c}) {\n pad++;\n continue;\n }\n ${n}\n }`:`\n for (int i = 0; i < ${i}; i++) {\n x[${s} - 1] = indices[${s} - 1] * ${a} - ${u} + i;\n ${n}\n }`,2===e.kernelShape.length){const n=e.kernelShape[e.kernelShape.length-2],r=e.strides[e.strides.length-2],o=e.pads[e.pads.length/2-2],a=e.pads[e.pads.length-2],u=t[s-2];d=o+a!==0?`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n if (x[${s} - 2] < 0 || x[${s} - 2] >= ${u}) {\n pad+= ${i};\n continue;\n }\n `:`\n for (int j = 0; j < ${n}; j++) {\n x[${s} - 2] = indices[${s} - 2] * ${r} - ${o} + j;\n `,f="\n }\n "}return`\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n\n float value = ${o};\n int pad = 0;\n ${d}\n ${h}\n ${f}\n ${r}\n return value;\n }\n `}{const a=i.ShapeUtil.size(e.kernelShape),u=i.ShapeUtil.computeStrides(e.kernelShape),l=u.length,c=e.pads.length,h=p(l),d=f(t,"inputDims"),g=f(e.pads,"pads"),m=f(u,"kernelStrides"),y=f(e.strides,"strides");let b="";return b=e.pads.reduce(((t,e)=>t+e))?`\n if (x[j] >= inputDims[j] || x[j] < 0) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n ${n}\n }`:`\n }\n ${n}\n `,`\n ${h}\n float process(int indices[${s}]) {\n int x[${s}];\n copyVec(indices, x);\n int offset[${l}];\n int pads[${c}];\n int inputDims[${s}];\n int kernelStrides[${l}];\n int strides[${l}];\n ${g}\n ${d}\n ${y}\n ${m}\n\n float value = ${o};\n int pad = 0;\n bool isPad = false;\n for (int i = 0; i < ${a}; i++) {\n offsetToIndices(i, kernelStrides, offset);\n isPad = false;\n for (int j = ${s} - ${l}; j < ${s}; j++) {\n x[j] = indices[j] * strides[j - ${s} + ${l}]\n + offset[j - ${s} + ${l}] - pads[j - 2];\n ${b}\n }\n ${r}\n\n return value;\n }\n `}},f=(t,e)=>{let n="";for(let r=0;r`\n void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) {\n if (${t} == 0) {\n return;\n }\n for (int i = 0; i < ${t} - 1; ++i) {\n indices[i] = offset / strides[i];\n offset -= indices[i] * strides[i];\n }\n indices[${t} - 1] = offset;\n }`},4939:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.reduceLogSumSquare=e.reduceLogSum=e.reduceProd=e.reduceMin=e.reduceMax=e.reduceMean=e.reduceSum=e.parseReduceAttributes=void 0;const r=n(246),i=n(782),o=n(2517),s=n(2039),a=(t,e,n,r,i)=>{l(e);const o={name:r,inputNames:["A"],inputTypes:[s.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},o),{cacheHint:n.cacheKey,get:()=>u(t,e,n,r,i,o)}),e)]};e.parseReduceAttributes=t=>{const e=t.attributes.getInts("axes",[]),n=1===t.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:e,keepDims:n})};const u=(t,e,n,r,i,a)=>{const u=[],l=e[0].dims.length||1,c=[],h=o.ShapeUtil.normalizeAxes(n.axes,e[0].dims.length),d=i(e,h);let f=d[1];for(let t=0;t=0||0===h.length?(n.keepDims&&u.push(1),f=`\n for(int j${t} = 0; j${t} < ${e[0].dims[t]}; j${t}++) {\n inputIdx[${t}] = j${t};\n ${f}\n }`):(c.push(`inputIdx[${t}] = outputIdx[${u.length}];`),u.push(e[0].dims[t]));const p=`\n float process(int outputIdx[${u.length||1}]) {\n float value; // final result\n int inputIdx[${l}]; // addressing input data\n ${c.join("\n")}\n ${d[0]} // init ops for reduce max/min\n ${f}\n ${d[2]} // final computation for reduce mean\n return value;\n }`;return Object.assign(Object.assign({},a),{output:{dims:u,type:e[0].type,textureType:s.TextureType.unpacked},shaderSource:p})},l=t=>{if(!t||1!==t.length)throw new Error("Reduce op requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.reduceSum=(t,e,n)=>a(t,e,n,"ReduceSum",(()=>["value = 0.0;","value += _A(inputIdx);",""])),e.reduceMean=(t,e,n)=>a(t,e,n,"ReduceMean",((t,e)=>{let n=1;for(let r=0;r=0||0===e.length)&&(n*=t[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]})),e.reduceMax=(t,e,n)=>a(t,e,n,"ReduceMax",((t,e)=>{const n=[];for(let r=0;r=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]})),e.reduceMin=(t,e,n)=>a(t,e,n,"ReduceMin",((t,e)=>{const n=[];for(let r=0;r=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]})),e.reduceProd=(t,e,n)=>a(t,e,n,"ReduceProd",(()=>["value = 1.0;","value *= _A(inputIdx);",""])),e.reduceLogSum=(t,e,n)=>a(t,e,n,"ReduceLogSum",(()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"])),e.reduceLogSumSquare=(t,e,n)=>a(t,e,n,"ReduceLogSumSquare",(()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""]))},7019:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isReshapeCheap=e.processDims3D=e.createPackedReshape3DProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),s=n(2827);e.createPackedReshape3DProgramInfoLoader=(t,e,n)=>{const a=(t=>({name:"Reshape (packed)",inputTypes:[o.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(n);return Object.assign(Object.assign({},a),{get:()=>((t,e,n,a)=>{const u=e.dims,l=a;let c="";for(let t=0;t<4;t++){let e="";switch(t){case 0:e="outputCoords = rc;";break;case 1:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:e="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}c+=`\n ${e}\n ${t>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n int flattenedIndex = getFlattenedIndex(outputCoords);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${t}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n ${t>0?"}":""}\n `}const h=(0,i.getGlsl)(t.session.backend.glContext.version),d=`\n ${function(t){const e=r.ShapeUtil.computeStrides(t),n=["b","r","c"],i="index";return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${e.map(((t,r)=>`int ${n[r]} = ${i} / ${t}; ${r===e.length-1?`int ${n[r+1]} = ${i} - ${n[r]} * ${t}`:`index -= ${n[r]} * ${t}`};`)).join("")}\n return ivec3(b, r, c);\n }\n `}(u)}\n ${function(t){const e=r.ShapeUtil.computeStrides(t);return`\n int getFlattenedIndex(ivec3 coords) {\n // reverse y, z order\n return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y;\n }\n`}(l)}\n ${(0,s.unpackFromChannel)()}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.0);\n\n ivec3 outputCoords;\n int rows = ${l[2]};\n int cols = ${l[1]};\n\n ${c}\n ${h.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:l,type:e.type,textureType:o.TextureType.packed},shaderSource:d,hasMain:!0})})(t,e,a,n)})},e.processDims3D=function(t){if(0===t.length)return[1,1,1];let e=1;for(let n=0;n1?t[t.length-2]:1,t[t.length-1]]},e.isReshapeCheap=function(t,e){let n=!1;return n=0===t.length||0===e.length||(t.length<2||e.length<2?t[t.length-1]===e[e.length-1]:t[t.length-1]===e[e.length-1]&&t[t.length-2]===e[e.length-2]),n}},718:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.reshape=void 0;const r=n(2517);e.reshape=(t,e)=>{const n=r.ShapeUtil.calculateReshapedDims(e[0].dims,e[1].integerData);return t.session.pack?[t.reshapePacked(e[0],n)]:[t.reshapeUnpacked(e[0],n)]}},2268:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseResizeAttributesV11=e.parseResizeAttributesV10=e.resize=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827),a=n(9793),u={name:"Resize",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.resize=(t,e,n)=>((0,a.validateInputs)(e,n),[t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>l(t,e,n)}),e)]),e.parseResizeAttributesV10=t=>(0,a.parseUpsampleAttributes)(t,10),e.parseResizeAttributesV11=t=>(0,a.parseUpsampleAttributes)(t,11);const l=(t,e,n)=>{const a=(0,r.getGlsl)(t.session.backend.glContext.version),[l,h]=c(e,n);if(l.every((t=>1===t))&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},u),{output:{dims:h,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:`void main() {\n vec4 v = ${a.texture2D}(X, TexCoords);\n ${a.output} = v;\n }`});const d=h.length;if(d<2)throw new Error(`output dimension should be at least 2, but got ${d}`);const f=h[d-2],p=h[d-1],g=e[0].dims;if(d!==g.length)throw new Error(`output dimension should match input ${g.length}, but got ${d}`);const m=g[d-2],y=g[d-1],b=l[d-2],_=l[d-1];let v="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":v="\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n ";break;case"half_pixel":v="\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n ";break;case"pytorch_half_pixel":v=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 fcoords = vec4(coords);\n return vec4(\n ${p}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n ${f}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n ${p}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n ${f}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n );\n }\n `;break;case"align_corners":v=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 resized = vec4(${p}.0 - 1.0, ${f}.0 - 1.0, ${p}.0 - 1.0,\n ${f}.0 - 1.0);\n vec4 original = vec4(${y}.0 - 1.0, ${m}.0 - 1.0, ${y}.0 - 1.0,\n ${m}.0 - 1.0);\n vec4 new_scale = original / resized;\n return vec4(coords) * new_scale;\n }\n `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}const w=(0,o.getCoordsDataType)(d),x=`\n const vec2 inputWH = vec2(${m}.0, ${y}.0);\n const vec4 scaleWHWH = vec4(float(${b}), float(${_}), float(${b}), float(${_}));\n ${(0,s.unpackFromChannel)()}\n ${v}\n float getAValue(int x10, int r, int c, int d) {\n return getChannel(getA(x10, r, c, d), vec2(c, d));\n }\n void main() {\n ${w} rc = getOutputCoords();\n\n int batch = rc[0];\n int depth = rc[1];\n\n // retrieve the 4 coordinates that is used in the 4 packed output values.\n ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n // calculate the source index in fraction\n vec4 sourceFrac = getSourceFracIndex(coords);\n\n // get the lower and upper bound of the 4 values that will be packed into one texel.\n ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n bool hasNextRow = rc.w < ${f-1};\n bool hasNextCol = rc.z < ${p-1};\n\n // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n vec4 topLeft = vec4(\n getAValue(batch, depth, x00.x, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n vec4 topRight = vec4(\n getAValue(batch, depth, x00.x, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n vec4 bottomLeft = vec4(\n getAValue(batch, depth, x00.z, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n vec4 bottomRight = vec4(\n getAValue(batch, depth, x00.z, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n // calculate the interpolation fraction on u and v direction\n vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n ${a.output} = vec4(newValue);\n }\n `;return Object.assign(Object.assign({},u),{output:{dims:h,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:x})},c=(t,e)=>{const n=t[0].dims;let r,i=e.scales;if(0===i.length){const o=t[e.scalesInputIdx];if(o&&0!==o.size){if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=h(o,e.mode,e.isResize)}else{const o=t[e.sizesInputIdx];if(!o||0===o.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(o.integerData),i=d(r,n,e.mode,e.isResize)}}else if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const o=r||n.map(((t,e)=>Math.floor(t*i[e])));return[i,o]},h=(t,e,n)=>{const r=Array.from(t.floatData);return(0,a.scalesValidation)(r,e,n),r},d=(t,e,n,r)=>{const i=e.length,o=new Array(i);for(let n=0,r=i;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.shape=void 0;const r=n(9162);e.shape=(t,e)=>(i(e),[new r.Tensor([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]);const i=t=>{if(!t||1!==t.length)throw new Error("Shape requires 1 input.")}},2278:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sliceV10=e.parseSliceAttributes=e.slice=void 0;const r=n(246),i=n(782),o=n(2517),s=n(2039),a={name:"Slice",inputNames:["A"],inputTypes:[s.TextureType.unpacked]};e.slice=(t,e,n)=>(l(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),e)]),e.parseSliceAttributes=t=>{const e=t.attributes.getInts("starts"),n=t.attributes.getInts("ends"),i=t.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:e,ends:n,axes:i})};const u=(t,e,n)=>{const r=0===n.axes.length?e.dims.slice(0).map(((t,e)=>e)):n.axes,i=o.ShapeUtil.normalizeAxes(r,e.dims.length),u=n.starts.map(((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]]))),l=n.ends.map(((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]]))),c=e.dims.slice(),h=[];for(let t=0;t0&&h.push(`outputIdx[${i[t]}] += ${u[t]};`);const d=`\n float process(int outputIdx[${c.length}]) {\n ${h.join("\n ")}\n return _A(outputIdx);\n }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:e.type,textureType:s.TextureType.unpacked},shaderSource:d})},l=t=>{if(!t||1!==t.length)throw new Error("Slice requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.sliceV10=(t,e)=>{h(e);const n=c(t,e);return[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),[e[0]])]};const c=(t,e)=>{if(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)||e.length>=4&&!t.session.isInitializer(e[3].dataId)||e.length>=5&&!t.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some((t=>1!==t)))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(e[1].integerData),r=Array.from(e[2].integerData),i=e.length>=4?Array.from(e[3].integerData):[];return{starts:n,ends:r,axes:i,cacheKey:`${i};${n};${r}`}},h=t=>{if(!t||t.length<3||t.length>5)throw new Error("Invalid input number.");if("int32"!==t[1].type||1!==t[1].dims.length)throw new Error("Invalid input type.");if("int32"!==t[2].type||1!==t[2].dims.length)throw new Error("Invalid input type.");if(t.length>=4&&("int32"!==t[3].type||1!==t[3].dims.length))throw new Error("Invalid input type.");if(t.length>=5&&("int32"!==t[4].type||1!==t[4].dims.length))throw new Error("Invalid input type.")}},5524:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.softmaxV13=e.parseSoftmaxAttributesV13=e.parseSoftmaxAttributes=e.softmax=void 0;const r=n(246),i=n(2517),o=n(5060),s=n(2039),a=n(3738),u={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[s.TextureType.unpacked]},l={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked]},c={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[s.TextureType.unpacked,s.TextureType.unpacked,s.TextureType.unpacked]};e.softmax=(t,e,n)=>{g(e);const r=e[0].dims.slice(),o=i.ShapeUtil.normalizeAxis(n.axis,r.length),s=i.ShapeUtil.sizeToDimension(r,o),a=i.ShapeUtil.sizeFromDimension(r,o);return h(t,e,n,s,a)},e.parseSoftmaxAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",1)}),e.parseSoftmaxAttributesV13=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",-1)}),e.softmaxV13=(t,e,n)=>{g(e);const o=e[0].dims.slice(),s=i.ShapeUtil.normalizeAxis(n.axis,o.length),u=o.length,l=s!==u-1,c=[];let d,f=[],p=[];l&&(f=Array.from({length:u}).map(((t,e)=>e)),f[s]=u-1,f[u-1]=s,f.map((t=>c.push(o[t]))),d=(0,r.createAttributeWithCacheKey)({perm:f}),p=(0,a.transpose)(t,e,d));const m=l?i.ShapeUtil.sizeToDimension(c,u-1):i.ShapeUtil.sizeToDimension(o,u-1),y=l?i.ShapeUtil.sizeFromDimension(c,u-1):i.ShapeUtil.sizeFromDimension(o,u-1),b=h(t,l?p:e,n,m,y);return l?(0,a.transpose)(t,b,d):b};const h=(t,e,n,r,i)=>{const o=d(t,e[0],r,i,[r]),s=t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>o}),e),a=f(t,e[0],r,i,o.output.dims,[r]),h=t.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>a}),[e[0],s]),g=p(t,e[0],r,i,o.output.dims,a.output.dims);return[t.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>g}),[e[0],s,h])]},d=(t,e,n,r,i)=>{const[a,l]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),c=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const h=(0,o.getGlsl)(t.session.backend.glContext.version),d=`\n float process(int[${c}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float max = getColorAsFloat(${h.texture2D}(A, offsetToCoords(logical_row_start_offset, ${a},\n ${l} )));\n for(int i=1; i<${r}; ++i)\n {\n float current = getColorAsFloat(${h.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${a}, ${l})));\n if(current > max)\n max = current;\n }\n\n return max;\n }`;return Object.assign(Object.assign({},u),{output:{dims:i,type:e.type,textureType:s.TextureType.unpacked},shaderSource:d})},f=(t,e,n,r,i,a)=>{const[u,c]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),h=a.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==a.length)throw new Error("Dimensionality of the output should be 1");if(a[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const d=`\n float process(int[${h}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float norm_factor = 0.0;\n float max = _Max(indices);\n for(int i=0; i<${r}; ++i)\n {\n norm_factor += exp(getColorAsFloat(${(0,o.getGlsl)(t.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${u}, ${c}))) - max);\n }\n\n return norm_factor;\n }`;return Object.assign(Object.assign({},l),{output:{dims:a,type:e.type,textureType:s.TextureType.unpacked},shaderSource:d})},p=(t,e,n,r,i,o)=>{const[a,u]=t.calculateTextureWidthAndHeight(e.dims,s.TextureType.unpacked),l=e.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length||1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n||o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const h=`\n float process(int[${l}] indices) {\n\n // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n int offset = coordsToOffset(TexCoords, ${a}, ${u});\n\n //determine the logical row for this index\n int logical_row_index[1];\n logical_row_index[0] = offset / ${r};\n\n float norm_factor = _Norm(logical_row_index);\n\n // avoid possible division by 0\n // if norm_facor is 0, all elements are zero\n // if so, return 0\n if(norm_factor == 0.0)\n return 0.0;\n\n return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n }`;return Object.assign(Object.assign({},c),{output:{dims:e.dims,type:e.type,textureType:s.TextureType.unpacked},shaderSource:h})},g=t=>{if(!t||1!==t.length)throw new Error("Softmax requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type")}},5975:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseSplitAttributes=e.split=void 0;const r=n(246),i=n(2517),o=n(2039),s={name:"Split",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.split=(t,e,n)=>{l(e);const r=i.ShapeUtil.normalizeAxis(n.axis,e[0].dims.length),o=a(t,e,r,n),c=[];for(let i=0;iu(t,e[0],n,r,i)}),e));return c},e.parseSplitAttributes=t=>{const e=t.attributes.getInt("axis",0),n=t.attributes.getInts("split",[]),i=t.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:e,split:n,numOutputs:i})};const a=(t,e,n,r)=>{const[,o]=i.SplitUtil.splitShape(e[0].dims,n,r.split,r.numOutputs);return o.length},u=(t,e,n,r,a)=>{const[u,l]=i.SplitUtil.splitShape(e.dims,r,n.split,n.numOutputs),c=l[a],h=u[a],d=`\n float process(int indices[${h.length}]) {\n indices[${r}] += ${c};\n return _A(indices);\n }\n `;return Object.assign(Object.assign({},s),{cacheHint:`${n.cacheKey}:${a}`,output:{dims:h,type:e.type,textureType:o.TextureType.unpacked},shaderSource:d})},l=t=>{if(!t||1!==t.length)throw new Error("Split requires one input.");if("int8"!==t[0].type&&"uint8"!==t[0].type&&"int16"!==t[0].type&&"uint16"!==t[0].type&&"int32"!==t[0].type&&"uint32"!==t[0].type&&"float32"!==t[0].type&&"float64"!==t[0].type&&"bool"!==t[0].type)throw new Error("Invalid input type.")}},3933:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseSqueezeAttributes=e.squeezeV13=e.squeeze=void 0;const r=n(2517);e.squeeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.squeezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.squeezeV13=(t,n)=>(o(n),(0,e.squeeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseSqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Squeeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},6558:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sum=void 0;const r=n(5060),i=n(2039);e.sum=(t,e)=>{s(e);const n={name:"Sum",inputNames:e.map(((t,e)=>`X${e}`)),inputTypes:new Array(e.length).fill(i.TextureType.unpacked)};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const o=(0,r.getGlsl)(t.session.backend.glContext.version),s=e[0].dims.slice(),a=`\n void main() {\n vec4 result = ${e.map(((t,e)=>`${o.texture2D}(X${e},TexCoords)`)).join(" + ")};\n ${o.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:s,type:e[0].type,textureType:i.TextureType.unpacked},hasMain:!0,shaderSource:a})},s=t=>{if(!t||0===t.length)throw new Error("Sum requires inputs.");const e=t[0].dims.length;for(let n=1;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tile=void 0;const r=n(782),i=n(2039);e.tile=(t,e)=>{s(e);const n={name:"Tile",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const r=e[0].dims.slice(),o=new Array(r.length),s=[];for(let t=0;t{if(!t||2!==t.length)throw new Error("Tile requires 2 input.");if(1!==t[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(t[1].dims[0]!==t[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invalid repeat type.")}},3738:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseTransposeAttributes=e.transpose=void 0;const r=n(246),i=n(2517),o=n(2039),s={name:"Transpose",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.transpose=(t,e,n)=>(h(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>a(t,e[0],n.perm)}),e)]),e.parseTransposeAttributes=t=>(0,r.createAttributeWithCacheKey)({perm:t.attributes.getInts("perm",[])});const a=(t,e,n)=>{const r=e.dims;n=u(r,n);const i=l(r,n),a=r.length,h=`\n ${c("perm",n,a)}\n float process(int indices[${a}]) {\n int a[${a}];\n perm(a, indices);\n return _A(a);\n }`;return Object.assign(Object.assign({},s),{output:{dims:i,type:e.type,textureType:o.TextureType.unpacked},shaderSource:h})},u=(t,e)=>(e&&e.length!==t.length&&(e=[...t.keys()].reverse()),e),l=(t,e)=>(e=u(t,e),i.ShapeUtil.sortBasedOnPerm(t,e)),c=(t,e,n)=>{const r=[];r.push(`void ${t}(out int a[${n}], int src[${n}]) {`);for(let t=0;t{if(!t||1!==t.length)throw new Error("Transpose requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("input should be float tensor")}},8710:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.encodeAsUint8=void 0;const r=n(5060),i=n(2039);e.encodeAsUint8=(t,e)=>{const n=e.shape,o=(0,r.getGlsl)(t.session.backend.glContext.version),s=`\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n highp vec4 encodeAsUint8(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float value = ${o.texture2D}(X,TexCoords).r;\n ${o.output} = encodeAsUint8(value);\n }`,a={name:"Uint8Encode",inputTypes:[i.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:e.tensor.type,textureType:i.TextureType.downloadUint8AsFloat},shaderSource:s,hasMain:!0};return t.executeProgram(a,[e.tensor])}},4909:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tanh=e.tan=e.sqrt=e.sin=e.sigmoid=e.relu=e.not=e.neg=e.log=e.parseLeakyReluAttributes=e.leakyRelu=e.identity=e.floor=e.exp=e.parseEluAttributes=e.elu=e.cos=e.ceil=e.clipV11=e.parseClipAttributes=e.clip=e.atan=e.asin=e.acos=e.abs=e.glslTanh=e.glslTan=e.glslSqrt=e.glslSigmoid=e.glslRelu=e.glslSin=e.glslNot=e.glslNeg=e.glslLog=e.glslLeakyRelu=e.glslIdentity=e.glslClip=e.glslFloor=e.glslExp=e.glslElu=e.glslCos=e.glslCeil=e.glslAtan=e.glslAsin=e.glslAcos=e.glslAbs=void 0;const r=n(246),i=n(2517),o=n(8520),s=n(5060),a=n(2039);function u(){return P("abs")}function l(){return P("acos")}function c(){return P("asin")}function h(){return P("atan")}function d(){return P("ceil")}function f(){return P("cos")}function p(t){const e="elu";return{body:`\n const float alpha = float(${t});\n\n float elu_(float a) {\n return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n }\n vec4 elu_(vec4 v) {\n return vec4(elu_(v.x), elu_(v.y), elu_(v.z), elu_(v.w));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function g(){return P("exp")}function m(){return P("floor")}function y(t,e){const n="clip";return{body:`\n const float min = float(${t});\n const float max = float(${e});\n\n float clip_(float a) {\n return clamp(a, min, max);\n }\n vec4 clip_(vec4 v) {\n return clamp(v, min, max);\n }\n `,name:n,type:o.FunctionType.ValueBased}}function b(){const t="indentity";return{body:`\n float ${t}_(float a) {\n return a;\n }\n vec4 ${t}_(vec4 v) {\n return v;\n }\n `,name:t,type:o.FunctionType.ValueBased}}function _(t){const e="leakyRelu";return{body:`\n const float alpha = float(${t});\n\n float ${e}_(float a) {\n return a < 0.0 ? a * alpha : a;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function v(){return P("log")}function w(){const t="neg";return{body:"\n float neg_(float a) {\n return -a;\n }\n vec4 neg_(vec4 v) {\n return -v;\n }\n ",name:t,type:o.FunctionType.ValueBased}}function x(){const t="not";return{body:"\n float not_(float a) {\n return float( ! bool(a) );\n }\n bool not_(bool a) {\n return !a;\n }\n vec4 not_(vec4 v) {\n return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n }\n bvec4 not_(bvec4 v) {\n return bvec4(!v.x, !v.y, !v.z, !v.w);\n }\n ",name:t,type:o.FunctionType.ValueBased}}function T(){return P("sin")}function S(){const t="relu";return{body:"\n float relu_(float a) {\n return max( a, 0.0 );\n }\n vec4 relu_(vec4 v) {\n return max( v, 0.0 );\n }\n ",name:t,type:o.FunctionType.ValueBased}}function O(){const t="sigmoid";return{body:`\n float ${t}_(float a) {\n return 1.0 / (1.0 + exp(-a));\n }\n vec4 ${t}_(vec4 v) {\n return 1.0 / (1.0 + exp(-v));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function E(){return P("sqrt")}function I(){return P("tan")}function A(){const t="tanh";return{body:"\n float tanh_(float a) {\n a = clamp(a, -10., 10.);\n a = exp(2.*a);\n return (a - 1.) / (a + 1.);\n }\n vec4 tanh_(vec4 v) {\n v = clamp(v, -10., 10.);\n v = exp(2.*v);\n return (v - 1.) / (v + 1.);\n }\n ",name:t,type:o.FunctionType.ValueBased}}function P(t){return{body:`\n float ${t}_(float a) {\n return ${t}(a);\n }\n vec4 ${t}_(vec4 v) {\n return ${t}(v);\n }\n `,name:t,type:o.FunctionType.ValueBased}}e.glslAbs=u,e.glslAcos=l,e.glslAsin=c,e.glslAtan=h,e.glslCeil=d,e.glslCos=f,e.glslElu=p,e.glslExp=g,e.glslFloor=m,e.glslClip=y,e.glslIdentity=b,e.glslLeakyRelu=_,e.glslLog=v,e.glslNeg=w,e.glslNot=x,e.glslSin=T,e.glslRelu=S,e.glslSigmoid=O,e.glslSqrt=E,e.glslTan=I,e.glslTanh=A;const C=(t,e,n,r)=>{const i=t.session.pack?a.TextureType.packed:a.TextureType.unpacked,o={name:n.name,inputTypes:[i],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},o),{get:()=>((t,e,n,r)=>{const i=t.session.pack?a.TextureType.packed:a.TextureType.unpacked,o=(0,s.getGlsl)(t.session.backend.glContext.version);return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i},shaderSource:`\n ${r.body}\n void main() {\n vec4 v = ${o.texture2D}(A, TexCoords);\n v = ${r.name}_(v);\n ${o.output} = v;\n }\n `,hasMain:!0})})(t,o,e,n)})};e.abs=(t,e)=>[t.run(C(t,e[0],u()),e)],e.acos=(t,e)=>[t.run(C(t,e[0],l()),e)],e.asin=(t,e)=>[t.run(C(t,e[0],c()),e)],e.atan=(t,e)=>[t.run(C(t,e[0],h()),e)],e.clip=(t,e,n)=>[t.run(C(t,e[0],y(n.min,n.max),n.cacheKey),e)],e.parseClipAttributes=t=>(0,r.createAttributeWithCacheKey)({min:t.attributes.getFloat("min",i.MIN_CLIP),max:t.attributes.getFloat("max",i.MAX_CLIP)}),e.clipV11=(t,n)=>{const r=D(t,n);return(0,e.clip)(t,[n[0]],r)};const D=(t,e)=>{if(e.length>=3&&(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=e.length>=3?e[1].numberData[0]:i.MIN_CLIP,o=e.length>=3?e[2].numberData[0]:i.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:o})};e.ceil=(t,e)=>[t.run(C(t,e[0],d()),e)],e.cos=(t,e)=>[t.run(C(t,e[0],f()),e)],e.elu=(t,e,n)=>[t.run(C(t,e[0],p(n.alpha),n.cacheKey),e)],e.parseEluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",1)}),e.exp=(t,e)=>[t.run(C(t,e[0],g()),e)],e.floor=(t,e)=>[t.run(C(t,e[0],m()),e)],e.identity=(t,e)=>[t.run(C(t,e[0],b()),e)],e.leakyRelu=(t,e,n)=>[t.run(C(t,e[0],_(n.alpha),n.cacheKey),e)],e.parseLeakyReluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",.01)}),e.log=(t,e)=>[t.run(C(t,e[0],v()),e)],e.neg=(t,e)=>[t.run(C(t,e[0],w()),e)],e.not=(t,e)=>[t.run(C(t,e[0],x()),e)],e.relu=(t,e)=>[t.run(C(t,e[0],S()),e)],e.sigmoid=(t,e)=>[t.run(C(t,e[0],O()),e)],e.sin=(t,e)=>[t.run(C(t,e[0],T()),e)],e.sqrt=(t,e)=>[t.run(C(t,e[0],E()),e)],e.tan=(t,e)=>[t.run(C(t,e[0],I()),e)],e.tanh=(t,e)=>[t.run(C(t,e[0],A()),e)]},5611:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackProgramInfoLoader=e.createUnpackProgramInfo=void 0;const r=n(5060),i=n(2039),o=n(9390),s=n(2827),a={name:"unpack",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.createUnpackProgramInfo=(t,e)=>{const n=e.dims.length,u=(0,s.getChannels)("rc",n),l=u.slice(-2),c=(0,o.getCoordsDataType)(n),h=(0,s.unpackFromChannel)(),d=0===e.dims.length?"":function(t,e){if(1===t)return"rc";let n="";for(let r=0;rObject.assign(Object.assign({},a),{get:()=>(0,e.createUnpackProgramInfo)(t,n)})},8428:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseUnsqueezeAttributes=e.unsqueezeV13=e.unsqueeze=void 0;const r=n(2517);e.unsqueeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.unsqueezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.unsqueezeV13=(t,n)=>(o(n),(0,e.unsqueeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseUnsqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Unsqueeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},9793:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.scalesValidation=e.validateInputs=e.parseUpsampleAttributes=e.parseUpsampleAttributesV9=e.parseUpsampleAttributesV7=e.upsample=void 0;const r=n(246),i=n(5060),o=n(2039),s={name:"Upsample",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.upsample=(t,n,r)=>((0,e.validateInputs)(n,r),[t.run(Object.assign(Object.assign({},s),{cacheHint:r.cacheKey,get:()=>a(t,n,r)}),n)]),e.parseUpsampleAttributesV7=t=>(0,e.parseUpsampleAttributes)(t,7),e.parseUpsampleAttributesV9=t=>(0,e.parseUpsampleAttributes)(t,9),e.parseUpsampleAttributes=(t,n)=>{const i=n>=10,o=t.attributes.getString("mode","nearest");if("nearest"!==o&&"linear"!==o&&(n<11||"cubic"!==o))throw new Error(`unrecognized mode: ${o}`);let s=[];n<9&&(s=t.attributes.getFloats("scales"),(0,e.scalesValidation)(s,o,i));const a=t.attributes.getFloat("extrapolation_value",0),u=n>10?t.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(u))throw new Error(`coordinate_transform_mode '${u}' is not supported`);const l="tf_crop_and_resize"===u,c=l,h="nearest"===o&&n>=11?t.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(h))throw new Error(`nearest_mode '${h}' is not supported`);const d=t.attributes.getFloat("cubic_coeff_a",-.75),f=0!==t.attributes.getInt("exclude_outside",0);if(f&&"cubic"!==o)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const p=n<11||"nearest"===o&&"asymmetric"===u&&"floor"===h;let g=0,m=0,y=0;return n>10?t.inputs.length>2?(g=1,m=2,y=3):(m=1,y=2):9===n&&(m=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:i,mode:o,scales:s,extrapolationValue:a,coordinateTransformMode:u,useExtrapolation:c,needRoiInput:l,nearestMode:h,cubicCoefficientA:d,excludeOutside:f,useNearest2xOptimization:p,roiInputIdx:g,scalesInputIdx:m,sizesInputIdx:y})};const a=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),[a,u]=t.calculateTextureWidthAndHeight(e[0].dims,o.TextureType.unpacked),l=e[0].dims.map(((t,e)=>Math.floor(t*n.scales[e]))),[c,h]=t.calculateTextureWidthAndHeight(l,o.TextureType.unpacked),d=l.length,f=new Array(d),p=new Array(d);let g=`\n int output_pitches[${d}];\n int input_pitches[${d}];\n `;for(let t=d-1;t>=0;t--)f[t]=t===d-1?1:f[t+1]*l[t+1],p[t]=t===d-1?1:p[t+1]*e[0].dims[t+1],g+=`\n output_pitches[${t}] = ${f[t]};\n input_pitches[${t}] = ${p[t]};\n `;const m=`\n float getInputFloat(int index) {\n vec2 coords = offsetToCoords(index, ${a}, ${u});\n float value = getColorAsFloat(${r.texture2D}(X, coords));\n return value;\n }\n `,y="nearest"===n.mode?`\n ${m}\n float process(int indices[${d}]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${h});\n\n ${g}\n\n int d, m;\n for (int dim = 0; dim < ${d}; ++dim) {\n d = output_index / output_pitches[dim];\n m = output_index - d * output_pitches[dim];\n output_index = m;\n\n if (scales[dim] != 1 && d > 0) {\n int d2 = d / scales[dim];\n m = d - d2 * scales[dim];\n d = d2;\n }\n input_index += input_pitches[dim] * d;\n }\n\n return getInputFloat(input_index);\n }`:4===d?`\n ${m}\n float process(int indices[4]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${h});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m / output_pitches[1];\n m = m - index_of_dim1 * output_pitches[1];\n index_of_dim2 = m / output_pitches[2];\n m = m - index_of_dim2 * output_pitches[2];\n index_of_dim3 = m;\n\n int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n index_of_input_dim2 = index_of_dim2 / scales[2];\n y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n index_of_input_dim3 = index_of_dim3 / scales[3];\n x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n input_index = index_of_dim0 * input_pitches[0] +\n index_of_dim1 * input_pitches[1] +\n index_of_input_dim2 * input_pitches[2] +\n index_of_input_dim3;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim2 = false;\n if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) {\n // It's the end in dimension 2\n x01 = x00;\n end_of_dim2 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[2]);\n }\n\n if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n // It's the end in dimension 3\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n }`:`\n ${m}\n float process(int indices[2]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${c}, ${h});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m;\n\n int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n index_of_input_dim0 = index_of_dim0 / scales[0];\n y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n index_of_input_dim1 = index_of_dim1 / scales[1];\n x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim0 = false;\n if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) {\n // It's the end in dimension 0\n x01 = x00;\n end_of_dim0 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[0]);\n }\n\n if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n // It's the end in dimension 1\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n }`;return Object.assign(Object.assign({},s),{output:{dims:l,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:y,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map((t=>Math.ceil(t)))}]})};e.validateInputs=(t,e)=>{if(!t||e.opset<9&&1!==t.length||e.opset>=9&&e.opset<11&&2!==t.length||e.opset>=11&&t.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&t[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if("string"===t[0].type)throw new Error("Invalid input tensor types.")},e.scalesValidation=(t,e,n)=>{if(n){for(const e of t)if(e<=0)throw new Error("Scale value should be greater than 0.")}else for(const e of t)if(e<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==e&&"cubic"!==e||2===t.length||4===t.length&&1===t[0]&&1===t[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}},1958:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ProgramManager=void 0;const r=n(1670),i=n(6231),o=n(8879),s=n(5060);e.ProgramManager=class{constructor(t,e,n){this.profiler=t,this.glContext=e,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=t.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,(()=>{var r;const o=this.glContext.gl,s=t.program;o.useProgram(s);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(t.attribLocations),this.bindUniforms(t.uniformLocations,null!==(r=t.programInfo.variables)&&void 0!==r?r:[],e)}catch(e){throw i.Logger.error("ProgramManager",t.programInfo.shaderSource),e}this.profiler.event("backend","GlContext.draw()",(()=>{this.glContext.draw()}))}),this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((t=>this.glContext.deleteProgram(t.program)))}build(t,e,n){return this.profiler.event("backend","ProgramManager.build",(()=>{const r=new o.GlslPreprocessor(this.glContext,t,e,n),i=r.preprocess(),s=this.compile(i);return{programInfo:t,program:s,uniformLocations:this.getUniformLocations(s,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(s)}}))}compile(t){if(!this.vertexShader){i.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const t=(0,s.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(t,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&i.Logger.verbose("ProrgramManager",`FragShader:\n${t}\n`);const e=this.glContext.compileShader(t,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,e);return this.glContext.deleteShader(e),n}bindOutput(t){const e=t.width,n=t.height;i.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${e}/${n}, shape=${t.shape}, type=${t.tensor.type}`),this.glContext.attachFramebuffer(t.texture,e,n)}bindAttributes(t){const e=t.position,n=t.textureCoord;this.glContext.setVertexAttributes(e,n),this.attributesBound=!0}bindUniforms(t,e,n){var r;const i=this.glContext.gl;let o=0;for(const{name:s,type:a,location:u,arrayLength:l}of t){const t=null===(r=e.find((t=>t.name===s)))||void 0===r?void 0:r.data;if("sampler2D"!==a&&!t)throw new Error(`variable '${s}' does not have data defined in program info`);switch(a){case"sampler2D":this.bindTexture(n[o],u,o),o++;break;case"float":l?i.uniform1fv(u,t):i.uniform1f(u,t);break;case"int":l?i.uniform1iv(u,t):i.uniform1i(u,t);break;default:throw new Error(`Uniform not implemented: ${a}`)}}}bindTexture(t,e,n){this.glContext.bindTextureToUniform(t.texture,n,e)}getAttribLocations(t){return{position:this.getAttribLocation(t,"position"),textureCoord:this.getAttribLocation(t,"textureCoord")}}getUniformLocations(t,e,n){const r=[];if(e)for(const n of e)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(t,n)});if(n)for(const e of n)r.push(Object.assign(Object.assign({},e),{location:this.getUniformLocation(t,e.name)}));return r}getUniformLocation(t,e){const n=this.glContext.gl.getUniformLocation(t,e);if(null===n)throw new Error(`Uniform ${e} not found.`);return n}getAttribLocation(t,e){return this.glContext.gl.getAttribLocation(t,e)}}},6416:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLSessionHandler=void 0;const r=n(6231),i=n(1047),o=n(8316),s=n(1640),a=n(1958),u=n(7859),l=n(5702);e.WebGLSessionHandler=class{constructor(t,e){this.backend=t,this.context=e,this.layoutStrategy=new u.PreferLogicalStrategy(t.glContext.maxTextureSize),this.programManager=new a.ProgramManager(this.context.profiler,t.glContext,this.layoutStrategy),this.textureManager=new l.TextureManager(t.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===t.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=t.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new o.WebGLInferenceHandler(this)}onGraphInitialized(t){const e=t.getValues().filter((t=>-1===t.from&&t.tensor)).map((t=>t.tensor.dataId));this.initializers=new Set(e)}isInitializer(t){return!!this.initializers&&this.initializers.has(t)}addInitializer(t){this.initializers.add(t)}getTextureData(t,e){return e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(t,e):this.unpackedTextureDataCache.set(t,e)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((t=>this.textureManager.releaseTexture(t,!0))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((t=>this.textureManager.releaseTexture(t,!0))),this.unpackedTextureDataCache=new Map}resolve(t,e,n){const r=(0,i.resolveOperator)(t,e,s.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(t,n):t}}}},7769:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Uint8DataEncoder=e.RGBAFloatDataEncoder=e.RedFloat32DataEncoder=void 0;const r=n(6231);e.RedFloat32DataEncoder=class{constructor(t,e=1){if(1===e)this.internalFormat=t.R32F,this.format=t.RED,this.textureType=t.FLOAT,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA32F,this.format=t.RGBA,this.textureType=t.FLOAT,this.channelSize=e}}encode(t,e){let n,i;return t.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(t)),e*this.channelSize>t.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),i=t,n=this.allocate(e*this.channelSize),i.forEach(((t,e)=>n[e]=t))):(i=t,n=i),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter(((t,e)=>e%4==0)).subarray(0,e):t.subarray(0,e)}},e.RGBAFloatDataEncoder=class{constructor(t,e=1,n){if(1!==e&&4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.channelSize=e,this.textureType=n||t.FLOAT}encode(t,e){let n=t;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(e),t.forEach(((t,e)=>n[4*e]=t))),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter(((t,e)=>e%4==0)).subarray(0,e):t.subarray(0,e)}},e.Uint8DataEncoder=class{constructor(t,e=1){if(this.channelSize=4,1===e)this.internalFormat=t.ALPHA,this.format=t.ALPHA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e}}encode(t,e){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}allocate(t){return new Uint8Array(t*this.channelSize)}decode(t,e){if(t instanceof Uint8Array)return t.subarray(0,e);throw new Error(`Invalid array type: ${t.constructor}`)}}},7859:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBatchDim=e.sizeToSquarishShape=e.getRowsCols=e.sizeFromShape=e.isInt=e.parseAxisParam=e.squeezeShape=e.PreferLogicalStrategy=e.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(6231),i=n(2517);function o(t,e){const n=[],r=[],i=null!=e&&Array.isArray(e)&&0===e.length,o=null==e||i?null:s(e,t).sort();let a=0;for(let e=0;ee)&&1===t[e]&&(n.push(t[e]),r.push(e)),o[a]<=e&&a++}1!==t[e]&&(n.push(t[e]),r.push(e))}return{newShape:n,keptDims:r}}function s(t,e){const n=e.length;return t=null==t?e.map(((t,e)=>e)):[].concat(t),(0,i.assert)(t.every((t=>t>=-n&&t`All values in axis param must be in range [-${n}, ${n}) but got axis ${t}`)),(0,i.assert)(t.every(a),(()=>`All values in axis param must be integers but got axis ${t}`)),t.map((t=>t<0?n+t:t))}function a(t){return t%1==0}function u(t){if(0===t.length)return 1;let e=t[0];for(let n=1;n=t.length?1:t.slice(e.breakAxis).reduce(((t,e)=>t*e)),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce(((t,e)=>t*e));if(!(i>n||o>n))return[i,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}const i=t.reduce(((t,e)=>t*e));let o=Math.floor(Math.sqrt(i));for(;o=n||i%o!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${t}`);return[o,i/o]}},e.PreferLogicalStrategy=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){const n=this.computeTexture(t,e);return e&&e.isPacked&&(n[0]/=2,n[1]/=2),e&&e.reverseWH?[n[1],n[0]]:n}computeTexture(t,e){const n=e&&e.isPacked;if(0===t.length)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(e&&void 0!==e.breakAxis){const n=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce(((t,e)=>t*e)),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce(((t,e)=>t*e));if(!(n>i||o>i))return[n,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}let s=t.slice(0);if(n&&(i*=2,s=s.map(((t,e)=>e>=s.length-2?s[e]%2==0?s[e]:s[e]+1:s[e])),1===s.length&&(s=[2,s[0]])),2!==s.length){const t=o(s);s=t.newShape}const a=u(s);return s.length<=1&&a<=i?[1,a]:2===s.length&&s[0]<=i&&s[1]<=i?s:3===s.length&&s[0]*s[1]<=i&&s[2]<=i?[s[0]*s[1],s[2]]:3===s.length&&s[0]<=i&&s[1]*s[2]<=i?[s[0],s[1]*s[2]]:4===s.length&&s[0]*s[1]*s[2]<=i&&s[3]<=i?[s[0]*s[1]*s[2],s[3]]:4===s.length&&s[0]<=i&&s[1]*s[2]*s[3]<=i?[s[0],s[1]*s[2]*s[3]]:n?l(a/4).map((t=>2*t)):l(a)}},e.squeezeShape=o,e.parseAxisParam=s,e.isInt=a,e.sizeFromShape=u,e.getRowsCols=function(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]},e.sizeToSquarishShape=l,e.getBatchDim=function(t,e=2){return u(t.slice(0,t.length-e))}},4057:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createTextureLayoutFromShape=e.calculateTextureWidthAndHeight=e.createTextureLayoutFromTextureType=void 0;const r=n(2517),i=n(2039);e.createTextureLayoutFromTextureType=(t,n,r)=>{const o=r===i.TextureType.unpacked||r===i.TextureType.unpackedReversed?1:4,s=r===i.TextureType.packed,a=r===i.TextureType.unpackedReversed||r===i.TextureType.packed,u=r===i.TextureType.packedLastDimension?n.length-1:void 0,l=r===i.TextureType.packedLastDimension?n.map(((t,e)=>e===n.length-1?4*t:t)):void 0;return(0,e.createTextureLayoutFromShape)(t,n,o,l,{isPacked:s,reverseWH:a,breakAxis:u})},e.calculateTextureWidthAndHeight=(t,n,r)=>{const i=(0,e.createTextureLayoutFromTextureType)(t,n,r);return[i.width,i.height]},e.createTextureLayoutFromShape=(t,e,n=1,i,o)=>{const s=!(!o||!o.isPacked),[a,u]=t.computeTextureWH(s&&i||e,o),l=e.length;let c=e.slice(0);if(0===l&&(c=[1]),1===n)i=e;else if(s){if(4!==n)throw new Error("a packed texture must be 4-channel");i=e,l>0&&(c[l-1]=Math.ceil(c[l-1]/2)),l>1&&(c[l-2]=Math.ceil(c[l-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:a,height:u,channels:n,isPacked:s,shape:c,strides:r.ShapeUtil.computeStrides(c),unpackedShape:i,reversedWH:o&&o.reverseWH}}},5702:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TextureManager=void 0;const r=n(6231);e.TextureManager=class{constructor(t,e,n,r){this.glContext=t,this.layoutStrategy=e,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(t,e,n,i){const o=this.toEncoderType(t),s=this.glContext.getEncoder(o,e.channels||1,i);if(e.isPacked&&1===i)throw new Error("not implemented");const a=e.width,u=e.height;let l,c;if(this.config.reuseTextures){l=`${a}x${u}_${s.format}_${s.internalFormat}_${s.textureType}`,c=this.inUseTextures.get(l),c||(c=[],this.inUseTextures.set(l,c));const e=this.idleTextures.get(l);if(e&&e.length>0){const r=e.pop();return c.push(r),1===i&&this.glContext.updateTexture(r,a,u,s,this.toTextureData(t,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${e.width}x${e.height}`);const h=this.glContext.allocateTexture(a,u,s,this.toTextureData(t,n));return this.config.reuseTextures&&(c.push(h),this.textureLookup.set(h,l)),h}readTexture(t,e,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",(()=>{const r=t.shape.reduce(((t,e)=>t*e))*n,i=this.glContext.readTexture(t.texture,t.width,t.height,r,this.toEncoderType(e),n);return this.toTensorData(e,i)}))}async readTextureAsync(t,e,n){const r=t.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const t=this.pendingRead.get(r);return new Promise((e=>null==t?void 0:t.push(e)))}return this.profiler.event("backend","TextureManager.readTextureAsync",(async()=>{this.pendingRead.set(r,[]);const i=t.shape.reduce(((t,e)=>t*e))*n;await this.glContext.createAndWaitForFence();const o=this.glContext.readTexture(t.texture,t.width,t.height,i,this.toEncoderType(e),n),s=this.toTensorData(e,o),a=this.pendingRead.get(r);return this.pendingRead.delete(r),null==a||a.forEach((t=>t(s))),s}))}readUint8TextureAsFloat(t){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",(()=>{const e=t.shape.reduce(((t,e)=>t*e)),n=this.glContext.readTexture(t.texture,t.width,t.height,4*e,"byte",4);return new Float32Array(n.buffer,n.byteOffset,e)}))}releaseTexture(t,e){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(t.texture),n)){e&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const e=r.indexOf(t.texture);if(-1!==e){r.splice(e,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(t.texture)}}}n&&!e||(r.Logger.verbose("TextureManager",`Deleting texture of size ${t.width}x${t.height}`),this.glContext.deleteTexture(t.texture))}toTensorData(t,e){switch(t){case"int16":return e instanceof Int16Array?e:Int16Array.from(e);case"int32":return e instanceof Int32Array?e:Int32Array.from(e);case"int8":return e instanceof Int8Array?e:Int8Array.from(e);case"uint16":return e instanceof Uint16Array?e:Uint16Array.from(e);case"uint32":return e instanceof Uint32Array?e:Uint32Array.from(e);case"uint8":case"bool":return e instanceof Uint8Array?e:Uint8Array.from(e);case"float32":return e instanceof Float32Array?e:Float32Array.from(e);case"float64":return e instanceof Float64Array?e:Float64Array.from(e);default:throw new Error(`TensorData type ${t} is not supported`)}}toTextureData(t,e){if(e)return e instanceof Float32Array?e:new Float32Array(e)}toEncoderType(t){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(t,e)=>{"use strict";var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TextureType=void 0,(n=e.TextureType||(e.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},9390:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getGlChannels=e.getCoordsDataType=e.getSqueezedParams=e.squeezeInputShape=e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=e.generateShaderFuncNameFromInputSamplerName=e.repeatedTry=e.getPackedShape=void 0;const r=n(2517);e.getPackedShape=function(t){const e=t.length;return t.slice(0,e-1).concat(t[e-1]/4)},e.repeatedTry=async function(t,e=(t=>0),n){return new Promise(((r,i)=>{let o=0;const s=()=>{if(t())return void r();o++;const a=e(o);null!=n&&o>=n?i():setTimeout(s,a)};s()}))},e.generateShaderFuncNameFromInputSamplerName=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,(()=>"empty string found for sampler name")),"get"+t.charAt(0).toUpperCase()+t.slice(1)},e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,(()=>"empty string found for sampler name")),"get"+t.charAt(0).toUpperCase()+t.slice(1)+"AtOutCoords"},e.squeezeInputShape=function(t,e){let n=JSON.parse(JSON.stringify(t));return n=e,n},e.getSqueezedParams=function(t,e){return e.map((e=>t[e])).join(", ")},e.getCoordsDataType=function(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error(`GPU for rank ${t} is not yet supported`)},e.getGlChannels=function(t=6){return["x","y","z","w","u","v"].slice(0,t)}},7305:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createNewWebGLContext=e.createWebGLContext=void 0;const r=n(6231),i=n(1713),o={};function s(t){const e=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const t=document.createElement("canvas");return t.width=1,t.height=1,t}();let n;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!t||"webgl2"===t)&&(n=e.getContext("webgl2",o),n))try{return new i.WebGLContext(n,2)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!t||"webgl"===t)&&(n=e.getContext("webgl",o)||e.getContext("experimental-webgl",o),n))try{return new i.WebGLContext(n,1)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}e.createWebGLContext=function t(e){let n;e&&"webgl2"!==e||!("webgl2"in o)?e&&"webgl"!==e||!("webgl"in o)||(n=o.webgl):n=o.webgl2,n=n||s(e),e=e||1===n.version?"webgl":"webgl2";const r=n.gl;return o[e]=n,r.isContextLost()?(delete o[e],t(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},e.createNewWebGLContext=s},1713:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLContext=e.linearSearchLastTrue=void 0;const s=n(1670),a=o(n(7769)),u=n(9390);function l(t){let e=0;for(;ethis.isTimerResultAvailable(t))),this.getTimerResult(t)}async createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e;const n=t,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),e=null===r?()=>!0:()=>{const t=n.clientWaitSync(r,0,0);return t===n.ALREADY_SIGNALED||t===n.CONDITION_SATISFIED},{query:r,isFencePassed:e}}async pollFence(t){return new Promise((e=>{this.addItemToPoll((()=>t.isFencePassed()),(()=>e()))}))}pollItems(){const t=l(this.itemsToPoll.map((t=>t.isDoneFn)));for(let e=0;e<=t;++e){const{resolveFn:t}=this.itemsToPoll[e];t()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}async addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||await(0,u.repeatedTry)((()=>(this.pollItems(),0===this.itemsToPoll.length)))}}},1036:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ExecutionPlan=void 0;const r=n(6231);class i{constructor(t,e){this.op=t,this.node=e}}e.ExecutionPlan=class{constructor(t,e,n){this.graph=t,this.profiler=n,this.initialize(e)}initialize(t){this.profiler.event("session","ExecutionPlan.initialize",(()=>{const e=this.graph.getNodes();if(e.length!==t.length)throw new Error("The size of nodes and OPs do not match.");this._ops=t.map(((t,n)=>new i(t,e[n]))),this.reset(),this._starter=[],this._ops.forEach(((t,e)=>{let n=!0;for(const e of t.node.inputs)if(!this._values[e]&&-1===this.graph.getInputIndices().indexOf(e)){n=!1;break}n&&this._starter.push(e)}))}))}reset(){this._values=this.graph.getValues().map((t=>t.tensor))}async execute(t,e){return this.profiler.event("session","ExecutionPlan.execute",(async()=>{this.reset();const n=t.createInferenceHandler(),i=this.graph.getInputIndices();if(e.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${i.length}`);e.forEach(((t,e)=>{const n=i[e];this._values[n]=t}));const o=this._starter.slice(0),s=this.graph.getValues(),a=this.graph.getNodes();let u=0;for(;uthis._values[t]));if(-1!==i.indexOf(void 0))throw new Error(`unresolved input detected: op: ${e.node}`);const l=i;r.Logger.verbose("ExecPlan",`Runing op:${e.node.name} (${l.map(((t,n)=>`'${e.node.inputs[n]}': ${t.type}[${t.dims.join(",")}]`)).join(", ")})`);const c=await this.profiler.event("node",e.node.name,(async()=>e.op.impl(n,l,e.op.context)));if(c.length!==e.node.outputs.length)throw new Error("the size of output does not match model definition.");c.forEach(((t,n)=>{const r=e.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${e.node.name}`);this._values[r]=t}));const h=new Set;c.forEach(((t,n)=>{const r=e.node.outputs[n];for(const t of s[r].to){const e=a[t];let n=!0;for(const t of e.inputs)if(!this._values[t]){n=!1;break}n&&h.add(t)}})),o.push(...h)}const l=[];for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Graph=void 0;const r=n(1446),i=n(7778),o=n(9395),s=n(9162),a=n(2517);var u=o.onnxruntime.experimental.fbs;e.Graph={from:(t,e)=>new h(t,e)};class l{constructor(t){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,t&&(this.type=a.ProtoUtil.tensorValueTypeFromProto(t.type.tensorType))}get from(){return this._from}get to(){return this._to}}class c{constructor(t,e){t instanceof r.onnx.NodeProto?(this.name=t.name,this.opType=t.opType,this.attributes=new i.Attribute(t.attribute)):t instanceof u.Node&&(this.name=null!=e?e:t.name(),this.opType=t.opType(),this.attributes=new i.Attribute(a.ProtoUtil.tensorAttributesFromORTFormat(t))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class h{constructor(t,e){if(!t)throw new TypeError("graph is empty");this.buildGraph(t),this.transformGraph(e),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(t){if(t instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(t);else{if(!(t instanceof u.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(t)}}buildGraphFromOnnxFormat(t){const e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!t.input)throw new Error("missing information in graph: input");const r=[];for(const n of t.input){if(e.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const t=this._allData.push(new l(n))-1;e.set(n.name,t),r.push(n.name)}if(!t.initializer)throw new Error("missing information in graph: initializer");for(const n of t.initializer){let t=e.get(n.name);if(void 0===t){const r=new l;r.type={shape:{dims:a.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:a.ProtoUtil.tensorDataTypeFromProto(n.dataType)},t=this._allData.push(r)-1,e.set(n.name,t)}this._allData[t]._from=-1,this._allData[t].tensor=s.Tensor.fromProto(n)}for(let t=0;t{this._allData[e]._to.forEach((e=>{t.add(e)}))}));const e=Array.from(t),n=new Array(this._nodes.length).fill("white");for(;e.length>0;){const t=e.pop();"gray"===n[t]?n[t]="black":(e.push(t),n[t]="gray",this._nodes[t].outputs.forEach((r=>{const i=this._allData[r];if(void 0!==i.tensor)throw new Error("node outputs should not be initialized");if(i._from!==t)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach((t=>{if("gray"===n[t])throw new Error("model graph is cyclic");"white"===n[t]&&e.push(t)}))})))}}transformGraph(t){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),t&&t.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let t=0;for(let e=0;e0&&(this._nodes[e].inputs.forEach((n=>{const r=this._allData[n]._to.indexOf(e+t);-1!==r&&(this._allData[n]._to[r]=e)})),this._nodes[e].outputs.forEach((n=>{this._allData[n]._from&&this._allData[n]._from===e+t&&(this._allData[n]._from=e)}))):(t++,this._nodes[e].outputs.forEach((t=>{this._allData[t]._from=-2})),this._nodes.splice(e,1),e--);t=0;for(let e=0;e0){let n=-1;void 0!==this._allData[e].from&&-1!==this._allData[e].from?(n=this._nodes[this._allData[e].from].outputs.indexOf(e+t),-1!==n&&(this._nodes[this._allData[e].from].outputs[n]=e)):(n=this._allInputIndices.indexOf(e+t),-1!==n&&(this._allInputIndices[n]=e)),this._allData[e].to.forEach((r=>{n=this._nodes[r].inputs.indexOf(e+t),-1!==n&&(this._nodes[r].inputs[n]=e)})),0===this._allData[e].to.length&&(n=this._allOutputIndices.indexOf(e+t),-1!==n&&(this._allOutputIndices[n]=e))}}else t++,this._allData.splice(e,1),e--}deleteNode(t){const e=this._nodes[t];if(e.outputs.length>1)for(let t=1;t0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");e.executeNode=!1;const n=e.inputs[0],r=e.outputs[0],i=this._allData[r].to,o=this._allData[n].to.indexOf(t);if(-1===o)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[n].to.splice(o,1),this._allData[r]._to=[];const s=this._allOutputIndices.indexOf(r);if(-1!==s&&(this._allOutputIndices[s]=n),i&&i.length>0)for(const t of i){const e=this._nodes[t].inputs.indexOf(r);if(-1===e)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[t].inputs[e]=n,this._allData[n].to.push(t)}}removeAllDropoutNodes(){let t=0;for(const e of this._nodes){if("Dropout"===e.opType){if(1!==e.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==e.outputs.length&&2!==e.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===e.outputs.length&&0!==this._allData[e.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(t)}t++}}removeAllIdentityNodes(){let t=0;for(const e of this._nodes)"Identity"===e.opType&&this.deleteNode(t),t++}isActivation(t){switch(t.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const t of this._nodes)if("Conv"===t.opType){const e=this._allData[t.outputs[0]]._to;if(1===e.length&&this.isActivation(this._nodes[e[0]])){const n=this._nodes[e[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{t.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(e){t.attributes.set("activation_params","floats",[a.MIN_CLIP,a.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;t.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}t.attributes.set("activation","string",n.opType),this.deleteNode(e[0])}}}}},6231:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.now=e.Profiler=e.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(t,e,n){}},console:new class{log(t,e,n){console.log(`${this.color(t)} ${n?""+n+" ":""}${e}`)}color(t){switch(t){case"verbose":return"v";case"info":return"i";case"warning":return"w";case"error":return"e";case"fatal":return"f";default:throw new Error(`unsupported severity: ${t}`)}}}},i={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let o={"":i};function s(t,e,n,r){if(void 0===e)return i=t,{verbose:s.verbose.bind(null,i),info:s.info.bind(null,i),warning:s.warning.bind(null,i),error:s.error.bind(null,i),fatal:s.fatal.bind(null,i)};if(void 0===n)a(t,e);else if("number"==typeof n&&void 0===r)a(t,e);else if("string"==typeof n&&void 0===r)a(t,n,0,e);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");a(t,n,0,e)}var i}function a(t,e,i,s){const a=o[s||""]||o[""];n[t]{s.then((async e=>{i&&await i.end(),t(e)}),(async t=>{i&&await i.end(),e(t)}))}));if(!o&&i){const t=i.end();if(t&&"function"==typeof t.then)return new Promise(((e,n)=>{t.then((()=>{e(s)}),(t=>{n(t)}))}))}return s}begin(t,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,e.now)();return this.flush(r),new u(t,n,r,(t=>this.endSync(t)))}{const e=r.beginTimer();return new u(t,n,0,(async t=>this.end(t)),e,r)}}async end(t){const e=await t.checkTimer();this._timingEvents.length=this._flushBatchSize||t-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Model=void 0;const r=n(5686),i=n(1446),o=n(7070),s=n(9395),a=n(2517);var u=s.onnxruntime.experimental.fbs;e.Model=class{constructor(){}load(t,e,n){if(!n)try{return void this.loadFromOnnxFormat(t,e)}catch(t){if(void 0!==n)throw t}this.loadFromOrtFormat(t,e)}loadFromOnnxFormat(t,e){const n=i.onnx.ModelProto.decode(t);if(a.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map((t=>({domain:t.domain,version:a.LongUtil.longToNumber(t.version)}))),this._graph=o.Graph.from(n.graph,e)}loadFromOrtFormat(t,e){const n=new r.flatbuffers.ByteBuffer(t),i=u.InferenceSession.getRootAsInferenceSession(n).model();if(a.LongUtil.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FLOAT_TYPES=e.INT_TYPES=e.NUMBER_TYPES=void 0,e.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],e.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],e.FLOAT_TYPES=["float32","float64"]},1047:(t,e)=>{"use strict";function n(t,e){if(e.endsWith("+")){const n=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(n)&&n<=t}if(2===e.split("-").length){const n=e.split("-"),r=Number.parseInt(n[0],10),i=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(i)&&r<=t&&t<=i}return Number.parseInt(e,10)===t}Object.defineProperty(e,"__esModule",{value:!0}),e.resolveOperator=void 0,e.resolveOperator=function(t,e,r){for(const i of r){const r=i[0],o=i[1],s=i[2],a=i[3],u=i[4];if(t.opType===r)for(const t of e)if((t.domain===o||"ai.onnx"===t.domain&&""===o)&&n(t.version,s))return{opImpl:a,opInit:u}}throw new TypeError(`cannot resolve operator '${t.opType}' with opsets: ${e.map((t=>`${t.domain||"ai.onnx"} v${t.version}`)).join(", ")}`)}},9395:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.onnxruntime=void 0;const r=n(5686);var i,o;(function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.INT=2]="INT",t[t.STRING=3]="STRING",t[t.TENSOR=4]="TENSOR",t[t.GRAPH=5]="GRAPH",t[t.FLOATS=6]="FLOATS",t[t.INTS=7]="INTS",t[t.STRINGS=8]="STRINGS",t[t.TENSORS=9]="TENSORS",t[t.GRAPHS=10]="GRAPHS",t[t.SPARSE_TENSOR=11]="SPARSE_TENSOR",t[t.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(e=t.AttributeType||(t.AttributeType={}))})((o=(i=e.onnxruntime||(e.onnxruntime={})).experimental||(i.experimental={})).fbs||(o.fbs={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.VALUE=1]="VALUE",t[t.PARAM=2]="PARAM"}(e=t.DimensionValueType||(t.DimensionValueType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.UINT8=2]="UINT8",t[t.INT8=3]="INT8",t[t.UINT16=4]="UINT16",t[t.INT16=5]="INT16",t[t.INT32=6]="INT32",t[t.INT64=7]="INT64",t[t.STRING=8]="STRING",t[t.BOOL=9]="BOOL",t[t.FLOAT16=10]="FLOAT16",t[t.DOUBLE=11]="DOUBLE",t[t.UINT32=12]="UINT32",t[t.UINT64=13]="UINT64",t[t.COMPLEX64=14]="COMPLEX64",t[t.COMPLEX128=15]="COMPLEX128",t[t.BFLOAT16=16]="BFLOAT16"}(e=t.TensorDataType||(t.TensorDataType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.Primitive=0]="Primitive",t[t.Fused=1]="Fused"}(e=t.NodeType||(t.NodeType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.NONE=0]="NONE",t[t.tensor_type=1]="tensor_type",t[t.sequence_type=2]="sequence_type",t[t.map_type=3]="map_type"}(e=t.TypeInfoValue||(t.TypeInfoValue={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dim(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return n.startShape(t),n.addDim(t,e),n.endShape(t)}}e.Shape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}value(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,r){return n.startDimension(t),n.addValue(t,e),n.addDenotation(t,r),n.endDimension(t)}}e.Dimension=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt8(this.bb_pos+e):t.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(e,n){e.addFieldInt8(0,n,t.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,r,i){return n.startDimensionValue(t),n.addDimType(t,e),n.addDimValue(t,r),n.addDimParam(t,i),n.endDimensionValue(t)}}e.DimensionValue=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}shape(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return n.startTensorTypeAndShape(t),n.addElemType(t,e),n.addShape(t,r),n.endTensorTypeAndShape(t)}}e.TensorTypeAndShape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}valueType(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return n.startMapType(t),n.addKeyType(t,e),n.addValueType(t,r),n.endMapType(t)}}e.MapType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return n.startSequenceType(t),n.addElemType(t,e),n.endSequenceType(t)}}e.SequenceType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){(t.fbs||(t.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(t,e,n,r){return t.prep(4,12),t.writeInt32(r),t.writeInt32(n),t.writeInt32(e),t.offset()}}}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,r,i){return n.startNodeEdge(t),n.addNodeIndex(t,e),n.addInputEdges(t,r),n.addOutputEdges(t,i),n.endNodeEdge(t)}}e.NodeEdge=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(e,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new t.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(e,n){e.addFieldInt32(6,n,t.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,r,i,o,s,a,u,l,c,h,d,f,p){return n.startNode(t),n.addName(t,e),n.addDocString(t,r),n.addDomain(t,i),n.addSinceVersion(t,o),n.addIndex(t,s),n.addOpType(t,a),n.addType(t,u),n.addExecutionProviderType(t,l),n.addInputs(t,c),n.addOutputs(t,h),n.addAttributes(t,d),n.addInputArgCounts(t,f),n.addImplicitInputs(t,p),n.endNode(t)}}e.Node=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,r,i){return n.startValueInfo(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.endValueInfo(t)}}e.ValueInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):t.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(e,n){e.addFieldInt8(1,n,t.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return n.startTypeInfo(t),n.addDenotation(t,e),n.addValueType(t,r),n.addValue(t,i),n.endTypeInfo(t)}}e.TypeInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,n,r){return e.startOperatorSetId(t),e.addDomain(t,n),e.addVersion(t,r),e.endOperatorSetId(t)}}t.OperatorSetId=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(e,n){e.addFieldInt32(3,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,r,i,o,s,a){return n.startTensor(t),n.addName(t,e),n.addDocString(t,r),n.addDims(t,i),n.addDataType(t,o),n.addRawData(t,s),n.addStringData(t,a),n.endTensor(t)}}e.Tensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}values(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,r,i){return n.startSparseTensor(t),n.addValues(t,e),n.addIndices(t,r),n.addDims(t,i),n.endSparseTensor(t)}}e.SparseTensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(e){let n=this.bb.__offset(this.bb_pos,16);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(e,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(e,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(e,n){e.addFieldInt32(2,n,t.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addFloat32(e[n]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,r,i,o,s,a,u,l,c,h,d,f,p){return n.startAttribute(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.addF(t,o),n.addI(t,s),n.addS(t,a),n.addT(t,u),n.addG(t,l),n.addFloats(t,c),n.addInts(t,h),n.addStrings(t,d),n.addTensors(t,f),n.addGraphs(t,p),n.endAttribute(t)}}e.Attribute=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}initializers(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(e,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new t.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(e,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new t.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,r,i,o,s,a,u,l){return n.startGraph(t),n.addInitializers(t,e),n.addNodeArgs(t,r),n.addNodes(t,i),n.addMaxNodeIndex(t,o),n.addNodeEdges(t,s),n.addInputs(t,a),n.addOutputs(t,u),n.addSparseInitializers(t,l),n.endGraph(t)}}e.Graph=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,r,i,o,s,a,u,l,c){return n.startModel(t),n.addIrVersion(t,e),n.addOpsetImport(t,r),n.addProducerName(t,i),n.addProducerVersion(t,o),n.addDomain(t,s),n.addModelVersion(t,a),n.addDocString(t,u),n.addGraph(t,l),n.addGraphDocString(t,c),n.endModel(t)}}e.Model=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,n,r){return e.startKernelCreateInfos(t),e.addNodeIndices(t,n),e.addKernelDefHashes(t,r),e.endKernelCreateInfos(t)}}t.KernelCreateInfos=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,r){return n.startSubGraphSessionState(t),n.addGraphId(t,e),n.addSessionState(t,r),n.endSubGraphSessionState(t)}}e.SubGraphSessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}kernels(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,r){return n.startSessionState(t),n.addKernels(t,e),n.addSubGraphSessionStates(t,r),n.endSessionState(t)}}e.SessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,r,i){return n.startInferenceSession(t),n.addOrtVersion(t,e),n.addModel(t,r),n.addSessionState(t,i),n.endInferenceSession(t)}}e.InferenceSession=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={}))},7448:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxjsSessionHandler=void 0;const r=n(1670),i=n(9162);e.OnnxjsSessionHandler=class{constructor(t){this.session=t,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(t,e,n){const o=new Map;for(const e in t)if(Object.hasOwnProperty.call(t,e)){const n=t[e];o.set(e,new i.Tensor(n.dims,n.type,void 0,void 0,n.data))}const s=await this.session.run(o),a={};return s.forEach(((t,e)=>{a[e]=new r.Tensor(t.type,t.data,t.dims)})),a}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Session=void 0;const r=n(7067),i=n(1296),o=n(7091),s=n(1036),a=n(6231),u=n(2644);e.Session=class{constructor(t={}){this._initialized=!1,this.backendHint=t.backendHint,this.profiler=a.Profiler.create(t.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(t,e,n){await this.profiler.event("session","Session.loadModel",(async()=>{const s=await(0,o.resolveBackend)(this.backendHint);if(this.sessionHandler=s.createSessionHandler(this.context),this._model=new u.Model,"string"==typeof t){const e=t.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(t);this.initialize(n,e)}else{const n=await fetch(t),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),e)}}else if(ArrayBuffer.isView(t))this.initialize(t);else{const r=new Uint8Array(t,e||0,n||t.byteLength);this.initialize(r)}}))}initialize(t,e){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",(()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(t,n,e),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new s.ExecutionPlan(this._model.graph,this._ops,this.profiler)})),this._initialized=!0}async run(t){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",(async()=>{const e=this.normalizeAndValidateInputs(t),n=await this._executionPlan.execute(this.sessionHandler,e);return this.createOutput(n)}))}normalizeAndValidateInputs(t){const e=this._model.graph.getInputNames();if(Array.isArray(t)){if(t.length!==e.length)throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`)}else{if(t.size!==e.length)throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`);const n=new Array(t.size);let r=0;for(let i=0;i"string"==typeof t))))throw new TypeError("cache should be a string array");l&&(this.cache=new Array(a))}else{if(void 0!==o){const t=d(e);if(!(o instanceof t))throw new TypeError(`cache should be type ${t.name}`)}if(l){const t=new ArrayBuffer(a*function(t){switch(t){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${t}`)}}(e));this.cache=function(t,e){return new(d(e))(t)}(t,e)}}}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");const e=u.ProtoUtil.tensorDataTypeFromProto(t.dataType),n=u.ProtoUtil.tensorDimsFromProto(t.dims),r=new c(n,e);if("string"===e)t.stringData.forEach(((t,e)=>{r.data[e]=(0,u.decodeUtf8String)(t)}));else if(t.rawData&&"number"==typeof t.rawData.byteLength&&t.rawData.byteLength>0){const e=r.data,n=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),i=h(t.dataType),o=t.rawData.byteLength/i;if(t.rawData.byteLength%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r0){const e=r.data,n=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),i=h(t.dataType()),o=t.rawDataLength()/i;if(t.rawDataLength()%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r1&&u>1)return;s[o-a]=Math.max(n,u)}return s}static index(t,e){const n=new Array(e.length);return l.fillIndex(t,e,n),n}static fillIndex(t,e,n){const r=t.length-e.length;for(let i=0;i=0;t--)r[t]=c%o[t],c=Math.floor(c/o[t]);f||(l.fillIndex(r,t.dims,i),h=t.get(i)),p||(l.fillIndex(r,e.dims,a),d=e.get(a)),u.set(r,n(h,d))}}return u}}static isValidBroadcast(t,e){const n=t.length,r=e.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==t[n-i]&&t[n-i]!==e[r-i])return!1;return!0}static getBroadcastDims(t,e){const n=t.length,r=[];for(let i=0;i1&&1===s&&r.unshift(o)}return r}}e.BroadcastUtil=l,e.arrayCopyHelper=function(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;oo.default.isLong(t)?t.toNumber():t))}static tensorValueTypeFromProto(t){return{tensorType:c.tensorDataTypeFromProto(t.elemType),shape:{dims:c.tensorDimsFromProto(t.shape.dim.map((t=>t.dimValue)))}}}static tensorDimsFromORTFormat(t){const e=[];for(let n=0;nt.length)throw new Error(`invalid dimension of ${e} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return d.getSizeFromDimensionRange(t,e,t.length)}static sizeToDimension(t,e){if(e<0||e>t.length)throw new Error(`invalid dimension of ${e} for sizeToDimension as Tensor has ${t.length} dimensions.`);return d.getSizeFromDimensionRange(t,0,e)}static getSizeFromDimensionRange(t,e,n){let r=1;for(let i=e;i=0;--r)n[r]=n[r+1]*t[r+1];return n}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,e,n){void 0===n&&(n=t.length);let r=0;for(let i=0;i=e)throw new Error("unsupported axis for this operation.");return t<0?t+e:t}static normalizeAxes(t,e){return t.map((t=>this.normalizeAxis(t,e)))}static incrementIndex(t,e,n){if(0===e.length||0===t.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=e.length;else if(n<=0||n>e.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(t[r]++,!(t[r]=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[s]=t[s]}else r[s]=e[s];o*=r[s]}}const s=d.size(t);if(-1!==i){if(s%o!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${e}]`);r[i]=s/o}else if(o!==s)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(t,e){return e?e.map((e=>t[e])):t.slice().reverse()}static padShape(t,e){const n=t.length;return t.map(((t,r)=>t+e[r]+e[r+n]))}static areEqual(t,e){return t.length===e.length&&t.every(((t,n)=>t===e[n]))}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let e=1;for(const n of t){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);e*=n}return e}static flattenShape(t,e){e<0&&(e+=t.length);const n=t.reduce(((t,e)=>t*e),1),r=t.slice(e).reduce(((t,e)=>t*e),1);return[n/r,r]}static squeezeShape(t,e){const n=new Array;e=d.normalizeAxes(e,t.length);for(let r=0;r=0;if(i&&1!==t[r])throw new Error("squeeze an axis of size different than 1");(0===e.length&&t[r]>1||e.length>0&&!i)&&n.push(t[r])}return n}static unsqueezeShape(t,e){const n=new Array(t.length+e.length);n.fill(0);for(let t=0;t=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let e=0;e=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let s=0;s=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let s=0;s=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;oe.push(n)));const s=p.calcReduceShape(o,e,!0),u=d.size(s),c=new a.Tensor(s,t.type),h=d.computeStrides(s),f=d.computeStrides(o),g=new Array(o.length);for(let n=0;n=e.length)return o(t[i]);const u=e[r],l=u>=n.length?1:d.size(n.slice(u+1));for(let c=0;c0!==t))}}e.ReduceUtil=p;class g{static adjustPoolAttributes(t,e,n,r,i,o){if(!t&&n.length!==e.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let t=0;t=n.length?n.push(e[t+2]):n[t]=e[t+2];for(let t=0;t=n[t]||o[t+n.length]>=n[t])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,e,n,r,i,o){if(o){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(e.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,i)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,o])=>{const s=n?n+t:t;if("object"==typeof o)(0,e.iterateExtraOptions)(o,s+".",r,i);else if("string"==typeof o||"number"==typeof o)i(s,o.toString());else{if("boolean"!=typeof o)throw new Error("Can't handle extra config type: "+typeof o);i(s,o?"1":"0")}}))}},2157:function(t,e,n){"use strict";var r,i=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),s=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&i(e,t,n);return o(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=e.initWasm=void 0;const a=n(1670),u=s(n(349)),l=n(6361),c=()=>!!a.env.wasm.proxy&&"undefined"!=typeof document;let h,d,f,p=!1,g=!1,m=!1;const y=[],b=[],_=[],v=[],w=[],x=[],T=()=>{if(p||!g||m||!h)throw new Error("worker not ready")},S=t=>{switch(t.data.type){case"init-wasm":p=!1,t.data.err?(m=!0,d[1](t.data.err)):(g=!0,d[0]());break;case"init-ort":t.data.err?f[1](t.data.err):f[0]();break;case"create_allocate":t.data.err?y.shift()[1](t.data.err):y.shift()[0](t.data.out);break;case"create_finalize":t.data.err?b.shift()[1](t.data.err):b.shift()[0](t.data.out);break;case"create":t.data.err?_.shift()[1](t.data.err):_.shift()[0](t.data.out);break;case"release":t.data.err?v.shift()[1](t.data.err):v.shift()[0]();break;case"run":t.data.err?w.shift()[1](t.data.err):w.shift()[0](t.data.out);break;case"end-profiling":t.data.err?x.shift()[1](t.data.err):x.shift()[0]()}},O="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;e.initWasm=async()=>{if(c()){if(g)return;if(p)throw new Error("multiple calls to 'initWasm()' detected.");if(m)throw new Error("previous call to 'initWasm()' failed.");return p=!0,void 0===a.env.wasm.wasmPaths&&O&&0!==O.indexOf("blob:")&&(a.env.wasm.wasmPaths=O.substr(0,+O.lastIndexOf("/")+1)),new Promise(((t,e)=>{null==h||h.terminate(),h=n(9710).Z(),h.onmessage=S,d=[t,e];const r={type:"init-wasm",in:a.env.wasm};h.postMessage(r)}))}return(0,l.initializeWebAssembly)(a.env.wasm)},e.initOrt=async(t,e)=>{if(c())return T(),new Promise(((n,r)=>{f=[n,r];const i={type:"init-ort",in:{numThreads:t,loggingLevel:e}};h.postMessage(i)}));u.initOrt(t,e)},e.createSessionAllocate=async t=>c()?(T(),new Promise(((e,n)=>{y.push([e,n]);const r={type:"create_allocate",in:{model:t}};h.postMessage(r,[t.buffer])}))):u.createSessionAllocate(t),e.createSessionFinalize=async(t,e)=>c()?(T(),new Promise(((n,r)=>{b.push([n,r]);const i={type:"create_finalize",in:{modeldata:t,options:e}};h.postMessage(i)}))):u.createSessionFinalize(t,e),e.createSession=async(t,e)=>c()?(T(),new Promise(((n,r)=>{_.push([n,r]);const i={type:"create",in:{model:t,options:e}};h.postMessage(i,[t.buffer])}))):u.createSession(t,e),e.releaseSession=async t=>{if(c())return T(),new Promise(((e,n)=>{v.push([e,n]);const r={type:"release",in:t};h.postMessage(r)}));u.releaseSession(t)},e.run=async(t,e,n,r,i)=>c()?(T(),new Promise(((o,s)=>{w.push([o,s]);const a={type:"run",in:{sessionId:t,inputIndices:e,inputs:n,outputIndices:r,options:i}};h.postMessage(a,u.extractTransferableBuffers(n))}))):u.run(t,e,n,r,i),e.endProfiling=async t=>{if(c())return T(),new Promise(((e,n)=>{x.push([e,n]);const r={type:"end-profiling",in:t};h.postMessage(r)}));u.endProfiling(t)}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setRunOptions=t=>{const e=(0,o.getInstance)();let n=0;const s=[],a=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))a.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))a.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(a.terminate=!1);let o=0;if(void 0!==(null==t?void 0:t.tag)&&(o=(0,i.allocWasmString)(t.tag,s)),n=e._OrtCreateRunOptions(a.logSeverityLevel,a.logVerbosityLevel,!!a.terminate,o),0===n)throw new Error("Can't create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const o=(0,i.allocWasmString)(t,s),a=(0,i.allocWasmString)(r,s);if(0!==e._OrtAddRunConfigEntry(n,o,a))throw new Error(`Can't set a run config entry: ${t} - ${r}`)})),[n,s]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),s.forEach(e._free),t}}},2306:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),i=n(1670),o=n(2850),s=n(2157);let a;e.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(t){const e=await fetch(t),n=await e.arrayBuffer();return(0,s.createSessionAllocate)(new Uint8Array(n))}async loadModel(t,e){if(a||(await(0,s.initOrt)(i.env.wasm.numThreads,(t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}})(i.env.logLevel)),a=!0),"string"==typeof t)if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(n,e)}else{const n=await this.createSessionAllocate(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSessionFinalize)(n,e)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,s.createSession)(t,e)}async dispose(){return(0,s.releaseSession)(this.sessionId)}async run(t,e,n){const r=[],o=[];Object.entries(t).forEach((t=>{const e=t[0],n=t[1],i=this.inputNames.indexOf(e);if(-1===i)throw new Error(`invalid input '${e}'`);r.push(n),o.push(i)}));const a=[];Object.entries(e).forEach((t=>{const e=t[0],n=this.outputNames.indexOf(e);if(-1===n)throw new Error(`invalid output '${e}'`);a.push(n)}));const u=await(0,s.run)(this.sessionId,o,r.map((t=>[t.type,t.dims,t.data])),a,n),l={};for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setSessionOptions=t=>{const e=(0,o.getInstance)();let n=0;const s=[],a=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(a);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(a.graphOptimizationLevel="all");const u=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(a.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(a.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(a.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(a.executionMode="sequential");const l=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(a.executionMode);let c=0;if(void 0!==(null==t?void 0:t.logId)&&(c=(0,i.allocWasmString)(t.logId,s)),void 0===(null==t?void 0:t.logSeverityLevel))a.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))a.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(a.enableProfiling=!1),n=e._OrtCreateSessionOptions(u,!!a.enableCpuMemArena,!!a.enableMemPattern,l,!!a.enableProfiling,0,c,a.logSeverityLevel,a.logVerbosityLevel),0===n)throw new Error("Can't create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const s=(0,i.allocWasmString)(e,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(t,s))throw new Error(`Can't append execution provider: ${e}`)}})(n,t.executionProviders,s),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const o=(0,i.allocWasmString)(t,s),a=(0,i.allocWasmString)(r,s);if(0!==e._OrtAddSessionConfigEntry(n,o,a))throw new Error(`Can't set a session config entry: ${t} - ${r}`)})),[n,s]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),s.forEach(e._free),t}}},4983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(6361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),i=n.lengthBytesUTF8(t)+1,o=n._malloc(i);return n.stringToUTF8(t,o,i),e.push(o),o}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),i=n(4919),o=n(4983),s=n(6361);e.initOrt=(t,e)=>{const n=(0,s.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const a=new Map;e.createSessionAllocate=t=>{const e=(0,s.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,s.getInstance)();let r=0,o=0,u=[];try{if([o,u]=(0,i.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],o),0===r)throw new Error("Can't create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(o),u.forEach(n._free)}const l=n._OrtGetInputCount(r),c=n._OrtGetOutputCount(r),h=[],d=[],f=[],p=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,s.getInstance)(),n=a.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=n[1],o=n[2];i.forEach(e._OrtFree),o.forEach(e._OrtFree),e._OrtReleaseSession(r),a.delete(t)};const u=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},c=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,i,h)=>{const d=(0,s.getInstance)(),f=a.get(t);if(!f)throw new Error("invalid session id");const p=f[0],g=f[1],m=f[2],y=e.length,b=i.length;let _=0,v=[];const w=[],x=[];try{[_,v]=(0,r.setRunOptions)(h);for(let t=0;td.HEAP32[t++]=e));const n=d._OrtCreateTensor(u(e),s,a,c,r.length);if(0===n)throw new Error("Can't create a tensor");w.push(n)}finally{d.stackRestore(l)}}const t=d.stackSave(),s=d.stackAlloc(4*y),a=d.stackAlloc(4*y),f=d.stackAlloc(4*b),T=d.stackAlloc(4*b);try{let n=s/4,r=a/4,o=f/4,u=T/4;for(let t=0;tt*e));if(i=l(s),"string"===i){const t=[];let e=o/4;for(let n=0;n{const e=(0,s.getInstance)(),n=a.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=e._OrtEndProfiling(r);if(0===i)throw new Error("Can't get an profile file name");e._OrtFree(i)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},6361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e},s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const a=o(n(6449)),u=s(n(932)),l=n(3474);let c,h=!1,d=!1,f=!1;const p=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(h)return Promise.resolve();if(d)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(f)throw new Error("previous call to 'initializeWebAssembly()' failed.");d=!0;const e=t.initTimeout,r=t.numThreads,i=t.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),s=i&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),g="string"==typeof t.wasmPaths?t.wasmPaths:void 0,m=p(!1,o),y=p(s,o),b="object"==typeof t.wasmPaths?t.wasmPaths[y]:void 0;let _=!1;const v=[];if(e>0&&v.push(new Promise((t=>{setTimeout((()=>{_=!0,t()}),e)}))),v.push(new Promise(((t,e)=>{const r=o?l:u.default,i={locateFile:(t,e)=>o&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):t===m?null!=b?b:(null!=g?g:e)+y:e+t};if(o)if("undefined"==typeof Blob)i.mainScriptUrlOrBlob=a.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;i.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(i).then((e=>{d=!1,h=!0,c=e,t()}),(t=>{d=!1,f=!0,e(t)}))}))),await Promise.race(v),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(h&&c)return c;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!h||d||f||(d=!0,null===(t=c.PThread)||void 0===t||t.terminateAllThreads(),c=void 0,d=!1,h=!1,f=!0)}},9710:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(477),i=n.n(r);function o(){return i()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:t=>{"use strict";t.exports=function(t,e,n,r){var i=self||window;try{try{var o;try{o=new i.Blob([t])}catch(e){(o=new(i.BlobBuilder||i.WebKitBlobBuilder||i.MozBlobBuilder||i.MSBlobBuilder)).append(t),o=o.getBlob()}var s=i.URL||i.webkitURL,a=s.createObjectURL(o),u=new i[e](a,n);return s.revokeObjectURL(a),u}catch(r){return new i[e]("data:application/javascript,".concat(encodeURIComponent(t)),n)}}catch(t){if(!r)throw Error("Inline worker is not supported");return new i[e](r,n)}}},4154:t=>{"use strict";t.exports='"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'},1670:t=>{"use strict";t.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(t,e,n)=>{"use strict";n.r(e),n.d(e,{flatbuffers:()=>r});var r={};r.Offset,r.Table,r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(t,e){this.low=0|t,this.high=0|e},r.Long.create=function(t,e){return 0==t&&0==e?r.Long.ZERO:new r.Long(t,e)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(t){return this.low==t.low&&this.high==t.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(t){if(t)e=t;else var e=1024;this.bb=r.ByteBuffer.allocate(e),this.space=e,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.forceDefaults=function(t){this.force_defaults=t},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(t,e){t>this.minalign&&(this.minalign=t);for(var n=1+~(this.bb.capacity()-this.space+e)&t-1;this.space=0&&0==this.vtable[e];e--);for(var n=e+1;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);var i=(n+2)*r.SIZEOF_SHORT;this.addInt16(i);var o=0,s=this.space;t:for(e=0;e=0;s--)this.writeInt8(o.charCodeAt(s))}this.prep(this.minalign,r.SIZEOF_INT+i),this.addOffset(t),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(t,e){this.finish(t,e,!0)},r.Builder.prototype.requiredField=function(t,e){var n=this.bb.capacity()-t,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+e))throw new Error("FlatBuffers: field "+e+" must be set")},r.Builder.prototype.startVector=function(t,e,n){this.notNested(),this.vector_num_elems=e,this.prep(r.SIZEOF_INT,t*e),this.prep(n,t*e)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(t){if(t instanceof Uint8Array)var e=t;else{e=[];for(var n=0;n=56320?i:(i<<10)+t.charCodeAt(n++)+-56613888)<128?e.push(r):(r<2048?e.push(r>>6&31|192):(r<65536?e.push(r>>12&15|224):e.push(r>>18&7|240,r>>12&63|128),e.push(r>>6&63|128)),e.push(63&r|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length),n=0;for(var o=this.space,s=this.bb.bytes();n>24},r.ByteBuffer.prototype.readUint8=function(t){return this.bytes_[t]},r.ByteBuffer.prototype.readInt16=function(t){return this.readUint16(t)<<16>>16},r.ByteBuffer.prototype.readUint16=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8},r.ByteBuffer.prototype.readInt32=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24},r.ByteBuffer.prototype.readUint32=function(t){return this.readInt32(t)>>>0},r.ByteBuffer.prototype.readInt64=function(t){return new r.Long(this.readInt32(t),this.readInt32(t+4))},r.ByteBuffer.prototype.readUint64=function(t){return new r.Long(this.readUint32(t),this.readUint32(t+4))},r.ByteBuffer.prototype.readFloat32=function(t){return r.int32[0]=this.readInt32(t),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(t){return r.int32[r.isLittleEndian?0:1]=this.readInt32(t),r.int32[r.isLittleEndian?1:0]=this.readInt32(t+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeUint8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeInt16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeUint16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeInt32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeUint32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeInt64=function(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)},r.ByteBuffer.prototype.writeUint64=function(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)},r.ByteBuffer.prototype.writeFloat32=function(t,e){r.float32[0]=e,this.writeInt32(t,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(t,e){r.float64[0]=e,this.writeInt32(t,r.int32[r.isLittleEndian?0:1]),this.writeInt32(t+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&s)))}return i},r.ByteBuffer.prototype.__indirect=function(t){return t+this.readInt32(t)},r.ByteBuffer.prototype.__vector=function(t){return t+this.readInt32(t)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(t){return this.readInt32(t+this.readInt32(t))},r.ByteBuffer.prototype.__has_identifier=function(t){if(t.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var e=0;e{var e=t&&t.__esModule?()=>t.default:()=>t;return __nested_webpack_require_546802__.d(e,{a:e}),e},__nested_webpack_require_546802__.d=(t,e)=>{for(var n in e)__nested_webpack_require_546802__.o(e,n)&&!__nested_webpack_require_546802__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__nested_webpack_require_546802__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),__nested_webpack_require_546802__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__nested_webpack_require_546802__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__=__nested_webpack_require_546802__(6018);return __webpack_exports__})(),module.exports=e(__webpack_require__(226))},155:t=>{var e,n,r=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(t){if(e===setTimeout)return setTimeout(t,0);if((e===i||!e)&&setTimeout)return e=setTimeout,setTimeout(t,0);try{return e(t,0)}catch(n){try{return e.call(null,t,0)}catch(n){return e.call(this,t,0)}}}!function(){try{e="function"==typeof setTimeout?setTimeout:i}catch(t){e=i}try{n="function"==typeof clearTimeout?clearTimeout:o}catch(t){n=o}}();var a,u=[],l=!1,c=-1;function h(){l&&a&&(l=!1,a.length?u=a.concat(u):c=-1,u.length&&d())}function d(){if(!l){var t=s(h);l=!0;for(var e=u.length;e;){for(a=u,u=[];++c1)for(var n=1;ni;){if(o-i>600){var a=o-i+1,u=r-i+1,l=Math.log(a),c=.5*Math.exp(2*l/3),h=.5*Math.sqrt(l*c*(a-c)/a)*(u-a/2<0?-1:1);t(n,r,Math.max(i,Math.floor(r-u*c/a+h)),Math.min(o,Math.floor(r+(a-u)*c/a+h)),s)}var d=n[r],f=i,p=o;for(e(n,i,r),s(n[o],d)>0&&e(n,i,o);f0;)p--}0===s(n[i],d)?e(n,i,p):e(n,++p,o),p<=r&&(i=p+1),r<=p&&(o=p-1)}}(t,r,i||0,o||t.length-1,s||n)}function e(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function n(t,e){return te?1:0}var r=function(t){void 0===t&&(t=9),this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function i(t,e,n){if(!n)return e.indexOf(t);for(var r=0;r=t.minX&&e.maxY>=t.minY}function p(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function g(e,n,r,i,o){for(var s=[n,r];s.length;)if(!((r=s.pop())-(n=s.pop())<=i)){var a=n+Math.ceil((r-n)/i/2)*i;t(e,a,n,r,o),s.push(n,a,a,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(t){var e=this.data,n=[];if(!f(t,e))return n;for(var r=this.toBBox,i=[];e;){for(var o=0;o=0&&i[e].children.length>this._maxEntries;)this._split(i,e),e--;this._adjustParentBBoxes(r,i,e)},r.prototype._split=function(t,e){var n=t[e],r=n.children.length,i=this._minEntries;this._chooseSplitAxis(n,i,r);var s=this._chooseSplitIndex(n,i,r),a=p(n.children.splice(s,n.children.length-s));a.height=n.height,a.leaf=n.leaf,o(n,this.toBBox),o(a,this.toBBox),e?t[e-1].children.push(a):this._splitRoot(n,a)},r.prototype._splitRoot=function(t,e){this.data=p([t,e]),this.data.height=t.height+1,this.data.leaf=!1,o(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(t,e,n){for(var r,i,o,a,u,l,h,d=1/0,f=1/0,p=e;p<=n-e;p++){var g=s(t,0,p,this.toBBox),m=s(t,p,n,this.toBBox),y=(i=g,o=m,a=void 0,u=void 0,l=void 0,h=void 0,a=Math.max(i.minX,o.minX),u=Math.max(i.minY,o.minY),l=Math.min(i.maxX,o.maxX),h=Math.min(i.maxY,o.maxY),Math.max(0,l-a)*Math.max(0,h-u)),b=c(g)+c(m);y=e;f--){var p=t.children[f];a(u,t.leaf?i(p):p),l+=h(u)}return l},r.prototype._adjustParentBBoxes=function(t,e,n){for(var r=n;r>=0;r--)a(e[r],t)},r.prototype._condense=function(t){for(var e=t.length-1,n=void 0;e>=0;e--)0===t[e].children.length?e>0?(n=t[e-1].children).splice(n.indexOf(t[e]),1):this.clear():o(t[e],this.toBBox)},r}()}},__webpack_module_cache__={},deferred;function __webpack_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var n=__webpack_module_cache__[t]={id:t,loaded:!1,exports:{}};return __webpack_modules__[t].call(n.exports,n,n.exports,__webpack_require__),n.loaded=!0,n.exports}__webpack_require__.m=__webpack_modules__,deferred=[],__webpack_require__.O=(t,e,n,r)=>{if(!e){var i=1/0;for(u=0;u=r)&&Object.keys(__webpack_require__.O).every((t=>__webpack_require__.O[t](e[s])))?e.splice(s--,1):(o=!1,r0&&deferred[u-1][2]>r;u--)deferred[u]=deferred[u-1];deferred[u]=[e,n,r]},__webpack_require__.n=t=>{var e=t&&t.__esModule?()=>t.default:()=>t;return __webpack_require__.d(e,{a:e}),e},__webpack_require__.d=(t,e)=>{for(var n in e)__webpack_require__.o(e,n)&&!__webpack_require__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__webpack_require__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__webpack_require__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},__webpack_require__.nmd=t=>(t.paths=[],t.children||(t.children=[]),t),(()=>{var t={355:0,392:0};__webpack_require__.O.j=e=>0===t[e];var e=(e,n)=>{var r,i,[o,s,a]=n,u=0;if(o.some((e=>0!==t[e]))){for(r in s)__webpack_require__.o(s,r)&&(__webpack_require__.m[r]=s[r]);if(a)var l=a(__webpack_require__)}for(e&&e(n);u__webpack_require__(645)));var __webpack_exports__=__webpack_require__.O(void 0,[392],(()=>__webpack_require__(401)));__webpack_exports__=__webpack_require__.O(__webpack_exports__)})(); \ No newline at end of file +/******/ (() => { // webpackBootstrap +/******/ var __webpack_modules__ = ({ + +/***/ "./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./src/resources/assets/js/MagicSamMixin.vue?vue&type=script&lang=js&": +/*!********************************************************************************************************************************************************************************************************************!*\ + !*** ./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./src/resources/assets/js/MagicSamMixin.vue?vue&type=script&lang=js& ***! + \********************************************************************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _api_image__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./api/image */ "./src/resources/assets/js/api/image.js"); +/* harmony import */ var _ol_MagicSamInteraction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ol/MagicSamInteraction */ "./src/resources/assets/js/ol/MagicSamInteraction.js"); +/* harmony import */ var _import__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./import */ "./src/resources/assets/js/import.js"); + + + + + + + + +var magicSamInteraction; +var loadedImageId; +var loadingImageId; +/** + * Mixin for the annotationCanvas component that contains logic for the Magic Sam interaction. + * + * @type {Object} + */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + data: function data() { + return { + loadingMagicSam: false, + loadingMagicSamTakesLong: false, + throttleInterval: 1000 + }; + }, + computed: { + isMagicSamming: function isMagicSamming() { + return this.interactionMode === 'magicSam'; + }, + magicSamButtonClass: function magicSamButtonClass() { + return this.loadingMagicSamTakesLong ? 'loading-magic-sam-long' : ''; + }, + magicSamButtonTitle: function magicSamButtonTitle() { + if (this.loadingMagicSamTakesLong) { + return 'Preparing the magic for this image'; + } + + return 'Draw a polygon using the magic SAM tool 𝗭'; + } + }, + methods: { + setThrottleInterval: function setThrottleInterval(interval) { + this.throttleInterval = interval; + + if (magicSamInteraction) { + magicSamInteraction.setThrottleInterval(interval); + } + }, + startLoadingMagicSam: function startLoadingMagicSam() { + this.loadingMagicSam = true; + }, + finishLoadingMagicSam: function finishLoadingMagicSam() { + this.loadingMagicSam = false; + this.loadingMagicSamTakesLong = false; + }, + toggleMagicSam: function toggleMagicSam() { + if (this.isMagicSamming) { + this.resetInteractionMode(); + } else if (this.canAdd && !this.image.tiled) { + if (!magicSamInteraction) { + this.initMagicSamInteraction(); + } + + this.interactionMode = 'magicSam'; + } + }, + handleSamEmbeddingRequestSuccess: function handleSamEmbeddingRequestSuccess(response) { + if (this.image.id !== loadingImageId) { + return; + } + + if (response.body.url !== null) { + this.handleSamEmbeddingAvailable(response.body); + } else { + // Wait for the Websockets event. + this.loadingMagicSamTakesLong = true; + } + }, + handleSamEmbeddingRequestFailure: function handleSamEmbeddingRequestFailure(response) { + this.resetInteractionMode(); + this.finishLoadingMagicSam(); + (0,_import__WEBPACK_IMPORTED_MODULE_2__.handleErrorResponse)(response); + }, + handleSamEmbeddingAvailable: function handleSamEmbeddingAvailable(event) { + var _this = this; + + if (!this.loadingMagicSam) { + return; + } + + if (this.image.id !== loadingImageId) { + return; + } + + if (loadedImageId === this.image.id) { + return; + } + + loadedImageId = this.image.id; + magicSamInteraction.updateEmbedding(this.image, event.url).then(this.finishLoadingMagicSam).then(function () { + // The user could have disabled the interaction while loading. + if (_this.isMagicSamming) { + magicSamInteraction.setActive(true); + } + }); + }, + handleSamEmbeddingFailed: function handleSamEmbeddingFailed() { + if (this.loadingMagicSam) { + _import__WEBPACK_IMPORTED_MODULE_2__.Messages.danger('Could not load the image embedding.'); + this.finishLoadingMagicSam(); + this.resetInteractionMode(); + } + }, + initMagicSamInteraction: function initMagicSamInteraction() { + magicSamInteraction = new _ol_MagicSamInteraction__WEBPACK_IMPORTED_MODULE_1__["default"]({ + map: this.map, + source: this.annotationSource, + style: _import__WEBPACK_IMPORTED_MODULE_2__.Styles.editing, + indicatorPointStyle: _import__WEBPACK_IMPORTED_MODULE_2__.Styles.editing, + indicatorCrossStyle: _import__WEBPACK_IMPORTED_MODULE_2__.Styles.cross, + onnxUrl: biigle.$require('magic-sam.onnx-url'), + simplifyTolerant: 0.1, + throttleInterval: this.throttleInterval + }); + magicSamInteraction.on('drawend', this.handleNewFeature); + magicSamInteraction.setActive(false); + this.map.addInteraction(magicSamInteraction); + } + }, + watch: { + image: function image(_image) { + if (this.loadingMagicSam && loadingImageId !== _image.id) { + this.finishLoadingMagicSam(); + this.resetInteractionMode(); + } + + if (this.isMagicSamming) { + this.resetInteractionMode(); + } + }, + isMagicSamming: function isMagicSamming(active) { + if (!active) { + magicSamInteraction.setActive(false); + return; + } + + if (!this.hasSelectedLabel) { + this.requireSelectedLabel(); + return; + } + + if (loadedImageId === this.image.id) { + magicSamInteraction.setActive(true); + return; + } + + if (this.loadingMagicSam) { + return; + } + + loadingImageId = this.image.id; + this.startLoadingMagicSam(); + _api_image__WEBPACK_IMPORTED_MODULE_0__["default"].save({ + id: this.image.id + }, {}).then(this.handleSamEmbeddingRequestSuccess, this.handleSamEmbeddingRequestFailure); + }, + canAdd: { + handler: function handler(canAdd) { + if (canAdd) { + _import__WEBPACK_IMPORTED_MODULE_2__.Keyboard.on('z', this.toggleMagicSam, 0, this.listenerSet); + } else { + _import__WEBPACK_IMPORTED_MODULE_2__.Keyboard.off('z', this.toggleMagicSam, 0, this.listenerSet); + } + }, + immediate: true + } + }, + created: function created() { + _import__WEBPACK_IMPORTED_MODULE_2__.Events.$on('settings.samThrottleInterval', this.setThrottleInterval); + _import__WEBPACK_IMPORTED_MODULE_2__.Echo.getInstance()["private"]("user-".concat(this.userId)).listen('.Biigle\\Modules\\MagicSam\\Events\\EmbeddingAvailable', this.handleSamEmbeddingAvailable).listen('.Biigle\\Modules\\MagicSam\\Events\\EmbeddingFailed', this.handleSamEmbeddingFailed); + } +}); + +/***/ }), + +/***/ "./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./src/resources/assets/js/components/settingsTabPlugin.vue?vue&type=script&lang=js&": +/*!***********************************************************************************************************************************************************************************************************************************!*\ + !*** ./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./src/resources/assets/js/components/settingsTabPlugin.vue?vue&type=script&lang=js& ***! + \***********************************************************************************************************************************************************************************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _import__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../import */ "./src/resources/assets/js/import.js"); + +/** + * The plugin component to edit the Magic-SAM throttle interval. + * + * @type {Object} + */ + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + props: { + settings: { + type: Object, + required: true + } + }, + data: function data() { + return { + steps: [2000, 1000, 500, 200, 100], + stepNames: ['slower', 'slow', 'medium', 'fast', 'faster'], + stepIndex: 2 + }; + }, + computed: { + stepName: function stepName() { + return this.stepNames[this.stepIndex]; + } + }, + watch: { + stepIndex: function stepIndex(index) { + var interval = this.steps[index]; + _import__WEBPACK_IMPORTED_MODULE_0__.Events.$emit('settings.samThrottleInterval', interval); + this.settings.set('samRefreshRateStep', index); + } + }, + created: function created() { + if (this.settings.has('samRefreshRateStep')) { + this.stepIndex = this.settings.get('samRefreshRateStep'); + } + } +}); + +/***/ }), + +/***/ "./src/resources/assets/js/api/image.js": +/*!**********************************************!*\ + !*** ./src/resources/assets/js/api/image.js ***! + \**********************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * Resource to request a SAM embedding. + * + * resource.save({id: 1}, {}).then(...); + * + * @type {Vue.resource} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Vue.resource('api/v1/images{/id}/sam-embedding')); + +/***/ }), + +/***/ "./src/resources/assets/js/import.js": +/*!*******************************************!*\ + !*** ./src/resources/assets/js/import.js ***! + \*******************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Echo": () => (/* binding */ Echo), +/* harmony export */ "Events": () => (/* binding */ Events), +/* harmony export */ "Keyboard": () => (/* binding */ Keyboard), +/* harmony export */ "Messages": () => (/* binding */ Messages), +/* harmony export */ "SettingsTabPlugins": () => (/* binding */ SettingsTabPlugins), +/* harmony export */ "Styles": () => (/* binding */ Styles), +/* harmony export */ "annotationCanvasMixins": () => (/* binding */ annotationCanvasMixins), +/* harmony export */ "handleErrorResponse": () => (/* binding */ handleErrorResponse), +/* harmony export */ "throttle": () => (/* binding */ throttle) +/* harmony export */ }); +var annotationCanvasMixins = biigle.$require('annotations.stores.canvasMixins'); +var Echo = biigle.$require('echo'); +var Events = biigle.$require('events'); +var Keyboard = biigle.$require('keyboard'); +var Messages = biigle.$require('messages'); +var handleErrorResponse = Messages.handleErrorResponse; +var SettingsTabPlugins = biigle.$require('annotations.components.settingsTabPlugins'); +var Styles = biigle.$require('annotations.stores.styles'); +var throttle = biigle.$require('utils.throttle'); + +/***/ }), + +/***/ "./src/resources/assets/js/main.js": +/*!*****************************************!*\ + !*** ./src/resources/assets/js/main.js ***! + \*****************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _settingsTabPlugins__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./settingsTabPlugins */ "./src/resources/assets/js/settingsTabPlugins.js"); +/* harmony import */ var _MagicSamMixin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./MagicSamMixin */ "./src/resources/assets/js/MagicSamMixin.vue"); +/* harmony import */ var _import__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./import */ "./src/resources/assets/js/import.js"); + + + +_import__WEBPACK_IMPORTED_MODULE_2__.annotationCanvasMixins.push(_MagicSamMixin__WEBPACK_IMPORTED_MODULE_1__["default"]); + +/***/ }), + +/***/ "./src/resources/assets/js/ol/MagicSamInteraction.js": +/*!***********************************************************!*\ + !*** ./src/resources/assets/js/ol/MagicSamInteraction.js ***! + \***********************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _biigle_ol_Feature__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @biigle/ol/Feature */ "./node_modules/@biigle/ol/Feature.js"); +/* harmony import */ var magic_wand_tool__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! magic-wand-tool */ "./node_modules/magic-wand-tool/dist/magic-wand.js"); +/* harmony import */ var magic_wand_tool__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(magic_wand_tool__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var npyjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! npyjs */ "./node_modules/npyjs/index.js"); +/* harmony import */ var _biigle_ol_interaction_Pointer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @biigle/ol/interaction/Pointer */ "./node_modules/@biigle/ol/interaction/Pointer.js"); +/* harmony import */ var _biigle_ol_geom_Polygon__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @biigle/ol/geom/Polygon */ "./node_modules/@biigle/ol/geom/Polygon.js"); +/* harmony import */ var _biigle_ol_layer_Vector__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @biigle/ol/layer/Vector */ "./node_modules/@biigle/ol/layer/Vector.js"); +/* harmony import */ var _biigle_ol_source_Vector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @biigle/ol/source/Vector */ "./node_modules/@biigle/ol/source/Vector.js"); +/* harmony import */ var onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! onnxruntime-web */ "./node_modules/onnxruntime-web/dist/ort-web.min.js"); +/* harmony import */ var onnxruntime_web__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _biigle_ol_geom_flat_contains__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @biigle/ol/geom/flat/contains */ "./node_modules/@biigle/ol/geom/flat/contains.js"); +/* harmony import */ var _import__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../import */ "./src/resources/assets/js/import.js"); +function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } + +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } + +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + +function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } + +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } + + + + + + + + + + + + +var LONG_SIDE_LENGTH = 1024; + +function contourContainsPoint(contour, point) { + var flatContour = contour.points.flatMap(function (p) { + return [p.x, p.y]; + }); + + var _point = _slicedToArray(point, 2), + px = _point[0], + py = _point[1]; + + return (0,_biigle_ol_geom_flat_contains__WEBPACK_IMPORTED_MODULE_4__.linearRingContainsXY)(flatContour, 0, flatContour.length, 2, px, py); +} +/** + * Control for drawing polygons using the Segment Anything Model (SAM). + */ + + +var MagicSamInteraction = /*#__PURE__*/function (_PointerInteraction) { + _inherits(MagicSamInteraction, _PointerInteraction); + + var _super = _createSuper(MagicSamInteraction); + + function MagicSamInteraction(options) { + var _this; + + _classCallCheck(this, MagicSamInteraction); + + _this = _super.call(this, options); + + _this.on('change:active', _this.toggleActive); // The image layer to use as source for the magic wand tool. + + + _this.layer = options.layer; // Value to adjust simplification of the sketch polygon. Higher values result in + // less vertices of the polygon. Set to 0 to disable simplification. + + _this.simplifyTolerant = options.simplifyTolerant === undefined ? 0 : options.simplifyTolerant; // Minimum number of required vertices for the simplified polygon. + + _this.simplifyCount = options.simplifyCount === undefined ? 3 : options.simplifyCount; + _this.map = options.map; + _this.throttleInterval = options.throttleInterval || 1000; + _this.sketchFeature = null; + _this.source = options.source; + + if (_this.source === undefined) { + _this.source = new _biigle_ol_source_Vector__WEBPACK_IMPORTED_MODULE_5__["default"](); + + _this.map.addLayer(new _biigle_ol_layer_Vector__WEBPACK_IMPORTED_MODULE_6__["default"]({ + source: _this.source, + zIndex: 200 + })); + } + + var sketchLayer = new _biigle_ol_layer_Vector__WEBPACK_IMPORTED_MODULE_6__["default"]({ + source: new _biigle_ol_source_Vector__WEBPACK_IMPORTED_MODULE_5__["default"](), + map: _this.map, + zIndex: 200 + }); + _this.sketchSource = sketchLayer.getSource(); + _this.sketchStyle = options.style === undefined ? null : options.style; + _this.MASK_INPUT_TENSOR = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", new Float32Array(256 * 256), [1, 1, 256, 256]); + _this.HAS_MASK_INPUT_TENSOR = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", [0]); // Add in the extra label when only clicks and no box. + // The extra point is at (0, 0) with label -1. + + _this.POINT_LABELS_TENSOR = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", new Float32Array([1.0, -1.0]), [1, 2]); + _this.model = null; + _this.embedding = null; + _this.imageSizeTensor = null; + _this.samSizeTensor = null; + _this.imageSamScale = null; + _this.isDragging = false; // wasm needs to be present in the assets folder. + + _this.initPromise = onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.InferenceSession.create(options.onnxUrl, { + executionProviders: ['wasm'] + }).then(function (response) { + return _this.model = response; + }); + return _this; + } + + _createClass(MagicSamInteraction, [{ + key: "setThrottleInterval", + value: function setThrottleInterval(value) { + this.throttleInterval = value; + } + }, { + key: "getThrottleInterval", + value: function getThrottleInterval() { + return this.throttleInterval; + } + }, { + key: "updateEmbedding", + value: function updateEmbedding(image, url) { + var _this2 = this; + + this.imageSizeTensor = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", [image.height, image.width]); + this.imageSamScale = LONG_SIDE_LENGTH / Math.max(image.height, image.width); + this.samSizeTensor = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", [Math.round(image.height * this.imageSamScale), Math.round(image.width * this.imageSamScale)]); + var npy = new npyjs__WEBPACK_IMPORTED_MODULE_1__["default"](); // Maybe the model is not initialized at this point so we have to wait for that, + // too. + + return Vue.Promise.all([npy.load(url), this.initPromise]).then(function (_ref) { + var _ref2 = _slicedToArray(_ref, 1), + npArray = _ref2[0]; + + _this2.embedding = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", npArray.data, npArray.shape); + + _this2._runModelWarmup(); + }); + } + }, { + key: "handleUpEvent", + value: function handleUpEvent() { + // Do not fire the event if the user was previously dragging. + if (this.sketchFeature && !this.isDragging) { + this.dispatchEvent({ + type: 'drawend', + feature: this.sketchFeature + }); + } + + this.isDragging = false; + return true; + } + }, { + key: "handleDownEvent", + value: function handleDownEvent() { + return true; + } + }, { + key: "stopDown", + value: function stopDown() { + // The down event must be propagated so the map can still be dragged. + return false; + } + }, { + key: "handleDragEvent", + value: function handleDragEvent() { + this.isDragging = true; + } + /** + * Update the target point. + */ + + }, { + key: "handleMoveEvent", + value: function handleMoveEvent(e) { + var _this3 = this; + + if (!this.model) { + return; + } // Do this not faster than once per second. + + + (0,_import__WEBPACK_IMPORTED_MODULE_3__.throttle)(function () { + var _this3$imageSizeTenso = _slicedToArray(_this3.imageSizeTensor.data, 1), + height = _this3$imageSizeTenso[0]; + + var pointCoords = new Float32Array([e.coordinate[0] * _this3.imageSamScale, (height - e.coordinate[1]) * _this3.imageSamScale, // Add in the extra point when only clicks and no box. + // The extra point is at (0, 0) with label -1. + 0, 0]); + var pointCoordsTensor = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", pointCoords, [1, 2, 2]); + + var feeds = _this3._getFeeds(pointCoordsTensor); + + _this3.model.run(feeds).then(_this3._processInferenceResult.bind(_this3, pointCoords)); + }, this.throttleInterval, 'magic-sam-move'); + } + /** + * Update event listeners depending on the active state of the interaction. + */ + + }, { + key: "toggleActive", + value: function toggleActive() { + if (!this.getActive() && this.sketchFeature) { + if (this.source.hasFeature(this.sketchFeature)) { + this.source.removeFeature(this.sketchFeature); + } + + this.sketchFeature = null; + } + } + }, { + key: "_getFeeds", + value: function _getFeeds(pointCoordsTensor) { + return { + image_embeddings: this.embedding, + point_coords: pointCoordsTensor, + point_labels: this.POINT_LABELS_TENSOR, + // Compute the mask on the downscaled size to make inference and tracing + // faster. We scale the tracing result to the original size later. + orig_im_size: this.samSizeTensor, + mask_input: this.MASK_INPUT_TENSOR, + has_mask_input: this.HAS_MASK_INPUT_TENSOR + }; + } + }, { + key: "_runModelWarmup", + value: function _runModelWarmup() { + // Run the model once for "warmup". After that, the interactions is + // considered ready. + var pointCoordsTensor = new onnxruntime_web__WEBPACK_IMPORTED_MODULE_2__.Tensor("float32", [0, 0, 0, 0], [1, 2, 2]); + + var feeds = this._getFeeds(pointCoordsTensor); + + return this.model.run(feeds); + } + }, { + key: "_processInferenceResult", + value: function _processInferenceResult(pointCoords, results) { + var _this4 = this; + + // Discard this result if the interaction was disabled in the meantime. + if (!this.getActive()) { + return; + } + + var _this$imageSizeTensor = _slicedToArray(this.imageSizeTensor.data, 1), + height = _this$imageSizeTensor[0]; + + var _this$samSizeTensor$d = _slicedToArray(this.samSizeTensor.data, 2), + samHeight = _this$samSizeTensor$d[0], + samWidth = _this$samSizeTensor$d[1]; + + var output = results[this.model.outputNames[0]]; + var thresholdedOutput = output.data.map(function (pixel) { + return pixel > 0 ? 1 : 0; + }); + var imageData = { + data: new Uint8Array(thresholdedOutput), + width: samWidth, + height: samHeight, + bounds: { + minX: 0, + maxX: samWidth, + minY: 0, + maxY: samHeight + } + }; + var contour = magic_wand_tool__WEBPACK_IMPORTED_MODULE_0___default().traceContours(imageData).filter(function (c) { + return !c.inner; + }).filter(function (c) { + return contourContainsPoint(c, pointCoords); + }).shift(); + + if (!contour) { + return; + } + + if (this.simplifyTolerant > 0) { + contour = magic_wand_tool__WEBPACK_IMPORTED_MODULE_0___default().simplifyContours([contour], this.simplifyTolerant, this.simplifyCount).shift(); + } + + var points = contour.points.map(function (point) { + return [point.x, point.y]; + }) // Scale up to original size. + .map(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + x = _ref4[0], + y = _ref4[1]; + + return [x / _this4.imageSamScale, y / _this4.imageSamScale]; + }) // Invert y axis for OpenLayers coordinates. + .map(function (_ref5) { + var _ref6 = _slicedToArray(_ref5, 2), + x = _ref6[0], + y = _ref6[1]; + + return [x, height - y]; + }); + + if (this.sketchFeature) { + this.sketchFeature.getGeometry().setCoordinates([points]); + } else { + this.sketchFeature = new _biigle_ol_Feature__WEBPACK_IMPORTED_MODULE_7__["default"](new _biigle_ol_geom_Polygon__WEBPACK_IMPORTED_MODULE_8__["default"]([points])); + + if (this.sketchStyle) { + this.sketchFeature.setStyle(this.sketchStyle); + } + } // This happens if the sketch feature was newly created (above) or if an annotation + // was created from the feature (which may also remove the sketch from its source). + + + if (!this.sketchSource.hasFeature(this.sketchFeature)) { + this.sketchSource.clear(); + this.sketchSource.addFeature(this.sketchFeature); + } + } + }]); + + return MagicSamInteraction; +}(_biigle_ol_interaction_Pointer__WEBPACK_IMPORTED_MODULE_9__["default"]); + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MagicSamInteraction); + +/***/ }), + +/***/ "./src/resources/assets/js/settingsTabPlugins.js": +/*!*******************************************************!*\ + !*** ./src/resources/assets/js/settingsTabPlugins.js ***! + \*******************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony import */ var _components_settingsTabPlugin__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./components/settingsTabPlugin */ "./src/resources/assets/js/components/settingsTabPlugin.vue"); +/* harmony import */ var _import__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./import */ "./src/resources/assets/js/import.js"); + + +/** + * The plugin component set the SAM throttle interval. + * + * @type {Object} + */ + +if (_import__WEBPACK_IMPORTED_MODULE_1__.SettingsTabPlugins) { + _import__WEBPACK_IMPORTED_MODULE_1__.SettingsTabPlugins.magicSam = _components_settingsTabPlugin__WEBPACK_IMPORTED_MODULE_0__["default"]; +} + +/***/ }), + +/***/ "./node_modules/cross-fetch/dist/browser-ponyfill.js": +/*!***********************************************************!*\ + !*** ./node_modules/cross-fetch/dist/browser-ponyfill.js ***! + \***********************************************************/ +/***/ (function(module, exports) { + +var global = typeof self !== 'undefined' ? self : this; +var __self__ = (function () { +function F() { +this.fetch = false; +this.DOMException = global.DOMException +} +F.prototype = global; +return new F(); +})(); +(function(self) { + +var irrelevant = (function (exports) { + + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: + 'FileReader' in self && + 'Blob' in self && + (function() { + try { + new Blob(); + return true + } catch (e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + }; + + function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ]; + + var isArrayBufferView = + ArrayBuffer.isView || + function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + }; + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value); + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift(); + return {done: value === undefined, value: value} + } + }; + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + }; + } + + return iterator + } + + function Headers(headers) { + this.map = {}; + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ', ' + value : value; + }; + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)]; + }; + + Headers.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null + }; + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + }; + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; + + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + + Headers.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items) + }; + + Headers.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items) + }; + + Headers.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items) + }; + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true; + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise + } + + function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsText(blob); + return promise + } + + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]); + } + return chars.join('') + } + + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + this._bodyText = body = Object.prototype.toString.call(body); + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } + + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + }; + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + }; + } + + this.json = function() { + return this.text().then(JSON.parse) + }; + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; + + function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method + } + + function Request(input, options) { + options = options || {}; + var body = options.body; + + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + + this.credentials = options.credentials || this.credentials || 'same-origin'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + this.method = normalizeMethod(options.method || this.method || 'GET'); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal; + this.referrer = null; + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body); + } + + Request.prototype.clone = function() { + return new Request(this, {body: this._bodyInit}) + }; + + function decode(body) { + var form = new FormData(); + body + .trim() + .split('&') + .forEach(function(bytes) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers(); + // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + preProcessedHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + return headers + } + + Body.call(Request.prototype); + + function Response(bodyInit, options) { + if (!options) { + options = {}; + } + + this.type = 'default'; + this.status = options.status === undefined ? 200 : options.status; + this.ok = this.status >= 200 && this.status < 300; + this.statusText = 'statusText' in options ? options.statusText : 'OK'; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + + Body.call(Response.prototype); + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + }; + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}); + response.type = 'error'; + return response + }; + + var redirectStatuses = [301, 302, 303, 307, 308]; + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + }; + + exports.DOMException = self.DOMException; + try { + new exports.DOMException(); + } catch (err) { + exports.DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + exports.DOMException.prototype = Object.create(Error.prototype); + exports.DOMException.prototype.constructor = exports.DOMException; + } + + function fetch(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init); + + if (request.signal && request.signal.aborted) { + return reject(new exports.DOMException('Aborted', 'AbortError')) + } + + var xhr = new XMLHttpRequest(); + + function abortXhr() { + xhr.abort(); + } + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + var body = 'response' in xhr ? xhr.response : xhr.responseText; + resolve(new Response(body, options)); + }; + + xhr.onerror = function() { + reject(new TypeError('Network request failed')); + }; + + xhr.ontimeout = function() { + reject(new TypeError('Network request failed')); + }; + + xhr.onabort = function() { + reject(new exports.DOMException('Aborted', 'AbortError')); + }; + + xhr.open(request.method, request.url, true); + + if (request.credentials === 'include') { + xhr.withCredentials = true; + } else if (request.credentials === 'omit') { + xhr.withCredentials = false; + } + + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob'; + } + + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + + if (request.signal) { + request.signal.addEventListener('abort', abortXhr); + + xhr.onreadystatechange = function() { + // DONE (success or failure) + if (xhr.readyState === 4) { + request.signal.removeEventListener('abort', abortXhr); + } + }; + } + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); + }) + } + + fetch.polyfill = true; + + if (!self.fetch) { + self.fetch = fetch; + self.Headers = Headers; + self.Request = Request; + self.Response = Response; + } + + exports.Headers = Headers; + exports.Request = Request; + exports.Response = Response; + exports.fetch = fetch; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); +})(__self__); +__self__.fetch.ponyfill = true; +// Remove "polyfill" property added by whatwg-fetch +delete __self__.fetch.polyfill; +// Choose between native implementation (global) or custom implementation (__self__) +// var ctx = global.fetch ? global : __self__; +var ctx = __self__; // this line disable service worker support temporarily +exports = ctx.fetch // To enable: import fetch from 'cross-fetch' +exports["default"] = ctx.fetch // For TypeScript consumers without esModuleInterop. +exports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch' +exports.Headers = ctx.Headers +exports.Request = ctx.Request +exports.Response = ctx.Response +module.exports = exports + + +/***/ }), + +/***/ "./node_modules/magic-wand-tool/dist/magic-wand.js": +/*!*********************************************************!*\ + !*** ./node_modules/magic-wand-tool/dist/magic-wand.js ***! + \*********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* module decorator */ module = __webpack_require__.nmd(module); +/* + Magic wand tool (fuzzy selection) by color + + @package magic-wand-tool + @author Ryasnoy Paul + @version 1.1.7 + @license MIT + @copyright (c) 2014-2020, Ryasnoy Paul + +*/ + +var MagicWand = (function () { + var lib = {}; + + /** Create a binary mask on the image by color threshold + * Algorithm: Scanline flood fill (http://en.wikipedia.org/wiki/Flood_fill) + * @param {Object} image: {Uint8Array} data, {int} width, {int} height, {int} bytes + * @param {int} x of start pixel + * @param {int} y of start pixel + * @param {int} color threshold + * @param {Uint8Array} mask of visited points (optional) + * @param {boolean} [includeBorders=false] indicate whether to include borders pixels + * @return {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + */ + lib.floodFill = function(image, px, py, colorThreshold, mask, includeBorders) { + return includeBorders + ? floodFillWithBorders(image, px, py, colorThreshold, mask) + : floodFillWithoutBorders(image, px, py, colorThreshold, mask); + }; + + function floodFillWithoutBorders(image, px, py, colorThreshold, mask) { + + var c, x, newY, el, xr, xl, dy, dyl, dyr, checkY, + data = image.data, + w = image.width, + h = image.height, + bytes = image.bytes, // number of bytes in the color + maxX = -1, minX = w + 1, maxY = -1, minY = h + 1, + i = py * w + px, // start point index in the mask data + result = new Uint8Array(w * h), // result mask + visited = new Uint8Array(mask ? mask : w * h); // mask of visited points + + if (visited[i] === 1) return null; + + i = i * bytes; // start point index in the image data + var sampleColor = [data[i], data[i + 1], data[i + 2], data[i + 3]]; // start point color (sample) + + var stack = [{ y: py, left: px - 1, right: px + 1, dir: 1 }]; // first scanning line + do { + el = stack.shift(); // get line for scanning + + checkY = false; + for (x = el.left + 1; x < el.right; x++) { + dy = el.y * w; + i = (dy + x) * bytes; // point index in the image data + + if (visited[dy + x] === 1) continue; // check whether the point has been visited + // compare the color of the sample + c = data[i] - sampleColor[0]; // check by red + if (c > colorThreshold || c < -colorThreshold) continue; + c = data[i + 1] - sampleColor[1]; // check by green + if (c > colorThreshold || c < -colorThreshold) continue; + c = data[i + 2] - sampleColor[2]; // check by blue + if (c > colorThreshold || c < -colorThreshold) continue; + + checkY = true; // if the color of the new point(x,y) is similar to the sample color need to check minmax for Y + + result[dy + x] = 1; // mark a new point in mask + visited[dy + x] = 1; // mark a new point as visited + + xl = x - 1; + // walk to left side starting with the left neighbor + while (xl > -1) { + dyl = dy + xl; + i = dyl * bytes; // point index in the image data + if (visited[dyl] === 1) break; // check whether the point has been visited + // compare the color of the sample + c = data[i] - sampleColor[0]; // check by red + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 1] - sampleColor[1]; // check by green + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 2] - sampleColor[2]; // check by blue + if (c > colorThreshold || c < -colorThreshold) break; + + result[dyl] = 1; + visited[dyl] = 1; + + xl--; + } + xr = x + 1; + // walk to right side starting with the right neighbor + while (xr < w) { + dyr = dy + xr; + i = dyr * bytes; // index point in the image data + if (visited[dyr] === 1) break; // check whether the point has been visited + // compare the color of the sample + c = data[i] - sampleColor[0]; // check by red + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 1] - sampleColor[1]; // check by green + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 2] - sampleColor[2]; // check by blue + if (c > colorThreshold || c < -colorThreshold) break; + + result[dyr] = 1; + visited[dyr] = 1; + + xr++; + } + + // check minmax for X + if (xl < minX) minX = xl + 1; + if (xr > maxX) maxX = xr - 1; + + newY = el.y - el.dir; + if (newY >= 0 && newY < h) { // add two scanning lines in the opposite direction (y - dir) if necessary + if (xl < el.left) stack.push({ y: newY, left: xl, right: el.left, dir: -el.dir }); // from "new left" to "current left" + if (el.right < xr) stack.push({ y: newY, left: el.right, right: xr, dir: -el.dir }); // from "current right" to "new right" + } + newY = el.y + el.dir; + if (newY >= 0 && newY < h) { // add the scanning line in the direction (y + dir) if necessary + if (xl < xr) stack.push({ y: newY, left: xl, right: xr, dir: el.dir }); // from "new left" to "new right" + } + } + // check minmax for Y if necessary + if (checkY) { + if (el.y < minY) minY = el.y; + if (el.y > maxY) maxY = el.y; + } + } while (stack.length > 0); + + return { + data: result, + width: image.width, + height: image.height, + bounds: { + minX: minX, + minY: minY, + maxX: maxX, + maxY: maxY + } + }; + } + function floodFillWithBorders(image, px, py, colorThreshold, mask) { + + var c, x, newY, el, xr, xl, dy, dyl, dyr, checkY, + data = image.data, + w = image.width, + h = image.height, + bytes = image.bytes, // number of bytes in the color + maxX = -1, minX = w + 1, maxY = -1, minY = h + 1, + i = py * w + px, // start point index in the mask data + result = new Uint8Array(w * h), // result mask + visited = new Uint8Array(mask ? mask : w * h); // mask of visited points + + if (visited[i] === 1) return null; + + i = i * bytes; // start point index in the image data + var sampleColor = [data[i], data[i + 1], data[i + 2], data[i + 3]]; // start point color (sample) + + var stack = [{ y: py, left: px - 1, right: px + 1, dir: 1 }]; // first scanning line + do { + el = stack.shift(); // get line for scanning + + checkY = false; + for (x = el.left + 1; x < el.right; x++) { + dy = el.y * w; + i = (dy + x) * bytes; // point index in the image data + + if (visited[dy + x] === 1) continue; // check whether the point has been visited + + checkY = true; // if the color of the new point(x,y) is similar to the sample color need to check minmax for Y + + result[dy + x] = 1; // mark a new point in mask + visited[dy + x] = 1; // mark a new point as visited + + // compare the color of the sample + c = data[i] - sampleColor[0]; // check by red + if (c > colorThreshold || c < -colorThreshold) continue; + c = data[i + 1] - sampleColor[1]; // check by green + if (c > colorThreshold || c < -colorThreshold) continue; + c = data[i + 2] - sampleColor[2]; // check by blue + if (c > colorThreshold || c < -colorThreshold) continue; + + xl = x - 1; + // walk to left side starting with the left neighbor + while (xl > -1) { + dyl = dy + xl; + i = dyl * bytes; // point index in the image data + if (visited[dyl] === 1) break; // check whether the point has been visited + + result[dyl] = 1; + visited[dyl] = 1; + xl--; + + // compare the color of the sample + c = data[i] - sampleColor[0]; // check by red + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 1] - sampleColor[1]; // check by green + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 2] - sampleColor[2]; // check by blue + if (c > colorThreshold || c < -colorThreshold) break; + } + xr = x + 1; + // walk to right side starting with the right neighbor + while (xr < w) { + dyr = dy + xr; + i = dyr * bytes; // index point in the image data + if (visited[dyr] === 1) break; // check whether the point has been visited + + result[dyr] = 1; + visited[dyr] = 1; + xr++; + + // compare the color of the sample + c = data[i] - sampleColor[0]; // check by red + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 1] - sampleColor[1]; // check by green + if (c > colorThreshold || c < -colorThreshold) break; + c = data[i + 2] - sampleColor[2]; // check by blue + if (c > colorThreshold || c < -colorThreshold) break; + } + + // check minmax for X + if (xl < minX) minX = xl + 1; + if (xr > maxX) maxX = xr - 1; + + newY = el.y - el.dir; + if (newY >= 0 && newY < h) { // add two scanning lines in the opposite direction (y - dir) if necessary + if (xl < el.left) stack.push({ y: newY, left: xl, right: el.left, dir: -el.dir }); // from "new left" to "current left" + if (el.right < xr) stack.push({ y: newY, left: el.right, right: xr, dir: -el.dir }); // from "current right" to "new right" + } + newY = el.y + el.dir; + if (newY >= 0 && newY < h) { // add the scanning line in the direction (y + dir) if necessary + if (xl < xr) stack.push({ y: newY, left: xl, right: xr, dir: el.dir }); // from "new left" to "new right" + } + } + // check minmax for Y if necessary + if (checkY) { + if (el.y < minY) minY = el.y; + if (el.y > maxY) maxY = el.y; + } + } while (stack.length > 0); + + return { + data: result, + width: image.width, + height: image.height, + bounds: { + minX: minX, + minY: minY, + maxX: maxX, + maxY: maxY + } + }; + } + /** Apply the gauss-blur filter to binary mask + * Algorithms: http://blog.ivank.net/fastest-gaussian-blur.html + * http://www.librow.com/articles/article-9 + * http://elynxsdk.free.fr/ext-docs/Blur/Fast_box_blur.pdf + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + * @param {int} blur radius + * @return {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + */ + lib.gaussBlur = function(mask, radius) { + + var i, k, k1, x, y, val, start, end, + n = radius * 2 + 1, // size of the pattern for radius-neighbors (from -r to +r with the center point) + s2 = radius * radius, + wg = new Float32Array(n), // weights + total = 0, // sum of weights(used for normalization) + w = mask.width, + h = mask.height, + data = mask.data, + minX = mask.bounds.minX, + maxX = mask.bounds.maxX, + minY = mask.bounds.minY, + maxY = mask.bounds.maxY; + + // calc gauss weights + for (i = 0; i < radius; i++) { + var dsq = (radius - i) * (radius - i); + var ww = Math.exp(-dsq / (2.0 * s2)) / (2 * Math.PI * s2); + wg[radius + i] = wg[radius - i] = ww; + total += 2 * ww; + } + // normalization weights + for (i = 0; i < n; i++) { + wg[i] /= total; + } + + var result = new Uint8Array(w * h), // result mask + endX = radius + w, + endY = radius + h; + + //walk through all source points for blur + for (y = minY; y < maxY + 1; y++) + for (x = minX; x < maxX + 1; x++) { + val = 0; + k = y * w + x; // index of the point + start = radius - x > 0 ? radius - x : 0; + end = endX - x < n ? endX - x : n; // Math.min((((w - 1) - x) + radius) + 1, n); + k1 = k - radius; + // walk through x-neighbors + for (i = start; i < end; i++) { + val += data[k1 + i] * wg[i]; + } + start = radius - y > 0 ? radius - y : 0; + end = endY - y < n ? endY - y : n; // Math.min((((h - 1) - y) + radius) + 1, n); + k1 = k - radius * w; + // walk through y-neighbors + for (i = start; i < end; i++) { + val += data[k1 + i * w] * wg[i]; + } + result[k] = val > 0.5 ? 1 : 0; + } + + return { + data: result, + width: w, + height: h, + bounds: { + minX: minX, + minY: minY, + maxX: maxX, + maxY: maxY + } + }; + }; + + /** Create a border index array of boundary points of the mask with radius-neighbors + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + * @param {int} blur radius + * @param {Uint8Array} visited: mask of visited points (optional) + * @return {Array} border index array of boundary points with radius-neighbors (only points need for blur) + */ + function createBorderForBlur(mask, radius, visited) { + + var x, i, j, y, k, k1, k2, + w = mask.width, + h = mask.height, + data = mask.data, + visitedData = new Uint8Array(data), + minX = mask.bounds.minX, + maxX = mask.bounds.maxX, + minY = mask.bounds.minY, + maxY = mask.bounds.maxY, + len = w * h, + temp = new Uint8Array(len), // auxiliary array to check uniqueness + border = [], // only border points + x0 = Math.max(minX, 1), + x1 = Math.min(maxX, w - 2), + y0 = Math.max(minY, 1), + y1 = Math.min(maxY, h - 2); + + if (visited && visited.length > 0) { + // copy visited points (only "black") + for (k = 0; k < len; k++) { + if (visited[k] === 1) visitedData[k] = 1; + } + } + + // walk through inner values except points on the boundary of the image + for (y = y0; y < y1 + 1; y++) + for (x = x0; x < x1 + 1; x++) { + k = y * w + x; + if (data[k] === 0) continue; // "white" point isn't the border + k1 = k + w; // y + 1 + k2 = k - w; // y - 1 + // check if any neighbor with a "white" color + if (visitedData[k + 1] === 0 || visitedData[k - 1] === 0 || + visitedData[k1] === 0 || visitedData[k1 + 1] === 0 || visitedData[k1 - 1] === 0 || + visitedData[k2] === 0 || visitedData[k2 + 1] === 0 || visitedData[k2 - 1] === 0) { + //if (visitedData[k + 1] + visitedData[k - 1] + + // visitedData[k1] + visitedData[k1 + 1] + visitedData[k1 - 1] + + // visitedData[k2] + visitedData[k2 + 1] + visitedData[k2 - 1] == 8) continue; + border.push(k); + } + } + + // walk through points on the boundary of the image if necessary + // if the "black" point is adjacent to the boundary of the image, it is a border point + if (minX == 0) + for (y = minY; y < maxY + 1; y++) + if (data[y * w] === 1) + border.push(y * w); + + if (maxX == w - 1) + for (y = minY; y < maxY + 1; y++) + if (data[y * w + maxX] === 1) + border.push(y * w + maxX); + + if (minY == 0) + for (x = minX; x < maxX + 1; x++) + if (data[x] === 1) + border.push(x); + + if (maxY == h - 1) + for (x = minX; x < maxX + 1; x++) + if (data[maxY * w + x] === 1) + border.push(maxY * w + x); + + var result = [], // border points with radius-neighbors + start, end, + endX = radius + w, + endY = radius + h, + n = radius * 2 + 1; // size of the pattern for radius-neighbors (from -r to +r with the center point) + + len = border.length; + // walk through radius-neighbors of border points and add them to the result array + for (j = 0; j < len; j++) { + k = border[j]; // index of the border point + temp[k] = 1; // mark border point + result.push(k); // save the border point + x = k % w; // calc x by index + y = (k - x) / w; // calc y by index + start = radius - x > 0 ? radius - x : 0; + end = endX - x < n ? endX - x : n; // Math.min((((w - 1) - x) + radius) + 1, n); + k1 = k - radius; + // walk through x-neighbors + for (i = start; i < end; i++) { + k2 = k1 + i; + if (temp[k2] === 0) { // check the uniqueness + temp[k2] = 1; + result.push(k2); + } + } + start = radius - y > 0 ? radius - y : 0; + end = endY - y < n ? endY - y : n; // Math.min((((h - 1) - y) + radius) + 1, n); + k1 = k - radius * w; + // walk through y-neighbors + for (i = start; i < end; i++) { + k2 = k1 + i * w; + if (temp[k2] === 0) { // check the uniqueness + temp[k2] = 1; + result.push(k2); + } + } + } + + return result; + } + /** Apply the gauss-blur filter ONLY to border points with radius-neighbors + * Algorithms: http://blog.ivank.net/fastest-gaussian-blur.html + * http://www.librow.com/articles/article-9 + * http://elynxsdk.free.fr/ext-docs/Blur/Fast_box_blur.pdf + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + * @param {int} blur radius + * @param {Uint8Array} visited: mask of visited points (optional) + * @return {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + */ + lib.gaussBlurOnlyBorder = function(mask, radius, visited) { + + var border = createBorderForBlur(mask, radius, visited), // get border points with radius-neighbors + ww, dsq, i, j, k, k1, x, y, val, start, end, + n = radius * 2 + 1, // size of the pattern for radius-neighbors (from -r to +r with center point) + s2 = 2 * radius * radius, + wg = new Float32Array(n), // weights + total = 0, // sum of weights(used for normalization) + w = mask.width, + h = mask.height, + data = mask.data, + minX = mask.bounds.minX, + maxX = mask.bounds.maxX, + minY = mask.bounds.minY, + maxY = mask.bounds.maxY, + len = border.length; + + // calc gauss weights + for (i = 0; i < radius; i++) { + dsq = (radius - i) * (radius - i); + ww = Math.exp(-dsq / s2) / Math.PI; + wg[radius + i] = wg[radius - i] = ww; + total += 2 * ww; + } + // normalization weights + for (i = 0; i < n; i++) { + wg[i] /= total; + } + + var result = new Uint8Array(data), // copy the source mask + endX = radius + w, + endY = radius + h; + + //walk through all border points for blur + for (i = 0; i < len; i++) { + k = border[i]; // index of the border point + val = 0; + x = k % w; // calc x by index + y = (k - x) / w; // calc y by index + start = radius - x > 0 ? radius - x : 0; + end = endX - x < n ? endX - x : n; // Math.min((((w - 1) - x) + radius) + 1, n); + k1 = k - radius; + // walk through x-neighbors + for (j = start; j < end; j++) { + val += data[k1 + j] * wg[j]; + } + if (val > 0.5) { + result[k] = 1; + // check minmax + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + continue; + } + start = radius - y > 0 ? radius - y : 0; + end = endY - y < n ? endY - y : n; // Math.min((((h - 1) - y) + radius) + 1, n); + k1 = k - radius * w; + // walk through y-neighbors + for (j = start; j < end; j++) { + val += data[k1 + j * w] * wg[j]; + } + if (val > 0.5) { + result[k] = 1; + // check minmax + if (x < minX) minX = x; + if (x > maxX) maxX = x; + if (y < minY) minY = y; + if (y > maxY) maxY = y; + } else { + result[k] = 0; + } + } + + return { + data: result, + width: w, + height: h, + bounds: { + minX: minX, + minY: minY, + maxX: maxX, + maxY: maxY + } + }; + }; + + /** Create a border mask (only boundary points) + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + * @return {Object} border mask: {Uint8Array} data, {int} width, {int} height, {Object} offset + */ + lib.createBorderMask = function(mask) { + + var x, y, k, k1, k2, + w = mask.width, + h = mask.height, + data = mask.data, + minX = mask.bounds.minX, + maxX = mask.bounds.maxX, + minY = mask.bounds.minY, + maxY = mask.bounds.maxY, + rw = maxX - minX + 1, // bounds size + rh = maxY - minY + 1, + result = new Uint8Array(rw * rh), // reduced mask (bounds size) + x0 = Math.max(minX, 1), + x1 = Math.min(maxX, w - 2), + y0 = Math.max(minY, 1), + y1 = Math.min(maxY, h - 2); + + // walk through inner values except points on the boundary of the image + for (y = y0; y < y1 + 1; y++) + for (x = x0; x < x1 + 1; x++) { + k = y * w + x; + if (data[k] === 0) continue; // "white" point isn't the border + k1 = k + w; // y + 1 + k2 = k - w; // y - 1 + // check if any neighbor with a "white" color + if (data[k + 1] === 0 || data[k - 1] === 0 || + data[k1] === 0 || data[k1 + 1] === 0 || data[k1 - 1] === 0 || + data[k2] === 0 || data[k2 + 1] === 0 || data[k2 - 1] === 0) { + //if (data[k + 1] + data[k - 1] + + // data[k1] + data[k1 + 1] + data[k1 - 1] + + // data[k2] + data[k2 + 1] + data[k2 - 1] == 8) continue; + result[(y - minY) * rw + (x - minX)] = 1; + } + } + + // walk through points on the boundary of the image if necessary + // if the "black" point is adjacent to the boundary of the image, it is a border point + if (minX == 0) + for (y = minY; y < maxY + 1; y++) + if (data[y * w] === 1) + result[(y - minY) * rw] = 1; + + if (maxX == w - 1) + for (y = minY; y < maxY + 1; y++) + if (data[y * w + maxX] === 1) + result[(y - minY) * rw + (maxX - minX)] = 1; + + if (minY == 0) + for (x = minX; x < maxX + 1; x++) + if (data[x] === 1) + result[x - minX] = 1; + + if (maxY == h - 1) + for (x = minX; x < maxX + 1; x++) + if (data[maxY * w + x] === 1) + result[(maxY - minY) * rw + (x - minX)] = 1; + + return { + data: result, + width: rw, + height: rh, + offset: { x: minX, y: minY } + }; + }; + + /** Create a border index array of boundary points of the mask + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height + * @return {Array} border index array boundary points of the mask + */ + lib.getBorderIndices = function(mask) { + + var x, y, k, k1, k2, + w = mask.width, + h = mask.height, + data = mask.data, + border = [], // only border points + x1 = w - 1, + y1 = h - 1; + + // walk through inner values except points on the boundary of the image + for (y = 1; y < y1; y++) + for (x = 1; x < x1; x++) { + k = y * w + x; + if (data[k] === 0) continue; // "white" point isn't the border + k1 = k + w; // y + 1 + k2 = k - w; // y - 1 + // check if any neighbor with a "white" color + if (data[k + 1] === 0 || data[k - 1] === 0 || + data[k1] === 0 || data[k1 + 1] === 0 || data[k1 - 1] === 0 || + data[k2] === 0 || data[k2 + 1] === 0 || data[k2 - 1] === 0) { + //if (data[k + 1] + data[k - 1] + + // data[k1] + data[k1 + 1] + data[k1 - 1] + + // data[k2] + data[k2 + 1] + data[k2 - 1] == 8) continue; + border.push(k); + } + } + + // walk through points on the boundary of the image if necessary + // if the "black" point is adjacent to the boundary of the image, it is a border point + for (y = 0; y < h; y++) + if (data[y * w] === 1) + border.push(y * w); + + for (x = 0; x < w; x++) + if (data[x] === 1) + border.push(x); + + k = w - 1; + for (y = 0; y < h; y++) + if (data[y * w + k] === 1) + border.push(y * w + k); + + k = (h - 1) * w; + for (x = 0; x < w; x++) + if (data[k + x] === 1) + border.push(k + x); + + return border; + }; + + /** Create a compressed mask with a "white" border (1px border with zero values) for the contour tracing + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + * @return {Object} border mask: {Uint8Array} data, {int} width, {int} height, {Object} offset + */ + function prepareMask(mask) { + var x, y, + w = mask.width, + data = mask.data, + minX = mask.bounds.minX, + maxX = mask.bounds.maxX, + minY = mask.bounds.minY, + maxY = mask.bounds.maxY, + rw = maxX - minX + 3, // bounds size +1 px on each side (a "white" border) + rh = maxY - minY + 3, + result = new Uint8Array(rw * rh); // reduced mask (bounds size) + + // walk through inner values and copy only "black" points to the result mask + for (y = minY; y < maxY + 1; y++) + for (x = minX; x < maxX + 1; x++) { + if (data[y * w + x] === 1) + result[(y - minY + 1) * rw + (x - minX + 1)] = 1; + } + + return { + data: result, + width: rw, + height: rh, + offset: { x: minX - 1, y: minY - 1 } + }; + } + /** Create a contour array for the binary mask + * Algorithm: http://www.sciencedirect.com/science/article/pii/S1077314203001401 + * @param {Object} mask: {Uint8Array} data, {int} width, {int} height, {Object} bounds + * @return {Array} contours: {Array} points, {bool} inner, {int} label + */ + lib.traceContours = function(mask) { + var m = prepareMask(mask), + contours = [], + label = 0, + w = m.width, + w2 = w * 2, + h = m.height, + src = m.data, + dx = m.offset.x, + dy = m.offset.y, + dest = new Uint8Array(src), // label matrix + i, j, x, y, k, k1, c, inner, dir, first, second, current, previous, next, d; + + // all [dx,dy] pairs (array index is the direction) + // 5 6 7 + // 4 X 0 + // 3 2 1 + var directions = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; + + for (y = 1; y < h - 1; y++) + for (x = 1; x < w - 1; x++) { + k = y * w + x; + if (src[k] === 1) { + for (i = -w; i < w2; i += w2) { // k - w: outer tracing (y - 1), k + w: inner tracing (y + 1) + if (src[k + i] === 0 && dest[k + i] === 0) { // need contour tracing + inner = i === w; // is inner contour tracing ? + label++; // label for the next contour + + c = []; + dir = inner ? 2 : 6; // start direction + current = previous = first = { x: x, y: y }; + second = null; + while (true) { + dest[current.y * w + current.x] = label; // mark label for the current point + // bypass all the neighbors around the current point in a clockwise + for (j = 0; j < 8; j++) { + dir = (dir + 1) % 8; + + // get the next point by new direction + d = directions[dir]; // index as direction + next = { x: current.x + d[0], y: current.y + d[1] }; + + k1 = next.y * w + next.x; + if (src[k1] === 1) // black boundary pixel + { + dest[k1] = label; // mark a label + break; + } + dest[k1] = -1; // mark a white boundary pixel + next = null; + } + if (next === null) break; // no neighbours (one-point contour) + current = next; + if (second) { + if (previous.x === first.x && previous.y === first.y && current.x === second.x && current.y === second.y) { + break; // creating the contour completed when returned to original position + } + } else { + second = next; + } + c.push({ x: previous.x + dx, y: previous.y + dy }); + previous = current; + dir = (dir + 4) % 8; // next dir (symmetrically to the current direction) + } + + if (next != null) { + c.push({ x: first.x + dx, y: first.y + dy }); // close the contour + contours.push({ inner: inner, label: label, points: c }); // add contour to the list + } + } + } + } + } + + return contours; + }; + + /** Simplify contours + * Algorithms: http://psimpl.sourceforge.net/douglas-peucker.html + * http://neerc.ifmo.ru/wiki/index.php?title=%D0%A3%D0%BF%D1%80%D0%BE%D1%89%D0%B5%D0%BD%D0%B8%D0%B5_%D0%BF%D0%BE%D0%BB%D0%B8%D0%B3%D0%BE%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B9_%D1%86%D0%B5%D0%BF%D0%B8 + * @param {Array} contours: {Array} points, {bool} inner, {int} label + * @param {float} simplify tolerant + * @param {int} simplify count: min number of points when the contour is simplified + * @return {Array} contours: {Array} points, {bool} inner, {int} label, {int} initialCount + */ + lib.simplifyContours = function(contours, simplifyTolerant, simplifyCount) { + var lenContours = contours.length, + result = [], + i, j, k, c, points, len, resPoints, lst, stack, ids, + maxd, maxi, dist, r1, r2, r12, dx, dy, pi, pf, pl; + + // walk through all contours + for (j = 0; j < lenContours; j++) { + c = contours[j]; + points = c.points; + len = c.points.length; + + if (len < simplifyCount) { // contour isn't simplified + resPoints = []; + for (k = 0; k < len; k++) { + resPoints.push({ x: points[k].x, y: points[k].y }); + } + result.push({ inner: c.inner, label: c.label, points: resPoints, initialCount: len }); + continue; + } + + lst = [0, len - 1]; // always add first and last points + stack = [{ first: 0, last: len - 1 }]; // first processed edge + + do { + ids = stack.shift(); + if (ids.last <= ids.first + 1) // no intermediate points + { + continue; + } + + maxd = -1.0; // max distance from point to current edge + maxi = ids.first; // index of maximally distant point + + for (i = ids.first + 1; i < ids.last; i++) // bypass intermediate points in edge + { + // calc the distance from current point to edge + pi = points[i]; + pf = points[ids.first]; + pl = points[ids.last]; + dx = pi.x - pf.x; + dy = pi.y - pf.y; + r1 = Math.sqrt(dx * dx + dy * dy); + dx = pi.x - pl.x; + dy = pi.y - pl.y; + r2 = Math.sqrt(dx * dx + dy * dy); + dx = pf.x - pl.x; + dy = pf.y - pl.y; + r12 = Math.sqrt(dx * dx + dy * dy); + if (r1 >= Math.sqrt(r2 * r2 + r12 * r12)) dist = r2; + else if (r2 >= Math.sqrt(r1 * r1 + r12 * r12)) dist = r1; + else dist = Math.abs((dy * pi.x - dx * pi.y + pf.x * pl.y - pl.x * pf.y) / r12); + + if (dist > maxd) { + maxi = i; // save the index of maximally distant point + maxd = dist; + } + } + + if (maxd > simplifyTolerant) // if the max "deviation" is larger than allowed then... + { + lst.push(maxi); // add index to the simplified list + stack.push({ first: ids.first, last: maxi }); // add the left part for processing + stack.push({ first: maxi, last: ids.last }); // add the right part for processing + } + + } while (stack.length > 0); + + resPoints = []; + len = lst.length; + lst.sort(function(a, b) { return a - b; }); // restore index order + for (k = 0; k < len; k++) { + resPoints.push({ x: points[lst[k]].x, y: points[lst[k]].y }); // add result points to the correct order + } + result.push({ inner: c.inner, label: c.label, points: resPoints, initialCount: c.points.length }); + } + + return result; + }; + + return lib; +})(); + +if ( true && module !== null) module.exports = MagicWand; +if (typeof window !== "undefined" && window !== null) window.MagicWand = MagicWand; +//# sourceMappingURL=magic-wand.js.map + + +/***/ }), + +/***/ "./src/resources/assets/sass/main.scss": +/*!*********************************************!*\ + !*** ./src/resources/assets/sass/main.scss ***! + \*********************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +// extracted by mini-css-extract-plugin + + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/backend-impl.js": +/*!******************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/backend-impl.js ***! + \******************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "registerBackend": () => (/* binding */ registerBackend), +/* harmony export */ "resolveBackend": () => (/* binding */ resolveBackend) +/* harmony export */ }); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +const backends = {}; +const backendsSortedByPriority = []; +/** + * Register a backend. + * + * @param name - the name as a key to lookup as an execution provider. + * @param backend - the backend object. + * @param priority - an integer indicating the priority of the backend. Higher number means higher priority. if priority + * < 0, it will be considered as a 'beta' version and will not be used as a fallback backend by default. + * + * @internal + */ +const registerBackend = (name, backend, priority) => { + if (backend && typeof backend.init === 'function' && typeof backend.createSessionHandler === 'function') { + const currentBackend = backends[name]; + if (currentBackend === undefined) { + backends[name] = { backend, priority }; + } + else if (currentBackend.priority > priority) { + // same name is already registered with a higher priority. skip registeration. + return; + } + else if (currentBackend.priority === priority) { + if (currentBackend.backend !== backend) { + throw new Error(`cannot register backend "${name}" using priority ${priority}`); + } + } + if (priority >= 0) { + const i = backendsSortedByPriority.indexOf(name); + if (i !== -1) { + backendsSortedByPriority.splice(i, 1); + } + for (let i = 0; i < backendsSortedByPriority.length; i++) { + if (backends[backendsSortedByPriority[i]].priority <= priority) { + backendsSortedByPriority.splice(i, 0, name); + return; + } + } + backendsSortedByPriority.push(name); + } + return; + } + throw new TypeError('not a valid backend'); +}; +/** + * Resolve backend by specified hints. + * + * @param backendHints - a list of execution provider names to lookup. If omitted use registered backends as list. + * @returns a promise that resolves to the backend. + * + * @internal + */ +const resolveBackend = async (backendHints) => { + const backendNames = backendHints.length === 0 ? backendsSortedByPriority : backendHints; + const errors = []; + for (const backendName of backendNames) { + const backendInfo = backends[backendName]; + if (backendInfo) { + if (backendInfo.initialized) { + return backendInfo.backend; + } + else if (backendInfo.aborted) { + continue; // current backend is unavailable; try next + } + const isInitializing = !!backendInfo.initPromise; + try { + if (!isInitializing) { + backendInfo.initPromise = backendInfo.backend.init(); + } + await backendInfo.initPromise; + backendInfo.initialized = true; + return backendInfo.backend; + } + catch (e) { + if (!isInitializing) { + errors.push({ name: backendName, err: e }); + } + backendInfo.aborted = true; + } + finally { + delete backendInfo.initPromise; + } + } + } + throw new Error(`no available backend found. ERR: ${errors.map(e => `[${e.name}] ${e.err}`).join(', ')}`); +}; +//# sourceMappingURL=backend-impl.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/backend.js": +/*!*************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/backend.js ***! + \*************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "registerBackend": () => (/* reexport safe */ _backend_impl__WEBPACK_IMPORTED_MODULE_0__.registerBackend) +/* harmony export */ }); +/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "./node_modules/onnxruntime-common/dist/lib/backend-impl.js"); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//# sourceMappingURL=backend.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/env-impl.js": +/*!**************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/env-impl.js ***! + \**************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "EnvImpl": () => (/* binding */ EnvImpl) +/* harmony export */ }); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +class EnvImpl { + constructor() { + this.wasm = {}; + this.webgl = {}; + this.logLevelInternal = 'warning'; + } + // TODO standadize the getter and setter convention in env for other fields. + set logLevel(value) { + if (value === undefined) { + return; + } + if (typeof value !== 'string' || ['verbose', 'info', 'warning', 'error', 'fatal'].indexOf(value) === -1) { + throw new Error(`Unsupported logging level: ${value}`); + } + this.logLevelInternal = value; + } + get logLevel() { + return this.logLevelInternal; + } +} +//# sourceMappingURL=env-impl.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/env.js": +/*!*********************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/env.js ***! + \*********************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "env": () => (/* binding */ env) +/* harmony export */ }); +/* harmony import */ var _env_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./env-impl */ "./node_modules/onnxruntime-common/dist/lib/env-impl.js"); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Represent a set of flags as a global singleton. + */ +const env = new _env_impl__WEBPACK_IMPORTED_MODULE_0__.EnvImpl(); +//# sourceMappingURL=env.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/index.js": +/*!***********************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/index.js ***! + \***********************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "InferenceSession": () => (/* reexport safe */ _inference_session__WEBPACK_IMPORTED_MODULE_2__.InferenceSession), +/* harmony export */ "Tensor": () => (/* reexport safe */ _tensor__WEBPACK_IMPORTED_MODULE_3__.Tensor), +/* harmony export */ "env": () => (/* reexport safe */ _env__WEBPACK_IMPORTED_MODULE_1__.env), +/* harmony export */ "registerBackend": () => (/* reexport safe */ _backend__WEBPACK_IMPORTED_MODULE_0__.registerBackend) +/* harmony export */ }); +/* harmony import */ var _backend__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend */ "./node_modules/onnxruntime-common/dist/lib/backend.js"); +/* harmony import */ var _env__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./env */ "./node_modules/onnxruntime-common/dist/lib/env.js"); +/* harmony import */ var _inference_session__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./inference-session */ "./node_modules/onnxruntime-common/dist/lib/inference-session.js"); +/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tensor */ "./node_modules/onnxruntime-common/dist/lib/tensor.js"); +/* harmony import */ var _onnx_value__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./onnx-value */ "./node_modules/onnxruntime-common/dist/lib/onnx-value.js"); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * # ONNX Runtime JavaScript API + * + * ONNX Runtime JavaScript API is a unified API for all JavaScript usages, including the following NPM packages: + * + * - [onnxruntime-node](https://www.npmjs.com/package/onnxruntime-node) + * - [onnxruntime-web](https://www.npmjs.com/package/onnxruntime-web) + * - [onnxruntime-react-native](https://www.npmjs.com/package/onnxruntime-react-native) + * + * See also: + * - [Get Started](https://onnxruntime.ai/docs/get-started/with-javascript.html) + * - [Inference examples](https://github.com/microsoft/onnxruntime-inference-examples/tree/main/js) + * + * @packageDocumentation + */ + + + + + +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/inference-session-impl.js": +/*!****************************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/inference-session-impl.js ***! + \****************************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "InferenceSession": () => (/* binding */ InferenceSession) +/* harmony export */ }); +/* harmony import */ var _backend_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backend-impl */ "./node_modules/onnxruntime-common/dist/lib/backend-impl.js"); +/* harmony import */ var _tensor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./tensor */ "./node_modules/onnxruntime-common/dist/lib/tensor.js"); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + + +class InferenceSession { + constructor(handler) { + this.handler = handler; + } + async run(feeds, arg1, arg2) { + const fetches = {}; + let options = {}; + // check inputs + if (typeof feeds !== 'object' || feeds === null || feeds instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor || Array.isArray(feeds)) { + throw new TypeError('\'feeds\' must be an object that use input names as keys and OnnxValue as corresponding values.'); + } + let isFetchesEmpty = true; + // determine which override is being used + if (typeof arg1 === 'object') { + if (arg1 === null) { + throw new TypeError('Unexpected argument[1]: cannot be null.'); + } + if (arg1 instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) { + throw new TypeError('\'fetches\' cannot be a Tensor'); + } + if (Array.isArray(arg1)) { + if (arg1.length === 0) { + throw new TypeError('\'fetches\' cannot be an empty array.'); + } + isFetchesEmpty = false; + // output names + for (const name of arg1) { + if (typeof name !== 'string') { + throw new TypeError('\'fetches\' must be a string array or an object.'); + } + if (this.outputNames.indexOf(name) === -1) { + throw new RangeError(`'fetches' contains invalid output name: ${name}.`); + } + fetches[name] = null; + } + if (typeof arg2 === 'object' && arg2 !== null) { + options = arg2; + } + else if (typeof arg2 !== 'undefined') { + throw new TypeError('\'options\' must be an object.'); + } + } + else { + // decide whether arg1 is fetches or options + // if any output name is present and its value is valid OnnxValue, we consider it fetches + let isFetches = false; + const arg1Keys = Object.getOwnPropertyNames(arg1); + for (const name of this.outputNames) { + if (arg1Keys.indexOf(name) !== -1) { + const v = arg1[name]; + if (v === null || v instanceof _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor) { + isFetches = true; + isFetchesEmpty = false; + fetches[name] = v; + } + } + } + if (isFetches) { + if (typeof arg2 === 'object' && arg2 !== null) { + options = arg2; + } + else if (typeof arg2 !== 'undefined') { + throw new TypeError('\'options\' must be an object.'); + } + } + else { + options = arg1; + } + } + } + else if (typeof arg1 !== 'undefined') { + throw new TypeError('Unexpected argument[1]: must be \'fetches\' or \'options\'.'); + } + // check if all inputs are in feed + for (const name of this.inputNames) { + if (typeof feeds[name] === 'undefined') { + throw new Error(`input '${name}' is missing in 'feeds'.`); + } + } + // if no fetches is specified, we use the full output names list + if (isFetchesEmpty) { + for (const name of this.outputNames) { + fetches[name] = null; + } + } + // feeds, fetches and options are prepared + const results = await this.handler.run(feeds, fetches, options); + const returnValue = {}; + for (const key in results) { + if (Object.hasOwnProperty.call(results, key)) { + returnValue[key] = new _tensor__WEBPACK_IMPORTED_MODULE_1__.Tensor(results[key].type, results[key].data, results[key].dims); + } + } + return returnValue; + } + static async create(arg0, arg1, arg2, arg3) { + // either load from a file or buffer + let filePathOrUint8Array; + let options = {}; + if (typeof arg0 === 'string') { + filePathOrUint8Array = arg0; + if (typeof arg1 === 'object' && arg1 !== null) { + options = arg1; + } + else if (typeof arg1 !== 'undefined') { + throw new TypeError('\'options\' must be an object.'); + } + } + else if (arg0 instanceof Uint8Array) { + filePathOrUint8Array = arg0; + if (typeof arg1 === 'object' && arg1 !== null) { + options = arg1; + } + else if (typeof arg1 !== 'undefined') { + throw new TypeError('\'options\' must be an object.'); + } + } + else if (arg0 instanceof ArrayBuffer || + (typeof SharedArrayBuffer !== 'undefined' && arg0 instanceof SharedArrayBuffer)) { + const buffer = arg0; + let byteOffset = 0; + let byteLength = arg0.byteLength; + if (typeof arg1 === 'object' && arg1 !== null) { + options = arg1; + } + else if (typeof arg1 === 'number') { + byteOffset = arg1; + if (!Number.isSafeInteger(byteOffset)) { + throw new RangeError('\'byteOffset\' must be an integer.'); + } + if (byteOffset < 0 || byteOffset >= buffer.byteLength) { + throw new RangeError(`'byteOffset' is out of range [0, ${buffer.byteLength}).`); + } + byteLength = arg0.byteLength - byteOffset; + if (typeof arg2 === 'number') { + byteLength = arg2; + if (!Number.isSafeInteger(byteLength)) { + throw new RangeError('\'byteLength\' must be an integer.'); + } + if (byteLength <= 0 || byteOffset + byteLength > buffer.byteLength) { + throw new RangeError(`'byteLength' is out of range (0, ${buffer.byteLength - byteOffset}].`); + } + if (typeof arg3 === 'object' && arg3 !== null) { + options = arg3; + } + else if (typeof arg3 !== 'undefined') { + throw new TypeError('\'options\' must be an object.'); + } + } + else if (typeof arg2 !== 'undefined') { + throw new TypeError('\'byteLength\' must be a number.'); + } + } + else if (typeof arg1 !== 'undefined') { + throw new TypeError('\'options\' must be an object.'); + } + filePathOrUint8Array = new Uint8Array(buffer, byteOffset, byteLength); + } + else { + throw new TypeError('Unexpected argument[0]: must be \'path\' or \'buffer\'.'); + } + // get backend hints + const eps = options.executionProviders || []; + const backendHints = eps.map(i => typeof i === 'string' ? i : i.name); + const backend = await (0,_backend_impl__WEBPACK_IMPORTED_MODULE_0__.resolveBackend)(backendHints); + const handler = await backend.createSessionHandler(filePathOrUint8Array, options); + return new InferenceSession(handler); + } + startProfiling() { + this.handler.startProfiling(); + } + endProfiling() { + this.handler.endProfiling(); + } + get inputNames() { + return this.handler.inputNames; + } + get outputNames() { + return this.handler.outputNames; + } +} +//# sourceMappingURL=inference-session-impl.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/inference-session.js": +/*!***********************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/inference-session.js ***! + \***********************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "InferenceSession": () => (/* binding */ InferenceSession) +/* harmony export */ }); +/* harmony import */ var _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./inference-session-impl */ "./node_modules/onnxruntime-common/dist/lib/inference-session-impl.js"); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// eslint-disable-next-line @typescript-eslint/naming-convention +const InferenceSession = _inference_session_impl__WEBPACK_IMPORTED_MODULE_0__.InferenceSession; +//# sourceMappingURL=inference-session.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/onnx-value.js": +/*!****************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/onnx-value.js ***! + \****************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//# sourceMappingURL=onnx-value.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/tensor-impl.js": +/*!*****************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/tensor-impl.js ***! + \*****************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Tensor": () => (/* binding */ Tensor) +/* harmony export */ }); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +const isBigInt64ArrayAvailable = typeof BigInt64Array !== 'undefined' && typeof BigInt64Array.from === 'function'; +const isBigUint64ArrayAvailable = typeof BigUint64Array !== 'undefined' && typeof BigUint64Array.from === 'function'; +// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap. +const NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP = new Map([ + ['float32', Float32Array], + ['uint8', Uint8Array], + ['int8', Int8Array], + ['uint16', Uint16Array], + ['int16', Int16Array], + ['int32', Int32Array], + ['bool', Uint8Array], + ['float64', Float64Array], + ['uint32', Uint32Array], +]); +// a runtime map that maps type string to TypedArray constructor. Should match Tensor.DataTypeMap. +const NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP = new Map([ + [Float32Array, 'float32'], + [Uint8Array, 'uint8'], + [Int8Array, 'int8'], + [Uint16Array, 'uint16'], + [Int16Array, 'int16'], + [Int32Array, 'int32'], + [Float64Array, 'float64'], + [Uint32Array, 'uint32'], +]); +if (isBigInt64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('int64', BigInt64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array, 'int64'); +} +if (isBigUint64ArrayAvailable) { + NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set('uint64', BigUint64Array); + NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array, 'uint64'); +} +/** + * calculate size from dims. + * + * @param dims the dims array. May be an illegal input. + */ +const calculateSize = (dims) => { + let size = 1; + for (let i = 0; i < dims.length; i++) { + const dim = dims[i]; + if (typeof dim !== 'number' || !Number.isSafeInteger(dim)) { + throw new TypeError(`dims[${i}] must be an integer, got: ${dim}`); + } + if (dim < 0) { + throw new RangeError(`dims[${i}] must be a non-negative integer, got: ${dim}`); + } + size *= dim; + } + return size; +}; +class Tensor { + constructor(arg0, arg1, arg2) { + let type; + let data; + let dims; + // check whether arg0 is type or data + if (typeof arg0 === 'string') { + // + // Override: constructor(type, data, ...) + // + type = arg0; + dims = arg2; + if (arg0 === 'string') { + // string tensor + if (!Array.isArray(arg1)) { + throw new TypeError('A string tensor\'s data must be a string array.'); + } + // we don't check whether every element in the array is string; this is too slow. we assume it's correct and + // error will be populated at inference + data = arg1; + } + else { + // numeric tensor + const typedArrayConstructor = NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(arg0); + if (typedArrayConstructor === undefined) { + throw new TypeError(`Unsupported tensor type: ${arg0}.`); + } + if (Array.isArray(arg1)) { + // use 'as any' here because TypeScript's check on type of 'SupportedTypedArrayConstructors.from()' produces + // incorrect results. + // 'typedArrayConstructor' should be one of the typed array prototype objects. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data = typedArrayConstructor.from(arg1); + } + else if (arg1 instanceof typedArrayConstructor) { + data = arg1; + } + else { + throw new TypeError(`A ${type} tensor's data must be type of ${typedArrayConstructor}`); + } + } + } + else { + // + // Override: constructor(data, ...) + // + dims = arg1; + if (Array.isArray(arg0)) { + // only boolean[] and string[] is supported + if (arg0.length === 0) { + throw new TypeError('Tensor type cannot be inferred from an empty array.'); + } + const firstElementType = typeof arg0[0]; + if (firstElementType === 'string') { + type = 'string'; + data = arg0; + } + else if (firstElementType === 'boolean') { + type = 'bool'; + // 'arg0' is of type 'boolean[]'. Uint8Array.from(boolean[]) actually works, but typescript thinks this is + // wrong type. We use 'as any' to make it happy. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + data = Uint8Array.from(arg0); + } + else { + throw new TypeError(`Invalid element type of data array: ${firstElementType}.`); + } + } + else { + // get tensor type from TypedArray + const mappedType = NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(arg0.constructor); + if (mappedType === undefined) { + throw new TypeError(`Unsupported type for tensor data: ${arg0.constructor}.`); + } + type = mappedType; + data = arg0; + } + } + // type and data is processed, now processing dims + if (dims === undefined) { + // assume 1-D tensor if dims omitted + dims = [data.length]; + } + else if (!Array.isArray(dims)) { + throw new TypeError('A tensor\'s dims must be a number array'); + } + // perform check + const size = calculateSize(dims); + if (size !== data.length) { + throw new Error(`Tensor's size(${size}) does not match data length(${data.length}).`); + } + this.dims = dims; + this.type = type; + this.data = data; + this.size = size; + } + // #endregion + /** + * Create a new tensor object from image object + * + * @param buffer - Extracted image buffer data - assuming RGBA format + * @param imageFormat - input image configuration - required configurations height, width, format + * @param tensorFormat - output tensor configuration - Default is RGB format + */ + static bufferToTensor(buffer, options) { + if (buffer === undefined) { + throw new Error('Image buffer must be defined'); + } + if (options.height === undefined || options.width === undefined) { + throw new Error('Image height and width must be defined'); + } + const { height, width } = options; + const norm = options.norm; + let normMean; + let normBias; + if (norm === undefined || norm.mean === undefined) { + normMean = 255; + } + else { + normMean = norm.mean; + } + if (norm === undefined || norm.bias === undefined) { + normBias = 0; + } + else { + normBias = norm.bias; + } + const inputformat = options.bitmapFormat !== undefined ? options.bitmapFormat : 'RGBA'; + // default value is RGBA since imagedata and HTMLImageElement uses it + const outputformat = options.tensorFormat !== undefined ? + (options.tensorFormat !== undefined ? options.tensorFormat : 'RGB') : + 'RGB'; + const offset = height * width; + const float32Data = outputformat === 'RGBA' ? new Float32Array(offset * 4) : new Float32Array(offset * 3); + // Default pointer assignments + let step = 4, rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; + let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1; + // Updating the pointer assignments based on the input image format + if (inputformat === 'RGB') { + step = 3; + rImagePointer = 0; + gImagePointer = 1; + bImagePointer = 2; + aImagePointer = -1; + } + // Updating the pointer assignments based on the output tensor format + if (outputformat === 'RGBA') { + aTensorPointer = offset * 3; + } + else if (outputformat === 'RBG') { + rTensorPointer = 0; + bTensorPointer = offset; + gTensorPointer = offset * 2; + } + else if (outputformat === 'BGR') { + bTensorPointer = 0; + gTensorPointer = offset; + rTensorPointer = offset * 2; + } + for (let i = 0; i < offset; i++, rImagePointer += step, bImagePointer += step, gImagePointer += step, aImagePointer += step) { + float32Data[rTensorPointer++] = (buffer[rImagePointer] + normBias) / normMean; + float32Data[gTensorPointer++] = (buffer[gImagePointer] + normBias) / normMean; + float32Data[bTensorPointer++] = (buffer[bImagePointer] + normBias) / normMean; + if (aTensorPointer !== -1 && aImagePointer !== -1) { + float32Data[aTensorPointer++] = (buffer[aImagePointer] + normBias) / normMean; + } + } + // Float32Array -> ort.Tensor + const outputTensor = outputformat === 'RGBA' ? new Tensor('float32', float32Data, [1, 4, height, width]) : + new Tensor('float32', float32Data, [1, 3, height, width]); + return outputTensor; + } + static async fromImage(image, options) { + // checking the type of image object + const isHTMLImageEle = typeof (HTMLImageElement) !== 'undefined' && image instanceof HTMLImageElement; + const isImageDataEle = typeof (ImageData) !== 'undefined' && image instanceof ImageData; + const isImageBitmap = typeof (ImageBitmap) !== 'undefined' && image instanceof ImageBitmap; + const isURL = typeof (String) !== 'undefined' && (image instanceof String || typeof image === 'string'); + let data; + let tensorConfig = {}; + // filling and checking image configuration options + if (isHTMLImageEle) { + // HTMLImageElement - image object - format is RGBA by default + const canvas = document.createElement('canvas'); + const pixels2DContext = canvas.getContext('2d'); + if (pixels2DContext != null) { + let height = image.naturalHeight; + let width = image.naturalWidth; + if (options !== undefined && options.resizedHeight !== undefined && options.resizedWidth !== undefined) { + height = options.resizedHeight; + width = options.resizedWidth; + } + if (options !== undefined) { + tensorConfig = options; + if (options.tensorFormat !== undefined) { + throw new Error('Image input config format must be RGBA for HTMLImageElement'); + } + else { + tensorConfig.tensorFormat = 'RGBA'; + } + if (options.height !== undefined && options.height !== height) { + throw new Error('Image input config height doesn\'t match HTMLImageElement height'); + } + else { + tensorConfig.height = height; + } + if (options.width !== undefined && options.width !== width) { + throw new Error('Image input config width doesn\'t match HTMLImageElement width'); + } + else { + tensorConfig.width = width; + } + } + else { + tensorConfig.tensorFormat = 'RGBA'; + tensorConfig.height = height; + tensorConfig.width = width; + } + canvas.width = width; + canvas.height = height; + pixels2DContext.drawImage(image, 0, 0, width, height); + data = pixels2DContext.getImageData(0, 0, width, height).data; + } + else { + throw new Error('Can not access image data'); + } + } + else if (isImageDataEle) { + // ImageData - image object - format is RGBA by default + const format = 'RGBA'; + let height; + let width; + if (options !== undefined && options.resizedWidth !== undefined && options.resizedHeight !== undefined) { + height = options.resizedHeight; + width = options.resizedWidth; + } + else { + height = image.height; + width = image.width; + } + if (options !== undefined) { + tensorConfig = options; + if (options.bitmapFormat !== undefined && options.bitmapFormat !== format) { + throw new Error('Image input config format must be RGBA for ImageData'); + } + else { + tensorConfig.bitmapFormat = 'RGBA'; + } + } + else { + tensorConfig.bitmapFormat = 'RGBA'; + } + tensorConfig.height = height; + tensorConfig.width = width; + if (options !== undefined) { + const tempCanvas = document.createElement('canvas'); + tempCanvas.width = width; + tempCanvas.height = height; + const pixels2DContext = tempCanvas.getContext('2d'); + if (pixels2DContext != null) { + pixels2DContext.putImageData(image, 0, 0); + data = pixels2DContext.getImageData(0, 0, width, height).data; + } + else { + throw new Error('Can not access image data'); + } + } + else { + data = image.data; + } + } + else if (isImageBitmap) { + // ImageBitmap - image object - format must be provided by user + if (options === undefined) { + throw new Error('Please provide image config with format for Imagebitmap'); + } + if (options.bitmapFormat !== undefined) { + throw new Error('Image input config format must be defined for ImageBitmap'); + } + const pixels2DContext = document.createElement('canvas').getContext('2d'); + if (pixels2DContext != null) { + const height = image.height; + const width = image.width; + pixels2DContext.drawImage(image, 0, 0, width, height); + data = pixels2DContext.getImageData(0, 0, width, height).data; + if (options !== undefined) { + // using square brackets to avoid TS error - type 'never' + if (options.height !== undefined && options.height !== height) { + throw new Error('Image input config height doesn\'t match ImageBitmap height'); + } + else { + tensorConfig.height = height; + } + // using square brackets to avoid TS error - type 'never' + if (options.width !== undefined && options.width !== width) { + throw new Error('Image input config width doesn\'t match ImageBitmap width'); + } + else { + tensorConfig.width = width; + } + } + else { + tensorConfig.height = height; + tensorConfig.width = width; + } + return Tensor.bufferToTensor(data, tensorConfig); + } + else { + throw new Error('Can not access image data'); + } + } + else if (isURL) { + return new Promise((resolve, reject) => { + const canvas = document.createElement('canvas'); + const context = canvas.getContext('2d'); + if (!image || !context) { + return reject(); + } + const newImage = new Image(); + newImage.crossOrigin = 'Anonymous'; + newImage.src = image; + newImage.onload = () => { + canvas.width = newImage.width; + canvas.height = newImage.height; + context.drawImage(newImage, 0, 0, canvas.width, canvas.height); + const img = context.getImageData(0, 0, canvas.width, canvas.height); + if (options !== undefined) { + // using square brackets to avoid TS error - type 'never' + if (options.height !== undefined && options.height !== canvas.height) { + throw new Error('Image input config height doesn\'t match ImageBitmap height'); + } + else { + tensorConfig.height = canvas.height; + } + // using square brackets to avoid TS error - type 'never' + if (options.width !== undefined && options.width !== canvas.width) { + throw new Error('Image input config width doesn\'t match ImageBitmap width'); + } + else { + tensorConfig.width = canvas.width; + } + } + else { + tensorConfig.height = canvas.height; + tensorConfig.width = canvas.width; + } + resolve(Tensor.bufferToTensor(img.data, tensorConfig)); + }; + }); + } + else { + throw new Error('Input data provided is not supported - aborted tensor creation'); + } + if (data !== undefined) { + return Tensor.bufferToTensor(data, tensorConfig); + } + else { + throw new Error('Input data provided is not supported - aborted tensor creation'); + } + } + toImageData(options) { + var _a, _b; + const pixels2DContext = document.createElement('canvas').getContext('2d'); + let image; + if (pixels2DContext != null) { + // Default values for height and width & format + const width = this.dims[3]; + const height = this.dims[2]; + const channels = this.dims[1]; + const inputformat = options !== undefined ? (options.format !== undefined ? options.format : 'RGB') : 'RGB'; + const normMean = options !== undefined ? (((_a = options.norm) === null || _a === void 0 ? void 0 : _a.mean) !== undefined ? options.norm.mean : 255) : 255; + const normBias = options !== undefined ? (((_b = options.norm) === null || _b === void 0 ? void 0 : _b.bias) !== undefined ? options.norm.bias : 0) : 0; + const offset = height * width; + if (options !== undefined) { + if (options.height !== undefined && options.height !== height) { + throw new Error('Image output config height doesn\'t match tensor height'); + } + if (options.width !== undefined && options.width !== width) { + throw new Error('Image output config width doesn\'t match tensor width'); + } + if (options.format !== undefined && (channels === 4 && options.format !== 'RGBA') || + (channels === 3 && (options.format !== 'RGB' && options.format !== 'BGR'))) { + throw new Error('Tensor format doesn\'t match input tensor dims'); + } + } + // Default pointer assignments + const step = 4; + let rImagePointer = 0, gImagePointer = 1, bImagePointer = 2, aImagePointer = 3; + let rTensorPointer = 0, gTensorPointer = offset, bTensorPointer = offset * 2, aTensorPointer = -1; + // Updating the pointer assignments based on the input image format + if (inputformat === 'RGBA') { + rTensorPointer = 0; + gTensorPointer = offset; + bTensorPointer = offset * 2; + aTensorPointer = offset * 3; + } + else if (inputformat === 'RGB') { + rTensorPointer = 0; + gTensorPointer = offset; + bTensorPointer = offset * 2; + } + else if (inputformat === 'RBG') { + rTensorPointer = 0; + bTensorPointer = offset; + gTensorPointer = offset * 2; + } + image = pixels2DContext.createImageData(width, height); + for (let i = 0; i < height * width; rImagePointer += step, gImagePointer += step, bImagePointer += step, aImagePointer += step, i++) { + image.data[rImagePointer] = (this.data[rTensorPointer++] - normBias) * normMean; // R value + image.data[gImagePointer] = (this.data[gTensorPointer++] - normBias) * normMean; // G value + image.data[bImagePointer] = (this.data[bTensorPointer++] - normBias) * normMean; // B value + image.data[aImagePointer] = + aTensorPointer === -1 ? 255 : (this.data[aTensorPointer++] - normBias) * normMean; // A value + } + } + else { + throw new Error('Can not access image data'); + } + return image; + } + // #endregion + // #region tensor utilities + reshape(dims) { + return new Tensor(this.type, this.data, dims); + } +} +//# sourceMappingURL=tensor-impl.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-common/dist/lib/tensor.js": +/*!************************************************************!*\ + !*** ./node_modules/onnxruntime-common/dist/lib/tensor.js ***! + \************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "Tensor": () => (/* binding */ Tensor) +/* harmony export */ }); +/* harmony import */ var _tensor_impl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./tensor-impl */ "./node_modules/onnxruntime-common/dist/lib/tensor-impl.js"); +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// eslint-disable-next-line @typescript-eslint/naming-convention +const Tensor = _tensor_impl__WEBPACK_IMPORTED_MODULE_0__.Tensor; +//# sourceMappingURL=tensor.js.map + +/***/ }), + +/***/ "./node_modules/onnxruntime-web/dist/ort-web.min.js": +/*!**********************************************************!*\ + !*** ./node_modules/onnxruntime-web/dist/ort-web.min.js ***! + \**********************************************************/ +/***/ ((module, __unused_webpack_exports, __webpack_require__) => { + +/* provided dependency */ var process = __webpack_require__(/*! process/browser.js */ "./node_modules/process/browser.js"); +/*! +* ONNX Runtime Web v1.14.0 +* Copyright (c) Microsoft Corporation. All rights reserved. +* Licensed under the MIT License. +*/ +!function(t,e){if(true)module.exports=e(__webpack_require__(/*! onnxruntime-common */ "./node_modules/onnxruntime-common/dist/lib/index.js"));else { var r, n; }}(self,(__WEBPACK_EXTERNAL_MODULE__1670__=>(()=>{var __webpack_modules__={3474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return $.buffer!=C&&H($.buffer),F}function r(){return $.buffer!=C&&H($.buffer),N}function i(){return $.buffer!=C&&H($.buffer),L}function o(){return $.buffer!=C&&H($.buffer),R}function a(){return $.buffer!=C&&H($.buffer),j}var s,u,c;t=t||{},s||(s=void 0!==t?t:{}),s.ready=new Promise((function(t,e){u=t,c=e}));var l,p,f,d,h,g,b=Object.assign({},s),m="./this.program",y=(t,e)=>{throw e},_="object"==typeof window,v="function"==typeof importScripts,w="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,x=s.ENVIRONMENT_IS_PTHREAD||!1,T="";function S(t){return s.locateFile?s.locateFile(t,T):T+t}if(w){let e;T=v?n(908).dirname(T)+"/":"//",g=()=>{h||(d=n(1384),h=n(908))},l=function(t,e){return g(),t=h.normalize(t),d.readFileSync(t,e?void 0:"utf8")},f=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),p=(t,e,n)=>{g(),t=h.normalize(t),d.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(J())throw process.exitCode=t,e;e instanceof ut||P("exiting due to exception: "+e),process.exit(t)},s.inspect=function(){return"[Emscripten Module object]"};try{e=n(9925)}catch(t){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),t}n.g.Worker=e.Worker}else(_||v)&&(v?T=self.location.href:"undefined"!=typeof document&&document.currentScript&&(T=document.currentScript.src),_scriptDir&&(T=_scriptDir),T=0!==T.indexOf("blob:")?T.substr(0,T.replace(/[?#].*/,"").lastIndexOf("/")+1):"",w||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},v&&(f=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),p=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));w&&"undefined"==typeof performance&&(n.g.performance=n(6953).performance);var O=console.log.bind(console),A=console.warn.bind(console);w&&(g(),O=t=>d.writeSync(1,t+"\n"),A=t=>d.writeSync(2,t+"\n"));var E,I=s.print||O,P=s.printErr||A;Object.assign(s,b),b=null,s.thisProgram&&(m=s.thisProgram),s.quit&&(y=s.quit),s.wasmBinary&&(E=s.wasmBinary);var D=s.noExitRuntime||!1;"object"!=typeof WebAssembly&&it("no native wasm support detected");var $,k,C,F,N,L,R,j,M=!1,U="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function V(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(i=224==(240&i)?(15&i)<<12|o<<6|a:(7&i)<<18|o<<12|a<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function B(t,e){return(t>>>=0)?V(r(),t,e):""}function z(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var o=0;o=a&&(a=65536+((1023&a)<<10)|1023&t.charCodeAt(++o)),127>=a){if(n>=r)break;e[n++>>>0]=a}else{if(2047>=a){if(n+1>=r)break;e[n++>>>0]=192|a>>6}else{if(65535>=a){if(n+2>=r)break;e[n++>>>0]=224|a>>12}else{if(n+3>=r)break;e[n++>>>0]=240|a>>18,e[n++>>>0]=128|a>>12&63}e[n++>>>0]=128|a>>6&63}e[n++>>>0]=128|63&a}}return e[n>>>0]=0,n-i}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function H(t){C=t,s.HEAP8=F=new Int8Array(t),s.HEAP16=new Int16Array(t),s.HEAP32=L=new Int32Array(t),s.HEAPU8=N=new Uint8Array(t),s.HEAPU16=new Uint16Array(t),s.HEAPU32=R=new Uint32Array(t),s.HEAPF32=new Float32Array(t),s.HEAPF64=j=new Float64Array(t)}x&&(C=s.buffer);var W=s.INITIAL_MEMORY||16777216;if(x)$=s.wasmMemory,C=s.buffer;else if(s.wasmMemory)$=s.wasmMemory;else if(!(($=new WebAssembly.Memory({initial:W/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw P("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),w&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");$&&(C=$.buffer),W=C.byteLength,H(C);var q,X=[],Y=[],K=[],Z=[];function J(){return D||!1}function Q(){var t=s.preRun.shift();X.unshift(t)}var tt,et=0,nt=null,rt=null;function it(t){throw x?postMessage({cmd:"onAbort",arg:t}):s.onAbort&&s.onAbort(t),P(t="Aborted("+t+")"),M=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),c(t),t}function ot(){return tt.startsWith("data:application/octet-stream;base64,")}function at(){var t=tt;try{if(t==tt&&E)return new Uint8Array(E);if(f)return f(t);throw"both async and sync fetching of the wasm failed"}catch(t){it(t)}}tt="ort-wasm-threaded.wasm",ot()||(tt=S(tt));var st={};function ut(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function ct(t){(t=dt.Vb[t])||it(),dt.mc(t)}function lt(t){var e=dt.Cc();if(!e)return 6;dt.ac.push(e),dt.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function pt(t){if(x)return qt(1,1,t);J()||(dt.oc(),s.onExit&&s.onExit(t),M=!0),y(t,new ut(t))}function ft(t,e){if(!e&&x)throw bt(t),"unwind";J()||x||(me(),ht(K),be(0),re[1].length&&ie(1,10),re[2].length&&ie(2,10),dt.oc()),pt(t)}var dt={Yb:[],ac:[],qc:[],Vb:{},fc:function(){x&&dt.Ec()},Pc:function(){},Ec:function(){dt.receiveObjectTransfer=dt.Gc,dt.threadInitTLS=dt.pc,dt.setExitStatus=dt.nc,D=!1},nc:function(){},oc:function(){for(var t of Object.values(dt.Vb))dt.mc(t);for(t of dt.Yb)t.terminate();dt.Yb=[]},mc:function(t){var e=t.Ub;delete dt.Vb[e],dt.Yb.push(t),dt.ac.splice(dt.ac.indexOf(t),1),t.Ub=0,xe(e)},Gc:function(){},pc:function(){dt.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(dt.Bc=t.Ub),n.targetThread&&n.targetThread!=de()){var i=dt.Vb[n.Qc];i?i.postMessage(n,n.transferList):P('Internal error! Worker sent a message "'+r+'" to target pthread '+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?Vt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?ct(n.thread):"killThread"===r?(n=n.thread,r=dt.Vb[n],delete dt.Vb[n],r.terminate(),xe(n),dt.ac.splice(dt.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?dt.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?I("Thread "+n.threadId+": "+n.text):"printErr"===r?P("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?s.onAbort&&s.onAbort(n.arg):r&&P("worker sent an unknown command "+r);dt.Bc=void 0},t.onerror=t=>{throw P("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},w&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:s.mainScriptUrlOrBlob||_scriptDir,wasmMemory:$,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");dt.Yb.push(new Worker(t))},Cc:function(){return 0==dt.Yb.length&&(dt.yc(),dt.Fc(dt.Yb[0])),dt.Yb.pop()}};function ht(t){for(;0>2>>>0];t=i()[t+48>>2>>>0],Oe(e,e-t),Ee(e)};var mt=[];function yt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=q.get(t)),e}s.invokeEntryPoint=function(t,e){t=yt(t)(e),J()?dt.nc(t):Te(t)};var _t,vt,wt=[],xt=0,Tt=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){o()[this.Sb+4>>2>>>0]=t},this.bc=function(){return o()[this.Sb+4>>2>>>0]},this.wc=function(t){o()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return o()[this.Sb+8>>2>>>0]},this.rc=function(){i()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(i(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(i(),this.Sb>>2,1)},this.cc=function(t){o()[this.Sb+16>>2>>>0]=t},this.tc=function(){return o()[this.Sb+16>>2>>>0]},this.vc=function(){if(De(this.bc()))return o()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Ot(t){return ge(new St(t).Sb)}function At(t,e,n,r){return x?qt(3,1,t,e,n,r):Et(t,e,n,r)}function Et(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return P("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var i=[];return x&&0===i.length?At(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:i},x?(t.Oc="spawnThread",postMessage(t,i),0):lt(t))}function It(t,e,n){return x?qt(4,1,t,e,n):0}function Pt(t,e){if(x)return qt(5,1,t,e)}function Dt(t,e){if(x)return qt(6,1,t,e)}function $t(t,e,n){if(x)return qt(7,1,t,e,n)}function kt(t,e,n){return x?qt(8,1,t,e,n):0}function Ct(t,e){if(x)return qt(9,1,t,e)}function Ft(t,e,n){if(x)return qt(10,1,t,e,n)}function Nt(t,e,n,r){if(x)return qt(11,1,t,e,n,r)}function Lt(t,e,n,r){if(x)return qt(12,1,t,e,n,r)}function Rt(t,e,n,r){if(x)return qt(13,1,t,e,n,r)}function jt(t){if(x)return qt(14,1,t)}function Mt(t,e){if(x)return qt(15,1,t,e)}function Ut(t,e,n){if(x)return qt(16,1,t,e,n)}function Vt(t){Atomics.store(i(),t>>2,1),de()&&we(t),Atomics.compareExchange(i(),t>>2,1,0)}function Bt(t){return o()[t>>>2]+4294967296*i()[t+4>>>2]}function zt(t,e,n,r,i,o){return x?qt(17,1,t,e,n,r,i,o):-52}function Gt(t,e,n,r,i,o){if(x)return qt(18,1,t,e,n,r,i,o)}function Ht(t){var n=G(t)+1,r=he(n);return r&&z(t,e(),r,n),r}function Wt(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}if(x)return qt(19,1,t,e,n);var a=(new Date).getFullYear(),s=new Date(a,0,1),u=new Date(a,6,1);a=s.getTimezoneOffset();var c=u.getTimezoneOffset(),l=Math.max(a,c);i()[t>>2>>>0]=60*l,i()[e>>2>>>0]=Number(a!=c),t=r(s),e=r(u),t=Ht(t),e=Ht(e),c>2>>>0]=t,o()[n+4>>2>>>0]=e):(o()[n>>2>>>0]=e,o()[n+4>>2>>>0]=t)}function qt(t,e){var n=arguments.length-2,r=arguments;return gt((()=>{for(var i=Ie(8*n),o=i>>3,s=0;s>>0]=u}return ve(t,n,i,e)}))}s.executeNotifiedProxyingQueue=Vt,vt=w?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:x?()=>performance.now()-s.__performance_now_clock_drift:()=>performance.now();var Xt,Yt=[],Kt={};function Zt(){if(!Xt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Kt)void 0===Kt[t]?delete e[t]:e[t]=Kt[t];var n=[];for(t in e)n.push(t+"="+e[t]);Xt=n}return Xt}function Jt(t,n){if(x)return qt(20,1,t,n);var r=0;return Zt().forEach((function(i,a){var s=n+r;for(a=o()[t+4*a>>2>>>0]=s,s=0;s>0>>>0]=i.charCodeAt(s);e()[a>>0>>>0]=0,r+=i.length+1})),0}function Qt(t,e){if(x)return qt(21,1,t,e);var n=Zt();o()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),o()[e>>2>>>0]=r,0}function te(t){return x?qt(22,1,t):52}function ee(t,e,n,r){return x?qt(23,1,t,e,n,r):52}function ne(t,e,n,r,i){return x?qt(24,1,t,e,n,r,i):70}var re=[null,[],[]];function ie(t,e){var n=re[t];0===e||10===e?((1===t?I:P)(V(n,0)),n.length=0):n.push(e)}function oe(t,e,n,i){if(x)return qt(25,1,t,e,n,i);for(var a=0,s=0;s>2>>>0],c=o()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);a+=c}return o()[i>>2>>>0]=a,0}var ae=0;function se(t){return 0==t%4&&(0!=t%100||0==t%400)}var ue=[31,29,31,30,31,30,31,31,30,31,30,31],ce=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,o){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=c(new Date(t.getFullYear(),0,4)),n=c(n),0>=u(e,t)?0>=u(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var p=i()[o+40>>2>>>0];for(var f in o={Lc:i()[o>>2>>>0],Kc:i()[o+4>>2>>>0],dc:i()[o+8>>2>>>0],jc:i()[o+12>>2>>>0],ec:i()[o+16>>2>>>0],Xb:i()[o+20>>2>>>0],Tb:i()[o+24>>2>>>0],Wb:i()[o+28>>2>>>0],Rc:i()[o+32>>2>>>0],Jc:i()[o+36>>2>>>0],Mc:p?B(p):""},r=B(r),p={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(f,"g"),p[f]);var d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),h="January February March April May June July August September October November December".split(" ");for(f in p={"%a":function(t){return d[t.Tb].substring(0,3)},"%A":function(t){return d[t.Tb]},"%b":function(t){return h[t.ec].substring(0,3)},"%B":function(t){return h[t.ec]},"%C":function(t){return s((t.Xb+1900)/100|0,2)},"%d":function(t){return s(t.jc,2)},"%e":function(t){return a(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return s(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return s(t.Lc,2)},"%t":function(){return"\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return s(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&se(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&se(t.Xb%400-1))&&e++}return s(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return s(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\0\0"),p)r.includes(f)&&(r=r.replace(new RegExp(f,"g"),p[f](o)));return f=function(t){var e=Array(G(t)+1);return z(t,e,0,e.length),e}(r=r.replace(/\0\0/g,"%")),f.length>n?0:(function(t,n){e().set(t,n>>>0)}(f,t),f.length-1)}dt.fc();var pe=[null,pt,bt,At,It,Pt,Dt,$t,kt,Ct,Ft,Nt,Lt,Rt,jt,Mt,Ut,zt,Gt,Wt,Jt,Qt,te,ee,ne,oe],fe={b:function(t){return he(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),xt--),t.ic(!1),wt.push(t),t.sc(),t.vc()},ma:function(t){throw P("Unexpected exception thrown, this is not properly supported - aborting"),M=!0,t},x:function(){Se(0);var t=wt.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&&yt(e)(t.Zb),Ot(t.Zb)}Tt=0},e:function(){var t=Tt;if(!t)return ae=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return ae=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;iVt(r)));else if(x)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=dt.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Bt(t)),i()[e>>2>>>0]=t.getUTCSeconds(),i()[e+4>>2>>>0]=t.getUTCMinutes(),i()[e+8>>2>>>0]=t.getUTCHours(),i()[e+12>>2>>>0]=t.getUTCDate(),i()[e+16>>2>>>0]=t.getUTCMonth(),i()[e+20>>2>>>0]=t.getUTCFullYear()-1900,i()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,i()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Bt(t)),i()[e>>2>>>0]=t.getSeconds(),i()[e+4>>2>>>0]=t.getMinutes(),i()[e+8>>2>>>0]=t.getHours(),i()[e+12>>2>>>0]=t.getDate(),i()[e+16>>2>>>0]=t.getMonth(),i()[e+20>>2>>>0]=t.getFullYear()-1900,i()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;i()[e+28>>2>>>0]=r,i()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),i()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(i()[t+20>>2>>>0]+1900,i()[t+16>>2>>>0],i()[t+12>>2>>>0],i()[t+8>>2>>>0],i()[t+4>>2>>>0],i()[t>>2>>>0],0),n=i()[t+32>>2>>>0],r=e.getTimezoneOffset(),o=new Date(e.getFullYear(),0,1),a=new Date(e.getFullYear(),6,1).getTimezoneOffset(),s=o.getTimezoneOffset(),u=Math.min(s,a);return 0>n?i()[t+32>>2>>>0]=Number(a!=s&&u==r):0>2>>>0]=e.getDay(),n=(e.getTime()-o.getTime())/864e5|0,i()[t+28>>2>>>0]=n,i()[t>>2>>>0]=e.getSeconds(),i()[t+4>>2>>>0]=e.getMinutes(),i()[t+8>>2>>>0]=e.getHours(),i()[t+12>>2>>>0]=e.getDate(),i()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:zt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Wt(e,n,r))},y:function(){it("")},U:function(){if(!w&&!v){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";_t||(_t={}),_t[t]||(_t[t]=1,w&&(t="warning: "+t),P(t))}},ra:function(){return 4294901760},B:vt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return w?n(3993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Yt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?st[-t-1]:pe[t]).apply(null,Yt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var i=e*(1+.2/n);i=Math.min(i,t+100663296);var o=Math;i=Math.max(t,i),o=o.min.call(o,4294901760,i+(65536-i%65536)%65536);t:{try{$.grow(o-C.byteLength+65535>>>16),H($.buffer);var a=1;break t}catch(t){}a=void 0}if(a)return!0}return!1},Na:function(){throw"unwind"},Ga:Jt,Ha:Qt,J:ft,I:te,S:ee,ga:ne,R:oe,d:function(){return ae},na:function t(r,i){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(w)try{var e=n(Object(function(){var t=new Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>it("randomDevice")}());for(var o=0;o>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ae();try{return yt(t)()}catch(t){if(Ee(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ae();try{return yt(t)(e)}catch(t){if(Ee(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ae();try{return yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var i=Ae();try{return yt(t)(e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,i){var o=Ae();try{return yt(t)(e,n,r,i)}catch(t){if(Ee(o),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,i,o){var a=Ae();try{return yt(t)(e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,i,o){var a=Ae();try{return yt(t)(e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,i,o,a){var s=Ae();try{return yt(t)(e,n,r,i,o,a)}catch(t){if(Ee(s),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,i,o,a,s){var u=Ae();try{return yt(t)(e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Ae();try{return yt(t)(e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(Ee(f),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,i,o,a,s){var u=Ae();try{return Me(t,e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,i,o,a){var s=Ae();try{return ke(t,e,n,r,i,o,a)}catch(t){if(Ee(s),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,i){var o=Ae();try{return Ue(t,e,n,r,i)}catch(t){if(Ee(o),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var i=Ae();try{return Re(t,e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ae();try{return $e(t)}catch(t){if(Ee(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ae();try{return je(t,e)}catch(t){if(Ee(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ae();try{return Ce(t,e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ae();try{yt(t)()}catch(t){if(Ee(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ae();try{yt(t)(e)}catch(t){if(Ee(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ae();try{yt(t)(e,n)}catch(t){if(Ee(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var i=Ae();try{yt(t)(e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var i=Ae();try{yt(t)(e,n,r)}catch(t){if(Ee(i),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,i){var o=Ae();try{yt(t)(e,n,r,i)}catch(t){if(Ee(o),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,i,o){var a=Ae();try{yt(t)(e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,i,o,a){var s=Ae();try{yt(t)(e,n,r,i,o,a)}catch(t){if(Ee(s),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,i,o,a,s){var u=Ae();try{yt(t)(e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,i,o,a,s,u){var c=Ae();try{yt(t)(e,n,r,i,o,a,s,u)}catch(t){if(Ee(c),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,i,o,a,s,u,c,l){var p=Ae();try{yt(t)(e,n,r,i,o,a,s,u,c,l)}catch(t){if(Ee(p),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,i,o,a,s,u,c,l,p,f,d,h,g){var b=Ae();try{yt(t)(e,n,r,i,o,a,s,u,c,l,p,f,d,h,g)}catch(t){if(Ee(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,i,o,a,s){var u=Ae();try{Fe(t,e,n,r,i,o,a,s)}catch(t){if(Ee(u),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Ae();try{Le(t,e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(Ee(f),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,i,o){var a=Ae();try{Ne(t,e,n,r,i,o)}catch(t){if(Ee(a),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:$||s.wasmMemory,G:function(t){ae=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){s.asm=t.exports,dt.qc.push(s.asm.sb),q=s.asm.ub,Y.unshift(s.asm.Va),k=e,x||(et--,s.monitorRunDependencies&&s.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!E&&(_||v)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+tt+"'";return t.arrayBuffer()})).catch((function(){return at()}));if(p)return new Promise((function(t,e){p(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return at()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){P("failed to asynchronously prepare wasm: "+t),it(t)}))}var r={a:fe};if(x||(et++,s.monitorRunDependencies&&s.monitorRunDependencies(et)),s.instantiateWasm)try{return s.instantiateWasm(r,t)}catch(t){return P("Module.instantiateWasm callback failed with error: "+t),!1}(E||"function"!=typeof WebAssembly.instantiateStreaming||ot()||tt.startsWith("file://")||w||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return P("wasm streaming compile failed: "+t),P("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(c)}(),s.___wasm_call_ctors=function(){return(s.___wasm_call_ctors=s.asm.Va).apply(null,arguments)},s._OrtInit=function(){return(s._OrtInit=s.asm.Wa).apply(null,arguments)},s._OrtCreateSessionOptions=function(){return(s._OrtCreateSessionOptions=s.asm.Xa).apply(null,arguments)},s._OrtAppendExecutionProvider=function(){return(s._OrtAppendExecutionProvider=s.asm.Ya).apply(null,arguments)},s._OrtAddSessionConfigEntry=function(){return(s._OrtAddSessionConfigEntry=s.asm.Za).apply(null,arguments)},s._OrtReleaseSessionOptions=function(){return(s._OrtReleaseSessionOptions=s.asm._a).apply(null,arguments)},s._OrtCreateSession=function(){return(s._OrtCreateSession=s.asm.$a).apply(null,arguments)},s._OrtReleaseSession=function(){return(s._OrtReleaseSession=s.asm.ab).apply(null,arguments)},s._OrtGetInputCount=function(){return(s._OrtGetInputCount=s.asm.bb).apply(null,arguments)},s._OrtGetOutputCount=function(){return(s._OrtGetOutputCount=s.asm.cb).apply(null,arguments)},s._OrtGetInputName=function(){return(s._OrtGetInputName=s.asm.db).apply(null,arguments)},s._OrtGetOutputName=function(){return(s._OrtGetOutputName=s.asm.eb).apply(null,arguments)},s._OrtFree=function(){return(s._OrtFree=s.asm.fb).apply(null,arguments)},s._OrtCreateTensor=function(){return(s._OrtCreateTensor=s.asm.gb).apply(null,arguments)},s._OrtGetTensorData=function(){return(s._OrtGetTensorData=s.asm.hb).apply(null,arguments)},s._OrtReleaseTensor=function(){return(s._OrtReleaseTensor=s.asm.ib).apply(null,arguments)},s._OrtCreateRunOptions=function(){return(s._OrtCreateRunOptions=s.asm.jb).apply(null,arguments)},s._OrtAddRunConfigEntry=function(){return(s._OrtAddRunConfigEntry=s.asm.kb).apply(null,arguments)},s._OrtReleaseRunOptions=function(){return(s._OrtReleaseRunOptions=s.asm.lb).apply(null,arguments)},s._OrtRun=function(){return(s._OrtRun=s.asm.mb).apply(null,arguments)},s._OrtEndProfiling=function(){return(s._OrtEndProfiling=s.asm.nb).apply(null,arguments)};var de=s._pthread_self=function(){return(de=s._pthread_self=s.asm.ob).apply(null,arguments)},he=s._malloc=function(){return(he=s._malloc=s.asm.pb).apply(null,arguments)},ge=s._free=function(){return(ge=s._free=s.asm.qb).apply(null,arguments)},be=s._fflush=function(){return(be=s._fflush=s.asm.rb).apply(null,arguments)};s.__emscripten_tls_init=function(){return(s.__emscripten_tls_init=s.asm.sb).apply(null,arguments)};var me=s.___funcs_on_exit=function(){return(me=s.___funcs_on_exit=s.asm.tb).apply(null,arguments)},ye=s.__emscripten_thread_init=function(){return(ye=s.__emscripten_thread_init=s.asm.vb).apply(null,arguments)};s.__emscripten_thread_crashed=function(){return(s.__emscripten_thread_crashed=s.asm.wb).apply(null,arguments)};var _e,ve=s._emscripten_run_in_main_runtime_thread_js=function(){return(ve=s._emscripten_run_in_main_runtime_thread_js=s.asm.xb).apply(null,arguments)},we=s.__emscripten_proxy_execute_task_queue=function(){return(we=s.__emscripten_proxy_execute_task_queue=s.asm.yb).apply(null,arguments)},xe=s.__emscripten_thread_free_data=function(){return(xe=s.__emscripten_thread_free_data=s.asm.zb).apply(null,arguments)},Te=s.__emscripten_thread_exit=function(){return(Te=s.__emscripten_thread_exit=s.asm.Ab).apply(null,arguments)},Se=s._setThrew=function(){return(Se=s._setThrew=s.asm.Bb).apply(null,arguments)},Oe=s._emscripten_stack_set_limits=function(){return(Oe=s._emscripten_stack_set_limits=s.asm.Cb).apply(null,arguments)},Ae=s.stackSave=function(){return(Ae=s.stackSave=s.asm.Db).apply(null,arguments)},Ee=s.stackRestore=function(){return(Ee=s.stackRestore=s.asm.Eb).apply(null,arguments)},Ie=s.stackAlloc=function(){return(Ie=s.stackAlloc=s.asm.Fb).apply(null,arguments)},Pe=s.___cxa_can_catch=function(){return(Pe=s.___cxa_can_catch=s.asm.Gb).apply(null,arguments)},De=s.___cxa_is_pointer_type=function(){return(De=s.___cxa_is_pointer_type=s.asm.Hb).apply(null,arguments)},$e=s.dynCall_j=function(){return($e=s.dynCall_j=s.asm.Ib).apply(null,arguments)},ke=s.dynCall_iiiiij=function(){return(ke=s.dynCall_iiiiij=s.asm.Jb).apply(null,arguments)},Ce=s.dynCall_jii=function(){return(Ce=s.dynCall_jii=s.asm.Kb).apply(null,arguments)},Fe=s.dynCall_viiiiij=function(){return(Fe=s.dynCall_viiiiij=s.asm.Lb).apply(null,arguments)},Ne=s.dynCall_vjji=function(){return(Ne=s.dynCall_vjji=s.asm.Mb).apply(null,arguments)},Le=s.dynCall_viiijjjii=function(){return(Le=s.dynCall_viiijjjii=s.asm.Nb).apply(null,arguments)},Re=s.dynCall_iij=function(){return(Re=s.dynCall_iij=s.asm.Ob).apply(null,arguments)},je=s.dynCall_ji=function(){return(je=s.dynCall_ji=s.asm.Pb).apply(null,arguments)},Me=s.dynCall_iiiiiij=function(){return(Me=s.dynCall_iiiiiij=s.asm.Qb).apply(null,arguments)},Ue=s.dynCall_iiij=function(){return(Ue=s.dynCall_iiij=s.asm.Rb).apply(null,arguments)};function Ve(){function t(){if(!_e&&(_e=!0,s.calledRun=!0,!M)&&(x||ht(Y),u(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),!x)){if(s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;){var t=s.postRun.shift();Z.unshift(t)}ht(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,i;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,i=e}));var o,a,s,u,c,l,p=Object.assign({},e),f="./this.program",d=(t,e)=>{throw e},h="object"==typeof window,g="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=g?n(908).dirname(m)+"/":"//",l=()=>{c||(u=n(1384),c=n(908))},o=function(t,e){return l(),t=c.normalize(t),u.readFileSync(t,e?void 0:"utf8")},s=t=>((t=o(t,!0)).buffer||(t=new Uint8Array(t)),t),a=(t,e,n)=>{l(),t=c.normalize(t),u.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(w||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},g&&(s=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),a=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var y,_=e.print||console.log.bind(console),v=e.printErr||console.warn.bind(console);Object.assign(e,p),p=null,e.thisProgram&&(f=e.thisProgram),e.quit&&(d=e.quit),e.wasmBinary&&(y=e.wasmBinary);var w=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&W("no native wasm support detected");var x,T,S,O,A,E,I=!1,P="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function D(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(i=224==(240&i)?(15&i)<<12|o<<6|a:(7&i)<<18|o<<12|a<<6|63&t[e++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r}function $(t,e){return(t>>>=0)?D(O,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var o=0;o=a&&(a=65536+((1023&a)<<10)|1023&t.charCodeAt(++o)),127>=a){if(n>=r)break;e[n++>>>0]=a}else{if(2047>=a){if(n+1>=r)break;e[n++>>>0]=192|a>>6}else{if(65535>=a){if(n+2>=r)break;e[n++>>>0]=224|a>>12}else{if(n+3>=r)break;e[n++>>>0]=240|a>>18,e[n++>>>0]=128|a>>12&63}e[n++>>>0]=128|a>>6&63}e[n++>>>0]=128|63&a}}return e[n>>>0]=0,n-i}function C(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function F(){var t=x.buffer;T=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=A=new Int32Array(t),e.HEAPU8=O=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=E=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var N,L=[],R=[],j=[],M=[],U=0;function V(){var t=e.preRun.shift();L.unshift(t)}var B,z=0,G=null,H=null;function W(t){throw e.onAbort&&e.onAbort(t),v(t="Aborted("+t+")"),I=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),i(t),t}function q(){return B.startsWith("data:application/octet-stream;base64,")}if(B="ort-wasm.wasm",!q()){var X=B;B=e.locateFile?e.locateFile(X,m):m+X}function Y(){var t=B;try{if(t==B&&y)return new Uint8Array(y);if(s)return s(t);throw"both async and sync fetching of the wasm failed"}catch(t){W(t)}}function K(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return E[this.zb+4>>2>>>0]},this.Sb=function(t){E[this.zb+8>>2>>>0]=t},this.Wb=function(){return E[this.zb+8>>2>>>0]},this.Tb=function(){A[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){A[this.zb>>2>>>0]+=1},this.Xb=function(){var t=A[this.zb>>2>>>0];return A[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){E[this.zb+16>>2>>>0]=t},this.Ob=function(){return E[this.zb+16>>2>>>0]},this.Qb=function(){if(Et(this.Eb()))return E[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return _t(new et(t).zb)}var rt=[];function it(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=N.get(t)),e}function ot(t){var e=C(t)+1,n=yt(e);return n&&k(t,S,n,e),n}var at={};function st(){if(!ut){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:f||"./this.program"};for(t in at)void 0===at[t]?delete e[t]:e[t]=at[t];var n=[];for(t in e)n.push(t+"="+e[t]);ut=n}return ut}var ut,ct=[null,[],[]];function lt(t,e){var n=ct[t];0===e||10===e?((1===t?_:v)(D(n,0)),n.length=0):n.push(e)}var pt=0;function ft(t){return 0==t%4&&(0!=t%100||0==t%400)}var dt=[31,29,31,30,31,30,31,31,30,31,30,31],ht=[31,28,31,30,31,30,31,31,30,31,30,31];function gt(t,e,n,r){function i(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=a(e,t)?0>=a(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var c=A[r+40>>2>>>0];for(var l in r={$b:A[r>>2>>>0],Zb:A[r+4>>2>>>0],Gb:A[r+8>>2>>>0],Kb:A[r+12>>2>>>0],Hb:A[r+16>>2>>>0],Cb:A[r+20>>2>>>0],Ab:A[r+24>>2>>>0],Bb:A[r+28>>2>>>0],bc:A[r+32>>2>>>0],Yb:A[r+36>>2>>>0],ac:c?$(c):""},n=$(n),c={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),c[l]);var p="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),f="January February March April May June July August September October November December".split(" ");for(l in c={"%a":function(t){return p[t.Ab].substring(0,3)},"%A":function(t){return p[t.Ab]},"%b":function(t){return f[t.Hb].substring(0,3)},"%B":function(t){return f[t.Hb]},"%C":function(t){return o((t.Cb+1900)/100|0,2)},"%d":function(t){return o(t.Kb,2)},"%e":function(t){return i(t.Kb,2," ")},"%g":function(t){return u(t).toString().substring(2)},"%G":function(t){return u(t)},"%H":function(t){return o(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return o(t.$b,2)},"%t":function(){return"\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return o(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&ft(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&ft(t.Cb%400-1))&&e++}return o(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return o(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\0\0"),c)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),c[l](r)));return l=function(t){var e=Array(C(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\0\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return yt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),Q--),t.Jb(!1),J.push(t),t.Nb(),t.Qb()},ia:function(t){throw v("Unexpected exception thrown, this is not properly supported - aborting"),I=!0,t},w:function(){xt(0);var t=J.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&it(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return pt=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return pt=0,t;for(var r=Array.prototype.slice.call(arguments),i=0;i>>2]+4294967296*A[t+4>>>2])),A[e>>2>>>0]=t.getUTCSeconds(),A[e+4>>2>>>0]=t.getUTCMinutes(),A[e+8>>2>>>0]=t.getUTCHours(),A[e+12>>2>>>0]=t.getUTCDate(),A[e+16>>2>>>0]=t.getUTCMonth(),A[e+20>>2>>>0]=t.getUTCFullYear()-1900,A[e+24>>2>>>0]=t.getUTCDay(),A[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(E[t>>>2]+4294967296*A[t+4>>>2])),A[e>>2>>>0]=t.getSeconds(),A[e+4>>2>>>0]=t.getMinutes(),A[e+8>>2>>>0]=t.getHours(),A[e+12>>2>>>0]=t.getDate(),A[e+16>>2>>>0]=t.getMonth(),A[e+20>>2>>>0]=t.getFullYear()-1900,A[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);A[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,A[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),A[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(A[t+20>>2>>>0]+1900,A[t+16>>2>>>0],A[t+12>>2>>>0],A[t+8>>2>>>0],A[t+4>>2>>>0],A[t>>2>>>0],0),n=A[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),a=i.getTimezoneOffset(),s=Math.min(a,o);return 0>n?A[t+32>>2>>>0]=Number(o!=a&&s==r):0>2>>>0]=e.getDay(),A[t+28>>2>>>0]=(e.getTime()-i.getTime())/864e5|0,A[t>>2>>>0]=e.getSeconds(),A[t+4>>2>>>0]=e.getMinutes(),A[t+8>>2>>>0]=e.getHours(),A[t+12>>2>>>0]=e.getDate(),A[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\(([A-Za-z ]+)\)$/))?t[1]:"GMT"}var i=(new Date).getFullYear(),o=new Date(i,0,1),a=new Date(i,6,1);i=o.getTimezoneOffset();var s=a.getTimezoneOffset();A[t>>2>>>0]=60*Math.max(i,s),A[e>>2>>>0]=Number(i!=s),t=r(o),e=r(a),t=ot(t),e=ot(e),s>2>>>0]=t,E[n+4>>2>>>0]=e):(E[n>>2>>>0]=e,E[n+4>>2>>>0]=t)}(e,n,r))},B:function(){W("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){O.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=O.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var i=Math;r=Math.max(t,r),i=i.min.call(i,4294901760,r+(65536-r%65536)%65536);t:{try{x.grow(i-T.byteLength+65535>>>16),F();var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},va:function(t,e){var n=0;return st().forEach((function(r,i){var o=e+n;for(i=E[t+4*i>>2>>>0]=o,o=0;o>0>>>0]=r.charCodeAt(o);S[i>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=st();E[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),E[e>>2>>>0]=r,0},ba:function(t){w||0>2>>>0],s=E[e+4>>2>>>0];e+=8;for(var u=0;u>>0]);i+=s}return E[r>>2>>>0]=i,0},c:function(){return pt},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module 'crypto'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>W("randomDevice")}());for(var i=0;i>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},fa:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},J:function(t){var e=Tt();try{return it(t)()}catch(t){if(St(e),t!==t+0)throw t;xt(1,0)}},e:function(t,e){var n=Tt();try{return it(t)(e)}catch(t){if(St(n),t!==t+0)throw t;xt(1,0)}},N:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},O:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},j:function(t,e,n){var r=Tt();try{return it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},o:function(t,e,n,r){var i=Tt();try{return it(t)(e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},p:function(t,e,n,r,i){var o=Tt();try{return it(t)(e,n,r,i)}catch(t){if(St(o),t!==t+0)throw t;xt(1,0)}},M:function(t,e,n,r,i,o){var a=Tt();try{return it(t)(e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},r:function(t,e,n,r,i,o){var a=Tt();try{return it(t)(e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},v:function(t,e,n,r,i,o,a){var s=Tt();try{return it(t)(e,n,r,i,o,a)}catch(t){if(St(s),t!==t+0)throw t;xt(1,0)}},K:function(t,e,n,r,i,o,a,s){var u=Tt();try{return it(t)(e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},D:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Tt();try{return it(t)(e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(St(f),t!==t+0)throw t;xt(1,0)}},X:function(t,e,n,r,i,o,a,s){var u=Tt();try{return Lt(t,e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},V:function(t,e,n,r,i,o,a){var s=Tt();try{return Pt(t,e,n,r,i,o,a)}catch(t){if(St(s),t!==t+0)throw t;xt(1,0)}},U:function(t,e,n,r,i){var o=Tt();try{return Rt(t,e,n,r,i)}catch(t){if(St(o),t!==t+0)throw t;xt(1,0)}},Z:function(t,e,n,r){var i=Tt();try{return Ft(t,e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},W:function(t){var e=Tt();try{return It(t)}catch(t){if(St(e),t!==t+0)throw t;xt(1,0)}},Y:function(t,e){var n=Tt();try{return Nt(t,e)}catch(t){if(St(n),t!==t+0)throw t;xt(1,0)}},T:function(t,e,n){var r=Tt();try{return Dt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},f:function(t){var e=Tt();try{it(t)()}catch(t){if(St(e),t!==t+0)throw t;xt(1,0)}},q:function(t,e){var n=Tt();try{it(t)(e)}catch(t){if(St(n),t!==t+0)throw t;xt(1,0)}},h:function(t,e,n){var r=Tt();try{it(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;xt(1,0)}},da:function(t,e,n,r){var i=Tt();try{it(t)(e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},l:function(t,e,n,r){var i=Tt();try{it(t)(e,n,r)}catch(t){if(St(i),t!==t+0)throw t;xt(1,0)}},t:function(t,e,n,r,i){var o=Tt();try{it(t)(e,n,r,i)}catch(t){if(St(o),t!==t+0)throw t;xt(1,0)}},u:function(t,e,n,r,i,o){var a=Tt();try{it(t)(e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},x:function(t,e,n,r,i,o,a){var s=Tt();try{it(t)(e,n,r,i,o,a)}catch(t){if(St(s),t!==t+0)throw t;xt(1,0)}},z:function(t,e,n,r,i,o,a,s){var u=Tt();try{it(t)(e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},ga:function(t,e,n,r,i,o,a,s,u){var c=Tt();try{it(t)(e,n,r,i,o,a,s,u)}catch(t){if(St(c),t!==t+0)throw t;xt(1,0)}},A:function(t,e,n,r,i,o,a,s,u,c,l){var p=Tt();try{it(t)(e,n,r,i,o,a,s,u,c,l)}catch(t){if(St(p),t!==t+0)throw t;xt(1,0)}},C:function(t,e,n,r,i,o,a,s,u,c,l,p,f,d,h,g){var b=Tt();try{it(t)(e,n,r,i,o,a,s,u,c,l,p,f,d,h,g)}catch(t){if(St(b),t!==t+0)throw t;xt(1,0)}},aa:function(t,e,n,r,i,o,a,s){var u=Tt();try{$t(t,e,n,r,i,o,a,s)}catch(t){if(St(u),t!==t+0)throw t;xt(1,0)}},_:function(t,e,n,r,i,o,a,s,u,c,l,p){var f=Tt();try{Ct(t,e,n,r,i,o,a,s,u,c,l,p)}catch(t){if(St(f),t!==t+0)throw t;xt(1,0)}},$:function(t,e,n,r,i,o){var a=Tt();try{kt(t,e,n,r,i,o)}catch(t){if(St(a),t!==t+0)throw t;xt(1,0)}},n:function(t){return t},F:function(t){pt=t},ha:gt,y:function(t,e,n,r){return gt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,x=e.asm.Ka,F(),N=e.asm.ib,R.unshift(e.asm.La),z--,e.monitorRunDependencies&&e.monitorRunDependencies(z),0==z&&(null!==G&&(clearInterval(G),G=null),H&&(t=H,H=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!y&&(h||g)){if("function"==typeof fetch&&!B.startsWith("file://"))return fetch(B,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at '"+B+"'";return t.arrayBuffer()})).catch((function(){return Y()}));if(a)return new Promise((function(t,e){a(B,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return Y()}))}().then((function(t){return WebAssembly.instantiate(t,o)})).then((function(t){return t})).then(t,(function(t){v("failed to asynchronously prepare wasm: "+t),W(t)}))}var o={a:bt};if(z++,e.monitorRunDependencies&&e.monitorRunDependencies(z),e.instantiateWasm)try{return e.instantiateWasm(o,t)}catch(t){return v("Module.instantiateWasm callback failed with error: "+t),!1}(y||"function"!=typeof WebAssembly.instantiateStreaming||q()||B.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(B,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,o).then(n,(function(t){return v("wasm streaming compile failed: "+t),v("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(i)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,yt=e._malloc=function(){return(yt=e._malloc=e.asm.eb).apply(null,arguments)},_t=e._free=function(){return(_t=e._free=e.asm.fb).apply(null,arguments)},vt=e._fflush=function(){return(vt=e._fflush=e.asm.gb).apply(null,arguments)},wt=e.___funcs_on_exit=function(){return(wt=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},xt=e._setThrew=function(){return(xt=e._setThrew=e.asm.jb).apply(null,arguments)},Tt=e.stackSave=function(){return(Tt=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Ot=e.stackAlloc=function(){return(Ot=e.stackAlloc=e.asm.mb).apply(null,arguments)},At=e.___cxa_can_catch=function(){return(At=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Et=e.___cxa_is_pointer_type=function(){return(Et=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},It=e.dynCall_j=function(){return(It=e.dynCall_j=e.asm.pb).apply(null,arguments)},Pt=e.dynCall_iiiiij=function(){return(Pt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Dt=e.dynCall_jii=function(){return(Dt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},$t=e.dynCall_viiiiij=function(){return($t=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Ct=e.dynCall_viiijjjii=function(){return(Ct=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Ft=e.dynCall_iij=function(){return(Ft=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Nt=e.dynCall_ji=function(){return(Nt=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Lt=e.dynCall_iiiiiij=function(){return(Lt=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},Rt=e.dynCall_iiij=function(){return(Rt=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function jt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!I)){if(Z(R),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();M.unshift(t)}Z(M)}}if(!(0{"use strict";t.exports=function(t,e){for(var n=new Array(arguments.length-1),r=0,i=2,o=!0;i{"use strict";var n=e;n.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&"="===t.charAt(e);)++n;return Math.ceil(3*t.length)/4-n};for(var r=new Array(64),i=new Array(123),o=0;o<64;)i[r[o]=o<26?o+65:o<52?o+71:o<62?o-4:o-59|43]=o++;n.encode=function(t,e,n){for(var i,o=null,a=[],s=0,u=0;e>2],i=(3&c)<<4,u=1;break;case 1:a[s++]=r[i|c>>4],i=(15&c)<<2,u=2;break;case 2:a[s++]=r[i|c>>6],a[s++]=r[63&c],u=0}s>8191&&((o||(o=[])).push(String.fromCharCode.apply(String,a)),s=0)}return u&&(a[s++]=r[i],a[s++]=61,1===u&&(a[s++]=61)),o?(s&&o.push(String.fromCharCode.apply(String,a.slice(0,s))),o.join("")):String.fromCharCode.apply(String,a.slice(0,s))};var a="invalid encoding";n.decode=function(t,e,n){for(var r,o=n,s=0,u=0;u1)break;if(void 0===(c=i[c]))throw Error(a);switch(s){case 0:r=c,s=1;break;case 1:e[n++]=r<<2|(48&c)>>4,r=c,s=2;break;case 2:e[n++]=(15&r)<<4|(60&c)>>2,r=c,s=3;break;case 3:e[n++]=(3&r)<<6|c,s=0}}if(1===s)throw Error(a);return n-o},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},9211:t=>{"use strict";function e(){this._listeners={}}t.exports=e,e.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this},e.prototype.off=function(t,e){if(void 0===t)this._listeners={};else if(void 0===e)this._listeners[t]=[];else for(var n=this._listeners[t],r=0;r{"use strict";function e(t){return"undefined"!=typeof Float32Array?function(){var e=new Float32Array([-0]),n=new Uint8Array(e.buffer),r=128===n[3];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3]}function o(t,r,i){e[0]=t,r[i]=n[3],r[i+1]=n[2],r[i+2]=n[1],r[i+3]=n[0]}function a(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],e[0]}function s(t,r){return n[3]=t[r],n[2]=t[r+1],n[1]=t[r+2],n[0]=t[r+3],e[0]}t.writeFloatLE=r?i:o,t.writeFloatBE=r?o:i,t.readFloatLE=r?a:s,t.readFloatBE=r?s:a}():function(){function e(t,e,n,r){var i=e<0?1:0;if(i&&(e=-e),0===e)t(1/e>0?0:2147483648,n,r);else if(isNaN(e))t(2143289344,n,r);else if(e>34028234663852886e22)t((i<<31|2139095040)>>>0,n,r);else if(e<11754943508222875e-54)t((i<<31|Math.round(e/1401298464324817e-60))>>>0,n,r);else{var o=Math.floor(Math.log(e)/Math.LN2);t((i<<31|o+127<<23|8388607&Math.round(e*Math.pow(2,-o)*8388608))>>>0,n,r)}}function a(t,e,n){var r=t(e,n),i=2*(r>>31)+1,o=r>>>23&255,a=8388607&r;return 255===o?a?NaN:i*(1/0):0===o?1401298464324817e-60*i*a:i*Math.pow(2,o-150)*(a+8388608)}t.writeFloatLE=e.bind(null,n),t.writeFloatBE=e.bind(null,r),t.readFloatLE=a.bind(null,i),t.readFloatBE=a.bind(null,o)}(),"undefined"!=typeof Float64Array?function(){var e=new Float64Array([-0]),n=new Uint8Array(e.buffer),r=128===n[7];function i(t,r,i){e[0]=t,r[i]=n[0],r[i+1]=n[1],r[i+2]=n[2],r[i+3]=n[3],r[i+4]=n[4],r[i+5]=n[5],r[i+6]=n[6],r[i+7]=n[7]}function o(t,r,i){e[0]=t,r[i]=n[7],r[i+1]=n[6],r[i+2]=n[5],r[i+3]=n[4],r[i+4]=n[3],r[i+5]=n[2],r[i+6]=n[1],r[i+7]=n[0]}function a(t,r){return n[0]=t[r],n[1]=t[r+1],n[2]=t[r+2],n[3]=t[r+3],n[4]=t[r+4],n[5]=t[r+5],n[6]=t[r+6],n[7]=t[r+7],e[0]}function s(t,r){return n[7]=t[r],n[6]=t[r+1],n[5]=t[r+2],n[4]=t[r+3],n[3]=t[r+4],n[2]=t[r+5],n[1]=t[r+6],n[0]=t[r+7],e[0]}t.writeDoubleLE=r?i:o,t.writeDoubleBE=r?o:i,t.readDoubleLE=r?a:s,t.readDoubleBE=r?s:a}():function(){function e(t,e,n,r,i,o){var a=r<0?1:0;if(a&&(r=-r),0===r)t(0,i,o+e),t(1/r>0?0:2147483648,i,o+n);else if(isNaN(r))t(0,i,o+e),t(2146959360,i,o+n);else if(r>17976931348623157e292)t(0,i,o+e),t((a<<31|2146435072)>>>0,i,o+n);else{var s;if(r<22250738585072014e-324)t((s=r/5e-324)>>>0,i,o+e),t((a<<31|s/4294967296)>>>0,i,o+n);else{var u=Math.floor(Math.log(r)/Math.LN2);1024===u&&(u=1023),t(4503599627370496*(s=r*Math.pow(2,-u))>>>0,i,o+e),t((a<<31|u+1023<<20|1048576*s&1048575)>>>0,i,o+n)}}}function a(t,e,n,r,i){var o=t(r,i+e),a=t(r,i+n),s=2*(a>>31)+1,u=a>>>20&2047,c=4294967296*(1048575&a)+o;return 2047===u?c?NaN:s*(1/0):0===u?5e-324*s*c:s*Math.pow(2,u-1075)*(c+4503599627370496)}t.writeDoubleLE=e.bind(null,n,0,4),t.writeDoubleBE=e.bind(null,r,4,0),t.readDoubleLE=a.bind(null,i,0,4),t.readDoubleBE=a.bind(null,o,4,0)}(),t}function n(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}function r(t,e,n){e[n]=t>>>24,e[n+1]=t>>>16&255,e[n+2]=t>>>8&255,e[n+3]=255&t}function i(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0}function o(t,e){return(t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3])>>>0}t.exports=e(e)},7199:module=>{"use strict";function inquire(moduleName){try{var mod=eval("quire".replace(/^/,"re"))(moduleName);if(mod&&(mod.length||Object.keys(mod).length))return mod}catch(t){}return null}module.exports=inquire},6662:t=>{"use strict";t.exports=function(t,e,n){var r=n||8192,i=r>>>1,o=null,a=r;return function(n){if(n<1||n>i)return t(n);a+n>r&&(o=t(r),a=0);var s=e.call(o,a,a+=n);return 7&a&&(a=1+(7|a)),s}}},4997:(t,e)=>{"use strict";var n=e;n.length=function(t){for(var e=0,n=0,r=0;r191&&r<224?o[a++]=(31&r)<<6|63&t[e++]:r>239&&r<365?(r=((7&r)<<18|(63&t[e++])<<12|(63&t[e++])<<6|63&t[e++])-65536,o[a++]=55296+(r>>10),o[a++]=56320+(1023&r)):o[a++]=(15&r)<<12|(63&t[e++])<<6|63&t[e++],a>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,o)),a=0);return i?(a&&i.push(String.fromCharCode.apply(String,o.slice(0,a))),i.join("")):String.fromCharCode.apply(String,o.slice(0,a))},n.write=function(t,e,n){for(var r,i,o=n,a=0;a>6|192,e[n++]=63&r|128):55296==(64512&r)&&56320==(64512&(i=t.charCodeAt(a+1)))?(r=65536+((1023&r)<<10)+(1023&i),++a,e[n++]=r>>18|240,e[n++]=r>>12&63|128,e[n++]=r>>6&63|128,e[n++]=63&r|128):(e[n++]=r>>12|224,e[n++]=r>>6&63|128,e[n++]=63&r|128);return n-o}},3442:(t,e)=>{"use strict";e.__esModule=!0;var n=function(){function t(e){if(!e)throw new TypeError("Invalid argument; `value` has no value.");this.value=t.EMPTY,e&&t.isGuid(e)&&(this.value=e)}return t.isGuid=function(e){var n=e.toString();return e&&(e instanceof t||t.validator.test(n))},t.create=function(){return new t([t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-"))},t.createEmpty=function(){return new t("emptyguid")},t.parse=function(e){return new t(e)},t.raw=function(){return[t.gen(2),t.gen(1),t.gen(1),t.gen(1),t.gen(3)].join("-")},t.gen=function(t){for(var e="",n=0;n{t.exports=n;var e=null;try{e=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(t){}function n(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function r(t){return!0===(t&&t.__isLong__)}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0}),n.isLong=r;var i={},o={};function a(t,e){var n,r,a;return e?(a=0<=(t>>>=0)&&t<256)&&(r=o[t])?r:(n=u(t,(0|t)<0?-1:0,!0),a&&(o[t]=n),n):(a=-128<=(t|=0)&&t<128)&&(r=i[t])?r:(n=u(t,t<0?-1:0,!1),a&&(i[t]=n),n)}function s(t,e){if(isNaN(t))return e?m:b;if(e){if(t<0)return m;if(t>=d)return x}else{if(t<=-h)return T;if(t+1>=h)return w}return t<0?s(-t,e).neg():u(t%f|0,t/f|0,e)}function u(t,e,r){return new n(t,e,r)}n.fromInt=a,n.fromNumber=s,n.fromBits=u;var c=Math.pow;function l(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return b;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return l(t.substring(1),e,n).neg();for(var i=s(c(n,8)),o=b,a=0;a>>0:this.low},S.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},S.toString=function(t){if((t=t||10)<2||36>>0).toString(t);if((o=u).isZero())return l+a;for(;l.length<6;)l="0"+l;a=""+l+a}},S.getHighBits=function(){return this.high},S.getHighBitsUnsigned=function(){return this.high>>>0},S.getLowBits=function(){return this.low},S.getLowBitsUnsigned=function(){return this.low>>>0},S.getNumBitsAbs=function(){if(this.isNegative())return this.eq(T)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<=0},S.isOdd=function(){return 1==(1&this.low)},S.isEven=function(){return 0==(1&this.low)},S.equals=function(t){return r(t)||(t=p(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&this.high===t.high&&this.low===t.low},S.eq=S.equals,S.notEquals=function(t){return!this.eq(t)},S.neq=S.notEquals,S.ne=S.notEquals,S.lessThan=function(t){return this.comp(t)<0},S.lt=S.lessThan,S.lessThanOrEqual=function(t){return this.comp(t)<=0},S.lte=S.lessThanOrEqual,S.le=S.lessThanOrEqual,S.greaterThan=function(t){return this.comp(t)>0},S.gt=S.greaterThan,S.greaterThanOrEqual=function(t){return this.comp(t)>=0},S.gte=S.greaterThanOrEqual,S.ge=S.greaterThanOrEqual,S.compare=function(t){if(r(t)||(t=p(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},S.comp=S.compare,S.negate=function(){return!this.unsigned&&this.eq(T)?T:this.not().add(y)},S.neg=S.negate,S.add=function(t){r(t)||(t=p(t));var e=this.high>>>16,n=65535&this.high,i=this.low>>>16,o=65535&this.low,a=t.high>>>16,s=65535&t.high,c=t.low>>>16,l=0,f=0,d=0,h=0;return d+=(h+=o+(65535&t.low))>>>16,f+=(d+=i+c)>>>16,l+=(f+=n+s)>>>16,l+=e+a,u((d&=65535)<<16|(h&=65535),(l&=65535)<<16|(f&=65535),this.unsigned)},S.subtract=function(t){return r(t)||(t=p(t)),this.add(t.neg())},S.sub=S.subtract,S.multiply=function(t){if(this.isZero())return b;if(r(t)||(t=p(t)),e)return u(e.mul(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned);if(t.isZero())return b;if(this.eq(T))return t.isOdd()?T:b;if(t.eq(T))return this.isOdd()?T:b;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(g)&&t.lt(g))return s(this.toNumber()*t.toNumber(),this.unsigned);var n=this.high>>>16,i=65535&this.high,o=this.low>>>16,a=65535&this.low,c=t.high>>>16,l=65535&t.high,f=t.low>>>16,d=65535&t.low,h=0,m=0,y=0,_=0;return y+=(_+=a*d)>>>16,m+=(y+=o*d)>>>16,y&=65535,m+=(y+=a*f)>>>16,h+=(m+=i*d)>>>16,m&=65535,h+=(m+=o*f)>>>16,m&=65535,h+=(m+=a*l)>>>16,h+=n*d+i*f+o*l+a*c,u((y&=65535)<<16|(_&=65535),(h&=65535)<<16|(m&=65535),this.unsigned)},S.mul=S.multiply,S.divide=function(t){if(r(t)||(t=p(t)),t.isZero())throw Error("division by zero");var n,i,o;if(e)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?u((this.unsigned?e.div_u:e.div_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?m:b;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return m;if(t.gt(this.shru(1)))return _;o=m}else{if(this.eq(T))return t.eq(y)||t.eq(v)?T:t.eq(T)?y:(n=this.shr(1).div(t).shl(1)).eq(b)?t.isNegative()?y:v:(i=this.sub(t.mul(n)),o=n.add(i.div(t)));if(t.eq(T))return this.unsigned?m:b;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();o=b}for(i=this;i.gte(t);){n=Math.max(1,Math.floor(i.toNumber()/t.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),l=a<=48?1:c(2,a-48),f=s(n),d=f.mul(t);d.isNegative()||d.gt(i);)d=(f=s(n-=l,this.unsigned)).mul(t);f.isZero()&&(f=y),o=o.add(f),i=i.sub(d)}return o},S.div=S.divide,S.modulo=function(t){return r(t)||(t=p(t)),e?u((this.unsigned?e.rem_u:e.rem_s)(this.low,this.high,t.low,t.high),e.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},S.mod=S.modulo,S.rem=S.modulo,S.not=function(){return u(~this.low,~this.high,this.unsigned)},S.and=function(t){return r(t)||(t=p(t)),u(this.low&t.low,this.high&t.high,this.unsigned)},S.or=function(t){return r(t)||(t=p(t)),u(this.low|t.low,this.high|t.high,this.unsigned)},S.xor=function(t){return r(t)||(t=p(t)),u(this.low^t.low,this.high^t.high,this.unsigned)},S.shiftLeft=function(t){return r(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?u(this.low<>>32-t,this.unsigned):u(0,this.low<>>t|this.high<<32-t,this.high>>t,this.unsigned):u(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},S.shr=S.shiftRight,S.shiftRightUnsigned=function(t){if(r(t)&&(t=t.toInt()),0==(t&=63))return this;var e=this.high;return t<32?u(this.low>>>t|e<<32-t,e>>>t,this.unsigned):u(32===t?e:e>>>t-32,0,this.unsigned)},S.shru=S.shiftRightUnsigned,S.shr_u=S.shiftRightUnsigned,S.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},S.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},S.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},S.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},S.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},n.fromBytes=function(t,e,r){return r?n.fromBytesLE(t,e):n.fromBytesBE(t,e)},n.fromBytesLE=function(t,e){return new n(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},n.fromBytesBE=function(t,e){return new n(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)}},1446:(t,e,n)=>{"use strict";var r,i,o,a=n(2100),s=a.Reader,u=a.Writer,c=a.util,l=a.roots.default||(a.roots.default={});l.onnx=((o={}).Version=(r={},(i=Object.create(r))[r[0]="_START_VERSION"]=0,i[r[1]="IR_VERSION_2017_10_10"]=1,i[r[2]="IR_VERSION_2017_10_30"]=2,i[r[3]="IR_VERSION_2017_11_3"]=3,i[r[4]="IR_VERSION_2019_1_22"]=4,i[r[5]="IR_VERSION"]=5,i),o.AttributeProto=function(){function t(t){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.name=t.string();break;case 21:r.refAttrName=t.string();break;case 13:r.docString=t.string();break;case 20:r.type=t.int32();break;case 2:r.f=t.float();break;case 3:r.i=t.int64();break;case 4:r.s=t.bytes();break;case 5:r.t=l.onnx.TensorProto.decode(t,t.uint32());break;case 6:r.g=l.onnx.GraphProto.decode(t,t.uint32());break;case 7:if(r.floats&&r.floats.length||(r.floats=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos>>0,t.i.high>>>0).toNumber())),null!=t.s&&("string"==typeof t.s?c.base64.decode(t.s,e.s=c.newBuffer(c.base64.length(t.s)),0):t.s.length&&(e.s=t.s)),null!=t.t){if("object"!=typeof t.t)throw TypeError(".onnx.AttributeProto.t: object expected");e.t=l.onnx.TensorProto.fromObject(t.t)}if(null!=t.g){if("object"!=typeof t.g)throw TypeError(".onnx.AttributeProto.g: object expected");e.g=l.onnx.GraphProto.fromObject(t.g)}if(t.floats){if(!Array.isArray(t.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");e.floats=[];for(var n=0;n>>0,t.ints[n].high>>>0).toNumber())}if(t.strings){if(!Array.isArray(t.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");for(e.strings=[],n=0;n>>0,t.i.high>>>0).toNumber():t.i),null!=t.s&&t.hasOwnProperty("s")&&(n.s=e.bytes===String?c.base64.encode(t.s,0,t.s.length):e.bytes===Array?Array.prototype.slice.call(t.s):t.s),null!=t.t&&t.hasOwnProperty("t")&&(n.t=l.onnx.TensorProto.toObject(t.t,e)),null!=t.g&&t.hasOwnProperty("g")&&(n.g=l.onnx.GraphProto.toObject(t.g,e)),t.floats&&t.floats.length){n.floats=[];for(var i=0;i>>0,t.ints[i].high>>>0).toNumber():t.ints[i];if(t.strings&&t.strings.length)for(n.strings=[],i=0;i>>3){case 1:r.name=t.string();break;case 2:r.type=l.onnx.TypeProto.decode(t,t.uint32());break;case 3:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.name&&t.hasOwnProperty("name")&&!c.isString(t.name))return"name: string expected";if(null!=t.type&&t.hasOwnProperty("type")){var e=l.onnx.TypeProto.verify(t.type);if(e)return"type."+e}return null!=t.docString&&t.hasOwnProperty("docString")&&!c.isString(t.docString)?"docString: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.ValueInfoProto)return t;var e=new l.onnx.ValueInfoProto;if(null!=t.name&&(e.name=String(t.name)),null!=t.type){if("object"!=typeof t.type)throw TypeError(".onnx.ValueInfoProto.type: object expected");e.type=l.onnx.TypeProto.fromObject(t.type)}return null!=t.docString&&(e.docString=String(t.docString)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.name="",n.type=null,n.docString=""),null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.type&&t.hasOwnProperty("type")&&(n.type=l.onnx.TypeProto.toObject(t.type,e)),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.NodeProto=function(){function t(t){if(this.input=[],this.output=[],this.attribute=[],t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.input&&r.input.length||(r.input=[]),r.input.push(t.string());break;case 2:r.output&&r.output.length||(r.output=[]),r.output.push(t.string());break;case 3:r.name=t.string();break;case 4:r.opType=t.string();break;case 7:r.domain=t.string();break;case 5:r.attribute&&r.attribute.length||(r.attribute=[]),r.attribute.push(l.onnx.AttributeProto.decode(t,t.uint32()));break;case 6:r.docString=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.input&&t.hasOwnProperty("input")){if(!Array.isArray(t.input))return"input: array expected";for(var e=0;e>>3){case 1:r.irVersion=t.int64();break;case 8:r.opsetImport&&r.opsetImport.length||(r.opsetImport=[]),r.opsetImport.push(l.onnx.OperatorSetIdProto.decode(t,t.uint32()));break;case 2:r.producerName=t.string();break;case 3:r.producerVersion=t.string();break;case 4:r.domain=t.string();break;case 5:r.modelVersion=t.int64();break;case 6:r.docString=t.string();break;case 7:r.graph=l.onnx.GraphProto.decode(t,t.uint32());break;case 14:r.metadataProps&&r.metadataProps.length||(r.metadataProps=[]),r.metadataProps.push(l.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.irVersion&&t.hasOwnProperty("irVersion")&&!(c.isInteger(t.irVersion)||t.irVersion&&c.isInteger(t.irVersion.low)&&c.isInteger(t.irVersion.high)))return"irVersion: integer|Long expected";if(null!=t.opsetImport&&t.hasOwnProperty("opsetImport")){if(!Array.isArray(t.opsetImport))return"opsetImport: array expected";for(var e=0;e>>0,t.irVersion.high>>>0).toNumber())),t.opsetImport){if(!Array.isArray(t.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");e.opsetImport=[];for(var n=0;n>>0,t.modelVersion.high>>>0).toNumber())),null!=t.docString&&(e.docString=String(t.docString)),null!=t.graph){if("object"!=typeof t.graph)throw TypeError(".onnx.ModelProto.graph: object expected");e.graph=l.onnx.GraphProto.fromObject(t.graph)}if(t.metadataProps){if(!Array.isArray(t.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");for(e.metadataProps=[],n=0;n>>0,t.irVersion.high>>>0).toNumber():t.irVersion),null!=t.producerName&&t.hasOwnProperty("producerName")&&(n.producerName=t.producerName),null!=t.producerVersion&&t.hasOwnProperty("producerVersion")&&(n.producerVersion=t.producerVersion),null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.modelVersion&&t.hasOwnProperty("modelVersion")&&("number"==typeof t.modelVersion?n.modelVersion=e.longs===String?String(t.modelVersion):t.modelVersion:n.modelVersion=e.longs===String?c.Long.prototype.toString.call(t.modelVersion):e.longs===Number?new c.LongBits(t.modelVersion.low>>>0,t.modelVersion.high>>>0).toNumber():t.modelVersion),null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),null!=t.graph&&t.hasOwnProperty("graph")&&(n.graph=l.onnx.GraphProto.toObject(t.graph,e)),t.opsetImport&&t.opsetImport.length){n.opsetImport=[];for(var i=0;i>>3){case 1:r.key=t.string();break;case 2:r.value=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.key&&t.hasOwnProperty("key")&&!c.isString(t.key)?"key: string expected":null!=t.value&&t.hasOwnProperty("value")&&!c.isString(t.value)?"value: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.StringStringEntryProto)return t;var e=new l.onnx.StringStringEntryProto;return null!=t.key&&(e.key=String(t.key)),null!=t.value&&(e.value=String(t.value)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.key="",n.value=""),null!=t.key&&t.hasOwnProperty("key")&&(n.key=t.key),null!=t.value&&t.hasOwnProperty("value")&&(n.value=t.value),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o.TensorAnnotation=function(){function t(t){if(this.quantParameterTensorNames=[],t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.tensorName=t.string();break;case 2:r.quantParameterTensorNames&&r.quantParameterTensorNames.length||(r.quantParameterTensorNames=[]),r.quantParameterTensorNames.push(l.onnx.StringStringEntryProto.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorName&&t.hasOwnProperty("tensorName")&&!c.isString(t.tensorName))return"tensorName: string expected";if(null!=t.quantParameterTensorNames&&t.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(t.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var e=0;e>>3){case 1:r.node&&r.node.length||(r.node=[]),r.node.push(l.onnx.NodeProto.decode(t,t.uint32()));break;case 2:r.name=t.string();break;case 5:r.initializer&&r.initializer.length||(r.initializer=[]),r.initializer.push(l.onnx.TensorProto.decode(t,t.uint32()));break;case 10:r.docString=t.string();break;case 11:r.input&&r.input.length||(r.input=[]),r.input.push(l.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 12:r.output&&r.output.length||(r.output=[]),r.output.push(l.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 13:r.valueInfo&&r.valueInfo.length||(r.valueInfo=[]),r.valueInfo.push(l.onnx.ValueInfoProto.decode(t,t.uint32()));break;case 14:r.quantizationAnnotation&&r.quantizationAnnotation.length||(r.quantizationAnnotation=[]),r.quantizationAnnotation.push(l.onnx.TensorAnnotation.decode(t,t.uint32()));break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.node&&t.hasOwnProperty("node")){if(!Array.isArray(t.node))return"node: array expected";for(var e=0;e>>3){case 1:if(r.dims&&r.dims.length||(r.dims=[]),2==(7&i))for(var o=t.uint32()+t.pos;t.pos>>0,t.dims[n].high>>>0).toNumber())}if(null!=t.dataType&&(e.dataType=0|t.dataType),null!=t.segment){if("object"!=typeof t.segment)throw TypeError(".onnx.TensorProto.segment: object expected");e.segment=l.onnx.TensorProto.Segment.fromObject(t.segment)}if(t.floatData){if(!Array.isArray(t.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");for(e.floatData=[],n=0;n>>0,t.int64Data[n].high>>>0).toNumber())}if(null!=t.name&&(e.name=String(t.name)),null!=t.docString&&(e.docString=String(t.docString)),null!=t.rawData&&("string"==typeof t.rawData?c.base64.decode(t.rawData,e.rawData=c.newBuffer(c.base64.length(t.rawData)),0):t.rawData.length&&(e.rawData=t.rawData)),t.externalData){if(!Array.isArray(t.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");for(e.externalData=[],n=0;n>>0,t.uint64Data[n].high>>>0).toNumber(!0))}return e},t.toObject=function(t,e){e||(e={});var n={};if((e.arrays||e.defaults)&&(n.dims=[],n.floatData=[],n.int32Data=[],n.stringData=[],n.int64Data=[],n.doubleData=[],n.uint64Data=[],n.externalData=[]),e.defaults&&(n.dataType=0,n.segment=null,n.name="",e.bytes===String?n.rawData="":(n.rawData=[],e.bytes!==Array&&(n.rawData=c.newBuffer(n.rawData))),n.docString="",n.dataLocation=e.enums===String?"DEFAULT":0),t.dims&&t.dims.length){n.dims=[];for(var r=0;r>>0,t.dims[r].high>>>0).toNumber():t.dims[r]}if(null!=t.dataType&&t.hasOwnProperty("dataType")&&(n.dataType=t.dataType),null!=t.segment&&t.hasOwnProperty("segment")&&(n.segment=l.onnx.TensorProto.Segment.toObject(t.segment,e)),t.floatData&&t.floatData.length)for(n.floatData=[],r=0;r>>0,t.int64Data[r].high>>>0).toNumber():t.int64Data[r];if(null!=t.name&&t.hasOwnProperty("name")&&(n.name=t.name),null!=t.rawData&&t.hasOwnProperty("rawData")&&(n.rawData=e.bytes===String?c.base64.encode(t.rawData,0,t.rawData.length):e.bytes===Array?Array.prototype.slice.call(t.rawData):t.rawData),t.doubleData&&t.doubleData.length)for(n.doubleData=[],r=0;r>>0,t.uint64Data[r].high>>>0).toNumber(!0):t.uint64Data[r];if(null!=t.docString&&t.hasOwnProperty("docString")&&(n.docString=t.docString),t.externalData&&t.externalData.length)for(n.externalData=[],r=0;r>>3){case 1:r.begin=t.int64();break;case 2:r.end=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.begin&&t.hasOwnProperty("begin")&&!(c.isInteger(t.begin)||t.begin&&c.isInteger(t.begin.low)&&c.isInteger(t.begin.high))?"begin: integer|Long expected":null!=t.end&&t.hasOwnProperty("end")&&!(c.isInteger(t.end)||t.end&&c.isInteger(t.end.low)&&c.isInteger(t.end.high))?"end: integer|Long expected":null},t.fromObject=function(t){if(t instanceof l.onnx.TensorProto.Segment)return t;var e=new l.onnx.TensorProto.Segment;return null!=t.begin&&(c.Long?(e.begin=c.Long.fromValue(t.begin)).unsigned=!1:"string"==typeof t.begin?e.begin=parseInt(t.begin,10):"number"==typeof t.begin?e.begin=t.begin:"object"==typeof t.begin&&(e.begin=new c.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber())),null!=t.end&&(c.Long?(e.end=c.Long.fromValue(t.end)).unsigned=!1:"string"==typeof t.end?e.end=parseInt(t.end,10):"number"==typeof t.end?e.end=t.end:"object"==typeof t.end&&(e.end=new c.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults){if(c.Long){var r=new c.Long(0,0,!1);n.begin=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.begin=e.longs===String?"0":0;c.Long?(r=new c.Long(0,0,!1),n.end=e.longs===String?r.toString():e.longs===Number?r.toNumber():r):n.end=e.longs===String?"0":0}return null!=t.begin&&t.hasOwnProperty("begin")&&("number"==typeof t.begin?n.begin=e.longs===String?String(t.begin):t.begin:n.begin=e.longs===String?c.Long.prototype.toString.call(t.begin):e.longs===Number?new c.LongBits(t.begin.low>>>0,t.begin.high>>>0).toNumber():t.begin),null!=t.end&&t.hasOwnProperty("end")&&("number"==typeof t.end?n.end=e.longs===String?String(t.end):t.end:n.end=e.longs===String?c.Long.prototype.toString.call(t.end):e.longs===Number?new c.LongBits(t.end.low>>>0,t.end.high>>>0).toNumber():t.end),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),t.DataLocation=function(){var t={},e=Object.create(t);return e[t[0]="DEFAULT"]=0,e[t[1]="EXTERNAL"]=1,e}(),t}(),o.TensorShapeProto=function(){function t(t){if(this.dim=[],t)for(var e=Object.keys(t),n=0;n>>3==1?(r.dim&&r.dim.length||(r.dim=[]),r.dim.push(l.onnx.TensorShapeProto.Dimension.decode(t,t.uint32()))):t.skipType(7&i)}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.dim&&t.hasOwnProperty("dim")){if(!Array.isArray(t.dim))return"dim: array expected";for(var e=0;e>>3){case 1:r.dimValue=t.int64();break;case 2:r.dimParam=t.string();break;case 3:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";var e={};if(null!=t.dimValue&&t.hasOwnProperty("dimValue")&&(e.value=1,!(c.isInteger(t.dimValue)||t.dimValue&&c.isInteger(t.dimValue.low)&&c.isInteger(t.dimValue.high))))return"dimValue: integer|Long expected";if(null!=t.dimParam&&t.hasOwnProperty("dimParam")){if(1===e.value)return"value: multiple values";if(e.value=1,!c.isString(t.dimParam))return"dimParam: string expected"}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!c.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.TensorShapeProto.Dimension)return t;var e=new l.onnx.TensorShapeProto.Dimension;return null!=t.dimValue&&(c.Long?(e.dimValue=c.Long.fromValue(t.dimValue)).unsigned=!1:"string"==typeof t.dimValue?e.dimValue=parseInt(t.dimValue,10):"number"==typeof t.dimValue?e.dimValue=t.dimValue:"object"==typeof t.dimValue&&(e.dimValue=new c.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber())),null!=t.dimParam&&(e.dimParam=String(t.dimParam)),null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.dimValue&&t.hasOwnProperty("dimValue")&&("number"==typeof t.dimValue?n.dimValue=e.longs===String?String(t.dimValue):t.dimValue:n.dimValue=e.longs===String?c.Long.prototype.toString.call(t.dimValue):e.longs===Number?new c.LongBits(t.dimValue.low>>>0,t.dimValue.high>>>0).toNumber():t.dimValue,e.oneofs&&(n.value="dimValue")),null!=t.dimParam&&t.hasOwnProperty("dimParam")&&(n.dimParam=t.dimParam,e.oneofs&&(n.value="dimParam")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),t}(),o.TypeProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.tensorType=l.onnx.TypeProto.Tensor.decode(t,t.uint32());break;case 6:r.denotation=t.string();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.tensorType&&t.hasOwnProperty("tensorType")){var e=l.onnx.TypeProto.Tensor.verify(t.tensorType);if(e)return"tensorType."+e}return null!=t.denotation&&t.hasOwnProperty("denotation")&&!c.isString(t.denotation)?"denotation: string expected":null},t.fromObject=function(t){if(t instanceof l.onnx.TypeProto)return t;var e=new l.onnx.TypeProto;if(null!=t.tensorType){if("object"!=typeof t.tensorType)throw TypeError(".onnx.TypeProto.tensorType: object expected");e.tensorType=l.onnx.TypeProto.Tensor.fromObject(t.tensorType)}return null!=t.denotation&&(e.denotation=String(t.denotation)),e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.denotation=""),null!=t.tensorType&&t.hasOwnProperty("tensorType")&&(n.tensorType=l.onnx.TypeProto.Tensor.toObject(t.tensorType,e),e.oneofs&&(n.value="tensorType")),null!=t.denotation&&t.hasOwnProperty("denotation")&&(n.denotation=t.denotation),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t.Tensor=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.elemType=t.int32();break;case 2:r.shape=l.onnx.TensorShapeProto.decode(t,t.uint32());break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){if("object"!=typeof t||null===t)return"object expected";if(null!=t.elemType&&t.hasOwnProperty("elemType")&&!c.isInteger(t.elemType))return"elemType: integer expected";if(null!=t.shape&&t.hasOwnProperty("shape")){var e=l.onnx.TensorShapeProto.verify(t.shape);if(e)return"shape."+e}return null},t.fromObject=function(t){if(t instanceof l.onnx.TypeProto.Tensor)return t;var e=new l.onnx.TypeProto.Tensor;if(null!=t.elemType&&(e.elemType=0|t.elemType),null!=t.shape){if("object"!=typeof t.shape)throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");e.shape=l.onnx.TensorShapeProto.fromObject(t.shape)}return e},t.toObject=function(t,e){e||(e={});var n={};return e.defaults&&(n.elemType=0,n.shape=null),null!=t.elemType&&t.hasOwnProperty("elemType")&&(n.elemType=t.elemType),null!=t.shape&&t.hasOwnProperty("shape")&&(n.shape=l.onnx.TensorShapeProto.toObject(t.shape,e)),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),t}(),o.OperatorSetIdProto=function(){function t(t){if(t)for(var e=Object.keys(t),n=0;n>>3){case 1:r.domain=t.string();break;case 2:r.version=t.int64();break;default:t.skipType(7&i)}}return r},t.decodeDelimited=function(t){return t instanceof s||(t=new s(t)),this.decode(t,t.uint32())},t.verify=function(t){return"object"!=typeof t||null===t?"object expected":null!=t.domain&&t.hasOwnProperty("domain")&&!c.isString(t.domain)?"domain: string expected":null!=t.version&&t.hasOwnProperty("version")&&!(c.isInteger(t.version)||t.version&&c.isInteger(t.version.low)&&c.isInteger(t.version.high))?"version: integer|Long expected":null},t.fromObject=function(t){if(t instanceof l.onnx.OperatorSetIdProto)return t;var e=new l.onnx.OperatorSetIdProto;return null!=t.domain&&(e.domain=String(t.domain)),null!=t.version&&(c.Long?(e.version=c.Long.fromValue(t.version)).unsigned=!1:"string"==typeof t.version?e.version=parseInt(t.version,10):"number"==typeof t.version?e.version=t.version:"object"==typeof t.version&&(e.version=new c.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber())),e},t.toObject=function(t,e){e||(e={});var n={};if(e.defaults)if(n.domain="",c.Long){var r=new c.Long(0,0,!1);n.version=e.longs===String?r.toString():e.longs===Number?r.toNumber():r}else n.version=e.longs===String?"0":0;return null!=t.domain&&t.hasOwnProperty("domain")&&(n.domain=t.domain),null!=t.version&&t.hasOwnProperty("version")&&("number"==typeof t.version?n.version=e.longs===String?String(t.version):t.version:n.version=e.longs===String?c.Long.prototype.toString.call(t.version):e.longs===Number?new c.LongBits(t.version.low>>>0,t.version.high>>>0).toNumber():t.version),n},t.prototype.toJSON=function(){return this.constructor.toObject(this,a.util.toJSONOptions)},t}(),o),t.exports=l},2100:(t,e,n)=>{"use strict";t.exports=n(9482)},9482:(t,e,n)=>{"use strict";var r=e;function i(){r.util._configure(),r.Writer._configure(r.BufferWriter),r.Reader._configure(r.BufferReader)}r.build="minimal",r.Writer=n(1173),r.BufferWriter=n(3155),r.Reader=n(1408),r.BufferReader=n(593),r.util=n(9693),r.rpc=n(5994),r.roots=n(5054),r.configure=i,i()},1408:(t,e,n)=>{"use strict";t.exports=u;var r,i=n(9693),o=i.LongBits,a=i.utf8;function s(t,e){return RangeError("index out of range: "+t.pos+" + "+(e||1)+" > "+t.len)}function u(t){this.buf=t,this.pos=0,this.len=t.length}var c,l="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new u(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new u(t);throw Error("illegal buffer")},p=function(){return i.Buffer?function(t){return(u.create=function(t){return i.Buffer.isBuffer(t)?new r(t):l(t)})(t)}:l};function f(){var t=new o(0,0),e=0;if(!(this.len-this.pos>4)){for(;e<3;++e){if(this.pos>=this.len)throw s(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*e)>>>0,t}for(;e<4;++e)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*e)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(e=0,this.len-this.pos>4){for(;e<5;++e)if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}else for(;e<5;++e){if(this.pos>=this.len)throw s(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*e+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,e){return(t[e-4]|t[e-3]<<8|t[e-2]<<16|t[e-1]<<24)>>>0}function h(){if(this.pos+8>this.len)throw s(this,8);return new o(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}u.create=p(),u.prototype._slice=i.Array.prototype.subarray||i.Array.prototype.slice,u.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return c;if(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return c;if((this.pos+=5)>this.len)throw this.pos=this.len,s(this,10);return c}),u.prototype.int32=function(){return 0|this.uint32()},u.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},u.prototype.bool=function(){return 0!==this.uint32()},u.prototype.fixed32=function(){if(this.pos+4>this.len)throw s(this,4);return d(this.buf,this.pos+=4)},u.prototype.sfixed32=function(){if(this.pos+4>this.len)throw s(this,4);return 0|d(this.buf,this.pos+=4)},u.prototype.float=function(){if(this.pos+4>this.len)throw s(this,4);var t=i.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},u.prototype.double=function(){if(this.pos+8>this.len)throw s(this,4);var t=i.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},u.prototype.bytes=function(){var t=this.uint32(),e=this.pos,n=this.pos+t;if(n>this.len)throw s(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(e,n):e===n?new this.buf.constructor(0):this._slice.call(this.buf,e,n)},u.prototype.string=function(){var t=this.bytes();return a.read(t,0,t.length)},u.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw s(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw s(this)}while(128&this.buf[this.pos++]);return this},u.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},u._configure=function(t){r=t,u.create=p(),r._configure();var e=i.Long?"toLong":"toNumber";i.merge(u.prototype,{int64:function(){return f.call(this)[e](!1)},uint64:function(){return f.call(this)[e](!0)},sint64:function(){return f.call(this).zzDecode()[e](!1)},fixed64:function(){return h.call(this)[e](!0)},sfixed64:function(){return h.call(this)[e](!1)}})}},593:(t,e,n)=>{"use strict";t.exports=o;var r=n(1408);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(t){r.call(this,t)}o._configure=function(){i.Buffer&&(o.prototype._slice=i.Buffer.prototype.slice)},o.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},o._configure()},5054:t=>{"use strict";t.exports={}},5994:(t,e,n)=>{"use strict";e.Service=n(7948)},7948:(t,e,n)=>{"use strict";t.exports=i;var r=n(9693);function i(t,e,n){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");r.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=Boolean(e),this.responseDelimited=Boolean(n)}(i.prototype=Object.create(r.EventEmitter.prototype)).constructor=i,i.prototype.rpcCall=function t(e,n,i,o,a){if(!o)throw TypeError("request must be specified");var s=this;if(!a)return r.asPromise(t,s,e,n,i,o);if(s.rpcImpl)try{return s.rpcImpl(e,n[s.requestDelimited?"encodeDelimited":"encode"](o).finish(),(function(t,n){if(t)return s.emit("error",t,e),a(t);if(null!==n){if(!(n instanceof i))try{n=i[s.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return s.emit("error",t,e),a(t)}return s.emit("data",n,e),a(null,n)}s.end(!0)}))}catch(t){return s.emit("error",t,e),void setTimeout((function(){a(t)}),0)}else setTimeout((function(){a(Error("already ended"))}),0)},i.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},1945:(t,e,n)=>{"use strict";t.exports=i;var r=n(9693);function i(t,e){this.lo=t>>>0,this.hi=e>>>0}var o=i.zero=new i(0,0);o.toNumber=function(){return 0},o.zzEncode=o.zzDecode=function(){return this},o.length=function(){return 1};var a=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(t){if(0===t)return o;var e=t<0;e&&(t=-t);var n=t>>>0,r=(t-n)/4294967296>>>0;return e&&(r=~r>>>0,n=~n>>>0,++n>4294967295&&(n=0,++r>4294967295&&(r=0))),new i(n,r)},i.from=function(t){if("number"==typeof t)return i.fromNumber(t);if(r.isString(t)){if(!r.Long)return i.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new i(t.low>>>0,t.high>>>0):o},i.prototype.toNumber=function(t){if(!t&&this.hi>>>31){var e=1+~this.lo>>>0,n=~this.hi>>>0;return e||(n=n+1>>>0),-(e+4294967296*n)}return this.lo+4294967296*this.hi},i.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,Boolean(t)):{low:0|this.lo,high:0|this.hi,unsigned:Boolean(t)}};var s=String.prototype.charCodeAt;i.fromHash=function(t){return t===a?o:new i((s.call(t,0)|s.call(t,1)<<8|s.call(t,2)<<16|s.call(t,3)<<24)>>>0,(s.call(t,4)|s.call(t,5)<<8|s.call(t,6)<<16|s.call(t,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},i.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},i.prototype.length=function(){var t=this.lo,e=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0===n?0===e?t<16384?t<128?1:2:t<2097152?3:4:e<16384?e<128?5:6:e<2097152?7:8:n<128?9:10}},9693:function(t,e,n){"use strict";var r=e;function i(t,e,n){for(var r=Object.keys(e),i=0;i0)},r.Buffer=function(){try{var t=r.inquire("buffer").Buffer;return t.prototype.utf8Write?t:null}catch(t){return null}}(),r._Buffer_from=null,r._Buffer_allocUnsafe=null,r.newBuffer=function(t){return"number"==typeof t?r.Buffer?r._Buffer_allocUnsafe(t):new r.Array(t):r.Buffer?r._Buffer_from(t):"undefined"==typeof Uint8Array?t:new Uint8Array(t)},r.Array="undefined"!=typeof Uint8Array?Uint8Array:Array,r.Long=r.global.dcodeIO&&r.global.dcodeIO.Long||r.global.Long||r.inquire("long"),r.key2Re=/^true|false|0|1$/,r.key32Re=/^-?(?:0|[1-9][0-9]*)$/,r.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,r.longToHash=function(t){return t?r.LongBits.from(t).toHash():r.LongBits.zeroHash},r.longFromHash=function(t,e){var n=r.LongBits.fromHash(t);return r.Long?r.Long.fromBits(n.lo,n.hi,e):n.toNumber(Boolean(e))},r.merge=i,r.lcFirst=function(t){return t.charAt(0).toLowerCase()+t.substring(1)},r.newError=o,r.ProtocolError=o("ProtocolError"),r.oneOfGetter=function(t){for(var e={},n=0;n-1;--n)if(1===e[t[n]]&&void 0!==this[t[n]]&&null!==this[t[n]])return t[n]}},r.oneOfSetter=function(t){return function(e){for(var n=0;n{"use strict";t.exports=p;var r,i=n(9693),o=i.LongBits,a=i.base64,s=i.utf8;function u(t,e,n){this.fn=t,this.len=e,this.next=void 0,this.val=n}function c(){}function l(t){this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}function p(){this.len=0,this.head=new u(c,0,0),this.tail=this.head,this.states=null}var f=function(){return i.Buffer?function(){return(p.create=function(){return new r})()}:function(){return new p}};function d(t,e,n){e[n]=255&t}function h(t,e){this.len=t,this.next=void 0,this.val=e}function g(t,e,n){for(;t.hi;)e[n++]=127&t.lo|128,t.lo=(t.lo>>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;t.lo>127;)e[n++]=127&t.lo|128,t.lo=t.lo>>>7;e[n++]=t.lo}function b(t,e,n){e[n]=255&t,e[n+1]=t>>>8&255,e[n+2]=t>>>16&255,e[n+3]=t>>>24}p.create=f(),p.alloc=function(t){return new i.Array(t)},i.Array!==Array&&(p.alloc=i.pool(p.alloc,i.Array.prototype.subarray)),p.prototype._push=function(t,e,n){return this.tail=this.tail.next=new u(t,e,n),this.len+=e,this},h.prototype=Object.create(u.prototype),h.prototype.fn=function(t,e,n){for(;t>127;)e[n++]=127&t|128,t>>>=7;e[n]=t},p.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new h((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},p.prototype.int32=function(t){return t<0?this._push(g,10,o.fromNumber(t)):this.uint32(t)},p.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},p.prototype.uint64=function(t){var e=o.from(t);return this._push(g,e.length(),e)},p.prototype.int64=p.prototype.uint64,p.prototype.sint64=function(t){var e=o.from(t).zzEncode();return this._push(g,e.length(),e)},p.prototype.bool=function(t){return this._push(d,1,t?1:0)},p.prototype.fixed32=function(t){return this._push(b,4,t>>>0)},p.prototype.sfixed32=p.prototype.fixed32,p.prototype.fixed64=function(t){var e=o.from(t);return this._push(b,4,e.lo)._push(b,4,e.hi)},p.prototype.sfixed64=p.prototype.fixed64,p.prototype.float=function(t){return this._push(i.float.writeFloatLE,4,t)},p.prototype.double=function(t){return this._push(i.float.writeDoubleLE,8,t)};var m=i.Array.prototype.set?function(t,e,n){e.set(t,n)}:function(t,e,n){for(var r=0;r>>0;if(!e)return this._push(d,1,0);if(i.isString(t)){var n=p.alloc(e=a.length(t));a.decode(t,n,0),t=n}return this.uint32(e)._push(m,e,t)},p.prototype.string=function(t){var e=s.length(t);return e?this.uint32(e)._push(s.write,e,t):this._push(d,1,0)},p.prototype.fork=function(){return this.states=new l(this),this.head=this.tail=new u(c,0,0),this.len=0,this},p.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new u(c,0,0),this.len=0),this},p.prototype.ldelim=function(){var t=this.head,e=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=e,this.len+=n),this},p.prototype.finish=function(){for(var t=this.head.next,e=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,e,n),n+=t.len,t=t.next;return e},p._configure=function(t){r=t,p.create=f(),r._configure()}},3155:(t,e,n)=>{"use strict";t.exports=o;var r=n(1173);(o.prototype=Object.create(r.prototype)).constructor=o;var i=n(9693);function o(){r.call(this)}function a(t,e,n){t.length<40?i.utf8.write(t,e,n):e.utf8Write?e.utf8Write(t,n):e.write(t,n)}o._configure=function(){o.alloc=i._Buffer_allocUnsafe,o.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&"set"===i.Buffer.prototype.set.name?function(t,e,n){e.set(t,n)}:function(t,e,n){if(t.copy)t.copy(e,n,0,t.length);else for(var r=0;r>>0;return this.uint32(e),e&&this._push(o.writeBytesBuffer,e,t),this},o.prototype.string=function(t){var e=i.Buffer.byteLength(t);return this.uint32(e),e&&this._push(a,e,t),this},o._configure()},7714:(t,e,n)=>{"use strict";e.R=void 0;const r=n(6919),i=n(7448);e.R=new class{async init(){}async createSessionHandler(t,e){const n=new r.Session(e);return await n.loadModel(t),new i.OnnxjsSessionHandler(n)}}},4200:(t,e,n)=>{"use strict";e.c8=e.rX=void 0;const r=n(1670),i=n(5381),o=n(2157),a=n(2306);e.rX=()=>{if(("number"!=typeof r.env.wasm.initTimeout||r.env.wasm.initTimeout<0)&&(r.env.wasm.initTimeout=0),"boolean"!=typeof r.env.wasm.simd&&(r.env.wasm.simd=!0),"boolean"!=typeof r.env.wasm.proxy&&(r.env.wasm.proxy=!1),"number"!=typeof r.env.wasm.numThreads||!Number.isInteger(r.env.wasm.numThreads)||r.env.wasm.numThreads<=0){const t="undefined"==typeof navigator?(0,i.cpus)().length:navigator.hardwareConcurrency;r.env.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},e.c8=new class{async init(){(0,e.rX)(),await(0,o.initWasm)()}async createSessionHandler(t,e){const n=new a.OnnxruntimeWebAssemblySessionHandler;return await n.loadModel(t,e),Promise.resolve(n)}}},6018:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||r(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),i(n(1670),e);const o=n(1670);{const t=n(7714).R;(0,o.registerBackend)("webgl",t,-10)}{const t=n(4200).c8;(0,o.registerBackend)("cpu",t,10),(0,o.registerBackend)("wasm",t,10),(0,o.registerBackend)("xnnpack",t,9)}},246:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createAttributeWithCacheKey=void 0;class n{constructor(t){Object.assign(this,t)}get cacheKey(){return this._cacheKey||(this._cacheKey=Object.getOwnPropertyNames(this).sort().map((t=>`${this[t]}`)).join(";")),this._cacheKey}}e.createAttributeWithCacheKey=t=>new n(t)},7778:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Attribute=void 0;const r=n(1446),i=n(9395),o=n(9162),a=n(2517);var s=i.onnxruntime.experimental.fbs;class u{constructor(t){if(this._attributes=new Map,null!=t){for(const e of t)e instanceof r.onnx.AttributeProto?this._attributes.set(e.name,[u.getValue(e),u.getType(e)]):e instanceof s.Attribute&&this._attributes.set(e.name(),[u.getValue(e),u.getType(e)]);if(this._attributes.sizeo.Tensor.fromProto(t)));if(t instanceof s.Attribute)return n.map((t=>o.Tensor.fromOrtTensor(t)))}if(e===r.onnx.AttributeProto.AttributeType.STRING&&t instanceof r.onnx.AttributeProto){const t=n;return(0,a.decodeUtf8String)(t)}return e===r.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof r.onnx.AttributeProto?n.map(a.decodeUtf8String):n}static getValueNoCheck(t){return t instanceof r.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case r.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case r.onnx.AttributeProto.AttributeType.INT:return t.i;case r.onnx.AttributeProto.AttributeType.STRING:return t.s;case r.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case r.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case r.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case r.onnx.AttributeProto.AttributeType.INTS:return t.ints;case r.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case r.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case r.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${r.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case s.AttributeType.FLOAT:return t.f();case s.AttributeType.INT:return t.i();case s.AttributeType.STRING:return t.s();case s.AttributeType.TENSOR:return t.t();case s.AttributeType.GRAPH:return t.g();case s.AttributeType.FLOATS:return t.floatsArray();case s.AttributeType.INTS:{const e=[];for(let n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.resolveBackend=e.backend=void 0;const r=n(5038),i=new Map;async function o(t){const n=e.backend;if(void 0!==n[t]&&function(t){const e=t;return"initialize"in e&&"function"==typeof e.initialize&&"createSessionHandler"in e&&"function"==typeof e.createSessionHandler&&"dispose"in e&&"function"==typeof e.dispose}(n[t])){const e=n[t];let r=e.initialize();if("object"==typeof r&&"then"in r&&(r=await r),r)return i.set(t,e),e}}e.backend={webgl:new r.WebGLBackend},e.resolveBackend=async function t(e){if(!e)return t(["webgl"]);{const t="string"==typeof e?[e]:e;for(const e of t){const t=i.get(e);if(t)return t;const n=await o(e);if(n)return n}}throw new Error("no available backend to use")}},5038:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLBackend=void 0;const r=n(1670),i=n(6231),o=n(6416),a=n(7305);e.WebGLBackend=class{get contextId(){return r.env.webgl.contextId}set contextId(t){r.env.webgl.contextId=t}get matmulMaxBatchSize(){return r.env.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(t){r.env.webgl.matmulMaxBatchSize=t}get textureCacheMode(){return r.env.webgl.textureCacheMode}set textureCacheMode(t){r.env.webgl.textureCacheMode=t}get pack(){return r.env.webgl.pack}set pack(t){r.env.webgl.pack=t}get async(){return r.env.webgl.async}set async(t){r.env.webgl.async=t}initialize(){try{return this.glContext=(0,a.createWebGLContext)(this.contextId),"number"!=typeof this.matmulMaxBatchSize&&(this.matmulMaxBatchSize=16),"string"!=typeof this.textureCacheMode&&(this.textureCacheMode="full"),"boolean"!=typeof this.pack&&(this.pack=!1),"boolean"!=typeof this.async&&(this.async=!1),i.Logger.setWithEnv(r.env),i.Logger.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(t){return i.Logger.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${t}`),!1}}createSessionHandler(t){return new o.WebGLSessionHandler(this,t)}dispose(){this.glContext.dispose()}}},5107:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CoordsGlslLib=void 0;const r=n(2517),i=n(8520),o=n(5060),a=n(7859),s=n(9390);class u extends i.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.offsetToCoords()),this.coordsToOffset()),this.toVec()),this.valueFrom()),this.getCommonUtilFuncs()),this.getInputsSamplingSnippets()),this.getOutputSamplingSnippet())}getCustomTypes(){return{}}offsetToCoords(){return{offsetToCoords:new i.GlslLibRoutine("\n vec2 offsetToCoords(int offset, int width, int height) {\n int t = offset / width;\n int s = offset - t*width;\n vec2 coords = (vec2(s,t) + vec2(0.5,0.5)) / vec2(width, height);\n return coords;\n }\n ")}}coordsToOffset(){return{coordsToOffset:new i.GlslLibRoutine("\n int coordsToOffset(vec2 coords, int width, int height) {\n float s = coords.s * float(width);\n float t = coords.t * float(height);\n int offset = int(t) * width + int(s);\n return offset;\n }\n ")}}getOutputSamplingSnippet(){const t=this.context.outputTextureLayout;return t.isPacked?this.getPackedOutputSamplingSnippet(t):this.getUnpackedOutputSamplingSnippet(t)}getPackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},a="getOutputCoords";switch(e.length){case 0:r[a]=this.getOutputScalarCoords();break;case 1:r[a]=this.getOutputPacked1DCoords(e,n);break;case 2:r[a]=this.getOutputPacked2DCoords(e,n);break;case 3:r[a]=this.getOutputPacked3DCoords(e,n);break;default:r[a]=this.getOutputPackedNDCoords(e,n)}const s=`\n void setOutput(vec4 val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = val;\n }\n `;return r.floatTextureSetRGBA=new i.GlslLibRoutine(s),r}getUnpackedOutputSamplingSnippet(t){const e=t.unpackedShape,n=[t.width,t.height],r={},a="getOutputCoords";switch(e.length){case 0:r[a]=this.getOutputScalarCoords();break;case 1:r[a]=this.getOutputUnpacked1DCoords(e,n);break;case 2:r[a]=this.getOutputUnpacked2DCoords(e,n);break;case 3:r[a]=this.getOutputUnpacked3DCoords(e,n);break;case 4:r[a]=this.getOutputUnpacked4DCoords(e,n);break;case 5:r[a]=this.getOutputUnpacked5DCoords(e,n);break;case 6:r[a]=this.getOutputUnpacked6DCoords(e,n);break;default:throw new Error(`Unsupported output dimensionality: ${e.length}`)}const s=`\n void setOutput(float val) {\n ${(0,o.getGlsl)(this.context.glContext.version).output} = vec4(val, 0, 0, 0);\n }\n `;return r.floatTextureSetR=new i.GlslLibRoutine(s),r}getOutputScalarCoords(){return new i.GlslLibRoutine("\n int getOutputCoords() {\n return 0;\n }\n ")}getOutputPacked1DCoords(t,e){const n=e;let r="";return 1===n[0]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.y * ${n[1]}.0);\n }\n `,new i.GlslLibRoutine(r)):1===n[1]?(r=`\n int getOutputCoords() {\n return 2 * int(TexCoords.x * ${n[0]}.0);\n }\n `,new i.GlslLibRoutine(r)):(r=`\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n return 2 * (resTexRC.y * ${n[0]} + resTexRC.x);\n }\n `,new i.GlslLibRoutine(r))}getOutputPacked2DCoords(t,e){let n="";if(r.ArrayUtil.arraysEqual(t,e))return n=`\n ivec2 getOutputCoords() {\n return 2 * ivec2(TexCoords.xy * vec2(${e[0]}, ${e[1]}));\n }\n `,new i.GlslLibRoutine(n);const o=e,a=Math.ceil(t[1]/2);return n=`\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${o[0]}, ${o[1]}));\n\n int index = resTexRC.y * ${o[0]} + resTexRC.x;\n\n // reverse r and c order for packed texture\n int r = imod(index, ${a}) * 2;\n int c = 2 * (index / ${a});\n\n return ivec2(r, c);\n }\n `,new i.GlslLibRoutine(n)}getOutputPacked3DCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[2]/2),o=r*Math.ceil(t[1]/2),a=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${n[0]}, ${n[1]}));\n int index = resTexRC.y * ${n[0]} + resTexRC.x;\n\n int b = index / ${o};\n index -= b * ${o};\n\n // reverse r and c order for packed texture\n int r = imod(index, ${r}) * 2;\n int c = 2 * (index / ${r});\n\n return ivec3(b, r, c);\n }\n `;return new i.GlslLibRoutine(a)}getOutputPackedNDCoords(t,e){const n=[e[0],e[1]],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2);let a=o,s="",u="b, r, c";for(let e=2;e=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${s}\n return ivec3(r, c, d);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked4DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d","d2"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n ivec4 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${s}\n return ivec4(r, c, d, d2);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked5DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d","d2","d3"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n ivec5 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${s}\n return ivec5(r, c, d, d2, d3);\n }\n `,new i.GlslLibRoutine(n)}getOutputUnpacked6DCoords(t,e){let n="";const r=t.length;let o=null;r<2&&(o=[]),o=new Array(r-1),o[r-2]=t[r-1];for(let e=r-3;e>=0;--e)o[e]=o[e+1]*t[e+1];const a=["r","c","d","d2","d3","d4"],s=o.map(((t,e)=>`int ${a[e]} = index / ${t}; ${e===o.length-1?`int ${a[e+1]} = index - ${a[e]} * ${t}`:`index -= ${a[e]} * ${t}`};`)).join("");return n=`\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(TexCoords.xy *\n vec2(${e[0]}, ${e[1]}));\n int index = resTexRC.y * ${e[0]} + resTexRC.x;\n ${s}\n return ivec6(r, c, d, d2, d3, d4);\n }\n `,new i.GlslLibRoutine(n)}getCommonUtilFuncs(){const t={};let e="uvFromFlat";t[e]=new i.GlslLibRoutine("\n vec2 uvFromFlat(int texNumR, int texNumC, int index) {\n int texC = index / texNumR;\n int texR = index - texC * texNumR;\n // TODO: swap texR, texC order in following function so row is corresponding to u and column is corresponding to\n // v.\n return (vec2(texR, texC) + halfCR) / vec2(texNumR, texNumC);\n }\n "),e="packedUVfrom1D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n int texelIndex = index / 2;\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="packedUVfrom2D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom2D(int texNumR, int texNumC, int texelsInLogicalRow, int row, int col) {\n int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = texelIndex / texNumC;\n int texC = texelIndex - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="packedUVfrom3D",t[e]=new i.GlslLibRoutine("\n vec2 packedUVfrom3D(int texNumR, int texNumC,\n int texelsInBatch, int texelsInLogicalRow, int b,\n int row, int col) {\n int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n int texR = index / texNumC;\n int texC = index - texR * texNumC;\n return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n }\n "),e="sampleTexture";const n=(0,o.getGlsl)(this.context.glContext.version);return t[e]=new i.GlslLibRoutine(`\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return ${n.texture2D}(textureSampler, uv).r;\n }`),t}getInputsSamplingSnippets(){const t={},e=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach(((n,r)=>{const i=this.context.inputTextureLayouts[r],o=(0,s.generateShaderFuncNameFromInputSamplerName)(n);i.isPacked?t[o]=this.getPackedSamplerFromInput(o,n,i):t[o]=this.getUnpackedSamplerFromInput(o,n,i);const a=(0,s.generateShaderFuncNameFromInputSamplerNameAtOutCoords)(n);i.unpackedShape.length<=e.unpackedShape.length&&(i.isPacked?t[a]=this.getPackedSamplerAtOutputCoords(a,i,e,n):t[a]=this.getUnpackedSamplerAtOutputCoords(a,i,e,n))})),t}getPackedSamplerAtOutputCoords(t,e,n,o){const a=e.unpackedShape,u=n.unpackedShape,c=o,l=(0,s.generateShaderFuncNameFromInputSamplerName)(c),p=a.length,f=u.length,d=r.BroadcastUtil.getBroadcastDims(a,u),h=(0,s.getCoordsDataType)(f),g=f-p;let b;const m=(0,s.getGlChannels)();b=0===p?"":f<2&&d.length>=1?"coords = 0;":d.map((t=>`coords.${m[t+g]} = 0;`)).join("\n");let y="";y=f<2&&p>0?"coords":a.map(((t,e)=>`coords.${m[e+g]}`)).join(", ");let _="return outputValue;";const v=1===r.ShapeUtil.size(a),w=1===r.ShapeUtil.size(u);if(1!==p||v||w){if(v&&!w)_=1===f?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(d.length){const t=p-2,e=p-1;d.indexOf(t)>-1&&d.indexOf(e)>-1?_="return vec4(outputValue.x);":d.indexOf(t)>-1?_="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":d.indexOf(e)>-1&&(_="return vec4(outputValue.xx, outputValue.zz);")}}else _="\n return vec4(outputValue.xy, outputValue.xy);\n ";const x=`\n vec4 ${t}() {\n ${h} coords = getOutputCoords();\n \n int lastDim = coords.${m[f-1]};\n coords.${m[f-1]} = coords.${m[f-2]};\n coords.${m[f-2]} = lastDim;\n \n ${b}\n vec4 outputValue = ${l}(${y});\n ${_}\n }\n `;return new i.GlslLibRoutine(x,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(t,e,n,o){const a=[n.width,n.height],u=[e.width,e.height],c=e.unpackedShape.length,l=n.unpackedShape.length,p=e.unpackedShape,f=n.unpackedShape,d=(0,s.generateShaderFuncNameFromInputSamplerName)(o);if(c===l&&r.ArrayUtil.arraysEqual(u,a)){const e=`\n float ${t}() {\n return sampleTexture(${o}, TexCoords);\n }\n `;return new i.GlslLibRoutine(e,["coordinates.sampleTexture"])}const h=(0,s.getCoordsDataType)(l),g=r.BroadcastUtil.getBroadcastDims(p,f),b=l-c;let m;const y=(0,s.getGlChannels)();m=0===c?"":l<2&&g.length>=1?"coords = 0;":g.map((t=>`coords.${y[t+b]} = 0;`)).join("\n");let _="";_=l<2&&c>0?"coords":e.unpackedShape.map(((t,e)=>`coords.${y[e+b]}`)).join(", ");const v=`\n float ${t}() {\n ${h} coords = getOutputCoords();\n ${m}\n return ${d}(${_});\n }\n `;return new i.GlslLibRoutine(v,["coordinates.getOutputCoords"])}getPackedSamplerFromInput(t,e,n){switch(n.unpackedShape.length){case 0:return this.getPackedSamplerScalar(t,e);case 1:return this.getPackedSampler1D(t,e,n);case 2:return this.getPackedSampler2D(t,e,n);case 3:return this.getPackedSampler3D(t,e,n);default:return this.getPackedSamplerND(t,e,n)}}getUnpackedSamplerFromInput(t,e,n){const r=n.unpackedShape;switch(r.length){case 0:return this.getUnpackedSamplerScalar(t,e,n);case 1:return this.getUnpackedSampler1D(t,e,n);case 2:return this.getUnpackedSampler2D(t,e,n);case 3:return this.getUnpackedSampler3D(t,e,n);case 4:return this.getUnpackedSampler4D(t,e,n);case 5:return this.getUnpackedSampler5D(t,e,n);case 6:return this.getUnpackedSampler6D(t,e,n);default:throw new Error(`Unsupported dimension ${r.length}-D`)}}getPackedSamplerScalar(t,e){const n=`\n vec4 ${t}() {\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${e}, halfCR);\n }\n `;return new i.GlslLibRoutine(n)}getPackedSampler1D(t,e,n){const r=[n.width,n.height],a=[r[1],r[0]],s=(0,o.getGlsl)(this.context.glContext.version),u=`vec4 ${t}(int index) {\n vec2 uv = packedUVfrom1D(\n ${a[0]}, ${a[1]}, index);\n return ${s.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(u,["coordinates.packedUVfrom1D"])}getPackedSampler2D(t,e,n){const a=n.unpackedShape,s=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),c=s[0],l=s[1];if(null!=s&&r.ArrayUtil.arraysEqual(a,s)){const n=`vec4 ${t}(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2(${l}.0, ${c}.0);\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(n)}const p=s,f=Math.ceil(a[1]/2),d=`vec4 ${t}(int row, int col) {\n vec2 uv = packedUVfrom2D(${p[1]}, ${p[0]}, ${f}, row, col);\n return ${u.texture2D}(${e}, uv);\n }`;return new i.GlslLibRoutine(d,["coordinates.packedUVfrom2D"])}getPackedSampler3D(t,e,n){const r=n.unpackedShape,a=[n.width,n.height],u=[a[0],a[1]],c=(0,o.getGlsl)(this.context.glContext.version);if(1===r[0]){const o=r.slice(1),a=[1,2],u=(0,s.squeezeInputShape)(r,o),c=["b","row","col"],l=JSON.parse(JSON.stringify(n));l.unpackedShape=u;const p=this.getPackedSamplerFromInput(t,e,l),f=`${p.routineBody}\n vec4 ${t}(int b, int row, int col) {\n return ${t}(${(0,s.getSqueezedParams)(c,a)});\n } `;return new i.GlslLibRoutine(f,p.dependencies)}const l=u[0],p=u[1],f=Math.ceil(r[2]/2),d=`vec4 ${t}(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n ${p}, ${l}, ${f*Math.ceil(r[1]/2)}, ${f}, b, row, col);\n return ${c.texture2D}(${e}, uv);}`;return new i.GlslLibRoutine(d,["coordinates.packedUVfrom3D"])}getPackedSamplerND(t,e,n){const r=n.unpackedShape,a=r.length,s=[n.width,n.height],u=(0,o.getGlsl)(this.context.glContext.version),c=[s[0],s[1]],l=c[1],p=c[0],f=Math.ceil(r[a-1]/2);let d=f*Math.ceil(r[a-2]/2),h="int b, int row, int col",g=`b * ${d} + (row / 2) * ${f} + (col / 2)`;for(let t=2;t{const r=this.context.inputTextureLayouts[n],o=(r.unpackedShape.length>0?r.unpackedShape:r.shape).length;let a=`_${e}`;t[a]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!1),[`shapeUtils.indicesToOffset${a}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"]),a+="_T",t[a]=new i.GlslLibRoutine(this.getValueFromSingle(e,o,r.width,r.height,!0),[`shapeUtils.indicesToOffset${a}`,"coordinates.offsetToCoords","fragcolor.getColorAsFloat"])})),t}getValueFromSingle(t,e,n,r,i){let a=`_${t}`;return i&&(a+="_T"),`\n float ${a}(int m[${e}]) {\n int offset = indicesToOffset${a}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n float value = getColorAsFloat(${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords));\n return value;\n }\n `}getPackedValueFrom(t,e,n,r,i){let a=`_${t}_Pack`;return i&&(a+="_T"),`\n vec4 ${a}(int m[${e}]) {\n int offset = indicesToOffset_${t}(m);\n vec2 coords = offsetToCoords(offset, ${n}, ${r});\n return ${(0,o.getGlsl)(this.context.glContext.version).texture2D}(${t}, coords);\n }\n `}}e.CoordsGlslLib=u},8520:(t,e)=>{"use strict";var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TopologicalSortGlslRoutines=e.GlslLibRoutineNode=e.GlslLibRoutine=e.GlslLib=e.GlslContext=e.FunctionType=void 0,(n=e.FunctionType||(e.FunctionType={}))[n.ValueBased=0]="ValueBased",n[n.Positional=1]="Positional",e.GlslContext=class{constructor(t,e,n,r){this.glContext=t,this.programInfo=e,this.inputTextureLayouts=n,this.outputTextureLayout=r}},e.GlslLib=class{constructor(t){this.context=t}},e.GlslLibRoutine=class{constructor(t,e){this.routineBody=t,this.dependencies=e}},e.GlslLibRoutineNode=class{constructor(t,e,n){this.name=t,this.dependencies=n||[],e&&(this.routineBody=e)}addDependency(t){t&&this.dependencies.push(t)}},e.TopologicalSortGlslRoutines=class{static returnOrderedNodes(t){if(!t||0===t.length)return[];if(1===t.length)return t;const e=new Set,n=new Set,r=new Array;return this.createOrderedNodes(t,e,n,r),r}static createOrderedNodes(t,e,n,r){for(let i=0;i0)for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EncodingGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.encodeFloat32()),this.decodeFloat32())}getCustomTypes(){return{}}encodeFloat32(){return{encode:new r.GlslLibRoutine("highp vec4 encode(highp float f) {\n return vec4(f, 0.0, 0.0, 0.0);\n }\n ")}}decodeFloat32(){return{decode:new r.GlslLibRoutine("highp float decode(highp vec4 rgba) {\n return rgba.r;\n }\n ")}}encodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new r.GlslLibRoutine(`\n highp vec4 encode(highp float f) {\n highp float F = abs(f);\n highp float Sign = step(0.0,-f);\n highp float Exponent = floor(log2(F));\n highp float Mantissa = (exp2(- Exponent) * F);\n Exponent = floor(log2(F) + 127.0) + floor(log2(Mantissa));\n highp vec4 rgba;\n rgba[0] = 128.0 * Sign + floor(Exponent*exp2(-1.0));\n rgba[1] = 128.0 * mod(Exponent,2.0) + mod(floor(Mantissa*128.0),128.0);\n rgba[2] = floor(mod(floor(Mantissa*exp2(23.0 -8.0)),exp2(8.0)));\n rgba[3] = floor(exp2(23.0)*mod(Mantissa,exp2(-15.0)));\n ${t}\n rgba = rgba / 255.0; // values need to be normalized to [0,1]\n return rgba;\n }\n `)}}decodeUint8(){const t=i.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new r.GlslLibRoutine(`\n highp float decode(highp vec4 rgba) {\n rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255]\n ${t}\n highp float Sign = 1.0 - step(128.0,rgba[0])*2.0;\n highp float Exponent = 2.0 * mod(rgba[0],128.0) + step(128.0,rgba[1]) - 127.0;\n highp float Mantissa = mod(rgba[1],128.0)*65536.0 + rgba[2]*256.0 +rgba[3] + float(0x800000);\n highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 ));\n return Result;\n }\n `)}}static isLittleEndian(){const t=new ArrayBuffer(4),e=new Uint32Array(t),n=new Uint8Array(t);if(e[0]=3735928559,239===n[0])return!0;if(222===n[0])return!1;throw new Error("unknown endianness")}}e.EncodingGlslLib=i},9894:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FragColorGlslLib=void 0;const r=n(8520),i=n(5060);class o extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign({},this.setFragColor()),this.getColorAsFloat())}getCustomTypes(){return{}}setFragColor(){const t=(0,i.getGlsl)(this.context.glContext.version);return{setFragColor:new r.GlslLibRoutine(`\n void setFragColor(float value) {\n ${t.output} = encode(value);\n }\n `,["encoding.encode"])}}getColorAsFloat(){return{getColorAsFloat:new r.GlslLibRoutine("\n float getColorAsFloat(vec4 color) {\n return decode(color);\n }\n ",["encoding.decode"])}}}e.FragColorGlslLib=o},2848:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.replaceInlines=void 0;const n=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm;e.replaceInlines=function(t){const e={};let r;for(;null!==(r=n.exec(t));){const t=r[3].split(",").map((t=>{const e=t.trim().split(" ");return e&&2===e.length?{type:e[0],name:e[1]}:null})).filter((t=>null!==t));e[r[2]]={params:t,body:r[4]}}for(const n in e){const i="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;".replace("__FUNC__",n),o=new RegExp(i,"gm");for(;null!==(r=o.exec(t));){const i=r[1],o=r[2],a=r[3].split(","),s=i?`${i} ${o};`:"";let u=e[n].body,c="";e[n].params.forEach(((t,e)=>{t&&(c+=`${t.type} ${t.name} = ${a[e]};\n`)})),u=`${c}\n ${u}`,u=u.replace("return",`${o} = `);const l=`\n ${s}\n {\n ${u}\n }\n `;t=t.replace(r[0],l)}}return t.replace(n,"")}},8879:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GlslPreprocessor=void 0;const r=n(8520),i=n(2848),o=n(5483),a=n(5060);e.GlslPreprocessor=class{constructor(t,e,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new r.GlslContext(t,e,n,i),Object.keys(o.glslRegistry).forEach((t=>{const e=new o.glslRegistry[t](this.context);this.libs[t]=e}));const a=this.glslLibRoutineDependencyGraph;for(const t in this.libs){const e=this.libs[t].getFunctions();for(const n in e){const i=t+"."+n;let o;a[i]?(o=a[i],o.routineBody=e[n].routineBody):(o=new r.GlslLibRoutineNode(i,e[n].routineBody),a[i]=o);const s=e[n].dependencies;if(s)for(let t=0;t{const r=n.split(".")[1];-1!==t.indexOf(r)&&e.push(this.glslLibRoutineDependencyGraph[n])})),r.TopologicalSortGlslRoutines.returnOrderedNodes(e)}getUniforms(t,e){const n=[];if(t)for(const e of t)n.push(`uniform sampler2D ${e};`);if(e)for(const t of e)n.push(`uniform ${t.type} ${t.name}${t.arrayLength?`[${t.arrayLength}]`:""};`);return n.join("\n")}}},5483:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.glslRegistry=void 0;const r=n(5107),i=n(7341),o=n(9894),a=n(2655),s=n(3891);e.glslRegistry={encoding:i.EncodingGlslLib,fragcolor:o.FragColorGlslLib,vec:s.VecGlslLib,shapeUtils:a.ShapeUtilsGlslLib,coordinates:r.CoordsGlslLib}},2655:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ShapeUtilsGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},this.bcastIndex()),this.bcastMatmulIndex()),this.offsetToIndices()),this.indicesToOffset()),this.incrementIndices())}getCustomTypes(){return{}}bcastIndex(){const t=this.context.outputTextureLayout.shape.length,e={};return this.context.programInfo.inputNames.forEach(((n,i)=>{const o=this.context.inputTextureLayouts[i].unpackedShape;if(o.length<=t){const i=o.length,a=t-i,s=`bcastIndices_${n}`;let u="";for(let t=0;t{const o=this.context.inputTextureLayouts[i].shape;if(!(o.length<2||o.length>t)){const i=o.length,a=t-i,s=`bcastMatmulIndices_${n}`;let u="";for(let t=0;t{const o=this.context.inputTextureLayouts[n].shape,a=this.context.inputTextureLayouts[n].strides,s=o.length;let u=`indicesToOffset_${e}`;t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,s,a)),u=`indicesToOffset_${e}_T`,t[u]=new r.GlslLibRoutine(i.indexToOffsetSingle(u,s,a.slice().reverse()))})),t}static indexToOffsetSingle(t,e,n){let r="";for(let t=e-1;t>=0;--t)r+=`\n offset += indices[${t}] * ${n[t]};\n `;return`\n int ${t}(int indices[${e}]) {\n int offset = 0;\n ${r}\n return offset;\n }\n `}offsetToIndices(){const t={};return this.context.programInfo.inputNames.forEach(((e,n)=>{const o=this.context.inputTextureLayouts[n].shape,a=this.context.inputTextureLayouts[n].strides,s=o.length;let u=`offsetToIndices_${e}`;t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,s,a)),u=`offsetToIndices_${e}_T`,t[u]=new r.GlslLibRoutine(i.offsetToIndicesSingle(u,s,a.slice().reverse()))})),t}static offsetToIndicesSingle(t,e,n){const r=[];for(let t=0;t{const i=this.context.inputTextureLayouts[n].shape,o=i.length,a=`incrementIndices_${e}`;let s="";for(let t=0;t= 0; --i) {\n if(i > axis) continue;\n indices[i] += 1;\n if(indices[i] < shape[i]) {\n break;\n }\n indices[i] = 0;\n }\n }\n `;t[a]=new r.GlslLibRoutine(u)})),t}}e.ShapeUtilsGlslLib=i},5060:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultFragShaderMain=e.getFragShaderPreamble=e.getVertexShaderSource=e.getGlsl=void 0;const n={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},r={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"};function i(t){return 1===t?n:r}e.getGlsl=i,e.getVertexShaderSource=function(t){const e=i(t);return`${e.version}\n precision highp float;\n ${e.attribute} vec3 position;\n ${e.attribute} vec2 textureCoord;\n\n ${e.varyingVertex} vec2 TexCoords;\n\n void main()\n {\n gl_Position = vec4(position, 1.0);\n TexCoords = textureCoord;\n }`},e.getFragShaderPreamble=function(t){const e=i(t);return`${e.version}\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n ${e.varyingFrag} vec2 TexCoords;\n ${e.outputDeclaration}\n const vec2 halfCR = vec2(0.5, 0.5);\n\n // Custom vector types to handle higher dimenalities.\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n `},e.getDefaultFragShaderMain=function(t,e){return`\n void main() {\n int indices[${e}];\n toVec(TexCoords, indices);\n vec4 result = vec4(process(indices));\n ${i(t).output} = result;\n }\n `}},3891:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VecGlslLib=void 0;const r=n(8520);class i extends r.GlslLib{constructor(t){super(t)}getCustomTypes(){return{}}getFunctions(){return Object.assign(Object.assign(Object.assign(Object.assign({},this.binaryVecFunctions()),this.copyVec()),this.setVecItem()),this.getVecItem())}binaryVecFunctions(){const t=this.context.outputTextureLayout.shape.length,e={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(const i in e){const o=`${i}Vec`;let a="";for(let n=0;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLInferenceHandler=void 0;const r=n(6231),i=n(9162),o=n(2517),a=n(2403),s=n(7019),u=n(8710),c=n(5611),l=n(4057),p=n(2039);e.WebGLInferenceHandler=class{constructor(t){this.session=t,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(t,e){return(0,l.calculateTextureWidthAndHeight)(this.session.layoutStrategy,t,e)}executeProgram(t,e){if(e.length{const n=e.map((t=>`${t.unpackedShape.join(",")};${t.width}x${t.height}`)).join("_");let r=t.name;return t.cacheHint&&(r+="["+t.cacheHint+"]"),r+=":"+n,r})(t,n);let i=this.session.programManager.getArtifact(r);const o=i?i.programInfo:"function"==typeof t.get?t.get():t,a=(0,l.createTextureLayoutFromTextureType)(this.session.layoutStrategy,o.output.dims,o.output.textureType),s=this.createTextureData(a,o.output.type);return i||(i=this.session.programManager.build(o,n,s),this.session.programManager.setArtifact(r,i)),this.runProgram(i,n,s),s}run(t,e){return this.executeProgram(t,e).tensor}runProgram(t,e,n){for(let n=0;nthis.readTexture(a)),(async t=>this.readTextureAsync(a)),void 0,o),texture:n});return this.setTextureData(a.tensor.dataId,a,t.isPacked),a}getTextureData(t,e=!1){return this.session.isInitializer(t)?this.session.getTextureData(t,e):e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){this.session.isInitializer(t)?this.session.setTextureData(t,e,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(t,e)}isTextureLayoutCached(t,e=!1){return!!this.getTextureData(t.dataId,e)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((t=>this.session.textureManager.releaseTexture(t))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((t=>this.session.textureManager.releaseTexture(t))),this.unpackedTextureDataCache=new Map}readTexture(t){return t.isPacked?this.readTexture(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}async readTextureAsync(t){return t.isPacked?this.readTextureAsync(this.unpack(t)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(t,t.tensor.type,t.channels):this.session.textureManager.readUint8TextureAsFloat((0,u.encodeAsUint8)(this,t))}pack(t){return this.executeProgram((0,a.createPackProgramInfoLoader)(this,t.tensor),[t.tensor])}unpack(t){return this.executeProgram((0,c.createUnpackProgramInfoLoader)(this,t.tensor),[t.tensor])}}},1640:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WEBGL_OP_RESOLVE_RULES=void 0;const a=n(2898),s=o(n(7839)),u=n(4196),c=n(2069),l=n(8138),p=n(9663),f=n(5193),d=n(7992),h=n(1253),g=n(4776),b=n(6572),m=n(3346),y=n(5623),_=n(2870),v=n(2143),w=n(4939),x=n(718),T=n(2268),S=n(8117),O=n(2278),A=n(5524),E=n(5975),I=n(3933),P=n(6558),D=n(5723),$=n(3738),k=o(n(4909)),C=n(8428),F=n(9793);e.WEBGL_OP_RESOLVE_RULES=[["Abs","","6+",k.abs],["Acos","","7+",k.acos],["Add","","7+",s.add],["And","","7+",s.and],["Asin","","7+",k.asin],["Atan","","7+",k.atan],["AveragePool","","7+",v.averagePool,v.parseAveragePoolAttributes],["BatchNormalization","","7+",a.batchNormalization,a.parseBatchNormalizationAttributes],["Cast","","6+",u.cast,u.parseCastAttributes],["Ceil","","6+",k.ceil],["Clip","","6-10",k.clip,k.parseClipAttributes],["Clip","","11+",k.clipV11],["Concat","","4+",c.concat,c.parseConcatAttributes],["Conv","","1+",l.conv,l.parseConvAttributes],["ConvTranspose","","1+",p.convTranspose,p.parseConvTransposeAttributes],["Cos","","7+",k.cos],["Div","","7+",s.div],["Dropout","","7+",k.identity],["DepthToSpace","","1+",f.depthToSpace,f.parseDepthToSpaceAttributes],["Equal","","7+",s.equal],["Elu","","6+",k.elu,k.parseEluAttributes],["Exp","","6+",k.exp],["Flatten","","1+",d.flatten,d.parseFlattenAttributes],["Floor","","6+",k.floor],["FusedConv","com.microsoft","1+",l.conv,l.parseConvAttributes],["Gather","","1+",h.gather,h.parseGatherAttributes],["Gemm","","7-10",g.gemm,g.parseGemmAttributesV7],["Gemm","","11+",g.gemm,g.parseGemmAttributesV11],["GlobalAveragePool","","1+",v.globalAveragePool,v.parseGlobalAveragePoolAttributes],["GlobalMaxPool","","1+",v.globalMaxPool],["Greater","","7+",s.greater],["Identity","","1+",k.identity],["ImageScaler","","1+",b.imageScaler,b.parseImageScalerAttributes],["InstanceNormalization","","6+",m.instanceNormalization,m.parseInstanceNormalizationAttributes],["LeakyRelu","","6+",k.leakyRelu,k.parseLeakyReluAttributes],["Less","","7+",s.less],["Log","","6+",k.log],["MatMul","","1+",y.matMul,y.parseMatMulAttributes],["MaxPool","","1+",v.maxPool,v.parseMaxPoolAttributes],["Mul","","7+",s.mul],["Neg","","6+",k.neg],["Not","","1+",k.not],["Or","","7+",s.or],["Pad","","2-10",_.padV2,_.parsePadAttributesV2],["Pad","","11+",_.padV11,_.parsePadAttributesV11],["Pow","","7+",s.pow],["PRelu","","7+",s.pRelu],["ReduceLogSum","","1+",w.reduceLogSum,w.parseReduceAttributes],["ReduceMax","","1+",w.reduceMax,w.parseReduceAttributes],["ReduceMean","","1+",w.reduceMean,w.parseReduceAttributes],["ReduceMin","","1+",w.reduceMin,w.parseReduceAttributes],["ReduceProd","","1+",w.reduceProd,w.parseReduceAttributes],["ReduceSum","","1-12",w.reduceSum,w.parseReduceAttributes],["ReduceSumSquare","","1+",w.reduceLogSumSquare,w.parseReduceAttributes],["Relu","","6+",k.relu],["Reshape","","5+",x.reshape],["Resize","","10",T.resize,T.parseResizeAttributesV10],["Resize","","11+",T.resize,T.parseResizeAttributesV11],["Shape","","1+",S.shape],["Sigmoid","","6+",k.sigmoid],["Sin","","7+",k.sin],["Slice","","10+",O.sliceV10],["Slice","","1-9",O.slice,O.parseSliceAttributes],["Softmax","","1-12",A.softmax,A.parseSoftmaxAttributes],["Softmax","","13+",A.softmaxV13,A.parseSoftmaxAttributesV13],["Split","","2-12",E.split,E.parseSplitAttributes],["Sqrt","","6+",k.sqrt],["Squeeze","","1-12",I.squeeze,I.parseSqueezeAttributes],["Squeeze","","13+",I.squeezeV13],["Sub","","7+",s.sub],["Sum","","6+",P.sum],["Tan","","7+",k.tan],["Tanh","","6+",k.tanh],["Tile","","6+",D.tile],["Transpose","","1+",$.transpose,$.parseTransposeAttributes],["Upsample","","7-8",F.upsample,F.parseUpsampleAttributesV7],["Upsample","","9",F.upsample,F.parseUpsampleAttributesV9],["Unsqueeze","","1-12",C.unsqueeze,C.parseUnsqueezeAttributes],["Unsqueeze","","13+",C.unsqueezeV13],["Xor","","7+",s.xor]]},2898:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseBatchNormalizationAttributes=e.batchNormalization=void 0;const r=n(246),i=n(5060),o=n(2039),a={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]};e.batchNormalization=(t,e,n)=>(u(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>s(t,e,n)}),e)]),e.parseBatchNormalizationAttributes=t=>{const e=t.attributes.getFloat("epsilon",1e-5),n=t.attributes.getFloat("momentum",.9),i=t.attributes.getInt("spatial",1);return(0,r.createAttributeWithCacheKey)({epsilon:e,momentum:n,spatial:i})};const s=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),s=e[0].dims.length,[u,c]=t.calculateTextureWidthAndHeight(e[1].dims,o.TextureType.unpacked),l=`\n float process(int[${s}] indices) {\n vec2 position = offsetToCoords(indices[1], ${u}, ${c});\n float scale = getColorAsFloat(${r.texture2D}(Scale, position));\n float mean = getColorAsFloat(${r.texture2D}(Mean, position));\n float variance = getColorAsFloat(${r.texture2D}(Variance, position));\n float b = getColorAsFloat(${r.texture2D}(B, position));\n\n return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b;\n }`;return Object.assign(Object.assign({},a),{output:{dims:e[0].dims,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:l})},u=t=>{if(!t||5!==t.length)throw new Error("BatchNormalization requires 5 inputs.");const e=t[0],n=t[1],r=t[2],i=t[3],o=t[4];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length||1!==i.dims.length||1!==o.dims.length)throw new Error("invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1]||i.dims[0]!==e.dims[1]||o.dims[0]!==e.dims[1])throw new Error("invalid input shape.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type||"float32"!==i.type&&"float64"!==i.type||"float32"!==o.type&&"float64"!==o.type)throw new Error("invalid input tensor types.")}},7839:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.xor=e.sub=e.pRelu=e.pow=e.or=e.mul=e.less=e.greater=e.equal=e.div=e.and=e.add=e.glslPRelu=e.glslPow=e.glslXor=e.glslOr=e.glslAnd=e.glslLess=e.glslGreater=e.glslEqual=e.glslSub=e.glslMul=e.glslDiv=e.glslAdd=void 0;const r=n(2517),i=n(8520),o=n(5060),a=n(2039);function s(){const t="add_";return{body:`\n float ${t}(float a, float b) {\n return a + b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 + v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function u(){const t="div_";return{body:`\n float ${t}(float a, float b) {\n return a / b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 / v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function c(){const t="mul_";return{body:`\n float ${t}(float a, float b) {\n return a * b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 * v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function l(){const t="sub_";return{body:`\n float ${t}(float a, float b) {\n return a - b;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return v1 - v2;\n }\n `,name:t,type:i.FunctionType.ValueBased}}function p(){const t="equal_";return{body:`\n float ${t}(float a, float b) {\n return float(a == b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4(equal(v1, v2));\n }\n `,name:t,type:i.FunctionType.ValueBased}}function f(){const t="greater_";return{body:`\n float ${t}(float a, float b) {\n return float(a > b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4( v1.r > v2.r ,\n v1.g > v2.g,\n v1.b > v2.b,\n v1.a > v2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function d(){const t="less_";return{body:`\n float ${t}(float a, float b) {\n return float(a < b);\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4( v1.r < v2.r ,\n v1.g < v2.g,\n v1.b < v2.b,\n v1.a < v2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function h(){const t="and_";return{body:`\n float ${t}(float a, float b) {\n return float( bool(a) && bool(b) );\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r && b2.r ,\n b1.g && b2.g,\n b1.b && b2.b,\n b1.a && b2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function g(){const t="or_";return{body:`\n float ${t}(float a, float b) {\n return float( bool(a) || bool(b) );\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r || b2.r ,\n b1.g || b2.g,\n b1.b || b2.b,\n b1.a || b2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function b(){const t="xor_";return{body:`\n float ${t}(float a, float b) {\n return float( bool(a) ^^ bool(b) );\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n bvec4 b1 = bvec4(v1);\n bvec4 b2 = bvec4(v2);\n return vec4( b1.r ^^ b2.r ,\n b1.g ^^ b2.g,\n b1.b ^^ b2.b,\n b1.a ^^ b2.a );\n }\n `,name:t,type:i.FunctionType.ValueBased}}function m(){return function(t){const e=`${t}_`;return{body:`\n float ${e}(float a, float b) {\n return ${t}(a, b);\n }\n vec4 ${e}(vec4 v1, vec4 v2) {\n return ${t}(v1, v2);\n }\n `,name:e,type:i.FunctionType.ValueBased}}("pow")}function y(){const t="prelu_";return{body:`\n float ${t}(float a, float b) {\n return a < 0.0 ? a * b: a;\n }\n vec4 ${t}(vec4 v1, vec4 v2) {\n return vec4(\n v1.r < 0.0 ? v1.r * v2.r: v1.r,\n v1.g < 0.0 ? v1.g * v2.g: v1.g,\n v1.b < 0.0 ? v1.b * v2.b: v1.b,\n v1.a < 0.0 ? v1.a * v2.a: v1.a\n );\n }\n `,name:t,type:i.FunctionType.ValueBased}}e.glslAdd=s,e.glslDiv=u,e.glslMul=c,e.glslSub=l,e.glslEqual=p,e.glslGreater=f,e.glslLess=d,e.glslAnd=h,e.glslOr=g,e.glslXor=b,e.glslPow=m,e.glslPRelu=y;const _=(t,e,n,r=e[0].type,i)=>{const o=t.session.pack?a.TextureType.packed:a.TextureType.unpacked;return{name:n.name,inputNames:["A","B"],inputTypes:[o,o],cacheHint:i,get:()=>v(t,e,n,r)}},v=(t,e,n,i=e[0].type)=>{const s=t.session.pack?a.TextureType.packed:a.TextureType.unpacked,u=!r.ShapeUtil.areEqual(e[0].dims,e[1].dims);let c=e[0].dims;const l=t.session.pack;if(u){const a=r.BroadcastUtil.calcShape(e[0].dims,e[1].dims,!1);if(!a)throw new Error("Can't perform binary op on the given tensors");c=a;const u=c.length,p=0!==e[0].dims.length?e[0].dims.length:1,f=0!==e[1].dims.length?e[1].dims.length:1,d=0!==e[0].dims.length?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",h=0!==e[1].dims.length?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",g=(0,o.getGlsl)(t.session.backend.glContext.version),b=l?`\n ${n.body}\n void main() {\n vec4 a = getAAtOutCoords();\n vec4 b = getBAtOutCoords();\n vec4 result = ${n.name}(a, b);\n ${g.output} = result;\n }`:`\n ${n.body}\n float process(int indices[${u}]) {\n int aindices[${p}];\n int bindices[${f}];\n ${d}\n ${h}\n return ${n.name}(_A(aindices), _B(bindices));\n }`;return{name:n.name,inputNames:["A","B"],inputTypes:[s,s],output:{dims:c,type:i,textureType:s},shaderSource:b,hasMain:l}}const p=(0,o.getGlsl)(t.session.backend.glContext.version),f=`\n ${n.body}\n void main() {\n vec4 v1 = ${p.texture2D}(A, TexCoords);\n vec4 v2 = ${p.texture2D}(B, TexCoords);\n vec4 result = ${n.name}(v1, v2);\n ${p.output} = result;\n }\n `;return{name:n.name,inputNames:["A","B"],inputTypes:[s,s],output:{dims:e[0].dims,type:i,textureType:s},shaderSource:f,hasMain:!0}};e.add=(t,e)=>[t.run(_(t,e,s()),e)],e.and=(t,e)=>[t.run(_(t,e,h(),"bool"),e)],e.div=(t,e)=>[t.run(_(t,e,u()),e)],e.equal=(t,e)=>[t.run(_(t,e,p(),"bool"),e)],e.greater=(t,e)=>[t.run(_(t,e,f(),"bool"),e)],e.less=(t,e)=>[t.run(_(t,e,d(),"bool"),e)],e.mul=(t,e)=>[t.run(_(t,e,c()),e)],e.or=(t,e)=>[t.run(_(t,e,g(),"bool"),e)],e.pow=(t,e)=>[t.run(_(t,e,m()),e)],e.pRelu=(t,e)=>[t.run(_(t,e,y()),e)],e.sub=(t,e)=>[t.run(_(t,e,l()),e)],e.xor=(t,e)=>[t.run(_(t,e,b(),"bool"),e)]},4196:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseCastAttributes=e.cast=void 0;const r=n(2517);e.cast=(t,e,n)=>(i(e),[t.cast(e[0],n)]),e.parseCastAttributes=t=>r.ProtoUtil.tensorDataTypeFromProto(t.attributes.getInt("to"));const i=t=>{if(!t||1!==t.length)throw new Error("Cast requires 1 input.");if("string"===t[0].type)throw new Error("Invalid input type.")}},1163:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedConcatProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827);e.createPackedConcatProgramInfoLoader=(t,e,n)=>{const u=(c=e.length,l=n.cacheKey,{name:"Concat (packed)",inputNames:Array.from({length:c},((t,e)=>`X${e}`)),inputTypes:Array(c).fill(i.TextureType.packed),cacheHint:l});var c,l;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const c=n[0].dims.slice();if(u>=c.length||u<-1*c.length)throw new Error("axis specified for concat doesn't match input dimensionality");u<0&&(u=c.length+u);const l=c.slice(0);for(let t=1;tt.dims)),b=(0,o.getGlChannels)(p),m=new Array(g.length-1);m[0]=g[0][u];for(let t=1;t= ${m[t-1]}) {\n return getChannel(\n getX${t}(${s(b,y,e)}),\n vec2(${s(_,y,e)}));\n }`}const x=m.length,T=m[m.length-1];w+=`\n return getChannel(\n getX${x}(${s(b,y,T)}),\n vec2(${s(_,y,T)}));`;const S=(0,r.getGlsl)(t.session.backend.glContext.version),O=`\n ${h}\n float getValue(${b.map((t=>"int "+t))}) {\n ${w}\n }\n\n void main() {\n ${d} coords = getOutputCoords();\n int lastDim = coords.${b[p-1]};\n coords.${b[p-1]} = coords.${b[p-2]};\n coords.${b[p-2]} = lastDim;\n\n vec4 result = vec4(getValue(${f}), 0., 0., 0.);\n\n ${f[p-1]} = ${f[p-1]} + 1;\n if (${f[p-1]} < ${l[p-1]}) {\n result.g = getValue(${f});\n }\n\n ${f[p-2]} = ${f[p-2]} + 1;\n if (${f[p-2]} < ${l[p-2]}) {\n result.a = getValue(${f});\n }\n\n ${f[p-1]} = ${f[p-1]} - 1;\n if (${f[p-2]} < ${l[p-2]} &&\n ${f[p-1]} < ${l[p-1]}) {\n result.b = getValue(${f});\n }\n ${S.output} = result;\n }\n `;return Object.assign(Object.assign({},e),{output:{dims:l,type:n[0].type,textureType:i.TextureType.packed},shaderSource:O,hasMain:!0})})(t,u,e,n.axis)})};const s=(t,e,n)=>{const r=t.indexOf(e);return t.map(((t,e)=>e===r?`${t} - ${n}`:t)).join()}},2069:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConcatAttributes=e.concat=void 0;const r=n(246),i=n(2039),o=n(1163);e.concat=(t,e,n)=>(p(e),t.session.pack&&e[0].dims.length>1?[t.run((0,o.createPackedConcatProgramInfoLoader)(t,e,n),e)]:[t.run(a(t,e,n),e)]);const a=(t,e,n)=>{const r=(o=e.length,a=n.cacheKey,{name:"Concat",inputNames:Array.from({length:o},((t,e)=>`X${e}`)),inputTypes:Array(o).fill(i.TextureType.unpacked),cacheHint:a});var o,a;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice();if(r>=o.length||r<-1*o.length)throw new Error("axis specified for concat doesn't match input dimensionality");r<0&&(r=o.length+r);const a=o.slice(0);for(let t=1;t`int getTextureWhereDataResides(int index) {\n ${t.map(((t,e)=>`if(index<${t}) {return ${e};}\n`)).join("")}\n }`,u=t=>s(t),c=(t,e)=>{const n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${e}]) {`];for(let e=0;e{const e=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;n(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis")});const p=t=>{if(!t||t.length<1)throw new Error("too few inputs");const e=t[0].type,n=t[0].dims.length;if("string"===e)throw new Error("string tensor is not supported yet");for(const r of t){if(r.type!==e)throw new Error("input tensors should be one type");if(r.dims.length!==n)throw new Error("input tensors should have the same shape")}}},4770:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackedGroupedConvProgramInfoLoader=void 0;const r=n(6231),i=n(5060),o=n(2039),a=n(8138),s=n(2823);e.createUnpackedGroupedConvProgramInfoLoader=(t,e,n)=>{const u=(c=e.length>2,l=n.cacheKey,{name:"GroupedConv",inputNames:c?["X","W","Bias"]:["X","W"],inputTypes:c?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:l});var c,l;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,u)=>{const c=e.length>2?"value += getBias(output_channel);":"",l=e[0].dims.slice(),p=e[1].dims.slice(),f=p[0]/u.group;r.Logger.verbose("GroupedConv",`autpPad:${u.autoPad}, dilations:${u.dilations}, group:${u.group}, kernelShape:${u.kernelShape}, pads:${u.pads}, strides:${u.strides}`);const d=(0,a.calculateOutputShape)(l,p,u.dilations,u.pads,u.strides),h=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:g,applyActivation:b}=(0,s.getActivationSnippet)(u),m=`\n const ivec2 strides = ivec2(${u.strides[0]}, ${u.strides[1]});\n const ivec2 pads = ivec2(${u.pads[0]}, ${u.pads[1]});\n ${g}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n ivec2 xRCCorner = coords.zw * strides - pads;\n int group_id = output_channel / ${f};\n\n float value = 0.0;\n for (int wInChannel = 0; wInChannel < ${p[1]}; wInChannel++) {\n int input_channel = group_id * ${p[1]} + wInChannel;\n for (int wHeight = 0; wHeight < ${p[2]}; wHeight++) {\n int xHeight = xRCCorner.x + wHeight * ${u.dilations[0]};\n\n if (xHeight < 0 || xHeight >= ${l[2]}) {\n continue;\n }\n\n for (int wWidth = 0; wWidth < ${p[3]}; wWidth++) {\n int xWidth = xRCCorner.y + wWidth * ${u.dilations[1]};\n if (xWidth < 0 || xWidth >= ${l[3]}) {\n continue;\n }\n\n float xVal = getX(batch, input_channel, xWidth, xHeight);\n float wVal = getW(output_channel, wInChannel, wWidth, wHeight);\n value += xVal*wVal;\n }\n }\n }\n ${c}\n ${b}\n ${h.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:d,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:m,hasMain:!0})})(t,e,u,n)})}},1386:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.conv2DPacked=e.conv2DPackedPointwise=void 0;const r=n(8138),i=n(8555),o=n(708);e.conv2DPackedPointwise=(t,e,n)=>{const i=e[0].dims,a=e[1].dims,s=(0,r.calculateOutputShape)(i,a,n.dilations,n.pads,n.strides),u=t.reshapePacked(e[0],[i[1],i[2]*i[3]]),c=t.reshapePacked(e[1],[a[0],a[1]]),l=e.length>2?[c,u,e[2]]:[c,u],p=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,l,n),l);return t.reshapePacked(p,s)},e.conv2DPacked=(t,e,n)=>{const a=e[0].dims,s=e[1].dims,u=(0,r.calculateOutputShape)(a,s,n.dilations,n.pads,n.strides),c=t.run((0,i.createPackedIm2ColProgramInfoLoader)(t,e[0],e[1],u,n),[e[0]]),l=t.reshapePacked(e[1],[s[0],s[1]*s[2]*s[3]]),p=3===e.length?[l,c,e[2]]:[l,c],f=t.run((0,o.createPackedMatmulProgramInfoLoader)(t,p,n),p);return t.reshapePacked(f,u)}},9663:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvTransposeAttributes=e.convTranspose=void 0;const r=n(246),i=n(5060),o=n(2039),a=n(2823),s=(t,e,n,r,i,o)=>(t-1)*e+n+(r-1)*i+1-o,u=(t,e,n,r,i)=>{const o=Math.floor(t/2);"SAME_UPPER"===e?(n[r]=o,n[i]=t-o):"SAME_LOWER"===e&&(n[r]=t-o,n[i]=o)};e.convTranspose=(t,e,n)=>(f(e,n),c(t,e,n));const c=(t,e,n)=>{const r=p(n,e);return[l(t,e,r)]},l=(t,e,n)=>t.run(((t,e,n)=>{const r=(s=e.length>2,u=n.cacheKey,{name:"ConvTranspose",inputNames:s?["X","W","B"]:["X","W"],inputTypes:s?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],cacheHint:u});var s,u;return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const s=e.length>2?"getB(output_channel)":"0.0",u=e[0].dims,c=e[1].dims,l=c[1],p=c[0]/r.group,f=[e[0].dims[0],e[1].dims[1]*r.group,...r.outputShape],d=(0,i.getGlsl)(t.session.backend.glContext.version),{activationFunction:h,applyActivation:g}=(0,a.getActivationSnippet)(r),b=`\n const ivec2 strides = ivec2(${r.strides[0]}, ${r.strides[1]});\n const ivec2 pads = ivec2(${r.pads[0]}, ${r.pads[1]});\n ${h}\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n int output_channel = coords.y;\n\n ivec2 loc = coords.zw + pads;\n\n int group_id = output_channel / ${l};\n int wOutChannel = output_channel - group_id * ${l};\n\n float value = ${s};\n for (int inChannelOffset = 0; inChannelOffset < ${p}; inChannelOffset++) {\n int input_channel = group_id * ${p} + inChannelOffset;\n for (int wWOff = 0; wWOff < ${c[2]}; wWOff++) {\n for (int wHOff = 0; wHOff < ${c[3]}; wHOff++) {\n ivec2 wOff = ivec2(wWOff * ${r.dilations[0]}, wHOff * ${r.dilations[1]});\n ivec2 wLoc = loc - wOff;\n ivec2 wLocIn = wLoc / strides;\n if (\n wLocIn * strides == wLoc &&\n wLocIn.x >= 0 && wLocIn.x < ${u[2]} &&\n wLocIn.y >= 0 && wLocIn.y < ${u[3]}\n ) {\n float xVal = getX(batch, input_channel, wLocIn.y, wLocIn.x);\n float wVal = getW(input_channel, wOutChannel, wHOff, wWOff);\n value += xVal * wVal;\n }\n }\n }\n }\n ${g}\n ${d.output} = vec4(value, .0, .0, .0);\n }\n`;return Object.assign(Object.assign({},n),{output:{dims:f,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:b,hasMain:!0})})(t,e,r,n)})})(t,e,n),e),p=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t{const l=t.length-2,p=0===c.length;for(let f=0;f{const e=t.attributes,n=(0,a.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),s=e.getInt("group",1),u=e.getInts("kernel_shape",[]),c=e.getInts("output_padding",[0,0]),l=e.getInts("output_shape",[]),p=e.getInts("pads",[0,0,0,0]),f=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:s,kernelShape:u,outputPadding:c,outputShape:l,pads:p,strides:f},n))};const f=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[0])throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");const n=t[1].dims[1]*e.group;if(3===t.length&&(1!==t[2].dims.length||t[2].dims[0]!==n))throw new Error("invalid bias");const r=t[0].dims.length-2;if(e.dilations.length!==r)throw new Error(`dilations should be ${r}D`);if(e.strides.length!==r)throw new Error(`strides should be ${r}D`);if(e.pads.length!==2*r)throw new Error(`pads should be ${2*r}D`);if(e.outputPadding.length!==r)throw new Error(`output_padding should be ${r}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if(0!==e.outputShape.length&&e.outputShape.length!==t[0].dims.length-2)throw new Error("invalid output shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("ConvTranspose input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("ConvTranspose input(bias) should be float tensor")}},8138:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseConvAttributes=e.conv=e.calculateOutputShape=void 0;const r=n(246),i=n(2517),o=n(4770),a=n(1386),s=n(9828),u=n(2823),c=n(3248),l=n(5623);e.calculateOutputShape=(t,e,n,r,i)=>{const o=t[0],a=t.slice(2),s=a.length,u=e[0],c=e.slice(2).map(((t,e)=>t+(t-1)*(n[e]-1))),l=a.map(((t,e)=>t+r[e]+r[e+s])).map(((t,e)=>Math.floor((t-c[e]+i[e])/i[e])));return[o,u].concat(...l)},e.conv=(t,e,n)=>(g(e,n),p(t,e,n));const p=(t,e,n)=>{const r=h(n,e),i=t.session.pack,s=1===r.kernelShape[0]&&1===r.kernelShape[1];return r.group>1?[t.run((0,o.createUnpackedGroupedConvProgramInfoLoader)(t,e,r),e)]:s&&i?[f(t,e,r)]:i&&4===e[0].dims.length&&1===e[0].dims[0]&&!s?[(0,a.conv2DPacked)(t,e,r)]:[d(t,e,r)]},f=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,a=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),s=t.reshapeUnpacked(n[0],[i[1],i[2]*i[3]]),u=t.reshapeUnpacked(n[1],[o[0],o[1]]),c=n.length>2?[u,s,n[2]]:[u,s],p=t.run((0,l.createMatmulProgramInfoLoader)(c,r),c);return t.reshapeUnpacked(p,a)},d=(t,n,r)=>{const i=n[0].dims,o=n[1].dims,a=(0,e.calculateOutputShape)(i,o,r.dilations,r.pads,r.strides),u=t.run((0,c.createIm2ColProgramInfoLoader)(t,n[0],n[1],a,r),[n[0]]),l=3===n.length?[u,n[1],n[2]]:[u,n[1]];return t.run((0,s.createDotProductProgramInfoLoader)(t,n,a,r),l)},h=(t,e)=>{const n=t.kernelShape.slice();if(0===t.kernelShape.length)for(let t=2;t{const e=t.attributes,n=(0,u.parseInternalActivationAttributes)(e),i=e.getString("auto_pad","NOTSET"),o=e.getInts("dilations",[1,1]),a=e.getInt("group",1),s=e.getInts("kernel_shape",[]),c=e.getInts("pads",[0,0,0,0]),l=e.getInts("strides",[1,1]);return(0,r.createAttributeWithCacheKey)(Object.assign({autoPad:i,dilations:o,group:a,kernelShape:s,pads:c,strides:l},n))};const g=(t,e)=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Conv requires 2 or 3 inputs");if(4!==t[0].dims.length||4!==t[1].dims.length)throw new Error("currently only support 2-dimensional conv");if(t[0].dims[1]!==t[1].dims[1]*e.group)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(3===t.length&&(1!==t[2].dims.length||t[1].dims[0]!==t[2].dims[0]))throw new Error("invalid bias");const n=t[0].dims.length-2;if(e.dilations.length!==n)throw new Error(`dilations should be ${n}D`);if(e.strides.length!==n)throw new Error(`strides should be ${n}D`);if(e.pads.length!==2*n)throw new Error(`pads should be ${2*n}D`);if(0!==e.kernelShape.length&&e.kernelShape.length!==t[1].dims.length-2)throw new Error("invalid kernel shape");if("float32"!==t[0].type||"float32"!==t[1].type)throw new Error("Conv input(X,W) should be float tensor");if(3===t.length&&"float32"!==t[2].type)throw new Error("Conv input(bias) should be float tensor")}},5193:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseDepthToSpaceAttributes=e.depthToSpace=void 0;const r=n(3738);e.depthToSpace=(t,e,n)=>{i(e);const o=n.blocksize,a=o*o,s="DCR"===n.mode?[0,3,4,1,5,2]:[0,1,4,2,5,3],u="DCR"===n.mode?[e[0].dims[0],o,o,e[0].dims[1]/a,e[0].dims[2],e[0].dims[3]]:[e[0].dims[0],e[0].dims[1]/a,o,o,e[0].dims[2],e[0].dims[3]],c=t.reshapeUnpacked(e[0],u),l={perm:s,cacheKey:`${s}`},[p]=(0,r.transpose)(t,[c],l),f=[e[0].dims[0],e[0].dims[1]/a,e[0].dims[2]*o,e[0].dims[3]*o];return[t.reshapeUnpacked(p,f)]},e.parseDepthToSpaceAttributes=t=>{const e=t.attributes.getInt("blocksize");if(e<1)throw new Error(`blocksize must be >= 1, but got : ${e} for DepthToSpace`);const n=t.attributes.getString("mode","DCR");if("DCR"!==n&&"CRD"!==n)throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:e}};const i=t=>{if(1!==t.length)throw new Error(`DepthToSpace expect 1 inputs, but got ${t.length}`);if("string"===t[0].type||4!==t[0].dims.length)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}},9828:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createDotProductProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),a=n(2823),s=n(3248);e.createDotProductProgramInfoLoader=(t,e,n,u)=>{const c=((t,e)=>({name:"ConvDotProduct",inputNames:t?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:t?[o.TextureType.unpacked,o.TextureType.packedLastDimension,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.packedLastDimension],cacheKey:e.activationCacheKey}))(e.length>2,u);return Object.assign(Object.assign({},c),{get:()=>((t,e,n,u,c)=>{const l=n[0].dims,p=n[1].dims,f=[p[0],Math.ceil(l[1]*p[2]*p[3]/4)],d=(0,s.calculateIm2ColDims)(l,p,u),[h,g]=t.calculateTextureWidthAndHeight(f,o.TextureType.packedLastDimension),b=r.ShapeUtil.computeStrides(d),[m,y]=t.calculateTextureWidthAndHeight(d,o.TextureType.packedLastDimension),_=u.length,v=n.length<3?"0.0":"_B(b)",w=Math.ceil(l[1]*p[2]*p[3]/4),{activationFunction:x,applyActivation:T}=(0,a.getActivationSnippet)(c),S=(0,i.getGlsl)(t.session.backend.glContext.version),O=`\n${x}\nfloat process(int indices[${_}]) {\n int b[1];\n b[0] = indices[1];\n int im2col[4];\n im2col[0] = indices[0];\n im2col[1] = indices[2];\n im2col[2] = indices[3];\n int im2colOffset = im2col[0] * ${b[0]} + im2col[1] * ${b[1]} + im2col[2] * ${b[2]};\n int kernelOffset = indices[1] * ${f[1]};\n float value = ${v};\n for (int i = 0; i < ${w}; ++i) {\n vec2 im2colCoords = offsetToCoords(im2colOffset, ${m}, ${y});\n vec2 kernelCoords = offsetToCoords(kernelOffset, ${h}, ${g});\n value += dot(${S.texture2D}(Im2Col, im2colCoords), ${S.texture2D}(K, kernelCoords));\n ++im2colOffset;\n ++kernelOffset;\n }\n ${T}\n return value;\n}`;return Object.assign(Object.assign({},e),{output:{dims:u,type:n[0].type,textureType:o.TextureType.unpacked},shaderSource:O})})(t,c,e,n,u)})}},7992:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseFlattenAttributes=e.flatten=void 0;const r=n(2517);e.flatten=(t,e,n)=>{i(e,n);const o=r.ShapeUtil.flattenShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.parseFlattenAttributes=t=>t.attributes.getInt("axis",1);const i=(t,e)=>{if(!t||1!==t.length)throw new Error("Flatten requires 1 input.");const n=t[0].dims.length;if(0===n)throw new Error("scalar tensor is not supported.");if(e<-n||e>n)throw new Error("Invalid axis");if("string"===t[0].type)throw new Error("string tensor is not supported.")}},2823:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseInternalActivationAttributes=e.getActivationSnippet=void 0;const r=n(2517),i=n(4909);e.getActivationSnippet=function(t){let e;switch(t.activation){case"Relu":e=(0,i.glslRelu)();break;case"Sigmoid":e=(0,i.glslSigmoid)();break;case"Clip":e=(0,i.glslClip)(t.clipMin,t.clipMax);break;default:return{activationFunction:"",applyActivation:""}}const n=e.name;return{activationFunction:e.body,applyActivation:`value = ${n}_(value);`}},e.parseInternalActivationAttributes=t=>{const e=t.getString("activation","");if("Clip"===e){const[n,i]=t.getFloats("activation_params",[r.MIN_CLIP,r.MAX_CLIP]);return{activation:e,clipMax:i,clipMin:n,activationCacheKey:`${e}:${n},${i}`}}return{activation:e,activationCacheKey:e}}},1253:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseGatherAttributes=e.gather=void 0;const r=n(246),i=n(782),o=n(2517),a=n(2039);e.gather=(t,e,n)=>(c(e,n.axis),[t.run(u(t,e,n),e)]),e.parseGatherAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",0)});const s={name:"Gather",inputNames:["A","B"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},u=(t,e,n)=>{const r=Object.assign(Object.assign({},s),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const i=n[0].dims.slice(),s=n[1].dims.slice(),u=new Array(i.length+s.length-1);r=o.ShapeUtil.normalizeAxis(r,i.length);const c=[];for(let t=0;t{if(!t||2!==t.length)throw new Error("Gather requires 2 inputs.");const n=t[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(e<-n||e>n-1)throw new Error("Invalid axis.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invaid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invaid input type.")}},4776:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseGemmAttributesV11=e.parseGemmAttributesV7=e.gemm=void 0;const r=n(246),i=n(2517),o=n(2039);e.gemm=(t,e,n)=>(c(e,n),[t.run(s(e,n),e)]);const a=(t,e)=>{const n=0!==t.attributes.getInt("transA",0),i=0!==t.attributes.getInt("transB",0),o=t.attributes.getFloat("alpha",1),a=t.attributes.getFloat("beta",1);return(0,r.createAttributeWithCacheKey)({transA:n,transB:i,alpha:o,beta:a,isOptionalC:e})};e.parseGemmAttributesV7=t=>a(t,!1),e.parseGemmAttributesV11=t=>a(t,!0);const s=(t,e)=>{const n={name:"Gemm",inputNames:3===t.length?["A","B","C"]:["A","B"],inputTypes:3===t.length?[o.TextureType.unpacked,o.TextureType.unpacked,o.TextureType.unpacked]:[o.TextureType.unpacked,o.TextureType.unpacked],key:e.cacheKey};return Object.assign(Object.assign({},n),{get:()=>u(n,t,e)})},u=(t,e,n)=>{const r=e[0].dims.slice(),a=e[1].dims.slice(),[s,u]=i.GemmUtil.getShapeOfGemmResult(r,n.transA,a,n.transB,3===e.length?e[2].dims:void 0),c=[s,u];if(!c)throw new Error("Can't use gemm on the given tensors");let l=r[r.length-1],p="";n.transA&&(l=r[0]),n.transA&&n.transB?p="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?p="value += _A_T(a) * _B(b);":!n.transA&&n.transB?p="value += _A(a) * _B_T(b);":n.transA||n.transB||(p="value += _A(a) * _B(b);");const f=c.length,d=`\n float process(int indices[${f}]) {\n int a[${f}];\n int b[${f}];\n ${3===e.length?`int c[${e[2].dims.length}];`:""}\n\n copyVec(indices, a);\n copyVec(indices, b);\n ${3===e.length?"bcastIndices_C(indices, c);":""}\n\n float value = 0.0;\n for (int k=0; k<${l}; ++k) {\n a[${f-1}] = k;\n b[${f-2}] = k;\n ${p}\n }\n\n value = value * alpha;\n ${3===e.length?"value += beta * _C(c);":""}\n return value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:c,type:e[0].type,textureType:o.TextureType.unpacked},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:d})},c=(t,e)=>{if(!t)throw new Error("Input is missing");if(e.isOptionalC&&(t.length<2||t.length>3))throw new Error("Invaid input shape.");if(!e.isOptionalC&&3!==t.length)throw new Error("Gemm requires 3 inputs");if(3===t.length&&1!==t[2].dims.length&&2!==t[2].dims.length)throw new Error("Invalid input shape of C");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type||3===t.length&&"float32"!==t[2].type&&"float64"!==t[2].type)throw new Error("Invalid input type.");if(t[0].type!==t[1].type||3===t.length&&t[0].type!==t[2].type)throw new Error("Input types are mismatched")}},8555:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedIm2ColProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(2827);e.createPackedIm2ColProgramInfoLoader=(t,e,n,a,s)=>{const u=(c=s.cacheKey,{name:"Im2Col (packed)",inputNames:["A"],inputTypes:[i.TextureType.packed],cacheHint:c});var c;return Object.assign(Object.assign({},u),{get:()=>((t,e,n,a,s,u)=>{const c=n.dims,l=a.dims,p=s.length,f=[l[1]*l[2]*l[3],s[2]*s[3]],d=l[2]*l[3],h=(0,o.unpackFromChannel)(),g=(0,r.getGlsl)(t.session.backend.glContext.version);let b="";for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)b+=`\n blockIndex = rc.x + ${e};\n pos = rc.y + ${t};\n\n if(blockIndex < ${f[1]} && pos < ${f[0]}) {\n offsetY = int(blockIndex / (${s[p-1]})) * ${u.strides[0]} -\n ${u.pads[0]};\n d0 = offsetY + ${u.dilations[0]} * (imod(pos, ${d}) / ${l[2]});\n\n if(d0 < ${c[2]} && d0 >= 0) {\n offsetX = imod(blockIndex, ${s[p-1]}) * ${u.strides[1]} -\n ${u.pads[1]};\n d1 = offsetX + ${u.dilations[1]} * imod(imod(pos, ${d}), ${l[2]});\n\n if(d1 < ${c[3]} && d1 >= 0) {\n\n ch = int(float(pos)/ ${d}.);\n innerDims = vec2(d0, d1);\n result[${2*t+e}] = getChannel(\n getA(0, ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n\n `;const m=`\n ${h}\n\n void main() {\n ivec2 rc = getOutputCoords();\n vec4 result = vec4(0.0);\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n ${b}\n ${g.output} = result;\n }\n `;return Object.assign(Object.assign({},e),{output:{dims:f,type:n.type,textureType:i.TextureType.packed},shaderSource:m,hasMain:!0})})(t,u,e,n,a,s)})}},3248:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.calculateIm2ColDims=e.createIm2ColProgramInfoLoader=void 0;const r=n(2039);e.createIm2ColProgramInfoLoader=(t,n,i,o,a)=>{const s=(u=a.cacheKey,{name:"Im2Col",inputNames:["X"],inputTypes:[r.TextureType.unpacked],cacheHint:u});var u;return Object.assign(Object.assign({},s),{get:()=>((t,n,i,o,a,s)=>{const u=i.dims,c=o.dims,l=a.length,p=(0,e.calculateIm2ColDims)(u,c,a,4),f=`\n const int XC = ${u[1]};\n const int XH = ${u[2]};\n const int XW = ${u[3]};\n const int KH = ${s.kernelShape[0]};\n const int KW = ${s.kernelShape[1]};\n const int dilationH = ${s.dilations[0]};\n const int dilationW = ${s.dilations[1]};\n const int strideH = ${s.strides[0]};\n const int strideW = ${s.strides[1]};\n const int padH = ${s.pads[0]};\n const int padW = ${s.pads[1]};\n const int KHKW = KH*KW;\n const int XCKHKW = XC * KHKW;\n const int outputChannels = 4;\n vec4 process(int indices[${l}]) {\n int b = indices[0]; // batch size\n int oh = indices[1] * strideH - padH; //output height\n int ow = indices[2] * strideW - padW; //output width\n int p = indices[3] * outputChannels; //patch\n vec4 value = vec4(0.0);\n for(int i=0; i < outputChannels; ++i) {\n if(p < XCKHKW) {\n int patchC = p / KHKW;\n int patchH = (p - patchC*KHKW) / KW;\n int patchW = (p - patchC*KHKW) - patchH * KW;\n int xh2 = oh + patchH * dilationH;\n int xw2 = ow + patchW * dilationW;\n int x[${u.length}];\n x[0] = b;\n x[1] = patchC;\n x[2] = xh2;\n x[3] = xw2;\n if(xh2 >= 0 &&\n xh2 < XH &&\n xw2 >= 0 &&\n xw2 < XW) {\n value[i] = _X(x);\n }\n }\n ++p;\n }\n return value;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:p,type:i.type,textureType:r.TextureType.packedLastDimension},shaderSource:f})})(0,s,n,i,o,a)})},e.calculateIm2ColDims=(t,e,n,r=4)=>[n[0],n[2],n[3],Math.ceil(t[1]*e[2]*e[3]/r)]},6572:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseImageScalerAttributes=e.imageScaler=void 0;const r=n(246),i=n(2039);e.imageScaler=(t,e,n)=>(u(e),[t.run(a(t,e,n),e)]),e.parseImageScalerAttributes=t=>{const e=t.attributes.getFloat("scale"),n=t.attributes.getFloats("bias");return(0,r.createAttributeWithCacheKey)({scale:e,bias:n})};const o={name:"ImageScaler",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},a=(t,e,n)=>{const r=Object.assign(Object.assign({},o),{cacheHint:n.cacheKey});return Object.assign(Object.assign({},r),{get:()=>((t,e,n,r)=>{const o=n[0].dims.slice(),a=o.length,u=`\n ${s(r.bias.length)}\n float process(int indices[${a}]) {\n return _X(indices) * scale + getBias(bias, indices[1]);\n }`;return Object.assign(Object.assign({},e),{output:{dims:o,type:n[0].type,textureType:i.TextureType.unpacked},variables:[{name:"bias",type:"float",arrayLength:r.bias.length,data:r.bias},{name:"scale",type:"float",data:r.scale}],shaderSource:u})})(0,r,e,n)})},s=t=>{const e=[`float getBias(float bias[${t}], int channel) {`];for(let n=0;n{if(!t||1!==t.length)throw new Error("ImageScaler requires 1 input.");if(4!==t[0].dims.length)throw new Error("Invalid input shape.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")}},3346:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseInstanceNormalizationAttributes=e.instanceNormalization=void 0;const r=n(5060),i=n(2039);e.instanceNormalization=(t,e,n)=>{c(e);const r=t.run(a(e[0]),e);return[t.run(u(t,e[0],n,r.dims),[e[0],r,e[1],e[2]])]},e.parseInstanceNormalizationAttributes=t=>t.attributes.getFloat("epsilon",1e-5);const o={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[i.TextureType.unpacked]},a=t=>Object.assign(Object.assign({},o),{get:()=>((t,e)=>{const n=e.dims.slice(),r=n[1],o=n[2]*n[3],a=[n[0],r],s=`\n vec4 process(int[2] indices) {\n vec4 v = vec4(0.0);\n int a[4];\n a[0] = indices[0];\n a[1] = indices[1];\n float temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += x;\n }\n }\n float mean = temp / float(${o});\n temp = 0.0;\n for(int a2=0; a2<${n[2]}; a2++) {\n a[2] = a2;\n for(int a3=0; a3<${n[3]}; a3++) {\n a[3] = a3;\n float x = _X(a);\n temp += (x - mean) * (x - mean);\n }\n }\n v.r = mean;\n v.g = temp / float(${o});\n\n return v;\n }`;return Object.assign(Object.assign({},t),{output:{dims:a,type:e.type,textureType:i.TextureType.packedLastDimension},shaderSource:s})})(o,t)}),s={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[i.TextureType.unpacked,i.TextureType.packedLastDimension,i.TextureType.unpacked,i.TextureType.unpacked]},u=(t,e,n,o)=>{const a=Object.assign(Object.assign({},s),{cacheHint:`${n}`});return Object.assign(Object.assign({},a),{get:()=>((t,e,n,o,a)=>{const s=(0,r.getGlsl)(t.session.backend.glContext.version),[u,c]=t.calculateTextureWidthAndHeight(a,i.TextureType.packedLastDimension),[l,p]=[u/4,c],f=`\n vec4 get_MeanAndVariance(int[2] mv) {\n int offset = indicesToOffset_MeanAndVariance(mv);\n vec2 coords = offsetToCoords(offset, ${l}, ${p});\n return ${s.texture2D}(MeanAndVariance, coords);\n }\n\n float process(int[4] indices) {\n int mv[2];\n mv[0] = indices[0];\n mv[1] = indices[1];\n vec4 mean_and_variance = get_MeanAndVariance(mv);\n float mean = mean_and_variance.r;\n float variance = mean_and_variance.g;\n\n int sb[1];\n sb[0] = indices[1];\n float scale = _Scale(sb);\n float b = _B(sb);\n\n return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b;\n }`;return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i.TextureType.unpacked},variables:[{name:"epsilon",type:"float",data:o}],shaderSource:f})})(t,a,e,n,o)})},c=t=>{if(!t||3!==t.length)throw new Error("InstanceNormalization requires 3 inputs.");const e=t[0],n=t[1],r=t[2];if(e.dims.length<3||1!==n.dims.length||1!==r.dims.length)throw new Error("Invalid input shape.");if(n.dims[0]!==e.dims[1]||r.dims[0]!==e.dims[1])throw new Error("Input shapes are mismatched.");if("float32"!==e.type&&"float64"!==e.type||"float32"!==n.type&&"float64"!==n.type||"float32"!==r.type&&"float64"!==r.type)throw new Error("Invalid input type.");if(4!==t[0].dims.length)throw new Error("Only support 4-D input shape.")}},708:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackedMatmulProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),a=n(9390),s=n(2823),u=n(5623);e.createPackedMatmulProgramInfoLoader=(t,e,n)=>{const c=(l=e.length>2,p=n.activationCacheKey,{name:"MatMul (packed)",inputNames:l?["A","B","Bias"]:["A","B"],inputTypes:l?[o.TextureType.packed,o.TextureType.packed,o.TextureType.packed]:[o.TextureType.packed,o.TextureType.packed],cacheHint:p});var l,p;return Object.assign(Object.assign({},c),{get:()=>((t,e,n,c)=>{const l=n.length>2,p=l?"value += getBiasForMatmul();":"",f=n[0].dims,d=n[1].dims,h=r.BroadcastUtil.calcShape(f,d,!0),g=!r.ShapeUtil.areEqual(n[0].dims,n[1].dims);if(!h)throw new Error("Can't use matmul on the given tensors");const b=f[f.length-1],m=Math.ceil(b/2),y=f.length,_=d.length,v=(0,i.getGlsl)(t.session.backend.glContext.version),w=(0,a.getCoordsDataType)(h.length),x=h.length,T=(0,a.getGlChannels)(),{activationFunction:S,applyActivation:O}=(0,s.getActivationSnippet)(c),A=l?`${(0,u.getBiasForMatmul)(w,T,n[2].dims,h,!0)}`:"",E=g?`${function(t,e,n,i){let o=[],a=[];const s=n[0].dims,u=n[1].dims,c=s.length,l=u.length,p=i.length,f=p-c,d=p-l;o=s.map(((t,n)=>`coords.${e[n+f]}`)),o[c-1]="i*2",o.join(", "),a=u.map(((t,n)=>`coords.${e[n+d]}`)),a[l-2]="i*2",a.join(", ");const h=r.BroadcastUtil.getBroadcastDims(s,i),g=r.BroadcastUtil.getBroadcastDims(u,i),b=h.map((t=>`coords.${e[t+f]} = 0;`)).join("\n"),m=g.map((t=>`coords.${e[t+d]} = 0;`)).join("\n"),y=`int lastDim = coords.${e[p-1]};\n coords.${e[p-1]} = coords.${e[p-2]};\n coords.${e[p-2]} = lastDim;`;return`\nvec4 getAAtOutCoordsMatmul(int i) {\n ${t} coords = getOutputCoords();\n ${y}\n ${b}\n vec4 outputValue = getA(${o});\n return outputValue;\n}\n\nvec4 getBAtOutCoordsMatmul(int i) {\n ${t} coords = getOutputCoords();\n ${y}\n ${m}\n vec4 outputValue = getB(${a});\n return outputValue;\n}`}(w,T,n,h)}`:"",I=g?"getAAtOutCoordsMatmul(i)":`getA(${function(t,e){let n="";for(let r=0;r{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBiasForMatmul=e.createMatmulProgramInfoLoader=e.parseMatMulAttributes=e.matMul=void 0;const r=n(2517),i=n(2039),o=n(9390),a=n(2823),s=n(708);function u(t,e){const n=(s=t.length>2,u=e.activationCacheKey,{name:"MatMul",inputNames:s?["A","B","Bias"]:["A","B"],inputTypes:s?[i.TextureType.unpacked,i.TextureType.unpacked,i.TextureType.unpacked]:[i.TextureType.unpacked,i.TextureType.unpacked],cacheHint:u});var s,u;return Object.assign(Object.assign({},n),{get:()=>function(t,e,n){const s=e[0].dims,u=e[1].dims,c=r.BroadcastUtil.calcShape(s,u,!0);if(!c)throw new Error("Can't use matmul on the given tensors");const p=(0,o.getCoordsDataType)(c.length),f=(0,o.getGlChannels)(),{activationFunction:d,applyActivation:h}=(0,a.getActivationSnippet)(n),g=e.length>2,b=g?"value += getBiasForMatmul();":"",m=g?`${l(p,f,e[2].dims,c,!1)}`:"",y=c.length,_=s.length,v=u.length,w=`\n ${d}\n ${m}\n float process(int indices[${y}]) {\n int a[${_}];\n int b[${v}];\n bcastMatmulIndices_A(indices, a);\n bcastMatmulIndices_B(indices, b);\n\n float value;\n for (int k=0; k<${s[s.length-1]}; ++k) {\n a[${_-1}] = k;\n b[${v-2}] = k;\n value += _A(a) * _B(b);\n }\n ${b}\n ${h}\n return value;\n }`;return Object.assign(Object.assign({},t),{output:{dims:c,type:e[0].type,textureType:i.TextureType.unpacked},shaderSource:w})}(n,t,e)})}e.matMul=(t,e,n)=>(c(e),t.session.pack?[t.run((0,s.createPackedMatmulProgramInfoLoader)(t,e,n),e)]:[t.run(u(e,n),e)]),e.parseMatMulAttributes=t=>(0,a.parseInternalActivationAttributes)(t.attributes),e.createMatmulProgramInfoLoader=u;const c=t=>{if(!t||2!==t.length)throw new Error("MatMul requires 2 inputs.");if(t[0].dims[t[0].dims.length-1]!==t[1].dims[t[1].dims.length-2])throw new Error("shared dimension does not match.");if("float32"!==t[0].type&&"float64"!==t[0].type||"float32"!==t[1].type&&"float64"!==t[1].type)throw new Error("inputs should be float type");if(t[0].type!==t[1].type)throw new Error("inputs types should match")};function l(t,e,n,i,o){let a="";const s=n.length,u=i.length,c=u-s;a=u<2&&s>0?"coords":n.map(((t,n)=>`coords.${e[n+c]}`)).join(", ");const l=r.BroadcastUtil.getBroadcastDims(n,i).map((t=>`coords.${e[t+c]} = 0;`)).join("\n");let p="vec4(outputValue.xx, outputValue.yy)";return 1===r.ShapeUtil.size(n)&&(p="vec4(outputValue.x)"),o?`\nvec4 getBiasForMatmul() {\n ${t} coords = getOutputCoords();\n ${l}\n vec4 outputValue = getBias(${a});\n return ${p};\n}`:`\nfloat getBiasForMatmul() {\n ${t} coords = getOutputCoords();\n ${l}\n return getBias(coords.x);\n}`}e.getBiasForMatmul=l},2403:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createPackProgramInfoLoader=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827),s={name:"pack",inputNames:["A"],inputTypes:[i.TextureType.unpackedReversed]};e.createPackProgramInfoLoader=(t,e)=>Object.assign(Object.assign({},s),{get:()=>((t,e)=>{const n=(0,r.getGlsl)(t.session.backend.glContext.version),u=e.dims,c=u.length,l=e.dims.length,p=(0,o.getCoordsDataType)(l),f=(0,a.getChannels)("rc",l),d=(h=l,g=f,b=u[u.length-2],m=u[u.length-1],0===h||1===h?"":`\n int r = ${g[h-2]};\n int c = ${g[h-1]};\n int rp1 = ${g[h-2]} + 1;\n int cp1 = ${g[h-1]} + 1;\n bool rEdge = rp1 >= ${m};\n bool cEdge = cp1 >= ${b};\n `);var h,g,b,m;let y;y=0===c?[1,1]:1===c?[u[0],1]:[u[l-1],u[l-2]];const _=function(t,e,n){if(0===t)return"false";if(1===t)return`rc > ${e[0]}`;let r="";for(let i=t-2;i= ${e[i-t+2]}`,i= ${t[0]} ? 0. : getA(rc + 1),\n 0, 0`;let r="";if(n>2)for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.unpackFromChannel=e.getChannels=e.getVecChannels=void 0;const r=n(9390);function i(t,e){return(0,r.getGlChannels)(e).map((e=>`${t}.${e}`))}e.getVecChannels=i,e.getChannels=function(t,e){return 1===e?[t]:i(t,e)},e.unpackFromChannel=function(){return"\n float getChannel(vec4 frag, int dim) {\n int modCoord = imod(dim, 2);\n return modCoord == 0 ? frag.r : frag.g;\n }\n\n float getChannel(vec4 frag, vec2 innerDims) {\n vec2 modCoord = mod(innerDims, 2.);\n return modCoord.x == 0. ?\n (modCoord.y == 0. ? frag.r : frag.g) :\n (modCoord.y == 0. ? frag.b : frag.a);\n }\n "}},2870:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parsePadAttributesV11=e.padV11=e.parsePadAttributesV2=e.padV2=void 0;const r=n(246),i=n(2517),o=n(5060),a=n(2039),s={name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};e.padV2=(t,e,n)=>(l(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>c(t,e[0],n)}),e)]),e.parsePadAttributesV2=t=>{const e=t.attributes.getString("mode","constant"),n=t.attributes.getFloat("value",0),i=t.attributes.getInts("pads");return(0,r.createAttributeWithCacheKey)({mode:e,value:n,pads:i})},e.padV11=(t,n,r)=>{p(n);const i=u(t,n,r);return(0,e.padV2)(t,[n[0]],i)},e.parsePadAttributesV11=t=>t.attributes.getString("mode","constant");const u=(t,e,n)=>{if(!t.session.isInitializer(e[1].dataId)||e.length>=3&&!t.session.isInitializer(e[2].dataId))throw new Error("dynamic pad attributes are not allowed");const i=Array.from(e[1].integerData),o=e.length>=3?e[2].floatData[0]:0;return(0,r.createAttributeWithCacheKey)({mode:n,pads:i,value:o})},c=(t,e,n)=>{const r=i.ShapeUtil.padShape(e.dims.slice(),n.pads),o=r.length,s=`\n ${f(t,e,n)}\n float process(int[${o}] indices) {\n return padA(indices);\n }`;return{name:"Pad",inputNames:["A"],inputTypes:[a.TextureType.unpacked],output:{dims:r,type:e.type,textureType:a.TextureType.unpacked},shaderSource:s}},l=t=>{if(!t||1!==t.length)throw new Error("Pad requires 1 input");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},p=t=>{if(!t||2!==t.length&&3!==t.length)throw new Error("Pad requires 2 or 3 inputs");if("int32"!==t[1].type)throw new Error("Invalid input type.");if(t.length>=3&&"string"===t[2].type)throw new Error("Invalid input type.")},f=(t,e,n)=>{const r=(0,o.getGlsl)(t.session.backend.glContext.version),[s,u]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),c=i.ShapeUtil.computeStrides(e.dims);switch(n.mode){case"constant":return d(r,e.dims,c,s,u,n.pads,n.value);case"reflect":return h(r,e.dims,c,s,u,n.pads);case"edge":return g(r,e.dims,c,s,u,n.pads);default:throw new Error("Invalid mode")}},d=(t,e,n,r,i,o,a)=>{const s=e.length;let u="";for(let t=s-1;t>=0;--t)u+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) return constant;\n if (k >= ${e[t]}) return constant;\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${s}]) {\n const float constant = float(${a});\n int offset = 0;\n int k = 0;\n ${u}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `},h=(t,e,n,r,i,o)=>{const a=e.length;let s="";for(let t=a-1;t>=0;--t)s+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) { k = -k; }\n {\n const int _2n_1 = ${2*(e[t]-1)};\n k = int( mod( float(k), float(_2n_1) ) ) ;\n if(k >= ${e[t]}) { k = _2n_1 - k; }\n }\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${a}]) {\n int offset = 0;\n int k = 0;\n ${s}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `},g=(t,e,n,r,i,o)=>{const a=e.length;let s="";for(let t=a-1;t>=0;--t)s+=`\n k = m[${t}] - ${o[t]};\n if (k < 0) k = 0;\n if (k >= ${e[t]}) k = ${e[t]-1};\n offset += k * ${n[t]};\n `;return`\n float padA(int m[${a}]) {\n int offset = 0;\n int k = 0;\n ${s}\n vec2 coords = offsetToCoords(offset, ${r}, ${i});\n float value = getColorAsFloat(${t.texture2D}(A, coords));\n return value;\n }\n `}},2143:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.globalMaxPool=e.parseMaxPoolAttributes=e.maxPool=e.parseGlobalAveragePoolAttributes=e.globalAveragePool=e.parseAveragePoolAttributes=e.averagePool=void 0;const r=n(246),i=n(2517),o=n(2039);e.averagePool=(t,e,n)=>{p(e);const r={name:"AveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>a(e,r,!1,n)}),e)]},e.parseAveragePoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=0!==t.attributes.getInt("count_include_pad",0),o=t.attributes.getInts("kernel_shape"),a=t.attributes.getInts("strides",[]),s=t.attributes.getInts("pads",[]);if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:i,kernelShape:o,strides:a,pads:s})};const a=(t,e,n,r)=>{const[a,s]=u(t,r,n),c=i.ShapeUtil.size(a.kernelShape);let l="";a.countIncludePad?l+=`value /= float(${c});`:l+=`value /= float(${c} - pad);`;const p=`\n ${f(t[0].dims,a,"value += _X(x);",l,"0.0")}\n `;return Object.assign(Object.assign({},e),{output:{dims:s,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:p})};e.globalAveragePool=(t,e,n)=>{p(e);const r={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:`${n.countIncludePad}`};return[t.run(Object.assign(Object.assign({},r),{get:()=>a(e,r,!0,n)}),e)]},e.parseGlobalAveragePoolAttributes=t=>{const e=0!==t.attributes.getInt("count_include_pad",0);return(0,r.createAttributeWithCacheKey)({autoPad:"",ceilMode:0,countIncludePad:e,kernelShape:[],strides:[],pads:[]})},e.maxPool=(t,e,n)=>{p(e);const r={name:"MaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked],cacheHint:n.cacheKey};return[t.run(Object.assign(Object.assign({},r),{get:()=>s(e,r,!1,n)}),e)]},e.parseMaxPoolAttributes=t=>{const e=t.attributes.getString("auto_pad","NOTSET"),n=t.attributes.getInt("ceil_mode",0),i=t.attributes.getInts("kernel_shape"),o=t.attributes.getInts("strides",[]),a=t.attributes.getInts("pads",[]),s=t.attributes.getInt("storage_order",0),u=t.attributes.getInts("dilations",[]);if(0!==s)throw new Error("column major storage order is not yet supported for MaxPool");if(0!==n)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return(0,r.createAttributeWithCacheKey)({autoPad:e,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:o,pads:a,storageOrder:s,dilations:u})};const s=(t,e,n,r)=>{const[i,a]=u(t,r,n),s=`\n ${f(t[0].dims,i,"\n value = max(_X(x), value);\n ","","-1e5")}\n `;return Object.assign(Object.assign({},e),{output:{dims:a,type:t[0].type,textureType:o.TextureType.unpacked},shaderSource:s})},u=(t,e,n)=>{const r=t[0].dims.slice(),o=Object.hasOwnProperty.call(e,"dilations"),a=e.kernelShape.slice(),s=e.strides.slice(),u=o?e.dilations.slice():[],c=e.pads.slice();i.PoolConvUtil.adjustPoolAttributes(n,r,a,s,u,c);const l=i.PoolConvUtil.computePoolOutputShape(n,r,s,u,a,c,e.autoPad),p=Object.assign({},e);return o?Object.assign(p,{kernelShape:a,strides:s,pads:c,dilations:u,cacheKey:e.cacheKey}):Object.assign(p,{kernelShape:a,strides:s,pads:c,cacheKey:e.cacheKey}),[p,l]},c={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},l={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.globalMaxPool=(t,e)=>(p(e),[t.run(Object.assign(Object.assign({},l),{get:()=>s(e,l,!0,c)}),e)]);const p=t=>{if(!t||1!==t.length)throw new Error("Pool ops requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type.")},f=(t,e,n,r,o)=>{const a=t.length;if(e.kernelShape.length<=2){const i=e.kernelShape[e.kernelShape.length-1],s=e.strides[e.strides.length-1],u=e.pads[e.pads.length/2-1],c=e.pads[e.pads.length-1],l=t[a-1];let p="",f="",d="";if(p=u+c!==0?`\n for (int i = 0; i < ${i}; i++) {\n x[${a} - 1] = indices[${a} - 1] * ${s} - ${u} + i;\n if (x[${a} - 1] < 0 || x[${a} - 1] >= ${l}) {\n pad++;\n continue;\n }\n ${n}\n }`:`\n for (int i = 0; i < ${i}; i++) {\n x[${a} - 1] = indices[${a} - 1] * ${s} - ${u} + i;\n ${n}\n }`,2===e.kernelShape.length){const n=e.kernelShape[e.kernelShape.length-2],r=e.strides[e.strides.length-2],o=e.pads[e.pads.length/2-2],s=e.pads[e.pads.length-2],u=t[a-2];f=o+s!==0?`\n for (int j = 0; j < ${n}; j++) {\n x[${a} - 2] = indices[${a} - 2] * ${r} - ${o} + j;\n if (x[${a} - 2] < 0 || x[${a} - 2] >= ${u}) {\n pad+= ${i};\n continue;\n }\n `:`\n for (int j = 0; j < ${n}; j++) {\n x[${a} - 2] = indices[${a} - 2] * ${r} - ${o} + j;\n `,d="\n }\n "}return`\n float process(int indices[${a}]) {\n int x[${a}];\n copyVec(indices, x);\n\n float value = ${o};\n int pad = 0;\n ${f}\n ${p}\n ${d}\n ${r}\n return value;\n }\n `}{const s=i.ShapeUtil.size(e.kernelShape),u=i.ShapeUtil.computeStrides(e.kernelShape),c=u.length,l=e.pads.length,p=h(c),f=d(t,"inputDims"),g=d(e.pads,"pads"),b=d(u,"kernelStrides"),m=d(e.strides,"strides");let y="";return y=e.pads.reduce(((t,e)=>t+e))?`\n if (x[j] >= inputDims[j] || x[j] < 0) {\n pad++;\n isPad = true;\n break;\n }\n }\n if (!isPad) {\n ${n}\n }`:`\n }\n ${n}\n `,`\n ${p}\n float process(int indices[${a}]) {\n int x[${a}];\n copyVec(indices, x);\n int offset[${c}];\n int pads[${l}];\n int inputDims[${a}];\n int kernelStrides[${c}];\n int strides[${c}];\n ${g}\n ${f}\n ${m}\n ${b}\n\n float value = ${o};\n int pad = 0;\n bool isPad = false;\n for (int i = 0; i < ${s}; i++) {\n offsetToIndices(i, kernelStrides, offset);\n isPad = false;\n for (int j = ${a} - ${c}; j < ${a}; j++) {\n x[j] = indices[j] * strides[j - ${a} + ${c}]\n + offset[j - ${a} + ${c}] - pads[j - 2];\n ${y}\n }\n ${r}\n\n return value;\n }\n `}},d=(t,e)=>{let n="";for(let r=0;r`\n void offsetToIndices(int offset, int[${t}] strides, out int[${t}] indices) {\n if (${t} == 0) {\n return;\n }\n for (int i = 0; i < ${t} - 1; ++i) {\n indices[i] = offset / strides[i];\n offset -= indices[i] * strides[i];\n }\n indices[${t} - 1] = offset;\n }`},4939:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.reduceLogSumSquare=e.reduceLogSum=e.reduceProd=e.reduceMin=e.reduceMax=e.reduceMean=e.reduceSum=e.parseReduceAttributes=void 0;const r=n(246),i=n(782),o=n(2517),a=n(2039),s=(t,e,n,r,i)=>{c(e);const o={name:r,inputNames:["A"],inputTypes:[a.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},o),{cacheHint:n.cacheKey,get:()=>u(t,e,n,r,i,o)}),e)]};e.parseReduceAttributes=t=>{const e=t.attributes.getInts("axes",[]),n=1===t.attributes.getInt("keepdims",1);return(0,r.createAttributeWithCacheKey)({axes:e,keepDims:n})};const u=(t,e,n,r,i,s)=>{const u=[],c=e[0].dims.length||1,l=[],p=o.ShapeUtil.normalizeAxes(n.axes,e[0].dims.length),f=i(e,p);let d=f[1];for(let t=0;t=0||0===p.length?(n.keepDims&&u.push(1),d=`\n for(int j${t} = 0; j${t} < ${e[0].dims[t]}; j${t}++) {\n inputIdx[${t}] = j${t};\n ${d}\n }`):(l.push(`inputIdx[${t}] = outputIdx[${u.length}];`),u.push(e[0].dims[t]));const h=`\n float process(int outputIdx[${u.length||1}]) {\n float value; // final result\n int inputIdx[${c}]; // addressing input data\n ${l.join("\n")}\n ${f[0]} // init ops for reduce max/min\n ${d}\n ${f[2]} // final computation for reduce mean\n return value;\n }`;return Object.assign(Object.assign({},s),{output:{dims:u,type:e[0].type,textureType:a.TextureType.unpacked},shaderSource:h})},c=t=>{if(!t||1!==t.length)throw new Error("Reduce op requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.reduceSum=(t,e,n)=>s(t,e,n,"ReduceSum",(()=>["value = 0.0;","value += _A(inputIdx);",""])),e.reduceMean=(t,e,n)=>s(t,e,n,"ReduceMean",((t,e)=>{let n=1;for(let r=0;r=0||0===e.length)&&(n*=t[0].dims[r]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${n}.;`]})),e.reduceMax=(t,e,n)=>s(t,e,n,"ReduceMax",((t,e)=>{const n=[];for(let r=0;r=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]})),e.reduceMin=(t,e,n)=>s(t,e,n,"ReduceMin",((t,e)=>{const n=[];for(let r=0;r=0||0===e.length)&&n.push(`inputIdx[${r}] = 0;`);return[`${n.join("\n")}\nvalue = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]})),e.reduceProd=(t,e,n)=>s(t,e,n,"ReduceProd",(()=>["value = 1.0;","value *= _A(inputIdx);",""])),e.reduceLogSum=(t,e,n)=>s(t,e,n,"ReduceLogSum",(()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"])),e.reduceLogSumSquare=(t,e,n)=>s(t,e,n,"ReduceLogSumSquare",(()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""]))},7019:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isReshapeCheap=e.processDims3D=e.createPackedReshape3DProgramInfoLoader=void 0;const r=n(2517),i=n(5060),o=n(2039),a=n(2827);e.createPackedReshape3DProgramInfoLoader=(t,e,n)=>{const s=(t=>({name:"Reshape (packed)",inputTypes:[o.TextureType.packed],inputNames:["A"],cacheHint:`${t}`}))(n);return Object.assign(Object.assign({},s),{get:()=>((t,e,n,s)=>{const u=e.dims,c=s;let l="";for(let t=0;t<4;t++){let e="";switch(t){case 0:e="outputCoords = rc;";break;case 1:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:e="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:e="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}l+=`\n ${e}\n ${t>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""}\n int flattenedIndex = getFlattenedIndex(outputCoords);\n\n ivec3 inputRC = inputCoordsFromReshapedOutCoords(flattenedIndex);\n vec2 innerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n result[${t}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), innerDims);\n\n ${t>0?"}":""}\n `}const p=(0,i.getGlsl)(t.session.backend.glContext.version),f=`\n ${function(t){const e=r.ShapeUtil.computeStrides(t),n=["b","r","c"],i="index";return`\n ivec3 inputCoordsFromReshapedOutCoords(int index) {\n ${e.map(((t,r)=>`int ${n[r]} = ${i} / ${t}; ${r===e.length-1?`int ${n[r+1]} = ${i} - ${n[r]} * ${t}`:`index -= ${n[r]} * ${t}`};`)).join("")}\n return ivec3(b, r, c);\n }\n `}(u)}\n ${function(t){const e=r.ShapeUtil.computeStrides(t);return`\n int getFlattenedIndex(ivec3 coords) {\n // reverse y, z order\n return coords.x * ${e[0]} + coords.z * ${e[1]} + coords.y;\n }\n`}(c)}\n ${(0,a.unpackFromChannel)()}\n\n void main() {\n ivec3 rc = getOutputCoords();\n\n vec4 result = vec4(0.0);\n\n ivec3 outputCoords;\n int rows = ${c[2]};\n int cols = ${c[1]};\n\n ${l}\n ${p.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:c,type:e.type,textureType:o.TextureType.packed},shaderSource:f,hasMain:!0})})(t,e,s,n)})},e.processDims3D=function(t){if(0===t.length)return[1,1,1];let e=1;for(let n=0;n1?t[t.length-2]:1,t[t.length-1]]},e.isReshapeCheap=function(t,e){let n=!1;return n=0===t.length||0===e.length||(t.length<2||e.length<2?t[t.length-1]===e[e.length-1]:t[t.length-1]===e[e.length-1]&&t[t.length-2]===e[e.length-2]),n}},718:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.reshape=void 0;const r=n(2517);e.reshape=(t,e)=>{const n=r.ShapeUtil.calculateReshapedDims(e[0].dims,e[1].integerData);return t.session.pack?[t.reshapePacked(e[0],n)]:[t.reshapeUnpacked(e[0],n)]}},2268:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseResizeAttributesV11=e.parseResizeAttributesV10=e.resize=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827),s=n(9793),u={name:"Resize",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.resize=(t,e,n)=>((0,s.validateInputs)(e,n),[t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>c(t,e,n)}),e)]),e.parseResizeAttributesV10=t=>(0,s.parseUpsampleAttributes)(t,10),e.parseResizeAttributesV11=t=>(0,s.parseUpsampleAttributes)(t,11);const c=(t,e,n)=>{const s=(0,r.getGlsl)(t.session.backend.glContext.version),[c,p]=l(e,n);if(c.every((t=>1===t))&&"tf_crop_and_resize"!==n.coordinateTransformMode)return Object.assign(Object.assign({},u),{output:{dims:p,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:`void main() {\n vec4 v = ${s.texture2D}(X, TexCoords);\n ${s.output} = v;\n }`});const f=p.length;if(f<2)throw new Error(`output dimension should be at least 2, but got ${f}`);const d=p[f-2],h=p[f-1],g=e[0].dims;if(f!==g.length)throw new Error(`output dimension should match input ${g.length}, but got ${f}`);const b=g[f-2],m=g[f-1],y=c[f-2],_=c[f-1];let v="";if("linear"!==n.mode)throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":v="\n vec4 getSourceFracIndex(ivec4 coords) {\n return vec4(coords) / scaleWHWH;\n }\n ";break;case"half_pixel":v="\n vec4 getSourceFracIndex(ivec4 coords) {\n return (vec4(coords) + 0.5) / scaleWHWH - 0.5;\n }\n ";break;case"pytorch_half_pixel":v=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 fcoords = vec4(coords);\n return vec4(\n ${h}.0 > 1.0 ? (fcoords.x + 0.5) / scaleWHWH.x - 0.5 : 0.0,\n ${d}.0 > 1.0 ? (fcoords.y + 0.5) / scaleWHWH.y - 0.5 : 0.0,\n ${h}.0 > 1.0 ? (fcoords.z + 0.5) / scaleWHWH.z - 0.5 : 0.0,\n ${d}.0 > 1.0 ? (fcoords.w + 0.5) / scaleWHWH.w - 0.5 : 0.0\n );\n }\n `;break;case"align_corners":v=`\n vec4 getSourceFracIndex(ivec4 coords) {\n vec4 resized = vec4(${h}.0 - 1.0, ${d}.0 - 1.0, ${h}.0 - 1.0,\n ${d}.0 - 1.0);\n vec4 original = vec4(${m}.0 - 1.0, ${b}.0 - 1.0, ${m}.0 - 1.0,\n ${b}.0 - 1.0);\n vec4 new_scale = original / resized;\n return vec4(coords) * new_scale;\n }\n `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}const w=(0,o.getCoordsDataType)(f),x=`\n const vec2 inputWH = vec2(${b}.0, ${m}.0);\n const vec4 scaleWHWH = vec4(float(${y}), float(${_}), float(${y}), float(${_}));\n ${(0,a.unpackFromChannel)()}\n ${v}\n float getAValue(int x10, int r, int c, int d) {\n return getChannel(getA(x10, r, c, d), vec2(c, d));\n }\n void main() {\n ${w} rc = getOutputCoords();\n\n int batch = rc[0];\n int depth = rc[1];\n\n // retrieve the 4 coordinates that is used in the 4 packed output values.\n ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1);\n\n // calculate the source index in fraction\n vec4 sourceFrac = getSourceFracIndex(coords);\n\n // get the lower and upper bound of the 4 values that will be packed into one texel.\n ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy)));\n ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw)));\n ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy)));\n ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw)));\n\n bool hasNextRow = rc.w < ${d-1};\n bool hasNextCol = rc.z < ${h-1};\n\n // pack x00, x01, x10, x11's top-left corner into one vec4 structure\n vec4 topLeft = vec4(\n getAValue(batch, depth, x00.x, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's top-right corner into one vec4 structure\n vec4 topRight = vec4(\n getAValue(batch, depth, x00.x, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure\n vec4 bottomLeft = vec4(\n getAValue(batch, depth, x00.z, x00.y),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0);\n\n // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure\n vec4 bottomRight = vec4(\n getAValue(batch, depth, x00.z, x00.w),\n hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0,\n hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0,\n (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0);\n\n // calculate the interpolation fraction on u and v direction\n vec4 frac = vec4(sourceFrac) - floor(sourceFrac);\n vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0));\n\n vec4 top = mix(topLeft, topRight, clampFrac.ywyw);\n vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw);\n vec4 newValue = mix(top, bottom, clampFrac.xxzz);\n\n ${s.output} = vec4(newValue);\n }\n `;return Object.assign(Object.assign({},u),{output:{dims:p,type:e[0].type,textureType:i.TextureType.packed},hasMain:!0,shaderSource:x})},l=(t,e)=>{const n=t[0].dims;let r,i=e.scales;if(0===i.length){const o=t[e.scalesInputIdx];if(o&&0!==o.size){if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=p(o,e.mode,e.isResize)}else{const o=t[e.sizesInputIdx];if(!o||0===o.size)throw new Error("Either scales or sizes MUST be provided as input.");r=Array.from(o.integerData),i=f(r,n,e.mode,e.isResize)}}else if(t[e.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");const o=r||n.map(((t,e)=>Math.floor(t*i[e])));return[i,o]},p=(t,e,n)=>{const r=Array.from(t.floatData);return(0,s.scalesValidation)(r,e,n),r},f=(t,e,n,r)=>{const i=e.length,o=new Array(i);for(let n=0,r=i;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.shape=void 0;const r=n(9162);e.shape=(t,e)=>(i(e),[new r.Tensor([e[0].dims.length],"int32",void 0,void 0,new Int32Array(e[0].dims))]);const i=t=>{if(!t||1!==t.length)throw new Error("Shape requires 1 input.")}},2278:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sliceV10=e.parseSliceAttributes=e.slice=void 0;const r=n(246),i=n(782),o=n(2517),a=n(2039),s={name:"Slice",inputNames:["A"],inputTypes:[a.TextureType.unpacked]};e.slice=(t,e,n)=>(c(e),[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),e)]),e.parseSliceAttributes=t=>{const e=t.attributes.getInts("starts"),n=t.attributes.getInts("ends"),i=t.attributes.getInts("axes",[]);return(0,r.createAttributeWithCacheKey)({starts:e,ends:n,axes:i})};const u=(t,e,n)=>{const r=0===n.axes.length?e.dims.slice(0).map(((t,e)=>e)):n.axes,i=o.ShapeUtil.normalizeAxes(r,e.dims.length),u=n.starts.map(((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]]))),c=n.ends.map(((t,n)=>t>e.dims[i[n]]-1?e.dims[i[n]]:o.ShapeUtil.normalizeAxis(t,e.dims[i[n]]))),l=e.dims.slice(),p=[];for(let t=0;t0&&p.push(`outputIdx[${i[t]}] += ${u[t]};`);const f=`\n float process(int outputIdx[${l.length}]) {\n ${p.join("\n ")}\n return _A(outputIdx);\n }`;return Object.assign(Object.assign({},s),{output:{dims:l,type:e.type,textureType:a.TextureType.unpacked},shaderSource:f})},c=t=>{if(!t||1!==t.length)throw new Error("Slice requires 1 input.");if(-1===i.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.")};e.sliceV10=(t,e)=>{p(e);const n=l(t,e);return[t.run(Object.assign(Object.assign({},s),{cacheHint:n.cacheKey,get:()=>u(t,e[0],n)}),[e[0]])]};const l=(t,e)=>{if(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)||e.length>=4&&!t.session.isInitializer(e[3].dataId)||e.length>=5&&!t.session.isInitializer(e[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(e.length>=5&&e[4].integerData.some((t=>1!==t)))throw new Error("currently non-1 steps is not supported for Slice");const n=Array.from(e[1].integerData),r=Array.from(e[2].integerData),i=e.length>=4?Array.from(e[3].integerData):[];return{starts:n,ends:r,axes:i,cacheKey:`${i};${n};${r}`}},p=t=>{if(!t||t.length<3||t.length>5)throw new Error("Invalid input number.");if("int32"!==t[1].type||1!==t[1].dims.length)throw new Error("Invalid input type.");if("int32"!==t[2].type||1!==t[2].dims.length)throw new Error("Invalid input type.");if(t.length>=4&&("int32"!==t[3].type||1!==t[3].dims.length))throw new Error("Invalid input type.");if(t.length>=5&&("int32"!==t[4].type||1!==t[4].dims.length))throw new Error("Invalid input type.")}},5524:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.softmaxV13=e.parseSoftmaxAttributesV13=e.parseSoftmaxAttributes=e.softmax=void 0;const r=n(246),i=n(2517),o=n(5060),a=n(2039),s=n(3738),u={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[a.TextureType.unpacked]},c={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked]},l={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[a.TextureType.unpacked,a.TextureType.unpacked,a.TextureType.unpacked]};e.softmax=(t,e,n)=>{g(e);const r=e[0].dims.slice(),o=i.ShapeUtil.normalizeAxis(n.axis,r.length),a=i.ShapeUtil.sizeToDimension(r,o),s=i.ShapeUtil.sizeFromDimension(r,o);return p(t,e,n,a,s)},e.parseSoftmaxAttributes=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",1)}),e.parseSoftmaxAttributesV13=t=>(0,r.createAttributeWithCacheKey)({axis:t.attributes.getInt("axis",-1)}),e.softmaxV13=(t,e,n)=>{g(e);const o=e[0].dims.slice(),a=i.ShapeUtil.normalizeAxis(n.axis,o.length),u=o.length,c=a!==u-1,l=[];let f,d=[],h=[];c&&(d=Array.from({length:u}).map(((t,e)=>e)),d[a]=u-1,d[u-1]=a,d.map((t=>l.push(o[t]))),f=(0,r.createAttributeWithCacheKey)({perm:d}),h=(0,s.transpose)(t,e,f));const b=c?i.ShapeUtil.sizeToDimension(l,u-1):i.ShapeUtil.sizeToDimension(o,u-1),m=c?i.ShapeUtil.sizeFromDimension(l,u-1):i.ShapeUtil.sizeFromDimension(o,u-1),y=p(t,c?h:e,n,b,m);return c?(0,s.transpose)(t,y,f):y};const p=(t,e,n,r,i)=>{const o=f(t,e[0],r,i,[r]),a=t.run(Object.assign(Object.assign({},u),{cacheHint:n.cacheKey,get:()=>o}),e),s=d(t,e[0],r,i,o.output.dims,[r]),p=t.run(Object.assign(Object.assign({},c),{cacheHint:n.cacheKey,get:()=>s}),[e[0],a]),g=h(t,e[0],r,i,o.output.dims,s.output.dims);return[t.run(Object.assign(Object.assign({},l),{cacheHint:n.cacheKey,get:()=>g}),[e[0],a,p])]},f=(t,e,n,r,i)=>{const[s,c]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),l=i.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length)throw new Error("Dimensionality of the output should be 1");if(i[0]!==n)throw new Error("Shape of the output should be equal to logical row count");const p=(0,o.getGlsl)(t.session.backend.glContext.version),f=`\n float process(int[${l}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float max = getColorAsFloat(${p.texture2D}(A, offsetToCoords(logical_row_start_offset, ${s},\n ${c} )));\n for(int i=1; i<${r}; ++i)\n {\n float current = getColorAsFloat(${p.texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${s}, ${c})));\n if(current > max)\n max = current;\n }\n\n return max;\n }`;return Object.assign(Object.assign({},u),{output:{dims:i,type:e.type,textureType:a.TextureType.unpacked},shaderSource:f})},d=(t,e,n,r,i,s)=>{const[u,l]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),p=s.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==s.length)throw new Error("Dimensionality of the output should be 1");if(s[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(1!==i.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const f=`\n float process(int[${p}] indices) {\n int logical_row_start_offset = indices[0] * ${r};\n\n float norm_factor = 0.0;\n float max = _Max(indices);\n for(int i=0; i<${r}; ++i)\n {\n norm_factor += exp(getColorAsFloat(${(0,o.getGlsl)(t.session.backend.glContext.version).texture2D}(A, offsetToCoords(logical_row_start_offset + i,\n ${u}, ${l}))) - max);\n }\n\n return norm_factor;\n }`;return Object.assign(Object.assign({},c),{output:{dims:s,type:e.type,textureType:a.TextureType.unpacked},shaderSource:f})},h=(t,e,n,r,i,o)=>{const[s,u]=t.calculateTextureWidthAndHeight(e.dims,a.TextureType.unpacked),c=e.dims.length;if(n<1||r<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(1!==i.length||1!==o.length)throw new Error("Dimensionality of the intermediate results should be 1");if(i[0]!==n||o[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");const p=`\n float process(int[${c}] indices) {\n\n // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)\n int offset = coordsToOffset(TexCoords, ${s}, ${u});\n\n //determine the logical row for this index\n int logical_row_index[1];\n logical_row_index[0] = offset / ${r};\n\n float norm_factor = _Norm(logical_row_index);\n\n // avoid possible division by 0\n // if norm_facor is 0, all elements are zero\n // if so, return 0\n if(norm_factor == 0.0)\n return 0.0;\n\n return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;\n }`;return Object.assign(Object.assign({},l),{output:{dims:e.dims,type:e.type,textureType:a.TextureType.unpacked},shaderSource:p})},g=t=>{if(!t||1!==t.length)throw new Error("Softmax requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("Invalid input type")}},5975:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseSplitAttributes=e.split=void 0;const r=n(246),i=n(2517),o=n(2039),a={name:"Split",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.split=(t,e,n)=>{c(e);const r=i.ShapeUtil.normalizeAxis(n.axis,e[0].dims.length),o=s(t,e,r,n),l=[];for(let i=0;iu(t,e[0],n,r,i)}),e));return l},e.parseSplitAttributes=t=>{const e=t.attributes.getInt("axis",0),n=t.attributes.getInts("split",[]),i=t.outputs.length;return(0,r.createAttributeWithCacheKey)({axis:e,split:n,numOutputs:i})};const s=(t,e,n,r)=>{const[,o]=i.SplitUtil.splitShape(e[0].dims,n,r.split,r.numOutputs);return o.length},u=(t,e,n,r,s)=>{const[u,c]=i.SplitUtil.splitShape(e.dims,r,n.split,n.numOutputs),l=c[s],p=u[s],f=`\n float process(int indices[${p.length}]) {\n indices[${r}] += ${l};\n return _A(indices);\n }\n `;return Object.assign(Object.assign({},a),{cacheHint:`${n.cacheKey}:${s}`,output:{dims:p,type:e.type,textureType:o.TextureType.unpacked},shaderSource:f})},c=t=>{if(!t||1!==t.length)throw new Error("Split requires one input.");if("int8"!==t[0].type&&"uint8"!==t[0].type&&"int16"!==t[0].type&&"uint16"!==t[0].type&&"int32"!==t[0].type&&"uint32"!==t[0].type&&"float32"!==t[0].type&&"float64"!==t[0].type&&"bool"!==t[0].type)throw new Error("Invalid input type.")}},3933:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseSqueezeAttributes=e.squeezeV13=e.squeeze=void 0;const r=n(2517);e.squeeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.squeezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.squeezeV13=(t,n)=>(o(n),(0,e.squeeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseSqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Squeeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Squeeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},6558:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.sum=void 0;const r=n(5060),i=n(2039);e.sum=(t,e)=>{a(e);const n={name:"Sum",inputNames:e.map(((t,e)=>`X${e}`)),inputTypes:new Array(e.length).fill(i.TextureType.unpacked)};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const o=(0,r.getGlsl)(t.session.backend.glContext.version),a=e[0].dims.slice(),s=`\n void main() {\n vec4 result = ${e.map(((t,e)=>`${o.texture2D}(X${e},TexCoords)`)).join(" + ")};\n ${o.output} = result;\n }\n `;return Object.assign(Object.assign({},n),{output:{dims:a,type:e[0].type,textureType:i.TextureType.unpacked},hasMain:!0,shaderSource:s})},a=t=>{if(!t||0===t.length)throw new Error("Sum requires inputs.");const e=t[0].dims.length;for(let n=1;n{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tile=void 0;const r=n(782),i=n(2039);e.tile=(t,e)=>{a(e);const n={name:"Tile",inputNames:["A"],inputTypes:[i.TextureType.unpacked]};return[t.run(Object.assign(Object.assign({},n),{get:()=>o(t,e,n)}),e)]};const o=(t,e,n)=>{const r=e[0].dims.slice(),o=new Array(r.length),a=[];for(let t=0;t{if(!t||2!==t.length)throw new Error("Tile requires 2 input.");if(1!==t[1].dims.length)throw new Error("The second input shape must 1 dimension.");if(t[1].dims[0]!==t[0].dims.length)throw new Error("Invalid input shape.");if(-1===r.NUMBER_TYPES.indexOf(t[0].type))throw new Error("Invalid input type.");if("int32"!==t[1].type&&"int16"!==t[1].type)throw new Error("Invalid repeat type.")}},3738:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseTransposeAttributes=e.transpose=void 0;const r=n(246),i=n(2517),o=n(2039),a={name:"Transpose",inputNames:["A"],inputTypes:[o.TextureType.unpacked]};e.transpose=(t,e,n)=>(p(e),[t.run(Object.assign(Object.assign({},a),{cacheHint:n.cacheKey,get:()=>s(t,e[0],n.perm)}),e)]),e.parseTransposeAttributes=t=>(0,r.createAttributeWithCacheKey)({perm:t.attributes.getInts("perm",[])});const s=(t,e,n)=>{const r=e.dims;n=u(r,n);const i=c(r,n),s=r.length,p=`\n ${l("perm",n,s)}\n float process(int indices[${s}]) {\n int a[${s}];\n perm(a, indices);\n return _A(a);\n }`;return Object.assign(Object.assign({},a),{output:{dims:i,type:e.type,textureType:o.TextureType.unpacked},shaderSource:p})},u=(t,e)=>(e&&e.length!==t.length&&(e=[...t.keys()].reverse()),e),c=(t,e)=>(e=u(t,e),i.ShapeUtil.sortBasedOnPerm(t,e)),l=(t,e,n)=>{const r=[];r.push(`void ${t}(out int a[${n}], int src[${n}]) {`);for(let t=0;t{if(!t||1!==t.length)throw new Error("Transpose requires 1 input.");if("float32"!==t[0].type&&"float64"!==t[0].type)throw new Error("input should be float tensor")}},8710:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.encodeAsUint8=void 0;const r=n(5060),i=n(2039);e.encodeAsUint8=(t,e)=>{const n=e.shape,o=(0,r.getGlsl)(t.session.backend.glContext.version),a=`\n const float FLOAT_MAX = 1.70141184e38;\n const float FLOAT_MIN = 1.17549435e-38;\n\n bool isNaN(float val) {\n return (val < 1.0 || 0.0 < val || val == 0.0) ? false : true;\n }\n\n highp vec4 encodeAsUint8(highp float v) {\n if (isNaN(v)) {\n return vec4(255, 255, 255, 255);\n }\n\n highp float av = abs(v);\n\n if(av < FLOAT_MIN) {\n return vec4(0.0, 0.0, 0.0, 0.0);\n } else if(v > FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n } else if(v < -FLOAT_MAX) {\n return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;\n }\n\n highp vec4 c = vec4(0,0,0,0);\n\n highp float e = floor(log2(av));\n highp float m = exp2(fract(log2(av))) - 1.0;\n\n c[2] = floor(128.0 * m);\n m -= c[2] / 128.0;\n c[1] = floor(32768.0 * m);\n m -= c[1] / 32768.0;\n c[0] = floor(8388608.0 * m);\n\n highp float ebias = e + 127.0;\n c[3] = floor(ebias / 2.0);\n ebias -= c[3] * 2.0;\n c[2] += floor(ebias) * 128.0;\n\n c[3] += 128.0 * step(0.0, -v);\n\n return c / 255.0;\n }\n\n void main() {\n float value = ${o.texture2D}(X,TexCoords).r;\n ${o.output} = encodeAsUint8(value);\n }`,s={name:"Uint8Encode",inputTypes:[i.TextureType.unpacked],inputNames:["X"],output:{dims:n,type:e.tensor.type,textureType:i.TextureType.downloadUint8AsFloat},shaderSource:a,hasMain:!0};return t.executeProgram(s,[e.tensor])}},4909:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tanh=e.tan=e.sqrt=e.sin=e.sigmoid=e.relu=e.not=e.neg=e.log=e.parseLeakyReluAttributes=e.leakyRelu=e.identity=e.floor=e.exp=e.parseEluAttributes=e.elu=e.cos=e.ceil=e.clipV11=e.parseClipAttributes=e.clip=e.atan=e.asin=e.acos=e.abs=e.glslTanh=e.glslTan=e.glslSqrt=e.glslSigmoid=e.glslRelu=e.glslSin=e.glslNot=e.glslNeg=e.glslLog=e.glslLeakyRelu=e.glslIdentity=e.glslClip=e.glslFloor=e.glslExp=e.glslElu=e.glslCos=e.glslCeil=e.glslAtan=e.glslAsin=e.glslAcos=e.glslAbs=void 0;const r=n(246),i=n(2517),o=n(8520),a=n(5060),s=n(2039);function u(){return P("abs")}function c(){return P("acos")}function l(){return P("asin")}function p(){return P("atan")}function f(){return P("ceil")}function d(){return P("cos")}function h(t){const e="elu";return{body:`\n const float alpha = float(${t});\n\n float ${e}_(float a) {\n return a >= 0.0 ? a: (exp(a) - 1.0) * alpha;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function g(){return P("exp")}function b(){return P("floor")}function m(t,e){const n="clip";return{body:`\n const float min = float(${t});\n const float max = float(${e});\n\n float ${n}_(float a) {\n return clamp(a, min, max);\n }\n vec4 ${n}_(vec4 v) {\n return clamp(v, min, max);\n }\n `,name:n,type:o.FunctionType.ValueBased}}function y(){const t="indentity";return{body:`\n float ${t}_(float a) {\n return a;\n }\n vec4 ${t}_(vec4 v) {\n return v;\n }\n `,name:t,type:o.FunctionType.ValueBased}}function _(t){const e="leakyRelu";return{body:`\n const float alpha = float(${t});\n\n float ${e}_(float a) {\n return a < 0.0 ? a * alpha : a;\n }\n vec4 ${e}_(vec4 v) {\n return vec4(${e}_(v.x), ${e}_(v.y), ${e}_(v.z), ${e}_(v.w));\n }\n `,name:e,type:o.FunctionType.ValueBased}}function v(){return P("log")}function w(){const t="neg";return{body:`\n float ${t}_(float a) {\n return -a;\n }\n vec4 ${t}_(vec4 v) {\n return -v;\n }\n `,name:t,type:o.FunctionType.ValueBased}}function x(){const t="not";return{body:`\n float ${t}_(float a) {\n return float( ! bool(a) );\n }\n bool ${t}_(bool a) {\n return !a;\n }\n vec4 ${t}_(vec4 v) {\n return vec4(!bool(v.x), !bool(v.y), !bool(v.z), !bool(v.w));\n }\n bvec4 ${t}_(bvec4 v) {\n return bvec4(!v.x, !v.y, !v.z, !v.w);\n }\n `,name:t,type:o.FunctionType.ValueBased}}function T(){return P("sin")}function S(){const t="relu";return{body:`\n float ${t}_(float a) {\n return max( a, 0.0 );\n }\n vec4 ${t}_(vec4 v) {\n return max( v, 0.0 );\n }\n `,name:t,type:o.FunctionType.ValueBased}}function O(){const t="sigmoid";return{body:`\n float ${t}_(float a) {\n return 1.0 / (1.0 + exp(-a));\n }\n vec4 ${t}_(vec4 v) {\n return 1.0 / (1.0 + exp(-v));\n }\n `,name:t,type:o.FunctionType.ValueBased}}function A(){return P("sqrt")}function E(){return P("tan")}function I(){const t="tanh";return{body:`\n float ${t}_(float a) {\n a = clamp(a, -10., 10.);\n a = exp(2.*a);\n return (a - 1.) / (a + 1.);\n }\n vec4 ${t}_(vec4 v) {\n v = clamp(v, -10., 10.);\n v = exp(2.*v);\n return (v - 1.) / (v + 1.);\n }\n `,name:t,type:o.FunctionType.ValueBased}}function P(t){return{body:`\n float ${t}_(float a) {\n return ${t}(a);\n }\n vec4 ${t}_(vec4 v) {\n return ${t}(v);\n }\n `,name:t,type:o.FunctionType.ValueBased}}e.glslAbs=u,e.glslAcos=c,e.glslAsin=l,e.glslAtan=p,e.glslCeil=f,e.glslCos=d,e.glslElu=h,e.glslExp=g,e.glslFloor=b,e.glslClip=m,e.glslIdentity=y,e.glslLeakyRelu=_,e.glslLog=v,e.glslNeg=w,e.glslNot=x,e.glslSin=T,e.glslRelu=S,e.glslSigmoid=O,e.glslSqrt=A,e.glslTan=E,e.glslTanh=I;const D=(t,e,n,r)=>{const i=t.session.pack?s.TextureType.packed:s.TextureType.unpacked,o={name:n.name,inputTypes:[i],inputNames:["A"],cacheHint:r};return Object.assign(Object.assign({},o),{get:()=>((t,e,n,r)=>{const i=t.session.pack?s.TextureType.packed:s.TextureType.unpacked,o=(0,a.getGlsl)(t.session.backend.glContext.version);return Object.assign(Object.assign({},e),{output:{dims:n.dims,type:n.type,textureType:i},shaderSource:`\n ${r.body}\n void main() {\n vec4 v = ${o.texture2D}(A, TexCoords);\n v = ${r.name}_(v);\n ${o.output} = v;\n }\n `,hasMain:!0})})(t,o,e,n)})};e.abs=(t,e)=>[t.run(D(t,e[0],u()),e)],e.acos=(t,e)=>[t.run(D(t,e[0],c()),e)],e.asin=(t,e)=>[t.run(D(t,e[0],l()),e)],e.atan=(t,e)=>[t.run(D(t,e[0],p()),e)],e.clip=(t,e,n)=>[t.run(D(t,e[0],m(n.min,n.max),n.cacheKey),e)],e.parseClipAttributes=t=>(0,r.createAttributeWithCacheKey)({min:t.attributes.getFloat("min",i.MIN_CLIP),max:t.attributes.getFloat("max",i.MAX_CLIP)}),e.clipV11=(t,n)=>{const r=$(t,n);return(0,e.clip)(t,[n[0]],r)};const $=(t,e)=>{if(e.length>=3&&(!t.session.isInitializer(e[1].dataId)||!t.session.isInitializer(e[2].dataId)))throw new Error("dynamic clip attributes are not allowed");const n=e.length>=3?e[1].numberData[0]:i.MIN_CLIP,o=e.length>=3?e[2].numberData[0]:i.MAX_CLIP;return(0,r.createAttributeWithCacheKey)({min:n,max:o})};e.ceil=(t,e)=>[t.run(D(t,e[0],f()),e)],e.cos=(t,e)=>[t.run(D(t,e[0],d()),e)],e.elu=(t,e,n)=>[t.run(D(t,e[0],h(n.alpha),n.cacheKey),e)],e.parseEluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",1)}),e.exp=(t,e)=>[t.run(D(t,e[0],g()),e)],e.floor=(t,e)=>[t.run(D(t,e[0],b()),e)],e.identity=(t,e)=>[t.run(D(t,e[0],y()),e)],e.leakyRelu=(t,e,n)=>[t.run(D(t,e[0],_(n.alpha),n.cacheKey),e)],e.parseLeakyReluAttributes=t=>(0,r.createAttributeWithCacheKey)({alpha:t.attributes.getFloat("alpha",.01)}),e.log=(t,e)=>[t.run(D(t,e[0],v()),e)],e.neg=(t,e)=>[t.run(D(t,e[0],w()),e)],e.not=(t,e)=>[t.run(D(t,e[0],x()),e)],e.relu=(t,e)=>[t.run(D(t,e[0],S()),e)],e.sigmoid=(t,e)=>[t.run(D(t,e[0],O()),e)],e.sin=(t,e)=>[t.run(D(t,e[0],T()),e)],e.sqrt=(t,e)=>[t.run(D(t,e[0],A()),e)],e.tan=(t,e)=>[t.run(D(t,e[0],E()),e)],e.tanh=(t,e)=>[t.run(D(t,e[0],I()),e)]},5611:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createUnpackProgramInfoLoader=e.createUnpackProgramInfo=void 0;const r=n(5060),i=n(2039),o=n(9390),a=n(2827),s={name:"unpack",inputNames:["A"],inputTypes:[i.TextureType.packed]};e.createUnpackProgramInfo=(t,e)=>{const n=e.dims.length,u=(0,a.getChannels)("rc",n),c=u.slice(-2),l=(0,o.getCoordsDataType)(n),p=(0,a.unpackFromChannel)(),f=0===e.dims.length?"":function(t,e){if(1===t)return"rc";let n="";for(let r=0;rObject.assign(Object.assign({},s),{get:()=>(0,e.createUnpackProgramInfo)(t,n)})},8428:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.parseUnsqueezeAttributes=e.unsqueezeV13=e.unsqueeze=void 0;const r=n(2517);e.unsqueeze=(t,e,n)=>{i(e);const o=r.ShapeUtil.unsqueezeShape(e[0].dims,n);return[t.reshapeUnpacked(e[0],o)]},e.unsqueezeV13=(t,n)=>(o(n),(0,e.unsqueeze)(t,[n[0]],Array.from(n[1].integerData))),e.parseUnsqueezeAttributes=t=>t.attributes.getInts("axes");const i=t=>{if(!t||1!==t.length)throw new Error("Unsqueeze requires 1 input.");if("string"===t[0].type)throw new Error("invalid input tensor types.")},o=t=>{if(!t||2!==t.length)throw new Error("Unsqueeze requires 2 inputs.");if("int32"!==t[1].type)throw new Error("Invalid input type.")}},9793:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.scalesValidation=e.validateInputs=e.parseUpsampleAttributes=e.parseUpsampleAttributesV9=e.parseUpsampleAttributesV7=e.upsample=void 0;const r=n(246),i=n(5060),o=n(2039),a={name:"Upsample",inputNames:["X"],inputTypes:[o.TextureType.unpacked]};e.upsample=(t,n,r)=>((0,e.validateInputs)(n,r),[t.run(Object.assign(Object.assign({},a),{cacheHint:r.cacheKey,get:()=>s(t,n,r)}),n)]),e.parseUpsampleAttributesV7=t=>(0,e.parseUpsampleAttributes)(t,7),e.parseUpsampleAttributesV9=t=>(0,e.parseUpsampleAttributes)(t,9),e.parseUpsampleAttributes=(t,n)=>{const i=n>=10,o=t.attributes.getString("mode","nearest");if("nearest"!==o&&"linear"!==o&&(n<11||"cubic"!==o))throw new Error(`unrecognized mode: ${o}`);let a=[];n<9&&(a=t.attributes.getFloats("scales"),(0,e.scalesValidation)(a,o,i));const s=t.attributes.getFloat("extrapolation_value",0),u=n>10?t.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(-1===["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(u))throw new Error(`coordinate_transform_mode '${u}' is not supported`);const c="tf_crop_and_resize"===u,l=c,p="nearest"===o&&n>=11?t.attributes.getString("nearest_mode","round_prefer_floor"):"";if(-1===["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(p))throw new Error(`nearest_mode '${p}' is not supported`);const f=t.attributes.getFloat("cubic_coeff_a",-.75),d=0!==t.attributes.getInt("exclude_outside",0);if(d&&"cubic"!==o)throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");const h=n<11||"nearest"===o&&"asymmetric"===u&&"floor"===p;let g=0,b=0,m=0;return n>10?t.inputs.length>2?(g=1,b=2,m=3):(b=1,m=2):9===n&&(b=1),(0,r.createAttributeWithCacheKey)({opset:n,isResize:i,mode:o,scales:a,extrapolationValue:s,coordinateTransformMode:u,useExtrapolation:l,needRoiInput:c,nearestMode:p,cubicCoefficientA:f,excludeOutside:d,useNearest2xOptimization:h,roiInputIdx:g,scalesInputIdx:b,sizesInputIdx:m})};const s=(t,e,n)=>{const r=(0,i.getGlsl)(t.session.backend.glContext.version),[s,u]=t.calculateTextureWidthAndHeight(e[0].dims,o.TextureType.unpacked),c=e[0].dims.map(((t,e)=>Math.floor(t*n.scales[e]))),[l,p]=t.calculateTextureWidthAndHeight(c,o.TextureType.unpacked),f=c.length,d=new Array(f),h=new Array(f);let g=`\n int output_pitches[${f}];\n int input_pitches[${f}];\n `;for(let t=f-1;t>=0;t--)d[t]=t===f-1?1:d[t+1]*c[t+1],h[t]=t===f-1?1:h[t+1]*e[0].dims[t+1],g+=`\n output_pitches[${t}] = ${d[t]};\n input_pitches[${t}] = ${h[t]};\n `;const b=`\n float getInputFloat(int index) {\n vec2 coords = offsetToCoords(index, ${s}, ${u});\n float value = getColorAsFloat(${r.texture2D}(X, coords));\n return value;\n }\n `,m="nearest"===n.mode?`\n ${b}\n float process(int indices[${f}]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${l}, ${p});\n\n ${g}\n\n int d, m;\n for (int dim = 0; dim < ${f}; ++dim) {\n d = output_index / output_pitches[dim];\n m = output_index - d * output_pitches[dim];\n output_index = m;\n\n if (scales[dim] != 1 && d > 0) {\n int d2 = d / scales[dim];\n m = d - d2 * scales[dim];\n d = d2;\n }\n input_index += input_pitches[dim] * d;\n }\n\n return getInputFloat(input_index);\n }`:4===f?`\n ${b}\n float process(int indices[4]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${l}, ${p});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m / output_pitches[1];\n m = m - index_of_dim1 * output_pitches[1];\n index_of_dim2 = m / output_pitches[2];\n m = m - index_of_dim2 * output_pitches[2];\n index_of_dim3 = m;\n\n int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;\n index_of_input_dim2 = index_of_dim2 / scales[2];\n y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];\n index_of_input_dim3 = index_of_dim3 / scales[3];\n x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];\n\n input_index = index_of_dim0 * input_pitches[0] +\n index_of_dim1 * input_pitches[1] +\n index_of_input_dim2 * input_pitches[2] +\n index_of_input_dim3;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim2 = false;\n if (index_of_input_dim2 == (${e[0].dims[2]} - 1)) {\n // It's the end in dimension 2\n x01 = x00;\n end_of_dim2 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[2]);\n }\n\n if (index_of_input_dim3 == (input_pitches[2] - 1)) {\n // It's the end in dimension 3\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);\n }`:`\n ${b}\n float process(int indices[2]) {\n int input_index = 0;\n int output_index = coordsToOffset(TexCoords, ${l}, ${p});\n\n ${g}\n\n int m;\n int index_of_dim0, index_of_dim1;\n index_of_dim0 = output_index / output_pitches[0];\n m = output_index - index_of_dim0 * output_pitches[0];\n index_of_dim1 = m;\n\n int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;\n index_of_input_dim0 = index_of_dim0 / scales[0];\n y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];\n index_of_input_dim1 = index_of_dim1 / scales[1];\n x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];\n\n input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;\n\n float x00 = getInputFloat(input_index);\n float x10, x01, x11;\n\n bool end_of_dim0 = false;\n if (index_of_input_dim0 == (${e[0].dims[0]} - 1)) {\n // It's the end in dimension 0\n x01 = x00;\n end_of_dim0 = true;\n } else {\n x01 = getInputFloat(input_index + input_pitches[0]);\n }\n\n if (index_of_input_dim1 == (input_pitches[0] - 1)) {\n // It's the end in dimension 1\n x10 = x00;\n x11 = x01;\n }\n else {\n x10 = getInputFloat(input_index + 1);\n x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);\n }\n\n float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);\n float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);\n return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);\n }`;return Object.assign(Object.assign({},a),{output:{dims:c,type:e[0].type,textureType:o.TextureType.unpacked},shaderSource:m,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map((t=>Math.ceil(t)))}]})};e.validateInputs=(t,e)=>{if(!t||e.opset<9&&1!==t.length||e.opset>=9&&e.opset<11&&2!==t.length||e.opset>=11&&t.length<2)throw new Error("invalid inputs.");if(e.scales.length>0&&t[0].dims.length!==e.scales.length)throw new Error("Invalid input shape.");if("string"===t[0].type)throw new Error("Invalid input tensor types.")},e.scalesValidation=(t,e,n)=>{if(n){for(const e of t)if(e<=0)throw new Error("Scale value should be greater than 0.")}else for(const e of t)if(e<1)throw new Error("Scale value should be greater than or equal to 1.");if(!("linear"!==e&&"cubic"!==e||2===t.length||4===t.length&&1===t[0]&&1===t[1]))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}},1958:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ProgramManager=void 0;const r=n(1670),i=n(6231),o=n(8879),a=n(5060);e.ProgramManager=class{constructor(t,e,n){this.profiler=t,this.glContext=e,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(t){return this.repo.get(t)}setArtifact(t,e){this.repo.set(t,e)}run(t,e,n){var r;this.profiler.event("op",`ProgramManager.run ${null!==(r=t.programInfo.name)&&void 0!==r?r:"unknown kernel"}`,(()=>{var r;const o=this.glContext.gl,a=t.program;o.useProgram(a);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(t.attribLocations),this.bindUniforms(t.uniformLocations,null!==(r=t.programInfo.variables)&&void 0!==r?r:[],e)}catch(e){throw i.Logger.error("ProgramManager",t.programInfo.shaderSource),e}this.profiler.event("backend","GlContext.draw()",(()=>{this.glContext.draw()}))}),this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach((t=>this.glContext.deleteProgram(t.program)))}build(t,e,n){return this.profiler.event("backend","ProgramManager.build",(()=>{const r=new o.GlslPreprocessor(this.glContext,t,e,n),i=r.preprocess(),a=this.compile(i);return{programInfo:t,program:a,uniformLocations:this.getUniformLocations(a,r.context.programInfo.inputNames,r.context.programInfo.variables),attribLocations:this.getAttribLocations(a)}}))}compile(t){if(!this.vertexShader){i.Logger.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");const t=(0,a.getVertexShaderSource)(this.glContext.version);this.vertexShader=this.glContext.compileShader(t,this.glContext.gl.VERTEX_SHADER)}r.env.debug&&i.Logger.verbose("ProrgramManager",`FragShader:\n${t}\n`);const e=this.glContext.compileShader(t,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,e);return this.glContext.deleteShader(e),n}bindOutput(t){const e=t.width,n=t.height;i.Logger.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${e}/${n}, shape=${t.shape}, type=${t.tensor.type}`),this.glContext.attachFramebuffer(t.texture,e,n)}bindAttributes(t){const e=t.position,n=t.textureCoord;this.glContext.setVertexAttributes(e,n),this.attributesBound=!0}bindUniforms(t,e,n){var r;const i=this.glContext.gl;let o=0;for(const{name:a,type:s,location:u,arrayLength:c}of t){const t=null===(r=e.find((t=>t.name===a)))||void 0===r?void 0:r.data;if("sampler2D"!==s&&!t)throw new Error(`variable '${a}' does not have data defined in program info`);switch(s){case"sampler2D":this.bindTexture(n[o],u,o),o++;break;case"float":c?i.uniform1fv(u,t):i.uniform1f(u,t);break;case"int":c?i.uniform1iv(u,t):i.uniform1i(u,t);break;default:throw new Error(`Uniform not implemented: ${s}`)}}}bindTexture(t,e,n){this.glContext.bindTextureToUniform(t.texture,n,e)}getAttribLocations(t){return{position:this.getAttribLocation(t,"position"),textureCoord:this.getAttribLocation(t,"textureCoord")}}getUniformLocations(t,e,n){const r=[];if(e)for(const n of e)r.push({name:n,type:"sampler2D",location:this.getUniformLocation(t,n)});if(n)for(const e of n)r.push(Object.assign(Object.assign({},e),{location:this.getUniformLocation(t,e.name)}));return r}getUniformLocation(t,e){const n=this.glContext.gl.getUniformLocation(t,e);if(null===n)throw new Error(`Uniform ${e} not found.`);return n}getAttribLocation(t,e){return this.glContext.gl.getAttribLocation(t,e)}}},6416:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLSessionHandler=void 0;const r=n(6231),i=n(1047),o=n(8316),a=n(1640),s=n(1958),u=n(7859),c=n(5702);e.WebGLSessionHandler=class{constructor(t,e){this.backend=t,this.context=e,this.layoutStrategy=new u.PreferLogicalStrategy(t.glContext.maxTextureSize),this.programManager=new s.ProgramManager(this.context.profiler,t.glContext,this.layoutStrategy),this.textureManager=new c.TextureManager(t.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:"full"===t.textureCacheMode}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=t.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new o.WebGLInferenceHandler(this)}onGraphInitialized(t){const e=t.getValues().filter((t=>-1===t.from&&t.tensor)).map((t=>t.tensor.dataId));this.initializers=new Set(e)}isInitializer(t){return!!this.initializers&&this.initializers.has(t)}addInitializer(t){this.initializers.add(t)}getTextureData(t,e){return e?this.packedTextureDataCache.get(t):this.unpackedTextureDataCache.get(t)}setTextureData(t,e,n=!1){r.Logger.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(t,e):this.unpackedTextureDataCache.set(t,e)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach((t=>this.textureManager.releaseTexture(t,!0))),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach((t=>this.textureManager.releaseTexture(t,!0))),this.unpackedTextureDataCache=new Map}resolve(t,e,n){const r=(0,i.resolveOperator)(t,e,a.WEBGL_OP_RESOLVE_RULES);return{impl:r.opImpl,context:r.opInit?r.opInit(t,n):t}}}},7769:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Uint8DataEncoder=e.RGBAFloatDataEncoder=e.RedFloat32DataEncoder=void 0;const r=n(6231);e.RedFloat32DataEncoder=class{constructor(t,e=1){if(1===e)this.internalFormat=t.R32F,this.format=t.RED,this.textureType=t.FLOAT,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA32F,this.format=t.RGBA,this.textureType=t.FLOAT,this.channelSize=e}}encode(t,e){let n,i;return t.constructor!==Float32Array&&(r.Logger.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(t)),e*this.channelSize>t.length?(r.Logger.warning("Encoder","Source data too small. Allocating larger array"),i=t,n=this.allocate(e*this.channelSize),i.forEach(((t,e)=>n[e]=t))):(i=t,n=i),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter(((t,e)=>e%4==0)).subarray(0,e):t.subarray(0,e)}},e.RGBAFloatDataEncoder=class{constructor(t,e=1,n){if(1!==e&&4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.channelSize=e,this.textureType=n||t.FLOAT}encode(t,e){let n=t;return 1===this.channelSize&&(r.Logger.verbose("Encoder","Exploding into a larger array"),n=this.allocate(e),t.forEach(((t,e)=>n[4*e]=t))),n}allocate(t){return new Float32Array(4*t)}decode(t,e){return 1===this.channelSize?t.filter(((t,e)=>e%4==0)).subarray(0,e):t.subarray(0,e)}},e.Uint8DataEncoder=class{constructor(t,e=1){if(this.channelSize=4,1===e)this.internalFormat=t.ALPHA,this.format=t.ALPHA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e;else{if(4!==e)throw new Error(`Invalid number of channels: ${e}`);this.internalFormat=t.RGBA,this.format=t.RGBA,this.textureType=t.UNSIGNED_BYTE,this.channelSize=e}}encode(t,e){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}allocate(t){return new Uint8Array(t*this.channelSize)}decode(t,e){if(t instanceof Uint8Array)return t.subarray(0,e);throw new Error(`Invalid array type: ${t.constructor}`)}}},7859:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getBatchDim=e.sizeToSquarishShape=e.getRowsCols=e.sizeFromShape=e.isInt=e.parseAxisParam=e.squeezeShape=e.PreferLogicalStrategy=e.AlwaysKeepOriginalSizeStrategy=void 0;const r=n(6231),i=n(2517);function o(t,e){const n=[],r=[],i=null!=e&&Array.isArray(e)&&0===e.length,o=null==e||i?null:a(e,t).sort();let s=0;for(let e=0;ee)&&1===t[e]&&(n.push(t[e]),r.push(e)),o[s]<=e&&s++}1!==t[e]&&(n.push(t[e]),r.push(e))}return{newShape:n,keptDims:r}}function a(t,e){const n=e.length;return t=null==t?e.map(((t,e)=>e)):[].concat(t),(0,i.assert)(t.every((t=>t>=-n&&t`All values in axis param must be in range [-${n}, ${n}) but got axis ${t}`)),(0,i.assert)(t.every(s),(()=>`All values in axis param must be integers but got axis ${t}`)),t.map((t=>t<0?n+t:t))}function s(t){return t%1==0}function u(t){if(0===t.length)return 1;let e=t[0];for(let n=1;n=t.length?1:t.slice(e.breakAxis).reduce(((t,e)=>t*e)),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce(((t,e)=>t*e));if(!(i>n||o>n))return[i,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}const i=t.reduce(((t,e)=>t*e));let o=Math.floor(Math.sqrt(i));for(;o=n||i%o!=0)throw new Error(`The given dimensions are outside this GPU's boundaries: ${t}`);return[o,i/o]}},e.PreferLogicalStrategy=class{constructor(t){this.maxTextureSize=t}computeTextureWH(t,e){const n=this.computeTexture(t,e);return e&&e.isPacked&&(n[0]/=2,n[1]/=2),e&&e.reverseWH?[n[1],n[0]]:n}computeTexture(t,e){const n=e&&e.isPacked;if(0===t.length)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(e&&void 0!==e.breakAxis){const n=e.breakAxis>=t.length?1:t.slice(e.breakAxis).reduce(((t,e)=>t*e)),o=e.breakAxis<=0?1:t.slice(0,e.breakAxis).reduce(((t,e)=>t*e));if(!(n>i||o>i))return[n,o];r.Logger.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${t}, breakAxis:${e.breakAxis}`)}let a=t.slice(0);if(n&&(i*=2,a=a.map(((t,e)=>e>=a.length-2?a[e]%2==0?a[e]:a[e]+1:a[e])),1===a.length&&(a=[2,a[0]])),2!==a.length){const t=o(a);a=t.newShape}const s=u(a);return a.length<=1&&s<=i?[1,s]:2===a.length&&a[0]<=i&&a[1]<=i?a:3===a.length&&a[0]*a[1]<=i&&a[2]<=i?[a[0]*a[1],a[2]]:3===a.length&&a[0]<=i&&a[1]*a[2]<=i?[a[0],a[1]*a[2]]:4===a.length&&a[0]*a[1]*a[2]<=i&&a[3]<=i?[a[0]*a[1]*a[2],a[3]]:4===a.length&&a[0]<=i&&a[1]*a[2]*a[3]<=i?[a[0],a[1]*a[2]*a[3]]:n?c(s/4).map((t=>2*t)):c(s)}},e.squeezeShape=o,e.parseAxisParam=a,e.isInt=s,e.sizeFromShape=u,e.getRowsCols=function(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]]},e.sizeToSquarishShape=c,e.getBatchDim=function(t,e=2){return u(t.slice(0,t.length-e))}},4057:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createTextureLayoutFromShape=e.calculateTextureWidthAndHeight=e.createTextureLayoutFromTextureType=void 0;const r=n(2517),i=n(2039);e.createTextureLayoutFromTextureType=(t,n,r)=>{const o=r===i.TextureType.unpacked||r===i.TextureType.unpackedReversed?1:4,a=r===i.TextureType.packed,s=r===i.TextureType.unpackedReversed||r===i.TextureType.packed,u=r===i.TextureType.packedLastDimension?n.length-1:void 0,c=r===i.TextureType.packedLastDimension?n.map(((t,e)=>e===n.length-1?4*t:t)):void 0;return(0,e.createTextureLayoutFromShape)(t,n,o,c,{isPacked:a,reverseWH:s,breakAxis:u})},e.calculateTextureWidthAndHeight=(t,n,r)=>{const i=(0,e.createTextureLayoutFromTextureType)(t,n,r);return[i.width,i.height]},e.createTextureLayoutFromShape=(t,e,n=1,i,o)=>{const a=!(!o||!o.isPacked),[s,u]=t.computeTextureWH(a&&i||e,o),c=e.length;let l=e.slice(0);if(0===c&&(l=[1]),1===n)i=e;else if(a){if(4!==n)throw new Error("a packed texture must be 4-channel");i=e,c>0&&(l[c-1]=Math.ceil(l[c-1]/2)),c>1&&(l[c-2]=Math.ceil(l[c-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:s,height:u,channels:n,isPacked:a,shape:l,strides:r.ShapeUtil.computeStrides(l),unpackedShape:i,reversedWH:o&&o.reverseWH}}},5702:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TextureManager=void 0;const r=n(6231);e.TextureManager=class{constructor(t,e,n,r){this.glContext=t,this.layoutStrategy=e,this.profiler=n,this.config=r,this.pendingRead=new Map,r.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(t,e,n,i){const o=this.toEncoderType(t),a=this.glContext.getEncoder(o,e.channels||1,i);if(e.isPacked&&1===i)throw new Error("not implemented");const s=e.width,u=e.height;let c,l;if(this.config.reuseTextures){c=`${s}x${u}_${a.format}_${a.internalFormat}_${a.textureType}`,l=this.inUseTextures.get(c),l||(l=[],this.inUseTextures.set(c,l));const e=this.idleTextures.get(c);if(e&&e.length>0){const r=e.pop();return l.push(r),1===i&&this.glContext.updateTexture(r,s,u,a,this.toTextureData(t,n)),r}}r.Logger.verbose("TextureManager",`Creating new texture of size ${e.width}x${e.height}`);const p=this.glContext.allocateTexture(s,u,a,this.toTextureData(t,n));return this.config.reuseTextures&&(l.push(p),this.textureLookup.set(p,c)),p}readTexture(t,e,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",(()=>{const r=t.shape.reduce(((t,e)=>t*e))*n,i=this.glContext.readTexture(t.texture,t.width,t.height,r,this.toEncoderType(e),n);return this.toTensorData(e,i)}))}async readTextureAsync(t,e,n){const r=t.tensor.dataId;if(n||(n=1),this.pendingRead.has(r)){const t=this.pendingRead.get(r);return new Promise((e=>null==t?void 0:t.push(e)))}return this.profiler.event("backend","TextureManager.readTextureAsync",(async()=>{this.pendingRead.set(r,[]);const i=t.shape.reduce(((t,e)=>t*e))*n;await this.glContext.createAndWaitForFence();const o=this.glContext.readTexture(t.texture,t.width,t.height,i,this.toEncoderType(e),n),a=this.toTensorData(e,o),s=this.pendingRead.get(r);return this.pendingRead.delete(r),null==s||s.forEach((t=>t(a))),a}))}readUint8TextureAsFloat(t){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",(()=>{const e=t.shape.reduce(((t,e)=>t*e)),n=this.glContext.readTexture(t.texture,t.width,t.height,4*e,"byte",4);return new Float32Array(n.buffer,n.byteOffset,e)}))}releaseTexture(t,e){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(t.texture),n)){e&&this.textureLookup.delete(n);const r=this.inUseTextures.get(n);if(r){const e=r.indexOf(t.texture);if(-1!==e){r.splice(e,1);let i=this.idleTextures.get(n);i||(i=[],this.idleTextures.set(n,i)),i.push(t.texture)}}}n&&!e||(r.Logger.verbose("TextureManager",`Deleting texture of size ${t.width}x${t.height}`),this.glContext.deleteTexture(t.texture))}toTensorData(t,e){switch(t){case"int16":return e instanceof Int16Array?e:Int16Array.from(e);case"int32":return e instanceof Int32Array?e:Int32Array.from(e);case"int8":return e instanceof Int8Array?e:Int8Array.from(e);case"uint16":return e instanceof Uint16Array?e:Uint16Array.from(e);case"uint32":return e instanceof Uint32Array?e:Uint32Array.from(e);case"uint8":case"bool":return e instanceof Uint8Array?e:Uint8Array.from(e);case"float32":return e instanceof Float32Array?e:Float32Array.from(e);case"float64":return e instanceof Float64Array?e:Float64Array.from(e);default:throw new Error(`TensorData type ${t} is not supported`)}}toTextureData(t,e){if(e)return e instanceof Float32Array?e:new Float32Array(e)}toEncoderType(t){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}},2039:(t,e)=>{"use strict";var n;Object.defineProperty(e,"__esModule",{value:!0}),e.TextureType=void 0,(n=e.TextureType||(e.TextureType={}))[n.unpacked=0]="unpacked",n[n.unpackedReversed=1]="unpackedReversed",n[n.packed=2]="packed",n[n.downloadUint8AsFloat=3]="downloadUint8AsFloat",n[n.packedLastDimension=4]="packedLastDimension"},9390:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getGlChannels=e.getCoordsDataType=e.getSqueezedParams=e.squeezeInputShape=e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=e.generateShaderFuncNameFromInputSamplerName=e.repeatedTry=e.getPackedShape=void 0;const r=n(2517);e.getPackedShape=function(t){const e=t.length;return t.slice(0,e-1).concat(t[e-1]/4)},e.repeatedTry=async function(t,e=(t=>0),n){return new Promise(((r,i)=>{let o=0;const a=()=>{if(t())return void r();o++;const s=e(o);null!=n&&o>=n?i():setTimeout(a,s)};a()}))},e.generateShaderFuncNameFromInputSamplerName=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,(()=>"empty string found for sampler name")),"get"+t.charAt(0).toUpperCase()+t.slice(1)},e.generateShaderFuncNameFromInputSamplerNameAtOutCoords=function(t){return(0,r.assert)(void 0!==t&&0!==t.length,(()=>"empty string found for sampler name")),"get"+t.charAt(0).toUpperCase()+t.slice(1)+"AtOutCoords"},e.squeezeInputShape=function(t,e){let n=JSON.parse(JSON.stringify(t));return n=e,n},e.getSqueezedParams=function(t,e){return e.map((e=>t[e])).join(", ")},e.getCoordsDataType=function(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error(`GPU for rank ${t} is not yet supported`)},e.getGlChannels=function(t=6){return["x","y","z","w","u","v"].slice(0,t)}},7305:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createNewWebGLContext=e.createWebGLContext=void 0;const r=n(6231),i=n(1713),o={};function a(t){const e=function(){if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas)throw new TypeError("failed to create canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}const t=document.createElement("canvas");return t.width=1,t.height=1,t}();let n;const o={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1};if((!t||"webgl2"===t)&&(n=e.getContext("webgl2",o),n))try{return new i.WebGLContext(n,2)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${t}`)}if((!t||"webgl"===t)&&(n=e.getContext("webgl",o)||e.getContext("experimental-webgl",o),n))try{return new i.WebGLContext(n,1)}catch(t){r.Logger.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${t}`)}throw new Error("WebGL is not supported")}e.createWebGLContext=function t(e){let n;e&&"webgl2"!==e||!("webgl2"in o)?e&&"webgl"!==e||!("webgl"in o)||(n=o.webgl):n=o.webgl2,n=n||a(e),e=e||1===n.version?"webgl":"webgl2";const r=n.gl;return o[e]=n,r.isContextLost()?(delete o[e],t(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),n)},e.createNewWebGLContext=a},1713:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.WebGLContext=e.linearSearchLastTrue=void 0;const a=n(1670),s=o(n(7769)),u=n(9390);function c(t){let e=0;for(;ethis.isTimerResultAvailable(t))),this.getTimerResult(t)}async createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e;const n=t,r=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return t.flush(),e=null===r?()=>!0:()=>{const t=n.clientWaitSync(r,0,0);return t===n.ALREADY_SIGNALED||t===n.CONDITION_SATISFIED},{query:r,isFencePassed:e}}async pollFence(t){return new Promise((e=>{this.addItemToPoll((()=>t.isFencePassed()),(()=>e()))}))}pollItems(){const t=c(this.itemsToPoll.map((t=>t.isDoneFn)));for(let e=0;e<=t;++e){const{resolveFn:t}=this.itemsToPoll[e];t()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}async addItemToPoll(t,e){this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||await(0,u.repeatedTry)((()=>(this.pollItems(),0===this.itemsToPoll.length)))}}},1036:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ExecutionPlan=void 0;const r=n(6231);class i{constructor(t,e){this.op=t,this.node=e}}e.ExecutionPlan=class{constructor(t,e,n){this.graph=t,this.profiler=n,this.initialize(e)}initialize(t){this.profiler.event("session","ExecutionPlan.initialize",(()=>{const e=this.graph.getNodes();if(e.length!==t.length)throw new Error("The size of nodes and OPs do not match.");this._ops=t.map(((t,n)=>new i(t,e[n]))),this.reset(),this._starter=[],this._ops.forEach(((t,e)=>{let n=!0;for(const e of t.node.inputs)if(!this._values[e]&&-1===this.graph.getInputIndices().indexOf(e)){n=!1;break}n&&this._starter.push(e)}))}))}reset(){this._values=this.graph.getValues().map((t=>t.tensor))}async execute(t,e){return this.profiler.event("session","ExecutionPlan.execute",(async()=>{this.reset();const n=t.createInferenceHandler(),i=this.graph.getInputIndices();if(e.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${e.length} expected: ${i.length}`);e.forEach(((t,e)=>{const n=i[e];this._values[n]=t}));const o=this._starter.slice(0),a=this.graph.getValues(),s=this.graph.getNodes();let u=0;for(;uthis._values[t]));if(-1!==i.indexOf(void 0))throw new Error(`unresolved input detected: op: ${e.node}`);const c=i;r.Logger.verbose("ExecPlan",`Runing op:${e.node.name} (${c.map(((t,n)=>`'${e.node.inputs[n]}': ${t.type}[${t.dims.join(",")}]`)).join(", ")})`);const l=await this.profiler.event("node",e.node.name,(async()=>e.op.impl(n,c,e.op.context)));if(l.length!==e.node.outputs.length)throw new Error("the size of output does not match model definition.");l.forEach(((t,n)=>{const r=e.node.outputs[n];if(this._values[r])throw new Error(`output [${r}] already has value: op:${e.node.name}`);this._values[r]=t}));const p=new Set;l.forEach(((t,n)=>{const r=e.node.outputs[n];for(const t of a[r].to){const e=s[t];let n=!0;for(const t of e.inputs)if(!this._values[t]){n=!1;break}n&&p.add(t)}})),o.push(...p)}const c=[];for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Graph=void 0;const r=n(1446),i=n(7778),o=n(9395),a=n(9162),s=n(2517);var u=o.onnxruntime.experimental.fbs;e.Graph={from:(t,e)=>new p(t,e)};class c{constructor(t){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,t&&(this.type=s.ProtoUtil.tensorValueTypeFromProto(t.type.tensorType))}get from(){return this._from}get to(){return this._to}}class l{constructor(t,e){t instanceof r.onnx.NodeProto?(this.name=t.name,this.opType=t.opType,this.attributes=new i.Attribute(t.attribute)):t instanceof u.Node&&(this.name=null!=e?e:t.name(),this.opType=t.opType(),this.attributes=new i.Attribute(s.ProtoUtil.tensorAttributesFromORTFormat(t))),this.inputs=[],this.outputs=[],this.executeNode=!0}}class p{constructor(t,e){if(!t)throw new TypeError("graph is empty");this.buildGraph(t),this.transformGraph(e),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(t){if(t instanceof r.onnx.GraphProto)this.buildGraphFromOnnxFormat(t);else{if(!(t instanceof u.Graph))throw new TypeError("Graph type is not supported.");this.buildGraphFromOrtFormat(t)}}buildGraphFromOnnxFormat(t){const e=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];const n=new Map;if(!t.input)throw new Error("missing information in graph: input");const r=[];for(const n of t.input){if(e.has(n.name))throw new Error(`duplicated input name: ${n.name}`);const t=this._allData.push(new c(n))-1;e.set(n.name,t),r.push(n.name)}if(!t.initializer)throw new Error("missing information in graph: initializer");for(const n of t.initializer){let t=e.get(n.name);if(void 0===t){const r=new c;r.type={shape:{dims:s.ProtoUtil.tensorDimsFromProto(n.dims)},tensorType:s.ProtoUtil.tensorDataTypeFromProto(n.dataType)},t=this._allData.push(r)-1,e.set(n.name,t)}this._allData[t]._from=-1,this._allData[t].tensor=a.Tensor.fromProto(n)}for(let t=0;t{this._allData[e]._to.forEach((e=>{t.add(e)}))}));const e=Array.from(t),n=new Array(this._nodes.length).fill("white");for(;e.length>0;){const t=e.pop();"gray"===n[t]?n[t]="black":(e.push(t),n[t]="gray",this._nodes[t].outputs.forEach((r=>{const i=this._allData[r];if(void 0!==i.tensor)throw new Error("node outputs should not be initialized");if(i._from!==t)throw new Error("from property of the Value object doesn't match index of Node being processed");i._to.forEach((t=>{if("gray"===n[t])throw new Error("model graph is cyclic");"white"===n[t]&&e.push(t)}))})))}}transformGraph(t){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),t&&t.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let t=0;for(let e=0;e0&&(this._nodes[e].inputs.forEach((n=>{const r=this._allData[n]._to.indexOf(e+t);-1!==r&&(this._allData[n]._to[r]=e)})),this._nodes[e].outputs.forEach((n=>{this._allData[n]._from&&this._allData[n]._from===e+t&&(this._allData[n]._from=e)}))):(t++,this._nodes[e].outputs.forEach((t=>{this._allData[t]._from=-2})),this._nodes.splice(e,1),e--);t=0;for(let e=0;e0){let n=-1;void 0!==this._allData[e].from&&-1!==this._allData[e].from?(n=this._nodes[this._allData[e].from].outputs.indexOf(e+t),-1!==n&&(this._nodes[this._allData[e].from].outputs[n]=e)):(n=this._allInputIndices.indexOf(e+t),-1!==n&&(this._allInputIndices[n]=e)),this._allData[e].to.forEach((r=>{n=this._nodes[r].inputs.indexOf(e+t),-1!==n&&(this._nodes[r].inputs[n]=e)})),0===this._allData[e].to.length&&(n=this._allOutputIndices.indexOf(e+t),-1!==n&&(this._allOutputIndices[n]=e))}}else t++,this._allData.splice(e,1),e--}deleteNode(t){const e=this._nodes[t];if(e.outputs.length>1)for(let t=1;t0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ");e.executeNode=!1;const n=e.inputs[0],r=e.outputs[0],i=this._allData[r].to,o=this._allData[n].to.indexOf(t);if(-1===o)throw new Error("The Value object doesn't have the current Node in it's 'to' property ");this._allData[n].to.splice(o,1),this._allData[r]._to=[];const a=this._allOutputIndices.indexOf(r);if(-1!==a&&(this._allOutputIndices[a]=n),i&&i.length>0)for(const t of i){const e=this._nodes[t].inputs.indexOf(r);if(-1===e)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[t].inputs[e]=n,this._allData[n].to.push(t)}}removeAllDropoutNodes(){let t=0;for(const e of this._nodes){if("Dropout"===e.opType){if(1!==e.inputs.length)throw new Error("Dropout nodes should only contain one input. ");if(1!==e.outputs.length&&2!==e.outputs.length)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(2===e.outputs.length&&0!==this._allData[e.outputs[1]]._to.length)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(t)}t++}}removeAllIdentityNodes(){let t=0;for(const e of this._nodes)"Identity"===e.opType&&this.deleteNode(t),t++}isActivation(t){switch(t.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(const t of this._nodes)if("Conv"===t.opType){const e=this._allData[t.outputs[0]]._to;if(1===e.length&&this.isActivation(this._nodes[e[0]])){const n=this._nodes[e[0]];if("Clip"===n.opType)if(1===n.inputs.length)try{t.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch(e){t.attributes.set("activation_params","floats",[s.MIN_CLIP,s.MAX_CLIP])}else{if(!(n.inputs.length>=3&&void 0!==this._allData[n.inputs[1]].tensor&&void 0!==this._allData[n.inputs[2]].tensor))continue;t.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]])}t.attributes.set("activation","string",n.opType),this.deleteNode(e[0])}}}}},6231:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.now=e.Profiler=e.Logger=void 0;const n={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},r={none:new class{log(t,e,n){}},console:new class{log(t,e,n){console.log(`${this.color(t)} ${n?""+n+" ":""}${e}`)}color(t){switch(t){case"verbose":return"v";case"info":return"i";case"warning":return"w";case"error":return"e";case"fatal":return"f";default:throw new Error(`unsupported severity: ${t}`)}}}},i={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1};let o={"":i};function a(t,e,n,r){if(void 0===e)return i=t,{verbose:a.verbose.bind(null,i),info:a.info.bind(null,i),warning:a.warning.bind(null,i),error:a.error.bind(null,i),fatal:a.fatal.bind(null,i)};if(void 0===n)s(t,e);else if("number"==typeof n&&void 0===r)s(t,e);else if("string"==typeof n&&void 0===r)s(t,n,0,e);else{if("string"!=typeof n||"number"!=typeof r)throw new TypeError("input is valid");s(t,n,0,e)}var i}function s(t,e,i,a){const s=o[a||""]||o[""];n[t]{a.then((async e=>{i&&await i.end(),t(e)}),(async t=>{i&&await i.end(),e(t)}))}));if(!o&&i){const t=i.end();if(t&&"function"==typeof t.then)return new Promise(((e,n)=>{t.then((()=>{e(a)}),(t=>{n(t)}))}))}return a}begin(t,n,r){if(!this._started)throw new Error("profiler is not started yet");if(void 0===r){const r=(0,e.now)();return this.flush(r),new u(t,n,r,(t=>this.endSync(t)))}{const e=r.beginTimer();return new u(t,n,0,(async t=>this.end(t)),e,r)}}async end(t){const e=await t.checkTimer();this._timingEvents.length=this._flushBatchSize||t-this._flushTime>=this._flushIntervalInMilliseconds){for(const t=this._flushPointer;this._flushPointerperformance.now():Date.now},2644:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Model=void 0;const r=n(5686),i=n(1446),o=n(7070),a=n(9395),s=n(2517);var u=a.onnxruntime.experimental.fbs;e.Model=class{constructor(){}load(t,e,n){if(!n)try{return void this.loadFromOnnxFormat(t,e)}catch(t){if(void 0!==n)throw t}this.loadFromOrtFormat(t,e)}loadFromOnnxFormat(t,e){const n=i.onnx.ModelProto.decode(t);if(s.LongUtil.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map((t=>({domain:t.domain,version:s.LongUtil.longToNumber(t.version)}))),this._graph=o.Graph.from(n.graph,e)}loadFromOrtFormat(t,e){const n=new r.flatbuffers.ByteBuffer(t),i=u.InferenceSession.getRootAsInferenceSession(n).model();if(s.LongUtil.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FLOAT_TYPES=e.INT_TYPES=e.NUMBER_TYPES=void 0,e.NUMBER_TYPES=["float32","float64","int32","int16","int8","uint16","uint32","uint8"],e.INT_TYPES=["int32","int16","int8","uint16","uint32","uint8"],e.FLOAT_TYPES=["float32","float64"]},1047:(t,e)=>{"use strict";function n(t,e){if(e.endsWith("+")){const n=Number.parseInt(e.substring(0,e.length-1),10);return!isNaN(n)&&n<=t}if(2===e.split("-").length){const n=e.split("-"),r=Number.parseInt(n[0],10),i=Number.parseInt(n[1],10);return!isNaN(r)&&!isNaN(i)&&r<=t&&t<=i}return Number.parseInt(e,10)===t}Object.defineProperty(e,"__esModule",{value:!0}),e.resolveOperator=void 0,e.resolveOperator=function(t,e,r){for(const i of r){const r=i[0],o=i[1],a=i[2],s=i[3],u=i[4];if(t.opType===r)for(const t of e)if((t.domain===o||"ai.onnx"===t.domain&&""===o)&&n(t.version,a))return{opImpl:s,opInit:u}}throw new TypeError(`cannot resolve operator '${t.opType}' with opsets: ${e.map((t=>`${t.domain||"ai.onnx"} v${t.version}`)).join(", ")}`)}},9395:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.onnxruntime=void 0;const r=n(5686);var i,o;i=e.onnxruntime||(e.onnxruntime={}),function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.INT=2]="INT",t[t.STRING=3]="STRING",t[t.TENSOR=4]="TENSOR",t[t.GRAPH=5]="GRAPH",t[t.FLOATS=6]="FLOATS",t[t.INTS=7]="INTS",t[t.STRINGS=8]="STRINGS",t[t.TENSORS=9]="TENSORS",t[t.GRAPHS=10]="GRAPHS",t[t.SPARSE_TENSOR=11]="SPARSE_TENSOR",t[t.SPARSE_TENSORS=12]="SPARSE_TENSORS"}(e=t.AttributeType||(t.AttributeType={}))}((o=i.experimental||(i.experimental={})).fbs||(o.fbs={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.VALUE=1]="VALUE",t[t.PARAM=2]="PARAM"}(e=t.DimensionValueType||(t.DimensionValueType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.UNDEFINED=0]="UNDEFINED",t[t.FLOAT=1]="FLOAT",t[t.UINT8=2]="UINT8",t[t.INT8=3]="INT8",t[t.UINT16=4]="UINT16",t[t.INT16=5]="INT16",t[t.INT32=6]="INT32",t[t.INT64=7]="INT64",t[t.STRING=8]="STRING",t[t.BOOL=9]="BOOL",t[t.FLOAT16=10]="FLOAT16",t[t.DOUBLE=11]="DOUBLE",t[t.UINT32=12]="UINT32",t[t.UINT64=13]="UINT64",t[t.COMPLEX64=14]="COMPLEX64",t[t.COMPLEX128=15]="COMPLEX128",t[t.BFLOAT16=16]="BFLOAT16"}(e=t.TensorDataType||(t.TensorDataType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.Primitive=0]="Primitive",t[t.Fused=1]="Fused"}(e=t.NodeType||(t.NodeType={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){let e;!function(t){t[t.NONE=0]="NONE",t[t.tensor_type=1]="tensor_type",t[t.sequence_type=2]="sequence_type",t[t.map_type=3]="map_type"}(e=t.TypeInfoValue||(t.TypeInfoValue={}))}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsShape(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dim(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Dimension).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}dimLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}static startShape(t){t.startObject(1)}static addDim(t,e){t.addFieldOffset(0,e,0)}static createDimVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startDimVector(t,e){t.startVector(4,e,4)}static endShape(t){return t.endObject()}static createShape(t,e){return n.startShape(t),n.addDim(t,e),n.endShape(t)}}e.Shape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimension(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimension(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}value(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.DimensionValue).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}denotation(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimension(t){t.startObject(2)}static addValue(t,e){t.addFieldOffset(0,e,0)}static addDenotation(t,e){t.addFieldOffset(1,e,0)}static endDimension(t){return t.endObject()}static createDimension(t,e,r){return n.startDimension(t),n.addValue(t,e),n.addDenotation(t,r),n.endDimension(t)}}e.Dimension=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsDimensionValue(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsDimensionValue(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}dimType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt8(this.bb_pos+e):t.experimental.fbs.DimensionValueType.UNKNOWN}dimValue(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}dimParam(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}static startDimensionValue(t){t.startObject(3)}static addDimType(e,n){e.addFieldInt8(0,n,t.experimental.fbs.DimensionValueType.UNKNOWN)}static addDimValue(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static addDimParam(t,e){t.addFieldOffset(2,e,0)}static endDimensionValue(t){return t.endObject()}static createDimensionValue(t,e,r,i){return n.startDimensionValue(t),n.addDimType(t,e),n.addDimValue(t,r),n.addDimParam(t,i),n.endDimensionValue(t)}}e.DimensionValue=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensorTypeAndShape(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensorTypeAndShape(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}shape(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Shape).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startTensorTypeAndShape(t){t.startObject(2)}static addElemType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addShape(t,e){t.addFieldOffset(1,e,0)}static endTensorTypeAndShape(t){return t.endObject()}static createTensorTypeAndShape(t,e,r){return n.startTensorTypeAndShape(t),n.addElemType(t,e),n.addShape(t,r),n.endTensorTypeAndShape(t)}}e.TensorTypeAndShape=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsMapType(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsMapType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}keyType(){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}valueType(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startMapType(t){t.startObject(2)}static addKeyType(e,n){e.addFieldInt32(0,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addValueType(t,e){t.addFieldOffset(1,e,0)}static endMapType(t){return t.endObject()}static createMapType(t,e,r){return n.startMapType(t),n.addKeyType(t,e),n.addValueType(t,r),n.endMapType(t)}}e.MapType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSequenceType(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSequenceType(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}elemType(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSequenceType(t){t.startObject(1)}static addElemType(t,e){t.addFieldOffset(0,e,0)}static endSequenceType(t){return t.endObject()}static createSequenceType(t,e){return n.startSequenceType(t),n.addElemType(t,e),n.endSequenceType(t)}}e.SequenceType=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){(t.fbs||(t.fbs={})).EdgeEnd=class{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static createEdgeEnd(t,e,n,r){return t.prep(4,12),t.writeInt32(r),t.writeInt32(n),t.writeInt32(e),t.offset()}}}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNodeEdge(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNodeEdge(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}nodeIndex(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readUint32(this.bb_pos+t):0}inputEdges(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,this.bb):null}inputEdgesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}outputEdges(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.EdgeEnd).__init(this.bb.__vector(this.bb_pos+r)+12*e,this.bb):null}outputEdgesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNodeEdge(t){t.startObject(3)}static addNodeIndex(t,e){t.addFieldInt32(0,e,0)}static addInputEdges(t,e){t.addFieldOffset(1,e,0)}static startInputEdgesVector(t,e){t.startVector(12,e,4)}static addOutputEdges(t,e){t.addFieldOffset(2,e,0)}static startOutputEdgesVector(t,e){t.startVector(12,e,4)}static endNodeEdge(t){return t.endObject()}static createNodeEdge(t,e,r,i){return n.startNodeEdge(t),n.addNodeIndex(t,e),n.addInputEdges(t,r),n.addOutputEdges(t,i),n.endNodeEdge(t)}}e.NodeEdge=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsNode(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsNode(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}sinceVersion(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readInt32(this.bb_pos+t):0}index(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readUint32(this.bb_pos+t):0}opType(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.NodeType.Primitive}executionProviderType(t){let e=this.bb.__offset(this.bb_pos,18);return e?this.bb.__string(this.bb_pos+e,t):null}inputs(t,e){let n=this.bb.__offset(this.bb_pos,20);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,22);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}attributes(e,n){let r=this.bb.__offset(this.bb_pos,24);return r?(n||new t.experimental.fbs.Attribute).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}attributesLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCounts(t){let e=this.bb.__offset(this.bb_pos,26);return e?this.bb.readInt32(this.bb.__vector(this.bb_pos+e)+4*t):0}inputArgCountsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}inputArgCountsArray(){let t=this.bb.__offset(this.bb_pos,26);return t?new Int32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}implicitInputs(t,e){let n=this.bb.__offset(this.bb_pos,28);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}implicitInputsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startNode(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDomain(t,e){t.addFieldOffset(2,e,0)}static addSinceVersion(t,e){t.addFieldInt32(3,e,0)}static addIndex(t,e){t.addFieldInt32(4,e,0)}static addOpType(t,e){t.addFieldOffset(5,e,0)}static addType(e,n){e.addFieldInt32(6,n,t.experimental.fbs.NodeType.Primitive)}static addExecutionProviderType(t,e){t.addFieldOffset(7,e,0)}static addInputs(t,e){t.addFieldOffset(8,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(9,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addAttributes(t,e){t.addFieldOffset(10,e,0)}static createAttributesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startAttributesVector(t,e){t.startVector(4,e,4)}static addInputArgCounts(t,e){t.addFieldOffset(11,e,0)}static createInputArgCountsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startInputArgCountsVector(t,e){t.startVector(4,e,4)}static addImplicitInputs(t,e){t.addFieldOffset(12,e,0)}static createImplicitInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startImplicitInputsVector(t,e){t.startVector(4,e,4)}static endNode(t){return t.endObject()}static createNode(t,e,r,i,o,a,s,u,c,l,p,f,d,h){return n.startNode(t),n.addName(t,e),n.addDocString(t,r),n.addDomain(t,i),n.addSinceVersion(t,o),n.addIndex(t,a),n.addOpType(t,s),n.addType(t,u),n.addExecutionProviderType(t,c),n.addInputs(t,l),n.addOutputs(t,p),n.addAttributes(t,f),n.addInputArgCounts(t,d),n.addImplicitInputs(t,h),n.endNode(t)}}e.Node=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsValueInfo(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsValueInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.TypeInfo).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startValueInfo(t){t.startObject(3)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(t,e){t.addFieldOffset(2,e,0)}static endValueInfo(t){return t.endObject()}static createValueInfo(t,e,r,i){return n.startValueInfo(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.endValueInfo(t)}}e.ValueInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTypeInfo(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTypeInfo(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}denotation(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}valueType(){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint8(this.bb_pos+e):t.experimental.fbs.TypeInfoValue.NONE}value(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__union(t,this.bb_pos+e):null}static startTypeInfo(t){t.startObject(3)}static addDenotation(t,e){t.addFieldOffset(0,e,0)}static addValueType(e,n){e.addFieldInt8(1,n,t.experimental.fbs.TypeInfoValue.NONE)}static addValue(t,e){t.addFieldOffset(2,e,0)}static endTypeInfo(t){return t.endObject()}static createTypeInfo(t,e,r,i){return n.startTypeInfo(t),n.addDenotation(t,e),n.addValueType(t,r),n.addValue(t,i),n.endTypeInfo(t)}}e.TypeInfo=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsOperatorSetId(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsOperatorSetId(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}domain(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}version(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}static startOperatorSetId(t){t.startObject(2)}static addDomain(t,e){t.addFieldOffset(0,e,0)}static addVersion(t,e){t.addFieldInt64(1,e,t.createLong(0,0))}static endOperatorSetId(t){return t.endObject()}static createOperatorSetId(t,n,r){return e.startOperatorSetId(t),e.addDomain(t,n),e.addVersion(t,r),e.endOperatorSetId(t)}}t.OperatorSetId=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsTensor(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}dataType(){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.TensorDataType.UNDEFINED}rawData(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.readUint8(this.bb.__vector(this.bb_pos+e)+t):0}rawDataLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}rawDataArray(){let t=this.bb.__offset(this.bb_pos,12);return t?new Uint8Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}stringData(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringDataLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}static startTensor(t){t.startObject(6)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static addDataType(e,n){e.addFieldInt32(3,n,t.experimental.fbs.TensorDataType.UNDEFINED)}static addRawData(t,e){t.addFieldOffset(4,e,0)}static createRawDataVector(t,e){t.startVector(1,e.length,1);for(let n=e.length-1;n>=0;n--)t.addInt8(e[n]);return t.endVector()}static startRawDataVector(t,e){t.startVector(1,e,1)}static addStringData(t,e){t.addFieldOffset(5,e,0)}static createStringDataVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startStringDataVector(t,e){t.startVector(4,e,4)}static endTensor(t){return t.endObject()}static createTensor(t,e,r,i,o,a,s){return n.startTensor(t),n.addName(t,e),n.addDocString(t,r),n.addDims(t,i),n.addDataType(t,o),n.addRawData(t,a),n.addStringData(t,s),n.endTensor(t)}}e.Tensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSparseTensor(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSparseTensor(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}values(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}indices(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}dims(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}dimsLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSparseTensor(t){t.startObject(3)}static addValues(t,e){t.addFieldOffset(0,e,0)}static addIndices(t,e){t.addFieldOffset(1,e,0)}static addDims(t,e){t.addFieldOffset(2,e,0)}static createDimsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startDimsVector(t,e){t.startVector(8,e,8)}static endSparseTensor(t){return t.endObject()}static createSparseTensor(t,e,r,i){return n.startSparseTensor(t),n.addValues(t,e),n.addIndices(t,r),n.addDims(t,i),n.endSparseTensor(t)}}e.SparseTensor=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsAttribute(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsAttribute(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}name(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}docString(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.__string(this.bb_pos+e,t):null}type(){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.readInt32(this.bb_pos+e):t.experimental.fbs.AttributeType.UNDEFINED}f(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readFloat32(this.bb_pos+t):0}i(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}s(t){let e=this.bb.__offset(this.bb_pos,14);return e?this.bb.__string(this.bb_pos+e,t):null}t(e){let n=this.bb.__offset(this.bb_pos,16);return n?(e||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}g(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}floats(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.readFloat32(this.bb.__vector(this.bb_pos+e)+4*t):0}floatsLength(){let t=this.bb.__offset(this.bb_pos,20);return t?this.bb.__vector_len(this.bb_pos+t):0}floatsArray(){let t=this.bb.__offset(this.bb_pos,20);return t?new Float32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}ints(t){let e=this.bb.__offset(this.bb_pos,22);return e?this.bb.readInt64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}intsLength(){let t=this.bb.__offset(this.bb_pos,22);return t?this.bb.__vector_len(this.bb_pos+t):0}strings(t,e){let n=this.bb.__offset(this.bb_pos,24);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}stringsLength(){let t=this.bb.__offset(this.bb_pos,24);return t?this.bb.__vector_len(this.bb_pos+t):0}tensors(e,n){let r=this.bb.__offset(this.bb_pos,26);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}tensorsLength(){let t=this.bb.__offset(this.bb_pos,26);return t?this.bb.__vector_len(this.bb_pos+t):0}graphs(e,n){let r=this.bb.__offset(this.bb_pos,28);return r?(n||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}graphsLength(){let t=this.bb.__offset(this.bb_pos,28);return t?this.bb.__vector_len(this.bb_pos+t):0}static startAttribute(t){t.startObject(13)}static addName(t,e){t.addFieldOffset(0,e,0)}static addDocString(t,e){t.addFieldOffset(1,e,0)}static addType(e,n){e.addFieldInt32(2,n,t.experimental.fbs.AttributeType.UNDEFINED)}static addF(t,e){t.addFieldFloat32(3,e,0)}static addI(t,e){t.addFieldInt64(4,e,t.createLong(0,0))}static addS(t,e){t.addFieldOffset(5,e,0)}static addT(t,e){t.addFieldOffset(6,e,0)}static addG(t,e){t.addFieldOffset(7,e,0)}static addFloats(t,e){t.addFieldOffset(8,e,0)}static createFloatsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addFloat32(e[n]);return t.endVector()}static startFloatsVector(t,e){t.startVector(4,e,4)}static addInts(t,e){t.addFieldOffset(9,e,0)}static createIntsVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startIntsVector(t,e){t.startVector(8,e,8)}static addStrings(t,e){t.addFieldOffset(10,e,0)}static createStringsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startStringsVector(t,e){t.startVector(4,e,4)}static addTensors(t,e){t.addFieldOffset(11,e,0)}static createTensorsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startTensorsVector(t,e){t.startVector(4,e,4)}static addGraphs(t,e){t.addFieldOffset(12,e,0)}static createGraphsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startGraphsVector(t,e){t.startVector(4,e,4)}static endAttribute(t){return t.endObject()}static createAttribute(t,e,r,i,o,a,s,u,c,l,p,f,d,h){return n.startAttribute(t),n.addName(t,e),n.addDocString(t,r),n.addType(t,i),n.addF(t,o),n.addI(t,a),n.addS(t,s),n.addT(t,u),n.addG(t,c),n.addFloats(t,l),n.addInts(t,p),n.addStrings(t,f),n.addTensors(t,d),n.addGraphs(t,h),n.endAttribute(t)}}e.Attribute=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsGraph(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsGraph(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}initializers(e,n){let r=this.bb.__offset(this.bb_pos,4);return r?(n||new t.experimental.fbs.Tensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}initializersLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeArgs(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.ValueInfo).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodeArgsLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}nodes(e,n){let r=this.bb.__offset(this.bb_pos,8);return r?(n||new t.experimental.fbs.Node).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodesLength(){let t=this.bb.__offset(this.bb_pos,8);return t?this.bb.__vector_len(this.bb_pos+t):0}maxNodeIndex(){let t=this.bb.__offset(this.bb_pos,10);return t?this.bb.readUint32(this.bb_pos+t):0}nodeEdges(e,n){let r=this.bb.__offset(this.bb_pos,12);return r?(n||new t.experimental.fbs.NodeEdge).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}nodeEdgesLength(){let t=this.bb.__offset(this.bb_pos,12);return t?this.bb.__vector_len(this.bb_pos+t):0}inputs(t,e){let n=this.bb.__offset(this.bb_pos,14);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}inputsLength(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.__vector_len(this.bb_pos+t):0}outputs(t,e){let n=this.bb.__offset(this.bb_pos,16);return n?this.bb.__string(this.bb.__vector(this.bb_pos+n)+4*t,e):null}outputsLength(){let t=this.bb.__offset(this.bb_pos,16);return t?this.bb.__vector_len(this.bb_pos+t):0}sparseInitializers(e,n){let r=this.bb.__offset(this.bb_pos,18);return r?(n||new t.experimental.fbs.SparseTensor).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}sparseInitializersLength(){let t=this.bb.__offset(this.bb_pos,18);return t?this.bb.__vector_len(this.bb_pos+t):0}static startGraph(t){t.startObject(8)}static addInitializers(t,e){t.addFieldOffset(0,e,0)}static createInitializersVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInitializersVector(t,e){t.startVector(4,e,4)}static addNodeArgs(t,e){t.addFieldOffset(1,e,0)}static createNodeArgsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodeArgsVector(t,e){t.startVector(4,e,4)}static addNodes(t,e){t.addFieldOffset(2,e,0)}static createNodesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodesVector(t,e){t.startVector(4,e,4)}static addMaxNodeIndex(t,e){t.addFieldInt32(3,e,0)}static addNodeEdges(t,e){t.addFieldOffset(4,e,0)}static createNodeEdgesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startNodeEdgesVector(t,e){t.startVector(4,e,4)}static addInputs(t,e){t.addFieldOffset(5,e,0)}static createInputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startInputsVector(t,e){t.startVector(4,e,4)}static addOutputs(t,e){t.addFieldOffset(6,e,0)}static createOutputsVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOutputsVector(t,e){t.startVector(4,e,4)}static addSparseInitializers(t,e){t.addFieldOffset(7,e,0)}static createSparseInitializersVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startSparseInitializersVector(t,e){t.startVector(4,e,4)}static endGraph(t){return t.endObject()}static createGraph(t,e,r,i,o,a,s,u,c){return n.startGraph(t),n.addInitializers(t,e),n.addNodeArgs(t,r),n.addNodes(t,i),n.addMaxNodeIndex(t,o),n.addNodeEdges(t,a),n.addInputs(t,s),n.addOutputs(t,u),n.addSparseInitializers(t,c),n.endGraph(t)}}e.Graph=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsModel(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsModel(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}irVersion(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}opsetImport(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.OperatorSetId).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}opsetImportLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}producerName(t){let e=this.bb.__offset(this.bb_pos,8);return e?this.bb.__string(this.bb_pos+e,t):null}producerVersion(t){let e=this.bb.__offset(this.bb_pos,10);return e?this.bb.__string(this.bb_pos+e,t):null}domain(t){let e=this.bb.__offset(this.bb_pos,12);return e?this.bb.__string(this.bb_pos+e,t):null}modelVersion(){let t=this.bb.__offset(this.bb_pos,14);return t?this.bb.readInt64(this.bb_pos+t):this.bb.createLong(0,0)}docString(t){let e=this.bb.__offset(this.bb_pos,16);return e?this.bb.__string(this.bb_pos+e,t):null}graph(e){let n=this.bb.__offset(this.bb_pos,18);return n?(e||new t.experimental.fbs.Graph).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}graphDocString(t){let e=this.bb.__offset(this.bb_pos,20);return e?this.bb.__string(this.bb_pos+e,t):null}static startModel(t){t.startObject(9)}static addIrVersion(t,e){t.addFieldInt64(0,e,t.createLong(0,0))}static addOpsetImport(t,e){t.addFieldOffset(1,e,0)}static createOpsetImportVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startOpsetImportVector(t,e){t.startVector(4,e,4)}static addProducerName(t,e){t.addFieldOffset(2,e,0)}static addProducerVersion(t,e){t.addFieldOffset(3,e,0)}static addDomain(t,e){t.addFieldOffset(4,e,0)}static addModelVersion(t,e){t.addFieldInt64(5,e,t.createLong(0,0))}static addDocString(t,e){t.addFieldOffset(6,e,0)}static addGraph(t,e){t.addFieldOffset(7,e,0)}static addGraphDocString(t,e){t.addFieldOffset(8,e,0)}static endModel(t){return t.endObject()}static createModel(t,e,r,i,o,a,s,u,c,l){return n.startModel(t),n.addIrVersion(t,e),n.addOpsetImport(t,r),n.addProducerName(t,i),n.addProducerVersion(t,o),n.addDomain(t,a),n.addModelVersion(t,s),n.addDocString(t,u),n.addGraph(t,c),n.addGraphDocString(t,l),n.endModel(t)}}e.Model=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(t){!function(t){class e{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsKernelCreateInfos(t,n){return(n||new e).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsKernelCreateInfos(t,n){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(n||new e).__init(t.readInt32(t.position())+t.position(),t)}nodeIndices(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.readUint32(this.bb.__vector(this.bb_pos+e)+4*t):0}nodeIndicesLength(){let t=this.bb.__offset(this.bb_pos,4);return t?this.bb.__vector_len(this.bb_pos+t):0}nodeIndicesArray(){let t=this.bb.__offset(this.bb_pos,4);return t?new Uint32Array(this.bb.bytes().buffer,this.bb.bytes().byteOffset+this.bb.__vector(this.bb_pos+t),this.bb.__vector_len(this.bb_pos+t)):null}kernelDefHashes(t){let e=this.bb.__offset(this.bb_pos,6);return e?this.bb.readUint64(this.bb.__vector(this.bb_pos+e)+8*t):this.bb.createLong(0,0)}kernelDefHashesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startKernelCreateInfos(t){t.startObject(2)}static addNodeIndices(t,e){t.addFieldOffset(0,e,0)}static createNodeIndicesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addInt32(e[n]);return t.endVector()}static startNodeIndicesVector(t,e){t.startVector(4,e,4)}static addKernelDefHashes(t,e){t.addFieldOffset(1,e,0)}static createKernelDefHashesVector(t,e){t.startVector(8,e.length,8);for(let n=e.length-1;n>=0;n--)t.addInt64(e[n]);return t.endVector()}static startKernelDefHashesVector(t,e){t.startVector(8,e,8)}static endKernelCreateInfos(t){return t.endObject()}static createKernelCreateInfos(t,n,r){return e.startKernelCreateInfos(t),e.addNodeIndices(t,n),e.addKernelDefHashes(t,r),e.endKernelCreateInfos(t)}}t.KernelCreateInfos=e}(t.fbs||(t.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSubGraphSessionState(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSubGraphSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}graphId(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startSubGraphSessionState(t){t.startObject(2)}static addGraphId(t,e){t.addFieldOffset(0,e,0)}static addSessionState(t,e){t.addFieldOffset(1,e,0)}static endSubGraphSessionState(t){let e=t.endObject();return t.requiredField(e,4),e}static createSubGraphSessionState(t,e,r){return n.startSubGraphSessionState(t),n.addGraphId(t,e),n.addSessionState(t,r),n.endSubGraphSessionState(t)}}e.SubGraphSessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsSessionState(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsSessionState(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}kernels(e){let n=this.bb.__offset(this.bb_pos,4);return n?(e||new t.experimental.fbs.KernelCreateInfos).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}subGraphSessionStates(e,n){let r=this.bb.__offset(this.bb_pos,6);return r?(n||new t.experimental.fbs.SubGraphSessionState).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos+r)+4*e),this.bb):null}subGraphSessionStatesLength(){let t=this.bb.__offset(this.bb_pos,6);return t?this.bb.__vector_len(this.bb_pos+t):0}static startSessionState(t){t.startObject(2)}static addKernels(t,e){t.addFieldOffset(0,e,0)}static addSubGraphSessionStates(t,e){t.addFieldOffset(1,e,0)}static createSubGraphSessionStatesVector(t,e){t.startVector(4,e.length,4);for(let n=e.length-1;n>=0;n--)t.addOffset(e[n]);return t.endVector()}static startSubGraphSessionStatesVector(t,e){t.startVector(4,e,4)}static endSessionState(t){return t.endObject()}static createSessionState(t,e,r){return n.startSessionState(t),n.addKernels(t,e),n.addSubGraphSessionStates(t,r),n.endSessionState(t)}}e.SessionState=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={})),function(t){!function(e){!function(e){class n{constructor(){this.bb=null,this.bb_pos=0}__init(t,e){return this.bb_pos=t,this.bb=e,this}static getRootAsInferenceSession(t,e){return(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static getSizePrefixedRootAsInferenceSession(t,e){return t.setPosition(t.position()+r.flatbuffers.SIZE_PREFIX_LENGTH),(e||new n).__init(t.readInt32(t.position())+t.position(),t)}static bufferHasIdentifier(t){return t.__has_identifier("ORTM")}ortVersion(t){let e=this.bb.__offset(this.bb_pos,4);return e?this.bb.__string(this.bb_pos+e,t):null}model(e){let n=this.bb.__offset(this.bb_pos,6);return n?(e||new t.experimental.fbs.Model).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}sessionState(e){let n=this.bb.__offset(this.bb_pos,8);return n?(e||new t.experimental.fbs.SessionState).__init(this.bb.__indirect(this.bb_pos+n),this.bb):null}static startInferenceSession(t){t.startObject(3)}static addOrtVersion(t,e){t.addFieldOffset(0,e,0)}static addModel(t,e){t.addFieldOffset(1,e,0)}static addSessionState(t,e){t.addFieldOffset(2,e,0)}static endInferenceSession(t){return t.endObject()}static finishInferenceSessionBuffer(t,e){t.finish(e,"ORTM")}static finishSizePrefixedInferenceSessionBuffer(t,e){t.finish(e,"ORTM",!0)}static createInferenceSession(t,e,r,i){return n.startInferenceSession(t),n.addOrtVersion(t,e),n.addModel(t,r),n.addSessionState(t,i),n.endInferenceSession(t)}}e.InferenceSession=n}(e.fbs||(e.fbs={}))}(t.experimental||(t.experimental={}))}(e.onnxruntime||(e.onnxruntime={}))},7448:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxjsSessionHandler=void 0;const r=n(1670),i=n(9162);e.OnnxjsSessionHandler=class{constructor(t){this.session=t,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}async dispose(){}async run(t,e,n){const o=new Map;for(const e in t)if(Object.hasOwnProperty.call(t,e)){const n=t[e];o.set(e,new i.Tensor(n.dims,n.type,void 0,void 0,n.data))}const a=await this.session.run(o),s={};return a.forEach(((t,e)=>{s[e]=new r.Tensor(t.type,t.data,t.dims)})),s}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}},6919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Session=void 0;const r=n(7067),i=n(1296),o=n(7091),a=n(1036),s=n(6231),u=n(2644);e.Session=class{constructor(t={}){this._initialized=!1,this.backendHint=t.backendHint,this.profiler=s.Profiler.create(t.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(t,e,n){await this.profiler.event("session","Session.loadModel",(async()=>{const a=await(0,o.resolveBackend)(this.backendHint);if(this.sessionHandler=a.createSessionHandler(this.context),this._model=new u.Model,"string"==typeof t){const e=t.endsWith(".ort");if("undefined"==typeof fetch){const n=await(0,i.promisify)(r.readFile)(t);this.initialize(n,e)}else{const n=await fetch(t),r=await n.arrayBuffer();this.initialize(new Uint8Array(r),e)}}else if(ArrayBuffer.isView(t))this.initialize(t);else{const r=new Uint8Array(t,e||0,n||t.byteLength);this.initialize(r)}}))}initialize(t,e){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",(()=>{const n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(t,n,e),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new a.ExecutionPlan(this._model.graph,this._ops,this.profiler)})),this._initialized=!0}async run(t){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",(async()=>{const e=this.normalizeAndValidateInputs(t),n=await this._executionPlan.execute(this.sessionHandler,e);return this.createOutput(n)}))}normalizeAndValidateInputs(t){const e=this._model.graph.getInputNames();if(Array.isArray(t)){if(t.length!==e.length)throw new Error(`incorrect input array length: expected ${e.length} but got ${t.length}`)}else{if(t.size!==e.length)throw new Error(`incorrect input map size: expected ${e.length} but got ${t.size}`);const n=new Array(t.size);let r=0;for(let i=0;i"string"==typeof t))))throw new TypeError("cache should be a string array");c&&(this.cache=new Array(s))}else{if(void 0!==o){const t=f(e);if(!(o instanceof t))throw new TypeError(`cache should be type ${t.name}`)}if(c){const t=new ArrayBuffer(s*function(t){switch(t){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${t}`)}}(e));this.cache=function(t,e){return new(f(e))(t)}(t,e)}}}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");const e=u.ProtoUtil.tensorDataTypeFromProto(t.dataType),n=u.ProtoUtil.tensorDimsFromProto(t.dims),r=new l(n,e);if("string"===e)t.stringData.forEach(((t,e)=>{r.data[e]=(0,u.decodeUtf8String)(t)}));else if(t.rawData&&"number"==typeof t.rawData.byteLength&&t.rawData.byteLength>0){const e=r.data,n=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),i=p(t.dataType),o=t.rawData.byteLength/i;if(t.rawData.byteLength%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r0){const e=r.data,n=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),i=p(t.dataType()),o=t.rawDataLength()/i;if(t.rawDataLength()%i!=0)throw new Error("invalid buffer length");if(e.length!==o)throw new Error("buffer length mismatch");for(let r=0;r1&&u>1)return;a[o-s]=Math.max(n,u)}return a}static index(t,e){const n=new Array(e.length);return c.fillIndex(t,e,n),n}static fillIndex(t,e,n){const r=t.length-e.length;for(let i=0;i=0;t--)r[t]=l%o[t],l=Math.floor(l/o[t]);d||(c.fillIndex(r,t.dims,i),p=t.get(i)),h||(c.fillIndex(r,e.dims,s),f=e.get(s)),u.set(r,n(p,f))}}return u}}static isValidBroadcast(t,e){const n=t.length,r=e.length;if(n>r)return!1;for(let i=1;i<=n;i++)if(1!==t[n-i]&&t[n-i]!==e[r-i])return!1;return!0}static getBroadcastDims(t,e){const n=t.length,r=[];for(let i=0;i1&&1===a&&r.unshift(o)}return r}}e.BroadcastUtil=c,e.arrayCopyHelper=function(t,e,n,r,i){if(r<0||r>=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;oo.default.isLong(t)?t.toNumber():t))}static tensorValueTypeFromProto(t){return{tensorType:l.tensorDataTypeFromProto(t.elemType),shape:{dims:l.tensorDimsFromProto(t.shape.dim.map((t=>t.dimValue)))}}}static tensorDimsFromORTFormat(t){const e=[];for(let n=0;nt.length)throw new Error(`invalid dimension of ${e} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return f.getSizeFromDimensionRange(t,e,t.length)}static sizeToDimension(t,e){if(e<0||e>t.length)throw new Error(`invalid dimension of ${e} for sizeToDimension as Tensor has ${t.length} dimensions.`);return f.getSizeFromDimensionRange(t,0,e)}static getSizeFromDimensionRange(t,e,n){let r=1;for(let i=e;i=0;--r)n[r]=n[r+1]*t[r+1];return n}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,e,n){void 0===n&&(n=t.length);let r=0;for(let i=0;i=e)throw new Error("unsupported axis for this operation.");return t<0?t+e:t}static normalizeAxes(t,e){return t.map((t=>this.normalizeAxis(t,e)))}static incrementIndex(t,e,n){if(0===e.length||0===t.length)throw new Error("Index incrementing unsupported for scalar Tensor");if(void 0===n)n=e.length;else if(n<=0||n>e.length)throw new Error("Incorrect axis to increment on");for(let r=n-1;r>=0&&(t[r]++,!(t[r]=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");r[a]=t[a]}else r[a]=e[a];o*=r[a]}}const a=f.size(t);if(-1!==i){if(a%o!=0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${e}]`);r[i]=a/o}else if(o!==a)throw new Error("reshapedDims and originalDims don't have matching sizes");return r}static sortBasedOnPerm(t,e){return e?e.map((e=>t[e])):t.slice().reverse()}static padShape(t,e){const n=t.length;return t.map(((t,r)=>t+e[r]+e[r+n]))}static areEqual(t,e){return t.length===e.length&&t.every(((t,n)=>t===e[n]))}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let e=1;for(const n of t){if(!Number.isInteger(n))throw new TypeError(`Invalid shape: ${n} is not an integer`);if(n<0||n>2147483647)throw new TypeError(`Invalid shape: length ${n} is not allowed`);e*=n}return e}static flattenShape(t,e){e<0&&(e+=t.length);const n=t.reduce(((t,e)=>t*e),1),r=t.slice(e).reduce(((t,e)=>t*e),1);return[n/r,r]}static squeezeShape(t,e){const n=new Array;e=f.normalizeAxes(e,t.length);for(let r=0;r=0;if(i&&1!==t[r])throw new Error("squeeze an axis of size different than 1");(0===e.length&&t[r]>1||e.length>0&&!i)&&n.push(t[r])}return n}static unsqueezeShape(t,e){const n=new Array(t.length+e.length);n.fill(0);for(let t=0;t=n.length)throw new Error("'axes' has an out of range axis");if(0!==n[r])throw new Error("'axes' has a duplicate axis");n[r]=1}let r=0;for(let e=0;e=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;o=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let a=0;a=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let a=0;a=e.length)throw new Error("sourceIndex out of bounds");if(n<0||n>=t.length)throw new Error("targetIndex out of bounds");if(r+i>e.length)throw new Error("source indices to be copied are outside bounds");if(n+i>t.length)throw new Error("target array is too small to hold result");for(let o=0;oe.push(n)));const a=h.calcReduceShape(o,e,!0),u=f.size(a),l=new s.Tensor(a,t.type),p=f.computeStrides(a),d=f.computeStrides(o),g=new Array(o.length);for(let n=0;n=e.length)return o(t[i]);const u=e[r],c=u>=n.length?1:f.size(n.slice(u+1));for(let l=0;l0!==t))}}e.ReduceUtil=h;class g{static adjustPoolAttributes(t,e,n,r,i,o){if(!t&&n.length!==e.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let t=0;t=n.length?n.push(e[t+2]):n[t]=e[t+2];for(let t=0;t=n[t]||o[t+n.length]>=n[t])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,e,n,r,i,o){if(o){if(i.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(e.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(r.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,i)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,o])=>{const a=n?n+t:t;if("object"==typeof o)(0,e.iterateExtraOptions)(o,a+".",r,i);else if("string"==typeof o||"number"==typeof o)i(a,o.toString());else{if("boolean"!=typeof o)throw new Error("Can't handle extra config type: "+typeof o);i(a,o?"1":"0")}}))}},2157:function(t,e,n){"use strict";var r,i=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),o=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),a=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&i(e,t,n);return o(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=e.initWasm=void 0;const s=n(1670),u=a(n(349)),c=n(6361),l=()=>!!s.env.wasm.proxy&&"undefined"!=typeof document;let p,f,d,h=!1,g=!1,b=!1;const m=[],y=[],_=[],v=[],w=[],x=[],T=()=>{if(h||!g||b||!p)throw new Error("worker not ready")},S=t=>{switch(t.data.type){case"init-wasm":h=!1,t.data.err?(b=!0,f[1](t.data.err)):(g=!0,f[0]());break;case"init-ort":t.data.err?d[1](t.data.err):d[0]();break;case"create_allocate":t.data.err?m.shift()[1](t.data.err):m.shift()[0](t.data.out);break;case"create_finalize":t.data.err?y.shift()[1](t.data.err):y.shift()[0](t.data.out);break;case"create":t.data.err?_.shift()[1](t.data.err):_.shift()[0](t.data.out);break;case"release":t.data.err?v.shift()[1](t.data.err):v.shift()[0]();break;case"run":t.data.err?w.shift()[1](t.data.err):w.shift()[0](t.data.out);break;case"end-profiling":t.data.err?x.shift()[1](t.data.err):x.shift()[0]()}},O="undefined"!=typeof document?null===(r=null===document||void 0===document?void 0:document.currentScript)||void 0===r?void 0:r.src:void 0;e.initWasm=async()=>{if(l()){if(g)return;if(h)throw new Error("multiple calls to 'initWasm()' detected.");if(b)throw new Error("previous call to 'initWasm()' failed.");return h=!0,void 0===s.env.wasm.wasmPaths&&O&&0!==O.indexOf("blob:")&&(s.env.wasm.wasmPaths=O.substr(0,+O.lastIndexOf("/")+1)),new Promise(((t,e)=>{null==p||p.terminate(),p=n(9710).Z(),p.onmessage=S,f=[t,e];const r={type:"init-wasm",in:s.env.wasm};p.postMessage(r)}))}return(0,c.initializeWebAssembly)(s.env.wasm)},e.initOrt=async(t,e)=>{if(l())return T(),new Promise(((n,r)=>{d=[n,r];const i={type:"init-ort",in:{numThreads:t,loggingLevel:e}};p.postMessage(i)}));u.initOrt(t,e)},e.createSessionAllocate=async t=>l()?(T(),new Promise(((e,n)=>{m.push([e,n]);const r={type:"create_allocate",in:{model:t}};p.postMessage(r,[t.buffer])}))):u.createSessionAllocate(t),e.createSessionFinalize=async(t,e)=>l()?(T(),new Promise(((n,r)=>{y.push([n,r]);const i={type:"create_finalize",in:{modeldata:t,options:e}};p.postMessage(i)}))):u.createSessionFinalize(t,e),e.createSession=async(t,e)=>l()?(T(),new Promise(((n,r)=>{_.push([n,r]);const i={type:"create",in:{model:t,options:e}};p.postMessage(i,[t.buffer])}))):u.createSession(t,e),e.releaseSession=async t=>{if(l())return T(),new Promise(((e,n)=>{v.push([e,n]);const r={type:"release",in:t};p.postMessage(r)}));u.releaseSession(t)},e.run=async(t,e,n,r,i)=>l()?(T(),new Promise(((o,a)=>{w.push([o,a]);const s={type:"run",in:{sessionId:t,inputIndices:e,inputs:n,outputIndices:r,options:i}};p.postMessage(s,u.extractTransferableBuffers(n))}))):u.run(t,e,n,r,i),e.endProfiling=async t=>{if(l())return T(),new Promise(((e,n)=>{x.push([e,n]);const r={type:"end-profiling",in:t};p.postMessage(r)}));u.endProfiling(t)}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setRunOptions=t=>{const e=(0,o.getInstance)();let n=0;const a=[],s=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))s.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))s.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(s.terminate=!1);let o=0;if(void 0!==(null==t?void 0:t.tag)&&(o=(0,i.allocWasmString)(t.tag,a)),n=e._OrtCreateRunOptions(s.logSeverityLevel,s.logVerbosityLevel,!!s.terminate,o),0===n)throw new Error("Can't create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const o=(0,i.allocWasmString)(t,a),s=(0,i.allocWasmString)(r,a);if(0!==e._OrtAddRunConfigEntry(n,o,s))throw new Error(`Can't set a run config entry: ${t} - ${r}`)})),[n,a]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),a.forEach(e._free),t}}},2306:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.OnnxruntimeWebAssemblySessionHandler=void 0;const r=n(2806),i=n(1670),o=n(2850),a=n(2157);let s;e.OnnxruntimeWebAssemblySessionHandler=class{async createSessionAllocate(t){const e=await fetch(t),n=await e.arrayBuffer();return(0,a.createSessionAllocate)(new Uint8Array(n))}async loadModel(t,e){if(s||(await(0,a.initOrt)(i.env.wasm.numThreads,(t=>{switch(t){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${t}`)}})(i.env.logLevel)),s=!0),"string"==typeof t)if("undefined"==typeof fetch){const n=await(0,o.promisify)(r.readFile)(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(n,e)}else{const n=await this.createSessionAllocate(t);[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSessionFinalize)(n,e)}else[this.sessionId,this.inputNames,this.outputNames]=await(0,a.createSession)(t,e)}async dispose(){return(0,a.releaseSession)(this.sessionId)}async run(t,e,n){const r=[],o=[];Object.entries(t).forEach((t=>{const e=t[0],n=t[1],i=this.inputNames.indexOf(e);if(-1===i)throw new Error(`invalid input '${e}'`);r.push(n),o.push(i)}));const s=[];Object.entries(e).forEach((t=>{const e=t[0],n=this.outputNames.indexOf(e);if(-1===n)throw new Error(`invalid output '${e}'`);s.push(n)}));const u=await(0,a.run)(this.sessionId,o,r.map((t=>[t.type,t.dims,t.data])),s,n),c={};for(let t=0;t{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(7967),i=n(4983),o=n(6361);e.setSessionOptions=t=>{const e=(0,o.getInstance)();let n=0;const a=[],s=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(s);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(s.graphOptimizationLevel="all");const u=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(s.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(s.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(s.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(s.executionMode="sequential");const c=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(s.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,i.allocWasmString)(t.logId,a)),void 0===(null==t?void 0:t.logSeverityLevel))s.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))s.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(s.enableProfiling=!1),n=e._OrtCreateSessionOptions(u,!!s.enableCpuMemArena,!!s.enableMemPattern,c,!!s.enableProfiling,0,l,s.logSeverityLevel,s.logVerbosityLevel),0===n)throw new Error("Can't create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const a=(0,i.allocWasmString)(e,n);if(0!==(0,o.getInstance)()._OrtAppendExecutionProvider(t,a))throw new Error(`Can't append execution provider: ${e}`)}})(n,t.executionProviders,a),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const o=(0,i.allocWasmString)(t,a),s=(0,i.allocWasmString)(r,a);if(0!==e._OrtAddSessionConfigEntry(n,o,s))throw new Error(`Can't set a session config entry: ${t} - ${r}`)})),[n,a]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),a.forEach(e._free),t}}},4983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(6361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),i=n.lengthBytesUTF8(t)+1,o=n._malloc(i);return n.stringToUTF8(t,o,i),e.push(o),o}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),i=n(4919),o=n(4983),a=n(6361);e.initOrt=(t,e)=>{const n=(0,a.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can't initialize onnxruntime. error code = ${n}`)};const s=new Map;e.createSessionAllocate=t=>{const e=(0,a.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,a.getInstance)();let r=0,o=0,u=[];try{if([o,u]=(0,i.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],o),0===r)throw new Error("Can't create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(o),u.forEach(n._free)}const c=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),p=[],f=[],d=[],h=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,a.getInstance)(),n=s.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=n[1],o=n[2];i.forEach(e._OrtFree),o.forEach(e._OrtFree),e._OrtReleaseSession(r),s.delete(t)};const u=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},c=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,i,p)=>{const f=(0,a.getInstance)(),d=s.get(t);if(!d)throw new Error("invalid session id");const h=d[0],g=d[1],b=d[2],m=e.length,y=i.length;let _=0,v=[];const w=[],x=[];try{[_,v]=(0,r.setRunOptions)(p);for(let t=0;tf.HEAP32[t++]=e));const n=f._OrtCreateTensor(u(e),a,s,l,r.length);if(0===n)throw new Error("Can't create a tensor");w.push(n)}finally{f.stackRestore(c)}}const t=f.stackSave(),a=f.stackAlloc(4*m),s=f.stackAlloc(4*m),d=f.stackAlloc(4*y),T=f.stackAlloc(4*y);try{let n=a/4,r=s/4,o=d/4,u=T/4;for(let t=0;tt*e));if(i=c(a),"string"===i){const t=[];let e=o/4;for(let n=0;n{const e=(0,a.getInstance)(),n=s.get(t);if(!n)throw new Error("invalid session id");const r=n[0],i=e._OrtEndProfiling(r);if(0===i)throw new Error("Can't get an profile file name");e._OrtFree(i)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},6361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(e,n);i&&!("get"in i?!e.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,i)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),i=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return i(e,t),e},a=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const s=o(n(6449)),u=a(n(932)),c=n(3474);let l,p=!1,f=!1,d=!1;const h=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(p)return Promise.resolve();if(f)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(d)throw new Error("previous call to 'initializeWebAssembly()' failed.");f=!0;const e=t.initTimeout,r=t.numThreads,i=t.simd,o=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),a=i&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),g="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=h(!1,o),m=h(a,o),y="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let _=!1;const v=[];if(e>0&&v.push(new Promise((t=>{setTimeout((()=>{_=!0,t()}),e)}))),v.push(new Promise(((t,e)=>{const r=o?c:u.default,i={locateFile:(t,e)=>o&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(4154)],{type:"text/javascript"})):t===b?null!=y?y:(null!=g?g:e)+m:e+t};if(o)if("undefined"==typeof Blob)i.mainScriptUrlOrBlob=s.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;i.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(i).then((e=>{f=!1,p=!0,l=e,t()}),(t=>{f=!1,d=!0,e(t)}))}))),await Promise.race(v),_)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(p&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!p||f||d||(f=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,f=!1,p=!1,d=!0)}},9710:(t,e,n)=>{"use strict";n.d(e,{Z:()=>o});var r=n(477),i=n.n(r);function o(){return i()('/*!\n* ONNX Runtime Web v1.14.0\n* Copyright (c) Microsoft Corporation. All rights reserved.\n* Licensed under the MIT License.\n*/\n(()=>{var t={474:(t,e,n)=>{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){function e(){return j.buffer!=D&&N(j.buffer),P}function r(){return j.buffer!=D&&N(j.buffer),U}function a(){return j.buffer!=D&&N(j.buffer),F}function i(){return j.buffer!=D&&N(j.buffer),I}function o(){return j.buffer!=D&&N(j.buffer),W}var u,c,s;t=t||{},u||(u=void 0!==t?t:{}),u.ready=new Promise((function(t,e){c=t,s=e}));var l,f,p,h,d,y,b=Object.assign({},u),m="./this.program",g=(t,e)=>{throw e},v="object"==typeof window,w="function"==typeof importScripts,_="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,O=u.ENVIRONMENT_IS_PTHREAD||!1,A="";function S(t){return u.locateFile?u.locateFile(t,A):A+t}if(_){let e;A=w?n(908).dirname(A)+"/":"//",y=()=>{d||(h=n(384),d=n(908))},l=function(t,e){return y(),t=d.normalize(t),h.readFileSync(t,e?void 0:"utf8")},p=t=>((t=l(t,!0)).buffer||(t=new Uint8Array(t)),t),f=(t,e,n)=>{y(),t=d.normalize(t),h.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(Q())throw process.exitCode=t,e;e instanceof ct||x("exiting due to exception: "+e),process.exit(t)},u.inspect=function(){return"[Emscripten Module object]"};try{e=n(925)}catch(t){throw console.error(\'The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?\'),t}n.g.Worker=e.Worker}else(v||w)&&(w?A=self.location.href:"undefined"!=typeof document&&document.currentScript&&(A=document.currentScript.src),_scriptDir&&(A=_scriptDir),A=0!==A.indexOf("blob:")?A.substr(0,A.replace(/[?#].*/,"").lastIndexOf("/")+1):"",_||(l=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},w&&(p=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),f=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)}));_&&"undefined"==typeof performance&&(n.g.performance=n(953).performance);var T=console.log.bind(console),E=console.warn.bind(console);_&&(y(),T=t=>h.writeSync(1,t+"\\n"),E=t=>h.writeSync(2,t+"\\n"));var M,C=u.print||T,x=u.printErr||E;Object.assign(u,b),b=null,u.thisProgram&&(m=u.thisProgram),u.quit&&(g=u.quit),u.wasmBinary&&(M=u.wasmBinary);var R=u.noExitRuntime||!1;"object"!=typeof WebAssembly&&at("no native wasm support detected");var j,k,D,P,U,F,I,W,H=!1,L="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function z(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function Y(t,e){return(t>>>=0)?z(r(),t,e):""}function B(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function G(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function N(t){D=t,u.HEAP8=P=new Int8Array(t),u.HEAP16=new Int16Array(t),u.HEAP32=F=new Int32Array(t),u.HEAPU8=U=new Uint8Array(t),u.HEAPU16=new Uint16Array(t),u.HEAPU32=I=new Uint32Array(t),u.HEAPF32=new Float32Array(t),u.HEAPF64=W=new Float64Array(t)}O&&(D=u.buffer);var V=u.INITIAL_MEMORY||16777216;if(O)j=u.wasmMemory,D=u.buffer;else if(u.wasmMemory)j=u.wasmMemory;else if(!((j=new WebAssembly.Memory({initial:V/65536,maximum:65536,shared:!0})).buffer instanceof SharedArrayBuffer))throw x("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),_&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");j&&(D=j.buffer),V=D.byteLength,N(D);var $,q=[],X=[],J=[],Z=[];function Q(){return R||!1}function K(){var t=u.preRun.shift();q.unshift(t)}var tt,et=0,nt=null,rt=null;function at(t){throw O?postMessage({cmd:"onAbort",arg:t}):u.onAbort&&u.onAbort(t),x(t="Aborted("+t+")"),H=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),s(t),t}function it(){return tt.startsWith("data:application/octet-stream;base64,")}function ot(){var t=tt;try{if(t==tt&&M)return new Uint8Array(M);if(p)return p(t);throw"both async and sync fetching of the wasm failed"}catch(t){at(t)}}tt="ort-wasm-threaded.wasm",it()||(tt=S(tt));var ut={};function ct(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function st(t){(t=ht.Vb[t])||at(),ht.mc(t)}function lt(t){var e=ht.Cc();if(!e)return 6;ht.ac.push(e),ht.Vb[t.Ub]=e,e.Ub=t.Ub;var n={cmd:"run",start_routine:t.Ic,arg:t.zc,pthread_ptr:t.Ub};return e.$b=()=>{n.time=performance.now(),e.postMessage(n,t.Nc)},e.loaded&&(e.$b(),delete e.$b),0}function ft(t){if(O)return $t(1,1,t);Q()||(ht.oc(),u.onExit&&u.onExit(t),H=!0),g(t,new ct(t))}function pt(t,e){if(!e&&O)throw bt(t),"unwind";Q()||O||(me(),dt(J),be(0),re[1].length&&ae(1,10),re[2].length&&ae(2,10),ht.oc()),ft(t)}var ht={Yb:[],ac:[],qc:[],Vb:{},fc:function(){O&&ht.Ec()},Pc:function(){},Ec:function(){ht.receiveObjectTransfer=ht.Gc,ht.threadInitTLS=ht.pc,ht.setExitStatus=ht.nc,R=!1},nc:function(){},oc:function(){for(var t of Object.values(ht.Vb))ht.mc(t);for(t of ht.Yb)t.terminate();ht.Yb=[]},mc:function(t){var e=t.Ub;delete ht.Vb[e],ht.Yb.push(t),ht.ac.splice(ht.ac.indexOf(t),1),t.Ub=0,Oe(e)},Gc:function(){},pc:function(){ht.qc.forEach((t=>t()))},Fc:function(t,e){t.onmessage=n=>{var r=(n=n.data).cmd;if(t.Ub&&(ht.Bc=t.Ub),n.targetThread&&n.targetThread!=he()){var a=ht.Vb[n.Qc];a?a.postMessage(n,n.transferList):x(\'Internal error! Worker sent a message "\'+r+\'" to target pthread \'+n.targetThread+", but that thread no longer exists!")}else"processProxyingQueue"===r?zt(n.queue):"spawnThread"===r?lt(n):"cleanupThread"===r?st(n.thread):"killThread"===r?(n=n.thread,r=ht.Vb[n],delete ht.Vb[n],r.terminate(),Oe(n),ht.ac.splice(ht.ac.indexOf(r),1),r.Ub=0):"cancelThread"===r?ht.Vb[n.thread].postMessage({cmd:"cancel"}):"loaded"===r?(t.loaded=!0,e&&e(t),t.$b&&(t.$b(),delete t.$b)):"print"===r?C("Thread "+n.threadId+": "+n.text):"printErr"===r?x("Thread "+n.threadId+": "+n.text):"alert"===r?alert("Thread "+n.threadId+": "+n.text):"setimmediate"===n.target?t.postMessage(n):"onAbort"===r?u.onAbort&&u.onAbort(n.arg):r&&x("worker sent an unknown command "+r);ht.Bc=void 0},t.onerror=t=>{throw x("worker sent an error! "+t.filename+":"+t.lineno+": "+t.message),t},_&&(t.on("message",(function(e){t.onmessage({data:e})})),t.on("error",(function(e){t.onerror(e)})),t.on("detachedExit",(function(){}))),t.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||_scriptDir,wasmMemory:j,wasmModule:k})},yc:function(){var t=S("ort-wasm-threaded.worker.js");ht.Yb.push(new Worker(t))},Cc:function(){return 0==ht.Yb.length&&(ht.yc(),ht.Fc(ht.Yb[0])),ht.Yb.pop()}};function dt(t){for(;0>2>>>0];t=a()[t+48>>2>>>0],Te(e,e-t),Me(e)};var mt=[];function gt(t){var e=mt[t];return e||(t>=mt.length&&(mt.length=t+1),mt[t]=e=$.get(t)),e}u.invokeEntryPoint=function(t,e){t=gt(t)(e),Q()?ht.nc(t):Ae(t)};var vt,wt,_t=[],Ot=0,At=0;function St(t){this.Zb=t,this.Sb=t-24,this.xc=function(t){i()[this.Sb+4>>2>>>0]=t},this.bc=function(){return i()[this.Sb+4>>2>>>0]},this.wc=function(t){i()[this.Sb+8>>2>>>0]=t},this.Dc=function(){return i()[this.Sb+8>>2>>>0]},this.rc=function(){a()[this.Sb>>2>>>0]=0},this.hc=function(t){t=t?1:0,e()[this.Sb+12>>0>>>0]=t},this.uc=function(){return 0!=e()[this.Sb+12>>0>>>0]},this.ic=function(t){t=t?1:0,e()[this.Sb+13>>0>>>0]=t},this.kc=function(){return 0!=e()[this.Sb+13>>0>>>0]},this.fc=function(t,e){this.cc(0),this.xc(t),this.wc(e),this.rc(),this.hc(!1),this.ic(!1)},this.sc=function(){Atomics.add(a(),this.Sb>>2,1)},this.Hc=function(){return 1===Atomics.sub(a(),this.Sb>>2,1)},this.cc=function(t){i()[this.Sb+16>>2>>>0]=t},this.tc=function(){return i()[this.Sb+16>>2>>>0]},this.vc=function(){if(Re(this.bc()))return i()[this.Zb>>2>>>0];var t=this.tc();return 0!==t?t:this.Zb}}function Tt(t){return ye(new St(t).Sb)}function Et(t,e,n,r){return O?$t(3,1,t,e,n,r):Mt(t,e,n,r)}function Mt(t,e,n,r){if("undefined"==typeof SharedArrayBuffer)return x("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var a=[];return O&&0===a.length?Et(t,e,n,r):(t={Ic:n,Ub:t,zc:r,Nc:a},O?(t.Oc="spawnThread",postMessage(t,a),0):lt(t))}function Ct(t,e,n){return O?$t(4,1,t,e,n):0}function xt(t,e){if(O)return $t(5,1,t,e)}function Rt(t,e){if(O)return $t(6,1,t,e)}function jt(t,e,n){if(O)return $t(7,1,t,e,n)}function kt(t,e,n){return O?$t(8,1,t,e,n):0}function Dt(t,e){if(O)return $t(9,1,t,e)}function Pt(t,e,n){if(O)return $t(10,1,t,e,n)}function Ut(t,e,n,r){if(O)return $t(11,1,t,e,n,r)}function Ft(t,e,n,r){if(O)return $t(12,1,t,e,n,r)}function It(t,e,n,r){if(O)return $t(13,1,t,e,n,r)}function Wt(t){if(O)return $t(14,1,t)}function Ht(t,e){if(O)return $t(15,1,t,e)}function Lt(t,e,n){if(O)return $t(16,1,t,e,n)}function zt(t){Atomics.store(a(),t>>2,1),he()&&_e(t),Atomics.compareExchange(a(),t>>2,1,0)}function Yt(t){return i()[t>>>2]+4294967296*a()[t+4>>>2]}function Bt(t,e,n,r,a,i){return O?$t(17,1,t,e,n,r,a,i):-52}function Gt(t,e,n,r,a,i){if(O)return $t(18,1,t,e,n,r,a,i)}function Nt(t){var n=G(t)+1,r=de(n);return r&&B(t,e(),r,n),r}function Vt(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}if(O)return $t(19,1,t,e,n);var o=(new Date).getFullYear(),u=new Date(o,0,1),c=new Date(o,6,1);o=u.getTimezoneOffset();var s=c.getTimezoneOffset(),l=Math.max(o,s);a()[t>>2>>>0]=60*l,a()[e>>2>>>0]=Number(o!=s),t=r(u),e=r(c),t=Nt(t),e=Nt(e),s>2>>>0]=t,i()[n+4>>2>>>0]=e):(i()[n>>2>>>0]=e,i()[n+4>>2>>>0]=t)}function $t(t,e){var n=arguments.length-2,r=arguments;return yt((()=>{for(var a=Ce(8*n),i=a>>3,u=0;u>>0]=c}return we(t,n,a,e)}))}u.executeNotifiedProxyingQueue=zt,wt=_?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:O?()=>performance.now()-u.__performance_now_clock_drift:()=>performance.now();var qt,Xt=[],Jt={};function Zt(){if(!qt){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:m||"./this.program"};for(t in Jt)void 0===Jt[t]?delete e[t]:e[t]=Jt[t];var n=[];for(t in e)n.push(t+"="+e[t]);qt=n}return qt}function Qt(t,n){if(O)return $t(20,1,t,n);var r=0;return Zt().forEach((function(a,o){var u=n+r;for(o=i()[t+4*o>>2>>>0]=u,u=0;u>0>>>0]=a.charCodeAt(u);e()[o>>0>>>0]=0,r+=a.length+1})),0}function Kt(t,e){if(O)return $t(21,1,t,e);var n=Zt();i()[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),i()[e>>2>>>0]=r,0}function te(t){return O?$t(22,1,t):52}function ee(t,e,n,r){return O?$t(23,1,t,e,n,r):52}function ne(t,e,n,r,a){return O?$t(24,1,t,e,n,r,a):70}var re=[null,[],[]];function ae(t,e){var n=re[t];0===e||10===e?((1===t?C:x)(z(n,0)),n.length=0):n.push(e)}function ie(t,e,n,a){if(O)return $t(25,1,t,e,n,a);for(var o=0,u=0;u>2>>>0],s=i()[e+4>>2>>>0];e+=8;for(var l=0;l>>0]);o+=s}return i()[a>>2>>>0]=o,0}var oe=0;function ue(t){return 0==t%4&&(0!=t%100||0==t%400)}var ce=[31,29,31,30,31,30,31,31,30,31,30,31],se=[31,28,31,30,31,30,31,31,30,31,30,31];function le(t,n,r,i){function o(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=s(new Date(t.getFullYear(),0,4)),n=s(n),0>=c(e,t)?0>=c(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var f=a()[i+40>>2>>>0];for(var p in i={Lc:a()[i>>2>>>0],Kc:a()[i+4>>2>>>0],dc:a()[i+8>>2>>>0],jc:a()[i+12>>2>>>0],ec:a()[i+16>>2>>>0],Xb:a()[i+20>>2>>>0],Tb:a()[i+24>>2>>>0],Wb:a()[i+28>>2>>>0],Rc:a()[i+32>>2>>>0],Jc:a()[i+36>>2>>>0],Mc:f?Y(f):""},r=Y(r),f={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})r=r.replace(new RegExp(p,"g"),f[p]);var h="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),d="January February March April May June July August September October November December".split(" ");for(p in f={"%a":function(t){return h[t.Tb].substring(0,3)},"%A":function(t){return h[t.Tb]},"%b":function(t){return d[t.ec].substring(0,3)},"%B":function(t){return d[t.ec]},"%C":function(t){return u((t.Xb+1900)/100|0,2)},"%d":function(t){return u(t.jc,2)},"%e":function(t){return o(t.jc,2," ")},"%g":function(t){return l(t).toString().substring(2)},"%G":function(t){return l(t)},"%H":function(t){return u(t.dc,2)},"%I":function(t){return 0==(t=t.dc)?t=12:12t.dc?"AM":"PM"},"%S":function(t){return u(t.Lc,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Tb||7},"%U":function(t){return u(Math.floor((t.Wb+7-t.Tb)/7),2)},"%V":function(t){var e=Math.floor((t.Wb+7-(t.Tb+6)%7)/7);if(2>=(t.Tb+371-t.Wb-2)%7&&e++,e)53==e&&(4==(n=(t.Tb+371-t.Wb)%7)||3==n&&ue(t.Xb)||(e=1));else{e=52;var n=(t.Tb+7-t.Wb-1)%7;(4==n||5==n&&ue(t.Xb%400-1))&&e++}return u(e,2)},"%w":function(t){return t.Tb},"%W":function(t){return u(Math.floor((t.Wb+7-(t.Tb+6)%7)/7),2)},"%y":function(t){return(t.Xb+1900).toString().substring(2)},"%Y":function(t){return t.Xb+1900},"%z":function(t){var e=0<=(t=t.Jc);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.Mc},"%%":function(){return"%"}},r=r.replace(/%%/g,"\\0\\0"),f)r.includes(p)&&(r=r.replace(new RegExp(p,"g"),f[p](i)));return p=function(t){var e=Array(G(t)+1);return B(t,e,0,e.length),e}(r=r.replace(/\\0\\0/g,"%")),p.length>n?0:(function(t,n){e().set(t,n>>>0)}(p,t),p.length-1)}ht.fc();var fe=[null,ft,bt,Et,Ct,xt,Rt,jt,kt,Dt,Pt,Ut,Ft,It,Wt,Ht,Lt,Bt,Gt,Vt,Qt,Kt,te,ee,ne,ie],pe={b:function(t){return de(t+24)+24},n:function(t){return(t=new St(t)).uc()||(t.hc(!0),Ot--),t.ic(!1),_t.push(t),t.sc(),t.vc()},ma:function(t){throw x("Unexpected exception thrown, this is not properly supported - aborting"),H=!0,t},x:function(){Se(0);var t=_t.pop();if(t.Hc()&&!t.kc()){var e=t.Dc();e&>(e)(t.Zb),Tt(t.Zb)}At=0},e:function(){var t=At;if(!t)return oe=0;var e=new St(t);e.cc(t);var n=e.bc();if(!n)return oe=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;azt(r)));else if(O)postMessage({targetThread:t,cmd:"processProxyingQueue",queue:r});else{if(!(t=ht.Vb[t]))return;t.postMessage({cmd:"processProxyingQueue",queue:r})}return 1},Ea:function(){return-1},Pa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getUTCSeconds(),a()[e+4>>2>>>0]=t.getUTCMinutes(),a()[e+8>>2>>>0]=t.getUTCHours(),a()[e+12>>2>>>0]=t.getUTCDate(),a()[e+16>>2>>>0]=t.getUTCMonth(),a()[e+20>>2>>>0]=t.getUTCFullYear()-1900,a()[e+24>>2>>>0]=t.getUTCDay(),t=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,a()[e+28>>2>>>0]=t},Qa:function(t,e){t=new Date(1e3*Yt(t)),a()[e>>2>>>0]=t.getSeconds(),a()[e+4>>2>>>0]=t.getMinutes(),a()[e+8>>2>>>0]=t.getHours(),a()[e+12>>2>>>0]=t.getDate(),a()[e+16>>2>>>0]=t.getMonth(),a()[e+20>>2>>>0]=t.getFullYear()-1900,a()[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1),r=(t.getTime()-n.getTime())/864e5|0;a()[e+28>>2>>>0]=r,a()[e+36>>2>>>0]=-60*t.getTimezoneOffset(),r=new Date(t.getFullYear(),6,1).getTimezoneOffset(),t=0|(r!=(n=n.getTimezoneOffset())&&t.getTimezoneOffset()==Math.min(n,r)),a()[e+32>>2>>>0]=t},Ra:function(t){var e=new Date(a()[t+20>>2>>>0]+1900,a()[t+16>>2>>>0],a()[t+12>>2>>>0],a()[t+8>>2>>>0],a()[t+4>>2>>>0],a()[t>>2>>>0],0),n=a()[t+32>>2>>>0],r=e.getTimezoneOffset(),i=new Date(e.getFullYear(),0,1),o=new Date(e.getFullYear(),6,1).getTimezoneOffset(),u=i.getTimezoneOffset(),c=Math.min(u,o);return 0>n?a()[t+32>>2>>>0]=Number(o!=u&&c==r):0>2>>>0]=e.getDay(),n=(e.getTime()-i.getTime())/864e5|0,a()[t+28>>2>>>0]=n,a()[t>>2>>>0]=e.getSeconds(),a()[t+4>>2>>>0]=e.getMinutes(),a()[t+8>>2>>>0]=e.getHours(),a()[t+12>>2>>>0]=e.getDate(),a()[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},Aa:Bt,Ba:Gt,Sa:function t(e,n,r){t.Ac||(t.Ac=!0,Vt(e,n,r))},y:function(){at("")},U:function(){if(!_&&!w){var t="Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread";vt||(vt={}),vt[t]||(vt[t]=1,_&&(t="warning: "+t),x(t))}},ra:function(){return 4294901760},B:wt,Ia:function(t,e,n){r().copyWithin(t>>>0,e>>>0,e+n>>>0)},F:function(){return _?n(993).cpus().length:navigator.hardwareConcurrency},Da:function(t,e,n){Xt.length=e,n>>=3;for(var r=0;r>>0];return(0>t?ut[-t-1]:fe[t]).apply(null,Xt)},qa:function(t){var e=r().length;if((t>>>=0)<=e||4294901760=n;n*=2){var a=e*(1+.2/n);a=Math.min(a,t+100663296);var i=Math;a=Math.max(t,a),i=i.min.call(i,4294901760,a+(65536-a%65536)%65536);t:{try{j.grow(i-D.byteLength+65535>>>16),N(j.buffer);var o=1;break t}catch(t){}o=void 0}if(o)return!0}return!1},Na:function(){throw"unwind"},Ga:Qt,Ha:Kt,J:pt,I:te,S:ee,ga:ne,R:ie,d:function(){return oe},na:function t(r,a){t.lc||(t.lc=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(_)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>at("randomDevice")}());for(var i=0;i>0>>>0]=t.lc();return 0},ia:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ja:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},K:function(t){var e=Ee();try{return gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},f:function(t,e){var n=Ee();try{return gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},P:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},Q:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},k:function(t,e,n){var r=Ee();try{return gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},p:function(t,e,n,r){var a=Ee();try{return gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},q:function(t,e,n,r,a){var i=Ee();try{return gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},N:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},s:function(t,e,n,r,a,i){var o=Ee();try{return gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},w:function(t,e,n,r,a,i,o){var u=Ee();try{return gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},L:function(t,e,n,r,a,i,o,u){var c=Ee();try{return gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},E:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{return gt(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=Ee();try{return He(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},_:function(t,e,n,r,a,i,o){var u=Ee();try{return ke(t,e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},Z:function(t,e,n,r,a){var i=Ee();try{return Le(t,e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},ca:function(t,e,n,r){var a=Ee();try{return Ie(t,e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},$:function(t){var e=Ee();try{return je(t)}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},ba:function(t,e){var n=Ee();try{return We(t,e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},Y:function(t,e,n){var r=Ee();try{return De(t,e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},g:function(t){var e=Ee();try{gt(t)()}catch(t){if(Me(e),t!==t+0)throw t;Se(1,0)}},r:function(t,e){var n=Ee();try{gt(t)(e)}catch(t){if(Me(n),t!==t+0)throw t;Se(1,0)}},i:function(t,e,n){var r=Ee();try{gt(t)(e,n)}catch(t){if(Me(r),t!==t+0)throw t;Se(1,0)}},ha:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},m:function(t,e,n,r){var a=Ee();try{gt(t)(e,n,r)}catch(t){if(Me(a),t!==t+0)throw t;Se(1,0)}},v:function(t,e,n,r,a){var i=Ee();try{gt(t)(e,n,r,a)}catch(t){if(Me(i),t!==t+0)throw t;Se(1,0)}},u:function(t,e,n,r,a,i){var o=Ee();try{gt(t)(e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},O:function(t,e,n,r,a,i,o){var u=Ee();try{gt(t)(e,n,r,a,i,o)}catch(t){if(Me(u),t!==t+0)throw t;Se(1,0)}},A:function(t,e,n,r,a,i,o,u){var c=Ee();try{gt(t)(e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},ka:function(t,e,n,r,a,i,o,u,c){var s=Ee();try{gt(t)(e,n,r,a,i,o,u,c)}catch(t){if(Me(s),t!==t+0)throw t;Se(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l){var f=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(Me(f),t!==t+0)throw t;Se(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=Ee();try{gt(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(Me(b),t!==t+0)throw t;Se(1,0)}},fa:function(t,e,n,r,a,i,o,u){var c=Ee();try{Pe(t,e,n,r,a,i,o,u)}catch(t){if(Me(c),t!==t+0)throw t;Se(1,0)}},da:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=Ee();try{Fe(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(Me(p),t!==t+0)throw t;Se(1,0)}},ea:function(t,e,n,r,a,i){var o=Ee();try{Ue(t,e,n,r,a,i)}catch(t){if(Me(o),t!==t+0)throw t;Se(1,0)}},o:function(t){return t},a:j||u.wasmMemory,G:function(t){oe=t},la:le,z:function(t,e,n,r){return le(t,e,n,r)}};!function(){function t(t,e){u.asm=t.exports,ht.qc.push(u.asm.sb),$=u.asm.ub,X.unshift(u.asm.Va),k=e,O||(et--,u.monitorRunDependencies&&u.monitorRunDependencies(et),0==et&&(null!==nt&&(clearInterval(nt),nt=null),rt&&(t=rt,rt=null,t())))}function e(e){t(e.instance,e.module)}function n(t){return function(){if(!M&&(v||w)){if("function"==typeof fetch&&!tt.startsWith("file://"))return fetch(tt,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+tt+"\'";return t.arrayBuffer()})).catch((function(){return ot()}));if(f)return new Promise((function(t,e){f(tt,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return ot()}))}().then((function(t){return WebAssembly.instantiate(t,r)})).then((function(t){return t})).then(t,(function(t){x("failed to asynchronously prepare wasm: "+t),at(t)}))}var r={a:pe};if(O||(et++,u.monitorRunDependencies&&u.monitorRunDependencies(et)),u.instantiateWasm)try{return u.instantiateWasm(r,t)}catch(t){return x("Module.instantiateWasm callback failed with error: "+t),!1}(M||"function"!=typeof WebAssembly.instantiateStreaming||it()||tt.startsWith("file://")||_||"function"!=typeof fetch?n(e):fetch(tt,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,r).then(e,(function(t){return x("wasm streaming compile failed: "+t),x("falling back to ArrayBuffer instantiation"),n(e)}))}))).catch(s)}(),u.___wasm_call_ctors=function(){return(u.___wasm_call_ctors=u.asm.Va).apply(null,arguments)},u._OrtInit=function(){return(u._OrtInit=u.asm.Wa).apply(null,arguments)},u._OrtCreateSessionOptions=function(){return(u._OrtCreateSessionOptions=u.asm.Xa).apply(null,arguments)},u._OrtAppendExecutionProvider=function(){return(u._OrtAppendExecutionProvider=u.asm.Ya).apply(null,arguments)},u._OrtAddSessionConfigEntry=function(){return(u._OrtAddSessionConfigEntry=u.asm.Za).apply(null,arguments)},u._OrtReleaseSessionOptions=function(){return(u._OrtReleaseSessionOptions=u.asm._a).apply(null,arguments)},u._OrtCreateSession=function(){return(u._OrtCreateSession=u.asm.$a).apply(null,arguments)},u._OrtReleaseSession=function(){return(u._OrtReleaseSession=u.asm.ab).apply(null,arguments)},u._OrtGetInputCount=function(){return(u._OrtGetInputCount=u.asm.bb).apply(null,arguments)},u._OrtGetOutputCount=function(){return(u._OrtGetOutputCount=u.asm.cb).apply(null,arguments)},u._OrtGetInputName=function(){return(u._OrtGetInputName=u.asm.db).apply(null,arguments)},u._OrtGetOutputName=function(){return(u._OrtGetOutputName=u.asm.eb).apply(null,arguments)},u._OrtFree=function(){return(u._OrtFree=u.asm.fb).apply(null,arguments)},u._OrtCreateTensor=function(){return(u._OrtCreateTensor=u.asm.gb).apply(null,arguments)},u._OrtGetTensorData=function(){return(u._OrtGetTensorData=u.asm.hb).apply(null,arguments)},u._OrtReleaseTensor=function(){return(u._OrtReleaseTensor=u.asm.ib).apply(null,arguments)},u._OrtCreateRunOptions=function(){return(u._OrtCreateRunOptions=u.asm.jb).apply(null,arguments)},u._OrtAddRunConfigEntry=function(){return(u._OrtAddRunConfigEntry=u.asm.kb).apply(null,arguments)},u._OrtReleaseRunOptions=function(){return(u._OrtReleaseRunOptions=u.asm.lb).apply(null,arguments)},u._OrtRun=function(){return(u._OrtRun=u.asm.mb).apply(null,arguments)},u._OrtEndProfiling=function(){return(u._OrtEndProfiling=u.asm.nb).apply(null,arguments)};var he=u._pthread_self=function(){return(he=u._pthread_self=u.asm.ob).apply(null,arguments)},de=u._malloc=function(){return(de=u._malloc=u.asm.pb).apply(null,arguments)},ye=u._free=function(){return(ye=u._free=u.asm.qb).apply(null,arguments)},be=u._fflush=function(){return(be=u._fflush=u.asm.rb).apply(null,arguments)};u.__emscripten_tls_init=function(){return(u.__emscripten_tls_init=u.asm.sb).apply(null,arguments)};var me=u.___funcs_on_exit=function(){return(me=u.___funcs_on_exit=u.asm.tb).apply(null,arguments)},ge=u.__emscripten_thread_init=function(){return(ge=u.__emscripten_thread_init=u.asm.vb).apply(null,arguments)};u.__emscripten_thread_crashed=function(){return(u.__emscripten_thread_crashed=u.asm.wb).apply(null,arguments)};var ve,we=u._emscripten_run_in_main_runtime_thread_js=function(){return(we=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},_e=u.__emscripten_proxy_execute_task_queue=function(){return(_e=u.__emscripten_proxy_execute_task_queue=u.asm.yb).apply(null,arguments)},Oe=u.__emscripten_thread_free_data=function(){return(Oe=u.__emscripten_thread_free_data=u.asm.zb).apply(null,arguments)},Ae=u.__emscripten_thread_exit=function(){return(Ae=u.__emscripten_thread_exit=u.asm.Ab).apply(null,arguments)},Se=u._setThrew=function(){return(Se=u._setThrew=u.asm.Bb).apply(null,arguments)},Te=u._emscripten_stack_set_limits=function(){return(Te=u._emscripten_stack_set_limits=u.asm.Cb).apply(null,arguments)},Ee=u.stackSave=function(){return(Ee=u.stackSave=u.asm.Db).apply(null,arguments)},Me=u.stackRestore=function(){return(Me=u.stackRestore=u.asm.Eb).apply(null,arguments)},Ce=u.stackAlloc=function(){return(Ce=u.stackAlloc=u.asm.Fb).apply(null,arguments)},xe=u.___cxa_can_catch=function(){return(xe=u.___cxa_can_catch=u.asm.Gb).apply(null,arguments)},Re=u.___cxa_is_pointer_type=function(){return(Re=u.___cxa_is_pointer_type=u.asm.Hb).apply(null,arguments)},je=u.dynCall_j=function(){return(je=u.dynCall_j=u.asm.Ib).apply(null,arguments)},ke=u.dynCall_iiiiij=function(){return(ke=u.dynCall_iiiiij=u.asm.Jb).apply(null,arguments)},De=u.dynCall_jii=function(){return(De=u.dynCall_jii=u.asm.Kb).apply(null,arguments)},Pe=u.dynCall_viiiiij=function(){return(Pe=u.dynCall_viiiiij=u.asm.Lb).apply(null,arguments)},Ue=u.dynCall_vjji=function(){return(Ue=u.dynCall_vjji=u.asm.Mb).apply(null,arguments)},Fe=u.dynCall_viiijjjii=function(){return(Fe=u.dynCall_viiijjjii=u.asm.Nb).apply(null,arguments)},Ie=u.dynCall_iij=function(){return(Ie=u.dynCall_iij=u.asm.Ob).apply(null,arguments)},We=u.dynCall_ji=function(){return(We=u.dynCall_ji=u.asm.Pb).apply(null,arguments)},He=u.dynCall_iiiiiij=function(){return(He=u.dynCall_iiiiiij=u.asm.Qb).apply(null,arguments)},Le=u.dynCall_iiij=function(){return(Le=u.dynCall_iiij=u.asm.Rb).apply(null,arguments)};function ze(){function t(){if(!ve&&(ve=!0,u.calledRun=!0,!H)&&(O||dt(X),c(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),!O)){if(u.postRun)for("function"==typeof u.postRun&&(u.postRun=[u.postRun]);u.postRun.length;){var t=u.postRun.shift();Z.unshift(t)}dt(Z)}}if(!(0{var _scriptDir,r=(_scriptDir=(_scriptDir="undefined"!=typeof document&&document.currentScript?document.currentScript.src:void 0)||"/index.js",function(t){var e,r,a;t=t||{},e||(e=void 0!==t?t:{}),e.ready=new Promise((function(t,e){r=t,a=e}));var i,o,u,c,s,l,f=Object.assign({},e),p="./this.program",h=(t,e)=>{throw e},d="object"==typeof window,y="function"==typeof importScripts,b="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,m="";b?(m=y?n(908).dirname(m)+"/":"//",l=()=>{s||(c=n(384),s=n(908))},i=function(t,e){return l(),t=s.normalize(t),c.readFileSync(t,e?void 0:"utf8")},u=t=>((t=i(t,!0)).buffer||(t=new Uint8Array(t)),t),o=(t,e,n)=>{l(),t=s.normalize(t),c.readFile(t,(function(t,r){t?n(t):e(r.buffer)}))},1{if(_||0{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.send(null),e.responseText},y&&(u=t=>{var e=new XMLHttpRequest;return e.open("GET",t,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),o=(t,e,n)=>{var r=new XMLHttpRequest;r.open("GET",t,!0),r.responseType="arraybuffer",r.onload=()=>{200==r.status||0==r.status&&r.response?e(r.response):n()},r.onerror=n,r.send(null)});var g,v=e.print||console.log.bind(console),w=e.printErr||console.warn.bind(console);Object.assign(e,f),f=null,e.thisProgram&&(p=e.thisProgram),e.quit&&(h=e.quit),e.wasmBinary&&(g=e.wasmBinary);var _=e.noExitRuntime||!1;"object"!=typeof WebAssembly&&V("no native wasm support detected");var O,A,S,T,E,M,C=!1,x="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function R(t,e,n){var r=(e>>>=0)+n;for(n=e;t[n]&&!(n>=r);)++n;if(16(a=224==(240&a)?(15&a)<<12|i<<6|o:(7&a)<<18|i<<12|o<<6|63&t[e++])?r+=String.fromCharCode(a):(a-=65536,r+=String.fromCharCode(55296|a>>10,56320|1023&a))}}else r+=String.fromCharCode(a)}return r}function j(t,e){return(t>>>=0)?R(T,t,e):""}function k(t,e,n,r){if(!(0>>=0;r=n+r-1;for(var i=0;i=o&&(o=65536+((1023&o)<<10)|1023&t.charCodeAt(++i)),127>=o){if(n>=r)break;e[n++>>>0]=o}else{if(2047>=o){if(n+1>=r)break;e[n++>>>0]=192|o>>6}else{if(65535>=o){if(n+2>=r)break;e[n++>>>0]=224|o>>12}else{if(n+3>=r)break;e[n++>>>0]=240|o>>18,e[n++>>>0]=128|o>>12&63}e[n++>>>0]=128|o>>6&63}e[n++>>>0]=128|63&o}}return e[n>>>0]=0,n-a}function D(t){for(var e=0,n=0;n=r?e++:2047>=r?e+=2:55296<=r&&57343>=r?(e+=4,++n):e+=3}return e}function P(){var t=O.buffer;A=t,e.HEAP8=S=new Int8Array(t),e.HEAP16=new Int16Array(t),e.HEAP32=E=new Int32Array(t),e.HEAPU8=T=new Uint8Array(t),e.HEAPU16=new Uint16Array(t),e.HEAPU32=M=new Uint32Array(t),e.HEAPF32=new Float32Array(t),e.HEAPF64=new Float64Array(t)}var U,F=[],I=[],W=[],H=[],L=0;function z(){var t=e.preRun.shift();F.unshift(t)}var Y,B=0,G=null,N=null;function V(t){throw e.onAbort&&e.onAbort(t),w(t="Aborted("+t+")"),C=!0,t=new WebAssembly.RuntimeError(t+". Build with -sASSERTIONS for more info."),a(t),t}function $(){return Y.startsWith("data:application/octet-stream;base64,")}if(Y="ort-wasm.wasm",!$()){var q=Y;Y=e.locateFile?e.locateFile(q,m):m+q}function X(){var t=Y;try{if(t==Y&&g)return new Uint8Array(g);if(u)return u(t);throw"both async and sync fetching of the wasm failed"}catch(t){V(t)}}function J(t){this.name="ExitStatus",this.message="Program terminated with exit("+t+")",this.status=t}function Z(t){for(;0>2>>>0]=t},this.Eb=function(){return M[this.zb+4>>2>>>0]},this.Sb=function(t){M[this.zb+8>>2>>>0]=t},this.Wb=function(){return M[this.zb+8>>2>>>0]},this.Tb=function(){E[this.zb>>2>>>0]=0},this.Ib=function(t){S[this.zb+12>>0>>>0]=t?1:0},this.Pb=function(){return 0!=S[this.zb+12>>0>>>0]},this.Jb=function(t){S[this.zb+13>>0>>>0]=t?1:0},this.Lb=function(){return 0!=S[this.zb+13>>0>>>0]},this.Rb=function(t,e){this.Fb(0),this.Ub(t),this.Sb(e),this.Tb(),this.Ib(!1),this.Jb(!1)},this.Nb=function(){E[this.zb>>2>>>0]+=1},this.Xb=function(){var t=E[this.zb>>2>>>0];return E[this.zb>>2>>>0]=t-1,1===t},this.Fb=function(t){M[this.zb+16>>2>>>0]=t},this.Ob=function(){return M[this.zb+16>>2>>>0]},this.Qb=function(){if(Mt(this.Eb()))return M[this.Db>>2>>>0];var t=this.Ob();return 0!==t?t:this.Db}}function nt(t){return vt(new et(t).zb)}var rt=[];function at(t){var e=rt[t];return e||(t>=rt.length&&(rt.length=t+1),rt[t]=e=U.get(t)),e}function it(t){var e=D(t)+1,n=gt(e);return n&&k(t,S,n,e),n}var ot={};function ut(){if(!ct){var t,e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:p||"./this.program"};for(t in ot)void 0===ot[t]?delete e[t]:e[t]=ot[t];var n=[];for(t in e)n.push(t+"="+e[t]);ct=n}return ct}var ct,st=[null,[],[]];function lt(t,e){var n=st[t];0===e||10===e?((1===t?v:w)(R(n,0)),n.length=0):n.push(e)}var ft=0;function pt(t){return 0==t%4&&(0!=t%100||0==t%400)}var ht=[31,29,31,30,31,30,31,31,30,31,30,31],dt=[31,28,31,30,31,30,31,31,30,31,30,31];function yt(t,e,n,r){function a(t,e,n){for(t="number"==typeof t?t.toString():t||"";t.lengtht?-1:0r-t.getDate())){t.setDate(t.getDate()+e);break}e-=r-t.getDate()+1,t.setDate(1),11>n?t.setMonth(n+1):(t.setMonth(0),t.setFullYear(t.getFullYear()+1))}return n=new Date(t.getFullYear()+1,0,4),e=u(new Date(t.getFullYear(),0,4)),n=u(n),0>=o(e,t)?0>=o(n,t)?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var s=E[r+40>>2>>>0];for(var l in r={$b:E[r>>2>>>0],Zb:E[r+4>>2>>>0],Gb:E[r+8>>2>>>0],Kb:E[r+12>>2>>>0],Hb:E[r+16>>2>>>0],Cb:E[r+20>>2>>>0],Ab:E[r+24>>2>>>0],Bb:E[r+28>>2>>>0],bc:E[r+32>>2>>>0],Yb:E[r+36>>2>>>0],ac:s?j(s):""},n=j(n),s={"%c":"%a %b %d %H:%M:%S %Y","%D":"%m/%d/%y","%F":"%Y-%m-%d","%h":"%b","%r":"%I:%M:%S %p","%R":"%H:%M","%T":"%H:%M:%S","%x":"%m/%d/%y","%X":"%H:%M:%S","%Ec":"%c","%EC":"%C","%Ex":"%m/%d/%y","%EX":"%H:%M:%S","%Ey":"%y","%EY":"%Y","%Od":"%d","%Oe":"%e","%OH":"%H","%OI":"%I","%Om":"%m","%OM":"%M","%OS":"%S","%Ou":"%u","%OU":"%U","%OV":"%V","%Ow":"%w","%OW":"%W","%Oy":"%y"})n=n.replace(new RegExp(l,"g"),s[l]);var f="Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),p="January February March April May June July August September October November December".split(" ");for(l in s={"%a":function(t){return f[t.Ab].substring(0,3)},"%A":function(t){return f[t.Ab]},"%b":function(t){return p[t.Hb].substring(0,3)},"%B":function(t){return p[t.Hb]},"%C":function(t){return i((t.Cb+1900)/100|0,2)},"%d":function(t){return i(t.Kb,2)},"%e":function(t){return a(t.Kb,2," ")},"%g":function(t){return c(t).toString().substring(2)},"%G":function(t){return c(t)},"%H":function(t){return i(t.Gb,2)},"%I":function(t){return 0==(t=t.Gb)?t=12:12t.Gb?"AM":"PM"},"%S":function(t){return i(t.$b,2)},"%t":function(){return"\\t"},"%u":function(t){return t.Ab||7},"%U":function(t){return i(Math.floor((t.Bb+7-t.Ab)/7),2)},"%V":function(t){var e=Math.floor((t.Bb+7-(t.Ab+6)%7)/7);if(2>=(t.Ab+371-t.Bb-2)%7&&e++,e)53==e&&(4==(n=(t.Ab+371-t.Bb)%7)||3==n&&pt(t.Cb)||(e=1));else{e=52;var n=(t.Ab+7-t.Bb-1)%7;(4==n||5==n&&pt(t.Cb%400-1))&&e++}return i(e,2)},"%w":function(t){return t.Ab},"%W":function(t){return i(Math.floor((t.Bb+7-(t.Ab+6)%7)/7),2)},"%y":function(t){return(t.Cb+1900).toString().substring(2)},"%Y":function(t){return t.Cb+1900},"%z":function(t){var e=0<=(t=t.Yb);return t=Math.abs(t)/60,(e?"+":"-")+String("0000"+(t/60*100+t%60)).slice(-4)},"%Z":function(t){return t.ac},"%%":function(){return"%"}},n=n.replace(/%%/g,"\\0\\0"),s)n.includes(l)&&(n=n.replace(new RegExp(l,"g"),s[l](r)));return l=function(t){var e=Array(D(t)+1);return k(t,e,0,e.length),e}(n=n.replace(/\\0\\0/g,"%")),l.length>e?0:(S.set(l,t>>>0),l.length-1)}var bt={a:function(t){return gt(t+24)+24},m:function(t){return(t=new et(t)).Pb()||(t.Ib(!0),K--),t.Jb(!1),Q.push(t),t.Nb(),t.Qb()},ia:function(t){throw w("Unexpected exception thrown, this is not properly supported - aborting"),C=!0,t},w:function(){Ot(0);var t=Q.pop();if(t.Xb()&&!t.Lb()){var e=t.Wb();e&&at(e)(t.Db),nt(t.Db)}tt=0},d:function(){var t=tt;if(!t)return ft=0;var e=new et(t);e.Fb(t);var n=e.Eb();if(!n)return ft=0,t;for(var r=Array.prototype.slice.call(arguments),a=0;a>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getUTCSeconds(),E[e+4>>2>>>0]=t.getUTCMinutes(),E[e+8>>2>>>0]=t.getUTCHours(),E[e+12>>2>>>0]=t.getUTCDate(),E[e+16>>2>>>0]=t.getUTCMonth(),E[e+20>>2>>>0]=t.getUTCFullYear()-1900,E[e+24>>2>>>0]=t.getUTCDay(),E[e+28>>2>>>0]=(t.getTime()-Date.UTC(t.getUTCFullYear(),0,1,0,0,0,0))/864e5|0},Ea:function(t,e){t=new Date(1e3*(M[t>>>2]+4294967296*E[t+4>>>2])),E[e>>2>>>0]=t.getSeconds(),E[e+4>>2>>>0]=t.getMinutes(),E[e+8>>2>>>0]=t.getHours(),E[e+12>>2>>>0]=t.getDate(),E[e+16>>2>>>0]=t.getMonth(),E[e+20>>2>>>0]=t.getFullYear()-1900,E[e+24>>2>>>0]=t.getDay();var n=new Date(t.getFullYear(),0,1);E[e+28>>2>>>0]=(t.getTime()-n.getTime())/864e5|0,E[e+36>>2>>>0]=-60*t.getTimezoneOffset();var r=new Date(t.getFullYear(),6,1).getTimezoneOffset();n=n.getTimezoneOffset(),E[e+32>>2>>>0]=0|(r!=n&&t.getTimezoneOffset()==Math.min(n,r))},Fa:function(t){var e=new Date(E[t+20>>2>>>0]+1900,E[t+16>>2>>>0],E[t+12>>2>>>0],E[t+8>>2>>>0],E[t+4>>2>>>0],E[t>>2>>>0],0),n=E[t+32>>2>>>0],r=e.getTimezoneOffset(),a=new Date(e.getFullYear(),0,1),i=new Date(e.getFullYear(),6,1).getTimezoneOffset(),o=a.getTimezoneOffset(),u=Math.min(o,i);return 0>n?E[t+32>>2>>>0]=Number(i!=o&&u==r):0>2>>>0]=e.getDay(),E[t+28>>2>>>0]=(e.getTime()-a.getTime())/864e5|0,E[t>>2>>>0]=e.getSeconds(),E[t+4>>2>>>0]=e.getMinutes(),E[t+8>>2>>>0]=e.getHours(),E[t+12>>2>>>0]=e.getDate(),E[t+16>>2>>>0]=e.getMonth(),e.getTime()/1e3|0},sa:function(){return-52},ta:function(){},Ga:function t(e,n,r){t.Vb||(t.Vb=!0,function(t,e,n){function r(t){return(t=t.toTimeString().match(/\\(([A-Za-z ]+)\\)$/))?t[1]:"GMT"}var a=(new Date).getFullYear(),i=new Date(a,0,1),o=new Date(a,6,1);a=i.getTimezoneOffset();var u=o.getTimezoneOffset();E[t>>2>>>0]=60*Math.max(a,u),E[e>>2>>>0]=Number(a!=u),t=r(i),e=r(o),t=it(t),e=it(e),u>2>>>0]=t,M[n+4>>2>>>0]=e):(M[n>>2>>>0]=e,M[n+4>>2>>>0]=t)}(e,n,r))},B:function(){V("")},ma:function(){return 4294901760},I:b?()=>{var t=process.hrtime();return 1e3*t[0]+t[1]/1e6}:()=>performance.now(),xa:function(t,e,n){T.copyWithin(t>>>0,e>>>0,e+n>>>0)},G:function(t){var e=T.length;if(4294901760<(t>>>=0))return!1;for(var n=1;4>=n;n*=2){var r=e*(1+.2/n);r=Math.min(r,t+100663296);var a=Math;r=Math.max(t,r),a=a.min.call(a,4294901760,r+(65536-r%65536)%65536);t:{try{O.grow(a-A.byteLength+65535>>>16),P();var i=1;break t}catch(t){}i=void 0}if(i)return!0}return!1},va:function(t,e){var n=0;return ut().forEach((function(r,a){var i=e+n;for(a=M[t+4*a>>2>>>0]=i,i=0;i>0>>>0]=r.charCodeAt(i);S[a>>0>>>0]=0,n+=r.length+1})),0},wa:function(t,e){var n=ut();M[t>>2>>>0]=n.length;var r=0;return n.forEach((function(t){r+=t.length+1})),M[e>>2>>>0]=r,0},ba:function(t){_||0>2>>>0],u=M[e+4>>2>>>0];e+=8;for(var c=0;c>>0]);a+=u}return M[r>>2>>>0]=a,0},c:function(){return ft},ja:function t(e,r){t.Mb||(t.Mb=function(){if("object"==typeof crypto&&"function"==typeof crypto.getRandomValues){var t=new Uint8Array(1);return()=>(crypto.getRandomValues(t),t[0])}if(b)try{var e=n(Object(function(){var t=new Error("Cannot find module \'crypto\'");throw t.code="MODULE_NOT_FOUND",t}()));return()=>e.randomBytes(1)[0]}catch(t){}return()=>V("randomDevice")}());for(var a=0;a>0>>>0]=t.Mb();return 0},ea:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},fa:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},J:function(t){var e=At();try{return at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},e:function(t,e){var n=At();try{return at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},N:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},O:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},j:function(t,e,n){var r=At();try{return at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},o:function(t,e,n,r){var a=At();try{return at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},p:function(t,e,n,r,a){var i=At();try{return at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},M:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},r:function(t,e,n,r,a,i){var o=At();try{return at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},v:function(t,e,n,r,a,i,o){var u=At();try{return at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},K:function(t,e,n,r,a,i,o,u){var c=At();try{return at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},D:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{return at(t)(e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},X:function(t,e,n,r,a,i,o,u){var c=At();try{return Ft(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},V:function(t,e,n,r,a,i,o){var u=At();try{return xt(t,e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},U:function(t,e,n,r,a){var i=At();try{return It(t,e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},Z:function(t,e,n,r){var a=At();try{return Pt(t,e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},W:function(t){var e=At();try{return Ct(t)}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},Y:function(t,e){var n=At();try{return Ut(t,e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},T:function(t,e,n){var r=At();try{return Rt(t,e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},f:function(t){var e=At();try{at(t)()}catch(t){if(St(e),t!==t+0)throw t;Ot(1,0)}},q:function(t,e){var n=At();try{at(t)(e)}catch(t){if(St(n),t!==t+0)throw t;Ot(1,0)}},h:function(t,e,n){var r=At();try{at(t)(e,n)}catch(t){if(St(r),t!==t+0)throw t;Ot(1,0)}},da:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},l:function(t,e,n,r){var a=At();try{at(t)(e,n,r)}catch(t){if(St(a),t!==t+0)throw t;Ot(1,0)}},t:function(t,e,n,r,a){var i=At();try{at(t)(e,n,r,a)}catch(t){if(St(i),t!==t+0)throw t;Ot(1,0)}},u:function(t,e,n,r,a,i){var o=At();try{at(t)(e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},x:function(t,e,n,r,a,i,o){var u=At();try{at(t)(e,n,r,a,i,o)}catch(t){if(St(u),t!==t+0)throw t;Ot(1,0)}},z:function(t,e,n,r,a,i,o,u){var c=At();try{at(t)(e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},ga:function(t,e,n,r,a,i,o,u,c){var s=At();try{at(t)(e,n,r,a,i,o,u,c)}catch(t){if(St(s),t!==t+0)throw t;Ot(1,0)}},A:function(t,e,n,r,a,i,o,u,c,s,l){var f=At();try{at(t)(e,n,r,a,i,o,u,c,s,l)}catch(t){if(St(f),t!==t+0)throw t;Ot(1,0)}},C:function(t,e,n,r,a,i,o,u,c,s,l,f,p,h,d,y){var b=At();try{at(t)(e,n,r,a,i,o,u,c,s,l,f,p,h,d,y)}catch(t){if(St(b),t!==t+0)throw t;Ot(1,0)}},aa:function(t,e,n,r,a,i,o,u){var c=At();try{jt(t,e,n,r,a,i,o,u)}catch(t){if(St(c),t!==t+0)throw t;Ot(1,0)}},_:function(t,e,n,r,a,i,o,u,c,s,l,f){var p=At();try{Dt(t,e,n,r,a,i,o,u,c,s,l,f)}catch(t){if(St(p),t!==t+0)throw t;Ot(1,0)}},$:function(t,e,n,r,a,i){var o=At();try{kt(t,e,n,r,a,i)}catch(t){if(St(o),t!==t+0)throw t;Ot(1,0)}},n:function(t){return t},F:function(t){ft=t},ha:yt,y:function(t,e,n,r){return yt(t,e,n,r)}};!function(){function t(t){e.asm=t.exports,O=e.asm.Ka,P(),U=e.asm.ib,I.unshift(e.asm.La),B--,e.monitorRunDependencies&&e.monitorRunDependencies(B),0==B&&(null!==G&&(clearInterval(G),G=null),N&&(t=N,N=null,t()))}function n(e){t(e.instance)}function r(t){return function(){if(!g&&(d||y)){if("function"==typeof fetch&&!Y.startsWith("file://"))return fetch(Y,{credentials:"same-origin"}).then((function(t){if(!t.ok)throw"failed to load wasm binary file at \'"+Y+"\'";return t.arrayBuffer()})).catch((function(){return X()}));if(o)return new Promise((function(t,e){o(Y,(function(e){t(new Uint8Array(e))}),e)}))}return Promise.resolve().then((function(){return X()}))}().then((function(t){return WebAssembly.instantiate(t,i)})).then((function(t){return t})).then(t,(function(t){w("failed to asynchronously prepare wasm: "+t),V(t)}))}var i={a:bt};if(B++,e.monitorRunDependencies&&e.monitorRunDependencies(B),e.instantiateWasm)try{return e.instantiateWasm(i,t)}catch(t){return w("Module.instantiateWasm callback failed with error: "+t),!1}(g||"function"!=typeof WebAssembly.instantiateStreaming||$()||Y.startsWith("file://")||b||"function"!=typeof fetch?r(n):fetch(Y,{credentials:"same-origin"}).then((function(t){return WebAssembly.instantiateStreaming(t,i).then(n,(function(t){return w("wasm streaming compile failed: "+t),w("falling back to ArrayBuffer instantiation"),r(n)}))}))).catch(a)}(),e.___wasm_call_ctors=function(){return(e.___wasm_call_ctors=e.asm.La).apply(null,arguments)},e._OrtInit=function(){return(e._OrtInit=e.asm.Ma).apply(null,arguments)},e._OrtCreateSessionOptions=function(){return(e._OrtCreateSessionOptions=e.asm.Na).apply(null,arguments)},e._OrtAppendExecutionProvider=function(){return(e._OrtAppendExecutionProvider=e.asm.Oa).apply(null,arguments)},e._OrtAddSessionConfigEntry=function(){return(e._OrtAddSessionConfigEntry=e.asm.Pa).apply(null,arguments)},e._OrtReleaseSessionOptions=function(){return(e._OrtReleaseSessionOptions=e.asm.Qa).apply(null,arguments)},e._OrtCreateSession=function(){return(e._OrtCreateSession=e.asm.Ra).apply(null,arguments)},e._OrtReleaseSession=function(){return(e._OrtReleaseSession=e.asm.Sa).apply(null,arguments)},e._OrtGetInputCount=function(){return(e._OrtGetInputCount=e.asm.Ta).apply(null,arguments)},e._OrtGetOutputCount=function(){return(e._OrtGetOutputCount=e.asm.Ua).apply(null,arguments)},e._OrtGetInputName=function(){return(e._OrtGetInputName=e.asm.Va).apply(null,arguments)},e._OrtGetOutputName=function(){return(e._OrtGetOutputName=e.asm.Wa).apply(null,arguments)},e._OrtFree=function(){return(e._OrtFree=e.asm.Xa).apply(null,arguments)},e._OrtCreateTensor=function(){return(e._OrtCreateTensor=e.asm.Ya).apply(null,arguments)},e._OrtGetTensorData=function(){return(e._OrtGetTensorData=e.asm.Za).apply(null,arguments)},e._OrtReleaseTensor=function(){return(e._OrtReleaseTensor=e.asm._a).apply(null,arguments)},e._OrtCreateRunOptions=function(){return(e._OrtCreateRunOptions=e.asm.$a).apply(null,arguments)},e._OrtAddRunConfigEntry=function(){return(e._OrtAddRunConfigEntry=e.asm.ab).apply(null,arguments)},e._OrtReleaseRunOptions=function(){return(e._OrtReleaseRunOptions=e.asm.bb).apply(null,arguments)},e._OrtRun=function(){return(e._OrtRun=e.asm.cb).apply(null,arguments)},e._OrtEndProfiling=function(){return(e._OrtEndProfiling=e.asm.db).apply(null,arguments)};var mt,gt=e._malloc=function(){return(gt=e._malloc=e.asm.eb).apply(null,arguments)},vt=e._free=function(){return(vt=e._free=e.asm.fb).apply(null,arguments)},wt=e._fflush=function(){return(wt=e._fflush=e.asm.gb).apply(null,arguments)},_t=e.___funcs_on_exit=function(){return(_t=e.___funcs_on_exit=e.asm.hb).apply(null,arguments)},Ot=e._setThrew=function(){return(Ot=e._setThrew=e.asm.jb).apply(null,arguments)},At=e.stackSave=function(){return(At=e.stackSave=e.asm.kb).apply(null,arguments)},St=e.stackRestore=function(){return(St=e.stackRestore=e.asm.lb).apply(null,arguments)},Tt=e.stackAlloc=function(){return(Tt=e.stackAlloc=e.asm.mb).apply(null,arguments)},Et=e.___cxa_can_catch=function(){return(Et=e.___cxa_can_catch=e.asm.nb).apply(null,arguments)},Mt=e.___cxa_is_pointer_type=function(){return(Mt=e.___cxa_is_pointer_type=e.asm.ob).apply(null,arguments)},Ct=e.dynCall_j=function(){return(Ct=e.dynCall_j=e.asm.pb).apply(null,arguments)},xt=e.dynCall_iiiiij=function(){return(xt=e.dynCall_iiiiij=e.asm.qb).apply(null,arguments)},Rt=e.dynCall_jii=function(){return(Rt=e.dynCall_jii=e.asm.rb).apply(null,arguments)},jt=e.dynCall_viiiiij=function(){return(jt=e.dynCall_viiiiij=e.asm.sb).apply(null,arguments)},kt=e.dynCall_vjji=function(){return(kt=e.dynCall_vjji=e.asm.tb).apply(null,arguments)},Dt=e.dynCall_viiijjjii=function(){return(Dt=e.dynCall_viiijjjii=e.asm.ub).apply(null,arguments)},Pt=e.dynCall_iij=function(){return(Pt=e.dynCall_iij=e.asm.vb).apply(null,arguments)},Ut=e.dynCall_ji=function(){return(Ut=e.dynCall_ji=e.asm.wb).apply(null,arguments)},Ft=e.dynCall_iiiiiij=function(){return(Ft=e.dynCall_iiiiiij=e.asm.xb).apply(null,arguments)},It=e.dynCall_iiij=function(){return(It=e.dynCall_iiij=e.asm.yb).apply(null,arguments)};function Wt(){function t(){if(!mt&&(mt=!0,e.calledRun=!0,!C)){if(Z(I),r(e),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;){var t=e.postRun.shift();H.unshift(t)}Z(H)}}if(!(0{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.iterateExtraOptions=void 0,e.iterateExtraOptions=(t,n,r,a)=>{if("object"==typeof t&&null!==t){if(r.has(t))throw new Error("Circular reference in options");r.add(t)}Object.entries(t).forEach((([t,i])=>{const o=n?n+t:t;if("object"==typeof i)(0,e.iterateExtraOptions)(i,o+".",r,a);else if("string"==typeof i||"number"==typeof i)a(o,i.toString());else{if("boolean"!=typeof i)throw new Error("Can\'t handle extra config type: "+typeof i);a(o,i?"1":"0")}}))}},586:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setRunOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setRunOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};try{if(void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);void 0===(null==t?void 0:t.terminate)&&(u.terminate=!1);let i=0;if(void 0!==(null==t?void 0:t.tag)&&(i=(0,a.allocWasmString)(t.tag,o)),n=e._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,i),0===n)throw new Error("Can\'t create run options");return void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddRunConfigEntry(n,i,u))throw new Error(`Can\'t set a run config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseRunOptions(n),o.forEach(e._free),t}}},919:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.setSessionOptions=void 0;const r=n(967),a=n(983),i=n(361);e.setSessionOptions=t=>{const e=(0,i.getInstance)();let n=0;const o=[],u=t||{};(t=>{t.extra||(t.extra={}),t.extra.session||(t.extra.session={});const e=t.extra.session;e.use_ort_model_bytes_directly||(e.use_ort_model_bytes_directly="1")})(u);try{void 0===(null==t?void 0:t.graphOptimizationLevel)&&(u.graphOptimizationLevel="all");const c=(t=>{switch(t){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${t}`)}})(u.graphOptimizationLevel);void 0===(null==t?void 0:t.enableCpuMemArena)&&(u.enableCpuMemArena=!0),void 0===(null==t?void 0:t.enableMemPattern)&&(u.enableMemPattern=!0),void 0===(null==t?void 0:t.executionMode)&&(u.executionMode="sequential");const s=(t=>{switch(t){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${t}`)}})(u.executionMode);let l=0;if(void 0!==(null==t?void 0:t.logId)&&(l=(0,a.allocWasmString)(t.logId,o)),void 0===(null==t?void 0:t.logSeverityLevel))u.logSeverityLevel=2;else if("number"!=typeof t.logSeverityLevel||!Number.isInteger(t.logSeverityLevel)||t.logSeverityLevel<0||t.logSeverityLevel>4)throw new Error(`log serverity level is not valid: ${t.logSeverityLevel}`);if(void 0===(null==t?void 0:t.logVerbosityLevel))u.logVerbosityLevel=0;else if("number"!=typeof t.logVerbosityLevel||!Number.isInteger(t.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${t.logVerbosityLevel}`);if(void 0===(null==t?void 0:t.enableProfiling)&&(u.enableProfiling=!1),n=e._OrtCreateSessionOptions(c,!!u.enableCpuMemArena,!!u.enableMemPattern,s,!!u.enableProfiling,0,l,u.logSeverityLevel,u.logVerbosityLevel),0===n)throw new Error("Can\'t create session options");return(null==t?void 0:t.executionProviders)&&((t,e,n)=>{for(const r of e){let e="string"==typeof r?r:r.name;switch(e){case"xnnpack":e="XNNPACK";break;case"wasm":case"cpu":continue;default:throw new Error(`not supported EP: ${e}`)}const o=(0,a.allocWasmString)(e,n);if(0!==(0,i.getInstance)()._OrtAppendExecutionProvider(t,o))throw new Error(`Can\'t append execution provider: ${e}`)}})(n,t.executionProviders,o),void 0!==(null==t?void 0:t.extra)&&(0,r.iterateExtraOptions)(t.extra,"",new WeakSet,((t,r)=>{const i=(0,a.allocWasmString)(t,o),u=(0,a.allocWasmString)(r,o);if(0!==e._OrtAddSessionConfigEntry(n,i,u))throw new Error(`Can\'t set a session config entry: ${t} - ${r}`)})),[n,o]}catch(t){throw 0!==n&&e._OrtReleaseSessionOptions(n),o.forEach(e._free),t}}},983:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.allocWasmString=void 0;const r=n(361);e.allocWasmString=(t,e)=>{const n=(0,r.getInstance)(),a=n.lengthBytesUTF8(t)+1,i=n._malloc(a);return n.stringToUTF8(t,i,a),e.push(i),i}},349:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.extractTransferableBuffers=e.endProfiling=e.run=e.releaseSession=e.createSession=e.createSessionFinalize=e.createSessionAllocate=e.initOrt=void 0;const r=n(586),a=n(919),i=n(983),o=n(361);e.initOrt=(t,e)=>{const n=(0,o.getInstance)()._OrtInit(t,e);if(0!==n)throw new Error(`Can\'t initialize onnxruntime. error code = ${n}`)};const u=new Map;e.createSessionAllocate=t=>{const e=(0,o.getInstance)(),n=e._malloc(t.byteLength);return e.HEAPU8.set(t,n),[n,t.byteLength]},e.createSessionFinalize=(t,e)=>{const n=(0,o.getInstance)();let r=0,i=0,c=[];try{if([i,c]=(0,a.setSessionOptions)(e),r=n._OrtCreateSession(t[0],t[1],i),0===r)throw new Error("Can\'t create a session")}finally{n._free(t[0]),n._OrtReleaseSessionOptions(i),c.forEach(n._free)}const s=n._OrtGetInputCount(r),l=n._OrtGetOutputCount(r),f=[],p=[],h=[],d=[];for(let t=0;t{const r=(0,e.createSessionAllocate)(t);return(0,e.createSessionFinalize)(r,n)},e.releaseSession=t=>{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=n[1],i=n[2];a.forEach(e._OrtFree),i.forEach(e._OrtFree),e._OrtReleaseSession(r),u.delete(t)};const c=t=>{switch(t){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;default:throw new Error(`unsupported data type: ${t}`)}},s=t=>{switch(t){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";default:throw new Error(`unsupported data type: ${t}`)}},l=t=>{switch(t){case"float32":return Float32Array;case"uint8":case"bool":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${t}`)}};e.run=(t,e,n,a,f)=>{const p=(0,o.getInstance)(),h=u.get(t);if(!h)throw new Error("invalid session id");const d=h[0],y=h[1],b=h[2],m=e.length,g=a.length;let v=0,w=[];const _=[],O=[];try{[v,w]=(0,r.setRunOptions)(f);for(let t=0;tp.HEAP32[t++]=e));const n=p._OrtCreateTensor(c(e),o,u,l,r.length);if(0===n)throw new Error("Can\'t create a tensor");_.push(n)}finally{p.stackRestore(s)}}const t=p.stackSave(),o=p.stackAlloc(4*m),u=p.stackAlloc(4*m),h=p.stackAlloc(4*g),A=p.stackAlloc(4*g);try{let n=o/4,r=u/4,i=h/4,c=A/4;for(let t=0;tt*e));if(a=s(o),"string"===a){const t=[];let e=i/4;for(let n=0;n{const e=(0,o.getInstance)(),n=u.get(t);if(!n)throw new Error("invalid session id");const r=n[0],a=e._OrtEndProfiling(r);if(0===a)throw new Error("Can\'t get an profile file name");e._OrtFree(a)},e.extractTransferableBuffers=t=>{const e=[];for(const n of t){const t=n[2];!Array.isArray(t)&&t.buffer&&e.push(t.buffer)}return e}},361:function(t,e,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(t,e,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(e,n);a&&!("get"in a?!e.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,a)}:function(t,e,n,r){void 0===r&&(r=n),t[r]=e[n]}),a=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),i=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&r(e,t,n);return a(e,t),e},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.dispose=e.getInstance=e.initializeWebAssembly=void 0;const u=i(n(449)),c=o(n(932)),s=n(474);let l,f=!1,p=!1,h=!1;const d=(t,e)=>e?t?"ort-wasm-simd-threaded.wasm":"ort-wasm-threaded.wasm":t?"ort-wasm-simd.wasm":"ort-wasm.wasm";e.initializeWebAssembly=async t=>{if(f)return Promise.resolve();if(p)throw new Error("multiple calls to \'initializeWebAssembly()\' detected.");if(h)throw new Error("previous call to \'initializeWebAssembly()\' failed.");p=!0;const e=t.initTimeout,r=t.numThreads,a=t.simd,i=r>1&&(()=>{try{return"undefined"!=typeof SharedArrayBuffer&&("undefined"!=typeof MessageChannel&&(new MessageChannel).port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11])))}catch(t){return!1}})(),o=a&&(()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch(t){return!1}})(),y="string"==typeof t.wasmPaths?t.wasmPaths:void 0,b=d(!1,i),m=d(o,i),g="object"==typeof t.wasmPaths?t.wasmPaths[m]:void 0;let v=!1;const w=[];if(e>0&&w.push(new Promise((t=>{setTimeout((()=>{v=!0,t()}),e)}))),w.push(new Promise(((t,e)=>{const r=i?s:c.default,a={locateFile:(t,e)=>i&&t.endsWith(".worker.js")&&"undefined"!=typeof Blob?URL.createObjectURL(new Blob([n(154)],{type:"text/javascript"})):t===b?null!=g?g:(null!=y?y:e)+m:e+t};if(i)if("undefined"==typeof Blob)a.mainScriptUrlOrBlob=u.join("/","ort-wasm-threaded.js");else{const t=`var ortWasmThreaded=(function(){var _scriptDir;return ${r.toString()}})();`;a.mainScriptUrlOrBlob=new Blob([t],{type:"text/javascript"})}r(a).then((e=>{p=!1,f=!0,l=e,t()}),(t=>{p=!1,h=!0,e(t)}))}))),await Promise.race(w),v)throw new Error(`WebAssembly backend initializing failed due to timeout: ${e}ms`)},e.getInstance=()=>{if(f&&l)return l;throw new Error("WebAssembly is not initialized yet.")},e.dispose=()=>{var t;!f||p||h||(p=!0,null===(t=l.PThread)||void 0===t||t.terminateAllThreads(),l=void 0,p=!1,f=!1,h=!0)}},154:t=>{"use strict";t.exports=\'"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\\n\'},384:()=>{},993:()=>{},908:()=>{},953:()=>{},925:()=>{},449:()=>{}},e={};function n(r){var a=e[r];if(void 0!==a)return a.exports;var i=e[r]={exports:{}};return t[r].call(i.exports,i,i.exports,n),i.exports}n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),(()=>{"use strict";const t=n(349),e=n(361);self.onmessage=n=>{switch(n.data.type){case"init-wasm":(0,e.initializeWebAssembly)(n.data.in).then((()=>postMessage({type:"init-wasm"})),(t=>postMessage({type:"init-wasm",err:t})));break;case"init-ort":try{const{numThreads:e,loggingLevel:r}=n.data.in;(0,t.initOrt)(e,r),postMessage({type:"init-ort"})}catch(t){postMessage({type:"init-ort",err:t})}break;case"create_allocate":try{const{model:e}=n.data.in,r=(0,t.createSessionAllocate)(e);postMessage({type:"create_allocate",out:r})}catch(t){postMessage({type:"create_allocate",err:t})}break;case"create_finalize":try{const{modeldata:e,options:r}=n.data.in,a=(0,t.createSessionFinalize)(e,r);postMessage({type:"create_finalize",out:a})}catch(t){postMessage({type:"create_finalize",err:t})}break;case"create":try{const{model:e,options:r}=n.data.in,a=(0,t.createSession)(e,r);postMessage({type:"create",out:a})}catch(t){postMessage({type:"create",err:t})}break;case"release":try{const e=n.data.in;(0,t.releaseSession)(e),postMessage({type:"release"})}catch(t){postMessage({type:"release",err:t})}break;case"run":try{const{sessionId:e,inputIndices:r,inputs:a,outputIndices:i,options:o}=n.data.in,u=(0,t.run)(e,r,a,i,o);postMessage({type:"run",out:u},(0,t.extractTransferableBuffers)(u))}catch(t){postMessage({type:"run",err:t})}break;case"end-profiling":try{const e=n.data.in;(0,t.endProfiling)(e),postMessage({type:"end-profiling"})}catch(t){postMessage({type:"end-profiling",err:t})}}}})()})();\n',"Worker",void 0,void 0)}},477:t=>{"use strict";t.exports=function(t,e,n,r){var i=self||window;try{try{var o;try{o=new i.Blob([t])}catch(e){(o=new(i.BlobBuilder||i.WebKitBlobBuilder||i.MozBlobBuilder||i.MSBlobBuilder)).append(t),o=o.getBlob()}var a=i.URL||i.webkitURL,s=a.createObjectURL(o),u=new i[e](s,n);return a.revokeObjectURL(s),u}catch(r){return new i[e]("data:application/javascript,".concat(encodeURIComponent(t)),n)}}catch(t){if(!r)throw Error("Inline worker is not supported");return new i[e](r,n)}}},4154:t=>{"use strict";t.exports='"use strict";var e={},t="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node;if(t){var r=require("worker_threads"),a=r.parentPort;a.on("message",(e=>onmessage({data:e})));var o=require("fs");Object.assign(global,{self:global,require:require,Module:e,location:{href:__filename},Worker:r.Worker,importScripts:function(e){(0,eval)(o.readFileSync(e,"utf8"))},postMessage:function(e){a.postMessage(e)},performance:global.performance||{now:function(){return Date.now()}}})}var s=!1,n=[],i=function(){var e=Array.prototype.slice.call(arguments).join(" ");t?o.writeSync(2,e+"\\n"):console.error(e)};self.alert=function(){var t=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:t,threadId:e._pthread_self()})},e.instantiateWasm=(t,r)=>{var a=new WebAssembly.Instance(e.wasmModule,t);return r(a),e.wasmModule=null,a.exports},self.onunhandledrejection=e=>{throw e.reason??e},self.onmessage=t=>{try{if("load"===t.data.cmd){if(e.wasmModule=t.data.wasmModule,e.wasmMemory=t.data.wasmMemory,e.buffer=e.wasmMemory.buffer,e.ENVIRONMENT_IS_PTHREAD=!0,"string"==typeof t.data.urlOrBlob)importScripts(t.data.urlOrBlob);else{var r=URL.createObjectURL(t.data.urlOrBlob);importScripts(r),URL.revokeObjectURL(r)}ortWasmThreaded(e).then((function(t){e=t}))}else if("run"===t.data.cmd){e.__performance_now_clock_drift=performance.now()-t.data.time,e.__emscripten_thread_init(t.data.pthread_ptr,0,0,1),e.establishStackSpace(),e.PThread.receiveObjectTransfer(t.data),e.PThread.threadInitTLS(),s||(n.forEach((t=>{e.executeNotifiedProxyingQueue(t)})),n=[],s=!0);try{e.invokeEntryPoint(t.data.start_routine,t.data.arg)}catch(t){if("unwind"!=t){if(!(t instanceof e.ExitStatus))throw t;e.keepRuntimeAlive()||e.__emscripten_thread_exit(t.status)}}}else"cancel"===t.data.cmd?e._pthread_self()&&e.__emscripten_thread_exit(-1):"setimmediate"===t.data.target||("processProxyingQueue"===t.data.cmd?s?e.executeNotifiedProxyingQueue(t.data.queue):n.push(t.data.queue):(i("worker.js received unknown command "+t.data.cmd),i(t.data)))}catch(t){throw i("worker.js onmessage() captured an uncaught exception: "+t),t&&t.stack&&i(t.stack),e.__emscripten_thread_crashed&&e.__emscripten_thread_crashed(),t}};\n'},1670:t=>{"use strict";t.exports=__WEBPACK_EXTERNAL_MODULE__1670__},7067:()=>{},1296:()=>{},1384:()=>{},3993:()=>{},908:()=>{},6953:()=>{},9925:()=>{},2806:()=>{},6449:()=>{},2850:()=>{},5381:()=>{},5686:(t,e,n)=>{"use strict";n.r(e),n.d(e,{flatbuffers:()=>r});var r={};r.Offset,r.Table,r.SIZEOF_SHORT=2,r.SIZEOF_INT=4,r.FILE_IDENTIFIER_LENGTH=4,r.SIZE_PREFIX_LENGTH=4,r.Encoding={UTF8_BYTES:1,UTF16_STRING:2},r.int32=new Int32Array(2),r.float32=new Float32Array(r.int32.buffer),r.float64=new Float64Array(r.int32.buffer),r.isLittleEndian=1===new Uint16Array(new Uint8Array([1,0]).buffer)[0],r.Long=function(t,e){this.low=0|t,this.high=0|e},r.Long.create=function(t,e){return 0==t&&0==e?r.Long.ZERO:new r.Long(t,e)},r.Long.prototype.toFloat64=function(){return(this.low>>>0)+4294967296*this.high},r.Long.prototype.equals=function(t){return this.low==t.low&&this.high==t.high},r.Long.ZERO=new r.Long(0,0),r.Builder=function(t){if(t)e=t;else var e=1024;this.bb=r.ByteBuffer.allocate(e),this.space=e,this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.clear=function(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1},r.Builder.prototype.forceDefaults=function(t){this.force_defaults=t},r.Builder.prototype.dataBuffer=function(){return this.bb},r.Builder.prototype.asUint8Array=function(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())},r.Builder.prototype.prep=function(t,e){t>this.minalign&&(this.minalign=t);for(var n=1+~(this.bb.capacity()-this.space+e)&t-1;this.space=0&&0==this.vtable[e];e--);for(var n=e+1;e>=0;e--)this.addInt16(0!=this.vtable[e]?t-this.vtable[e]:0);this.addInt16(t-this.object_start);var i=(n+2)*r.SIZEOF_SHORT;this.addInt16(i);var o=0,a=this.space;t:for(e=0;e=0;a--)this.writeInt8(o.charCodeAt(a))}this.prep(this.minalign,r.SIZEOF_INT+i),this.addOffset(t),i&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)},r.Builder.prototype.finishSizePrefixed=function(t,e){this.finish(t,e,!0)},r.Builder.prototype.requiredField=function(t,e){var n=this.bb.capacity()-t,r=n-this.bb.readInt32(n);if(0==this.bb.readInt16(r+e))throw new Error("FlatBuffers: field "+e+" must be set")},r.Builder.prototype.startVector=function(t,e,n){this.notNested(),this.vector_num_elems=e,this.prep(r.SIZEOF_INT,t*e),this.prep(n,t*e)},r.Builder.prototype.endVector=function(){return this.writeInt32(this.vector_num_elems),this.offset()},r.Builder.prototype.createString=function(t){if(t instanceof Uint8Array)var e=t;else{e=[];for(var n=0;n=56320?i:(i<<10)+t.charCodeAt(n++)+-56613888)<128?e.push(r):(r<2048?e.push(r>>6&31|192):(r<65536?e.push(r>>12&15|224):e.push(r>>18&7|240,r>>12&63|128),e.push(r>>6&63|128)),e.push(63&r|128))}}this.addInt8(0),this.startVector(1,e.length,1),this.bb.setPosition(this.space-=e.length),n=0;for(var o=this.space,a=this.bb.bytes();n>24},r.ByteBuffer.prototype.readUint8=function(t){return this.bytes_[t]},r.ByteBuffer.prototype.readInt16=function(t){return this.readUint16(t)<<16>>16},r.ByteBuffer.prototype.readUint16=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8},r.ByteBuffer.prototype.readInt32=function(t){return this.bytes_[t]|this.bytes_[t+1]<<8|this.bytes_[t+2]<<16|this.bytes_[t+3]<<24},r.ByteBuffer.prototype.readUint32=function(t){return this.readInt32(t)>>>0},r.ByteBuffer.prototype.readInt64=function(t){return new r.Long(this.readInt32(t),this.readInt32(t+4))},r.ByteBuffer.prototype.readUint64=function(t){return new r.Long(this.readUint32(t),this.readUint32(t+4))},r.ByteBuffer.prototype.readFloat32=function(t){return r.int32[0]=this.readInt32(t),r.float32[0]},r.ByteBuffer.prototype.readFloat64=function(t){return r.int32[r.isLittleEndian?0:1]=this.readInt32(t),r.int32[r.isLittleEndian?1:0]=this.readInt32(t+4),r.float64[0]},r.ByteBuffer.prototype.writeInt8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeUint8=function(t,e){this.bytes_[t]=e},r.ByteBuffer.prototype.writeInt16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeUint16=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8},r.ByteBuffer.prototype.writeInt32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeUint32=function(t,e){this.bytes_[t]=e,this.bytes_[t+1]=e>>8,this.bytes_[t+2]=e>>16,this.bytes_[t+3]=e>>24},r.ByteBuffer.prototype.writeInt64=function(t,e){this.writeInt32(t,e.low),this.writeInt32(t+4,e.high)},r.ByteBuffer.prototype.writeUint64=function(t,e){this.writeUint32(t,e.low),this.writeUint32(t+4,e.high)},r.ByteBuffer.prototype.writeFloat32=function(t,e){r.float32[0]=e,this.writeInt32(t,r.int32[0])},r.ByteBuffer.prototype.writeFloat64=function(t,e){r.float64[0]=e,this.writeInt32(t,r.int32[r.isLittleEndian?0:1]),this.writeInt32(t+4,r.int32[r.isLittleEndian?1:0])},r.ByteBuffer.prototype.getBufferIdentifier=function(){if(this.bytes_.length>10),56320+(1023&a)))}return i},r.ByteBuffer.prototype.__indirect=function(t){return t+this.readInt32(t)},r.ByteBuffer.prototype.__vector=function(t){return t+this.readInt32(t)+r.SIZEOF_INT},r.ByteBuffer.prototype.__vector_len=function(t){return this.readInt32(t+this.readInt32(t))},r.ByteBuffer.prototype.__has_identifier=function(t){if(t.length!=r.FILE_IDENTIFIER_LENGTH)throw new Error("FlatBuffers: file identifier must be length "+r.FILE_IDENTIFIER_LENGTH);for(var e=0;e{var e=t&&t.__esModule?()=>t.default:()=>t;return __nested_webpack_require_546802__.d(e,{a:e}),e},__nested_webpack_require_546802__.d=(t,e)=>{for(var n in e)__nested_webpack_require_546802__.o(e,n)&&!__nested_webpack_require_546802__.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:e[n]})},__nested_webpack_require_546802__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(t){if("object"==typeof window)return window}}(),__nested_webpack_require_546802__.o=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),__nested_webpack_require_546802__.r=t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})};var __webpack_exports__=__nested_webpack_require_546802__(6018);return __webpack_exports__})())); +//# sourceMappingURL=ort-web.min.js.map + +/***/ }), + +/***/ "./node_modules/process/browser.js": +/*!*****************************************!*\ + !*** ./node_modules/process/browser.js ***! + \*****************************************/ +/***/ ((module) => { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), + +/***/ "./node_modules/rbush/rbush.min.js": +/*!*****************************************!*\ + !*** ./node_modules/rbush/rbush.min.js ***! + \*****************************************/ +/***/ (function(module) { + +!function(t,i){ true?module.exports=i():0}(this,function(){"use strict";function t(t,r,e,a,h){!function t(n,r,e,a,h){for(;a>e;){if(a-e>600){var o=a-e+1,s=r-e+1,l=Math.log(o),f=.5*Math.exp(2*l/3),u=.5*Math.sqrt(l*f*(o-f)/o)*(s-o/2<0?-1:1),m=Math.max(e,Math.floor(r-s*f/o+u)),c=Math.min(a,Math.floor(r+(o-s)*f/o+u));t(n,r,m,c,h)}var p=n[r],d=e,x=a;for(i(n,e,r),h(n[a],p)>0&&i(n,e,a);d0;)x--}0===h(n[e],p)?i(n,e,x):i(n,++x,a),x<=r&&(e=x+1),r<=x&&(a=x-1)}}(t,r,e||0,a||t.length-1,h||n)}function i(t,i,n){var r=t[i];t[i]=t[n],t[n]=r}function n(t,i){return ti?1:0}var r=function(t){void 0===t&&(t=9),this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()};function e(t,i,n){if(!n)return i.indexOf(t);for(var r=0;r=t.minX&&i.maxY>=t.minY}function p(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function d(i,n,r,e,a){for(var h=[n,r];h.length;)if(!((r=h.pop())-(n=h.pop())<=e)){var o=n+Math.ceil((r-n)/e/2)*e;t(i,o,n,r,a),h.push(n,o,o,r)}}return r.prototype.all=function(){return this._all(this.data,[])},r.prototype.search=function(t){var i=this.data,n=[];if(!c(t,i))return n;for(var r=this.toBBox,e=[];i;){for(var a=0;a=0&&e[i].children.length>this._maxEntries;)this._split(e,i),i--;this._adjustParentBBoxes(r,e,i)},r.prototype._split=function(t,i){var n=t[i],r=n.children.length,e=this._minEntries;this._chooseSplitAxis(n,e,r);var h=this._chooseSplitIndex(n,e,r),o=p(n.children.splice(h,n.children.length-h));o.height=n.height,o.leaf=n.leaf,a(n,this.toBBox),a(o,this.toBBox),i?t[i-1].children.push(o):this._splitRoot(n,o)},r.prototype._splitRoot=function(t,i){this.data=p([t,i]),this.data.height=t.height+1,this.data.leaf=!1,a(this.data,this.toBBox)},r.prototype._chooseSplitIndex=function(t,i,n){for(var r,e,a,o,s,l,u,m=1/0,c=1/0,p=i;p<=n-i;p++){var d=h(t,0,p,this.toBBox),x=h(t,p,n,this.toBBox),v=(e=d,a=x,o=void 0,s=void 0,l=void 0,u=void 0,o=Math.max(e.minX,a.minX),s=Math.max(e.minY,a.minY),l=Math.min(e.maxX,a.maxX),u=Math.min(e.maxY,a.maxY),Math.max(0,l-o)*Math.max(0,u-s)),M=f(d)+f(x);v=i;c--){var p=t.children[c];o(s,t.leaf?e(p):p),l+=u(s)}return l},r.prototype._adjustParentBBoxes=function(t,i,n){for(var r=n;r>=0;r--)o(i[r],t)},r.prototype._condense=function(t){for(var i=t.length-1,n=void 0;i>=0;i--)0===t[i].children.length?i>0?(n=t[i-1].children).splice(n.indexOf(t[i]),1):this.clear():a(t[i],this.toBBox)},r}); + + +/***/ }), + +/***/ "./src/resources/assets/js/MagicSamMixin.vue": +/*!***************************************************!*\ + !*** ./src/resources/assets/js/MagicSamMixin.vue ***! + \***************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _MagicSamMixin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./MagicSamMixin.vue?vue&type=script&lang=js& */ "./src/resources/assets/js/MagicSamMixin.vue?vue&type=script&lang=js&"); +/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); +var render, staticRenderFns +; + + + +/* normalize component */ +; +var component = (0,_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_1__["default"])( + _MagicSamMixin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"], + render, + staticRenderFns, + false, + null, + null, + null + +) + +/* hot reload */ +if (false) { var api; } +component.options.__file = "src/resources/assets/js/MagicSamMixin.vue" +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (component.exports); + +/***/ }), + +/***/ "./src/resources/assets/js/components/settingsTabPlugin.vue": +/*!******************************************************************!*\ + !*** ./src/resources/assets/js/components/settingsTabPlugin.vue ***! + \******************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _settingsTabPlugin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./settingsTabPlugin.vue?vue&type=script&lang=js& */ "./src/resources/assets/js/components/settingsTabPlugin.vue?vue&type=script&lang=js&"); +/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); +var render, staticRenderFns +; + + + +/* normalize component */ +; +var component = (0,_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_1__["default"])( + _settingsTabPlugin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"], + render, + staticRenderFns, + false, + null, + null, + null + +) + +/* hot reload */ +if (false) { var api; } +component.options.__file = "src/resources/assets/js/components/settingsTabPlugin.vue" +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (component.exports); + +/***/ }), + +/***/ "./src/resources/assets/js/MagicSamMixin.vue?vue&type=script&lang=js&": +/*!****************************************************************************!*\ + !*** ./src/resources/assets/js/MagicSamMixin.vue?vue&type=script&lang=js& ***! + \****************************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _node_modules_babel_loader_lib_index_js_clonedRuleSet_5_0_rules_0_use_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MagicSamMixin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!../../../../node_modules/vue-loader/lib/index.js??vue-loader-options!./MagicSamMixin.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./src/resources/assets/js/MagicSamMixin.vue?vue&type=script&lang=js&"); + /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_babel_loader_lib_index_js_clonedRuleSet_5_0_rules_0_use_0_node_modules_vue_loader_lib_index_js_vue_loader_options_MagicSamMixin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); + +/***/ }), + +/***/ "./src/resources/assets/js/components/settingsTabPlugin.vue?vue&type=script&lang=js&": +/*!*******************************************************************************************!*\ + !*** ./src/resources/assets/js/components/settingsTabPlugin.vue?vue&type=script&lang=js& ***! + \*******************************************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _node_modules_babel_loader_lib_index_js_clonedRuleSet_5_0_rules_0_use_0_node_modules_vue_loader_lib_index_js_vue_loader_options_settingsTabPlugin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!../../../../../node_modules/vue-loader/lib/index.js??vue-loader-options!./settingsTabPlugin.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./src/resources/assets/js/components/settingsTabPlugin.vue?vue&type=script&lang=js&"); + /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_node_modules_babel_loader_lib_index_js_clonedRuleSet_5_0_rules_0_use_0_node_modules_vue_loader_lib_index_js_vue_loader_options_settingsTabPlugin_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); + +/***/ }), + +/***/ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js": +/*!********************************************************************!*\ + !*** ./node_modules/vue-loader/lib/runtime/componentNormalizer.js ***! + \********************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (/* binding */ normalizeComponent) +/* harmony export */ }); +/* globals __VUE_SSR_CONTEXT__ */ + +// IMPORTANT: Do NOT use ES2015 features in this file (except for modules). +// This module is a runtime utility for cleaner component module output and will +// be included in the final webpack user bundle. + +function normalizeComponent ( + scriptExports, + render, + staticRenderFns, + functionalTemplate, + injectStyles, + scopeId, + moduleIdentifier, /* server only */ + shadowMode /* vue-cli only */ +) { + // Vue.extend constructor export interop + var options = typeof scriptExports === 'function' + ? scriptExports.options + : scriptExports + + // render functions + if (render) { + options.render = render + options.staticRenderFns = staticRenderFns + options._compiled = true + } + + // functional template + if (functionalTemplate) { + options.functional = true + } + + // scopedId + if (scopeId) { + options._scopeId = 'data-v-' + scopeId + } + + var hook + if (moduleIdentifier) { // server build + hook = function (context) { + // 2.3 injection + context = + context || // cached call + (this.$vnode && this.$vnode.ssrContext) || // stateful + (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional + // 2.2 with runInNewContext: true + if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { + context = __VUE_SSR_CONTEXT__ + } + // inject component styles + if (injectStyles) { + injectStyles.call(this, context) + } + // register component module identifier for async chunk inferrence + if (context && context._registeredComponents) { + context._registeredComponents.add(moduleIdentifier) + } + } + // used by ssr in case component is cached and beforeCreate + // never gets called + options._ssrRegister = hook + } else if (injectStyles) { + hook = shadowMode + ? function () { + injectStyles.call( + this, + (options.functional ? this.parent : this).$root.$options.shadowRoot + ) + } + : injectStyles + } + + if (hook) { + if (options.functional) { + // for template-only hot-reload because in that case the render fn doesn't + // go through the normalizer + options._injectStyles = hook + // register for functional component in vue file + var originalRender = options.render + options.render = function renderWithStyleInjection (h, context) { + hook.call(context) + return originalRender(h, context) + } + } else { + // inject component registration as beforeCreate hook + var existing = options.beforeCreate + options.beforeCreate = existing + ? [].concat(existing, hook) + : [hook] + } + } + + return { + exports: scriptExports, + options: options + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/Collection.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/Collection.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CollectionEvent": () => (/* binding */ CollectionEvent), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Object.js */ "./node_modules/@biigle/ol/Object.js"); +/* harmony import */ var _CollectionEventType_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./CollectionEventType.js */ "./node_modules/@biigle/ol/CollectionEventType.js"); +/* harmony import */ var _events_Event_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events/Event.js */ "./node_modules/@biigle/ol/events/Event.js"); +/** + * @module ol/Collection + */ + + + + +/** + * @enum {string} + * @private + */ +const Property = { + LENGTH: 'length', +}; + +/** + * @classdesc + * Events emitted by {@link module:ol/Collection~Collection} instances are instances of this + * type. + * @template T + */ +class CollectionEvent extends _events_Event_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {import("./CollectionEventType.js").default} type Type. + * @param {T} element Element. + * @param {number} index The index of the added or removed element. + */ + constructor(type, element, index) { + super(type); + + /** + * The element that is added to or removed from the collection. + * @type {T} + * @api + */ + this.element = element; + + /** + * The index of the added or removed element. + * @type {number} + * @api + */ + this.index = index; + } +} + +/*** + * @template T + * @template Return + * @typedef {import("./Observable").OnSignature & + * import("./Observable").OnSignature & + * import("./Observable").OnSignature<'add'|'remove', CollectionEvent, Return> & + * import("./Observable").CombinedOnSignature} CollectionOnSignature + */ + +/** + * @typedef {Object} Options + * @property {boolean} [unique=false] Disallow the same item from being added to + * the collection twice. + */ + +/** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @fires CollectionEvent + * + * @template T + * @api + */ +class Collection extends _Object_js__WEBPACK_IMPORTED_MODULE_1__["default"] { + /** + * @param {Array} [array] Array. + * @param {Options} [options] Collection options. + */ + constructor(array, options) { + super(); + + /*** + * @type {CollectionOnSignature} + */ + this.on; + + /*** + * @type {CollectionOnSignature} + */ + this.once; + + /*** + * @type {CollectionOnSignature} + */ + this.un; + + options = options || {}; + + /** + * @private + * @type {boolean} + */ + this.unique_ = !!options.unique; + + /** + * @private + * @type {!Array} + */ + this.array_ = array ? array : []; + + if (this.unique_) { + for (let i = 0, ii = this.array_.length; i < ii; ++i) { + this.assertUnique_(this.array_[i], i); + } + } + + this.updateLength_(); + } + + /** + * Remove all elements from the collection. + * @api + */ + clear() { + while (this.getLength() > 0) { + this.pop(); + } + } + + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array} arr Array. + * @return {Collection} This collection. + * @api + */ + extend(arr) { + for (let i = 0, ii = arr.length; i < ii; ++i) { + this.push(arr[i]); + } + return this; + } + + /** + * Iterate over each element, calling the provided callback. + * @param {function(T, number, Array): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @api + */ + forEach(f) { + const array = this.array_; + for (let i = 0, ii = array.length; i < ii; ++i) { + f(array[i], i, array); + } + } + + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array} Array. + * @api + */ + getArray() { + return this.array_; + } + + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api + */ + item(index) { + return this.array_[index]; + } + + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api + */ + getLength() { + return this.get(Property.LENGTH); + } + + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api + */ + insertAt(index, elem) { + if (index < 0 || index > this.getLength()) { + throw new Error('Index out of bounds: ' + index); + } + if (this.unique_) { + this.assertUnique_(elem); + } + this.array_.splice(index, 0, elem); + this.updateLength_(); + this.dispatchEvent( + new CollectionEvent(_CollectionEventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].ADD, elem, index), + ); + } + + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api + */ + pop() { + return this.removeAt(this.getLength() - 1); + } + + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} New length of the collection. + * @api + */ + push(elem) { + if (this.unique_) { + this.assertUnique_(elem); + } + const n = this.getLength(); + this.insertAt(n, elem); + return this.getLength(); + } + + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api + */ + remove(elem) { + const arr = this.array_; + for (let i = 0, ii = arr.length; i < ii; ++i) { + if (arr[i] === elem) { + return this.removeAt(i); + } + } + return undefined; + } + + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api + */ + removeAt(index) { + if (index < 0 || index >= this.getLength()) { + return undefined; + } + const prev = this.array_[index]; + this.array_.splice(index, 1); + this.updateLength_(); + this.dispatchEvent( + /** @type {CollectionEvent} */ ( + new CollectionEvent(_CollectionEventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].REMOVE, prev, index) + ), + ); + return prev; + } + + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api + */ + setAt(index, elem) { + const n = this.getLength(); + if (index >= n) { + this.insertAt(index, elem); + return; + } + if (index < 0) { + throw new Error('Index out of bounds: ' + index); + } + if (this.unique_) { + this.assertUnique_(elem, index); + } + const prev = this.array_[index]; + this.array_[index] = elem; + this.dispatchEvent( + /** @type {CollectionEvent} */ ( + new CollectionEvent(_CollectionEventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].REMOVE, prev, index) + ), + ); + this.dispatchEvent( + /** @type {CollectionEvent} */ ( + new CollectionEvent(_CollectionEventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].ADD, elem, index) + ), + ); + } + + /** + * @private + */ + updateLength_() { + this.set(Property.LENGTH, this.array_.length); + } + + /** + * @private + * @param {T} elem Element. + * @param {number} [except] Optional index to ignore. + */ + assertUnique_(elem, except) { + for (let i = 0, ii = this.array_.length; i < ii; ++i) { + if (this.array_[i] === elem && i !== except) { + throw new Error('Duplicate item added to a unique collection'); + } + } + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Collection); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/CollectionEventType.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/CollectionEventType.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/CollectionEventType + */ + +/** + * @enum {string} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + /** + * Triggered when an item is added to the collection. + * @event module:ol/Collection.CollectionEvent#add + * @api + */ + ADD: 'add', + /** + * Triggered when an item is removed from the collection. + * @event module:ol/Collection.CollectionEvent#remove + * @api + */ + REMOVE: 'remove', +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/Disposable.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/Disposable.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/Disposable + */ + +/** + * @classdesc + * Objects that need to clean up after themselves. + */ +class Disposable { + constructor() { + /** + * The object has already been disposed. + * @type {boolean} + * @protected + */ + this.disposed = false; + } + + /** + * Clean up. + */ + dispose() { + if (!this.disposed) { + this.disposed = true; + this.disposeInternal(); + } + } + + /** + * Extension point for disposable objects. + * @protected + */ + disposeInternal() {} +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Disposable); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/Feature.js": +/*!********************************************!*\ + !*** ./node_modules/@biigle/ol/Feature.js ***! + \********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createStyleFunction": () => (/* binding */ createStyleFunction), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Object_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Object.js */ "./node_modules/@biigle/ol/Object.js"); +/* harmony import */ var _events_EventType_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./events/EventType.js */ "./node_modules/@biigle/ol/events/EventType.js"); +/* harmony import */ var _asserts_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./asserts.js */ "./node_modules/@biigle/ol/asserts.js"); +/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./events.js */ "./node_modules/@biigle/ol/events.js"); +/** + * @module ol/Feature + */ + + + + + +/** + * @typedef {typeof Feature|typeof import("./render/Feature.js").default} FeatureClass + */ + +/** + * @typedef {Feature|import("./render/Feature.js").default} FeatureLike + */ + +/*** + * @template Return + * @typedef {import("./Observable").OnSignature & + * import("./Observable").OnSignature & + * import("./Observable").CombinedOnSignature} FeatureOnSignature + */ + +/*** + * @template {import("./geom/Geometry.js").default} [Geometry=import("./geom/Geometry.js").default] + * @typedef {Object & { geometry?: Geometry }} ObjectWithGeometry + */ + +/** + * @classdesc + * A vector object for geographic features with a geometry and other + * attribute properties, similar to the features in vector file formats like + * GeoJSON. + * + * Features can be styled individually with `setStyle`; otherwise they use the + * style of their vector layer. + * + * Note that attribute properties are set as {@link module:ol/Object~BaseObject} properties on + * the feature object, so they are observable, and have get/set accessors. + * + * Typically, a feature has a single geometry property. You can set the + * geometry using the `setGeometry` method and get it with `getGeometry`. + * It is possible to store more than one geometry on a feature using attribute + * properties. By default, the geometry used for rendering is identified by + * the property name `geometry`. If you want to use another geometry property + * for rendering, use the `setGeometryName` method to change the attribute + * property associated with the geometry for the feature. For example: + * + * ```js + * + * import Feature from 'ol/Feature.js'; + * import Polygon from 'ol/geom/Polygon.js'; + * import Point from 'ol/geom/Point.js'; + * + * const feature = new Feature({ + * geometry: new Polygon(polyCoords), + * labelPoint: new Point(labelCoords), + * name: 'My Polygon', + * }); + * + * // get the polygon geometry + * const poly = feature.getGeometry(); + * + * // Render the feature as a point using the coordinates from labelPoint + * feature.setGeometryName('labelPoint'); + * + * // get the point geometry + * const point = feature.getGeometry(); + * ``` + * + * @api + * @template {import("./geom/Geometry.js").default} [Geometry=import("./geom/Geometry.js").default] + */ +class Feature extends _Object_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Geometry|ObjectWithGeometry} [geometryOrProperties] + * You may pass a Geometry object directly, or an object literal containing + * properties. If you pass an object literal, you may include a Geometry + * associated with a `geometry` key. + */ + constructor(geometryOrProperties) { + super(); + + /*** + * @type {FeatureOnSignature} + */ + this.on; + + /*** + * @type {FeatureOnSignature} + */ + this.once; + + /*** + * @type {FeatureOnSignature} + */ + this.un; + + /** + * @private + * @type {number|string|undefined} + */ + this.id_ = undefined; + + /** + * @type {string} + * @private + */ + this.geometryName_ = 'geometry'; + + /** + * User provided style. + * @private + * @type {import("./style/Style.js").StyleLike} + */ + this.style_ = null; + + /** + * @private + * @type {import("./style/Style.js").StyleFunction|undefined} + */ + this.styleFunction_ = undefined; + + /** + * @private + * @type {?import("./events.js").EventsKey} + */ + this.geometryChangeKey_ = null; + + this.addChangeListener(this.geometryName_, this.handleGeometryChanged_); + + if (geometryOrProperties) { + if ( + typeof ( + /** @type {?} */ (geometryOrProperties).getSimplifiedGeometry + ) === 'function' + ) { + const geometry = /** @type {Geometry} */ (geometryOrProperties); + this.setGeometry(geometry); + } else { + /** @type {Object} */ + const properties = geometryOrProperties; + this.setProperties(properties); + } + } + } + + /** + * Clone this feature. If the original feature has a geometry it + * is also cloned. The feature id is not set in the clone. + * @return {Feature} The clone. + * @api + */ + clone() { + const clone = /** @type {Feature} */ ( + new Feature(this.hasProperties() ? this.getProperties() : null) + ); + clone.setGeometryName(this.getGeometryName()); + const geometry = this.getGeometry(); + if (geometry) { + clone.setGeometry(/** @type {Geometry} */ (geometry.clone())); + } + const style = this.getStyle(); + if (style) { + clone.setStyle(style); + } + return clone; + } + + /** + * Get the feature's default geometry. A feature may have any number of named + * geometries. The "default" geometry (the one that is rendered by default) is + * set when calling {@link module:ol/Feature~Feature#setGeometry}. + * @return {Geometry|undefined} The default geometry for the feature. + * @api + * @observable + */ + getGeometry() { + return /** @type {Geometry|undefined} */ (this.get(this.geometryName_)); + } + + /** + * Get the feature identifier. This is a stable identifier for the feature and + * is either set when reading data from a remote source or set explicitly by + * calling {@link module:ol/Feature~Feature#setId}. + * @return {number|string|undefined} Id. + * @api + */ + getId() { + return this.id_; + } + + /** + * Get the name of the feature's default geometry. By default, the default + * geometry is named `geometry`. + * @return {string} Get the property name associated with the default geometry + * for this feature. + * @api + */ + getGeometryName() { + return this.geometryName_; + } + + /** + * Get the feature's style. Will return what was provided to the + * {@link module:ol/Feature~Feature#setStyle} method. + * @return {import("./style/Style.js").StyleLike|undefined} The feature style. + * @api + */ + getStyle() { + return this.style_; + } + + /** + * Get the feature's style function. + * @return {import("./style/Style.js").StyleFunction|undefined} Return a function + * representing the current style of this feature. + * @api + */ + getStyleFunction() { + return this.styleFunction_; + } + + /** + * @private + */ + handleGeometryChange_() { + this.changed(); + } + + /** + * @private + */ + handleGeometryChanged_() { + if (this.geometryChangeKey_) { + (0,_events_js__WEBPACK_IMPORTED_MODULE_1__.unlistenByKey)(this.geometryChangeKey_); + this.geometryChangeKey_ = null; + } + const geometry = this.getGeometry(); + if (geometry) { + this.geometryChangeKey_ = (0,_events_js__WEBPACK_IMPORTED_MODULE_1__.listen)( + geometry, + _events_EventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].CHANGE, + this.handleGeometryChange_, + this, + ); + } + this.changed(); + } + + /** + * Set the default geometry for the feature. This will update the property + * with the name returned by {@link module:ol/Feature~Feature#getGeometryName}. + * @param {Geometry|undefined} geometry The new geometry. + * @api + * @observable + */ + setGeometry(geometry) { + this.set(this.geometryName_, geometry); + } + + /** + * Set the style for the feature to override the layer style. This can be a + * single style object, an array of styles, or a function that takes a + * resolution and returns an array of styles. To unset the feature style, call + * `setStyle()` without arguments or a falsey value. + * @param {import("./style/Style.js").StyleLike} [style] Style for this feature. + * @api + * @fires module:ol/events/Event~BaseEvent#event:change + */ + setStyle(style) { + this.style_ = style; + this.styleFunction_ = !style ? undefined : createStyleFunction(style); + this.changed(); + } + + /** + * Set the feature id. The feature id is considered stable and may be used when + * requesting features or comparing identifiers returned from a remote source. + * The feature id can be used with the + * {@link module:ol/source/Vector~VectorSource#getFeatureById} method. + * @param {number|string|undefined} id The feature id. + * @api + * @fires module:ol/events/Event~BaseEvent#event:change + */ + setId(id) { + this.id_ = id; + this.changed(); + } + + /** + * Set the property name to be used when getting the feature's default geometry. + * When calling {@link module:ol/Feature~Feature#getGeometry}, the value of the property with + * this name will be returned. + * @param {string} name The property name of the default geometry. + * @api + */ + setGeometryName(name) { + this.removeChangeListener(this.geometryName_, this.handleGeometryChanged_); + this.geometryName_ = name; + this.addChangeListener(this.geometryName_, this.handleGeometryChanged_); + this.handleGeometryChanged_(); + } +} + +/** + * Convert the provided object into a feature style function. Functions passed + * through unchanged. Arrays of Style or single style objects wrapped + * in a new feature style function. + * @param {!import("./style/Style.js").StyleFunction|!Array|!import("./style/Style.js").default} obj + * A feature style function, a single style, or an array of styles. + * @return {import("./style/Style.js").StyleFunction} A style function. + */ +function createStyleFunction(obj) { + if (typeof obj === 'function') { + return obj; + } + /** + * @type {Array} + */ + let styles; + if (Array.isArray(obj)) { + styles = obj; + } else { + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_3__.assert)( + typeof (/** @type {?} */ (obj).getZIndex) === 'function', + 'Expected an `ol/style/Style` or an array of `ol/style/Style.js`', + ); + const style = /** @type {import("./style/Style.js").default} */ (obj); + styles = [style]; + } + return function () { + return styles; + }; +} +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Feature); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/Image.js": +/*!******************************************!*\ + !*** ./node_modules/@biigle/ol/Image.js ***! + \******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "decode": () => (/* binding */ decode), +/* harmony export */ "decodeFallback": () => (/* binding */ decodeFallback), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "listenImage": () => (/* binding */ listenImage), +/* harmony export */ "load": () => (/* binding */ load) +/* harmony export */ }); +/* harmony import */ var _events_Target_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events/Target.js */ "./node_modules/@biigle/ol/events/Target.js"); +/* harmony import */ var _events_EventType_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./events/EventType.js */ "./node_modules/@biigle/ol/events/EventType.js"); +/* harmony import */ var _ImageState_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./ImageState.js */ "./node_modules/@biigle/ol/ImageState.js"); +/* harmony import */ var _has_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./has.js */ "./node_modules/@biigle/ol/has.js"); +/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./events.js */ "./node_modules/@biigle/ol/events.js"); +/* harmony import */ var _functions_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./functions.js */ "./node_modules/@biigle/ol/functions.js"); +/** + * @module ol/Image + */ + + + + + + + +/** + * A function that takes an {@link module:ol/Image~ImageWrapper} for the image and a + * `{string}` for the src as arguments. It is supposed to make it so the + * underlying image {@link module:ol/Image~ImageWrapper#getImage} is assigned the + * content specified by the src. If not specified, the default is + * + * function(image, src) { + * image.getImage().src = src; + * } + * + * Providing a custom `imageLoadFunction` can be useful to load images with + * post requests or - in general - through XHR requests, where the src of the + * image element would be set to a data URI when the content is loaded. + * + * @typedef {function(import("./Image.js").default, string): void} LoadFunction + * @api + */ + +/** + * @typedef {Object} ImageObject + * @property {import("./extent.js").Extent} [extent] Extent, if different from the requested one. + * @property {import("./resolution.js").ResolutionLike} [resolution] Resolution, if different from the requested one. + * When x and y resolution are different, use the array type (`[xResolution, yResolution]`). + * @property {number} [pixelRatio] Pixel ratio, if different from the requested one. + * @property {import('./DataTile.js').ImageLike} image Image. + */ + +/** + * Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments. + * For images that cover any extent and resolution (static images), the loader function should not accept + * any arguments. The function returns an {@link import("./DataTile.js").ImageLike image}, an + * {@link import("./Image.js").ImageObject image object}, or a promise for the same. + * For loaders that generate images, the promise should not resolve until the image is loaded. + * If the returned image does not match the extent, resolution or pixel ratio passed to the loader, + * it has to return an {@link import("./Image.js").ImageObject image object} with the `image` and the + * correct `extent`, `resolution` and `pixelRatio`. + * + * @typedef {function(import("./extent.js").Extent, number, number, (function(HTMLImageElement, string): void)=): import("./DataTile.js").ImageLike|ImageObject|Promise} Loader + * @api + */ + +/** + * Loader function used for image sources. Receives extent, resolution and pixel ratio as arguments. + * The function returns a promise for an {@link import("./Image.js").ImageObject image object}. + * + * @typedef {function(import("./extent.js").Extent, number, number, (function(HTMLImageElement, string): void)=): import("./DataTile.js").ImageLike|ImageObject|Promise} ImageObjectPromiseLoader + */ + +class ImageWrapper extends _events_Target_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {import("./extent.js").Extent} extent Extent. + * @param {number|Array|undefined} resolution Resolution. If provided as array, x and y + * resolution will be assumed. + * @param {number} pixelRatio Pixel ratio. + * @param {import("./ImageState.js").default|import("./Image.js").Loader} stateOrLoader State. + */ + constructor(extent, resolution, pixelRatio, stateOrLoader) { + super(); + + /** + * @protected + * @type {import("./extent.js").Extent} + */ + this.extent = extent; + + /** + * @private + * @type {number} + */ + this.pixelRatio_ = pixelRatio; + + /** + * @protected + * @type {number|Array|undefined} + */ + this.resolution = resolution; + + /** + * @protected + * @type {import("./ImageState.js").default} + */ + this.state = + typeof stateOrLoader === 'function' ? _ImageState_js__WEBPACK_IMPORTED_MODULE_1__["default"].IDLE : stateOrLoader; + + /** + * @private + * @type {import('./DataTile.js').ImageLike|null} + */ + this.image_ = null; + + /** + * @protected + * @type {import("./Image.js").Loader} + */ + this.loader = typeof stateOrLoader === 'function' ? stateOrLoader : null; + } + + /** + * @protected + */ + changed() { + this.dispatchEvent(_events_EventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].CHANGE); + } + + /** + * @return {import("./extent.js").Extent} Extent. + */ + getExtent() { + return this.extent; + } + + /** + * @return {import('./DataTile.js').ImageLike} Image. + */ + getImage() { + return this.image_; + } + + /** + * @return {number} PixelRatio. + */ + getPixelRatio() { + return this.pixelRatio_; + } + + /** + * @return {number|Array} Resolution. + */ + getResolution() { + return /** @type {number} */ (this.resolution); + } + + /** + * @return {import("./ImageState.js").default} State. + */ + getState() { + return this.state; + } + + /** + * Load not yet loaded URI. + */ + load() { + if (this.state == _ImageState_js__WEBPACK_IMPORTED_MODULE_1__["default"].IDLE) { + if (this.loader) { + this.state = _ImageState_js__WEBPACK_IMPORTED_MODULE_1__["default"].LOADING; + this.changed(); + const resolution = this.getResolution(); + const requestResolution = Array.isArray(resolution) + ? resolution[0] + : resolution; + (0,_functions_js__WEBPACK_IMPORTED_MODULE_3__.toPromise)(() => + this.loader( + this.getExtent(), + requestResolution, + this.getPixelRatio(), + ), + ) + .then((image) => { + if ('image' in image) { + this.image_ = image.image; + } + if ('extent' in image) { + this.extent = image.extent; + } + if ('resolution' in image) { + this.resolution = image.resolution; + } + if ('pixelRatio' in image) { + this.pixelRatio_ = image.pixelRatio; + } + if ( + image instanceof HTMLImageElement || + image instanceof ImageBitmap || + image instanceof HTMLCanvasElement || + image instanceof HTMLVideoElement + ) { + this.image_ = image; + } + this.state = _ImageState_js__WEBPACK_IMPORTED_MODULE_1__["default"].LOADED; + }) + .catch((error) => { + this.state = _ImageState_js__WEBPACK_IMPORTED_MODULE_1__["default"].ERROR; + console.error(error); // eslint-disable-line no-console + }) + .finally(() => this.changed()); + } + } + } + + /** + * @param {import('./DataTile.js').ImageLike} image The image. + */ + setImage(image) { + this.image_ = image; + } + + /** + * @param {number|Array} resolution Resolution. + */ + setResolution(resolution) { + this.resolution = resolution; + } +} + +/** + * @param {import('./DataTile.js').ImageLike} image Image element. + * @param {function():any} loadHandler Load callback function. + * @param {function():any} errorHandler Error callback function. + * @return {function():void} Callback to stop listening. + */ +function listenImage(image, loadHandler, errorHandler) { + const img = /** @type {HTMLImageElement} */ (image); + let listening = true; + let decoding = false; + let loaded = false; + + const listenerKeys = [ + (0,_events_js__WEBPACK_IMPORTED_MODULE_4__.listenOnce)(img, _events_EventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].LOAD, function () { + loaded = true; + if (!decoding) { + loadHandler(); + } + }), + ]; + + if (img.src && _has_js__WEBPACK_IMPORTED_MODULE_5__.IMAGE_DECODE) { + decoding = true; + img + .decode() + .then(function () { + if (listening) { + loadHandler(); + } + }) + .catch(function (error) { + if (listening) { + if (loaded) { + loadHandler(); + } else { + errorHandler(); + } + } + }); + } else { + listenerKeys.push((0,_events_js__WEBPACK_IMPORTED_MODULE_4__.listenOnce)(img, _events_EventType_js__WEBPACK_IMPORTED_MODULE_2__["default"].ERROR, errorHandler)); + } + + return function unlisten() { + listening = false; + listenerKeys.forEach(_events_js__WEBPACK_IMPORTED_MODULE_4__.unlistenByKey); + }; +} + +/** + * Loads an image. + * @param {HTMLImageElement} image Image, not yet loaded. + * @param {string} [src] `src` attribute of the image. Optional, not required if already present. + * @return {Promise} Promise resolving to an `HTMLImageElement`. + * @api + */ +function load(image, src) { + return new Promise((resolve, reject) => { + function handleLoad() { + unlisten(); + resolve(image); + } + function handleError() { + unlisten(); + reject(new Error('Image load error')); + } + function unlisten() { + image.removeEventListener('load', handleLoad); + image.removeEventListener('error', handleError); + } + image.addEventListener('load', handleLoad); + image.addEventListener('error', handleError); + if (src) { + image.src = src; + } + }); +} + +/** + * @param {HTMLImageElement} image Image, not yet loaded. + * @param {string} [src] `src` attribute of the image. Optional, not required if already present. + * @return {Promise} Promise resolving to an `HTMLImageElement`. + */ +function decodeFallback(image, src) { + if (src) { + image.src = src; + } + return image.src && _has_js__WEBPACK_IMPORTED_MODULE_5__.IMAGE_DECODE + ? new Promise((resolve, reject) => + image + .decode() + .then(() => resolve(image)) + .catch((e) => + image.complete && image.width ? resolve(image) : reject(e), + ), + ) + : load(image); +} + +/** + * Loads an image and decodes it to an `ImageBitmap` if `createImageBitmap()` is supported. Returns + * the loaded image otherwise. + * @param {HTMLImageElement} image Image, not yet loaded. + * @param {string} [src] `src` attribute of the image. Optional, not required if already present. + * @return {Promise} Promise resolving to an `ImageBitmap` or an + * `HTMLImageElement` if `createImageBitmap()` is not supported. + * @api + */ +function decode(image, src) { + if (src) { + image.src = src; + } + return image.src && _has_js__WEBPACK_IMPORTED_MODULE_5__.IMAGE_DECODE && _has_js__WEBPACK_IMPORTED_MODULE_5__.CREATE_IMAGE_BITMAP + ? image + .decode() + .then(() => createImageBitmap(image)) + .catch((e) => { + if (image.complete && image.width) { + return image; + } + throw e; + }) + : decodeFallback(image); +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (ImageWrapper); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/ImageState.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/ImageState.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/ImageState + */ + +/** + * @enum {number} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + IDLE: 0, + LOADING: 1, + LOADED: 2, + ERROR: 3, + EMPTY: 4, +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/MapBrowserEventType.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/MapBrowserEventType.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _events_EventType_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events/EventType.js */ "./node_modules/@biigle/ol/events/EventType.js"); +/** + * @module ol/MapBrowserEventType + */ + + +/** + * Constants for event names. + * @enum {string} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + /** + * A true single click with no dragging and no double click. Note that this + * event is delayed by 250 ms to ensure that it is not a double click. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#singleclick + * @api + */ + SINGLECLICK: 'singleclick', + + /** + * A click with no dragging. A double click will fire two of this. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#click + * @api + */ + CLICK: _events_EventType_js__WEBPACK_IMPORTED_MODULE_0__["default"].CLICK, + + /** + * A true double click, with no dragging. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#dblclick + * @api + */ + DBLCLICK: _events_EventType_js__WEBPACK_IMPORTED_MODULE_0__["default"].DBLCLICK, + + /** + * Triggered when a pointer is dragged. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointerdrag + * @api + */ + POINTERDRAG: 'pointerdrag', + + /** + * Triggered when a pointer is moved. Note that on touch devices this is + * triggered when the map is panned, so is not the same as mousemove. + * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointermove + * @api + */ + POINTERMOVE: 'pointermove', + + POINTERDOWN: 'pointerdown', + POINTERUP: 'pointerup', + POINTEROVER: 'pointerover', + POINTEROUT: 'pointerout', + POINTERENTER: 'pointerenter', + POINTERLEAVE: 'pointerleave', + POINTERCANCEL: 'pointercancel', +}); + +/*** + * @typedef {'singleclick'|'click'|'dblclick'|'pointerdrag'|'pointermove'} Types + */ + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/Object.js": +/*!*******************************************!*\ + !*** ./node_modules/@biigle/ol/Object.js ***! + \*******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "ObjectEvent": () => (/* binding */ ObjectEvent), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _events_Event_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events/Event.js */ "./node_modules/@biigle/ol/events/Event.js"); +/* harmony import */ var _ObjectEventType_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ObjectEventType.js */ "./node_modules/@biigle/ol/ObjectEventType.js"); +/* harmony import */ var _Observable_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Observable.js */ "./node_modules/@biigle/ol/Observable.js"); +/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./util.js */ "./node_modules/@biigle/ol/util.js"); +/* harmony import */ var _obj_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./obj.js */ "./node_modules/@biigle/ol/obj.js"); +/** + * @module ol/Object + */ + + + + + + +/** + * @classdesc + * Events emitted by {@link module:ol/Object~BaseObject} instances are instances of this type. + */ +class ObjectEvent extends _events_Event_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {string} type The event type. + * @param {string} key The property name. + * @param {*} oldValue The old value for `key`. + */ + constructor(type, key, oldValue) { + super(type); + + /** + * The name of the property whose value is changing. + * @type {string} + * @api + */ + this.key = key; + + /** + * The old value. To get the new value use `e.target.get(e.key)` where + * `e` is the event object. + * @type {*} + * @api + */ + this.oldValue = oldValue; + } +} + +/*** + * @template Return + * @typedef {import("./Observable").OnSignature & + * import("./Observable").OnSignature & + * import("./Observable").CombinedOnSignature} ObjectOnSignature + */ + +/** + * @classdesc + * Abstract base class; normally only used for creating subclasses and not + * instantiated in apps. + * Most non-trivial classes inherit from this. + * + * This extends {@link module:ol/Observable~Observable} with observable + * properties, where each property is observable as well as the object as a + * whole. + * + * Classes that inherit from this have pre-defined properties, to which you can + * add your owns. The pre-defined properties are listed in this documentation as + * 'Observable Properties', and have their own accessors; for example, + * {@link module:ol/Map~Map} has a `target` property, accessed with + * `getTarget()` and changed with `setTarget()`. Not all properties are however + * settable. There are also general-purpose accessors `get()` and `set()`. For + * example, `get('target')` is equivalent to `getTarget()`. + * + * The `set` accessors trigger a change event, and you can monitor this by + * registering a listener. For example, {@link module:ol/View~View} has a + * `center` property, so `view.on('change:center', function(evt) {...});` would + * call the function whenever the value of the center property changes. Within + * the function, `evt.target` would be the view, so `evt.target.getCenter()` + * would return the new center. + * + * You can add your own observable properties with + * `object.set('prop', 'value')`, and retrieve that with `object.get('prop')`. + * You can listen for changes on that property value with + * `object.on('change:prop', listener)`. You can get a list of all + * properties with {@link module:ol/Object~BaseObject#getProperties}. + * + * Note that the observable properties are separate from standard JS properties. + * You can, for example, give your map object a title with + * `map.title='New title'` and with `map.set('title', 'Another title')`. The + * first will be a `hasOwnProperty`; the second will appear in + * `getProperties()`. Only the second is observable. + * + * Properties can be deleted by using the unset method. E.g. + * object.unset('foo'). + * + * @fires ObjectEvent + * @api + */ +class BaseObject extends _Observable_js__WEBPACK_IMPORTED_MODULE_1__["default"] { + /** + * @param {Object} [values] An object with key-value pairs. + */ + constructor(values) { + super(); + + /*** + * @type {ObjectOnSignature} + */ + this.on; + + /*** + * @type {ObjectOnSignature} + */ + this.once; + + /*** + * @type {ObjectOnSignature} + */ + this.un; + + // Call {@link module:ol/util.getUid} to ensure that the order of objects' ids is + // the same as the order in which they were created. This also helps to + // ensure that object properties are always added in the same order, which + // helps many JavaScript engines generate faster code. + (0,_util_js__WEBPACK_IMPORTED_MODULE_2__.getUid)(this); + + /** + * @private + * @type {Object|null} + */ + this.values_ = null; + + if (values !== undefined) { + this.setProperties(values); + } + } + + /** + * Gets a value. + * @param {string} key Key name. + * @return {*} Value. + * @api + */ + get(key) { + let value; + if (this.values_ && this.values_.hasOwnProperty(key)) { + value = this.values_[key]; + } + return value; + } + + /** + * Get a list of object property names. + * @return {Array} List of property names. + * @api + */ + getKeys() { + return (this.values_ && Object.keys(this.values_)) || []; + } + + /** + * Get an object of all property names and values. + * @return {Object} Object. + * @api + */ + getProperties() { + return (this.values_ && Object.assign({}, this.values_)) || {}; + } + + /** + * Get an object of all property names and values. + * @return {Object?} Object. + */ + getPropertiesInternal() { + return this.values_; + } + + /** + * @return {boolean} The object has properties. + */ + hasProperties() { + return !!this.values_; + } + + /** + * @param {string} key Key name. + * @param {*} oldValue Old value. + */ + notify(key, oldValue) { + let eventType; + eventType = `change:${key}`; + if (this.hasListener(eventType)) { + this.dispatchEvent(new ObjectEvent(eventType, key, oldValue)); + } + eventType = _ObjectEventType_js__WEBPACK_IMPORTED_MODULE_3__["default"].PROPERTYCHANGE; + if (this.hasListener(eventType)) { + this.dispatchEvent(new ObjectEvent(eventType, key, oldValue)); + } + } + + /** + * @param {string} key Key name. + * @param {import("./events.js").Listener} listener Listener. + */ + addChangeListener(key, listener) { + this.addEventListener(`change:${key}`, listener); + } + + /** + * @param {string} key Key name. + * @param {import("./events.js").Listener} listener Listener. + */ + removeChangeListener(key, listener) { + this.removeEventListener(`change:${key}`, listener); + } + + /** + * Sets a value. + * @param {string} key Key name. + * @param {*} value Value. + * @param {boolean} [silent] Update without triggering an event. + * @api + */ + set(key, value, silent) { + const values = this.values_ || (this.values_ = {}); + if (silent) { + values[key] = value; + } else { + const oldValue = values[key]; + values[key] = value; + if (oldValue !== value) { + this.notify(key, oldValue); + } + } + } + + /** + * Sets a collection of key-value pairs. Note that this changes any existing + * properties and adds new ones (it does not remove any existing properties). + * @param {Object} values Values. + * @param {boolean} [silent] Update without triggering an event. + * @api + */ + setProperties(values, silent) { + for (const key in values) { + this.set(key, values[key], silent); + } + } + + /** + * Apply any properties from another object without triggering events. + * @param {BaseObject} source The source object. + * @protected + */ + applyProperties(source) { + if (!source.values_) { + return; + } + Object.assign(this.values_ || (this.values_ = {}), source.values_); + } + + /** + * Unsets a property. + * @param {string} key Key name. + * @param {boolean} [silent] Unset without triggering an event. + * @api + */ + unset(key, silent) { + if (this.values_ && key in this.values_) { + const oldValue = this.values_[key]; + delete this.values_[key]; + if ((0,_obj_js__WEBPACK_IMPORTED_MODULE_4__.isEmpty)(this.values_)) { + this.values_ = null; + } + if (!silent) { + this.notify(key, oldValue); + } + } + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BaseObject); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/ObjectEventType.js": +/*!****************************************************!*\ + !*** ./node_modules/@biigle/ol/ObjectEventType.js ***! + \****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/ObjectEventType + */ + +/** + * @enum {string} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + /** + * Triggered when a property is changed. + * @event module:ol/Object.ObjectEvent#propertychange + * @api + */ + PROPERTYCHANGE: 'propertychange', +}); + +/** + * @typedef {'propertychange'} Types + */ + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/Observable.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/Observable.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "unByKey": () => (/* binding */ unByKey) +/* harmony export */ }); +/* harmony import */ var _events_Target_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./events/Target.js */ "./node_modules/@biigle/ol/events/Target.js"); +/* harmony import */ var _events_EventType_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./events/EventType.js */ "./node_modules/@biigle/ol/events/EventType.js"); +/* harmony import */ var _events_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./events.js */ "./node_modules/@biigle/ol/events.js"); +/** + * @module ol/Observable + */ + + + + +/*** + * @template {string} Type + * @template {Event|import("./events/Event.js").default} EventClass + * @template Return + * @typedef {(type: Type, listener: (event: EventClass) => ?) => Return} OnSignature + */ + +/*** + * @template {string} Type + * @template Return + * @typedef {(type: Type[], listener: (event: Event|import("./events/Event").default) => ?) => Return extends void ? void : Return[]} CombinedOnSignature + */ + +/** + * @typedef {'change'|'error'} EventTypes + */ + +/*** + * @template Return + * @typedef {OnSignature & CombinedOnSignature} ObservableOnSignature + */ + +/** + * @classdesc + * Abstract base class; normally only used for creating subclasses and not + * instantiated in apps. + * An event target providing convenient methods for listener registration + * and unregistration. A generic `change` event is always available through + * {@link module:ol/Observable~Observable#changed}. + * + * @fires import("./events/Event.js").default + * @api + */ +class Observable extends _events_Target_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor() { + super(); + + this.on = + /** @type {ObservableOnSignature} */ ( + this.onInternal + ); + + this.once = + /** @type {ObservableOnSignature} */ ( + this.onceInternal + ); + + this.un = /** @type {ObservableOnSignature} */ (this.unInternal); + + /** + * @private + * @type {number} + */ + this.revision_ = 0; + } + + /** + * Increases the revision counter and dispatches a 'change' event. + * @api + */ + changed() { + ++this.revision_; + this.dispatchEvent(_events_EventType_js__WEBPACK_IMPORTED_MODULE_1__["default"].CHANGE); + } + + /** + * Get the version number for this object. Each time the object is modified, + * its version number will be incremented. + * @return {number} Revision. + * @api + */ + getRevision() { + return this.revision_; + } + + /** + * @param {string|Array} type Type. + * @param {function((Event|import("./events/Event").default)): ?} listener Listener. + * @return {import("./events.js").EventsKey|Array} Event key. + * @protected + */ + onInternal(type, listener) { + if (Array.isArray(type)) { + const len = type.length; + const keys = new Array(len); + for (let i = 0; i < len; ++i) { + keys[i] = (0,_events_js__WEBPACK_IMPORTED_MODULE_2__.listen)(this, type[i], listener); + } + return keys; + } + return (0,_events_js__WEBPACK_IMPORTED_MODULE_2__.listen)(this, /** @type {string} */ (type), listener); + } + + /** + * @param {string|Array} type Type. + * @param {function((Event|import("./events/Event").default)): ?} listener Listener. + * @return {import("./events.js").EventsKey|Array} Event key. + * @protected + */ + onceInternal(type, listener) { + let key; + if (Array.isArray(type)) { + const len = type.length; + key = new Array(len); + for (let i = 0; i < len; ++i) { + key[i] = (0,_events_js__WEBPACK_IMPORTED_MODULE_2__.listenOnce)(this, type[i], listener); + } + } else { + key = (0,_events_js__WEBPACK_IMPORTED_MODULE_2__.listenOnce)(this, /** @type {string} */ (type), listener); + } + /** @type {Object} */ (listener).ol_key = key; + return key; + } + + /** + * Unlisten for a certain type of event. + * @param {string|Array} type Type. + * @param {function((Event|import("./events/Event").default)): ?} listener Listener. + * @protected + */ + unInternal(type, listener) { + const key = /** @type {Object} */ (listener).ol_key; + if (key) { + unByKey(key); + } else if (Array.isArray(type)) { + for (let i = 0, ii = type.length; i < ii; ++i) { + this.removeEventListener(type[i], listener); + } + } else { + this.removeEventListener(type, listener); + } + } +} + +/** + * Listen for a certain type of event. + * @function + * @param {string|Array} type The event type or array of event types. + * @param {function((Event|import("./events/Event").default)): ?} listener The listener function. + * @return {import("./events.js").EventsKey|Array} Unique key for the listener. If + * called with an array of event types as the first argument, the return + * will be an array of keys. + * @api + */ +Observable.prototype.on; + +/** + * Listen once for a certain type of event. + * @function + * @param {string|Array} type The event type or array of event types. + * @param {function((Event|import("./events/Event").default)): ?} listener The listener function. + * @return {import("./events.js").EventsKey|Array} Unique key for the listener. If + * called with an array of event types as the first argument, the return + * will be an array of keys. + * @api + */ +Observable.prototype.once; + +/** + * Unlisten for a certain type of event. + * @function + * @param {string|Array} type The event type or array of event types. + * @param {function((Event|import("./events/Event").default)): ?} listener The listener function. + * @api + */ +Observable.prototype.un; + +/** + * Removes an event listener using the key returned by `on()` or `once()`. + * @param {import("./events.js").EventsKey|Array} key The key returned by `on()` + * or `once()` (or an array of keys). + * @api + */ +function unByKey(key) { + if (Array.isArray(key)) { + for (let i = 0, ii = key.length; i < ii; ++i) { + (0,_events_js__WEBPACK_IMPORTED_MODULE_2__.unlistenByKey)(key[i]); + } + } else { + (0,_events_js__WEBPACK_IMPORTED_MODULE_2__.unlistenByKey)(/** @type {import("./events.js").EventsKey} */ (key)); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Observable); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/View.js": +/*!*****************************************!*\ + !*** ./node_modules/@biigle/ol/View.js ***! + \*****************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createCenterConstraint": () => (/* binding */ createCenterConstraint), +/* harmony export */ "createResolutionConstraint": () => (/* binding */ createResolutionConstraint), +/* harmony export */ "createRotationConstraint": () => (/* binding */ createRotationConstraint), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "isNoopAnimation": () => (/* binding */ isNoopAnimation) +/* harmony export */ }); +/* harmony import */ var _Object_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Object.js */ "./node_modules/@biigle/ol/Object.js"); +/* harmony import */ var _ViewHint_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./ViewHint.js */ "./node_modules/@biigle/ol/ViewHint.js"); +/* harmony import */ var _ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ViewProperty.js */ "./node_modules/@biigle/ol/ViewProperty.js"); +/* harmony import */ var _tilegrid_common_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./tilegrid/common.js */ "./node_modules/@biigle/ol/tilegrid/common.js"); +/* harmony import */ var _proj_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./proj.js */ "./node_modules/@biigle/ol/proj.js"); +/* harmony import */ var _functions_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./functions.js */ "./node_modules/@biigle/ol/functions.js"); +/* harmony import */ var _coordinate_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./coordinate.js */ "./node_modules/@biigle/ol/coordinate.js"); +/* harmony import */ var _asserts_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./asserts.js */ "./node_modules/@biigle/ol/asserts.js"); +/* harmony import */ var _centerconstraint_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./centerconstraint.js */ "./node_modules/@biigle/ol/centerconstraint.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./math.js */ "./node_modules/@biigle/ol/math.js"); +/* harmony import */ var _resolutionconstraint_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./resolutionconstraint.js */ "./node_modules/@biigle/ol/resolutionconstraint.js"); +/* harmony import */ var _rotationconstraint_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./rotationconstraint.js */ "./node_modules/@biigle/ol/rotationconstraint.js"); +/* harmony import */ var _easing_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./easing.js */ "./node_modules/@biigle/ol/easing.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _geom_Polygon_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./geom/Polygon.js */ "./node_modules/@biigle/ol/geom/Polygon.js"); +/** + * @module ol/View + */ + + + + + + + + + + + + + + + + + +/** + * An animation configuration + * + * @typedef {Object} Animation + * @property {import("./coordinate.js").Coordinate} [sourceCenter] Source center. + * @property {import("./coordinate.js").Coordinate} [targetCenter] Target center. + * @property {number} [sourceResolution] Source resolution. + * @property {number} [targetResolution] Target resolution. + * @property {number} [sourceRotation] Source rotation. + * @property {number} [targetRotation] Target rotation. + * @property {import("./coordinate.js").Coordinate} [anchor] Anchor. + * @property {number} start Start. + * @property {number} duration Duration. + * @property {boolean} complete Complete. + * @property {function(number):number} easing Easing. + * @property {function(boolean):void} callback Callback. + */ + +/** + * @typedef {Object} Constraints + * @property {import("./centerconstraint.js").Type} center Center. + * @property {import("./resolutionconstraint.js").Type} resolution Resolution. + * @property {import("./rotationconstraint.js").Type} rotation Rotation. + */ + +/** + * @typedef {Object} FitOptions + * @property {import("./size.js").Size} [size] The size in pixels of the box to + * fit the extent into. Defaults to the size of the map the view is associated with. + * If no map or multiple maps are connected to the view, provide the desired box size + * (e.g. `map.getSize()`). + * @property {!Array} [padding=[0, 0, 0, 0]] Padding (in pixels) to be + * cleared inside the view. Values in the array are top, right, bottom and left + * padding. + * @property {boolean} [nearest=false] If the view `constrainResolution` option is `true`, + * get the nearest extent instead of the closest that actually fits the view. + * @property {number} [minResolution=0] Minimum resolution that we zoom to. + * @property {number} [maxZoom] Maximum zoom level that we zoom to. If + * `minResolution` is given, this property is ignored. + * @property {number} [duration] The duration of the animation in milliseconds. + * By default, there is no animation to the target extent. + * @property {function(number):number} [easing] The easing function used during + * the animation (defaults to {@link module:ol/easing.inAndOut}). + * The function will be called for each frame with a number representing a + * fraction of the animation's duration. The function should return a number + * between 0 and 1 representing the progress toward the destination state. + * @property {function(boolean):void} [callback] Function called when the view is in + * its final position. The callback will be called with `true` if the animation + * series completed on its own or `false` if it was cancelled. + */ + +/** + * @typedef {Object} ViewOptions + * @property {import("./coordinate.js").Coordinate} [center] The initial center for + * the view. If a user projection is not set, the coordinate system for the center is + * specified with the `projection` option. Layer sources will not be fetched if this + * is not set, but the center can be set later with {@link #setCenter}. + * @property {boolean|number} [constrainRotation=true] Rotation constraint. + * `false` means no constraint. `true` means no constraint, but snap to zero + * near zero. A number constrains the rotation to that number of values. For + * example, `4` will constrain the rotation to 0, 90, 180, and 270 degrees. + * @property {boolean} [enableRotation=true] Enable rotation. + * If `false`, a rotation constraint that always sets the rotation to zero is + * used. The `constrainRotation` option has no effect if `enableRotation` is + * `false`. + * @property {import("./extent.js").Extent} [extent] The extent that constrains the + * view, in other words, nothing outside of this extent can be visible on the map. + * @property {boolean} [constrainOnlyCenter=false] If true, the extent + * constraint will only apply to the view center and not the whole extent. + * @property {boolean} [smoothExtentConstraint=true] If true, the extent + * constraint will be applied smoothly, i.e. allow the view to go slightly outside + * of the given `extent`. + * @property {number} [maxResolution] The maximum resolution used to determine + * the resolution constraint. It is used together with `minResolution` (or + * `maxZoom`) and `zoomFactor`. If unspecified it is calculated in such a way + * that the projection's validity extent fits in a 256x256 px tile. If the + * projection is Spherical Mercator (the default) then `maxResolution` defaults + * to `40075016.68557849 / 256 = 156543.03392804097`. + * @property {number} [minResolution] The minimum resolution used to determine + * the resolution constraint. It is used together with `maxResolution` (or + * `minZoom`) and `zoomFactor`. If unspecified it is calculated assuming 29 + * zoom levels (with a factor of 2). If the projection is Spherical Mercator + * (the default) then `minResolution` defaults to + * `40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253`. + * @property {number} [maxZoom=28] The maximum zoom level used to determine the + * resolution constraint. It is used together with `minZoom` (or + * `maxResolution`) and `zoomFactor`. Note that if `minResolution` is also + * provided, it is given precedence over `maxZoom`. + * @property {number} [minZoom=0] The minimum zoom level used to determine the + * resolution constraint. It is used together with `maxZoom` (or + * `minResolution`) and `zoomFactor`. Note that if `maxResolution` is also + * provided, it is given precedence over `minZoom`. + * @property {boolean} [multiWorld=false] If `false` the view is constrained so + * only one world is visible, and you cannot pan off the edge. If `true` the map + * may show multiple worlds at low zoom levels. Only used if the `projection` is + * global. Note that if `extent` is also provided it is given precedence. + * @property {boolean} [constrainResolution=false] If true, the view will always + * animate to the closest zoom level after an interaction; false means + * intermediary zoom levels are allowed. + * @property {boolean} [smoothResolutionConstraint=true] If true, the resolution + * min/max values will be applied smoothly, i. e. allow the view to exceed slightly + * the given resolution or zoom bounds. + * @property {boolean} [showFullExtent=false] Allow the view to be zoomed out to + * show the full configured extent. By default, when a view is configured with an + * extent, users will not be able to zoom out so the viewport exceeds the extent in + * either dimension. This means the full extent may not be visible if the viewport + * is taller or wider than the aspect ratio of the configured extent. If + * showFullExtent is true, the user will be able to zoom out so that the viewport + * exceeds the height or width of the configured extent, but not both, allowing the + * full extent to be shown. + * @property {import("./proj.js").ProjectionLike} [projection='EPSG:3857'] The + * projection. The default is Spherical Mercator. + * @property {number} [resolution] The initial resolution for the view. The + * units are `projection` units per pixel (e.g. meters per pixel). An + * alternative to setting this is to set `zoom`. Layer sources will not be + * fetched if neither this nor `zoom` are defined, but they can be set later + * with {@link #setZoom} or {@link #setResolution}. + * @property {Array} [resolutions] Resolutions that determine the + * zoom levels if specified. The index in the array corresponds to the zoom level, + * therefore the resolution values have to be in descending order. It also constrains + * the resolution by the minimum and maximum value. If set the `maxResolution`, + * `minResolution`, `minZoom`, `maxZoom`, and `zoomFactor` options are ignored. + * @property {number} [rotation=0] The initial rotation for the view in radians + * (positive rotation clockwise, 0 means North). + * @property {number} [zoom] Only used if `resolution` is not defined. Zoom + * level used to calculate the initial resolution for the view. + * @property {number} [zoomFactor=2] The zoom factor used to compute the + * corresponding resolution. + * @property {!Array} [padding=[0, 0, 0, 0]] Padding (in css pixels). + * If the map viewport is partially covered with other content (overlays) along + * its edges, this setting allows to shift the center of the viewport away from + * that content. The order of the values is top, right, bottom, left. + */ + +/** + * @typedef {Object} AnimationOptions + * @property {import("./coordinate.js").Coordinate} [center] The center of the view at the end of + * the animation. + * @property {number} [zoom] The zoom level of the view at the end of the + * animation. This takes precedence over `resolution`. + * @property {number} [resolution] The resolution of the view at the end + * of the animation. If `zoom` is also provided, this option will be ignored. + * @property {number} [rotation] The rotation of the view at the end of + * the animation. + * @property {import("./coordinate.js").Coordinate} [anchor] Optional anchor to remain fixed + * during a rotation or resolution animation. + * @property {number} [duration=1000] The duration of the animation in milliseconds. + * @property {function(number):number} [easing] The easing function used + * during the animation (defaults to {@link module:ol/easing.inAndOut}). + * The function will be called for each frame with a number representing a + * fraction of the animation's duration. The function should return a number + * between 0 and 1 representing the progress toward the destination state. + */ + +/** + * @typedef {Object} State + * @property {import("./coordinate.js").Coordinate} center Center (in view projection coordinates). + * @property {import("./proj/Projection.js").default} projection Projection. + * @property {number} resolution Resolution. + * @property {import("./coordinate.js").Coordinate} [nextCenter] The next center during an animation series. + * @property {number} [nextResolution] The next resolution during an animation series. + * @property {number} [nextRotation] The next rotation during an animation series. + * @property {number} rotation Rotation. + * @property {number} zoom Zoom. + */ + +/** + * Like {@link import("./Map.js").FrameState}, but just `viewState` and `extent`. + * @typedef {Object} ViewStateLayerStateExtent + * @property {State} viewState View state. + * @property {import("./extent.js").Extent} extent Extent (in user projection coordinates). + * @property {Array} [layerStatesArray] Layer states. + */ + +/** + * Default min zoom level for the map view. + * @type {number} + */ +const DEFAULT_MIN_ZOOM = 0; + +/** + * @typedef {import("./ObjectEventType").Types|'change:center'|'change:resolution'|'change:rotation'} ViewObjectEventTypes + */ + +/*** + * @template Return + * @typedef {import("./Observable").OnSignature & + * import("./Observable").OnSignature & + * import("./Observable").CombinedOnSignature} ViewOnSignature + */ + +/** + * @classdesc + * A View object represents a simple 2D view of the map. + * + * This is the object to act upon to change the center, resolution, + * and rotation of the map. + * + * A View has a `projection`. The projection determines the + * coordinate system of the center, and its units determine the units of the + * resolution (projection units per pixel). The default projection is + * Web Mercator (EPSG:3857). + * + * ### The view states + * + * A View is determined by three states: `center`, `resolution`, + * and `rotation`. Each state has a corresponding getter and setter, e.g. + * `getCenter` and `setCenter` for the `center` state. + * + * The `zoom` state is actually not saved on the view: all computations + * internally use the `resolution` state. Still, the `setZoom` and `getZoom` + * methods are available, as well as `getResolutionForZoom` and + * `getZoomForResolution` to switch from one system to the other. + * + * ### The constraints + * + * `setCenter`, `setResolution` and `setRotation` can be used to change the + * states of the view, but any constraint defined in the constructor will + * be applied along the way. + * + * A View object can have a *resolution constraint*, a *rotation constraint* + * and a *center constraint*. + * + * The *resolution constraint* typically restricts min/max values and + * snaps to specific resolutions. It is determined by the following + * options: `resolutions`, `maxResolution`, `maxZoom` and `zoomFactor`. + * If `resolutions` is set, the other three options are ignored. See + * documentation for each option for more information. By default, the view + * only has a min/max restriction and allow intermediary zoom levels when + * pinch-zooming for example. + * + * The *rotation constraint* snaps to specific angles. It is determined + * by the following options: `enableRotation` and `constrainRotation`. + * By default rotation is allowed and its value is snapped to zero when approaching the + * horizontal. + * + * The *center constraint* is determined by the `extent` option. By + * default the view center is not constrained at all. + * + * ### Changing the view state + * + * It is important to note that `setZoom`, `setResolution`, `setCenter` and + * `setRotation` are subject to the above mentioned constraints. As such, it + * may sometimes not be possible to know in advance the resulting state of the + * View. For example, calling `setResolution(10)` does not guarantee that + * `getResolution()` will return `10`. + * + * A consequence of this is that, when applying a delta on the view state, one + * should use `adjustCenter`, `adjustRotation`, `adjustZoom` and `adjustResolution` + * rather than the corresponding setters. This will let view do its internal + * computations. Besides, the `adjust*` methods also take an `anchor` + * argument which allows specifying an origin for the transformation. + * + * ### Interacting with the view + * + * View constraints are usually only applied when the view is *at rest*, meaning that + * no interaction or animation is ongoing. As such, if the user puts the view in a + * state that is not equivalent to a constrained one (e.g. rotating the view when + * the snap angle is 0), an animation will be triggered at the interaction end to + * put back the view to a stable state; + * + * @api + */ +class View extends _Object_js__WEBPACK_IMPORTED_MODULE_1__["default"] { + /** + * @param {ViewOptions} [options] View options. + */ + constructor(options) { + super(); + + /*** + * @type {ViewOnSignature} + */ + this.on; + + /*** + * @type {ViewOnSignature} + */ + this.once; + + /*** + * @type {ViewOnSignature} + */ + this.un; + + options = Object.assign({}, options); + + /** + * @private + * @type {Array} + */ + this.hints_ = [0, 0]; + + /** + * @private + * @type {Array>} + */ + this.animations_ = []; + + /** + * @private + * @type {number|undefined} + */ + this.updateAnimationKey_; + + /** + * @private + * @const + * @type {import("./proj/Projection.js").default} + */ + this.projection_ = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.createProjection)(options.projection, 'EPSG:3857'); + + /** + * @private + * @type {import("./size.js").Size} + */ + this.viewportSize_ = [100, 100]; + + /** + * @private + * @type {import("./coordinate.js").Coordinate|undefined} + */ + this.targetCenter_ = null; + + /** + * @private + * @type {number|undefined} + */ + this.targetResolution_; + + /** + * @private + * @type {number|undefined} + */ + this.targetRotation_; + + /** + * @private + * @type {import("./coordinate.js").Coordinate} + */ + this.nextCenter_ = null; + + /** + * @private + * @type {number} + */ + this.nextResolution_; + + /** + * @private + * @type {number} + */ + this.nextRotation_; + + /** + * @private + * @type {import("./coordinate.js").Coordinate|undefined} + */ + this.cancelAnchor_ = undefined; + + if (options.projection) { + (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.disableCoordinateWarning)(); + } + if (options.center) { + options.center = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)(options.center, this.projection_); + } + if (options.extent) { + options.extent = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserExtent)(options.extent, this.projection_); + } + + this.applyOptions_(options); + } + + /** + * Set up the view with the given options. + * @param {ViewOptions} options View options. + */ + applyOptions_(options) { + const properties = Object.assign({}, options); + for (const key in _ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"]) { + delete properties[key]; + } + this.setProperties(properties, true); + + const resolutionConstraintInfo = createResolutionConstraint(options); + + /** + * @private + * @type {number} + */ + this.maxResolution_ = resolutionConstraintInfo.maxResolution; + + /** + * @private + * @type {number} + */ + this.minResolution_ = resolutionConstraintInfo.minResolution; + + /** + * @private + * @type {number} + */ + this.zoomFactor_ = resolutionConstraintInfo.zoomFactor; + + /** + * @private + * @type {Array|undefined} + */ + this.resolutions_ = options.resolutions; + + /** + * @type {Array|undefined} + * @private + */ + this.padding_ = options.padding; + + /** + * @private + * @type {number} + */ + this.minZoom_ = resolutionConstraintInfo.minZoom; + + const centerConstraint = createCenterConstraint(options); + const resolutionConstraint = resolutionConstraintInfo.constraint; + const rotationConstraint = createRotationConstraint(options); + + /** + * @private + * @type {Constraints} + */ + this.constraints_ = { + center: centerConstraint, + resolution: resolutionConstraint, + rotation: rotationConstraint, + }; + + this.setRotation(options.rotation !== undefined ? options.rotation : 0); + this.setCenterInternal( + options.center !== undefined ? options.center : null, + ); + if (options.resolution !== undefined) { + this.setResolution(options.resolution); + } else if (options.zoom !== undefined) { + this.setZoom(options.zoom); + } + } + + /** + * Padding (in css pixels). + * If the map viewport is partially covered with other content (overlays) along + * its edges, this setting allows to shift the center of the viewport away from that + * content. The order of the values in the array is top, right, bottom, left. + * The default is no padding, which is equivalent to `[0, 0, 0, 0]`. + * @type {Array|undefined} + * @api + */ + get padding() { + return this.padding_; + } + set padding(padding) { + let oldPadding = this.padding_; + this.padding_ = padding; + const center = this.getCenterInternal(); + if (center) { + const newPadding = padding || [0, 0, 0, 0]; + oldPadding = oldPadding || [0, 0, 0, 0]; + const resolution = this.getResolution(); + const offsetX = + (resolution / 2) * + (newPadding[3] - oldPadding[3] + oldPadding[1] - newPadding[1]); + const offsetY = + (resolution / 2) * + (newPadding[0] - oldPadding[0] + oldPadding[2] - newPadding[2]); + this.setCenterInternal([center[0] + offsetX, center[1] - offsetY]); + } + } + + /** + * Get an updated version of the view options used to construct the view. The + * current resolution (or zoom), center, and rotation are applied to any stored + * options. The provided options can be used to apply new min/max zoom or + * resolution limits. + * @param {ViewOptions} newOptions New options to be applied. + * @return {ViewOptions} New options updated with the current view state. + */ + getUpdatedOptions_(newOptions) { + const options = this.getProperties(); + + // preserve resolution (or zoom) + if (options.resolution !== undefined) { + options.resolution = this.getResolution(); + } else { + options.zoom = this.getZoom(); + } + + // preserve center + options.center = this.getCenterInternal(); + + // preserve rotation + options.rotation = this.getRotation(); + + return Object.assign({}, options, newOptions); + } + + /** + * Animate the view. The view's center, zoom (or resolution), and rotation + * can be animated for smooth transitions between view states. For example, + * to animate the view to a new zoom level: + * + * view.animate({zoom: view.getZoom() + 1}); + * + * By default, the animation lasts one second and uses in-and-out easing. You + * can customize this behavior by including `duration` (in milliseconds) and + * `easing` options (see {@link module:ol/easing}). + * + * To chain together multiple animations, call the method with multiple + * animation objects. For example, to first zoom and then pan: + * + * view.animate({zoom: 10}, {center: [0, 0]}); + * + * If you provide a function as the last argument to the animate method, it + * will get called at the end of an animation series. The callback will be + * called with `true` if the animation series completed on its own or `false` + * if it was cancelled. + * + * Animations are cancelled by user interactions (e.g. dragging the map) or by + * calling `view.setCenter()`, `view.setResolution()`, or `view.setRotation()` + * (or another method that calls one of these). + * + * @param {...(AnimationOptions|function(boolean): void)} var_args Animation + * options. Multiple animations can be run in series by passing multiple + * options objects. To run multiple animations in parallel, call the method + * multiple times. An optional callback can be provided as a final + * argument. The callback will be called with a boolean indicating whether + * the animation completed without being cancelled. + * @api + */ + animate(var_args) { + if (this.isDef() && !this.getAnimating()) { + this.resolveConstraints(0); + } + const args = new Array(arguments.length); + for (let i = 0; i < args.length; ++i) { + let options = arguments[i]; + if (options.center) { + options = Object.assign({}, options); + options.center = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)( + options.center, + this.getProjection(), + ); + } + if (options.anchor) { + options = Object.assign({}, options); + options.anchor = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)( + options.anchor, + this.getProjection(), + ); + } + args[i] = options; + } + this.animateInternal.apply(this, args); + } + + /** + * @param {...(AnimationOptions|function(boolean): void)} var_args Animation options. + */ + animateInternal(var_args) { + let animationCount = arguments.length; + let callback; + if ( + animationCount > 1 && + typeof arguments[animationCount - 1] === 'function' + ) { + callback = arguments[animationCount - 1]; + --animationCount; + } + + let i = 0; + for (; i < animationCount && !this.isDef(); ++i) { + // if view properties are not yet set, shortcut to the final state + const state = arguments[i]; + if (state.center) { + this.setCenterInternal(state.center); + } + if (state.zoom !== undefined) { + this.setZoom(state.zoom); + } else if (state.resolution) { + this.setResolution(state.resolution); + } + if (state.rotation !== undefined) { + this.setRotation(state.rotation); + } + } + if (i === animationCount) { + if (callback) { + animationCallback(callback, true); + } + return; + } + + let start = Date.now(); + let center = this.targetCenter_.slice(); + let resolution = this.targetResolution_; + let rotation = this.targetRotation_; + const series = []; + for (; i < animationCount; ++i) { + const options = /** @type {AnimationOptions} */ (arguments[i]); + + const animation = { + start: start, + complete: false, + anchor: options.anchor, + duration: options.duration !== undefined ? options.duration : 1000, + easing: options.easing || _easing_js__WEBPACK_IMPORTED_MODULE_3__.inAndOut, + callback: callback, + }; + + if (options.center) { + animation.sourceCenter = center; + animation.targetCenter = options.center.slice(); + center = animation.targetCenter; + } + + if (options.zoom !== undefined) { + animation.sourceResolution = resolution; + animation.targetResolution = this.getResolutionForZoom(options.zoom); + resolution = animation.targetResolution; + } else if (options.resolution) { + animation.sourceResolution = resolution; + animation.targetResolution = options.resolution; + resolution = animation.targetResolution; + } + + if (options.rotation !== undefined) { + animation.sourceRotation = rotation; + const delta = + (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.modulo)(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI; + animation.targetRotation = rotation + delta; + rotation = animation.targetRotation; + } + + // check if animation is a no-op + if (isNoopAnimation(animation)) { + animation.complete = true; + // we still push it onto the series for callback handling + } else { + start += animation.duration; + } + series.push(animation); + } + this.animations_.push(series); + this.setHint(_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].ANIMATING, 1); + this.updateAnimations_(); + } + + /** + * Determine if the view is being animated. + * @return {boolean} The view is being animated. + * @api + */ + getAnimating() { + return this.hints_[_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].ANIMATING] > 0; + } + + /** + * Determine if the user is interacting with the view, such as panning or zooming. + * @return {boolean} The view is being interacted with. + * @api + */ + getInteracting() { + return this.hints_[_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].INTERACTING] > 0; + } + + /** + * Cancel any ongoing animations. + * @api + */ + cancelAnimations() { + this.setHint(_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].ANIMATING, -this.hints_[_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].ANIMATING]); + let anchor; + for (let i = 0, ii = this.animations_.length; i < ii; ++i) { + const series = this.animations_[i]; + if (series[0].callback) { + animationCallback(series[0].callback, false); + } + if (!anchor) { + for (let j = 0, jj = series.length; j < jj; ++j) { + const animation = series[j]; + if (!animation.complete) { + anchor = animation.anchor; + break; + } + } + } + } + this.animations_.length = 0; + this.cancelAnchor_ = anchor; + this.nextCenter_ = null; + this.nextResolution_ = NaN; + this.nextRotation_ = NaN; + } + + /** + * Update all animations. + */ + updateAnimations_() { + if (this.updateAnimationKey_ !== undefined) { + cancelAnimationFrame(this.updateAnimationKey_); + this.updateAnimationKey_ = undefined; + } + if (!this.getAnimating()) { + return; + } + const now = Date.now(); + let more = false; + for (let i = this.animations_.length - 1; i >= 0; --i) { + const series = this.animations_[i]; + let seriesComplete = true; + for (let j = 0, jj = series.length; j < jj; ++j) { + const animation = series[j]; + if (animation.complete) { + continue; + } + const elapsed = now - animation.start; + let fraction = + animation.duration > 0 ? elapsed / animation.duration : 1; + if (fraction >= 1) { + animation.complete = true; + fraction = 1; + } else { + seriesComplete = false; + } + const progress = animation.easing(fraction); + if (animation.sourceCenter) { + const x0 = animation.sourceCenter[0]; + const y0 = animation.sourceCenter[1]; + const x1 = animation.targetCenter[0]; + const y1 = animation.targetCenter[1]; + this.nextCenter_ = animation.targetCenter; + const x = x0 + progress * (x1 - x0); + const y = y0 + progress * (y1 - y0); + this.targetCenter_ = [x, y]; + } + if (animation.sourceResolution && animation.targetResolution) { + const resolution = + progress === 1 + ? animation.targetResolution + : animation.sourceResolution + + progress * + (animation.targetResolution - animation.sourceResolution); + if (animation.anchor) { + const size = this.getViewportSize_(this.getRotation()); + const constrainedResolution = this.constraints_.resolution( + resolution, + 0, + size, + true, + ); + this.targetCenter_ = this.calculateCenterZoom( + constrainedResolution, + animation.anchor, + ); + } + this.nextResolution_ = animation.targetResolution; + this.targetResolution_ = resolution; + this.applyTargetState_(true); + } + if ( + animation.sourceRotation !== undefined && + animation.targetRotation !== undefined + ) { + const rotation = + progress === 1 + ? (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.modulo)(animation.targetRotation + Math.PI, 2 * Math.PI) - + Math.PI + : animation.sourceRotation + + progress * + (animation.targetRotation - animation.sourceRotation); + if (animation.anchor) { + const constrainedRotation = this.constraints_.rotation( + rotation, + true, + ); + this.targetCenter_ = this.calculateCenterRotate( + constrainedRotation, + animation.anchor, + ); + } + this.nextRotation_ = animation.targetRotation; + this.targetRotation_ = rotation; + } + this.applyTargetState_(true); + more = true; + if (!animation.complete) { + break; + } + } + if (seriesComplete) { + this.animations_[i] = null; + this.setHint(_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].ANIMATING, -1); + this.nextCenter_ = null; + this.nextResolution_ = NaN; + this.nextRotation_ = NaN; + const callback = series[0].callback; + if (callback) { + animationCallback(callback, true); + } + } + } + // prune completed series + this.animations_ = this.animations_.filter(Boolean); + if (more && this.updateAnimationKey_ === undefined) { + this.updateAnimationKey_ = requestAnimationFrame( + this.updateAnimations_.bind(this), + ); + } + } + + /** + * @param {number} rotation Target rotation. + * @param {import("./coordinate.js").Coordinate} anchor Rotation anchor. + * @return {import("./coordinate.js").Coordinate|undefined} Center for rotation and anchor. + */ + calculateCenterRotate(rotation, anchor) { + let center; + const currentCenter = this.getCenterInternal(); + if (currentCenter !== undefined) { + center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]]; + (0,_coordinate_js__WEBPACK_IMPORTED_MODULE_6__.rotate)(center, rotation - this.getRotation()); + (0,_coordinate_js__WEBPACK_IMPORTED_MODULE_6__.add)(center, anchor); + } + return center; + } + + /** + * @param {number} resolution Target resolution. + * @param {import("./coordinate.js").Coordinate} anchor Zoom anchor. + * @return {import("./coordinate.js").Coordinate|undefined} Center for resolution and anchor. + */ + calculateCenterZoom(resolution, anchor) { + let center; + const currentCenter = this.getCenterInternal(); + const currentResolution = this.getResolution(); + if (currentCenter !== undefined && currentResolution !== undefined) { + const x = + anchor[0] - + (resolution * (anchor[0] - currentCenter[0])) / currentResolution; + const y = + anchor[1] - + (resolution * (anchor[1] - currentCenter[1])) / currentResolution; + center = [x, y]; + } + return center; + } + + /** + * Returns the current viewport size. + * @private + * @param {number} [rotation] Take into account the rotation of the viewport when giving the size + * @return {import("./size.js").Size} Viewport size or `[100, 100]` when no viewport is found. + */ + getViewportSize_(rotation) { + const size = this.viewportSize_; + if (rotation) { + const w = size[0]; + const h = size[1]; + return [ + Math.abs(w * Math.cos(rotation)) + Math.abs(h * Math.sin(rotation)), + Math.abs(w * Math.sin(rotation)) + Math.abs(h * Math.cos(rotation)), + ]; + } + return size; + } + + /** + * Stores the viewport size on the view. The viewport size is not read every time from the DOM + * to avoid performance hit and layout reflow. + * This should be done on map size change. + * Note: the constraints are not resolved during an animation to avoid stopping it + * @param {import("./size.js").Size} [size] Viewport size; if undefined, [100, 100] is assumed + */ + setViewportSize(size) { + this.viewportSize_ = Array.isArray(size) ? size.slice() : [100, 100]; + if (!this.getAnimating()) { + this.resolveConstraints(0); + } + } + + /** + * Get the view center. + * @return {import("./coordinate.js").Coordinate|undefined} The center of the view. + * @observable + * @api + */ + getCenter() { + const center = this.getCenterInternal(); + if (!center) { + return center; + } + return (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.toUserCoordinate)(center, this.getProjection()); + } + + /** + * Get the view center without transforming to user projection. + * @return {import("./coordinate.js").Coordinate|undefined} The center of the view. + */ + getCenterInternal() { + return /** @type {import("./coordinate.js").Coordinate|undefined} */ ( + this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].CENTER) + ); + } + + /** + * @return {Constraints} Constraints. + */ + getConstraints() { + return this.constraints_; + } + + /** + * @return {boolean} Resolution constraint is set + */ + getConstrainResolution() { + return this.get('constrainResolution'); + } + + /** + * @param {Array} [hints] Destination array. + * @return {Array} Hint. + */ + getHints(hints) { + if (hints !== undefined) { + hints[0] = this.hints_[0]; + hints[1] = this.hints_[1]; + return hints; + } + return this.hints_.slice(); + } + + /** + * Calculate the extent for the current view state and the passed box size. + * @param {import("./size.js").Size} [size] The pixel dimensions of the box + * into which the calculated extent should fit. Defaults to the size of the + * map the view is associated with. + * If no map or multiple maps are connected to the view, provide the desired + * box size (e.g. `map.getSize()`). + * @return {import("./extent.js").Extent} Extent. + * @api + */ + calculateExtent(size) { + const extent = this.calculateExtentInternal(size); + return (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.toUserExtent)(extent, this.getProjection()); + } + + /** + * @param {import("./size.js").Size} [size] Box pixel size. If not provided, + * the map's last known viewport size will be used. + * @return {import("./extent.js").Extent} Extent. + */ + calculateExtentInternal(size) { + size = size || this.getViewportSizeMinusPadding_(); + const center = /** @type {!import("./coordinate.js").Coordinate} */ ( + this.getCenterInternal() + ); + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_7__.assert)(center, 'The view center is not defined'); + const resolution = /** @type {!number} */ (this.getResolution()); + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_7__.assert)(resolution !== undefined, 'The view resolution is not defined'); + const rotation = /** @type {!number} */ (this.getRotation()); + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_7__.assert)(rotation !== undefined, 'The view rotation is not defined'); + + return (0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getForViewAndSize)(center, resolution, rotation, size); + } + + /** + * Get the maximum resolution of the view. + * @return {number} The maximum resolution of the view. + * @api + */ + getMaxResolution() { + return this.maxResolution_; + } + + /** + * Get the minimum resolution of the view. + * @return {number} The minimum resolution of the view. + * @api + */ + getMinResolution() { + return this.minResolution_; + } + + /** + * Get the maximum zoom level for the view. + * @return {number} The maximum zoom level. + * @api + */ + getMaxZoom() { + return /** @type {number} */ ( + this.getZoomForResolution(this.minResolution_) + ); + } + + /** + * Set a new maximum zoom level for the view. + * @param {number} zoom The maximum zoom level. + * @api + */ + setMaxZoom(zoom) { + this.applyOptions_(this.getUpdatedOptions_({maxZoom: zoom})); + } + + /** + * Get the minimum zoom level for the view. + * @return {number} The minimum zoom level. + * @api + */ + getMinZoom() { + return /** @type {number} */ ( + this.getZoomForResolution(this.maxResolution_) + ); + } + + /** + * Set a new minimum zoom level for the view. + * @param {number} zoom The minimum zoom level. + * @api + */ + setMinZoom(zoom) { + this.applyOptions_(this.getUpdatedOptions_({minZoom: zoom})); + } + + /** + * Set whether the view should allow intermediary zoom levels. + * @param {boolean} enabled Whether the resolution is constrained. + * @api + */ + setConstrainResolution(enabled) { + this.applyOptions_(this.getUpdatedOptions_({constrainResolution: enabled})); + } + + /** + * Get the view projection. + * @return {import("./proj/Projection.js").default} The projection of the view. + * @api + */ + getProjection() { + return this.projection_; + } + + /** + * Get the view resolution. + * @return {number|undefined} The resolution of the view. + * @observable + * @api + */ + getResolution() { + return /** @type {number|undefined} */ (this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].RESOLUTION)); + } + + /** + * Get the resolutions for the view. This returns the array of resolutions + * passed to the constructor of the View, or undefined if none were given. + * @return {Array|undefined} The resolutions of the view. + * @api + */ + getResolutions() { + return this.resolutions_; + } + + /** + * Get the resolution for a provided extent (in map units) and size (in pixels). + * @param {import("./extent.js").Extent} extent Extent. + * @param {import("./size.js").Size} [size] Box pixel size. + * @return {number} The resolution at which the provided extent will render at + * the given size. + * @api + */ + getResolutionForExtent(extent, size) { + return this.getResolutionForExtentInternal( + (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserExtent)(extent, this.getProjection()), + size, + ); + } + + /** + * Get the resolution for a provided extent (in map units) and size (in pixels). + * @param {import("./extent.js").Extent} extent Extent. + * @param {import("./size.js").Size} [size] Box pixel size. + * @return {number} The resolution at which the provided extent will render at + * the given size. + */ + getResolutionForExtentInternal(extent, size) { + size = size || this.getViewportSizeMinusPadding_(); + const xResolution = (0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getWidth)(extent) / size[0]; + const yResolution = (0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getHeight)(extent) / size[1]; + return Math.max(xResolution, yResolution); + } + + /** + * Return a function that returns a value between 0 and 1 for a + * resolution. Exponential scaling is assumed. + * @param {number} [power] Power. + * @return {function(number): number} Resolution for value function. + */ + getResolutionForValueFunction(power) { + power = power || 2; + const maxResolution = this.getConstrainedResolution(this.maxResolution_); + const minResolution = this.minResolution_; + const max = Math.log(maxResolution / minResolution) / Math.log(power); + return ( + /** + * @param {number} value Value. + * @return {number} Resolution. + */ + function (value) { + const resolution = maxResolution / Math.pow(power, value * max); + return resolution; + } + ); + } + + /** + * Get the view rotation. + * @return {number} The rotation of the view in radians. + * @observable + * @api + */ + getRotation() { + return /** @type {number} */ (this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].ROTATION)); + } + + /** + * Return a function that returns a resolution for a value between + * 0 and 1. Exponential scaling is assumed. + * @param {number} [power] Power. + * @return {function(number): number} Value for resolution function. + */ + getValueForResolutionFunction(power) { + const logPower = Math.log(power || 2); + const maxResolution = this.getConstrainedResolution(this.maxResolution_); + const minResolution = this.minResolution_; + const max = Math.log(maxResolution / minResolution) / logPower; + return ( + /** + * @param {number} resolution Resolution. + * @return {number} Value. + */ + function (resolution) { + const value = Math.log(maxResolution / resolution) / logPower / max; + return value; + } + ); + } + + /** + * Returns the size of the viewport minus padding. + * @private + * @param {number} [rotation] Take into account the rotation of the viewport when giving the size + * @return {import("./size.js").Size} Viewport size reduced by the padding. + */ + getViewportSizeMinusPadding_(rotation) { + let size = this.getViewportSize_(rotation); + const padding = this.padding_; + if (padding) { + size = [ + size[0] - padding[1] - padding[3], + size[1] - padding[0] - padding[2], + ]; + } + return size; + } + + /** + * @return {State} View state. + */ + getState() { + const projection = this.getProjection(); + const resolution = this.getResolution(); + const rotation = this.getRotation(); + let center = /** @type {import("./coordinate.js").Coordinate} */ ( + this.getCenterInternal() + ); + const padding = this.padding_; + if (padding) { + const reducedSize = this.getViewportSizeMinusPadding_(); + center = calculateCenterOn( + center, + this.getViewportSize_(), + [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]], + resolution, + rotation, + ); + } + return { + center: center.slice(0), + projection: projection !== undefined ? projection : null, + resolution: resolution, + nextCenter: this.nextCenter_, + nextResolution: this.nextResolution_, + nextRotation: this.nextRotation_, + rotation: rotation, + zoom: this.getZoom(), + }; + } + + /** + * @return {ViewStateLayerStateExtent} Like `FrameState`, but just `viewState` and `extent`. + */ + getViewStateAndExtent() { + return { + viewState: this.getState(), + extent: this.calculateExtent(), + }; + } + + /** + * Get the current zoom level. This method may return non-integer zoom levels + * if the view does not constrain the resolution, or if an interaction or + * animation is underway. + * @return {number|undefined} Zoom. + * @api + */ + getZoom() { + let zoom; + const resolution = this.getResolution(); + if (resolution !== undefined) { + zoom = this.getZoomForResolution(resolution); + } + return zoom; + } + + /** + * Get the zoom level for a resolution. + * @param {number} resolution The resolution. + * @return {number|undefined} The zoom level for the provided resolution. + * @api + */ + getZoomForResolution(resolution) { + let offset = this.minZoom_ || 0; + let max, zoomFactor; + if (this.resolutions_) { + const nearest = (0,_array_js__WEBPACK_IMPORTED_MODULE_9__.linearFindNearest)(this.resolutions_, resolution, 1); + offset = nearest; + max = this.resolutions_[nearest]; + if (nearest == this.resolutions_.length - 1) { + zoomFactor = 2; + } else { + zoomFactor = max / this.resolutions_[nearest + 1]; + } + } else { + max = this.maxResolution_; + zoomFactor = this.zoomFactor_; + } + return offset + Math.log(max / resolution) / Math.log(zoomFactor); + } + + /** + * Get the resolution for a zoom level. + * @param {number} zoom Zoom level. + * @return {number} The view resolution for the provided zoom level. + * @api + */ + getResolutionForZoom(zoom) { + if (this.resolutions_) { + if (this.resolutions_.length <= 1) { + return 0; + } + const baseLevel = (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.clamp)( + Math.floor(zoom), + 0, + this.resolutions_.length - 2, + ); + const zoomFactor = + this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1]; + return ( + this.resolutions_[baseLevel] / + Math.pow(zoomFactor, (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.clamp)(zoom - baseLevel, 0, 1)) + ); + } + return ( + this.maxResolution_ / Math.pow(this.zoomFactor_, zoom - this.minZoom_) + ); + } + + /** + * Fit the given geometry or extent based on the given map size and border. + * The size is pixel dimensions of the box to fit the extent into. + * In most cases you will want to use the map size, that is `map.getSize()`. + * Takes care of the map angle. + * @param {import("./geom/SimpleGeometry.js").default|import("./extent.js").Extent} geometryOrExtent The geometry or + * extent to fit the view to. + * @param {FitOptions} [options] Options. + * @api + */ + fit(geometryOrExtent, options) { + /** @type {import("./geom/SimpleGeometry.js").default} */ + let geometry; + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_7__.assert)( + Array.isArray(geometryOrExtent) || + typeof (/** @type {?} */ (geometryOrExtent).getSimplifiedGeometry) === + 'function', + 'Invalid extent or geometry provided as `geometry`', + ); + if (Array.isArray(geometryOrExtent)) { + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_7__.assert)( + !(0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.isEmpty)(geometryOrExtent), + 'Cannot fit empty extent provided as `geometry`', + ); + const extent = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserExtent)(geometryOrExtent, this.getProjection()); + geometry = (0,_geom_Polygon_js__WEBPACK_IMPORTED_MODULE_10__.fromExtent)(extent); + } else if (geometryOrExtent.getType() === 'Circle') { + const extent = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserExtent)( + geometryOrExtent.getExtent(), + this.getProjection(), + ); + geometry = (0,_geom_Polygon_js__WEBPACK_IMPORTED_MODULE_10__.fromExtent)(extent); + geometry.rotate(this.getRotation(), (0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getCenter)(extent)); + } else { + const userProjection = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.getUserProjection)(); + if (userProjection) { + geometry = /** @type {import("./geom/SimpleGeometry.js").default} */ ( + geometryOrExtent + .clone() + .transform(userProjection, this.getProjection()) + ); + } else { + geometry = geometryOrExtent; + } + } + + this.fitInternal(geometry, options); + } + + /** + * Calculate rotated extent + * @param {import("./geom/SimpleGeometry.js").default} geometry The geometry. + * @return {import("./extent").Extent} The rotated extent for the geometry. + */ + rotatedExtentForGeometry(geometry) { + const rotation = this.getRotation(); + const cosAngle = Math.cos(rotation); + const sinAngle = Math.sin(-rotation); + const coords = geometry.getFlatCoordinates(); + const stride = geometry.getStride(); + let minRotX = +Infinity; + let minRotY = +Infinity; + let maxRotX = -Infinity; + let maxRotY = -Infinity; + for (let i = 0, ii = coords.length; i < ii; i += stride) { + const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle; + const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle; + minRotX = Math.min(minRotX, rotX); + minRotY = Math.min(minRotY, rotY); + maxRotX = Math.max(maxRotX, rotX); + maxRotY = Math.max(maxRotY, rotY); + } + return [minRotX, minRotY, maxRotX, maxRotY]; + } + + /** + * @param {import("./geom/SimpleGeometry.js").default} geometry The geometry. + * @param {FitOptions} [options] Options. + */ + fitInternal(geometry, options) { + options = options || {}; + let size = options.size; + if (!size) { + size = this.getViewportSizeMinusPadding_(); + } + const padding = + options.padding !== undefined ? options.padding : [0, 0, 0, 0]; + const nearest = options.nearest !== undefined ? options.nearest : false; + let minResolution; + if (options.minResolution !== undefined) { + minResolution = options.minResolution; + } else if (options.maxZoom !== undefined) { + minResolution = this.getResolutionForZoom(options.maxZoom); + } else { + minResolution = 0; + } + + const rotatedExtent = this.rotatedExtentForGeometry(geometry); + + // calculate resolution + let resolution = this.getResolutionForExtentInternal(rotatedExtent, [ + size[0] - padding[1] - padding[3], + size[1] - padding[0] - padding[2], + ]); + resolution = isNaN(resolution) + ? minResolution + : Math.max(resolution, minResolution); + resolution = this.getConstrainedResolution(resolution, nearest ? 0 : 1); + + // calculate center + const rotation = this.getRotation(); + const sinAngle = Math.sin(rotation); + const cosAngle = Math.cos(rotation); + const centerRot = (0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getCenter)(rotatedExtent); + centerRot[0] += ((padding[1] - padding[3]) / 2) * resolution; + centerRot[1] += ((padding[0] - padding[2]) / 2) * resolution; + const centerX = centerRot[0] * cosAngle - centerRot[1] * sinAngle; + const centerY = centerRot[1] * cosAngle + centerRot[0] * sinAngle; + const center = this.getConstrainedCenter([centerX, centerY], resolution); + const callback = options.callback ? options.callback : _functions_js__WEBPACK_IMPORTED_MODULE_11__.VOID; + + if (options.duration !== undefined) { + this.animateInternal( + { + resolution: resolution, + center: center, + duration: options.duration, + easing: options.easing, + }, + callback, + ); + } else { + this.targetResolution_ = resolution; + this.targetCenter_ = center; + this.applyTargetState_(false, true); + animationCallback(callback, true); + } + } + + /** + * Center on coordinate and view position. + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("./size.js").Size} size Box pixel size. + * @param {import("./pixel.js").Pixel} position Position on the view to center on. + * @api + */ + centerOn(coordinate, size, position) { + this.centerOnInternal( + (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)(coordinate, this.getProjection()), + size, + position, + ); + } + + /** + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("./size.js").Size} size Box pixel size. + * @param {import("./pixel.js").Pixel} position Position on the view to center on. + */ + centerOnInternal(coordinate, size, position) { + this.setCenterInternal( + calculateCenterOn( + coordinate, + size, + position, + this.getResolution(), + this.getRotation(), + ), + ); + } + + /** + * Calculates the shift between map and viewport center. + * @param {import("./coordinate.js").Coordinate} center Center. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @param {import("./size.js").Size} size Size. + * @return {Array|undefined} Center shift. + */ + calculateCenterShift(center, resolution, rotation, size) { + let centerShift; + const padding = this.padding_; + if (padding && center) { + const reducedSize = this.getViewportSizeMinusPadding_(-rotation); + const shiftedCenter = calculateCenterOn( + center, + size, + [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]], + resolution, + rotation, + ); + centerShift = [ + center[0] - shiftedCenter[0], + center[1] - shiftedCenter[1], + ]; + } + return centerShift; + } + + /** + * @return {boolean} Is defined. + */ + isDef() { + return !!this.getCenterInternal() && this.getResolution() !== undefined; + } + + /** + * Adds relative coordinates to the center of the view. Any extent constraint will apply. + * @param {import("./coordinate.js").Coordinate} deltaCoordinates Relative value to add. + * @api + */ + adjustCenter(deltaCoordinates) { + const center = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.toUserCoordinate)(this.targetCenter_, this.getProjection()); + this.setCenter([ + center[0] + deltaCoordinates[0], + center[1] + deltaCoordinates[1], + ]); + } + + /** + * Adds relative coordinates to the center of the view. Any extent constraint will apply. + * @param {import("./coordinate.js").Coordinate} deltaCoordinates Relative value to add. + */ + adjustCenterInternal(deltaCoordinates) { + const center = this.targetCenter_; + this.setCenterInternal([ + center[0] + deltaCoordinates[0], + center[1] + deltaCoordinates[1], + ]); + } + + /** + * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution + * constraint will apply. + * @param {number} ratio The ratio to apply on the view resolution. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + * @api + */ + adjustResolution(ratio, anchor) { + anchor = anchor && (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)(anchor, this.getProjection()); + this.adjustResolutionInternal(ratio, anchor); + } + + /** + * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution + * constraint will apply. + * @param {number} ratio The ratio to apply on the view resolution. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + */ + adjustResolutionInternal(ratio, anchor) { + const isMoving = this.getAnimating() || this.getInteracting(); + const size = this.getViewportSize_(this.getRotation()); + const newResolution = this.constraints_.resolution( + this.targetResolution_ * ratio, + 0, + size, + isMoving, + ); + + if (anchor) { + this.targetCenter_ = this.calculateCenterZoom(newResolution, anchor); + } + + this.targetResolution_ *= ratio; + this.applyTargetState_(); + } + + /** + * Adds a value to the view zoom level, optionally using an anchor. Any resolution + * constraint will apply. + * @param {number} delta Relative value to add to the zoom level. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + * @api + */ + adjustZoom(delta, anchor) { + this.adjustResolution(Math.pow(this.zoomFactor_, -delta), anchor); + } + + /** + * Adds a value to the view rotation, optionally using an anchor. Any rotation + * constraint will apply. + * @param {number} delta Relative value to add to the zoom rotation, in radians. + * @param {import("./coordinate.js").Coordinate} [anchor] The rotation center. + * @api + */ + adjustRotation(delta, anchor) { + if (anchor) { + anchor = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)(anchor, this.getProjection()); + } + this.adjustRotationInternal(delta, anchor); + } + + /** + * @param {number} delta Relative value to add to the zoom rotation, in radians. + * @param {import("./coordinate.js").Coordinate} [anchor] The rotation center. + */ + adjustRotationInternal(delta, anchor) { + const isMoving = this.getAnimating() || this.getInteracting(); + const newRotation = this.constraints_.rotation( + this.targetRotation_ + delta, + isMoving, + ); + if (anchor) { + this.targetCenter_ = this.calculateCenterRotate(newRotation, anchor); + } + this.targetRotation_ += delta; + this.applyTargetState_(); + } + + /** + * Set the center of the current view. Any extent constraint will apply. + * @param {import("./coordinate.js").Coordinate|undefined} center The center of the view. + * @observable + * @api + */ + setCenter(center) { + this.setCenterInternal( + center ? (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)(center, this.getProjection()) : center, + ); + } + + /** + * Set the center using the view projection (not the user projection). + * @param {import("./coordinate.js").Coordinate|undefined} center The center of the view. + */ + setCenterInternal(center) { + this.targetCenter_ = center; + this.applyTargetState_(); + } + + /** + * @param {import("./ViewHint.js").default} hint Hint. + * @param {number} delta Delta. + * @return {number} New value. + */ + setHint(hint, delta) { + this.hints_[hint] += delta; + this.changed(); + return this.hints_[hint]; + } + + /** + * Set the resolution for this view. Any resolution constraint will apply. + * @param {number|undefined} resolution The resolution of the view. + * @observable + * @api + */ + setResolution(resolution) { + this.targetResolution_ = resolution; + this.applyTargetState_(); + } + + /** + * Set the rotation for this view. Any rotation constraint will apply. + * @param {number} rotation The rotation of the view in radians. + * @observable + * @api + */ + setRotation(rotation) { + this.targetRotation_ = rotation; + this.applyTargetState_(); + } + + /** + * Zoom to a specific zoom level. Any resolution constrain will apply. + * @param {number} zoom Zoom level. + * @api + */ + setZoom(zoom) { + this.setResolution(this.getResolutionForZoom(zoom)); + } + + /** + * Recompute rotation/resolution/center based on target values. + * Note: we have to compute rotation first, then resolution and center considering that + * parameters can influence one another in case a view extent constraint is present. + * @param {boolean} [doNotCancelAnims] Do not cancel animations. + * @param {boolean} [forceMoving] Apply constraints as if the view is moving. + * @private + */ + applyTargetState_(doNotCancelAnims, forceMoving) { + const isMoving = + this.getAnimating() || this.getInteracting() || forceMoving; + + // compute rotation + const newRotation = this.constraints_.rotation( + this.targetRotation_, + isMoving, + ); + const size = this.getViewportSize_(newRotation); + const newResolution = this.constraints_.resolution( + this.targetResolution_, + 0, + size, + isMoving, + ); + const newCenter = this.constraints_.center( + this.targetCenter_, + newResolution, + size, + isMoving, + this.calculateCenterShift( + this.targetCenter_, + newResolution, + newRotation, + size, + ), + ); + + if (this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].ROTATION) !== newRotation) { + this.set(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].ROTATION, newRotation); + } + if (this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].RESOLUTION) !== newResolution) { + this.set(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].RESOLUTION, newResolution); + this.set('zoom', this.getZoom(), true); + } + if ( + !newCenter || + !this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].CENTER) || + !(0,_coordinate_js__WEBPACK_IMPORTED_MODULE_6__.equals)(this.get(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].CENTER), newCenter) + ) { + this.set(_ViewProperty_js__WEBPACK_IMPORTED_MODULE_2__["default"].CENTER, newCenter); + } + + if (this.getAnimating() && !doNotCancelAnims) { + this.cancelAnimations(); + } + this.cancelAnchor_ = undefined; + } + + /** + * If any constraints need to be applied, an animation will be triggered. + * This is typically done on interaction end. + * Note: calling this with a duration of 0 will apply the constrained values straight away, + * without animation. + * @param {number} [duration] The animation duration in ms. + * @param {number} [resolutionDirection] Which direction to zoom. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + */ + resolveConstraints(duration, resolutionDirection, anchor) { + duration = duration !== undefined ? duration : 200; + const direction = resolutionDirection || 0; + + const newRotation = this.constraints_.rotation(this.targetRotation_); + const size = this.getViewportSize_(newRotation); + const newResolution = this.constraints_.resolution( + this.targetResolution_, + direction, + size, + ); + const newCenter = this.constraints_.center( + this.targetCenter_, + newResolution, + size, + false, + this.calculateCenterShift( + this.targetCenter_, + newResolution, + newRotation, + size, + ), + ); + + if (duration === 0 && !this.cancelAnchor_) { + this.targetResolution_ = newResolution; + this.targetRotation_ = newRotation; + this.targetCenter_ = newCenter; + this.applyTargetState_(); + return; + } + + anchor = anchor || (duration === 0 ? this.cancelAnchor_ : undefined); + this.cancelAnchor_ = undefined; + + if ( + this.getResolution() !== newResolution || + this.getRotation() !== newRotation || + !this.getCenterInternal() || + !(0,_coordinate_js__WEBPACK_IMPORTED_MODULE_6__.equals)(this.getCenterInternal(), newCenter) + ) { + if (this.getAnimating()) { + this.cancelAnimations(); + } + + this.animateInternal({ + rotation: newRotation, + center: newCenter, + resolution: newResolution, + duration: duration, + easing: _easing_js__WEBPACK_IMPORTED_MODULE_3__.easeOut, + anchor: anchor, + }); + } + } + + /** + * Notify the View that an interaction has started. + * The view state will be resolved to a stable one if needed + * (depending on its constraints). + * @api + */ + beginInteraction() { + this.resolveConstraints(0); + + this.setHint(_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].INTERACTING, 1); + } + + /** + * Notify the View that an interaction has ended. The view state will be resolved + * to a stable one if needed (depending on its constraints). + * @param {number} [duration] Animation duration in ms. + * @param {number} [resolutionDirection] Which direction to zoom. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + * @api + */ + endInteraction(duration, resolutionDirection, anchor) { + anchor = anchor && (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.fromUserCoordinate)(anchor, this.getProjection()); + this.endInteractionInternal(duration, resolutionDirection, anchor); + } + + /** + * Notify the View that an interaction has ended. The view state will be resolved + * to a stable one if needed (depending on its constraints). + * @param {number} [duration] Animation duration in ms. + * @param {number} [resolutionDirection] Which direction to zoom. + * @param {import("./coordinate.js").Coordinate} [anchor] The origin of the transformation. + */ + endInteractionInternal(duration, resolutionDirection, anchor) { + if (!this.getInteracting()) { + return; + } + this.setHint(_ViewHint_js__WEBPACK_IMPORTED_MODULE_5__["default"].INTERACTING, -1); + this.resolveConstraints(duration, resolutionDirection, anchor); + } + + /** + * Get a valid position for the view center according to the current constraints. + * @param {import("./coordinate.js").Coordinate|undefined} targetCenter Target center position. + * @param {number} [targetResolution] Target resolution. If not supplied, the current one will be used. + * This is useful to guess a valid center position at a different zoom level. + * @return {import("./coordinate.js").Coordinate|undefined} Valid center position. + */ + getConstrainedCenter(targetCenter, targetResolution) { + const size = this.getViewportSize_(this.getRotation()); + return this.constraints_.center( + targetCenter, + targetResolution || this.getResolution(), + size, + ); + } + + /** + * Get a valid zoom level according to the current view constraints. + * @param {number|undefined} targetZoom Target zoom. + * @param {number} [direction=0] Indicate which resolution should be used + * by a renderer if the view resolution does not match any resolution of the tile source. + * If 0, the nearest resolution will be used. If 1, the nearest lower resolution + * will be used. If -1, the nearest higher resolution will be used. + * @return {number|undefined} Valid zoom level. + */ + getConstrainedZoom(targetZoom, direction) { + const targetRes = this.getResolutionForZoom(targetZoom); + return this.getZoomForResolution( + this.getConstrainedResolution(targetRes, direction), + ); + } + + /** + * Get a valid resolution according to the current view constraints. + * @param {number|undefined} targetResolution Target resolution. + * @param {number} [direction=0] Indicate which resolution should be used + * by a renderer if the view resolution does not match any resolution of the tile source. + * If 0, the nearest resolution will be used. If 1, the nearest lower resolution + * will be used. If -1, the nearest higher resolution will be used. + * @return {number|undefined} Valid resolution. + */ + getConstrainedResolution(targetResolution, direction) { + direction = direction || 0; + const size = this.getViewportSize_(this.getRotation()); + + return this.constraints_.resolution(targetResolution, direction, size); + } +} + +/** + * @param {Function} callback Callback. + * @param {*} returnValue Return value. + */ +function animationCallback(callback, returnValue) { + setTimeout(function () { + callback(returnValue); + }, 0); +} + +/** + * @param {ViewOptions} options View options. + * @return {import("./centerconstraint.js").Type} The constraint. + */ +function createCenterConstraint(options) { + if (options.extent !== undefined) { + const smooth = + options.smoothExtentConstraint !== undefined + ? options.smoothExtentConstraint + : true; + return (0,_centerconstraint_js__WEBPACK_IMPORTED_MODULE_12__.createExtent)(options.extent, options.constrainOnlyCenter, smooth); + } + + const projection = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.createProjection)(options.projection, 'EPSG:3857'); + if (options.multiWorld !== true && projection.isGlobal()) { + const extent = projection.getExtent().slice(); + extent[0] = -Infinity; + extent[2] = Infinity; + return (0,_centerconstraint_js__WEBPACK_IMPORTED_MODULE_12__.createExtent)(extent, false, false); + } + + return _centerconstraint_js__WEBPACK_IMPORTED_MODULE_12__.none; +} + +/** + * @param {ViewOptions} options View options. + * @return {{constraint: import("./resolutionconstraint.js").Type, maxResolution: number, + * minResolution: number, minZoom: number, zoomFactor: number}} The constraint. + */ +function createResolutionConstraint(options) { + let resolutionConstraint; + let maxResolution; + let minResolution; + + // TODO: move these to be ol constants + // see https://github.com/openlayers/openlayers/issues/2076 + const defaultMaxZoom = 28; + const defaultZoomFactor = 2; + + let minZoom = + options.minZoom !== undefined ? options.minZoom : DEFAULT_MIN_ZOOM; + + let maxZoom = + options.maxZoom !== undefined ? options.maxZoom : defaultMaxZoom; + + const zoomFactor = + options.zoomFactor !== undefined ? options.zoomFactor : defaultZoomFactor; + + const multiWorld = + options.multiWorld !== undefined ? options.multiWorld : false; + + const smooth = + options.smoothResolutionConstraint !== undefined + ? options.smoothResolutionConstraint + : true; + + const showFullExtent = + options.showFullExtent !== undefined ? options.showFullExtent : false; + + const projection = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.createProjection)(options.projection, 'EPSG:3857'); + const projExtent = projection.getExtent(); + let constrainOnlyCenter = options.constrainOnlyCenter; + let extent = options.extent; + if (!multiWorld && !extent && projection.isGlobal()) { + constrainOnlyCenter = false; + extent = projExtent; + } + + if (options.resolutions !== undefined) { + const resolutions = options.resolutions; + maxResolution = resolutions[minZoom]; + minResolution = + resolutions[maxZoom] !== undefined + ? resolutions[maxZoom] + : resolutions[resolutions.length - 1]; + + if (options.constrainResolution) { + resolutionConstraint = (0,_resolutionconstraint_js__WEBPACK_IMPORTED_MODULE_13__.createSnapToResolutions)( + resolutions, + smooth, + !constrainOnlyCenter && extent, + showFullExtent, + ); + } else { + resolutionConstraint = (0,_resolutionconstraint_js__WEBPACK_IMPORTED_MODULE_13__.createMinMaxResolution)( + maxResolution, + minResolution, + smooth, + !constrainOnlyCenter && extent, + showFullExtent, + ); + } + } else { + // calculate the default min and max resolution + const size = !projExtent + ? // use an extent that can fit the whole world if need be + (360 * _proj_js__WEBPACK_IMPORTED_MODULE_0__.METERS_PER_UNIT.degrees) / projection.getMetersPerUnit() + : Math.max((0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getWidth)(projExtent), (0,_extent_js__WEBPACK_IMPORTED_MODULE_8__.getHeight)(projExtent)); + + const defaultMaxResolution = + size / _tilegrid_common_js__WEBPACK_IMPORTED_MODULE_14__.DEFAULT_TILE_SIZE / Math.pow(defaultZoomFactor, DEFAULT_MIN_ZOOM); + + const defaultMinResolution = + defaultMaxResolution / + Math.pow(defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM); + + // user provided maxResolution takes precedence + maxResolution = options.maxResolution; + if (maxResolution !== undefined) { + minZoom = 0; + } else { + maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom); + } + + // user provided minResolution takes precedence + minResolution = options.minResolution; + if (minResolution === undefined) { + if (options.maxZoom !== undefined) { + if (options.maxResolution !== undefined) { + minResolution = maxResolution / Math.pow(zoomFactor, maxZoom); + } else { + minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom); + } + } else { + minResolution = defaultMinResolution; + } + } + + // given discrete zoom levels, minResolution may be different than provided + maxZoom = + minZoom + + Math.floor( + Math.log(maxResolution / minResolution) / Math.log(zoomFactor), + ); + minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom); + + if (options.constrainResolution) { + resolutionConstraint = (0,_resolutionconstraint_js__WEBPACK_IMPORTED_MODULE_13__.createSnapToPower)( + zoomFactor, + maxResolution, + minResolution, + smooth, + !constrainOnlyCenter && extent, + showFullExtent, + ); + } else { + resolutionConstraint = (0,_resolutionconstraint_js__WEBPACK_IMPORTED_MODULE_13__.createMinMaxResolution)( + maxResolution, + minResolution, + smooth, + !constrainOnlyCenter && extent, + showFullExtent, + ); + } + } + return { + constraint: resolutionConstraint, + maxResolution: maxResolution, + minResolution: minResolution, + minZoom: minZoom, + zoomFactor: zoomFactor, + }; +} + +/** + * @param {ViewOptions} options View options. + * @return {import("./rotationconstraint.js").Type} Rotation constraint. + */ +function createRotationConstraint(options) { + const enableRotation = + options.enableRotation !== undefined ? options.enableRotation : true; + if (enableRotation) { + const constrainRotation = options.constrainRotation; + if (constrainRotation === undefined || constrainRotation === true) { + return (0,_rotationconstraint_js__WEBPACK_IMPORTED_MODULE_15__.createSnapToZero)(); + } + if (constrainRotation === false) { + return _rotationconstraint_js__WEBPACK_IMPORTED_MODULE_15__.none; + } + if (typeof constrainRotation === 'number') { + return (0,_rotationconstraint_js__WEBPACK_IMPORTED_MODULE_15__.createSnapToN)(constrainRotation); + } + return _rotationconstraint_js__WEBPACK_IMPORTED_MODULE_15__.none; + } + return _rotationconstraint_js__WEBPACK_IMPORTED_MODULE_15__.disable; +} + +/** + * Determine if an animation involves no view change. + * @param {Animation} animation The animation. + * @return {boolean} The animation involves no view change. + */ +function isNoopAnimation(animation) { + if (animation.sourceCenter && animation.targetCenter) { + if (!(0,_coordinate_js__WEBPACK_IMPORTED_MODULE_6__.equals)(animation.sourceCenter, animation.targetCenter)) { + return false; + } + } + if (animation.sourceResolution !== animation.targetResolution) { + return false; + } + if (animation.sourceRotation !== animation.targetRotation) { + return false; + } + return true; +} + +/** + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @param {import("./size.js").Size} size Box pixel size. + * @param {import("./pixel.js").Pixel} position Position on the view to center on. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @return {import("./coordinate.js").Coordinate} Shifted center. + */ +function calculateCenterOn(coordinate, size, position, resolution, rotation) { + // calculate rotated position + const cosAngle = Math.cos(-rotation); + let sinAngle = Math.sin(-rotation); + let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle; + let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle; + rotX += (size[0] / 2 - position[0]) * resolution; + rotY += (position[1] - size[1] / 2) * resolution; + + // go back to original angle + sinAngle = -sinAngle; // go back to original rotation + const centerX = rotX * cosAngle - rotY * sinAngle; + const centerY = rotY * cosAngle + rotX * sinAngle; + + return [centerX, centerY]; +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (View); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/ViewHint.js": +/*!*********************************************!*\ + !*** ./node_modules/@biigle/ol/ViewHint.js ***! + \*********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/ViewHint + */ + +/** + * @enum {number} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + ANIMATING: 0, + INTERACTING: 1, +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/ViewProperty.js": +/*!*************************************************!*\ + !*** ./node_modules/@biigle/ol/ViewProperty.js ***! + \*************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/ViewProperty + */ + +/** + * @enum {string} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + CENTER: 'center', + RESOLUTION: 'resolution', + ROTATION: 'rotation', +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/array.js": +/*!******************************************!*\ + !*** ./node_modules/@biigle/ol/array.js ***! + \******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "ascending": () => (/* binding */ ascending), +/* harmony export */ "binarySearch": () => (/* binding */ binarySearch), +/* harmony export */ "descending": () => (/* binding */ descending), +/* harmony export */ "equals": () => (/* binding */ equals), +/* harmony export */ "extend": () => (/* binding */ extend), +/* harmony export */ "isSorted": () => (/* binding */ isSorted), +/* harmony export */ "linearFindNearest": () => (/* binding */ linearFindNearest), +/* harmony export */ "remove": () => (/* binding */ remove), +/* harmony export */ "reverseSubArray": () => (/* binding */ reverseSubArray), +/* harmony export */ "stableSort": () => (/* binding */ stableSort) +/* harmony export */ }); +/** + * @module ol/array + */ + +/** + * Performs a binary search on the provided sorted list and returns the index of the item if found. If it can't be found it'll return -1. + * https://github.com/darkskyapp/binary-search + * + * @param {Array<*>} haystack Items to search through. + * @param {*} needle The item to look for. + * @param {Function} [comparator] Comparator function. + * @return {number} The index of the item if found, -1 if not. + */ +function binarySearch(haystack, needle, comparator) { + let mid, cmp; + comparator = comparator || ascending; + let low = 0; + let high = haystack.length; + let found = false; + + while (low < high) { + /* Note that "(low + high) >>> 1" may overflow, and results in a typecast + * to double (which gives the wrong results). */ + mid = low + ((high - low) >> 1); + cmp = +comparator(haystack[mid], needle); + + if (cmp < 0.0) { + /* Too low. */ + low = mid + 1; + } else { + /* Key found or too high */ + high = mid; + found = !cmp; + } + } + + /* Key not found. */ + return found ? low : ~low; +} + +/** + * Compare function sorting arrays in ascending order. Safe to use for numeric values. + * @param {*} a The first object to be compared. + * @param {*} b The second object to be compared. + * @return {number} A negative number, zero, or a positive number as the first + * argument is less than, equal to, or greater than the second. + */ +function ascending(a, b) { + return a > b ? 1 : a < b ? -1 : 0; +} + +/** + * Compare function sorting arrays in descending order. Safe to use for numeric values. + * @param {*} a The first object to be compared. + * @param {*} b The second object to be compared. + * @return {number} A negative number, zero, or a positive number as the first + * argument is greater than, equal to, or less than the second. + */ +function descending(a, b) { + return a < b ? 1 : a > b ? -1 : 0; +} + +/** + * {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution} can use a function + * of this type to determine which nearest resolution to use. + * + * This function takes a `{number}` representing a value between two array entries, + * a `{number}` representing the value of the nearest higher entry and + * a `{number}` representing the value of the nearest lower entry + * as arguments and returns a `{number}`. If a negative number or zero is returned + * the lower value will be used, if a positive number is returned the higher value + * will be used. + * @typedef {function(number, number, number): number} NearestDirectionFunction + * @api + */ + +/** + * @param {Array} arr Array in descending order. + * @param {number} target Target. + * @param {number|NearestDirectionFunction} direction + * 0 means return the nearest, + * > 0 means return the largest nearest, + * < 0 means return the smallest nearest. + * @return {number} Index. + */ +function linearFindNearest(arr, target, direction) { + if (arr[0] <= target) { + return 0; + } + + const n = arr.length; + if (target <= arr[n - 1]) { + return n - 1; + } + + if (typeof direction === 'function') { + for (let i = 1; i < n; ++i) { + const candidate = arr[i]; + if (candidate === target) { + return i; + } + if (candidate < target) { + if (direction(target, arr[i - 1], candidate) > 0) { + return i - 1; + } + return i; + } + } + return n - 1; + } + + if (direction > 0) { + for (let i = 1; i < n; ++i) { + if (arr[i] < target) { + return i - 1; + } + } + return n - 1; + } + + if (direction < 0) { + for (let i = 1; i < n; ++i) { + if (arr[i] <= target) { + return i; + } + } + return n - 1; + } + + for (let i = 1; i < n; ++i) { + if (arr[i] == target) { + return i; + } + if (arr[i] < target) { + if (arr[i - 1] - target < target - arr[i]) { + return i - 1; + } + return i; + } + } + return n - 1; +} + +/** + * @param {Array<*>} arr Array. + * @param {number} begin Begin index. + * @param {number} end End index. + */ +function reverseSubArray(arr, begin, end) { + while (begin < end) { + const tmp = arr[begin]; + arr[begin] = arr[end]; + arr[end] = tmp; + ++begin; + --end; + } +} + +/** + * @param {Array} arr The array to modify. + * @param {!Array|VALUE} data The elements or arrays of elements to add to arr. + * @template VALUE + */ +function extend(arr, data) { + const extension = Array.isArray(data) ? data : [data]; + const length = extension.length; + for (let i = 0; i < length; i++) { + arr[arr.length] = extension[i]; + } +} + +/** + * @param {Array} arr The array to modify. + * @param {VALUE} obj The element to remove. + * @template VALUE + * @return {boolean} If the element was removed. + */ +function remove(arr, obj) { + const i = arr.indexOf(obj); + const found = i > -1; + if (found) { + arr.splice(i, 1); + } + return found; +} + +/** + * @param {Array|Uint8ClampedArray} arr1 The first array to compare. + * @param {Array|Uint8ClampedArray} arr2 The second array to compare. + * @return {boolean} Whether the two arrays are equal. + */ +function equals(arr1, arr2) { + const len1 = arr1.length; + if (len1 !== arr2.length) { + return false; + } + for (let i = 0; i < len1; i++) { + if (arr1[i] !== arr2[i]) { + return false; + } + } + return true; +} + +/** + * Sort the passed array such that the relative order of equal elements is preserved. + * See https://en.wikipedia.org/wiki/Sorting_algorithm#Stability for details. + * @param {Array<*>} arr The array to sort (modifies original). + * @param {!function(*, *): number} compareFnc Comparison function. + * @api + */ +function stableSort(arr, compareFnc) { + const length = arr.length; + const tmp = Array(arr.length); + let i; + for (i = 0; i < length; i++) { + tmp[i] = {index: i, value: arr[i]}; + } + tmp.sort(function (a, b) { + return compareFnc(a.value, b.value) || a.index - b.index; + }); + for (i = 0; i < arr.length; i++) { + arr[i] = tmp[i].value; + } +} + +/** + * @param {Array<*>} arr The array to test. + * @param {Function} [func] Comparison function. + * @param {boolean} [strict] Strictly sorted (default false). + * @return {boolean} Return index. + */ +function isSorted(arr, func, strict) { + const compare = func || ascending; + return arr.every(function (currentVal, index) { + if (index === 0) { + return true; + } + const res = compare(arr[index - 1], currentVal); + return !(res > 0 || (strict && res === 0)); + }); +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/asserts.js": +/*!********************************************!*\ + !*** ./node_modules/@biigle/ol/asserts.js ***! + \********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "assert": () => (/* binding */ assert) +/* harmony export */ }); +/** + * @module ol/asserts + */ + +/** + * @param {*} assertion Assertion we expected to be truthy. + * @param {string} errorMessage Error message. + */ +function assert(assertion, errorMessage) { + if (!assertion) { + throw new Error(errorMessage); + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/centerconstraint.js": +/*!*****************************************************!*\ + !*** ./node_modules/@biigle/ol/centerconstraint.js ***! + \*****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createExtent": () => (/* binding */ createExtent), +/* harmony export */ "none": () => (/* binding */ none) +/* harmony export */ }); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/centerconstraint + */ + + +/** + * @typedef {function((import("./coordinate.js").Coordinate|undefined), number, import("./size.js").Size, boolean=, Array=): (import("./coordinate.js").Coordinate|undefined)} Type + */ + +/** + * @param {import("./extent.js").Extent} extent Extent. + * @param {boolean} onlyCenter If true, the constraint will only apply to the view center. + * @param {boolean} smooth If true, the view will be able to go slightly out of the given extent + * (only during interaction and animation). + * @return {Type} The constraint. + */ +function createExtent(extent, onlyCenter, smooth) { + return ( + /** + * @param {import("./coordinate.js").Coordinate|undefined} center Center. + * @param {number|undefined} resolution Resolution. + * @param {import("./size.js").Size} size Viewport size; unused if `onlyCenter` was specified. + * @param {boolean} [isMoving] True if an interaction or animation is in progress. + * @param {Array} [centerShift] Shift between map center and viewport center. + * @return {import("./coordinate.js").Coordinate|undefined} Center. + */ + function (center, resolution, size, isMoving, centerShift) { + if (!center) { + return undefined; + } + if (!resolution && !onlyCenter) { + return center; + } + const viewWidth = onlyCenter ? 0 : size[0] * resolution; + const viewHeight = onlyCenter ? 0 : size[1] * resolution; + const shiftX = centerShift ? centerShift[0] : 0; + const shiftY = centerShift ? centerShift[1] : 0; + let minX = extent[0] + viewWidth / 2 + shiftX; + let maxX = extent[2] - viewWidth / 2 + shiftX; + let minY = extent[1] + viewHeight / 2 + shiftY; + let maxY = extent[3] - viewHeight / 2 + shiftY; + + // note: when zooming out of bounds, min and max values for x and y may + // end up inverted (min > max); this has to be accounted for + if (minX > maxX) { + minX = (maxX + minX) / 2; + maxX = minX; + } + if (minY > maxY) { + minY = (maxY + minY) / 2; + maxY = minY; + } + + let x = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.clamp)(center[0], minX, maxX); + let y = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.clamp)(center[1], minY, maxY); + + // during an interaction, allow some overscroll + if (isMoving && smooth && resolution) { + const ratio = 30 * resolution; + x += + -ratio * Math.log(1 + Math.max(0, minX - center[0]) / ratio) + + ratio * Math.log(1 + Math.max(0, center[0] - maxX) / ratio); + y += + -ratio * Math.log(1 + Math.max(0, minY - center[1]) / ratio) + + ratio * Math.log(1 + Math.max(0, center[1] - maxY) / ratio); + } + + return [x, y]; + } + ); +} + +/** + * @param {import("./coordinate.js").Coordinate} [center] Center. + * @return {import("./coordinate.js").Coordinate|undefined} Center. + */ +function none(center) { + return center; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/color.js": +/*!******************************************!*\ + !*** ./node_modules/@biigle/ol/color.js ***! + \******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "asArray": () => (/* binding */ asArray), +/* harmony export */ "asString": () => (/* binding */ asString), +/* harmony export */ "fromString": () => (/* binding */ fromString), +/* harmony export */ "isStringColor": () => (/* binding */ isStringColor), +/* harmony export */ "lchaToRgba": () => (/* binding */ lchaToRgba), +/* harmony export */ "normalize": () => (/* binding */ normalize), +/* harmony export */ "rgbaToLcha": () => (/* binding */ rgbaToLcha), +/* harmony export */ "toString": () => (/* binding */ toString), +/* harmony export */ "withAlpha": () => (/* binding */ withAlpha) +/* harmony export */ }); +/* harmony import */ var color_space_lchuv_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! color-space/lchuv.js */ "./node_modules/color-space/lchuv.js"); +/* harmony import */ var color_rgba__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! color-rgba */ "./node_modules/color-rgba/index.js"); +/* harmony import */ var color_space_rgb_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! color-space/rgb.js */ "./node_modules/color-space/rgb.js"); +/* harmony import */ var color_space_xyz_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! color-space/xyz.js */ "./node_modules/color-space/xyz.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/color + */ + + + + + + +/** + * A color represented as a short array [red, green, blue, alpha]. + * red, green, and blue should be integers in the range 0..255 inclusive. + * alpha should be a float in the range 0..1 inclusive. If no alpha value is + * given then `1` will be used. + * @typedef {Array} Color + * @api + */ + +/** + * Return the color as an rgba string. + * @param {Color|string} color Color. + * @return {string} Rgba string. + * @api + */ +function asString(color) { + if (typeof color === 'string') { + return color; + } + return toString(color); +} + +/** + * @type {number} + */ +const MAX_CACHE_SIZE = 1024; + +/** + * We maintain a small cache of parsed strings. Whenever the cache grows too large, + * we delete an arbitrary set of the entries. + * + * @type {Object} + */ +const cache = {}; + +/** + * @type {number} + */ +let cacheSize = 0; + +/** + * @param {Color} color A color that may or may not have an alpha channel. + * @return {Color} The input color with an alpha channel. If the input color has + * an alpha channel, the input color will be returned unchanged. Otherwise, a new + * array will be returned with the input color and an alpha channel of 1. + */ +function withAlpha(color) { + if (color.length === 4) { + return color; + } + const output = color.slice(); + output[3] = 1; + return output; +} + +/** + * @param {Color} color RGBA color. + * @return {Color} LCHuv color with alpha. + */ +function rgbaToLcha(color) { + const output = color_space_xyz_js__WEBPACK_IMPORTED_MODULE_3__["default"].lchuv(color_space_rgb_js__WEBPACK_IMPORTED_MODULE_2__["default"].xyz(color)); + output[3] = color[3]; + return output; +} + +/** + * @param {Color} color LCHuv color with alpha. + * @return {Color} RGBA color. + */ +function lchaToRgba(color) { + const output = color_space_xyz_js__WEBPACK_IMPORTED_MODULE_3__["default"].rgb(color_space_lchuv_js__WEBPACK_IMPORTED_MODULE_0__["default"].xyz(color)); + output[3] = color[3]; + return output; +} + +/** + * @param {string} s String. + * @return {Color} Color. + */ +function fromString(s) { + if (cache.hasOwnProperty(s)) { + return cache[s]; + } + if (cacheSize >= MAX_CACHE_SIZE) { + let i = 0; + for (const key in cache) { + if ((i++ & 3) === 0) { + delete cache[key]; + --cacheSize; + } + } + } + + const color = (0,color_rgba__WEBPACK_IMPORTED_MODULE_1__["default"])(s); + if (color.length !== 4) { + throw new Error('Failed to parse "' + s + '" as color'); + } + for (const c of color) { + if (isNaN(c)) { + throw new Error('Failed to parse "' + s + '" as color'); + } + } + normalize(color); + cache[s] = color; + ++cacheSize; + return color; +} + +/** + * Return the color as an array. This function maintains a cache of calculated + * arrays which means the result should not be modified. + * @param {Color|string} color Color. + * @return {Color} Color. + * @api + */ +function asArray(color) { + if (Array.isArray(color)) { + return color; + } + return fromString(color); +} + +/** + * Exported for the tests. + * @param {Color} color Color. + * @return {Color} Clamped color. + */ +function normalize(color) { + color[0] = (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.clamp)((color[0] + 0.5) | 0, 0, 255); + color[1] = (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.clamp)((color[1] + 0.5) | 0, 0, 255); + color[2] = (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.clamp)((color[2] + 0.5) | 0, 0, 255); + color[3] = (0,_math_js__WEBPACK_IMPORTED_MODULE_4__.clamp)(color[3], 0, 1); + return color; +} + +/** + * @param {Color} color Color. + * @return {string} String. + */ +function toString(color) { + let r = color[0]; + if (r != (r | 0)) { + r = (r + 0.5) | 0; + } + let g = color[1]; + if (g != (g | 0)) { + g = (g + 0.5) | 0; + } + let b = color[2]; + if (b != (b | 0)) { + b = (b + 0.5) | 0; + } + const a = color[3] === undefined ? 1 : Math.round(color[3] * 1000) / 1000; + return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')'; +} + +/** + * @param {string} s String. + * @return {boolean} Whether the string is actually a valid color + */ +function isStringColor(s) { + try { + fromString(s); + return true; + } catch (_) { + return false; + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/colorlike.js": +/*!**********************************************!*\ + !*** ./node_modules/@biigle/ol/colorlike.js ***! + \**********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "asColorLike": () => (/* binding */ asColorLike) +/* harmony export */ }); +/* harmony import */ var _ImageState_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ImageState.js */ "./node_modules/@biigle/ol/ImageState.js"); +/* harmony import */ var _dom_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./dom.js */ "./node_modules/@biigle/ol/dom.js"); +/* harmony import */ var _style_IconImage_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./style/IconImage.js */ "./node_modules/@biigle/ol/style/IconImage.js"); +/* harmony import */ var _style_IconImageCache_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./style/IconImageCache.js */ "./node_modules/@biigle/ol/style/IconImageCache.js"); +/* harmony import */ var _color_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./color.js */ "./node_modules/@biigle/ol/color.js"); +/** + * @module ol/colorlike + */ + + + + + + +/** + * @typedef {Object} PatternDescriptor + * @property {string} src Pattern image URL + * @property {import("./color.js").Color|string} [color] Color to tint the pattern with. + * @property {import("./size.js").Size} [size] Size of the desired slice from the pattern image. + * Use this together with `offset` when the pattern image is a sprite sheet. + * @property {import("./size.js").Size} [offset] Offset of the desired slice from the pattern image. + * Use this together with `size` when the pattern image is a sprite sheet. + */ + +/** + * A type accepted by CanvasRenderingContext2D.fillStyle + * or CanvasRenderingContext2D.strokeStyle. + * Represents a color, [CanvasPattern](https://developer.mozilla.org/en-US/docs/Web/API/CanvasPattern), + * or [CanvasGradient](https://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient). The origin for + * patterns and gradients as fill style is an increment of 512 css pixels from map coordinate + * `[0, 0]`. For seamless repeat patterns, width and height of the pattern image + * must be a factor of two (2, 4, 8, ..., 512). + * + * @typedef {string|CanvasPattern|CanvasGradient} ColorLike + * @api + */ + +/** + * @param {import("./color.js").Color|ColorLike|PatternDescriptor|null} color Color. + * @return {ColorLike|null} The color as an {@link ol/colorlike~ColorLike}. + * @api + */ +function asColorLike(color) { + if (!color) { + return null; + } + if (Array.isArray(color)) { + return (0,_color_js__WEBPACK_IMPORTED_MODULE_0__.toString)(color); + } + if (typeof color === 'object' && 'src' in color) { + return asCanvasPattern(color); + } + return color; +} + +/** + * @param {PatternDescriptor} pattern Pattern descriptor. + * @return {CanvasPattern|null} Canvas pattern or null if the pattern referenced in the + * PatternDescriptor was not found in the icon image cache. + */ +function asCanvasPattern(pattern) { + if (!pattern.offset || !pattern.size) { + return _style_IconImageCache_js__WEBPACK_IMPORTED_MODULE_1__.shared.getPattern(pattern.src, 'anonymous', pattern.color); + } + + const cacheKey = pattern.src + ':' + pattern.offset; + + const canvasPattern = _style_IconImageCache_js__WEBPACK_IMPORTED_MODULE_1__.shared.getPattern( + cacheKey, + undefined, + pattern.color, + ); + if (canvasPattern) { + return canvasPattern; + } + + const iconImage = _style_IconImageCache_js__WEBPACK_IMPORTED_MODULE_1__.shared.get(pattern.src, 'anonymous', null); + if (iconImage.getImageState() !== _ImageState_js__WEBPACK_IMPORTED_MODULE_2__["default"].LOADED) { + return null; + } + const patternCanvasContext = (0,_dom_js__WEBPACK_IMPORTED_MODULE_3__.createCanvasContext2D)( + pattern.size[0], + pattern.size[1], + ); + patternCanvasContext.drawImage( + iconImage.getImage(1), + pattern.offset[0], + pattern.offset[1], + pattern.size[0], + pattern.size[1], + 0, + 0, + pattern.size[0], + pattern.size[1], + ); + (0,_style_IconImage_js__WEBPACK_IMPORTED_MODULE_4__.get)( + patternCanvasContext.canvas, + cacheKey, + undefined, + _ImageState_js__WEBPACK_IMPORTED_MODULE_2__["default"].LOADED, + pattern.color, + true, + ); + return _style_IconImageCache_js__WEBPACK_IMPORTED_MODULE_1__.shared.getPattern(cacheKey, undefined, pattern.color); +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/console.js": +/*!********************************************!*\ + !*** ./node_modules/@biigle/ol/console.js ***! + \********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "error": () => (/* binding */ error), +/* harmony export */ "log": () => (/* binding */ log), +/* harmony export */ "setLevel": () => (/* binding */ setLevel), +/* harmony export */ "warn": () => (/* binding */ warn) +/* harmony export */ }); +/** + * @module ol/console + */ + +/** + * @typedef {'info'|'warn'|'error'|'none'} Level + */ + +/** + * @type {Object} + */ +const levels = { + info: 1, + warn: 2, + error: 3, + none: 4, +}; + +/** + * @type {number} + */ +let level = levels.info; + +/** + * Set the logging level. By default, the level is set to 'info' and all + * messages will be logged. Set to 'warn' to only display warnings and errors. + * Set to 'error' to only display errors. Set to 'none' to silence all messages. + * + * @param {Level} l The new level. + */ +function setLevel(l) { + level = levels[l]; +} + +/** + * @param {...any} args Arguments to log + */ +function log(...args) { + if (level > levels.info) { + return; + } + console.log(...args); // eslint-disable-line no-console +} + +/** + * @param {...any} args Arguments to log + */ +function warn(...args) { + if (level > levels.warn) { + return; + } + console.warn(...args); // eslint-disable-line no-console +} + +/** + * @param {...any} args Arguments to log + */ +function error(...args) { + if (level > levels.error) { + return; + } + console.error(...args); // eslint-disable-line no-console +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/coordinate.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/coordinate.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "add": () => (/* binding */ add), +/* harmony export */ "closestOnCircle": () => (/* binding */ closestOnCircle), +/* harmony export */ "closestOnSegment": () => (/* binding */ closestOnSegment), +/* harmony export */ "createStringXY": () => (/* binding */ createStringXY), +/* harmony export */ "degreesToStringHDMS": () => (/* binding */ degreesToStringHDMS), +/* harmony export */ "distance": () => (/* binding */ distance), +/* harmony export */ "equals": () => (/* binding */ equals), +/* harmony export */ "format": () => (/* binding */ format), +/* harmony export */ "getWorldsAway": () => (/* binding */ getWorldsAway), +/* harmony export */ "rotate": () => (/* binding */ rotate), +/* harmony export */ "scale": () => (/* binding */ scale), +/* harmony export */ "squaredDistance": () => (/* binding */ squaredDistance), +/* harmony export */ "squaredDistanceToSegment": () => (/* binding */ squaredDistanceToSegment), +/* harmony export */ "toStringHDMS": () => (/* binding */ toStringHDMS), +/* harmony export */ "toStringXY": () => (/* binding */ toStringXY), +/* harmony export */ "wrapX": () => (/* binding */ wrapX) +/* harmony export */ }); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./math.js */ "./node_modules/@biigle/ol/math.js"); +/* harmony import */ var _string_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./string.js */ "./node_modules/@biigle/ol/string.js"); +/** + * @module ol/coordinate + */ + + + + +/** + * An array of numbers representing an `xy`, `xyz` or `xyzm` coordinate. + * Example: `[16, 48]`. + * @typedef {Array} Coordinate + * @api + */ + +/** + * A function that takes a {@link module:ol/coordinate~Coordinate} and + * transforms it into a `{string}`. + * + * @typedef {function((Coordinate|undefined)): string} CoordinateFormat + * @api + */ + +/** + * Add `delta` to `coordinate`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * import {add} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * add(coord, [-2, 4]); + * // coord is now [5.85, 51.983333] + * + * @param {Coordinate} coordinate Coordinate. + * @param {Coordinate} delta Delta. + * @return {Coordinate} The input coordinate adjusted by + * the given delta. + * @api + */ +function add(coordinate, delta) { + coordinate[0] += +delta[0]; + coordinate[1] += +delta[1]; + return coordinate; +} + +/** + * Calculates the point closest to the passed coordinate on the passed circle. + * + * @param {Coordinate} coordinate The coordinate. + * @param {import("./geom/Circle.js").default} circle The circle. + * @return {Coordinate} Closest point on the circumference. + */ +function closestOnCircle(coordinate, circle) { + const r = circle.getRadius(); + const center = circle.getCenter(); + const x0 = center[0]; + const y0 = center[1]; + const x1 = coordinate[0]; + const y1 = coordinate[1]; + + let dx = x1 - x0; + const dy = y1 - y0; + if (dx === 0 && dy === 0) { + dx = 1; + } + const d = Math.sqrt(dx * dx + dy * dy); + + const x = x0 + (r * dx) / d; + const y = y0 + (r * dy) / d; + + return [x, y]; +} + +/** + * Calculates the point closest to the passed coordinate on the passed segment. + * This is the foot of the perpendicular of the coordinate to the segment when + * the foot is on the segment, or the closest segment coordinate when the foot + * is outside the segment. + * + * @param {Coordinate} coordinate The coordinate. + * @param {Array} segment The two coordinates + * of the segment. + * @return {Coordinate} The foot of the perpendicular of + * the coordinate to the segment. + */ +function closestOnSegment(coordinate, segment) { + const x0 = coordinate[0]; + const y0 = coordinate[1]; + const start = segment[0]; + const end = segment[1]; + const x1 = start[0]; + const y1 = start[1]; + const x2 = end[0]; + const y2 = end[1]; + const dx = x2 - x1; + const dy = y2 - y1; + const along = + dx === 0 && dy === 0 + ? 0 + : (dx * (x0 - x1) + dy * (y0 - y1)) / (dx * dx + dy * dy || 0); + let x, y; + if (along <= 0) { + x = x1; + y = y1; + } else if (along >= 1) { + x = x2; + y = y2; + } else { + x = x1 + along * dx; + y = y1 + along * dy; + } + return [x, y]; +} + +/** + * Returns a {@link module:ol/coordinate~CoordinateFormat} function that can be + * used to format + * a {Coordinate} to a string. + * + * Example without specifying the fractional digits: + * + * import {createStringXY} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const stringifyFunc = createStringXY(); + * const out = stringifyFunc(coord); + * // out is now '8, 48' + * + * Example with explicitly specifying 2 fractional digits: + * + * import {createStringXY} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const stringifyFunc = createStringXY(2); + * const out = stringifyFunc(coord); + * // out is now '7.85, 47.98' + * + * @param {number} [fractionDigits] The number of digits to include + * after the decimal point. Default is `0`. + * @return {CoordinateFormat} Coordinate format. + * @api + */ +function createStringXY(fractionDigits) { + return ( + /** + * @param {Coordinate} coordinate Coordinate. + * @return {string} String XY. + */ + function (coordinate) { + return toStringXY(coordinate, fractionDigits); + } + ); +} + +/** + * @param {string} hemispheres Hemispheres. + * @param {number} degrees Degrees. + * @param {number} [fractionDigits] The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} String. + */ +function degreesToStringHDMS(hemispheres, degrees, fractionDigits) { + const normalizedDegrees = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.modulo)(degrees + 180, 360) - 180; + const x = Math.abs(3600 * normalizedDegrees); + const decimals = fractionDigits || 0; + + let deg = Math.floor(x / 3600); + let min = Math.floor((x - deg * 3600) / 60); + let sec = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.toFixed)(x - deg * 3600 - min * 60, decimals); + + if (sec >= 60) { + sec = 0; + min += 1; + } + + if (min >= 60) { + min = 0; + deg += 1; + } + + let hdms = deg + '\u00b0'; + if (min !== 0 || sec !== 0) { + hdms += ' ' + (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.padNumber)(min, 2) + '\u2032'; + } + if (sec !== 0) { + hdms += ' ' + (0,_string_js__WEBPACK_IMPORTED_MODULE_1__.padNumber)(sec, 2, decimals) + '\u2033'; + } + if (normalizedDegrees !== 0) { + hdms += ' ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0); + } + + return hdms; +} + +/** + * Transforms the given {@link module:ol/coordinate~Coordinate} to a string + * using the given string template. The strings `{x}` and `{y}` in the template + * will be replaced with the first and second coordinate values respectively. + * + * Example without specifying the fractional digits: + * + * import {format} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const template = 'Coordinate is ({x}|{y}).'; + * const out = format(coord, template); + * // out is now 'Coordinate is (8|48).' + * + * Example explicitly specifying the fractional digits: + * + * import {format} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const template = 'Coordinate is ({x}|{y}).'; + * const out = format(coord, template, 2); + * // out is now 'Coordinate is (7.85|47.98).' + * + * @param {Coordinate} coordinate Coordinate. + * @param {string} template A template string with `{x}` and `{y}` placeholders + * that will be replaced by first and second coordinate values. + * @param {number} [fractionDigits] The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Formatted coordinate. + * @api + */ +function format(coordinate, template, fractionDigits) { + if (coordinate) { + return template + .replace('{x}', coordinate[0].toFixed(fractionDigits)) + .replace('{y}', coordinate[1].toFixed(fractionDigits)); + } + return ''; +} + +/** + * @param {Coordinate} coordinate1 First coordinate. + * @param {Coordinate} coordinate2 Second coordinate. + * @return {boolean} The two coordinates are equal. + */ +function equals(coordinate1, coordinate2) { + let equals = true; + for (let i = coordinate1.length - 1; i >= 0; --i) { + if (coordinate1[i] != coordinate2[i]) { + equals = false; + break; + } + } + return equals; +} + +/** + * Rotate `coordinate` by `angle`. `coordinate` is modified in place and + * returned by the function. + * + * Example: + * + * import {rotate} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const rotateRadians = Math.PI / 2; // 90 degrees + * rotate(coord, rotateRadians); + * // coord is now [-47.983333, 7.85] + * + * @param {Coordinate} coordinate Coordinate. + * @param {number} angle Angle in radian. + * @return {Coordinate} Coordinate. + * @api + */ +function rotate(coordinate, angle) { + const cosAngle = Math.cos(angle); + const sinAngle = Math.sin(angle); + const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle; + const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle; + coordinate[0] = x; + coordinate[1] = y; + return coordinate; +} + +/** + * Scale `coordinate` by `scale`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * import {scale as scaleCoordinate} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const scale = 1.2; + * scaleCoordinate(coord, scale); + * // coord is now [9.42, 57.5799996] + * + * @param {Coordinate} coordinate Coordinate. + * @param {number} scale Scale factor. + * @return {Coordinate} Coordinate. + */ +function scale(coordinate, scale) { + coordinate[0] *= scale; + coordinate[1] *= scale; + return coordinate; +} + +/** + * @param {Coordinate} coord1 First coordinate. + * @param {Coordinate} coord2 Second coordinate. + * @return {number} Squared distance between coord1 and coord2. + */ +function squaredDistance(coord1, coord2) { + const dx = coord1[0] - coord2[0]; + const dy = coord1[1] - coord2[1]; + return dx * dx + dy * dy; +} + +/** + * @param {Coordinate} coord1 First coordinate. + * @param {Coordinate} coord2 Second coordinate. + * @return {number} Distance between coord1 and coord2. + */ +function distance(coord1, coord2) { + return Math.sqrt(squaredDistance(coord1, coord2)); +} + +/** + * Calculate the squared distance from a coordinate to a line segment. + * + * @param {Coordinate} coordinate Coordinate of the point. + * @param {Array} segment Line segment (2 + * coordinates). + * @return {number} Squared distance from the point to the line segment. + */ +function squaredDistanceToSegment(coordinate, segment) { + return squaredDistance(coordinate, closestOnSegment(coordinate, segment)); +} + +/** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and + * seconds. + * + * Example without specifying fractional digits: + * + * import {toStringHDMS} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const out = toStringHDMS(coord); + * // out is now '47° 58′ 60″ N 7° 50′ 60″ E' + * + * Example explicitly specifying 1 fractional digit: + * + * import {toStringHDMS} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const out = toStringHDMS(coord, 1); + * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' + * + * @param {Coordinate} coordinate Coordinate. + * @param {number} [fractionDigits] The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Hemisphere, degrees, minutes and seconds. + * @api + */ +function toStringHDMS(coordinate, fractionDigits) { + if (coordinate) { + return ( + degreesToStringHDMS('NS', coordinate[1], fractionDigits) + + ' ' + + degreesToStringHDMS('EW', coordinate[0], fractionDigits) + ); + } + return ''; +} + +/** + * Format a coordinate as a comma delimited string. + * + * Example without specifying fractional digits: + * + * import {toStringXY} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const out = toStringXY(coord); + * // out is now '8, 48' + * + * Example explicitly specifying 1 fractional digit: + * + * import {toStringXY} from 'ol/coordinate.js'; + * + * const coord = [7.85, 47.983333]; + * const out = toStringXY(coord, 1); + * // out is now '7.8, 48.0' + * + * @param {Coordinate} coordinate Coordinate. + * @param {number} [fractionDigits] The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} XY. + * @api + */ +function toStringXY(coordinate, fractionDigits) { + return format(coordinate, '{x}, {y}', fractionDigits); +} + +/** + * Modifies the provided coordinate in-place to be within the real world + * extent. The lower projection extent boundary is inclusive, the upper one + * exclusive. + * + * @param {Coordinate} coordinate Coordinate. + * @param {import("./proj/Projection.js").default} projection Projection. + * @return {Coordinate} The coordinate within the real world extent. + */ +function wrapX(coordinate, projection) { + if (projection.canWrapX()) { + const worldWidth = (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.getWidth)(projection.getExtent()); + const worldsAway = getWorldsAway(coordinate, projection, worldWidth); + if (worldsAway) { + coordinate[0] -= worldsAway * worldWidth; + } + } + return coordinate; +} +/** + * @param {Coordinate} coordinate Coordinate. + * @param {import("./proj/Projection.js").default} projection Projection. + * @param {number} [sourceExtentWidth] Width of the source extent. + * @return {number} Offset in world widths. + */ +function getWorldsAway(coordinate, projection, sourceExtentWidth) { + const projectionExtent = projection.getExtent(); + let worldsAway = 0; + if ( + projection.canWrapX() && + (coordinate[0] < projectionExtent[0] || coordinate[0] > projectionExtent[2]) + ) { + sourceExtentWidth = sourceExtentWidth || (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.getWidth)(projectionExtent); + worldsAway = Math.floor( + (coordinate[0] - projectionExtent[0]) / sourceExtentWidth, + ); + } + return worldsAway; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/css.js": +/*!****************************************!*\ + !*** ./node_modules/@biigle/ol/css.js ***! + \****************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CLASS_COLLAPSED": () => (/* binding */ CLASS_COLLAPSED), +/* harmony export */ "CLASS_CONTROL": () => (/* binding */ CLASS_CONTROL), +/* harmony export */ "CLASS_HIDDEN": () => (/* binding */ CLASS_HIDDEN), +/* harmony export */ "CLASS_SELECTABLE": () => (/* binding */ CLASS_SELECTABLE), +/* harmony export */ "CLASS_UNSELECTABLE": () => (/* binding */ CLASS_UNSELECTABLE), +/* harmony export */ "CLASS_UNSUPPORTED": () => (/* binding */ CLASS_UNSUPPORTED), +/* harmony export */ "getFontParameters": () => (/* binding */ getFontParameters) +/* harmony export */ }); +/** + * @module ol/css + */ + +/** + * @typedef {Object} FontParameters + * @property {string} style Style. + * @property {string} variant Variant. + * @property {string} weight Weight. + * @property {string} size Size. + * @property {string} lineHeight LineHeight. + * @property {string} family Family. + * @property {Array} families Families. + */ + +/** + * The CSS class for hidden feature. + * + * @const + * @type {string} + */ +const CLASS_HIDDEN = 'ol-hidden'; + +/** + * The CSS class that we'll give the DOM elements to have them selectable. + * + * @const + * @type {string} + */ +const CLASS_SELECTABLE = 'ol-selectable'; + +/** + * The CSS class that we'll give the DOM elements to have them unselectable. + * + * @const + * @type {string} + */ +const CLASS_UNSELECTABLE = 'ol-unselectable'; + +/** + * The CSS class for unsupported feature. + * + * @const + * @type {string} + */ +const CLASS_UNSUPPORTED = 'ol-unsupported'; + +/** + * The CSS class for controls. + * + * @const + * @type {string} + */ +const CLASS_CONTROL = 'ol-control'; + +/** + * The CSS class that we'll give the DOM elements that are collapsed, i.e. + * to those elements which usually can be expanded. + * + * @const + * @type {string} + */ +const CLASS_COLLAPSED = 'ol-collapsed'; + +/** + * From https://stackoverflow.com/questions/10135697/regex-to-parse-any-css-font + * @type {RegExp} + */ +const fontRegEx = new RegExp( + [ + '^\\s*(?=(?:(?:[-a-z]+\\s*){0,2}(italic|oblique))?)', + '(?=(?:(?:[-a-z]+\\s*){0,2}(small-caps))?)', + '(?=(?:(?:[-a-z]+\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)', + '(?:(?:normal|\\1|\\2|\\3)\\s*){0,3}((?:xx?-)?', + '(?:small|large)|medium|smaller|larger|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx]))', + '(?:\\s*\\/\\s*(normal|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx])?))', + '?\\s*([-,\\"\\\'\\sa-z]+?)\\s*$', + ].join(''), + 'i', +); +/** @type {Array<'style'|'variant'|'weight'|'size'|'lineHeight'|'family'>} */ +const fontRegExMatchIndex = [ + 'style', + 'variant', + 'weight', + 'size', + 'lineHeight', + 'family', +]; + +/** + * Get the list of font families from a font spec. Note that this doesn't work + * for font families that have commas in them. + * @param {string} fontSpec The CSS font property. + * @return {FontParameters|null} The font parameters (or null if the input spec is invalid). + */ +const getFontParameters = function (fontSpec) { + const match = fontSpec.match(fontRegEx); + if (!match) { + return null; + } + const style = /** @type {FontParameters} */ ({ + lineHeight: 'normal', + size: '1.2em', + style: 'normal', + weight: 'normal', + variant: 'normal', + }); + for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) { + const value = match[i + 1]; + if (value !== undefined) { + style[fontRegExMatchIndex[i]] = value; + } + } + style.families = style.family.split(/,\s?/); + return style; +}; + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/dom.js": +/*!****************************************!*\ + !*** ./node_modules/@biigle/ol/dom.js ***! + \****************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "createCanvasContext2D": () => (/* binding */ createCanvasContext2D), +/* harmony export */ "getSharedCanvasContext2D": () => (/* binding */ getSharedCanvasContext2D), +/* harmony export */ "outerHeight": () => (/* binding */ outerHeight), +/* harmony export */ "outerWidth": () => (/* binding */ outerWidth), +/* harmony export */ "releaseCanvas": () => (/* binding */ releaseCanvas), +/* harmony export */ "removeChildren": () => (/* binding */ removeChildren), +/* harmony export */ "removeNode": () => (/* binding */ removeNode), +/* harmony export */ "replaceChildren": () => (/* binding */ replaceChildren), +/* harmony export */ "replaceNode": () => (/* binding */ replaceNode) +/* harmony export */ }); +/* harmony import */ var _has_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./has.js */ "./node_modules/@biigle/ol/has.js"); + + +/** + * @module ol/dom + */ + +//FIXME Move this function to the canvas module +/** + * Create an html canvas element and returns its 2d context. + * @param {number} [width] Canvas width. + * @param {number} [height] Canvas height. + * @param {Array} [canvasPool] Canvas pool to take existing canvas from. + * @param {CanvasRenderingContext2DSettings} [settings] CanvasRenderingContext2DSettings + * @return {CanvasRenderingContext2D} The context. + */ +function createCanvasContext2D(width, height, canvasPool, settings) { + /** @type {HTMLCanvasElement|OffscreenCanvas} */ + let canvas; + if (canvasPool && canvasPool.length) { + canvas = /** @type {HTMLCanvasElement} */ (canvasPool.shift()); + } else if (_has_js__WEBPACK_IMPORTED_MODULE_0__.WORKER_OFFSCREEN_CANVAS) { + canvas = new OffscreenCanvas(width || 300, height || 300); + } else { + canvas = document.createElement('canvas'); + } + if (width) { + canvas.width = width; + } + if (height) { + canvas.height = height; + } + //FIXME Allow OffscreenCanvasRenderingContext2D as return type + return /** @type {CanvasRenderingContext2D} */ ( + canvas.getContext('2d', settings) + ); +} + +/** @type {CanvasRenderingContext2D} */ +let sharedCanvasContext; + +/** + * @return {CanvasRenderingContext2D} Shared canvas context. + */ +function getSharedCanvasContext2D() { + if (!sharedCanvasContext) { + sharedCanvasContext = createCanvasContext2D(1, 1); + } + return sharedCanvasContext; +} + +/** + * Releases canvas memory to avoid exceeding memory limits in Safari. + * See https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/ + * @param {CanvasRenderingContext2D} context Context. + */ +function releaseCanvas(context) { + const canvas = context.canvas; + canvas.width = 1; + canvas.height = 1; + context.clearRect(0, 0, 1, 1); +} + +/** + * Get the current computed width for the given element including margin, + * padding and border. + * Equivalent to jQuery's `$(el).outerWidth(true)`. + * @param {!HTMLElement} element Element. + * @return {number} The width. + */ +function outerWidth(element) { + let width = element.offsetWidth; + const style = getComputedStyle(element); + width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10); + + return width; +} + +/** + * Get the current computed height for the given element including margin, + * padding and border. + * Equivalent to jQuery's `$(el).outerHeight(true)`. + * @param {!HTMLElement} element Element. + * @return {number} The height. + */ +function outerHeight(element) { + let height = element.offsetHeight; + const style = getComputedStyle(element); + height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10); + + return height; +} + +/** + * @param {Node} newNode Node to replace old node + * @param {Node} oldNode The node to be replaced + */ +function replaceNode(newNode, oldNode) { + const parent = oldNode.parentNode; + if (parent) { + parent.replaceChild(newNode, oldNode); + } +} + +/** + * @param {Node} node The node to remove. + * @return {Node|null} The node that was removed or null. + */ +function removeNode(node) { + return node && node.parentNode ? node.parentNode.removeChild(node) : null; +} + +/** + * @param {Node} node The node to remove the children from. + */ +function removeChildren(node) { + while (node.lastChild) { + node.removeChild(node.lastChild); + } +} + +/** + * Transform the children of a parent node so they match the + * provided list of children. This function aims to efficiently + * remove, add, and reorder child nodes while maintaining a simple + * implementation (it is not guaranteed to minimize DOM operations). + * @param {Node} node The parent node whose children need reworking. + * @param {Array} children The desired children. + */ +function replaceChildren(node, children) { + const oldChildren = node.childNodes; + + for (let i = 0; true; ++i) { + const oldChild = oldChildren[i]; + const newChild = children[i]; + + // check if our work is done + if (!oldChild && !newChild) { + break; + } + + // check if children match + if (oldChild === newChild) { + continue; + } + + // check if a new child needs to be added + if (!oldChild) { + node.appendChild(newChild); + continue; + } + + // check if an old child needs to be removed + if (!newChild) { + node.removeChild(oldChild); + --i; + continue; + } + + // reorder + node.insertBefore(newChild, oldChild); + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/easing.js": +/*!*******************************************!*\ + !*** ./node_modules/@biigle/ol/easing.js ***! + \*******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "easeIn": () => (/* binding */ easeIn), +/* harmony export */ "easeOut": () => (/* binding */ easeOut), +/* harmony export */ "inAndOut": () => (/* binding */ inAndOut), +/* harmony export */ "linear": () => (/* binding */ linear), +/* harmony export */ "upAndDown": () => (/* binding */ upAndDown) +/* harmony export */ }); +/** + * @module ol/easing + */ + +/** + * Start slow and speed up. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ +function easeIn(t) { + return Math.pow(t, 3); +} + +/** + * Start fast and slow down. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ +function easeOut(t) { + return 1 - easeIn(1 - t); +} + +/** + * Start slow, speed up, and then slow down again. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ +function inAndOut(t) { + return 3 * t * t - 2 * t * t * t; +} + +/** + * Maintain a constant speed over time. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ +function linear(t) { + return t; +} + +/** + * Start slow, speed up, and at the very end slow down again. This has the + * same general behavior as {@link module:ol/easing.inAndOut}, but the final + * slowdown is delayed. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ +function upAndDown(t) { + if (t < 0.5) { + return inAndOut(2 * t); + } + return 1 - inAndOut(2 * (t - 0.5)); +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/events.js": +/*!*******************************************!*\ + !*** ./node_modules/@biigle/ol/events.js ***! + \*******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "listen": () => (/* binding */ listen), +/* harmony export */ "listenOnce": () => (/* binding */ listenOnce), +/* harmony export */ "unlistenByKey": () => (/* binding */ unlistenByKey) +/* harmony export */ }); +/* harmony import */ var _obj_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./obj.js */ "./node_modules/@biigle/ol/obj.js"); +/** + * @module ol/events + */ + + +/** + * Key to use with {@link module:ol/Observable.unByKey}. + * @typedef {Object} EventsKey + * @property {ListenerFunction} listener Listener. + * @property {import("./events/Target.js").EventTargetLike} target Target. + * @property {string} type Type. + * @api + */ + +/** + * Listener function. This function is called with an event object as argument. + * When the function returns `false`, event propagation will stop. + * + * @typedef {function((Event|import("./events/Event.js").default)): (void|boolean)} ListenerFunction + * @api + */ + +/** + * @typedef {Object} ListenerObject + * @property {ListenerFunction} handleEvent HandleEvent listener function. + */ + +/** + * @typedef {ListenerFunction|ListenerObject} Listener + */ + +/** + * Registers an event listener on an event target. Inspired by + * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html + * + * This function efficiently binds a `listener` to a `this` object, and returns + * a key for use with {@link module:ol/events.unlistenByKey}. + * + * @param {import("./events/Target.js").EventTargetLike} target Event target. + * @param {string} type Event type. + * @param {ListenerFunction} listener Listener. + * @param {Object} [thisArg] Object referenced by the `this` keyword in the + * listener. Default is the `target`. + * @param {boolean} [once] If true, add the listener as one-off listener. + * @return {EventsKey} Unique key for the listener. + */ +function listen(target, type, listener, thisArg, once) { + if (thisArg && thisArg !== target) { + listener = listener.bind(thisArg); + } + if (once) { + const originalListener = listener; + listener = function () { + target.removeEventListener(type, listener); + originalListener.apply(this, arguments); + }; + } + const eventsKey = { + target: target, + type: type, + listener: listener, + }; + target.addEventListener(type, listener); + return eventsKey; +} + +/** + * Registers a one-off event listener on an event target. Inspired by + * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html + * + * This function efficiently binds a `listener` as self-unregistering listener + * to a `this` object, and returns a key for use with + * {@link module:ol/events.unlistenByKey} in case the listener needs to be + * unregistered before it is called. + * + * When {@link module:ol/events.listen} is called with the same arguments after this + * function, the self-unregistering listener will be turned into a permanent + * listener. + * + * @param {import("./events/Target.js").EventTargetLike} target Event target. + * @param {string} type Event type. + * @param {ListenerFunction} listener Listener. + * @param {Object} [thisArg] Object referenced by the `this` keyword in the + * listener. Default is the `target`. + * @return {EventsKey} Key for unlistenByKey. + */ +function listenOnce(target, type, listener, thisArg) { + return listen(target, type, listener, thisArg, true); +} + +/** + * Unregisters event listeners on an event target. Inspired by + * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html + * + * The argument passed to this function is the key returned from + * {@link module:ol/events.listen} or {@link module:ol/events.listenOnce}. + * + * @param {EventsKey} key The key. + */ +function unlistenByKey(key) { + if (key && key.target) { + key.target.removeEventListener(key.type, key.listener); + (0,_obj_js__WEBPACK_IMPORTED_MODULE_0__.clear)(key); + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/events/Event.js": +/*!*************************************************!*\ + !*** ./node_modules/@biigle/ol/events/Event.js ***! + \*************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "preventDefault": () => (/* binding */ preventDefault), +/* harmony export */ "stopPropagation": () => (/* binding */ stopPropagation) +/* harmony export */ }); +/** + * @module ol/events/Event + */ + +/** + * @classdesc + * Stripped down implementation of the W3C DOM Level 2 Event interface. + * See https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface. + * + * This implementation only provides `type` and `target` properties, and + * `stopPropagation` and `preventDefault` methods. It is meant as base class + * for higher level events defined in the library, and works with + * {@link module:ol/events/Target~Target}. + */ +class BaseEvent { + /** + * @param {string} type Type. + */ + constructor(type) { + /** + * @type {boolean} + */ + this.propagationStopped; + + /** + * @type {boolean} + */ + this.defaultPrevented; + + /** + * The event type. + * @type {string} + * @api + */ + this.type = type; + + /** + * The event target. + * @type {Object} + * @api + */ + this.target = null; + } + + /** + * Prevent default. This means that no emulated `click`, `singleclick` or `doubleclick` events + * will be fired. + * @api + */ + preventDefault() { + this.defaultPrevented = true; + } + + /** + * Stop event propagation. + * @api + */ + stopPropagation() { + this.propagationStopped = true; + } +} + +/** + * @param {Event|import("./Event.js").default} evt Event + */ +function stopPropagation(evt) { + evt.stopPropagation(); +} + +/** + * @param {Event|import("./Event.js").default} evt Event + */ +function preventDefault(evt) { + evt.preventDefault(); +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BaseEvent); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/events/EventType.js": +/*!*****************************************************!*\ + !*** ./node_modules/@biigle/ol/events/EventType.js ***! + \*****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/events/EventType + */ + +/** + * @enum {string} + * @const + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + /** + * Generic change event. Triggered when the revision counter is increased. + * @event module:ol/events/Event~BaseEvent#change + * @api + */ + CHANGE: 'change', + + /** + * Generic error event. Triggered when an error occurs. + * @event module:ol/events/Event~BaseEvent#error + * @api + */ + ERROR: 'error', + + BLUR: 'blur', + CLEAR: 'clear', + CONTEXTMENU: 'contextmenu', + CLICK: 'click', + DBLCLICK: 'dblclick', + DRAGENTER: 'dragenter', + DRAGOVER: 'dragover', + DROP: 'drop', + FOCUS: 'focus', + KEYDOWN: 'keydown', + KEYPRESS: 'keypress', + LOAD: 'load', + RESIZE: 'resize', + TOUCHMOVE: 'touchmove', + WHEEL: 'wheel', +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/events/Target.js": +/*!**************************************************!*\ + !*** ./node_modules/@biigle/ol/events/Target.js ***! + \**************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Disposable_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Disposable.js */ "./node_modules/@biigle/ol/Disposable.js"); +/* harmony import */ var _Event_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Event.js */ "./node_modules/@biigle/ol/events/Event.js"); +/* harmony import */ var _functions_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../functions.js */ "./node_modules/@biigle/ol/functions.js"); +/* harmony import */ var _obj_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../obj.js */ "./node_modules/@biigle/ol/obj.js"); +/** + * @module ol/events/Target + */ + + + + + +/** + * @typedef {EventTarget|Target} EventTargetLike + */ + +/** + * @classdesc + * A simplified implementation of the W3C DOM Level 2 EventTarget interface. + * See https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget. + * + * There are two important simplifications compared to the specification: + * + * 1. The handling of `useCapture` in `addEventListener` and + * `removeEventListener`. There is no real capture model. + * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`. + * There is no event target hierarchy. When a listener calls + * `stopPropagation` or `preventDefault` on an event object, it means that no + * more listeners after this one will be called. Same as when the listener + * returns false. + */ +class Target extends _Disposable_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {*} [target] Default event target for dispatched events. + */ + constructor(target) { + super(); + + /** + * @private + * @type {*} + */ + this.eventTarget_ = target; + + /** + * @private + * @type {Object|null} + */ + this.pendingRemovals_ = null; + + /** + * @private + * @type {Object|null} + */ + this.dispatching_ = null; + + /** + * @private + * @type {Object>|null} + */ + this.listeners_ = null; + } + + /** + * @param {string} type Type. + * @param {import("../events.js").Listener} listener Listener. + */ + addEventListener(type, listener) { + if (!type || !listener) { + return; + } + const listeners = this.listeners_ || (this.listeners_ = {}); + const listenersForType = listeners[type] || (listeners[type] = []); + if (!listenersForType.includes(listener)) { + listenersForType.push(listener); + } + } + + /** + * Dispatches an event and calls all listeners listening for events + * of this type. The event parameter can either be a string or an + * Object with a `type` property. + * + * @param {import("./Event.js").default|string} event Event object. + * @return {boolean|undefined} `false` if anyone called preventDefault on the + * event object or if any of the listeners returned false. + * @api + */ + dispatchEvent(event) { + const isString = typeof event === 'string'; + const type = isString ? event : event.type; + const listeners = this.listeners_ && this.listeners_[type]; + if (!listeners) { + return; + } + + const evt = isString ? new _Event_js__WEBPACK_IMPORTED_MODULE_1__["default"](event) : /** @type {Event} */ (event); + if (!evt.target) { + evt.target = this.eventTarget_ || this; + } + const dispatching = this.dispatching_ || (this.dispatching_ = {}); + const pendingRemovals = + this.pendingRemovals_ || (this.pendingRemovals_ = {}); + if (!(type in dispatching)) { + dispatching[type] = 0; + pendingRemovals[type] = 0; + } + ++dispatching[type]; + let propagate; + for (let i = 0, ii = listeners.length; i < ii; ++i) { + if ('handleEvent' in listeners[i]) { + propagate = /** @type {import("../events.js").ListenerObject} */ ( + listeners[i] + ).handleEvent(evt); + } else { + propagate = /** @type {import("../events.js").ListenerFunction} */ ( + listeners[i] + ).call(this, evt); + } + if (propagate === false || evt.propagationStopped) { + propagate = false; + break; + } + } + if (--dispatching[type] === 0) { + let pr = pendingRemovals[type]; + delete pendingRemovals[type]; + while (pr--) { + this.removeEventListener(type, _functions_js__WEBPACK_IMPORTED_MODULE_2__.VOID); + } + delete dispatching[type]; + } + return propagate; + } + + /** + * Clean up. + */ + disposeInternal() { + this.listeners_ && (0,_obj_js__WEBPACK_IMPORTED_MODULE_3__.clear)(this.listeners_); + } + + /** + * Get the listeners for a specified event type. Listeners are returned in the + * order that they will be called in. + * + * @param {string} type Type. + * @return {Array|undefined} Listeners. + */ + getListeners(type) { + return (this.listeners_ && this.listeners_[type]) || undefined; + } + + /** + * @param {string} [type] Type. If not provided, + * `true` will be returned if this event target has any listeners. + * @return {boolean} Has listeners. + */ + hasListener(type) { + if (!this.listeners_) { + return false; + } + return type + ? type in this.listeners_ + : Object.keys(this.listeners_).length > 0; + } + + /** + * @param {string} type Type. + * @param {import("../events.js").Listener} listener Listener. + */ + removeEventListener(type, listener) { + if (!this.listeners_) { + return; + } + const listeners = this.listeners_[type]; + if (!listeners) { + return; + } + const index = listeners.indexOf(listener); + if (index !== -1) { + if (this.pendingRemovals_ && type in this.pendingRemovals_) { + // make listener a no-op, and remove later in #dispatchEvent() + listeners[index] = _functions_js__WEBPACK_IMPORTED_MODULE_2__.VOID; + ++this.pendingRemovals_[type]; + } else { + listeners.splice(index, 1); + if (listeners.length === 0) { + delete this.listeners_[type]; + } + } + } + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Target); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/expr/cpu.js": +/*!*********************************************!*\ + !*** ./node_modules/@biigle/ol/expr/cpu.js ***! + \*********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "buildExpression": () => (/* binding */ buildExpression), +/* harmony export */ "newEvaluationContext": () => (/* binding */ newEvaluationContext) +/* harmony export */ }); +/* harmony import */ var _expression_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./expression.js */ "./node_modules/@biigle/ol/expr/expression.js"); +/* harmony import */ var _color_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../color.js */ "./node_modules/@biigle/ol/color.js"); +/** + * @module ol/expr/cpu + */ + + + + +/** + * @fileoverview This module includes functions to build expressions for evaluation on the CPU. + * Building is composed of two steps: parsing and compiling. The parsing step takes an encoded + * expression and returns an instance of one of the expression classes. The compiling step takes + * the expression instance and returns a function that can be evaluated in to return a literal + * value. The evaluator function should do as little allocation and work as possible. + */ + +/** + * @typedef {Object} EvaluationContext + * @property {Object} properties The values for properties used in 'get' expressions. + * @property {Object} variables The values for variables used in 'var' expressions. + * @property {number} resolution The map resolution. + * @property {string|number|null} featureId The feature id. + * @property {string} geometryType Geometry type of the current object. + */ + +/** + * @return {EvaluationContext} A new evaluation context. + */ +function newEvaluationContext() { + return { + variables: {}, + properties: {}, + resolution: NaN, + featureId: null, + geometryType: '', + }; +} + +/** + * @typedef {function(EvaluationContext):import("./expression.js").LiteralValue} ExpressionEvaluator + */ + +/** + * @typedef {function(EvaluationContext):boolean} BooleanEvaluator + */ + +/** + * @typedef {function(EvaluationContext):number} NumberEvaluator + */ + +/** + * @typedef {function(EvaluationContext):string} StringEvaluator + */ + +/** + * @typedef {function(EvaluationContext):(Array|string)} ColorLikeEvaluator + */ + +/** + * @typedef {function(EvaluationContext):Array} NumberArrayEvaluator + */ + +/** + * @typedef {function(EvaluationContext):Array} CoordinateEvaluator + */ + +/** + * @typedef {function(EvaluationContext):(Array)} SizeEvaluator + */ + +/** + * @typedef {function(EvaluationContext):(Array|number)} SizeLikeEvaluator + */ + +/** + * @param {import('./expression.js').EncodedExpression} encoded The encoded expression. + * @param {number} type The expected type. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The expression evaluator. + */ +function buildExpression(encoded, type, context) { + const expression = (0,_expression_js__WEBPACK_IMPORTED_MODULE_0__.parse)(encoded, context); + if (!(0,_expression_js__WEBPACK_IMPORTED_MODULE_0__.overlapsType)(type, expression.type)) { + const expected = (0,_expression_js__WEBPACK_IMPORTED_MODULE_0__.typeName)(type); + const actual = (0,_expression_js__WEBPACK_IMPORTED_MODULE_0__.typeName)(expression.type); + throw new Error( + `Expected expression to be of type ${expected}, got ${actual}`, + ); + } + return compileExpression(expression, context); +} + +/** + * @param {import("./expression.js").Expression} expression The expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileExpression(expression, context) { + if (expression instanceof _expression_js__WEBPACK_IMPORTED_MODULE_0__.LiteralExpression) { + // convert colors to array if possible + if (expression.type === _expression_js__WEBPACK_IMPORTED_MODULE_0__.ColorType && typeof expression.value === 'string') { + const colorValue = (0,_color_js__WEBPACK_IMPORTED_MODULE_1__.fromString)(expression.value); + return function () { + return colorValue; + }; + } + return function () { + return expression.value; + }; + } + const operator = expression.operator; + switch (operator) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Number: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.String: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Coalesce: { + return compileAssertionExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Get: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Var: { + return compileAccessorExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Id: { + return (context) => context.featureId; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.GeometryType: { + return (context) => context.geometryType; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Concat: { + const args = expression.args.map((e) => compileExpression(e, context)); + return (context) => + ''.concat(...args.map((arg) => arg(context).toString())); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Resolution: { + return (context) => context.resolution; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Any: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.All: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Between: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.In: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Not: { + return compileLogicalExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Equal: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.NotEqual: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.LessThan: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.LessThanOrEqualTo: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.GreaterThan: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.GreaterThanOrEqualTo: { + return compileComparisonExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Multiply: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Divide: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Add: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Subtract: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Clamp: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Mod: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Pow: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Abs: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Floor: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Ceil: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Round: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Sin: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Cos: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Atan: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Sqrt: { + return compileNumericExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Case: { + return compileCaseExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Match: { + return compileMatchExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Interpolate: { + return compileInterpolateExpression(expression, context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.ToString: { + return compileConvertExpression(expression, context); + } + default: { + throw new Error(`Unsupported operator ${operator}`); + } + // TODO: unimplemented + // Ops.Zoom + // Ops.Time + // Ops.Array + // Ops.Color + // Ops.Band + // Ops.Palette + } +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileAssertionExpression(expression, context) { + const type = expression.operator; + const length = expression.args.length; + + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + switch (type) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Coalesce: { + return (context) => { + for (let i = 0; i < length; ++i) { + const value = args[i](context); + if (typeof value !== 'undefined' && value !== null) { + return value; + } + } + throw new Error('Expected one of the values to be non-null'); + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Number: + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.String: { + return (context) => { + for (let i = 0; i < length; ++i) { + const value = args[i](context); + if (typeof value === type) { + return value; + } + } + throw new Error(`Expected one of the values to be a ${type}`); + }; + } + default: { + throw new Error(`Unsupported assertion operator ${type}`); + } + } +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileAccessorExpression(expression, context) { + const nameExpression = /** @type {LiteralExpression} */ (expression.args[0]); + const name = /** @type {string} */ (nameExpression.value); + switch (expression.operator) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Get: { + return (context) => context.properties[name]; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Var: { + return (context) => context.variables[name]; + } + default: { + throw new Error(`Unsupported accessor operator ${expression.operator}`); + } + } +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {BooleanEvaluator} The evaluator function. + */ +function compileComparisonExpression(expression, context) { + const op = expression.operator; + const left = compileExpression(expression.args[0], context); + const right = compileExpression(expression.args[1], context); + switch (op) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Equal: { + return (context) => left(context) === right(context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.NotEqual: { + return (context) => left(context) !== right(context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.LessThan: { + return (context) => left(context) < right(context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.LessThanOrEqualTo: { + return (context) => left(context) <= right(context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.GreaterThan: { + return (context) => left(context) > right(context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.GreaterThanOrEqualTo: { + return (context) => left(context) >= right(context); + } + default: { + throw new Error(`Unsupported comparison operator ${op}`); + } + } +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {BooleanEvaluator} The evaluator function. + */ +function compileLogicalExpression(expression, context) { + const op = expression.operator; + const length = expression.args.length; + + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + switch (op) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Any: { + return (context) => { + for (let i = 0; i < length; ++i) { + if (args[i](context)) { + return true; + } + } + return false; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.All: { + return (context) => { + for (let i = 0; i < length; ++i) { + if (!args[i](context)) { + return false; + } + } + return true; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Between: { + return (context) => { + const value = args[0](context); + const min = args[1](context); + const max = args[2](context); + return value >= min && value <= max; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.In: { + return (context) => { + const value = args[0](context); + for (let i = 1; i < length; ++i) { + if (value === args[i](context)) { + return true; + } + } + return false; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Not: { + return (context) => !args[0](context); + } + default: { + throw new Error(`Unsupported logical operator ${op}`); + } + } +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {NumberEvaluator} The evaluator function. + */ +function compileNumericExpression(expression, context) { + const op = expression.operator; + const length = expression.args.length; + + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + switch (op) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Multiply: { + return (context) => { + let value = 1; + for (let i = 0; i < length; ++i) { + value *= args[i](context); + } + return value; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Divide: { + return (context) => args[0](context) / args[1](context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Add: { + return (context) => { + let value = 0; + for (let i = 0; i < length; ++i) { + value += args[i](context); + } + return value; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Subtract: { + return (context) => args[0](context) - args[1](context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Clamp: { + return (context) => { + const value = args[0](context); + const min = args[1](context); + if (value < min) { + return min; + } + const max = args[2](context); + if (value > max) { + return max; + } + return value; + }; + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Mod: { + return (context) => args[0](context) % args[1](context); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Pow: { + return (context) => Math.pow(args[0](context), args[1](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Abs: { + return (context) => Math.abs(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Floor: { + return (context) => Math.floor(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Ceil: { + return (context) => Math.ceil(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Round: { + return (context) => Math.round(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Sin: { + return (context) => Math.sin(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Cos: { + return (context) => Math.cos(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Atan: { + if (length === 2) { + return (context) => Math.atan2(args[0](context), args[1](context)); + } + return (context) => Math.atan(args[0](context)); + } + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.Sqrt: { + return (context) => Math.sqrt(args[0](context)); + } + default: { + throw new Error(`Unsupported numeric operator ${op}`); + } + } +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileCaseExpression(expression, context) { + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + return (context) => { + for (let i = 0; i < length - 1; i += 2) { + const condition = args[i](context); + if (condition) { + return args[i + 1](context); + } + } + return args[length - 1](context); + }; +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileMatchExpression(expression, context) { + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + return (context) => { + const value = args[0](context); + for (let i = 1; i < length; i += 2) { + if (value === args[i](context)) { + return args[i + 1](context); + } + } + return args[length - 1](context); + }; +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileInterpolateExpression(expression, context) { + const length = expression.args.length; + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + return (context) => { + const base = args[0](context); + const value = args[1](context); + + let previousInput; + let previousOutput; + for (let i = 2; i < length; i += 2) { + const input = args[i](context); + let output = args[i + 1](context); + const isColor = Array.isArray(output); + if (isColor) { + output = (0,_color_js__WEBPACK_IMPORTED_MODULE_1__.withAlpha)(output); + } + if (input >= value) { + if (i === 2) { + return output; + } + if (isColor) { + return interpolateColor( + base, + value, + previousInput, + previousOutput, + input, + output, + ); + } + return interpolateNumber( + base, + value, + previousInput, + previousOutput, + input, + output, + ); + } + previousInput = input; + previousOutput = output; + } + return previousOutput; + }; +} + +/** + * @param {import('./expression.js').CallExpression} expression The call expression. + * @param {import('./expression.js').ParsingContext} context The parsing context. + * @return {ExpressionEvaluator} The evaluator function. + */ +function compileConvertExpression(expression, context) { + const op = expression.operator; + const length = expression.args.length; + + const args = new Array(length); + for (let i = 0; i < length; ++i) { + args[i] = compileExpression(expression.args[i], context); + } + switch (op) { + case _expression_js__WEBPACK_IMPORTED_MODULE_0__.Ops.ToString: { + return (context) => { + const value = args[0](context); + if (expression.args[0].type === _expression_js__WEBPACK_IMPORTED_MODULE_0__.ColorType) { + return (0,_color_js__WEBPACK_IMPORTED_MODULE_1__.toString)(value); + } + return value.toString(); + }; + } + default: { + throw new Error(`Unsupported convert operator ${op}`); + } + } +} + +/** + * @param {number} base The base. + * @param {number} value The value. + * @param {number} input1 The first input value. + * @param {number} output1 The first output value. + * @param {number} input2 The second input value. + * @param {number} output2 The second output value. + * @return {number} The interpolated value. + */ +function interpolateNumber(base, value, input1, output1, input2, output2) { + const delta = input2 - input1; + if (delta === 0) { + return output1; + } + const along = value - input1; + const factor = + base === 1 + ? along / delta + : (Math.pow(base, along) - 1) / (Math.pow(base, delta) - 1); + return output1 + factor * (output2 - output1); +} + +/** + * @param {number} base The base. + * @param {number} value The value. + * @param {number} input1 The first input value. + * @param {import('../color.js').Color} rgba1 The first output value. + * @param {number} input2 The second input value. + * @param {import('../color.js').Color} rgba2 The second output value. + * @return {import('../color.js').Color} The interpolated color. + */ +function interpolateColor(base, value, input1, rgba1, input2, rgba2) { + const delta = input2 - input1; + if (delta === 0) { + return rgba1; + } + const lcha1 = (0,_color_js__WEBPACK_IMPORTED_MODULE_1__.rgbaToLcha)(rgba1); + const lcha2 = (0,_color_js__WEBPACK_IMPORTED_MODULE_1__.rgbaToLcha)(rgba2); + let deltaHue = lcha2[2] - lcha1[2]; + if (deltaHue > 180) { + deltaHue -= 360; + } else if (deltaHue < -180) { + deltaHue += 360; + } + + const lcha = [ + interpolateNumber(base, value, input1, lcha1[0], input2, lcha2[0]), + interpolateNumber(base, value, input1, lcha1[1], input2, lcha2[1]), + lcha1[2] + interpolateNumber(base, value, input1, 0, input2, deltaHue), + interpolateNumber(base, value, input1, rgba1[3], input2, rgba2[3]), + ]; + return (0,_color_js__WEBPACK_IMPORTED_MODULE_1__.normalize)((0,_color_js__WEBPACK_IMPORTED_MODULE_1__.lchaToRgba)(lcha)); +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/expr/expression.js": +/*!****************************************************!*\ + !*** ./node_modules/@biigle/ol/expr/expression.js ***! + \****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "AnyType": () => (/* binding */ AnyType), +/* harmony export */ "BooleanType": () => (/* binding */ BooleanType), +/* harmony export */ "CallExpression": () => (/* binding */ CallExpression), +/* harmony export */ "ColorType": () => (/* binding */ ColorType), +/* harmony export */ "LiteralExpression": () => (/* binding */ LiteralExpression), +/* harmony export */ "NoneType": () => (/* binding */ NoneType), +/* harmony export */ "NumberArrayType": () => (/* binding */ NumberArrayType), +/* harmony export */ "NumberType": () => (/* binding */ NumberType), +/* harmony export */ "Ops": () => (/* binding */ Ops), +/* harmony export */ "SizeType": () => (/* binding */ SizeType), +/* harmony export */ "StringType": () => (/* binding */ StringType), +/* harmony export */ "computeGeometryType": () => (/* binding */ computeGeometryType), +/* harmony export */ "includesType": () => (/* binding */ includesType), +/* harmony export */ "isType": () => (/* binding */ isType), +/* harmony export */ "newParsingContext": () => (/* binding */ newParsingContext), +/* harmony export */ "overlapsType": () => (/* binding */ overlapsType), +/* harmony export */ "parse": () => (/* binding */ parse), +/* harmony export */ "typeName": () => (/* binding */ typeName) +/* harmony export */ }); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _color_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../color.js */ "./node_modules/@biigle/ol/color.js"); +/** + * @module ol/expr/expression + */ + + + +/** + * @fileoverview This module includes types and functions for parsing array encoded expressions. + * The result of parsing an encoded expression is one of the specific expression classes. + * During parsing, information is added to the parsing context about the data accessed by the + * expression. + */ + +/** + * Base type used for literal style parameters; can be a number literal or the output of an operator, + * which in turns takes {@link import("./expression.js").ExpressionValue} arguments. + * + * See below for details on the available operators (with notes for those that are WebGL or Canvas only). + * + * * Reading operators: + * * `['band', bandIndex, xOffset, yOffset]` For tile layers only. Fetches pixel values from band + * `bandIndex` of the source's data. The first `bandIndex` of the source data is `1`. Fetched values + * are in the 0..1 range. {@link import("../source/TileImage.js").default} sources have 4 bands: red, + * green, blue and alpha. {@link import("../source/DataTile.js").default} sources can have any number + * of bands, depending on the underlying data source and + * {@link import("../source/GeoTIFF.js").Options configuration}. `xOffset` and `yOffset` are optional + * and allow specifying pixel offsets for x and y. This is used for sampling data from neighboring pixels (WebGL only). + * * `['get', 'attributeName', typeHint]` fetches a feature property value, similar to `feature.get('attributeName')` + * A type hint can optionally be specified, in case the resulting expression contains a type ambiguity which + * will make it invalid. Type hints can be one of: 'string', 'color', 'number', 'boolean', 'number[]' + * * `['geometry-type']` returns a feature's geometry type as string, either: 'LineString', 'Point' or 'Polygon' + * `Multi*` values are returned as their singular equivalent + * `Circle` geometries are returned as 'Polygon' + * `GeometryCollection` geometries are returned as the type of the first geometry found in the collection (WebGL only). + * * `['resolution']` returns the current resolution + * * `['time']` The time in seconds since the creation of the layer (WebGL only). + * * `['var', 'varName']` fetches a value from the style variables; will throw an error if that variable is undefined + * * `['zoom']` The current zoom level (WebGL only). + * + * * Math operators: + * * `['*', value1, value2, ...]` multiplies the values (either numbers or colors) + * * `['/', value1, value2]` divides `value1` by `value2` + * * `['+', value1, value2, ...]` adds the values + * * `['-', value1, value2]` subtracts `value2` from `value1` + * * `['clamp', value, low, high]` clamps `value` between `low` and `high` + * * `['%', value1, value2]` returns the result of `value1 % value2` (modulo) + * * `['^', value1, value2]` returns the value of `value1` raised to the `value2` power + * * `['abs', value1]` returns the absolute value of `value1` + * * `['floor', value1]` returns the nearest integer less than or equal to `value1` + * * `['round', value1]` returns the nearest integer to `value1` + * * `['ceil', value1]` returns the nearest integer greater than or equal to `value1` + * * `['sin', value1]` returns the sine of `value1` + * * `['cos', value1]` returns the cosine of `value1` + * * `['atan', value1, value2]` returns `atan2(value1, value2)`. If `value2` is not provided, returns `atan(value1)` + * * `['sqrt', value1]` returns the square root of `value1` + * + * * Transform operators: + * * `['case', condition1, output1, ...conditionN, outputN, fallback]` selects the first output whose corresponding + * condition evaluates to `true`. If no match is found, returns the `fallback` value. + * All conditions should be `boolean`, output and fallback can be any kind. + * * `['match', input, match1, output1, ...matchN, outputN, fallback]` compares the `input` value against all + * provided `matchX` values, returning the output associated with the first valid match. If no match is found, + * returns the `fallback` value. + * `input` and `matchX` values must all be of the same type, and can be `number` or `string`. `outputX` and + * `fallback` values must be of the same type, and can be of any kind. + * * `['interpolate', interpolation, input, stop1, output1, ...stopN, outputN]` returns a value by interpolating between + * pairs of inputs and outputs; `interpolation` can either be `['linear']` or `['exponential', base]` where `base` is + * the rate of increase from stop A to stop B (i.e. power to which the interpolation ratio is raised); a value + * of 1 is equivalent to `['linear']`. + * `input` and `stopX` values must all be of type `number`. `outputX` values can be `number` or `color` values. + * Note: `input` will be clamped between `stop1` and `stopN`, meaning that all output values will be comprised + * between `output1` and `outputN`. + * * `['string', value1, value2, ...]` returns the first value in the list that evaluates to a string. + * An example would be to provide a default value for get: `['string', ['get', 'propertyname'], 'default value']]` + * (Canvas only). + * * `['number', value1, value2, ...]` returns the first value in the list that evaluates to a number. + * An example would be to provide a default value for get: `['string', ['get', 'propertyname'], 42]]` + * (Canvas only). + * * `['coalesce', value1, value2, ...]` returns the first value in the list which is not null or undefined. + * An example would be to provide a default value for get: `['coalesce', ['get','propertyname'], 'default value']]` + * (Canvas only). + * + * * Logical operators: + * * `['<', value1, value2]` returns `true` if `value1` is strictly lower than `value2`, or `false` otherwise. + * * `['<=', value1, value2]` returns `true` if `value1` is lower than or equals `value2`, or `false` otherwise. + * * `['>', value1, value2]` returns `true` if `value1` is strictly greater than `value2`, or `false` otherwise. + * * `['>=', value1, value2]` returns `true` if `value1` is greater than or equals `value2`, or `false` otherwise. + * * `['==', value1, value2]` returns `true` if `value1` equals `value2`, or `false` otherwise. + * * `['!=', value1, value2]` returns `true` if `value1` does not equal `value2`, or `false` otherwise. + * * `['!', value1]` returns `false` if `value1` is `true` or greater than `0`, or `true` otherwise. + * * `['all', value1, value2, ...]` returns `true` if all the inputs are `true`, `false` otherwise. + * * `['any', value1, value2, ...]` returns `true` if any of the inputs are `true`, `false` otherwise. + * * `['between', value1, value2, value3]` returns `true` if `value1` is contained between `value2` and `value3` + * (inclusively), or `false` otherwise. + * * `['in', needle, haystack]` returns `true` if `needle` is found in `haystack`, and + * `false` otherwise. + * This operator has the following limitations: + * * `haystack` has to be an array of numbers or strings (searching for a substring in a string is not supported yet) + * * Only literal arrays are supported as `haystack` for now; this means that `haystack` cannot be the result of an + * expression. If `haystack` is an array of strings, use the `literal` operator to disambiguate from an expression: + * `['literal', ['abc', 'def', 'ghi']]` + * + * * Conversion operators: + * * `['array', value1, ...valueN]` creates a numerical array from `number` values; please note that the amount of + * values can currently only be 2, 3 or 4 (WebGL only). + * * `['color', red, green, blue, alpha]` or `['color', shade, alpha]` creates a `color` value from `number` values; + * the `alpha` parameter is optional; if not specified, it will be set to 1 (WebGL only). + * Note: `red`, `green` and `blue` or `shade` components must be values between 0 and 255; `alpha` between 0 and 1. + * * `['palette', index, colors]` picks a `color` value from an array of colors using the given index; the `index` + * expression must evaluate to a number; the items in the `colors` array must be strings with hex colors + * (e.g. `'#86A136'`), colors using the rgba[a] functional notation (e.g. `'rgb(134, 161, 54)'` or `'rgba(134, 161, 54, 1)'`), + * named colors (e.g. `'red'`), or array literals with 3 ([r, g, b]) or 4 ([r, g, b, a]) values (with r, g, and b + * in the 0-255 range and a in the 0-1 range) (WebGL only). + * * `['to-string', value]` converts the input value to a string. If the input is a boolean, the result is "true" or "false". + * If the input is a number, it is converted to a string as specified by the "NumberToString" algorithm of the ECMAScript + * Language Specification. If the input is a color, it is converted to a string of the form "rgba(r,g,b,a)". (Canvas only) + * + * Values can either be literals or another operator, as they will be evaluated recursively. + * Literal values can be of the following types: + * * `boolean` + * * `number` + * * `number[]` (number arrays can only have a length of 2, 3 or 4) + * * `string` + * * {@link module:ol/color~Color} + * + * @typedef {Array<*>|import("../color.js").Color|string|number|boolean} ExpressionValue + * @api + */ + +let numTypes = 0; +const NoneType = 0; +const BooleanType = 1 << numTypes++; +const NumberType = 1 << numTypes++; +const StringType = 1 << numTypes++; +const ColorType = 1 << numTypes++; +const NumberArrayType = 1 << numTypes++; +const SizeType = 1 << numTypes++; +const AnyType = Math.pow(2, numTypes) - 1; + +const typeNames = { + [BooleanType]: 'boolean', + [NumberType]: 'number', + [StringType]: 'string', + [ColorType]: 'color', + [NumberArrayType]: 'number[]', + [SizeType]: 'size', +}; + +const namedTypes = Object.keys(typeNames).map(Number).sort(_array_js__WEBPACK_IMPORTED_MODULE_0__.ascending); + +/** + * Get a string representation for a type. + * @param {number} type The type. + * @return {string} The type name. + */ +function typeName(type) { + const names = []; + for (const namedType of namedTypes) { + if (includesType(type, namedType)) { + names.push(typeNames[namedType]); + } + } + if (names.length === 0) { + return 'untyped'; + } + if (names.length < 3) { + return names.join(' or '); + } + return names.slice(0, -1).join(', ') + ', or ' + names[names.length - 1]; +} + +/** + * @param {number} broad The broad type. + * @param {number} specific The specific type. + * @return {boolean} The broad type includes the specific type. + */ +function includesType(broad, specific) { + return (broad & specific) === specific; +} + +/** + * @param {number} oneType One type. + * @param {number} otherType Another type. + * @return {boolean} The set of types overlap (share a common specific type) + */ +function overlapsType(oneType, otherType) { + return !!(oneType & otherType); +} + +/** + * @param {number} type The type. + * @param {number} expected The expected type. + * @return {boolean} The given type is exactly the expected type. + */ +function isType(type, expected) { + return type === expected; +} + +/** + * @typedef {boolean|number|string|Array} LiteralValue + */ + +class LiteralExpression { + /** + * @param {number} type The value type. + * @param {LiteralValue} value The literal value. + */ + constructor(type, value) { + this.type = type; + this.value = value; + } +} + +class CallExpression { + /** + * @param {number} type The return type. + * @param {string} operator The operator. + * @param {...Expression} args The arguments. + */ + constructor(type, operator, ...args) { + this.type = type; + this.operator = operator; + this.args = args; + } +} + +/** + * @typedef {LiteralExpression|CallExpression} Expression + */ + +/** + * @typedef {Object} ParsingContext + * @property {Set} variables Variables referenced with the 'var' operator. + * @property {Set} properties Properties referenced with the 'get' operator. + * @property {boolean} featureId The style uses the feature id. + * @property {boolean} geometryType The style uses the feature geometry type. + * @property {import("../style/flat.js").FlatStyle|import("../style/webgl.js").WebGLStyle} style The style being parsed + */ + +/** + * @return {ParsingContext} A new parsing context. + */ +function newParsingContext() { + return { + variables: new Set(), + properties: new Set(), + featureId: false, + geometryType: false, + style: {}, + }; +} + +/** + * @param {string} typeHint Type hint + * @return {number} Resulting value type (will be a single type) + */ +function getTypeFromHint(typeHint) { + switch (typeHint) { + case 'string': + return StringType; + case 'color': + return ColorType; + case 'number': + return NumberType; + case 'boolean': + return BooleanType; + case 'number[]': + return NumberArrayType; + default: + throw new Error(`Unrecognized type hint: ${typeHint}`); + } +} + +/** + * @typedef {LiteralValue|Array} EncodedExpression + */ + +/** + * @param {EncodedExpression} encoded The encoded expression. + * @param {ParsingContext} context The parsing context. + * @param {number} [typeHint] Optional type hint + * @return {Expression} The parsed expression result. + */ +function parse(encoded, context, typeHint) { + switch (typeof encoded) { + case 'boolean': { + return new LiteralExpression(BooleanType, encoded); + } + case 'number': { + return new LiteralExpression( + typeHint === SizeType ? SizeType : NumberType, + encoded, + ); + } + case 'string': { + let type = StringType; + if ((0,_color_js__WEBPACK_IMPORTED_MODULE_1__.isStringColor)(encoded)) { + type |= ColorType; + } + // apply the given type hint only if it won't result in an empty type + if (!isType(type & typeHint, NoneType)) { + type &= typeHint; + } + return new LiteralExpression(type, encoded); + } + default: { + // pass + } + } + + if (!Array.isArray(encoded)) { + throw new Error('Expression must be an array or a primitive value'); + } + + if (encoded.length === 0) { + throw new Error('Empty expression'); + } + + if (typeof encoded[0] === 'string') { + return parseCallExpression(encoded, context, typeHint); + } + + for (const item of encoded) { + if (typeof item !== 'number') { + throw new Error('Expected an array of numbers'); + } + } + + let type = NumberArrayType; + if (encoded.length === 2) { + type |= SizeType; + } else if (encoded.length === 3 || encoded.length === 4) { + type |= ColorType; + } + if (typeHint) { + type &= typeHint; + } + return new LiteralExpression(type, encoded); +} + +/** + * @type {Object} + */ +const Ops = { + Get: 'get', + Var: 'var', + Concat: 'concat', + GeometryType: 'geometry-type', + Any: 'any', + All: 'all', + Not: '!', + Resolution: 'resolution', + Zoom: 'zoom', + Time: 'time', + Equal: '==', + NotEqual: '!=', + GreaterThan: '>', + GreaterThanOrEqualTo: '>=', + LessThan: '<', + LessThanOrEqualTo: '<=', + Multiply: '*', + Divide: '/', + Add: '+', + Subtract: '-', + Clamp: 'clamp', + Mod: '%', + Pow: '^', + Abs: 'abs', + Floor: 'floor', + Ceil: 'ceil', + Round: 'round', + Sin: 'sin', + Cos: 'cos', + Atan: 'atan', + Sqrt: 'sqrt', + Match: 'match', + Between: 'between', + Interpolate: 'interpolate', + Coalesce: 'coalesce', + Case: 'case', + In: 'in', + Number: 'number', + String: 'string', + Array: 'array', + Color: 'color', + Id: 'id', + Band: 'band', + Palette: 'palette', + ToString: 'to-string', +}; + +/** + * @typedef {function(Array, ParsingContext, number):Expression} Parser + * Third argument is a type hint + */ + +/** + * @type {Object} + */ +const parsers = { + [Ops.Get]: createParser( + ([_, typeHint]) => { + if (typeHint !== undefined) { + return getTypeFromHint( + /** @type {string} */ ( + /** @type {LiteralExpression} */ (typeHint).value + ), + ); + } + return AnyType; + }, + withArgsCount(1, 2), + withGetArgs, + ), + [Ops.Var]: createParser( + ([firstArg]) => firstArg.type, + withArgsCount(1, 1), + withVarArgs, + ), + [Ops.Id]: createParser(NumberType | StringType, withNoArgs, usesFeatureId), + [Ops.Concat]: createParser( + StringType, + withArgsCount(2, Infinity), + parseArgsOfType(AnyType), + ), + [Ops.GeometryType]: createParser(StringType, withNoArgs, usesGeometryType), + [Ops.Resolution]: createParser(NumberType, withNoArgs), + [Ops.Zoom]: createParser(NumberType, withNoArgs), + [Ops.Time]: createParser(NumberType, withNoArgs), + [Ops.Any]: createParser( + BooleanType, + withArgsCount(2, Infinity), + parseArgsOfType(BooleanType), + ), + [Ops.All]: createParser( + BooleanType, + withArgsCount(2, Infinity), + parseArgsOfType(BooleanType), + ), + [Ops.Not]: createParser( + BooleanType, + withArgsCount(1, 1), + parseArgsOfType(BooleanType), + ), + [Ops.Equal]: createParser( + BooleanType, + withArgsCount(2, 2), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.NotEqual]: createParser( + BooleanType, + withArgsCount(2, 2), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.GreaterThan]: createParser( + BooleanType, + withArgsCount(2, 2), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.GreaterThanOrEqualTo]: createParser( + BooleanType, + withArgsCount(2, 2), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.LessThan]: createParser( + BooleanType, + withArgsCount(2, 2), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.LessThanOrEqualTo]: createParser( + BooleanType, + withArgsCount(2, 2), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.Multiply]: createParser( + (parsedArgs) => { + let outputType = NumberType | ColorType; + for (let i = 0; i < parsedArgs.length; i++) { + outputType &= parsedArgs[i].type; + } + return outputType; + }, + withArgsCount(2, Infinity), + parseArgsOfType(NumberType | ColorType), + narrowArgsType, + ), + [Ops.Coalesce]: createParser( + (parsedArgs) => { + let type = AnyType; + for (let i = 1; i < parsedArgs.length; i += 2) { + type &= parsedArgs[i].type; + } + type &= parsedArgs[parsedArgs.length - 1].type; + return type; + }, + withArgsCount(2, Infinity), + parseArgsOfType(AnyType), + narrowArgsType, + ), + [Ops.Divide]: createParser( + NumberType, + withArgsCount(2, 2), + parseArgsOfType(NumberType), + ), + [Ops.Add]: createParser( + NumberType, + withArgsCount(2, Infinity), + parseArgsOfType(NumberType), + ), + [Ops.Subtract]: createParser( + NumberType, + withArgsCount(2, 2), + parseArgsOfType(NumberType), + ), + [Ops.Clamp]: createParser( + NumberType, + withArgsCount(3, 3), + parseArgsOfType(NumberType), + ), + [Ops.Mod]: createParser( + NumberType, + withArgsCount(2, 2), + parseArgsOfType(NumberType), + ), + [Ops.Pow]: createParser( + NumberType, + withArgsCount(2, 2), + parseArgsOfType(NumberType), + ), + [Ops.Abs]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Floor]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Ceil]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Round]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Sin]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Cos]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Atan]: createParser( + NumberType, + withArgsCount(1, 2), + parseArgsOfType(NumberType), + ), + [Ops.Sqrt]: createParser( + NumberType, + withArgsCount(1, 1), + parseArgsOfType(NumberType), + ), + [Ops.Match]: createParser( + (parsedArgs) => { + let type = AnyType; + for (let i = 2; i < parsedArgs.length; i += 2) { + type &= parsedArgs[i].type; + } + type &= parsedArgs[parsedArgs.length - 1].type; + return type; + }, + withArgsCount(4, Infinity), + withEvenArgs, + parseMatchArgs, + ), + [Ops.Between]: createParser( + BooleanType, + withArgsCount(3, 3), + parseArgsOfType(NumberType), + ), + [Ops.Interpolate]: createParser( + (parsedArgs) => { + let type = ColorType | NumberType; + for (let i = 3; i < parsedArgs.length; i += 2) { + type &= parsedArgs[i].type; + } + return type; + }, + withArgsCount(6, Infinity), + withEvenArgs, + parseInterpolateArgs, + ), + [Ops.Case]: createParser( + (parsedArgs) => { + let type = AnyType; + for (let i = 1; i < parsedArgs.length; i += 2) { + type &= parsedArgs[i].type; + } + type &= parsedArgs[parsedArgs.length - 1].type; + return type; + }, + withArgsCount(3, Infinity), + withOddArgs, + parseCaseArgs, + ), + [Ops.In]: createParser(BooleanType, withArgsCount(2, 2), parseInArgs), + [Ops.Number]: createParser( + NumberType, + withArgsCount(1, Infinity), + parseArgsOfType(AnyType), + ), + [Ops.String]: createParser( + StringType, + withArgsCount(1, Infinity), + parseArgsOfType(AnyType), + ), + [Ops.Array]: createParser( + (parsedArgs) => { + return parsedArgs.length === 2 + ? NumberArrayType | SizeType + : parsedArgs.length === 3 || parsedArgs.length === 4 + ? NumberArrayType | ColorType + : NumberArrayType; + }, + withArgsCount(1, Infinity), + parseArgsOfType(NumberType), + ), + [Ops.Color]: createParser( + ColorType, + withArgsCount(1, 4), + parseArgsOfType(NumberType), + ), + [Ops.Band]: createParser( + NumberType, + withArgsCount(1, 3), + parseArgsOfType(NumberType), + ), + [Ops.Palette]: createParser(ColorType, withArgsCount(2, 2), parsePaletteArgs), + [Ops.ToString]: createParser( + StringType, + withArgsCount(1, 1), + parseArgsOfType(BooleanType | NumberType | StringType | ColorType), + ), +}; + +/** + * @typedef {function(Array, ParsingContext, Array, number?):Array|void} ArgValidator + * An argument validator applies various checks to an encoded expression arguments + * Returns the parsed arguments if any. + * Third argument is the array of parsed arguments from previous validators + * Fourth argument is an optional type hint + */ + +/** + * @type ArgValidator + */ +function withGetArgs(encoded, context) { + const arg = parse(encoded[1], context); + if (!(arg instanceof LiteralExpression)) { + throw new Error('Expected a literal argument for get operation'); + } + if (typeof arg.value !== 'string') { + throw new Error('Expected a string argument for get operation'); + } + context.properties.add(arg.value); + if (encoded.length === 3) { + const hint = parse(encoded[2], context); + return [arg, hint]; + } + return [arg]; +} + +/** + * @type ArgValidator + */ +function withVarArgs(encoded, context, parsedArgs, typeHint) { + const varName = encoded[1]; + if (typeof varName !== 'string') { + throw new Error('Expected a string argument for var operation'); + } + context.variables.add(varName); + if ( + !('variables' in context.style) || + context.style.variables[varName] === undefined + ) { + return [new LiteralExpression(AnyType, varName)]; + } + const initialValue = context.style.variables[varName]; + const arg = /** @type {LiteralExpression} */ (parse(initialValue, context)); + arg.value = varName; + if (typeHint && !overlapsType(typeHint, arg.type)) { + throw new Error( + `The variable ${varName} has type ${typeName( + arg.type, + )} but the following type was expected: ${typeName(typeHint)}`, + ); + } + return [arg]; +} + +/** + * @type ArgValidator + */ +function usesFeatureId(encoded, context) { + context.featureId = true; +} + +/** + * @type ArgValidator + */ +function usesGeometryType(encoded, context) { + context.geometryType = true; +} + +/** + * @type ArgValidator + */ +function withNoArgs(encoded, context) { + const operation = encoded[0]; + if (encoded.length !== 1) { + throw new Error(`Expected no arguments for ${operation} operation`); + } + return []; +} + +/** + * @param {number} minArgs The minimum number of arguments. + * @param {number} maxArgs The maximum number of arguments. + * @return {ArgValidator} The argument validator + */ +function withArgsCount(minArgs, maxArgs) { + return function (encoded, context) { + const operation = encoded[0]; + const argCount = encoded.length - 1; + if (minArgs === maxArgs) { + if (argCount !== minArgs) { + const plural = minArgs === 1 ? '' : 's'; + throw new Error( + `Expected ${minArgs} argument${plural} for ${operation}, got ${argCount}`, + ); + } + } else if (argCount < minArgs || argCount > maxArgs) { + const range = + maxArgs === Infinity + ? `${minArgs} or more` + : `${minArgs} to ${maxArgs}`; + throw new Error( + `Expected ${range} arguments for ${operation}, got ${argCount}`, + ); + } + }; +} + +/** + * @param {number} argType The argument type. + * @return {ArgValidator} The argument validator + */ +function parseArgsOfType(argType) { + return function (encoded, context) { + const operation = encoded[0]; + const argCount = encoded.length - 1; + /** + * @type {Array} + */ + const args = new Array(argCount); + for (let i = 0; i < argCount; ++i) { + const expression = parse(encoded[i + 1], context); + if (!overlapsType(argType, expression.type)) { + const gotType = typeName(argType); + const expectedType = typeName(expression.type); + throw new Error( + `Unexpected type for argument ${i} of ${operation} operation` + + `, got ${gotType} but expected ${expectedType}`, + ); + } + expression.type &= argType; + args[i] = expression; + } + return args; + }; +} + +/** + * @type {ArgValidator} + */ +function narrowArgsType(encoded, context, parsedArgs) { + const operation = encoded[0]; + const argCount = encoded.length - 1; + + // first pass to determine a narrowed down type + let sameType = AnyType; + for (let i = 0; i < parsedArgs.length; ++i) { + sameType &= parsedArgs[i].type; + } + + if (sameType === NoneType) { + throw new Error( + `No common type could be found for arguments of ${operation} operation`, + ); + } + + // re-parse args + const args = new Array(argCount); + for (let i = 0; i < argCount; ++i) { + args[i] = parse(encoded[i + 1], context, sameType); + } + return args; +} + +/** + * @type {ArgValidator} + */ +function withOddArgs(encoded, context) { + const operation = encoded[0]; + const argCount = encoded.length - 1; + if (argCount % 2 === 0) { + throw new Error( + `An odd amount of arguments was expected for operation ${operation}, got ${JSON.stringify( + argCount, + )} instead`, + ); + } +} + +/** + * @type {ArgValidator} + */ +function withEvenArgs(encoded, context) { + const operation = encoded[0]; + const argCount = encoded.length - 1; + if (argCount % 2 === 1) { + throw new Error( + `An even amount of arguments was expected for operation ${operation}, got ${JSON.stringify( + argCount, + )} instead`, + ); + } +} + +/** + * @type ArgValidator + */ +function parseMatchArgs(encoded, context, parsedArgs, typeHint) { + const argsCount = encoded.length - 1; + + const input = parse(encoded[1], context); + let inputType = input.type; + const fallback = parse(encoded[encoded.length - 1], context); + let outputType = + typeHint !== undefined ? typeHint & fallback.type : fallback.type; + + // first parse args to figure out possible types + const args = new Array(argsCount - 2); + for (let i = 0; i < argsCount - 2; i += 2) { + const match = parse(encoded[i + 2], context); + const output = parse(encoded[i + 3], context); + inputType &= match.type; + outputType &= output.type; + args[i] = match; + args[i + 1] = output; + } + + // check input and output types validity + const expectedInputType = StringType | NumberType | BooleanType; + if (!overlapsType(expectedInputType, inputType)) { + throw new Error( + `Expected an input of type ${typeName( + expectedInputType, + )} for the interpolate operation` + + `, got ${typeName(inputType)} instead`, + ); + } + inputType &= expectedInputType; + if (isType(outputType, NoneType)) { + throw new Error( + `Could not find a common output type for the following match operation: ` + + JSON.stringify(encoded), + ); + } + + // parse again inputs and outputs with common type + for (let i = 0; i < argsCount - 2; i += 2) { + const match = parse(encoded[i + 2], context, inputType); + const output = parse(encoded[i + 3], context, outputType); + args[i] = match; + args[i + 1] = output; + } + + return [ + parse(encoded[1], context, inputType), + ...args, + parse(encoded[encoded.length - 1], context, outputType), + ]; +} + +/** + * @type ArgValidator + */ +function parseInterpolateArgs(encoded, context, parsedArgs, typeHint) { + const interpolationType = encoded[1]; + let interpolation; + switch (interpolationType[0]) { + case 'linear': + interpolation = 1; + break; + case 'exponential': + interpolation = interpolationType[1]; + if (typeof interpolation !== 'number') { + throw new Error( + `Expected a number base for exponential interpolation` + + `, got ${JSON.stringify(interpolation)} instead`, + ); + } + break; + default: + interpolation = null; + } + if (!interpolation) { + throw new Error( + `Invalid interpolation type: ${JSON.stringify(interpolationType)}`, + ); + } + interpolation = parse(interpolation, context); + + // check input types + let input = parse(encoded[2], context); + if (!overlapsType(NumberType, input.type)) { + throw new Error( + `Expected an input of type number for the interpolate operation` + + `, got ${typeName(input.type)} instead`, + ); + } + input = parse(encoded[2], context, NumberType); // parse again with narrower output + + const args = new Array(encoded.length - 3); + for (let i = 0; i < args.length; i += 2) { + let stop = parse(encoded[i + 3], context); + if (!overlapsType(NumberType, stop.type)) { + throw new Error( + `Expected all stop input values in the interpolate operation to be of type number` + + `, got ${typeName(stop.type)} at position ${i + 2} instead`, + ); + } + let output = parse(encoded[i + 4], context); + if (!overlapsType(NumberType | ColorType, output.type)) { + throw new Error( + `Expected all stop output values in the interpolate operation to be a number or color` + + `, got ${typeName(output.type)} at position ${i + 3} instead`, + ); + } + // parse again with narrower types + stop = parse(encoded[i + 3], context, NumberType); + output = parse(encoded[i + 4], context, NumberType | ColorType); + args[i] = stop; + args[i + 1] = output; + } + + return [interpolation, input, ...args]; +} + +/** + * @type ArgValidator + */ +function parseCaseArgs(encoded, context, parsedArgs, typeHint) { + const fallback = parse(encoded[encoded.length - 1], context, typeHint); + let outputType = + typeHint !== undefined ? typeHint & fallback.type : fallback.type; + + // first parse args to figure out possible types + const args = new Array(encoded.length - 1); + for (let i = 0; i < args.length - 1; i += 2) { + const condition = parse(encoded[i + 1], context); + const output = parse(encoded[i + 2], context, typeHint); + if (!overlapsType(BooleanType, condition.type)) { + throw new Error( + `Expected all conditions in the case operation to be of type boolean` + + `, got ${typeName(condition.type)} at position ${i} instead`, + ); + } + outputType &= output.type; + args[i] = condition; + args[i + 1] = output; + } + + if (isType(outputType, NoneType)) { + throw new Error( + `Could not find a common output type for the following case operation: ` + + JSON.stringify(encoded), + ); + } + + // parse again args with common output type + for (let i = 0; i < args.length - 1; i += 2) { + args[i + 1] = parse(encoded[i + 2], context, outputType); + } + args[args.length - 1] = parse( + encoded[encoded.length - 1], + context, + outputType, + ); + + return args; +} + +/** + * @type ArgValidator + */ +function parseInArgs(encoded, context) { + /** @type {Array} */ + let haystack = /** @type {any} */ (encoded[2]); + if (!Array.isArray(haystack)) { + throw new Error( + `The "in" operator was provided a literal value which was not an array as second argument.`, + ); + } + if (typeof haystack[0] === 'string') { + if (haystack[0] !== 'literal') { + throw new Error( + `For the "in" operator, a string array should be wrapped in a "literal" operator to disambiguate from expressions.`, + ); + } + if (!Array.isArray(haystack[1])) { + throw new Error( + `The "in" operator was provided a literal value which was not an array as second argument.`, + ); + } + haystack = haystack[1]; + } + + let needleType = StringType | NumberType; + const args = new Array(haystack.length); + for (let i = 0; i < args.length; i++) { + const arg = parse(haystack[i], context); + needleType &= arg.type; + args[i] = arg; + } + if (isType(needleType, NoneType)) { + throw new Error( + `Could not find a common type for the following in operation: ` + + JSON.stringify(encoded), + ); + } + + const needle = parse(encoded[1], context, needleType); + return [needle, ...args]; +} + +/** + * @type ArgValidator + */ +function parsePaletteArgs(encoded, context) { + const index = parse(encoded[1], context, NumberType); + if (index.type !== NumberType) { + throw new Error( + `The first argument of palette must be an number, got ${typeName( + index.type, + )} instead`, + ); + } + const colors = encoded[2]; + if (!Array.isArray(colors)) { + throw new Error('The second argument of palette must be an array'); + } + const parsedColors = new Array(colors.length); + for (let i = 0; i < parsedColors.length; i++) { + const color = parse(colors[i], context, ColorType); + if (!(color instanceof LiteralExpression)) { + throw new Error( + `The palette color at index ${i} must be a literal value`, + ); + } + if (!overlapsType(color.type, ColorType)) { + throw new Error( + `The palette color at index ${i} should be of type color, got ${typeName( + color.type, + )} instead`, + ); + } + parsedColors[i] = color; + } + return [index, ...parsedColors]; +} + +/** + * @param {number|function(Array):number} returnType The return type of the operator; can be a fixed value or a callback taking the parsed + * arguments + * @param {Array} argValidators A chain of argument validators; the return value of the last validator + * will be used as parsed arguments + * @return {Parser} The parser. + */ +function createParser(returnType, ...argValidators) { + return function (encoded, context, typeHint) { + const operator = encoded[0]; + let parsedArgs = []; + for (let i = 0; i < argValidators.length; i++) { + parsedArgs = + argValidators[i](encoded, context, parsedArgs, typeHint) || parsedArgs; + } + let actualType = + typeof returnType === 'function' ? returnType(parsedArgs) : returnType; + if (typeHint !== undefined) { + if (!overlapsType(actualType, typeHint)) { + throw new Error( + `The following expression was expected to return ${typeName( + typeHint, + )}, but returns ${typeName(actualType)} instead: ${JSON.stringify( + encoded, + )}`, + ); + } + actualType &= typeHint; + } + if (actualType === NoneType) { + throw new Error( + `No matching type was found for the following expression: ${JSON.stringify( + encoded, + )}`, + ); + } + return new CallExpression(actualType, operator, ...parsedArgs); + }; +} + +/** + * @param {Array} encoded The encoded expression. + * @param {ParsingContext} context The parsing context. + * @param {number} [typeHint] Optional type hint + * @return {Expression} The parsed expression. + */ +function parseCallExpression(encoded, context, typeHint) { + const operator = encoded[0]; + + const parser = parsers[operator]; + if (!parser) { + throw new Error(`Unknown operator: ${operator}`); + } + return parser(encoded, context, typeHint); +} + +/** + * Returns a simplified geometry type suited for the `geometry-type` operator + * @param {import('../geom/Geometry.js').default|import('../render/Feature.js').default} geometry Geometry object + * @return {'Point'|'LineString'|'Polygon'|''} Simplified geometry type; empty string of no geometry found + */ +function computeGeometryType(geometry) { + if (!geometry) { + return ''; + } + const type = geometry.getType(); + switch (type) { + case 'Point': + case 'LineString': + case 'Polygon': + return type; + case 'MultiPoint': + case 'MultiLineString': + case 'MultiPolygon': + return /** @type {'Point'|'LineString'|'Polygon'} */ (type.substring(5)); + case 'Circle': + return 'Polygon'; + case 'GeometryCollection': + return computeGeometryType( + /** @type {import("../geom/GeometryCollection.js").default} */ ( + geometry + ).getGeometries()[0], + ); + default: + return ''; + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/extent.js": +/*!*******************************************!*\ + !*** ./node_modules/@biigle/ol/extent.js ***! + \*******************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "applyTransform": () => (/* binding */ applyTransform), +/* harmony export */ "approximatelyEquals": () => (/* binding */ approximatelyEquals), +/* harmony export */ "boundingExtent": () => (/* binding */ boundingExtent), +/* harmony export */ "buffer": () => (/* binding */ buffer), +/* harmony export */ "clone": () => (/* binding */ clone), +/* harmony export */ "closestSquaredDistanceXY": () => (/* binding */ closestSquaredDistanceXY), +/* harmony export */ "containsCoordinate": () => (/* binding */ containsCoordinate), +/* harmony export */ "containsExtent": () => (/* binding */ containsExtent), +/* harmony export */ "containsXY": () => (/* binding */ containsXY), +/* harmony export */ "coordinateRelationship": () => (/* binding */ coordinateRelationship), +/* harmony export */ "createEmpty": () => (/* binding */ createEmpty), +/* harmony export */ "createOrUpdate": () => (/* binding */ createOrUpdate), +/* harmony export */ "createOrUpdateEmpty": () => (/* binding */ createOrUpdateEmpty), +/* harmony export */ "createOrUpdateFromCoordinate": () => (/* binding */ createOrUpdateFromCoordinate), +/* harmony export */ "createOrUpdateFromCoordinates": () => (/* binding */ createOrUpdateFromCoordinates), +/* harmony export */ "createOrUpdateFromFlatCoordinates": () => (/* binding */ createOrUpdateFromFlatCoordinates), +/* harmony export */ "createOrUpdateFromRings": () => (/* binding */ createOrUpdateFromRings), +/* harmony export */ "equals": () => (/* binding */ equals), +/* harmony export */ "extend": () => (/* binding */ extend), +/* harmony export */ "extendCoordinate": () => (/* binding */ extendCoordinate), +/* harmony export */ "extendCoordinates": () => (/* binding */ extendCoordinates), +/* harmony export */ "extendFlatCoordinates": () => (/* binding */ extendFlatCoordinates), +/* harmony export */ "extendRings": () => (/* binding */ extendRings), +/* harmony export */ "extendXY": () => (/* binding */ extendXY), +/* harmony export */ "forEachCorner": () => (/* binding */ forEachCorner), +/* harmony export */ "getArea": () => (/* binding */ getArea), +/* harmony export */ "getBottomLeft": () => (/* binding */ getBottomLeft), +/* harmony export */ "getBottomRight": () => (/* binding */ getBottomRight), +/* harmony export */ "getCenter": () => (/* binding */ getCenter), +/* harmony export */ "getCorner": () => (/* binding */ getCorner), +/* harmony export */ "getEnlargedArea": () => (/* binding */ getEnlargedArea), +/* harmony export */ "getForViewAndSize": () => (/* binding */ getForViewAndSize), +/* harmony export */ "getHeight": () => (/* binding */ getHeight), +/* harmony export */ "getIntersection": () => (/* binding */ getIntersection), +/* harmony export */ "getIntersectionArea": () => (/* binding */ getIntersectionArea), +/* harmony export */ "getMargin": () => (/* binding */ getMargin), +/* harmony export */ "getRotatedViewport": () => (/* binding */ getRotatedViewport), +/* harmony export */ "getSize": () => (/* binding */ getSize), +/* harmony export */ "getTopLeft": () => (/* binding */ getTopLeft), +/* harmony export */ "getTopRight": () => (/* binding */ getTopRight), +/* harmony export */ "getWidth": () => (/* binding */ getWidth), +/* harmony export */ "intersects": () => (/* binding */ intersects), +/* harmony export */ "intersectsSegment": () => (/* binding */ intersectsSegment), +/* harmony export */ "isEmpty": () => (/* binding */ isEmpty), +/* harmony export */ "returnOrUpdate": () => (/* binding */ returnOrUpdate), +/* harmony export */ "scaleFromCenter": () => (/* binding */ scaleFromCenter), +/* harmony export */ "wrapAndSliceX": () => (/* binding */ wrapAndSliceX), +/* harmony export */ "wrapX": () => (/* binding */ wrapX) +/* harmony export */ }); +/* harmony import */ var _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./extent/Relationship.js */ "./node_modules/@biigle/ol/extent/Relationship.js"); +/** + * @module ol/extent + */ + + +/** + * An array of numbers representing an extent: `[minx, miny, maxx, maxy]`. + * @typedef {Array} Extent + * @api + */ + +/** + * Extent corner. + * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} Corner + */ + +/** + * Build an extent that includes all given coordinates. + * + * @param {Array} coordinates Coordinates. + * @return {Extent} Bounding extent. + * @api + */ +function boundingExtent(coordinates) { + const extent = createEmpty(); + for (let i = 0, ii = coordinates.length; i < ii; ++i) { + extendCoordinate(extent, coordinates[i]); + } + return extent; +} + +/** + * @param {Array} xs Xs. + * @param {Array} ys Ys. + * @param {Extent} [dest] Destination extent. + * @private + * @return {Extent} Extent. + */ +function _boundingExtentXYs(xs, ys, dest) { + const minX = Math.min.apply(null, xs); + const minY = Math.min.apply(null, ys); + const maxX = Math.max.apply(null, xs); + const maxY = Math.max.apply(null, ys); + return createOrUpdate(minX, minY, maxX, maxY, dest); +} + +/** + * Return extent increased by the provided value. + * @param {Extent} extent Extent. + * @param {number} value The amount by which the extent should be buffered. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + * @api + */ +function buffer(extent, value, dest) { + if (dest) { + dest[0] = extent[0] - value; + dest[1] = extent[1] - value; + dest[2] = extent[2] + value; + dest[3] = extent[3] + value; + return dest; + } + return [ + extent[0] - value, + extent[1] - value, + extent[2] + value, + extent[3] + value, + ]; +} + +/** + * Creates a clone of an extent. + * + * @param {Extent} extent Extent to clone. + * @param {Extent} [dest] Extent. + * @return {Extent} The clone. + */ +function clone(extent, dest) { + if (dest) { + dest[0] = extent[0]; + dest[1] = extent[1]; + dest[2] = extent[2]; + dest[3] = extent[3]; + return dest; + } + return extent.slice(); +} + +/** + * @param {Extent} extent Extent. + * @param {number} x X. + * @param {number} y Y. + * @return {number} Closest squared distance. + */ +function closestSquaredDistanceXY(extent, x, y) { + let dx, dy; + if (x < extent[0]) { + dx = extent[0] - x; + } else if (extent[2] < x) { + dx = x - extent[2]; + } else { + dx = 0; + } + if (y < extent[1]) { + dy = extent[1] - y; + } else if (extent[3] < y) { + dy = y - extent[3]; + } else { + dy = 0; + } + return dx * dx + dy * dy; +} + +/** + * Check if the passed coordinate is contained or on the edge of the extent. + * + * @param {Extent} extent Extent. + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @return {boolean} The coordinate is contained in the extent. + * @api + */ +function containsCoordinate(extent, coordinate) { + return containsXY(extent, coordinate[0], coordinate[1]); +} + +/** + * Check if one extent contains another. + * + * An extent is deemed contained if it lies completely within the other extent, + * including if they share one or more edges. + * + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent 2. + * @return {boolean} The second extent is contained by or on the edge of the + * first. + * @api + */ +function containsExtent(extent1, extent2) { + return ( + extent1[0] <= extent2[0] && + extent2[2] <= extent1[2] && + extent1[1] <= extent2[1] && + extent2[3] <= extent1[3] + ); +} + +/** + * Check if the passed coordinate is contained or on the edge of the extent. + * + * @param {Extent} extent Extent. + * @param {number} x X coordinate. + * @param {number} y Y coordinate. + * @return {boolean} The x, y values are contained in the extent. + * @api + */ +function containsXY(extent, x, y) { + return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3]; +} + +/** + * Get the relationship between a coordinate and extent. + * @param {Extent} extent The extent. + * @param {import("./coordinate.js").Coordinate} coordinate The coordinate. + * @return {import("./extent/Relationship.js").default} The relationship (bitwise compare with + * import("./extent/Relationship.js").Relationship). + */ +function coordinateRelationship(extent, coordinate) { + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const x = coordinate[0]; + const y = coordinate[1]; + let relationship = _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].UNKNOWN; + if (x < minX) { + relationship = relationship | _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].LEFT; + } else if (x > maxX) { + relationship = relationship | _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].RIGHT; + } + if (y < minY) { + relationship = relationship | _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].BELOW; + } else if (y > maxY) { + relationship = relationship | _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].ABOVE; + } + if (relationship === _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].UNKNOWN) { + relationship = _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].INTERSECTING; + } + return relationship; +} + +/** + * Create an empty extent. + * @return {Extent} Empty extent. + * @api + */ +function createEmpty() { + return [Infinity, Infinity, -Infinity, -Infinity]; +} + +/** + * Create a new extent or update the provided extent. + * @param {number} minX Minimum X. + * @param {number} minY Minimum Y. + * @param {number} maxX Maximum X. + * @param {number} maxY Maximum Y. + * @param {Extent} [dest] Destination extent. + * @return {Extent} Extent. + */ +function createOrUpdate(minX, minY, maxX, maxY, dest) { + if (dest) { + dest[0] = minX; + dest[1] = minY; + dest[2] = maxX; + dest[3] = maxY; + return dest; + } + return [minX, minY, maxX, maxY]; +} + +/** + * Create a new empty extent or make the provided one empty. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + */ +function createOrUpdateEmpty(dest) { + return createOrUpdate(Infinity, Infinity, -Infinity, -Infinity, dest); +} + +/** + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + */ +function createOrUpdateFromCoordinate(coordinate, dest) { + const x = coordinate[0]; + const y = coordinate[1]; + return createOrUpdate(x, y, x, y, dest); +} + +/** + * @param {Array} coordinates Coordinates. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + */ +function createOrUpdateFromCoordinates(coordinates, dest) { + const extent = createOrUpdateEmpty(dest); + return extendCoordinates(extent, coordinates); +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + */ +function createOrUpdateFromFlatCoordinates( + flatCoordinates, + offset, + end, + stride, + dest, +) { + const extent = createOrUpdateEmpty(dest); + return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride); +} + +/** + * @param {Array>} rings Rings. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + */ +function createOrUpdateFromRings(rings, dest) { + const extent = createOrUpdateEmpty(dest); + return extendRings(extent, rings); +} + +/** + * Determine if two extents are equivalent. + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent 2. + * @return {boolean} The two extents are equivalent. + * @api + */ +function equals(extent1, extent2) { + return ( + extent1[0] == extent2[0] && + extent1[2] == extent2[2] && + extent1[1] == extent2[1] && + extent1[3] == extent2[3] + ); +} + +/** + * Determine if two extents are approximately equivalent. + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent 2. + * @param {number} tolerance Tolerance in extent coordinate units. + * @return {boolean} The two extents differ by less than the tolerance. + */ +function approximatelyEquals(extent1, extent2, tolerance) { + return ( + Math.abs(extent1[0] - extent2[0]) < tolerance && + Math.abs(extent1[2] - extent2[2]) < tolerance && + Math.abs(extent1[1] - extent2[1]) < tolerance && + Math.abs(extent1[3] - extent2[3]) < tolerance + ); +} + +/** + * Modify an extent to include another extent. + * @param {Extent} extent1 The extent to be modified. + * @param {Extent} extent2 The extent that will be included in the first. + * @return {Extent} A reference to the first (extended) extent. + * @api + */ +function extend(extent1, extent2) { + if (extent2[0] < extent1[0]) { + extent1[0] = extent2[0]; + } + if (extent2[2] > extent1[2]) { + extent1[2] = extent2[2]; + } + if (extent2[1] < extent1[1]) { + extent1[1] = extent2[1]; + } + if (extent2[3] > extent1[3]) { + extent1[3] = extent2[3]; + } + return extent1; +} + +/** + * @param {Extent} extent Extent. + * @param {import("./coordinate.js").Coordinate} coordinate Coordinate. + */ +function extendCoordinate(extent, coordinate) { + if (coordinate[0] < extent[0]) { + extent[0] = coordinate[0]; + } + if (coordinate[0] > extent[2]) { + extent[2] = coordinate[0]; + } + if (coordinate[1] < extent[1]) { + extent[1] = coordinate[1]; + } + if (coordinate[1] > extent[3]) { + extent[3] = coordinate[1]; + } +} + +/** + * @param {Extent} extent Extent. + * @param {Array} coordinates Coordinates. + * @return {Extent} Extent. + */ +function extendCoordinates(extent, coordinates) { + for (let i = 0, ii = coordinates.length; i < ii; ++i) { + extendCoordinate(extent, coordinates[i]); + } + return extent; +} + +/** + * @param {Extent} extent Extent. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {Extent} Extent. + */ +function extendFlatCoordinates( + extent, + flatCoordinates, + offset, + end, + stride, +) { + for (; offset < end; offset += stride) { + extendXY(extent, flatCoordinates[offset], flatCoordinates[offset + 1]); + } + return extent; +} + +/** + * @param {Extent} extent Extent. + * @param {Array>} rings Rings. + * @return {Extent} Extent. + */ +function extendRings(extent, rings) { + for (let i = 0, ii = rings.length; i < ii; ++i) { + extendCoordinates(extent, rings[i]); + } + return extent; +} + +/** + * @param {Extent} extent Extent. + * @param {number} x X. + * @param {number} y Y. + */ +function extendXY(extent, x, y) { + extent[0] = Math.min(extent[0], x); + extent[1] = Math.min(extent[1], y); + extent[2] = Math.max(extent[2], x); + extent[3] = Math.max(extent[3], y); +} + +/** + * This function calls `callback` for each corner of the extent. If the + * callback returns a truthy value the function returns that value + * immediately. Otherwise the function returns `false`. + * @param {Extent} extent Extent. + * @param {function(import("./coordinate.js").Coordinate): S} callback Callback. + * @return {S|boolean} Value. + * @template S + */ +function forEachCorner(extent, callback) { + let val; + val = callback(getBottomLeft(extent)); + if (val) { + return val; + } + val = callback(getBottomRight(extent)); + if (val) { + return val; + } + val = callback(getTopRight(extent)); + if (val) { + return val; + } + val = callback(getTopLeft(extent)); + if (val) { + return val; + } + return false; +} + +/** + * Get the size of an extent. + * @param {Extent} extent Extent. + * @return {number} Area. + * @api + */ +function getArea(extent) { + let area = 0; + if (!isEmpty(extent)) { + area = getWidth(extent) * getHeight(extent); + } + return area; +} + +/** + * Get the bottom left coordinate of an extent. + * @param {Extent} extent Extent. + * @return {import("./coordinate.js").Coordinate} Bottom left coordinate. + * @api + */ +function getBottomLeft(extent) { + return [extent[0], extent[1]]; +} + +/** + * Get the bottom right coordinate of an extent. + * @param {Extent} extent Extent. + * @return {import("./coordinate.js").Coordinate} Bottom right coordinate. + * @api + */ +function getBottomRight(extent) { + return [extent[2], extent[1]]; +} + +/** + * Get the center coordinate of an extent. + * @param {Extent} extent Extent. + * @return {import("./coordinate.js").Coordinate} Center. + * @api + */ +function getCenter(extent) { + return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2]; +} + +/** + * Get a corner coordinate of an extent. + * @param {Extent} extent Extent. + * @param {Corner} corner Corner. + * @return {import("./coordinate.js").Coordinate} Corner coordinate. + */ +function getCorner(extent, corner) { + let coordinate; + if (corner === 'bottom-left') { + coordinate = getBottomLeft(extent); + } else if (corner === 'bottom-right') { + coordinate = getBottomRight(extent); + } else if (corner === 'top-left') { + coordinate = getTopLeft(extent); + } else if (corner === 'top-right') { + coordinate = getTopRight(extent); + } else { + throw new Error('Invalid corner'); + } + return coordinate; +} + +/** + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent 2. + * @return {number} Enlarged area. + */ +function getEnlargedArea(extent1, extent2) { + const minX = Math.min(extent1[0], extent2[0]); + const minY = Math.min(extent1[1], extent2[1]); + const maxX = Math.max(extent1[2], extent2[2]); + const maxY = Math.max(extent1[3], extent2[3]); + return (maxX - minX) * (maxY - minY); +} + +/** + * @param {import("./coordinate.js").Coordinate} center Center. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @param {import("./size.js").Size} size Size. + * @param {Extent} [dest] Destination extent. + * @return {Extent} Extent. + */ +function getForViewAndSize(center, resolution, rotation, size, dest) { + const [x0, y0, x1, y1, x2, y2, x3, y3] = getRotatedViewport( + center, + resolution, + rotation, + size, + ); + return createOrUpdate( + Math.min(x0, x1, x2, x3), + Math.min(y0, y1, y2, y3), + Math.max(x0, x1, x2, x3), + Math.max(y0, y1, y2, y3), + dest, + ); +} + +/** + * @param {import("./coordinate.js").Coordinate} center Center. + * @param {number} resolution Resolution. + * @param {number} rotation Rotation. + * @param {import("./size.js").Size} size Size. + * @return {Array} Linear ring representing the viewport. + */ +function getRotatedViewport(center, resolution, rotation, size) { + const dx = (resolution * size[0]) / 2; + const dy = (resolution * size[1]) / 2; + const cosRotation = Math.cos(rotation); + const sinRotation = Math.sin(rotation); + const xCos = dx * cosRotation; + const xSin = dx * sinRotation; + const yCos = dy * cosRotation; + const ySin = dy * sinRotation; + const x = center[0]; + const y = center[1]; + return [ + x - xCos + ySin, + y - xSin - yCos, + x - xCos - ySin, + y - xSin + yCos, + x + xCos - ySin, + y + xSin + yCos, + x + xCos + ySin, + y + xSin - yCos, + x - xCos + ySin, + y - xSin - yCos, + ]; +} + +/** + * Get the height of an extent. + * @param {Extent} extent Extent. + * @return {number} Height. + * @api + */ +function getHeight(extent) { + return extent[3] - extent[1]; +} + +/** + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent 2. + * @return {number} Intersection area. + */ +function getIntersectionArea(extent1, extent2) { + const intersection = getIntersection(extent1, extent2); + return getArea(intersection); +} + +/** + * Get the intersection of two extents. + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent 2. + * @param {Extent} [dest] Optional extent to populate with intersection. + * @return {Extent} Intersecting extent. + * @api + */ +function getIntersection(extent1, extent2, dest) { + const intersection = dest ? dest : createEmpty(); + if (intersects(extent1, extent2)) { + if (extent1[0] > extent2[0]) { + intersection[0] = extent1[0]; + } else { + intersection[0] = extent2[0]; + } + if (extent1[1] > extent2[1]) { + intersection[1] = extent1[1]; + } else { + intersection[1] = extent2[1]; + } + if (extent1[2] < extent2[2]) { + intersection[2] = extent1[2]; + } else { + intersection[2] = extent2[2]; + } + if (extent1[3] < extent2[3]) { + intersection[3] = extent1[3]; + } else { + intersection[3] = extent2[3]; + } + } else { + createOrUpdateEmpty(intersection); + } + return intersection; +} + +/** + * @param {Extent} extent Extent. + * @return {number} Margin. + */ +function getMargin(extent) { + return getWidth(extent) + getHeight(extent); +} + +/** + * Get the size (width, height) of an extent. + * @param {Extent} extent The extent. + * @return {import("./size.js").Size} The extent size. + * @api + */ +function getSize(extent) { + return [extent[2] - extent[0], extent[3] - extent[1]]; +} + +/** + * Get the top left coordinate of an extent. + * @param {Extent} extent Extent. + * @return {import("./coordinate.js").Coordinate} Top left coordinate. + * @api + */ +function getTopLeft(extent) { + return [extent[0], extent[3]]; +} + +/** + * Get the top right coordinate of an extent. + * @param {Extent} extent Extent. + * @return {import("./coordinate.js").Coordinate} Top right coordinate. + * @api + */ +function getTopRight(extent) { + return [extent[2], extent[3]]; +} + +/** + * Get the width of an extent. + * @param {Extent} extent Extent. + * @return {number} Width. + * @api + */ +function getWidth(extent) { + return extent[2] - extent[0]; +} + +/** + * Determine if one extent intersects another. + * @param {Extent} extent1 Extent 1. + * @param {Extent} extent2 Extent. + * @return {boolean} The two extents intersect. + * @api + */ +function intersects(extent1, extent2) { + return ( + extent1[0] <= extent2[2] && + extent1[2] >= extent2[0] && + extent1[1] <= extent2[3] && + extent1[3] >= extent2[1] + ); +} + +/** + * Determine if an extent is empty. + * @param {Extent} extent Extent. + * @return {boolean} Is empty. + * @api + */ +function isEmpty(extent) { + return extent[2] < extent[0] || extent[3] < extent[1]; +} + +/** + * @param {Extent} extent Extent. + * @param {Extent} [dest] Extent. + * @return {Extent} Extent. + */ +function returnOrUpdate(extent, dest) { + if (dest) { + dest[0] = extent[0]; + dest[1] = extent[1]; + dest[2] = extent[2]; + dest[3] = extent[3]; + return dest; + } + return extent; +} + +/** + * @param {Extent} extent Extent. + * @param {number} value Value. + */ +function scaleFromCenter(extent, value) { + const deltaX = ((extent[2] - extent[0]) / 2) * (value - 1); + const deltaY = ((extent[3] - extent[1]) / 2) * (value - 1); + extent[0] -= deltaX; + extent[2] += deltaX; + extent[1] -= deltaY; + extent[3] += deltaY; +} + +/** + * Determine if the segment between two coordinates intersects (crosses, + * touches, or is contained by) the provided extent. + * @param {Extent} extent The extent. + * @param {import("./coordinate.js").Coordinate} start Segment start coordinate. + * @param {import("./coordinate.js").Coordinate} end Segment end coordinate. + * @return {boolean} The segment intersects the extent. + */ +function intersectsSegment(extent, start, end) { + let intersects = false; + const startRel = coordinateRelationship(extent, start); + const endRel = coordinateRelationship(extent, end); + if ( + startRel === _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].INTERSECTING || + endRel === _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].INTERSECTING + ) { + intersects = true; + } else { + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const startX = start[0]; + const startY = start[1]; + const endX = end[0]; + const endY = end[1]; + const slope = (endY - startY) / (endX - startX); + let x, y; + if (!!(endRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].ABOVE) && !(startRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].ABOVE)) { + // potentially intersects top + x = endX - (endY - maxY) / slope; + intersects = x >= minX && x <= maxX; + } + if ( + !intersects && + !!(endRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].RIGHT) && + !(startRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].RIGHT) + ) { + // potentially intersects right + y = endY - (endX - maxX) * slope; + intersects = y >= minY && y <= maxY; + } + if ( + !intersects && + !!(endRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].BELOW) && + !(startRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].BELOW) + ) { + // potentially intersects bottom + x = endX - (endY - minY) / slope; + intersects = x >= minX && x <= maxX; + } + if ( + !intersects && + !!(endRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].LEFT) && + !(startRel & _extent_Relationship_js__WEBPACK_IMPORTED_MODULE_0__["default"].LEFT) + ) { + // potentially intersects left + y = endY - (endX - minX) * slope; + intersects = y >= minY && y <= maxY; + } + } + return intersects; +} + +/** + * Apply a transform function to the extent. + * @param {Extent} extent Extent. + * @param {import("./proj.js").TransformFunction} transformFn Transform function. + * Called with `[minX, minY, maxX, maxY]` extent coordinates. + * @param {Extent} [dest] Destination extent. + * @param {number} [stops] Number of stops per side used for the transform. + * By default only the corners are used. + * @return {Extent} Extent. + * @api + */ +function applyTransform(extent, transformFn, dest, stops) { + if (isEmpty(extent)) { + return createOrUpdateEmpty(dest); + } + let coordinates = []; + if (stops > 1) { + const width = extent[2] - extent[0]; + const height = extent[3] - extent[1]; + for (let i = 0; i < stops; ++i) { + coordinates.push( + extent[0] + (width * i) / stops, + extent[1], + extent[2], + extent[1] + (height * i) / stops, + extent[2] - (width * i) / stops, + extent[3], + extent[0], + extent[3] - (height * i) / stops, + ); + } + } else { + coordinates = [ + extent[0], + extent[1], + extent[2], + extent[1], + extent[2], + extent[3], + extent[0], + extent[3], + ]; + } + transformFn(coordinates, coordinates, 2); + const xs = []; + const ys = []; + for (let i = 0, l = coordinates.length; i < l; i += 2) { + xs.push(coordinates[i]); + ys.push(coordinates[i + 1]); + } + return _boundingExtentXYs(xs, ys, dest); +} + +/** + * Modifies the provided extent in-place to be within the real world + * extent. + * + * @param {Extent} extent Extent. + * @param {import("./proj/Projection.js").default} projection Projection + * @return {Extent} The extent within the real world extent. + */ +function wrapX(extent, projection) { + const projectionExtent = projection.getExtent(); + const center = getCenter(extent); + if ( + projection.canWrapX() && + (center[0] < projectionExtent[0] || center[0] >= projectionExtent[2]) + ) { + const worldWidth = getWidth(projectionExtent); + const worldsAway = Math.floor( + (center[0] - projectionExtent[0]) / worldWidth, + ); + const offset = worldsAway * worldWidth; + extent[0] -= offset; + extent[2] -= offset; + } + return extent; +} + +/** + * Fits the extent to the real world + * + * If the extent does not cross the anti meridian, this will return the extent in an array + * If the extent crosses the anti meridian, the extent will be sliced, so each part fits within the + * real world + * + * + * @param {Extent} extent Extent. + * @param {import("./proj/Projection.js").default} projection Projection + * @param {boolean} [multiWorld] Return all worlds + * @return {Array} The extent within the real world extent. + */ +function wrapAndSliceX(extent, projection, multiWorld) { + if (projection.canWrapX()) { + const projectionExtent = projection.getExtent(); + + if (!isFinite(extent[0]) || !isFinite(extent[2])) { + return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]]; + } + + wrapX(extent, projection); + const worldWidth = getWidth(projectionExtent); + + if (getWidth(extent) > worldWidth && !multiWorld) { + // the extent wraps around on itself + return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]]; + } + if (extent[0] < projectionExtent[0]) { + // the extent crosses the anti meridian, so it needs to be sliced + return [ + [extent[0] + worldWidth, extent[1], projectionExtent[2], extent[3]], + [projectionExtent[0], extent[1], extent[2], extent[3]], + ]; + } + if (extent[2] > projectionExtent[2]) { + // the extent crosses the anti meridian, so it needs to be sliced + return [ + [extent[0], extent[1], projectionExtent[2], extent[3]], + [projectionExtent[0], extent[1], extent[2] - worldWidth, extent[3]], + ]; + } + } + + return [extent]; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/extent/Relationship.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/extent/Relationship.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/extent/Relationship + */ + +/** + * Relationship to an extent. + * @enum {number} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + UNKNOWN: 0, + INTERSECTING: 1, + ABOVE: 2, + RIGHT: 4, + BELOW: 8, + LEFT: 16, +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/featureloader.js": +/*!**************************************************!*\ + !*** ./node_modules/@biigle/ol/featureloader.js ***! + \**************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "loadFeaturesXhr": () => (/* binding */ loadFeaturesXhr), +/* harmony export */ "setWithCredentials": () => (/* binding */ setWithCredentials), +/* harmony export */ "xhr": () => (/* binding */ xhr) +/* harmony export */ }); +/* harmony import */ var _functions_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./functions.js */ "./node_modules/@biigle/ol/functions.js"); +/** + * @module ol/featureloader + */ + + +/** + * + * @type {boolean} + * @private + */ +let withCredentials = false; + +/** + * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to + * load features. + * + * This function takes up to 5 arguments. These are an {@link module:ol/extent~Extent} representing + * the area to be loaded, a `{number}` representing the resolution (map units per pixel), an + * {@link module:ol/proj/Projection~Projection} for the projection, an optional success callback that should get + * the loaded features passed as an argument and an optional failure callback with no arguments. If + * the callbacks are not used, the corresponding vector source will not fire `'featuresloadend'` and + * `'featuresloaderror'` events. `this` within the function is bound to the + * {@link module:ol/source/Vector~VectorSource} it's called from. + * + * The function is responsible for loading the features and adding them to the + * source. + * + * @template {import("./Feature.js").FeatureLike} [FeatureType=import("./Feature.js").default] + * @typedef {function(this:(import("./source/Vector").default|import("./VectorTile.js").default), + * import("./extent.js").Extent, + * number, + * import("./proj/Projection.js").default, + * function(Array): void=, + * function(): void=): void} FeatureLoader + * @api + */ + +/** + * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to + * get the url to load features from. + * + * This function takes an {@link module:ol/extent~Extent} representing the area + * to be loaded, a `{number}` representing the resolution (map units per pixel) + * and an {@link module:ol/proj/Projection~Projection} for the projection as + * arguments and returns a `{string}` representing the URL. + * @typedef {function(import("./extent.js").Extent, number, import("./proj/Projection.js").default): string} FeatureUrlFunction + * @api + */ + +/** + * @template {import("./Feature.js").FeatureLike} [FeatureType=import("./Feature.js").FeatureLike] + * @param {string|FeatureUrlFunction} url Feature URL service. + * @param {import("./format/Feature.js").default>} format Feature format. + * @param {import("./extent.js").Extent} extent Extent. + * @param {number} resolution Resolution. + * @param {import("./proj/Projection.js").default} projection Projection. + * @param {function(Array, import("./proj/Projection.js").default): void} success Success + * Function called with the loaded features and optionally with the data projection. + * @param {function(): void} failure Failure + * Function called when loading failed. + */ +function loadFeaturesXhr( + url, + format, + extent, + resolution, + projection, + success, + failure, +) { + const xhr = new XMLHttpRequest(); + xhr.open( + 'GET', + typeof url === 'function' ? url(extent, resolution, projection) : url, + true, + ); + if (format.getType() == 'arraybuffer') { + xhr.responseType = 'arraybuffer'; + } + xhr.withCredentials = withCredentials; + /** + * @param {Event} event Event. + * @private + */ + xhr.onload = function (event) { + // status will be 0 for file:// urls + if (!xhr.status || (xhr.status >= 200 && xhr.status < 300)) { + const type = format.getType(); + try { + /** @type {Document|Node|Object|string|undefined} */ + let source; + if (type == 'text' || type == 'json') { + source = xhr.responseText; + } else if (type == 'xml') { + source = xhr.responseXML || xhr.responseText; + } else if (type == 'arraybuffer') { + source = /** @type {ArrayBuffer} */ (xhr.response); + } + if (source) { + success( + /** @type {Array} */ + ( + format.readFeatures(source, { + extent: extent, + featureProjection: projection, + }) + ), + format.readProjection(source), + ); + } else { + failure(); + } + } catch { + failure(); + } + } else { + failure(); + } + }; + /** + * @private + */ + xhr.onerror = failure; + xhr.send(); +} + +/** + * Create an XHR feature loader for a `url` and `format`. The feature loader + * loads features (with XHR), parses the features, and adds them to the + * vector source. + * @template {import("./Feature.js").FeatureLike} [FeatureType=import("./Feature.js").FeatureLike] + * @param {string|FeatureUrlFunction} url Feature URL service. + * @param {import("./format/Feature.js").default>} format Feature format. + * @return {FeatureLoader} The feature loader. + * @api + */ +function xhr(url, format) { + /** + * @param {import("./extent.js").Extent} extent Extent. + * @param {number} resolution Resolution. + * @param {import("./proj/Projection.js").default} projection Projection. + * @param {function(Array): void} [success] Success + * Function called when loading succeeded. + * @param {function(): void} [failure] Failure + * Function called when loading failed. + */ + return function (extent, resolution, projection, success, failure) { + const source = + /** @type {import("./source/Vector").default} */ (this); + loadFeaturesXhr( + url, + format, + extent, + resolution, + projection, + /** + * @param {Array} features The loaded features. + * @param {import("./proj/Projection.js").default} dataProjection Data + * projection. + */ + function (features, dataProjection) { + source.addFeatures(features); + if (success !== undefined) { + success(features); + } + }, + /* FIXME handle error */ failure ? failure : _functions_js__WEBPACK_IMPORTED_MODULE_0__.VOID, + ); + }; +} + +/** + * Setter for the withCredentials configuration for the XHR. + * + * @param {boolean} xhrWithCredentials The value of withCredentials to set. + * Compare https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/ + * @api + */ +function setWithCredentials(xhrWithCredentials) { + withCredentials = xhrWithCredentials; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/functions.js": +/*!**********************************************!*\ + !*** ./node_modules/@biigle/ol/functions.js ***! + \**********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "FALSE": () => (/* binding */ FALSE), +/* harmony export */ "TRUE": () => (/* binding */ TRUE), +/* harmony export */ "VOID": () => (/* binding */ VOID), +/* harmony export */ "memoizeOne": () => (/* binding */ memoizeOne), +/* harmony export */ "toPromise": () => (/* binding */ toPromise) +/* harmony export */ }); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./array.js */ "./node_modules/@biigle/ol/array.js"); +/** + * @module ol/functions + */ + + + +/** + * Always returns true. + * @return {boolean} true. + */ +function TRUE() { + return true; +} + +/** + * Always returns false. + * @return {boolean} false. + */ +function FALSE() { + return false; +} + +/** + * A reusable function, used e.g. as a default for callbacks. + * + * @return {void} Nothing. + */ +function VOID() {} + +/** + * Wrap a function in another function that remembers the last return. If the + * returned function is called twice in a row with the same arguments and the same + * this object, it will return the value from the first call in the second call. + * + * @param {function(...any): ReturnType} fn The function to memoize. + * @return {function(...any): ReturnType} The memoized function. + * @template ReturnType + */ +function memoizeOne(fn) { + let called = false; + + /** @type {ReturnType} */ + let lastResult; + + /** @type {Array} */ + let lastArgs; + + let lastThis; + + return function () { + const nextArgs = Array.prototype.slice.call(arguments); + if (!called || this !== lastThis || !(0,_array_js__WEBPACK_IMPORTED_MODULE_0__.equals)(nextArgs, lastArgs)) { + called = true; + lastThis = this; + lastArgs = nextArgs; + lastResult = fn.apply(this, arguments); + } + return lastResult; + }; +} + +/** + * @template T + * @param {function(): (T | Promise)} getter A function that returns a value or a promise for a value. + * @return {Promise} A promise for the value. + */ +function toPromise(getter) { + function promiseGetter() { + let value; + try { + value = getter(); + } catch (err) { + return Promise.reject(err); + } + if (value instanceof Promise) { + return value; + } + return Promise.resolve(value); + } + return promiseGetter(); +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/Geometry.js": +/*!**************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/Geometry.js ***! + \**************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Object_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Object.js */ "./node_modules/@biigle/ol/Object.js"); +/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../util.js */ "./node_modules/@biigle/ol/util.js"); +/* harmony import */ var _transform_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../transform.js */ "./node_modules/@biigle/ol/transform.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _proj_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../proj.js */ "./node_modules/@biigle/ol/proj.js"); +/* harmony import */ var _functions_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../functions.js */ "./node_modules/@biigle/ol/functions.js"); +/* harmony import */ var _flat_transform_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flat/transform.js */ "./node_modules/@biigle/ol/geom/flat/transform.js"); +/** + * @module ol/geom/Geometry + */ + + + + + + + + +/** + * @typedef {'XY' | 'XYZ' | 'XYM' | 'XYZM'} GeometryLayout + * The coordinate layout for geometries, indicating whether a 3rd or 4th z ('Z') + * or measure ('M') coordinate is available. + */ + +/** + * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString' | 'MultiPolygon' | 'GeometryCollection' | 'Circle' | 'Ellipse' | 'Rectangle'} Type + * The geometry type. One of `'Point'`, `'LineString'`, `'LinearRing'`, + * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`, + * `'GeometryCollection'`, `'Circle'`, `'Ellipse'`, or `'Rectangle'`. + */ + +/** + * @type {import("../transform.js").Transform} + */ +const tmpTransform = (0,_transform_js__WEBPACK_IMPORTED_MODULE_1__.create)(); + +/** + * @classdesc + * Abstract base class; normally only used for creating subclasses and not + * instantiated in apps. + * Base class for vector geometries. + * + * To get notified of changes to the geometry, register a listener for the + * generic `change` event on your geometry instance. + * + * @abstract + * @api + */ +class Geometry extends _Object_js__WEBPACK_IMPORTED_MODULE_2__["default"] { + constructor() { + super(); + + /** + * @private + * @type {import("../extent.js").Extent} + */ + this.extent_ = (0,_extent_js__WEBPACK_IMPORTED_MODULE_3__.createEmpty)(); + + /** + * @private + * @type {number} + */ + this.extentRevision_ = -1; + + /** + * @protected + * @type {number} + */ + this.simplifiedGeometryMaxMinSquaredTolerance = 0; + + /** + * @protected + * @type {number} + */ + this.simplifiedGeometryRevision = 0; + + /** + * Get a transformed and simplified version of the geometry. + * @abstract + * @param {number} revision The geometry revision. + * @param {number} squaredTolerance Squared tolerance. + * @param {import("../proj.js").TransformFunction} [transform] Optional transform function. + * @return {Geometry} Simplified geometry. + */ + this.simplifyTransformedInternal = (0,_functions_js__WEBPACK_IMPORTED_MODULE_4__.memoizeOne)( + (revision, squaredTolerance, transform) => { + if (!transform) { + return this.getSimplifiedGeometry(squaredTolerance); + } + const clone = this.clone(); + clone.applyTransform(transform); + return clone.getSimplifiedGeometry(squaredTolerance); + }, + ); + } + + /** + * Get a transformed and simplified version of the geometry. + * @abstract + * @param {number} squaredTolerance Squared tolerance. + * @param {import("../proj.js").TransformFunction} [transform] Optional transform function. + * @return {Geometry} Simplified geometry. + */ + simplifyTransformed(squaredTolerance, transform) { + return this.simplifyTransformedInternal( + this.getRevision(), + squaredTolerance, + transform, + ); + } + + /** + * Make a complete copy of the geometry. + * @abstract + * @return {!Geometry} Clone. + */ + clone() { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * @abstract + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + const coord = this.getClosestPoint([x, y]); + return coord[0] === x && coord[1] === y; + } + + /** + * Return the closest point of the geometry to the passed point as + * {@link module:ol/coordinate~Coordinate coordinate}. + * @param {import("../coordinate.js").Coordinate} point Point. + * @param {import("../coordinate.js").Coordinate} [closestPoint] Closest point. + * @return {import("../coordinate.js").Coordinate} Closest point. + * @api + */ + getClosestPoint(point, closestPoint) { + closestPoint = closestPoint ? closestPoint : [NaN, NaN]; + this.closestPointXY(point[0], point[1], closestPoint, Infinity); + return closestPoint; + } + + /** + * Returns true if this geometry includes the specified coordinate. If the + * coordinate is on the boundary of the geometry, returns false. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @return {boolean} Contains coordinate. + * @api + */ + intersectsCoordinate(coordinate) { + return this.containsXY(coordinate[0], coordinate[1]); + } + + /** + * @abstract + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Get the extent of the geometry. + * @param {import("../extent.js").Extent} [extent] Extent. + * @return {import("../extent.js").Extent} extent Extent. + * @api + */ + getExtent(extent) { + if (this.extentRevision_ != this.getRevision()) { + const extent = this.computeExtent(this.extent_); + if (isNaN(extent[0]) || isNaN(extent[1])) { + (0,_extent_js__WEBPACK_IMPORTED_MODULE_3__.createOrUpdateEmpty)(extent); + } + this.extentRevision_ = this.getRevision(); + } + return (0,_extent_js__WEBPACK_IMPORTED_MODULE_3__.returnOrUpdate)(this.extent_, extent); + } + + /** + * Rotate the geometry around a given coordinate. This modifies the geometry + * coordinates in place. + * @abstract + * @param {number} angle Rotation angle in radians. + * @param {import("../coordinate.js").Coordinate} anchor The rotation center. + * @api + */ + rotate(angle, anchor) { + (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Scale the geometry (with an optional origin). This modifies the geometry + * coordinates in place. + * @abstract + * @param {number} sx The scaling factor in the x-direction. + * @param {number} [sy] The scaling factor in the y-direction (defaults to sx). + * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center + * of the geometry extent). + * @api + */ + scale(sx, sy, anchor) { + (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Create a simplified version of this geometry. For linestrings, this uses + * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm) + * algorithm. For polygons, a quantization-based + * simplification is used to preserve topology. + * @param {number} tolerance The tolerance distance for simplification. + * @return {Geometry} A new, simplified version of the original geometry. + * @api + */ + simplify(tolerance) { + return this.getSimplifiedGeometry(tolerance * tolerance); + } + + /** + * Create a simplified version of this geometry using the Douglas Peucker + * algorithm. + * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm. + * @abstract + * @param {number} squaredTolerance Squared tolerance. + * @return {Geometry} Simplified geometry. + */ + getSimplifiedGeometry(squaredTolerance) { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Get the type of this geometry. + * @abstract + * @return {Type} Geometry type. + */ + getType() { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Apply a transform function to the coordinates of the geometry. + * The geometry is modified in place. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * @abstract + * @param {import("../proj.js").TransformFunction} transformFn Transform function. + * Called with a flat array of geometry coordinates. + */ + applyTransform(transformFn) { + (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Test if the geometry and the passed extent intersect. + * @abstract + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + */ + intersectsExtent(extent) { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Translate the geometry. This modifies the geometry coordinates in place. If + * instead you want a new geometry, first `clone()` this geometry. + * @abstract + * @param {number} deltaX Delta X. + * @param {number} deltaY Delta Y. + * @api + */ + translate(deltaX, deltaY) { + (0,_util_js__WEBPACK_IMPORTED_MODULE_5__.abstract)(); + } + + /** + * Transform each coordinate of the geometry from one coordinate reference + * system to another. The geometry is modified in place. + * For example, a line will be transformed to a line and a circle to a circle. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * + * @param {import("../proj.js").ProjectionLike} source The current projection. Can be a + * string identifier or a {@link module:ol/proj/Projection~Projection} object. + * @param {import("../proj.js").ProjectionLike} destination The desired projection. Can be a + * string identifier or a {@link module:ol/proj/Projection~Projection} object. + * @return {this} This geometry. Note that original geometry is + * modified in place. + * @api + */ + transform(source, destination) { + /** @type {import("../proj/Projection.js").default} */ + const sourceProj = (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.get)(source); + const transformFn = + sourceProj.getUnits() == 'tile-pixels' + ? function (inCoordinates, outCoordinates, stride) { + const pixelExtent = sourceProj.getExtent(); + const projectedExtent = sourceProj.getWorldExtent(); + const scale = (0,_extent_js__WEBPACK_IMPORTED_MODULE_3__.getHeight)(projectedExtent) / (0,_extent_js__WEBPACK_IMPORTED_MODULE_3__.getHeight)(pixelExtent); + (0,_transform_js__WEBPACK_IMPORTED_MODULE_1__.compose)( + tmpTransform, + projectedExtent[0], + projectedExtent[3], + scale, + -scale, + 0, + 0, + 0, + ); + (0,_flat_transform_js__WEBPACK_IMPORTED_MODULE_6__.transform2D)( + inCoordinates, + 0, + inCoordinates.length, + stride, + tmpTransform, + outCoordinates, + ); + return (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.getTransform)(sourceProj, destination)( + inCoordinates, + outCoordinates, + stride, + ); + } + : (0,_proj_js__WEBPACK_IMPORTED_MODULE_0__.getTransform)(sourceProj, destination); + this.applyTransform(transformFn); + return this; + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Geometry); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/LineString.js": +/*!****************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/LineString.js ***! + \****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _flat_closest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/closest.js */ "./node_modules/@biigle/ol/geom/flat/closest.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _flat_simplify_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./flat/simplify.js */ "./node_modules/@biigle/ol/geom/flat/simplify.js"); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _flat_segments_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./flat/segments.js */ "./node_modules/@biigle/ol/geom/flat/segments.js"); +/* harmony import */ var _flat_inflate_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flat/inflate.js */ "./node_modules/@biigle/ol/geom/flat/inflate.js"); +/* harmony import */ var _flat_interpolate_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flat/interpolate.js */ "./node_modules/@biigle/ol/geom/flat/interpolate.js"); +/* harmony import */ var _flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./flat/intersectsextent.js */ "./node_modules/@biigle/ol/geom/flat/intersectsextent.js"); +/* harmony import */ var _flat_length_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./flat/length.js */ "./node_modules/@biigle/ol/geom/flat/length.js"); +/** + * @module ol/geom/LineString + */ + + + + + + + + + + + + +/** + * @classdesc + * Linestring geometry. + * + * @api + */ +class LineString extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Array|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates, layout) { + super(); + + /** + * @private + * @type {import("../coordinate.js").Coordinate|null} + */ + this.flatMidpoint_ = null; + + /** + * @private + * @type {number} + */ + this.flatMidpointRevision_ = -1; + + /** + * @private + * @type {number} + */ + this.maxDelta_ = -1; + + /** + * @private + * @type {number} + */ + this.maxDeltaRevision_ = -1; + + if (layout !== undefined && !Array.isArray(coordinates[0])) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ (coordinates), + ); + } else { + this.setCoordinates( + /** @type {Array} */ ( + coordinates + ), + layout, + ); + } + } + + /** + * Append the passed coordinate to the coordinates of the linestring. + * @param {import("../coordinate.js").Coordinate} coordinate Coordinate. + * @api + */ + appendCoordinate(coordinate) { + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(this.flatCoordinates, coordinate); + this.changed(); + } + + /** + * Make a complete copy of the geometry. + * @return {!LineString} Clone. + * @api + */ + clone() { + const lineString = new LineString( + this.flatCoordinates.slice(), + this.layout, + ); + lineString.applyProperties(this); + return lineString; + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.closestSquaredDistanceXY)(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.maxSquaredDelta)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + 0, + ), + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.assignClosestPoint)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + this.maxDelta_, + false, + x, + y, + closestPoint, + minSquaredDistance, + ); + } + + /** + * Iterate over each segment, calling the provided callback. + * If the callback returns a truthy value the function returns that + * value immediately. Otherwise the function returns `false`. + * + * @param {function(this: S, import("../coordinate.js").Coordinate, import("../coordinate.js").Coordinate): T} callback Function + * called for each segment. The function will receive two arguments, the start and end coordinates of the segment. + * @return {T|boolean} Value. + * @template T,S + * @api + */ + forEachSegment(callback) { + return (0,_flat_segments_js__WEBPACK_IMPORTED_MODULE_4__.forEach)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + callback, + ); + } + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * @param {number} m M. + * @param {boolean} [extrapolate] Extrapolate. Default is `false`. + * @return {import("../coordinate.js").Coordinate|null} Coordinate. + * @api + */ + getCoordinateAtM(m, extrapolate) { + if (this.layout != 'XYM' && this.layout != 'XYZM') { + return null; + } + extrapolate = extrapolate !== undefined ? extrapolate : false; + return (0,_flat_interpolate_js__WEBPACK_IMPORTED_MODULE_5__.lineStringCoordinateAtM)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + m, + extrapolate, + ); + } + + /** + * Return the coordinates of the linestring. + * @return {Array} Coordinates. + * @api + */ + getCoordinates() { + return (0,_flat_inflate_js__WEBPACK_IMPORTED_MODULE_6__.inflateCoordinates)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + ); + } + + /** + * Return the coordinate at the provided fraction along the linestring. + * The `fraction` is a number between 0 and 1, where 0 is the start of the + * linestring and 1 is the end. + * @param {number} fraction Fraction. + * @param {import("../coordinate.js").Coordinate} [dest] Optional coordinate whose values will + * be modified. If not provided, a new coordinate will be returned. + * @return {import("../coordinate.js").Coordinate} Coordinate of the interpolated point. + * @api + */ + getCoordinateAt(fraction, dest) { + return (0,_flat_interpolate_js__WEBPACK_IMPORTED_MODULE_5__.interpolatePoint)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + fraction, + dest, + this.stride, + ); + } + + /** + * Return the length of the linestring on projected plane. + * @return {number} Length (on projected plane). + * @api + */ + getLength() { + return (0,_flat_length_js__WEBPACK_IMPORTED_MODULE_7__.lineStringLength)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + ); + } + + /** + * @return {Array} Flat midpoint. + */ + getFlatMidpoint() { + if (this.flatMidpointRevision_ != this.getRevision()) { + this.flatMidpoint_ = this.getCoordinateAt( + 0.5, + this.flatMidpoint_ ?? undefined, + ); + this.flatMidpointRevision_ = this.getRevision(); + } + return /** @type {Array} */ (this.flatMidpoint_); + } + + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {LineString} Simplified LineString. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + /** @type {Array} */ + const simplifiedFlatCoordinates = []; + simplifiedFlatCoordinates.length = (0,_flat_simplify_js__WEBPACK_IMPORTED_MODULE_8__.douglasPeucker)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0, + ); + return new LineString(simplifiedFlatCoordinates, 'XY'); + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'LineString'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return (0,_flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_9__.intersectsLineString)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + extent, + ); + } + + /** + * Set the coordinates of the linestring. + * @param {!Array} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 1); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_10__.deflateCoordinates)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + ); + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (LineString); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/LinearRing.js": +/*!****************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/LinearRing.js ***! + \****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _flat_closest_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./flat/closest.js */ "./node_modules/@biigle/ol/geom/flat/closest.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _flat_simplify_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flat/simplify.js */ "./node_modules/@biigle/ol/geom/flat/simplify.js"); +/* harmony import */ var _flat_inflate_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./flat/inflate.js */ "./node_modules/@biigle/ol/geom/flat/inflate.js"); +/* harmony import */ var _flat_area_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/area.js */ "./node_modules/@biigle/ol/geom/flat/area.js"); +/** + * @module ol/geom/LinearRing + */ + + + + + + + + +/** + * @classdesc + * Linear ring geometry. Only used as part of polygon; cannot be rendered + * on its own. + * + * @api + */ +class LinearRing extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Array|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates, layout) { + super(); + + /** + * @private + * @type {number} + */ + this.maxDelta_ = -1; + + /** + * @private + * @type {number} + */ + this.maxDeltaRevision_ = -1; + + if (layout !== undefined && !Array.isArray(coordinates[0])) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ (coordinates), + ); + } else { + this.setCoordinates( + /** @type {Array} */ ( + coordinates + ), + layout, + ); + } + } + + /** + * Make a complete copy of the geometry. + * @return {!LinearRing} Clone. + * @api + */ + clone() { + return new LinearRing(this.flatCoordinates.slice(), this.layout); + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < (0,_extent_js__WEBPACK_IMPORTED_MODULE_1__.closestSquaredDistanceXY)(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_2__.maxSquaredDelta)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + 0, + ), + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_2__.assignClosestPoint)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + this.maxDelta_, + true, + x, + y, + closestPoint, + minSquaredDistance, + ); + } + + /** + * Return the area of the linear ring on projected plane. + * @return {number} Area (on projected plane). + * @api + */ + getArea() { + return (0,_flat_area_js__WEBPACK_IMPORTED_MODULE_3__.linearRing)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + ); + } + + /** + * Return the coordinates of the linear ring. + * @return {Array} Coordinates. + * @api + */ + getCoordinates() { + return (0,_flat_inflate_js__WEBPACK_IMPORTED_MODULE_4__.inflateCoordinates)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + ); + } + + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {LinearRing} Simplified LinearRing. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + /** @type {Array} */ + const simplifiedFlatCoordinates = []; + simplifiedFlatCoordinates.length = (0,_flat_simplify_js__WEBPACK_IMPORTED_MODULE_5__.douglasPeucker)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0, + ); + return new LinearRing(simplifiedFlatCoordinates, 'XY'); + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'LinearRing'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return false; + } + + /** + * Set the coordinates of the linear ring. + * @param {!Array} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 1); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_6__.deflateCoordinates)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + ); + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (LinearRing); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/MultiLineString.js": +/*!*********************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/MultiLineString.js ***! + \*********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _LineString_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./LineString.js */ "./node_modules/@biigle/ol/geom/LineString.js"); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _flat_closest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/closest.js */ "./node_modules/@biigle/ol/geom/flat/closest.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _flat_simplify_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./flat/simplify.js */ "./node_modules/@biigle/ol/geom/flat/simplify.js"); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _flat_inflate_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flat/inflate.js */ "./node_modules/@biigle/ol/geom/flat/inflate.js"); +/* harmony import */ var _flat_interpolate_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./flat/interpolate.js */ "./node_modules/@biigle/ol/geom/flat/interpolate.js"); +/* harmony import */ var _flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./flat/intersectsextent.js */ "./node_modules/@biigle/ol/geom/flat/intersectsextent.js"); +/** + * @module ol/geom/MultiLineString + */ + + + + + + + + + + + +/** + * @classdesc + * Multi-linestring geometry. + * + * @api + */ +class MultiLineString extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Array|LineString>|Array} coordinates + * Coordinates or LineString geometries. (For internal use, flat coordinates in + * combination with `layout` and `ends` are also accepted.) + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @param {Array} [ends] Flat coordinate ends for internal use. + */ + constructor(coordinates, layout, ends) { + super(); + + /** + * @type {Array} + * @private + */ + this.ends_ = []; + + /** + * @private + * @type {number} + */ + this.maxDelta_ = -1; + + /** + * @private + * @type {number} + */ + this.maxDeltaRevision_ = -1; + + if (Array.isArray(coordinates[0])) { + this.setCoordinates( + /** @type {Array>} */ ( + coordinates + ), + layout, + ); + } else if (layout !== undefined && ends) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ (coordinates), + ); + this.ends_ = ends; + } else { + const lineStrings = /** @type {Array} */ (coordinates); + /** @type {Array} */ + const flatCoordinates = []; + const ends = []; + for (let i = 0, ii = lineStrings.length; i < ii; ++i) { + const lineString = lineStrings[i]; + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(flatCoordinates, lineString.getFlatCoordinates()); + ends.push(flatCoordinates.length); + } + const layout = + lineStrings.length === 0 + ? this.getLayout() + : lineStrings[0].getLayout(); + this.setFlatCoordinates(layout, flatCoordinates); + this.ends_ = ends; + } + } + + /** + * Append the passed linestring to the multilinestring. + * @param {LineString} lineString LineString. + * @api + */ + appendLineString(lineString) { + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(this.flatCoordinates, lineString.getFlatCoordinates().slice()); + this.ends_.push(this.flatCoordinates.length); + this.changed(); + } + + /** + * Make a complete copy of the geometry. + * @return {!MultiLineString} Clone. + * @api + */ + clone() { + const multiLineString = new MultiLineString( + this.flatCoordinates.slice(), + this.layout, + this.ends_.slice(), + ); + multiLineString.applyProperties(this); + return multiLineString; + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.closestSquaredDistanceXY)(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.arrayMaxSquaredDelta)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + 0, + ), + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.assignClosestArrayPoint)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + this.maxDelta_, + false, + x, + y, + closestPoint, + minSquaredDistance, + ); + } + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * `interpolate` controls interpolation between consecutive LineStrings + * within the MultiLineString. If `interpolate` is `true` the coordinates + * will be linearly interpolated between the last coordinate of one LineString + * and the first coordinate of the next LineString. If `interpolate` is + * `false` then the function will return `null` for Ms falling between + * LineStrings. + * + * @param {number} m M. + * @param {boolean} [extrapolate] Extrapolate. Default is `false`. + * @param {boolean} [interpolate] Interpolate. Default is `false`. + * @return {import("../coordinate.js").Coordinate|null} Coordinate. + * @api + */ + getCoordinateAtM(m, extrapolate, interpolate) { + if ( + (this.layout != 'XYM' && this.layout != 'XYZM') || + this.flatCoordinates.length === 0 + ) { + return null; + } + extrapolate = extrapolate !== undefined ? extrapolate : false; + interpolate = interpolate !== undefined ? interpolate : false; + return (0,_flat_interpolate_js__WEBPACK_IMPORTED_MODULE_4__.lineStringsCoordinateAtM)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + m, + extrapolate, + interpolate, + ); + } + + /** + * Return the coordinates of the multilinestring. + * @return {Array>} Coordinates. + * @api + */ + getCoordinates() { + return (0,_flat_inflate_js__WEBPACK_IMPORTED_MODULE_5__.inflateCoordinatesArray)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + ); + } + + /** + * @return {Array} Ends. + */ + getEnds() { + return this.ends_; + } + + /** + * Return the linestring at the specified index. + * @param {number} index Index. + * @return {LineString} LineString. + * @api + */ + getLineString(index) { + if (index < 0 || this.ends_.length <= index) { + return null; + } + return new _LineString_js__WEBPACK_IMPORTED_MODULE_6__["default"]( + this.flatCoordinates.slice( + index === 0 ? 0 : this.ends_[index - 1], + this.ends_[index], + ), + this.layout, + ); + } + + /** + * Return the linestrings of this multilinestring. + * @return {Array} LineStrings. + * @api + */ + getLineStrings() { + const flatCoordinates = this.flatCoordinates; + const ends = this.ends_; + const layout = this.layout; + /** @type {Array} */ + const lineStrings = []; + let offset = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const lineString = new _LineString_js__WEBPACK_IMPORTED_MODULE_6__["default"]( + flatCoordinates.slice(offset, end), + layout, + ); + lineStrings.push(lineString); + offset = end; + } + return lineStrings; + } + + /** + * @return {Array} Flat midpoints. + */ + getFlatMidpoints() { + /** @type {Array} */ + const midpoints = []; + const flatCoordinates = this.flatCoordinates; + let offset = 0; + const ends = this.ends_; + const stride = this.stride; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const midpoint = (0,_flat_interpolate_js__WEBPACK_IMPORTED_MODULE_4__.interpolatePoint)( + flatCoordinates, + offset, + end, + stride, + 0.5, + ); + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(midpoints, midpoint); + offset = end; + } + return midpoints; + } + + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {MultiLineString} Simplified MultiLineString. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + /** @type {Array} */ + const simplifiedFlatCoordinates = []; + /** @type {Array} */ + const simplifiedEnds = []; + simplifiedFlatCoordinates.length = (0,_flat_simplify_js__WEBPACK_IMPORTED_MODULE_7__.douglasPeuckerArray)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0, + simplifiedEnds, + ); + return new MultiLineString(simplifiedFlatCoordinates, 'XY', simplifiedEnds); + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'MultiLineString'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return (0,_flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_8__.intersectsLineStringArray)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + extent, + ); + } + + /** + * Set the coordinates of the multilinestring. + * @param {!Array>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 2); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + const ends = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_9__.deflateCoordinatesArray)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + this.ends_, + ); + this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MultiLineString); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/MultiPoint.js": +/*!****************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/MultiPoint.js ***! + \****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Point_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Point.js */ "./node_modules/@biigle/ol/geom/Point.js"); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _flat_inflate_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./flat/inflate.js */ "./node_modules/@biigle/ol/geom/flat/inflate.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/geom/MultiPoint + */ + + + + + + + + +/** + * @classdesc + * Multi-point geometry. + * + * @api + */ +class MultiPoint extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Array|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates, layout) { + super(); + if (layout && !Array.isArray(coordinates[0])) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ (coordinates), + ); + } else { + this.setCoordinates( + /** @type {Array} */ ( + coordinates + ), + layout, + ); + } + } + + /** + * Append the passed point to this multipoint. + * @param {Point} point Point. + * @api + */ + appendPoint(point) { + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(this.flatCoordinates, point.getFlatCoordinates()); + this.changed(); + } + + /** + * Make a complete copy of the geometry. + * @return {!MultiPoint} Clone. + * @api + */ + clone() { + const multiPoint = new MultiPoint( + this.flatCoordinates.slice(), + this.layout, + ); + multiPoint.applyProperties(this); + return multiPoint; + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.closestSquaredDistanceXY)(this.getExtent(), x, y)) { + return minSquaredDistance; + } + const flatCoordinates = this.flatCoordinates; + const stride = this.stride; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + const squaredDistance = (0,_math_js__WEBPACK_IMPORTED_MODULE_3__.squaredDistance)( + x, + y, + flatCoordinates[i], + flatCoordinates[i + 1], + ); + if (squaredDistance < minSquaredDistance) { + minSquaredDistance = squaredDistance; + for (let j = 0; j < stride; ++j) { + closestPoint[j] = flatCoordinates[i + j]; + } + closestPoint.length = stride; + } + } + return minSquaredDistance; + } + + /** + * Return the coordinates of the multipoint. + * @return {Array} Coordinates. + * @api + */ + getCoordinates() { + return (0,_flat_inflate_js__WEBPACK_IMPORTED_MODULE_4__.inflateCoordinates)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + ); + } + + /** + * Return the point at the specified index. + * @param {number} index Index. + * @return {Point} Point. + * @api + */ + getPoint(index) { + const n = this.flatCoordinates.length / this.stride; + if (index < 0 || n <= index) { + return null; + } + return new _Point_js__WEBPACK_IMPORTED_MODULE_5__["default"]( + this.flatCoordinates.slice( + index * this.stride, + (index + 1) * this.stride, + ), + this.layout, + ); + } + + /** + * Return the points of this multipoint. + * @return {Array} Points. + * @api + */ + getPoints() { + const flatCoordinates = this.flatCoordinates; + const layout = this.layout; + const stride = this.stride; + /** @type {Array} */ + const points = []; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + const point = new _Point_js__WEBPACK_IMPORTED_MODULE_5__["default"](flatCoordinates.slice(i, i + stride), layout); + points.push(point); + } + return points; + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'MultiPoint'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + const flatCoordinates = this.flatCoordinates; + const stride = this.stride; + for (let i = 0, ii = flatCoordinates.length; i < ii; i += stride) { + const x = flatCoordinates[i]; + const y = flatCoordinates[i + 1]; + if ((0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.containsXY)(extent, x, y)) { + return true; + } + } + return false; + } + + /** + * Set the coordinates of the multipoint. + * @param {!Array} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 1); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_6__.deflateCoordinates)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + ); + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MultiPoint); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/MultiPolygon.js": +/*!******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/MultiPolygon.js ***! + \******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _MultiPoint_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./MultiPoint.js */ "./node_modules/@biigle/ol/geom/MultiPoint.js"); +/* harmony import */ var _Polygon_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Polygon.js */ "./node_modules/@biigle/ol/geom/Polygon.js"); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _flat_closest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/closest.js */ "./node_modules/@biigle/ol/geom/flat/closest.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _flat_interiorpoint_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./flat/interiorpoint.js */ "./node_modules/@biigle/ol/geom/flat/interiorpoint.js"); +/* harmony import */ var _flat_inflate_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./flat/inflate.js */ "./node_modules/@biigle/ol/geom/flat/inflate.js"); +/* harmony import */ var _flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./flat/intersectsextent.js */ "./node_modules/@biigle/ol/geom/flat/intersectsextent.js"); +/* harmony import */ var _flat_orient_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flat/orient.js */ "./node_modules/@biigle/ol/geom/flat/orient.js"); +/* harmony import */ var _flat_area_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flat/area.js */ "./node_modules/@biigle/ol/geom/flat/area.js"); +/* harmony import */ var _flat_center_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./flat/center.js */ "./node_modules/@biigle/ol/geom/flat/center.js"); +/* harmony import */ var _flat_contains_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./flat/contains.js */ "./node_modules/@biigle/ol/geom/flat/contains.js"); +/* harmony import */ var _flat_simplify_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./flat/simplify.js */ "./node_modules/@biigle/ol/geom/flat/simplify.js"); +/** + * @module ol/geom/MultiPolygon + */ + + + + + + + + + + + + + + + + +/** + * @classdesc + * Multi-polygon geometry. + * + * @api + */ +class MultiPolygon extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Array>|Polygon>|Array} coordinates Coordinates. + * For internal use, flat coordinates in combination with `layout` and `endss` are also accepted. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @param {Array>} [endss] Array of ends for internal use with flat coordinates. + */ + constructor(coordinates, layout, endss) { + super(); + + /** + * @type {Array>} + * @private + */ + this.endss_ = []; + + /** + * @private + * @type {number} + */ + this.flatInteriorPointsRevision_ = -1; + + /** + * @private + * @type {Array|null} + */ + this.flatInteriorPoints_ = null; + + /** + * @private + * @type {number} + */ + this.maxDelta_ = -1; + + /** + * @private + * @type {number} + */ + this.maxDeltaRevision_ = -1; + + /** + * @private + * @type {number} + */ + this.orientedRevision_ = -1; + + /** + * @private + * @type {Array|null} + */ + this.orientedFlatCoordinates_ = null; + + if (!endss && !Array.isArray(coordinates[0])) { + const polygons = /** @type {Array} */ (coordinates); + /** @type {Array} */ + const flatCoordinates = []; + const thisEndss = []; + for (let i = 0, ii = polygons.length; i < ii; ++i) { + const polygon = polygons[i]; + const offset = flatCoordinates.length; + const ends = polygon.getEnds(); + for (let j = 0, jj = ends.length; j < jj; ++j) { + ends[j] += offset; + } + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(flatCoordinates, polygon.getFlatCoordinates()); + thisEndss.push(ends); + } + layout = + polygons.length === 0 ? this.getLayout() : polygons[0].getLayout(); + coordinates = flatCoordinates; + endss = thisEndss; + } + if (layout !== undefined && endss) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ (coordinates), + ); + this.endss_ = endss; + } else { + this.setCoordinates( + /** @type {Array>>} */ ( + coordinates + ), + layout, + ); + } + } + + /** + * Append the passed polygon to this multipolygon. + * @param {Polygon} polygon Polygon. + * @api + */ + appendPolygon(polygon) { + /** @type {Array} */ + let ends; + if (!this.flatCoordinates) { + this.flatCoordinates = polygon.getFlatCoordinates().slice(); + ends = polygon.getEnds().slice(); + this.endss_.push(); + } else { + const offset = this.flatCoordinates.length; + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(this.flatCoordinates, polygon.getFlatCoordinates()); + ends = polygon.getEnds().slice(); + for (let i = 0, ii = ends.length; i < ii; ++i) { + ends[i] += offset; + } + } + this.endss_.push(ends); + this.changed(); + } + + /** + * Make a complete copy of the geometry. + * @return {!MultiPolygon} Clone. + * @api + */ + clone() { + const len = this.endss_.length; + const newEndss = new Array(len); + for (let i = 0; i < len; ++i) { + newEndss[i] = this.endss_[i].slice(); + } + + const multiPolygon = new MultiPolygon( + this.flatCoordinates.slice(), + this.layout, + newEndss, + ); + multiPolygon.applyProperties(this); + + return multiPolygon; + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.closestSquaredDistanceXY)(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.multiArrayMaxSquaredDelta)( + this.flatCoordinates, + 0, + this.endss_, + this.stride, + 0, + ), + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.assignClosestMultiArrayPoint)( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + this.maxDelta_, + true, + x, + y, + closestPoint, + minSquaredDistance, + ); + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + return (0,_flat_contains_js__WEBPACK_IMPORTED_MODULE_4__.linearRingssContainsXY)( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + x, + y, + ); + } + + /** + * Return the area of the multipolygon on projected plane. + * @return {number} Area (on projected plane). + * @api + */ + getArea() { + return (0,_flat_area_js__WEBPACK_IMPORTED_MODULE_5__.linearRingss)( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + ); + } + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for multi-polygons. + * + * @param {boolean} [right] Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @return {Array>>} Coordinates. + * @api + */ + getCoordinates(right) { + let flatCoordinates; + if (right !== undefined) { + flatCoordinates = this.getOrientedFlatCoordinates().slice(); + (0,_flat_orient_js__WEBPACK_IMPORTED_MODULE_6__.orientLinearRingsArray)( + flatCoordinates, + 0, + this.endss_, + this.stride, + right, + ); + } else { + flatCoordinates = this.flatCoordinates; + } + + return (0,_flat_inflate_js__WEBPACK_IMPORTED_MODULE_7__.inflateMultiCoordinatesArray)( + flatCoordinates, + 0, + this.endss_, + this.stride, + ); + } + + /** + * @return {Array>} Endss. + */ + getEndss() { + return this.endss_; + } + + /** + * @return {Array} Flat interior points. + */ + getFlatInteriorPoints() { + if (this.flatInteriorPointsRevision_ != this.getRevision()) { + const flatCenters = (0,_flat_center_js__WEBPACK_IMPORTED_MODULE_8__.linearRingss)( + this.flatCoordinates, + 0, + this.endss_, + this.stride, + ); + this.flatInteriorPoints_ = (0,_flat_interiorpoint_js__WEBPACK_IMPORTED_MODULE_9__.getInteriorPointsOfMultiArray)( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + flatCenters, + ); + this.flatInteriorPointsRevision_ = this.getRevision(); + } + return /** @type {Array} */ (this.flatInteriorPoints_); + } + + /** + * Return the interior points as {@link module:ol/geom/MultiPoint~MultiPoint multipoint}. + * @return {MultiPoint} Interior points as XYM coordinates, where M is + * the length of the horizontal intersection that the point belongs to. + * @api + */ + getInteriorPoints() { + return new _MultiPoint_js__WEBPACK_IMPORTED_MODULE_10__["default"](this.getFlatInteriorPoints().slice(), 'XYM'); + } + + /** + * @return {Array} Oriented flat coordinates. + */ + getOrientedFlatCoordinates() { + if (this.orientedRevision_ != this.getRevision()) { + const flatCoordinates = this.flatCoordinates; + if ( + (0,_flat_orient_js__WEBPACK_IMPORTED_MODULE_6__.linearRingssAreOriented)(flatCoordinates, 0, this.endss_, this.stride) + ) { + this.orientedFlatCoordinates_ = flatCoordinates; + } else { + this.orientedFlatCoordinates_ = flatCoordinates.slice(); + this.orientedFlatCoordinates_.length = (0,_flat_orient_js__WEBPACK_IMPORTED_MODULE_6__.orientLinearRingsArray)( + this.orientedFlatCoordinates_, + 0, + this.endss_, + this.stride, + ); + } + this.orientedRevision_ = this.getRevision(); + } + return /** @type {Array} */ (this.orientedFlatCoordinates_); + } + + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {MultiPolygon} Simplified MultiPolygon. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + /** @type {Array} */ + const simplifiedFlatCoordinates = []; + /** @type {Array>} */ + const simplifiedEndss = []; + simplifiedFlatCoordinates.length = (0,_flat_simplify_js__WEBPACK_IMPORTED_MODULE_11__.quantizeMultiArray)( + this.flatCoordinates, + 0, + this.endss_, + this.stride, + Math.sqrt(squaredTolerance), + simplifiedFlatCoordinates, + 0, + simplifiedEndss, + ); + return new MultiPolygon(simplifiedFlatCoordinates, 'XY', simplifiedEndss); + } + + /** + * Return the polygon at the specified index. + * @param {number} index Index. + * @return {Polygon} Polygon. + * @api + */ + getPolygon(index) { + if (index < 0 || this.endss_.length <= index) { + return null; + } + let offset; + if (index === 0) { + offset = 0; + } else { + const prevEnds = this.endss_[index - 1]; + offset = prevEnds[prevEnds.length - 1]; + } + const ends = this.endss_[index].slice(); + const end = ends[ends.length - 1]; + if (offset !== 0) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + ends[i] -= offset; + } + } + return new _Polygon_js__WEBPACK_IMPORTED_MODULE_12__["default"]( + this.flatCoordinates.slice(offset, end), + this.layout, + ends, + ); + } + + /** + * Return the polygons of this multipolygon. + * @return {Array} Polygons. + * @api + */ + getPolygons() { + const layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const endss = this.endss_; + const polygons = []; + let offset = 0; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i].slice(); + const end = ends[ends.length - 1]; + if (offset !== 0) { + for (let j = 0, jj = ends.length; j < jj; ++j) { + ends[j] -= offset; + } + } + const polygon = new _Polygon_js__WEBPACK_IMPORTED_MODULE_12__["default"]( + flatCoordinates.slice(offset, end), + layout, + ends, + ); + polygons.push(polygon); + offset = end; + } + return polygons; + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'MultiPolygon'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return (0,_flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_13__.intersectsLinearRingMultiArray)( + this.getOrientedFlatCoordinates(), + 0, + this.endss_, + this.stride, + extent, + ); + } + + /** + * Set the coordinates of the multipolygon. + * @param {!Array>>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 3); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + const endss = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_14__.deflateMultiCoordinatesArray)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + this.endss_, + ); + if (endss.length === 0) { + this.flatCoordinates.length = 0; + } else { + const lastEnds = endss[endss.length - 1]; + this.flatCoordinates.length = + lastEnds.length === 0 ? 0 : lastEnds[lastEnds.length - 1]; + } + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (MultiPolygon); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/Point.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/geom/Point.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/geom/Point + */ + + + + + +/** + * @classdesc + * Point geometry. + * + * @api + */ +class Point extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {import("../coordinate.js").Coordinate} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + constructor(coordinates, layout) { + super(); + this.setCoordinates(coordinates, layout); + } + + /** + * Make a complete copy of the geometry. + * @return {!Point} Clone. + * @api + */ + clone() { + const point = new Point(this.flatCoordinates.slice(), this.layout); + point.applyProperties(this); + return point; + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + const flatCoordinates = this.flatCoordinates; + const squaredDistance = (0,_math_js__WEBPACK_IMPORTED_MODULE_1__.squaredDistance)( + x, + y, + flatCoordinates[0], + flatCoordinates[1], + ); + if (squaredDistance < minSquaredDistance) { + const stride = this.stride; + for (let i = 0; i < stride; ++i) { + closestPoint[i] = flatCoordinates[i]; + } + closestPoint.length = stride; + return squaredDistance; + } + return minSquaredDistance; + } + + /** + * Return the coordinate of the point. + * @return {import("../coordinate.js").Coordinate} Coordinates. + * @api + */ + getCoordinates() { + return this.flatCoordinates.slice(); + } + + /** + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + return (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.createOrUpdateFromCoordinate)(this.flatCoordinates, extent); + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'Point'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.containsXY)(extent, this.flatCoordinates[0], this.flatCoordinates[1]); + } + + /** + * @param {!Array<*>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 0); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + this.flatCoordinates.length = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_3__.deflateCoordinate)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + ); + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Point); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/Polygon.js": +/*!*************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/Polygon.js ***! + \*************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "circular": () => (/* binding */ circular), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "fromCircle": () => (/* binding */ fromCircle), +/* harmony export */ "fromExtent": () => (/* binding */ fromExtent), +/* harmony export */ "makeRegular": () => (/* binding */ makeRegular) +/* harmony export */ }); +/* harmony import */ var _LinearRing_js__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./LinearRing.js */ "./node_modules/@biigle/ol/geom/LinearRing.js"); +/* harmony import */ var _Point_js__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./Point.js */ "./node_modules/@biigle/ol/geom/Point.js"); +/* harmony import */ var _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./SimpleGeometry.js */ "./node_modules/@biigle/ol/geom/SimpleGeometry.js"); +/* harmony import */ var _flat_closest_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/closest.js */ "./node_modules/@biigle/ol/geom/flat/closest.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_deflate_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./flat/deflate.js */ "./node_modules/@biigle/ol/geom/flat/deflate.js"); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _flat_interiorpoint_js__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./flat/interiorpoint.js */ "./node_modules/@biigle/ol/geom/flat/interiorpoint.js"); +/* harmony import */ var _flat_inflate_js__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./flat/inflate.js */ "./node_modules/@biigle/ol/geom/flat/inflate.js"); +/* harmony import */ var _flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./flat/intersectsextent.js */ "./node_modules/@biigle/ol/geom/flat/intersectsextent.js"); +/* harmony import */ var _flat_orient_js__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flat/orient.js */ "./node_modules/@biigle/ol/geom/flat/orient.js"); +/* harmony import */ var _flat_area_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flat/area.js */ "./node_modules/@biigle/ol/geom/flat/area.js"); +/* harmony import */ var _flat_contains_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./flat/contains.js */ "./node_modules/@biigle/ol/geom/flat/contains.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../math.js */ "./node_modules/@biigle/ol/math.js"); +/* harmony import */ var _flat_simplify_js__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./flat/simplify.js */ "./node_modules/@biigle/ol/geom/flat/simplify.js"); +/* harmony import */ var _sphere_js__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../sphere.js */ "./node_modules/@biigle/ol/sphere.js"); +/** + * @module ol/geom/Polygon + */ + + + + + + + + + + + + + + + + + +/** + * @classdesc + * Polygon geometry. + * + * @api + */ +class Polygon extends _SimpleGeometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {!Array>|!Array} coordinates + * Array of linear rings that define the polygon. The first linear ring of the + * array defines the outer-boundary or surface of the polygon. Each subsequent + * linear ring defines a hole in the surface of the polygon. A linear ring is + * an array of vertices' coordinates where the first coordinate and the last are + * equivalent. (For internal use, flat coordinates in combination with + * `layout` and `ends` are also accepted.) + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @param {Array} [ends] Ends (for internal use with flat coordinates). + */ + constructor(coordinates, layout, ends) { + super(); + + /** + * @type {Array} + * @private + */ + this.ends_ = []; + + /** + * @private + * @type {number} + */ + this.flatInteriorPointRevision_ = -1; + + /** + * @private + * @type {import("../coordinate.js").Coordinate|null} + */ + this.flatInteriorPoint_ = null; + + /** + * @private + * @type {number} + */ + this.maxDelta_ = -1; + + /** + * @private + * @type {number} + */ + this.maxDeltaRevision_ = -1; + + /** + * @private + * @type {number} + */ + this.orientedRevision_ = -1; + + /** + * @private + * @type {Array|null} + */ + this.orientedFlatCoordinates_ = null; + + if (layout !== undefined && ends) { + this.setFlatCoordinates( + layout, + /** @type {Array} */ (coordinates), + ); + this.ends_ = ends; + } else { + this.setCoordinates( + /** @type {Array>} */ ( + coordinates + ), + layout, + ); + } + } + + /** + * Append the passed linear ring to this polygon. + * @param {LinearRing} linearRing Linear ring. + * @api + */ + appendLinearRing(linearRing) { + if (!this.flatCoordinates) { + this.flatCoordinates = linearRing.getFlatCoordinates().slice(); + } else { + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)(this.flatCoordinates, linearRing.getFlatCoordinates()); + } + this.ends_.push(this.flatCoordinates.length); + this.changed(); + } + + /** + * Make a complete copy of the geometry. + * @return {!Polygon} Clone. + * @api + */ + clone() { + const polygon = new Polygon( + this.flatCoordinates.slice(), + this.layout, + this.ends_.slice(), + ); + polygon.applyProperties(this); + return polygon; + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @param {import("../coordinate.js").Coordinate} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @return {number} Minimum squared distance. + */ + closestPointXY(x, y, closestPoint, minSquaredDistance) { + if (minSquaredDistance < (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.closestSquaredDistanceXY)(this.getExtent(), x, y)) { + return minSquaredDistance; + } + if (this.maxDeltaRevision_ != this.getRevision()) { + this.maxDelta_ = Math.sqrt( + (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.arrayMaxSquaredDelta)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + 0, + ), + ); + this.maxDeltaRevision_ = this.getRevision(); + } + return (0,_flat_closest_js__WEBPACK_IMPORTED_MODULE_3__.assignClosestArrayPoint)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + this.maxDelta_, + true, + x, + y, + closestPoint, + minSquaredDistance, + ); + } + + /** + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ + containsXY(x, y) { + return (0,_flat_contains_js__WEBPACK_IMPORTED_MODULE_4__.linearRingsContainsXY)( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + x, + y, + ); + } + + /** + * Return the area of the polygon on projected plane. + * @return {number} Area (on projected plane). + * @api + */ + getArea() { + return (0,_flat_area_js__WEBPACK_IMPORTED_MODULE_5__.linearRings)( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + ); + } + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for polygons. + * + * @param {boolean} [right] Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @return {Array>} Coordinates. + * @api + */ + getCoordinates(right) { + let flatCoordinates; + if (right !== undefined) { + flatCoordinates = this.getOrientedFlatCoordinates().slice(); + (0,_flat_orient_js__WEBPACK_IMPORTED_MODULE_6__.orientLinearRings)(flatCoordinates, 0, this.ends_, this.stride, right); + } else { + flatCoordinates = this.flatCoordinates; + } + + return (0,_flat_inflate_js__WEBPACK_IMPORTED_MODULE_7__.inflateCoordinatesArray)(flatCoordinates, 0, this.ends_, this.stride); + } + + /** + * @return {Array} Ends. + */ + getEnds() { + return this.ends_; + } + + /** + * @return {Array} Interior point. + */ + getFlatInteriorPoint() { + if (this.flatInteriorPointRevision_ != this.getRevision()) { + const flatCenter = (0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.getCenter)(this.getExtent()); + this.flatInteriorPoint_ = (0,_flat_interiorpoint_js__WEBPACK_IMPORTED_MODULE_8__.getInteriorPointOfArray)( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + flatCenter, + 0, + ); + this.flatInteriorPointRevision_ = this.getRevision(); + } + return /** @type {import("../coordinate.js").Coordinate} */ ( + this.flatInteriorPoint_ + ); + } + + /** + * Return an interior point of the polygon. + * @return {Point} Interior point as XYM coordinate, where M is the + * length of the horizontal intersection that the point belongs to. + * @api + */ + getInteriorPoint() { + return new _Point_js__WEBPACK_IMPORTED_MODULE_9__["default"](this.getFlatInteriorPoint(), 'XYM'); + } + + /** + * Return the number of rings of the polygon, this includes the exterior + * ring and any interior rings. + * + * @return {number} Number of rings. + * @api + */ + getLinearRingCount() { + return this.ends_.length; + } + + /** + * Return the Nth linear ring of the polygon geometry. Return `null` if the + * given index is out of range. + * The exterior linear ring is available at index `0` and the interior rings + * at index `1` and beyond. + * + * @param {number} index Index. + * @return {LinearRing|null} Linear ring. + * @api + */ + getLinearRing(index) { + if (index < 0 || this.ends_.length <= index) { + return null; + } + return new _LinearRing_js__WEBPACK_IMPORTED_MODULE_10__["default"]( + this.flatCoordinates.slice( + index === 0 ? 0 : this.ends_[index - 1], + this.ends_[index], + ), + this.layout, + ); + } + + /** + * Return the linear rings of the polygon. + * @return {Array} Linear rings. + * @api + */ + getLinearRings() { + const layout = this.layout; + const flatCoordinates = this.flatCoordinates; + const ends = this.ends_; + const linearRings = []; + let offset = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const linearRing = new _LinearRing_js__WEBPACK_IMPORTED_MODULE_10__["default"]( + flatCoordinates.slice(offset, end), + layout, + ); + linearRings.push(linearRing); + offset = end; + } + return linearRings; + } + + /** + * @return {Array} Oriented flat coordinates. + */ + getOrientedFlatCoordinates() { + if (this.orientedRevision_ != this.getRevision()) { + const flatCoordinates = this.flatCoordinates; + if ((0,_flat_orient_js__WEBPACK_IMPORTED_MODULE_6__.linearRingsAreOriented)(flatCoordinates, 0, this.ends_, this.stride)) { + this.orientedFlatCoordinates_ = flatCoordinates; + } else { + this.orientedFlatCoordinates_ = flatCoordinates.slice(); + this.orientedFlatCoordinates_.length = (0,_flat_orient_js__WEBPACK_IMPORTED_MODULE_6__.orientLinearRings)( + this.orientedFlatCoordinates_, + 0, + this.ends_, + this.stride, + ); + } + this.orientedRevision_ = this.getRevision(); + } + return /** @type {Array} */ (this.orientedFlatCoordinates_); + } + + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {Polygon} Simplified Polygon. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + /** @type {Array} */ + const simplifiedFlatCoordinates = []; + /** @type {Array} */ + const simplifiedEnds = []; + simplifiedFlatCoordinates.length = (0,_flat_simplify_js__WEBPACK_IMPORTED_MODULE_11__.quantizeArray)( + this.flatCoordinates, + 0, + this.ends_, + this.stride, + Math.sqrt(squaredTolerance), + simplifiedFlatCoordinates, + 0, + simplifiedEnds, + ); + return new Polygon(simplifiedFlatCoordinates, 'XY', simplifiedEnds); + } + + /** + * Get the type of this geometry. + * @return {import("./Geometry.js").Type} Geometry type. + * @api + */ + getType() { + return 'Polygon'; + } + + /** + * Test if the geometry and the passed extent intersect. + * @param {import("../extent.js").Extent} extent Extent. + * @return {boolean} `true` if the geometry and the extent intersect. + * @api + */ + intersectsExtent(extent) { + return (0,_flat_intersectsextent_js__WEBPACK_IMPORTED_MODULE_12__.intersectsLinearRingArray)( + this.getOrientedFlatCoordinates(), + 0, + this.ends_, + this.stride, + extent, + ); + } + + /** + * Set the coordinates of the polygon. + * @param {!Array>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + * @api + */ + setCoordinates(coordinates, layout) { + this.setLayout(layout, coordinates, 2); + if (!this.flatCoordinates) { + this.flatCoordinates = []; + } + const ends = (0,_flat_deflate_js__WEBPACK_IMPORTED_MODULE_13__.deflateCoordinatesArray)( + this.flatCoordinates, + 0, + coordinates, + this.stride, + this.ends_, + ); + this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1]; + this.changed(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Polygon); + +/** + * Create an approximation of a circle on the surface of a sphere. + * @param {import("../coordinate.js").Coordinate} center Center (`[lon, lat]` in degrees). + * @param {number} radius The great-circle distance from the center to + * the polygon vertices in meters. + * @param {number} [n] Optional number of vertices for the resulting + * polygon. Default is `32`. + * @param {number} [sphereRadius] Optional radius for the sphere (defaults to + * the Earth's mean radius using the WGS84 ellipsoid). + * @return {Polygon} The "circular" polygon. + * @api + */ +function circular(center, radius, n, sphereRadius) { + n = n ? n : 32; + /** @type {Array} */ + const flatCoordinates = []; + for (let i = 0; i < n; ++i) { + (0,_array_js__WEBPACK_IMPORTED_MODULE_1__.extend)( + flatCoordinates, + (0,_sphere_js__WEBPACK_IMPORTED_MODULE_14__.offset)(center, radius, (2 * Math.PI * i) / n, sphereRadius), + ); + } + flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]); + return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]); +} + +/** + * Create a polygon from an extent. The layout used is `XY`. + * @param {import("../extent.js").Extent} extent The extent. + * @return {Polygon} The polygon. + * @api + */ +function fromExtent(extent) { + if ((0,_extent_js__WEBPACK_IMPORTED_MODULE_2__.isEmpty)(extent)) { + throw new Error('Cannot create polygon from empty extent'); + } + const minX = extent[0]; + const minY = extent[1]; + const maxX = extent[2]; + const maxY = extent[3]; + const flatCoordinates = [ + minX, + minY, + minX, + maxY, + maxX, + maxY, + maxX, + minY, + minX, + minY, + ]; + return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]); +} + +/** + * Create a regular polygon from a circle. + * @param {import("./Circle.js").default} circle Circle geometry. + * @param {number} [sides] Number of sides of the polygon. Default is 32. + * @param {number} [angle] Start angle for the first vertex of the polygon in + * counter-clockwise radians. 0 means East. Default is 0. + * @return {Polygon} Polygon geometry. + * @api + */ +function fromCircle(circle, sides, angle) { + sides = sides ? sides : 32; + const stride = circle.getStride(); + const layout = circle.getLayout(); + const center = circle.getCenter(); + const arrayLength = stride * (sides + 1); + const flatCoordinates = new Array(arrayLength); + for (let i = 0; i < arrayLength; i += stride) { + flatCoordinates[i] = 0; + flatCoordinates[i + 1] = 0; + for (let j = 2; j < stride; j++) { + flatCoordinates[i + j] = center[j]; + } + } + const ends = [flatCoordinates.length]; + const polygon = new Polygon(flatCoordinates, layout, ends); + makeRegular(polygon, center, circle.getRadius(), angle); + return polygon; +} + +/** + * Modify the coordinates of a polygon to make it a regular polygon. + * @param {Polygon} polygon Polygon geometry. + * @param {import("../coordinate.js").Coordinate} center Center of the regular polygon. + * @param {number} radius Radius of the regular polygon. + * @param {number} [angle] Start angle for the first vertex of the polygon in + * counter-clockwise radians. 0 means East. Default is 0. + */ +function makeRegular(polygon, center, radius, angle) { + const flatCoordinates = polygon.getFlatCoordinates(); + const stride = polygon.getStride(); + const sides = flatCoordinates.length / stride - 1; + const startAngle = angle ? angle : 0; + for (let i = 0; i <= sides; ++i) { + const offset = i * stride; + const angle = startAngle + ((0,_math_js__WEBPACK_IMPORTED_MODULE_15__.modulo)(i, sides) * 2 * Math.PI) / sides; + flatCoordinates[offset] = center[0] + radius * Math.cos(angle); + flatCoordinates[offset + 1] = center[1] + radius * Math.sin(angle); + } + polygon.changed(); +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/SimpleGeometry.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/SimpleGeometry.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "getLayoutForStride": () => (/* binding */ getLayoutForStride), +/* harmony export */ "getStrideForLayout": () => (/* binding */ getStrideForLayout), +/* harmony export */ "transformGeom2D": () => (/* binding */ transformGeom2D) +/* harmony export */ }); +/* harmony import */ var _Geometry_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Geometry.js */ "./node_modules/@biigle/ol/geom/Geometry.js"); +/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../util.js */ "./node_modules/@biigle/ol/util.js"); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _flat_transform_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./flat/transform.js */ "./node_modules/@biigle/ol/geom/flat/transform.js"); +/** + * @module ol/geom/SimpleGeometry + */ + + + + + +/** + * @classdesc + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + * + * @abstract + * @api + */ +class SimpleGeometry extends _Geometry_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + constructor() { + super(); + + /** + * @protected + * @type {import("./Geometry.js").GeometryLayout} + */ + this.layout = 'XY'; + + /** + * @protected + * @type {number} + */ + this.stride = 2; + + /** + * @protected + * @type {Array} + */ + this.flatCoordinates; + } + + /** + * @param {import("../extent.js").Extent} extent Extent. + * @protected + * @return {import("../extent.js").Extent} extent Extent. + */ + computeExtent(extent) { + return (0,_extent_js__WEBPACK_IMPORTED_MODULE_1__.createOrUpdateFromFlatCoordinates)( + this.flatCoordinates, + 0, + this.flatCoordinates.length, + this.stride, + extent, + ); + } + + /** + * @abstract + * @return {Array<*> | null} Coordinates. + */ + getCoordinates() { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_2__.abstract)(); + } + + /** + * Return the first coordinate of the geometry. + * @return {import("../coordinate.js").Coordinate} First coordinate. + * @api + */ + getFirstCoordinate() { + return this.flatCoordinates.slice(0, this.stride); + } + + /** + * @return {Array} Flat coordinates. + */ + getFlatCoordinates() { + return this.flatCoordinates; + } + + /** + * Return the last coordinate of the geometry. + * @return {import("../coordinate.js").Coordinate} Last point. + * @api + */ + getLastCoordinate() { + return this.flatCoordinates.slice( + this.flatCoordinates.length - this.stride, + ); + } + + /** + * Return the {@link import("./Geometry.js").GeometryLayout layout} of the geometry. + * @return {import("./Geometry.js").GeometryLayout} Layout. + * @api + */ + getLayout() { + return this.layout; + } + + /** + * Create a simplified version of this geometry using the Douglas Peucker algorithm. + * @param {number} squaredTolerance Squared tolerance. + * @return {SimpleGeometry} Simplified geometry. + */ + getSimplifiedGeometry(squaredTolerance) { + if (this.simplifiedGeometryRevision !== this.getRevision()) { + this.simplifiedGeometryMaxMinSquaredTolerance = 0; + this.simplifiedGeometryRevision = this.getRevision(); + } + // If squaredTolerance is negative or if we know that simplification will not + // have any effect then just return this. + if ( + squaredTolerance < 0 || + (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 && + squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance) + ) { + return this; + } + + const simplifiedGeometry = + this.getSimplifiedGeometryInternal(squaredTolerance); + const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates(); + if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) { + return simplifiedGeometry; + } + // Simplification did not actually remove any coordinates. We now know + // that any calls to getSimplifiedGeometry with a squaredTolerance less + // than or equal to the current squaredTolerance will also not have any + // effect. This allows us to short circuit simplification (saving CPU + // cycles) and prevents the cache of simplified geometries from filling + // up with useless identical copies of this geometry (saving memory). + this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance; + return this; + } + + /** + * @param {number} squaredTolerance Squared tolerance. + * @return {SimpleGeometry} Simplified geometry. + * @protected + */ + getSimplifiedGeometryInternal(squaredTolerance) { + return this; + } + + /** + * @return {number} Stride. + */ + getStride() { + return this.stride; + } + + /** + * @param {import("./Geometry.js").GeometryLayout} layout Layout. + * @param {Array} flatCoordinates Flat coordinates. + */ + setFlatCoordinates(layout, flatCoordinates) { + this.stride = getStrideForLayout(layout); + this.layout = layout; + this.flatCoordinates = flatCoordinates; + } + + /** + * @abstract + * @param {!Array<*>} coordinates Coordinates. + * @param {import("./Geometry.js").GeometryLayout} [layout] Layout. + */ + setCoordinates(coordinates, layout) { + (0,_util_js__WEBPACK_IMPORTED_MODULE_2__.abstract)(); + } + + /** + * @param {import("./Geometry.js").GeometryLayout|undefined} layout Layout. + * @param {Array<*>} coordinates Coordinates. + * @param {number} nesting Nesting. + * @protected + */ + setLayout(layout, coordinates, nesting) { + let stride; + if (layout) { + stride = getStrideForLayout(layout); + } else { + for (let i = 0; i < nesting; ++i) { + if (coordinates.length === 0) { + this.layout = 'XY'; + this.stride = 2; + return; + } + coordinates = /** @type {Array} */ (coordinates[0]); + } + stride = coordinates.length; + layout = getLayoutForStride(stride); + } + this.layout = layout; + this.stride = stride; + } + + /** + * Apply a transform function to the coordinates of the geometry. + * The geometry is modified in place. + * If you do not want the geometry modified in place, first `clone()` it and + * then use this function on the clone. + * @param {import("../proj.js").TransformFunction} transformFn Transform function. + * Called with a flat array of geometry coordinates. + * @api + */ + applyTransform(transformFn) { + if (this.flatCoordinates) { + transformFn(this.flatCoordinates, this.flatCoordinates, this.stride); + this.changed(); + } + } + + /** + * Rotate the geometry around a given coordinate. This modifies the geometry + * coordinates in place. + * @param {number} angle Rotation angle in counter-clockwise radians. + * @param {import("../coordinate.js").Coordinate} anchor The rotation center. + * @api + */ + rotate(angle, anchor) { + const flatCoordinates = this.getFlatCoordinates(); + if (flatCoordinates) { + const stride = this.getStride(); + (0,_flat_transform_js__WEBPACK_IMPORTED_MODULE_3__.rotate)( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + angle, + anchor, + flatCoordinates, + ); + this.changed(); + } + } + + /** + * Scale the geometry (with an optional origin). This modifies the geometry + * coordinates in place. + * @param {number} sx The scaling factor in the x-direction. + * @param {number} [sy] The scaling factor in the y-direction (defaults to sx). + * @param {import("../coordinate.js").Coordinate} [anchor] The scale origin (defaults to the center + * of the geometry extent). + * @api + */ + scale(sx, sy, anchor) { + if (sy === undefined) { + sy = sx; + } + if (!anchor) { + anchor = (0,_extent_js__WEBPACK_IMPORTED_MODULE_1__.getCenter)(this.getExtent()); + } + const flatCoordinates = this.getFlatCoordinates(); + if (flatCoordinates) { + const stride = this.getStride(); + (0,_flat_transform_js__WEBPACK_IMPORTED_MODULE_3__.scale)( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + sx, + sy, + anchor, + flatCoordinates, + ); + this.changed(); + } + } + + /** + * Translate the geometry. This modifies the geometry coordinates in place. If + * instead you want a new geometry, first `clone()` this geometry. + * @param {number} deltaX Delta X. + * @param {number} deltaY Delta Y. + * @api + */ + translate(deltaX, deltaY) { + const flatCoordinates = this.getFlatCoordinates(); + if (flatCoordinates) { + const stride = this.getStride(); + (0,_flat_transform_js__WEBPACK_IMPORTED_MODULE_3__.translate)( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + deltaX, + deltaY, + flatCoordinates, + ); + this.changed(); + } + } +} + +/** + * @param {number} stride Stride. + * @return {import("./Geometry.js").GeometryLayout} layout Layout. + */ +function getLayoutForStride(stride) { + let layout; + if (stride == 2) { + layout = 'XY'; + } else if (stride == 3) { + layout = 'XYZ'; + } else if (stride == 4) { + layout = 'XYZM'; + } + return /** @type {import("./Geometry.js").GeometryLayout} */ (layout); +} + +/** + * @param {import("./Geometry.js").GeometryLayout} layout Layout. + * @return {number} Stride. + */ +function getStrideForLayout(layout) { + let stride; + if (layout == 'XY') { + stride = 2; + } else if (layout == 'XYZ' || layout == 'XYM') { + stride = 3; + } else if (layout == 'XYZM') { + stride = 4; + } + return /** @type {number} */ (stride); +} + +/** + * @param {SimpleGeometry} simpleGeometry Simple geometry. + * @param {import("../transform.js").Transform} transform Transform. + * @param {Array} [dest] Destination. + * @return {Array} Transformed flat coordinates. + */ +function transformGeom2D(simpleGeometry, transform, dest) { + const flatCoordinates = simpleGeometry.getFlatCoordinates(); + if (!flatCoordinates) { + return null; + } + const stride = simpleGeometry.getStride(); + return (0,_flat_transform_js__WEBPACK_IMPORTED_MODULE_3__.transform2D)( + flatCoordinates, + 0, + flatCoordinates.length, + stride, + transform, + dest, + ); +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (SimpleGeometry); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/area.js": +/*!***************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/area.js ***! + \***************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "linearRing": () => (/* binding */ linearRing), +/* harmony export */ "linearRings": () => (/* binding */ linearRings), +/* harmony export */ "linearRingss": () => (/* binding */ linearRingss) +/* harmony export */ }); +/** + * @module ol/geom/flat/area + */ + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {number} Area. + */ +function linearRing(flatCoordinates, offset, end, stride) { + let twiceArea = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + twiceArea += y1 * x2 - x1 * y2; + x1 = x2; + y1 = y2; + } + return twiceArea / 2; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @return {number} Area. + */ +function linearRings(flatCoordinates, offset, ends, stride) { + let area = 0; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + area += linearRing(flatCoordinates, offset, end, stride); + offset = end; + } + return area; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @return {number} Area. + */ +function linearRingss(flatCoordinates, offset, endss, stride) { + let area = 0; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + area += linearRings(flatCoordinates, offset, ends, stride); + offset = ends[ends.length - 1]; + } + return area; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/center.js": +/*!*****************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/center.js ***! + \*****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "linearRingss": () => (/* binding */ linearRingss) +/* harmony export */ }); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/** + * @module ol/geom/flat/center + */ + + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @return {Array} Flat centers. + */ +function linearRingss(flatCoordinates, offset, endss, stride) { + const flatCenters = []; + let extent = (0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.createEmpty)(); + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + extent = (0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.createOrUpdateFromFlatCoordinates)( + flatCoordinates, + offset, + ends[0], + stride, + ); + flatCenters.push((extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2); + offset = ends[ends.length - 1]; + } + return flatCenters; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/closest.js": +/*!******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/closest.js ***! + \******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "arrayMaxSquaredDelta": () => (/* binding */ arrayMaxSquaredDelta), +/* harmony export */ "assignClosestArrayPoint": () => (/* binding */ assignClosestArrayPoint), +/* harmony export */ "assignClosestMultiArrayPoint": () => (/* binding */ assignClosestMultiArrayPoint), +/* harmony export */ "assignClosestPoint": () => (/* binding */ assignClosestPoint), +/* harmony export */ "maxSquaredDelta": () => (/* binding */ maxSquaredDelta), +/* harmony export */ "multiArrayMaxSquaredDelta": () => (/* binding */ multiArrayMaxSquaredDelta) +/* harmony export */ }); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/geom/flat/closest + */ + + +/** + * Returns the point on the 2D line segment flatCoordinates[offset1] to + * flatCoordinates[offset2] that is closest to the point (x, y). Extra + * dimensions are linearly interpolated. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset1 Offset 1. + * @param {number} offset2 Offset 2. + * @param {number} stride Stride. + * @param {number} x X. + * @param {number} y Y. + * @param {Array} closestPoint Closest point. + */ +function assignClosest( + flatCoordinates, + offset1, + offset2, + stride, + x, + y, + closestPoint, +) { + const x1 = flatCoordinates[offset1]; + const y1 = flatCoordinates[offset1 + 1]; + const dx = flatCoordinates[offset2] - x1; + const dy = flatCoordinates[offset2 + 1] - y1; + let offset; + if (dx === 0 && dy === 0) { + offset = offset1; + } else { + const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy); + if (t > 1) { + offset = offset2; + } else if (t > 0) { + for (let i = 0; i < stride; ++i) { + closestPoint[i] = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)( + flatCoordinates[offset1 + i], + flatCoordinates[offset2 + i], + t, + ); + } + closestPoint.length = stride; + return; + } else { + offset = offset1; + } + } + for (let i = 0; i < stride; ++i) { + closestPoint[i] = flatCoordinates[offset + i]; + } + closestPoint.length = stride; +} + +/** + * Return the squared of the largest distance between any pair of consecutive + * coordinates. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} max Max squared delta. + * @return {number} Max squared delta. + */ +function maxSquaredDelta(flatCoordinates, offset, end, stride, max) { + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + for (offset += stride; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + const squaredDelta = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.squaredDistance)(x1, y1, x2, y2); + if (squaredDelta > max) { + max = squaredDelta; + } + x1 = x2; + y1 = y2; + } + return max; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {number} max Max squared delta. + * @return {number} Max squared delta. + */ +function arrayMaxSquaredDelta( + flatCoordinates, + offset, + ends, + stride, + max, +) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + max = maxSquaredDelta(flatCoordinates, offset, end, stride, max); + offset = end; + } + return max; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {number} max Max squared delta. + * @return {number} Max squared delta. + */ +function multiArrayMaxSquaredDelta( + flatCoordinates, + offset, + endss, + stride, + max, +) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + max = arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max); + offset = ends[ends.length - 1]; + } + return max; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} maxDelta Max delta. + * @param {boolean} isRing Is ring. + * @param {number} x X. + * @param {number} y Y. + * @param {Array} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @param {Array} [tmpPoint] Temporary point object. + * @return {number} Minimum squared distance. + */ +function assignClosestPoint( + flatCoordinates, + offset, + end, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint, +) { + if (offset == end) { + return minSquaredDistance; + } + let i, squaredDistance; + if (maxDelta === 0) { + // All points are identical, so just test the first point. + squaredDistance = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.squaredDistance)( + x, + y, + flatCoordinates[offset], + flatCoordinates[offset + 1], + ); + if (squaredDistance < minSquaredDistance) { + for (i = 0; i < stride; ++i) { + closestPoint[i] = flatCoordinates[offset + i]; + } + closestPoint.length = stride; + return squaredDistance; + } + return minSquaredDistance; + } + tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN]; + let index = offset + stride; + while (index < end) { + assignClosest( + flatCoordinates, + index - stride, + index, + stride, + x, + y, + tmpPoint, + ); + squaredDistance = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.squaredDistance)(x, y, tmpPoint[0], tmpPoint[1]); + if (squaredDistance < minSquaredDistance) { + minSquaredDistance = squaredDistance; + for (i = 0; i < stride; ++i) { + closestPoint[i] = tmpPoint[i]; + } + closestPoint.length = stride; + index += stride; + } else { + // Skip ahead multiple points, because we know that all the skipped + // points cannot be any closer than the closest point we have found so + // far. We know this because we know how close the current point is, how + // close the closest point we have found so far is, and the maximum + // distance between consecutive points. For example, if we're currently + // at distance 10, the best we've found so far is 3, and that the maximum + // distance between consecutive points is 2, then we'll need to skip at + // least (10 - 3) / 2 == 3 (rounded down) points to have any chance of + // finding a closer point. We use Math.max(..., 1) to ensure that we + // always advance at least one point, to avoid an infinite loop. + index += + stride * + Math.max( + ((Math.sqrt(squaredDistance) - Math.sqrt(minSquaredDistance)) / + maxDelta) | + 0, + 1, + ); + } + } + if (isRing) { + // Check the closing segment. + assignClosest( + flatCoordinates, + end - stride, + offset, + stride, + x, + y, + tmpPoint, + ); + squaredDistance = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.squaredDistance)(x, y, tmpPoint[0], tmpPoint[1]); + if (squaredDistance < minSquaredDistance) { + minSquaredDistance = squaredDistance; + for (i = 0; i < stride; ++i) { + closestPoint[i] = tmpPoint[i]; + } + closestPoint.length = stride; + } + } + return minSquaredDistance; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {number} maxDelta Max delta. + * @param {boolean} isRing Is ring. + * @param {number} x X. + * @param {number} y Y. + * @param {Array} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @param {Array} [tmpPoint] Temporary point object. + * @return {number} Minimum squared distance. + */ +function assignClosestArrayPoint( + flatCoordinates, + offset, + ends, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint, +) { + tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN]; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + minSquaredDistance = assignClosestPoint( + flatCoordinates, + offset, + end, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint, + ); + offset = end; + } + return minSquaredDistance; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {number} maxDelta Max delta. + * @param {boolean} isRing Is ring. + * @param {number} x X. + * @param {number} y Y. + * @param {Array} closestPoint Closest point. + * @param {number} minSquaredDistance Minimum squared distance. + * @param {Array} [tmpPoint] Temporary point object. + * @return {number} Minimum squared distance. + */ +function assignClosestMultiArrayPoint( + flatCoordinates, + offset, + endss, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint, +) { + tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN]; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + minSquaredDistance = assignClosestArrayPoint( + flatCoordinates, + offset, + ends, + stride, + maxDelta, + isRing, + x, + y, + closestPoint, + minSquaredDistance, + tmpPoint, + ); + offset = ends[ends.length - 1]; + } + return minSquaredDistance; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/contains.js": +/*!*******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/contains.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "linearRingContainsExtent": () => (/* binding */ linearRingContainsExtent), +/* harmony export */ "linearRingContainsXY": () => (/* binding */ linearRingContainsXY), +/* harmony export */ "linearRingsContainsXY": () => (/* binding */ linearRingsContainsXY), +/* harmony export */ "linearRingssContainsXY": () => (/* binding */ linearRingssContainsXY) +/* harmony export */ }); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/** + * @module ol/geom/flat/contains + */ + + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {import("../../extent.js").Extent} extent Extent. + * @return {boolean} Contains extent. + */ +function linearRingContainsExtent( + flatCoordinates, + offset, + end, + stride, + extent, +) { + const outside = (0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.forEachCorner)( + extent, + /** + * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate. + * @return {boolean} Contains (x, y). + */ + function (coordinate) { + return !linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + coordinate[0], + coordinate[1], + ); + }, + ); + return !outside; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ +function linearRingContainsXY( + flatCoordinates, + offset, + end, + stride, + x, + y, +) { + // https://geomalgorithms.com/a03-_inclusion.html + // Copyright 2000 softSurfer, 2012 Dan Sunday + // This code may be freely used and modified for any purpose + // providing that this copyright notice is included with it. + // SoftSurfer makes no warranty for this code, and cannot be held + // liable for any real or imagined damage resulting from its use. + // Users of this code must verify correctness for their application. + let wn = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + if (y1 <= y) { + if (y2 > y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) > 0) { + wn++; + } + } else if (y2 <= y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) < 0) { + wn--; + } + x1 = x2; + y1 = y2; + } + return wn !== 0; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ +function linearRingsContainsXY( + flatCoordinates, + offset, + ends, + stride, + x, + y, +) { + if (ends.length === 0) { + return false; + } + if (!linearRingContainsXY(flatCoordinates, offset, ends[0], stride, x, y)) { + return false; + } + for (let i = 1, ii = ends.length; i < ii; ++i) { + if ( + linearRingContainsXY(flatCoordinates, ends[i - 1], ends[i], stride, x, y) + ) { + return false; + } + } + return true; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {number} x X. + * @param {number} y Y. + * @return {boolean} Contains (x, y). + */ +function linearRingssContainsXY( + flatCoordinates, + offset, + endss, + stride, + x, + y, +) { + if (endss.length === 0) { + return false; + } + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) { + return true; + } + offset = ends[ends.length - 1]; + } + return false; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/deflate.js": +/*!******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/deflate.js ***! + \******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "deflateCoordinate": () => (/* binding */ deflateCoordinate), +/* harmony export */ "deflateCoordinates": () => (/* binding */ deflateCoordinates), +/* harmony export */ "deflateCoordinatesArray": () => (/* binding */ deflateCoordinatesArray), +/* harmony export */ "deflateMultiCoordinatesArray": () => (/* binding */ deflateMultiCoordinatesArray) +/* harmony export */ }); +/** + * @module ol/geom/flat/deflate + */ + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {import("../../coordinate.js").Coordinate} coordinate Coordinate. + * @param {number} stride Stride. + * @return {number} offset Offset. + */ +function deflateCoordinate(flatCoordinates, offset, coordinate, stride) { + for (let i = 0, ii = coordinate.length; i < ii; ++i) { + flatCoordinates[offset++] = coordinate[i]; + } + return offset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} coordinates Coordinates. + * @param {number} stride Stride. + * @return {number} offset Offset. + */ +function deflateCoordinates( + flatCoordinates, + offset, + coordinates, + stride, +) { + for (let i = 0, ii = coordinates.length; i < ii; ++i) { + const coordinate = coordinates[i]; + for (let j = 0; j < stride; ++j) { + flatCoordinates[offset++] = coordinate[j]; + } + } + return offset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} coordinatess Coordinatess. + * @param {number} stride Stride. + * @param {Array} [ends] Ends. + * @return {Array} Ends. + */ +function deflateCoordinatesArray( + flatCoordinates, + offset, + coordinatess, + stride, + ends, +) { + ends = ends ? ends : []; + let i = 0; + for (let j = 0, jj = coordinatess.length; j < jj; ++j) { + const end = deflateCoordinates( + flatCoordinates, + offset, + coordinatess[j], + stride, + ); + ends[i++] = end; + offset = end; + } + ends.length = i; + return ends; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>>} coordinatesss Coordinatesss. + * @param {number} stride Stride. + * @param {Array>} [endss] Endss. + * @return {Array>} Endss. + */ +function deflateMultiCoordinatesArray( + flatCoordinates, + offset, + coordinatesss, + stride, + endss, +) { + endss = endss ? endss : []; + let i = 0; + for (let j = 0, jj = coordinatesss.length; j < jj; ++j) { + const ends = deflateCoordinatesArray( + flatCoordinates, + offset, + coordinatesss[j], + stride, + endss[i], + ); + if (ends.length === 0) { + ends[0] = offset; + } + endss[i++] = ends; + offset = ends[ends.length - 1]; + } + endss.length = i; + return endss; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/inflate.js": +/*!******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/inflate.js ***! + \******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "inflateCoordinates": () => (/* binding */ inflateCoordinates), +/* harmony export */ "inflateCoordinatesArray": () => (/* binding */ inflateCoordinatesArray), +/* harmony export */ "inflateMultiCoordinatesArray": () => (/* binding */ inflateMultiCoordinatesArray) +/* harmony export */ }); +/** + * @module ol/geom/flat/inflate + */ + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {Array} [coordinates] Coordinates. + * @return {Array} Coordinates. + */ +function inflateCoordinates( + flatCoordinates, + offset, + end, + stride, + coordinates, +) { + coordinates = coordinates !== undefined ? coordinates : []; + let i = 0; + for (let j = offset; j < end; j += stride) { + coordinates[i++] = flatCoordinates.slice(j, j + stride); + } + coordinates.length = i; + return coordinates; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {Array>} [coordinatess] Coordinatess. + * @return {Array>} Coordinatess. + */ +function inflateCoordinatesArray( + flatCoordinates, + offset, + ends, + stride, + coordinatess, +) { + coordinatess = coordinatess !== undefined ? coordinatess : []; + let i = 0; + for (let j = 0, jj = ends.length; j < jj; ++j) { + const end = ends[j]; + coordinatess[i++] = inflateCoordinates( + flatCoordinates, + offset, + end, + stride, + coordinatess[i], + ); + offset = end; + } + coordinatess.length = i; + return coordinatess; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {Array>>} [coordinatesss] + * Coordinatesss. + * @return {Array>>} Coordinatesss. + */ +function inflateMultiCoordinatesArray( + flatCoordinates, + offset, + endss, + stride, + coordinatesss, +) { + coordinatesss = coordinatesss !== undefined ? coordinatesss : []; + let i = 0; + for (let j = 0, jj = endss.length; j < jj; ++j) { + const ends = endss[j]; + coordinatesss[i++] = + ends.length === 1 && ends[0] === offset + ? [] + : inflateCoordinatesArray( + flatCoordinates, + offset, + ends, + stride, + coordinatesss[i], + ); + offset = ends[ends.length - 1]; + } + coordinatesss.length = i; + return coordinatesss; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/interiorpoint.js": +/*!************************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/interiorpoint.js ***! + \************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "getInteriorPointOfArray": () => (/* binding */ getInteriorPointOfArray), +/* harmony export */ "getInteriorPointsOfMultiArray": () => (/* binding */ getInteriorPointsOfMultiArray) +/* harmony export */ }); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _contains_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./contains.js */ "./node_modules/@biigle/ol/geom/flat/contains.js"); +/** + * @module ol/geom/flat/interiorpoint + */ + + + +/** + * Calculates a point that is likely to lie in the interior of the linear rings. + * Inspired by JTS's com.vividsolutions.jts.geom.Geometry#getInteriorPoint. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {Array} flatCenters Flat centers. + * @param {number} flatCentersOffset Flat center offset. + * @param {Array} [dest] Destination. + * @return {Array} Destination point as XYM coordinate, where M is the + * length of the horizontal intersection that the point belongs to. + */ +function getInteriorPointOfArray( + flatCoordinates, + offset, + ends, + stride, + flatCenters, + flatCentersOffset, + dest, +) { + let i, ii, x, x1, x2, y1, y2; + const y = flatCenters[flatCentersOffset + 1]; + /** @type {Array} */ + const intersections = []; + // Calculate intersections with the horizontal line + for (let r = 0, rr = ends.length; r < rr; ++r) { + const end = ends[r]; + x1 = flatCoordinates[end - stride]; + y1 = flatCoordinates[end - stride + 1]; + for (i = offset; i < end; i += stride) { + x2 = flatCoordinates[i]; + y2 = flatCoordinates[i + 1]; + if ((y <= y1 && y2 <= y) || (y1 <= y && y <= y2)) { + x = ((y - y1) / (y2 - y1)) * (x2 - x1) + x1; + intersections.push(x); + } + x1 = x2; + y1 = y2; + } + } + // Find the longest segment of the horizontal line that has its center point + // inside the linear ring. + let pointX = NaN; + let maxSegmentLength = -Infinity; + intersections.sort(_array_js__WEBPACK_IMPORTED_MODULE_0__.ascending); + x1 = intersections[0]; + for (i = 1, ii = intersections.length; i < ii; ++i) { + x2 = intersections[i]; + const segmentLength = Math.abs(x2 - x1); + if (segmentLength > maxSegmentLength) { + x = (x1 + x2) / 2; + if ((0,_contains_js__WEBPACK_IMPORTED_MODULE_1__.linearRingsContainsXY)(flatCoordinates, offset, ends, stride, x, y)) { + pointX = x; + maxSegmentLength = segmentLength; + } + } + x1 = x2; + } + if (isNaN(pointX)) { + // There is no horizontal line that has its center point inside the linear + // ring. Use the center of the the linear ring's extent. + pointX = flatCenters[flatCentersOffset]; + } + if (dest) { + dest.push(pointX, y, maxSegmentLength); + return dest; + } + return [pointX, y, maxSegmentLength]; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {Array} flatCenters Flat centers. + * @return {Array} Interior points as XYM coordinates, where M is the + * length of the horizontal intersection that the point belongs to. + */ +function getInteriorPointsOfMultiArray( + flatCoordinates, + offset, + endss, + stride, + flatCenters, +) { + /** @type {Array} */ + let interiorPoints = []; + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + interiorPoints = getInteriorPointOfArray( + flatCoordinates, + offset, + ends, + stride, + flatCenters, + 2 * i, + interiorPoints, + ); + offset = ends[ends.length - 1]; + } + return interiorPoints; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/interpolate.js": +/*!**********************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/interpolate.js ***! + \**********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "interpolatePoint": () => (/* binding */ interpolatePoint), +/* harmony export */ "lineStringCoordinateAtM": () => (/* binding */ lineStringCoordinateAtM), +/* harmony export */ "lineStringsCoordinateAtM": () => (/* binding */ lineStringsCoordinateAtM) +/* harmony export */ }); +/* harmony import */ var _array_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../array.js */ "./node_modules/@biigle/ol/array.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/geom/flat/interpolate + */ + + + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} fraction Fraction. + * @param {Array} [dest] Destination. + * @param {number} [dimension] Destination dimension (default is `2`) + * @return {Array} Destination. + */ +function interpolatePoint( + flatCoordinates, + offset, + end, + stride, + fraction, + dest, + dimension, +) { + let o, t; + const n = (end - offset) / stride; + if (n === 1) { + o = offset; + } else if (n === 2) { + o = offset; + t = fraction; + } else if (n !== 0) { + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + let length = 0; + const cumulativeLengths = [0]; + for (let i = offset + stride; i < end; i += stride) { + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; + length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + cumulativeLengths.push(length); + x1 = x2; + y1 = y2; + } + const target = fraction * length; + const index = (0,_array_js__WEBPACK_IMPORTED_MODULE_0__.binarySearch)(cumulativeLengths, target); + if (index < 0) { + t = + (target - cumulativeLengths[-index - 2]) / + (cumulativeLengths[-index - 1] - cumulativeLengths[-index - 2]); + o = offset + (-index - 2) * stride; + } else { + o = offset + index * stride; + } + } + dimension = dimension > 1 ? dimension : 2; + dest = dest ? dest : new Array(dimension); + for (let i = 0; i < dimension; ++i) { + dest[i] = + o === undefined + ? NaN + : t === undefined + ? flatCoordinates[o + i] + : (0,_math_js__WEBPACK_IMPORTED_MODULE_1__.lerp)(flatCoordinates[o + i], flatCoordinates[o + stride + i], t); + } + return dest; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} m M. + * @param {boolean} extrapolate Extrapolate. + * @return {import("../../coordinate.js").Coordinate|null} Coordinate. + */ +function lineStringCoordinateAtM( + flatCoordinates, + offset, + end, + stride, + m, + extrapolate, +) { + if (end == offset) { + return null; + } + let coordinate; + if (m < flatCoordinates[offset + stride - 1]) { + if (extrapolate) { + coordinate = flatCoordinates.slice(offset, offset + stride); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + if (flatCoordinates[end - 1] < m) { + if (extrapolate) { + coordinate = flatCoordinates.slice(end - stride, end); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + // FIXME use O(1) search + if (m == flatCoordinates[offset + stride - 1]) { + return flatCoordinates.slice(offset, offset + stride); + } + let lo = offset / stride; + let hi = end / stride; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (m < flatCoordinates[(mid + 1) * stride - 1]) { + hi = mid; + } else { + lo = mid + 1; + } + } + const m0 = flatCoordinates[lo * stride - 1]; + if (m == m0) { + return flatCoordinates.slice((lo - 1) * stride, (lo - 1) * stride + stride); + } + const m1 = flatCoordinates[(lo + 1) * stride - 1]; + const t = (m - m0) / (m1 - m0); + coordinate = []; + for (let i = 0; i < stride - 1; ++i) { + coordinate.push( + (0,_math_js__WEBPACK_IMPORTED_MODULE_1__.lerp)( + flatCoordinates[(lo - 1) * stride + i], + flatCoordinates[lo * stride + i], + t, + ), + ); + } + coordinate.push(m); + return coordinate; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {number} m M. + * @param {boolean} extrapolate Extrapolate. + * @param {boolean} interpolate Interpolate. + * @return {import("../../coordinate.js").Coordinate|null} Coordinate. + */ +function lineStringsCoordinateAtM( + flatCoordinates, + offset, + ends, + stride, + m, + extrapolate, + interpolate, +) { + if (interpolate) { + return lineStringCoordinateAtM( + flatCoordinates, + offset, + ends[ends.length - 1], + stride, + m, + extrapolate, + ); + } + let coordinate; + if (m < flatCoordinates[stride - 1]) { + if (extrapolate) { + coordinate = flatCoordinates.slice(0, stride); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + if (flatCoordinates[flatCoordinates.length - 1] < m) { + if (extrapolate) { + coordinate = flatCoordinates.slice(flatCoordinates.length - stride); + coordinate[stride - 1] = m; + return coordinate; + } + return null; + } + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + if (offset == end) { + continue; + } + if (m < flatCoordinates[offset + stride - 1]) { + return null; + } + if (m <= flatCoordinates[end - 1]) { + return lineStringCoordinateAtM( + flatCoordinates, + offset, + end, + stride, + m, + false, + ); + } + offset = end; + } + return null; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/intersectsextent.js": +/*!***************************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/intersectsextent.js ***! + \***************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "intersectsLineString": () => (/* binding */ intersectsLineString), +/* harmony export */ "intersectsLineStringArray": () => (/* binding */ intersectsLineStringArray), +/* harmony export */ "intersectsLinearRing": () => (/* binding */ intersectsLinearRing), +/* harmony export */ "intersectsLinearRingArray": () => (/* binding */ intersectsLinearRingArray), +/* harmony export */ "intersectsLinearRingMultiArray": () => (/* binding */ intersectsLinearRingMultiArray) +/* harmony export */ }); +/* harmony import */ var _extent_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../extent.js */ "./node_modules/@biigle/ol/extent.js"); +/* harmony import */ var _segments_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./segments.js */ "./node_modules/@biigle/ol/geom/flat/segments.js"); +/* harmony import */ var _contains_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./contains.js */ "./node_modules/@biigle/ol/geom/flat/contains.js"); +/** + * @module ol/geom/flat/intersectsextent + */ + + + + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {import("../../extent.js").Extent} extent Extent. + * @return {boolean} True if the geometry and the extent intersect. + */ +function intersectsLineString( + flatCoordinates, + offset, + end, + stride, + extent, +) { + const coordinatesExtent = (0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.extendFlatCoordinates)( + (0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.createEmpty)(), + flatCoordinates, + offset, + end, + stride, + ); + if (!(0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.intersects)(extent, coordinatesExtent)) { + return false; + } + if ((0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.containsExtent)(extent, coordinatesExtent)) { + return true; + } + if (coordinatesExtent[0] >= extent[0] && coordinatesExtent[2] <= extent[2]) { + return true; + } + if (coordinatesExtent[1] >= extent[1] && coordinatesExtent[3] <= extent[3]) { + return true; + } + return (0,_segments_js__WEBPACK_IMPORTED_MODULE_1__.forEach)( + flatCoordinates, + offset, + end, + stride, + /** + * @param {import("../../coordinate.js").Coordinate} point1 Start point. + * @param {import("../../coordinate.js").Coordinate} point2 End point. + * @return {boolean} `true` if the segment and the extent intersect, + * `false` otherwise. + */ + function (point1, point2) { + return (0,_extent_js__WEBPACK_IMPORTED_MODULE_0__.intersectsSegment)(extent, point1, point2); + }, + ); +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {import("../../extent.js").Extent} extent Extent. + * @return {boolean} True if the geometry and the extent intersect. + */ +function intersectsLineStringArray( + flatCoordinates, + offset, + ends, + stride, + extent, +) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + if ( + intersectsLineString(flatCoordinates, offset, ends[i], stride, extent) + ) { + return true; + } + offset = ends[i]; + } + return false; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {import("../../extent.js").Extent} extent Extent. + * @return {boolean} True if the geometry and the extent intersect. + */ +function intersectsLinearRing( + flatCoordinates, + offset, + end, + stride, + extent, +) { + if (intersectsLineString(flatCoordinates, offset, end, stride, extent)) { + return true; + } + if ( + (0,_contains_js__WEBPACK_IMPORTED_MODULE_2__.linearRingContainsXY)( + flatCoordinates, + offset, + end, + stride, + extent[0], + extent[1], + ) + ) { + return true; + } + if ( + (0,_contains_js__WEBPACK_IMPORTED_MODULE_2__.linearRingContainsXY)( + flatCoordinates, + offset, + end, + stride, + extent[0], + extent[3], + ) + ) { + return true; + } + if ( + (0,_contains_js__WEBPACK_IMPORTED_MODULE_2__.linearRingContainsXY)( + flatCoordinates, + offset, + end, + stride, + extent[2], + extent[1], + ) + ) { + return true; + } + if ( + (0,_contains_js__WEBPACK_IMPORTED_MODULE_2__.linearRingContainsXY)( + flatCoordinates, + offset, + end, + stride, + extent[2], + extent[3], + ) + ) { + return true; + } + return false; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {import("../../extent.js").Extent} extent Extent. + * @return {boolean} True if the geometry and the extent intersect. + */ +function intersectsLinearRingArray( + flatCoordinates, + offset, + ends, + stride, + extent, +) { + if (!intersectsLinearRing(flatCoordinates, offset, ends[0], stride, extent)) { + return false; + } + if (ends.length === 1) { + return true; + } + for (let i = 1, ii = ends.length; i < ii; ++i) { + if ( + (0,_contains_js__WEBPACK_IMPORTED_MODULE_2__.linearRingContainsExtent)( + flatCoordinates, + ends[i - 1], + ends[i], + stride, + extent, + ) + ) { + if ( + !intersectsLineString( + flatCoordinates, + ends[i - 1], + ends[i], + stride, + extent, + ) + ) { + return false; + } + } + } + return true; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {import("../../extent.js").Extent} extent Extent. + * @return {boolean} True if the geometry and the extent intersect. + */ +function intersectsLinearRingMultiArray( + flatCoordinates, + offset, + endss, + stride, + extent, +) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + if ( + intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent) + ) { + return true; + } + offset = ends[ends.length - 1]; + } + return false; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/length.js": +/*!*****************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/length.js ***! + \*****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "lineStringLength": () => (/* binding */ lineStringLength), +/* harmony export */ "linearRingLength": () => (/* binding */ linearRingLength) +/* harmony export */ }); +/** + * @module ol/geom/flat/length + */ + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {number} Length. + */ +function lineStringLength(flatCoordinates, offset, end, stride) { + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + let length = 0; + for (let i = offset + stride; i < end; i += stride) { + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; + length += Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + x1 = x2; + y1 = y2; + } + return length; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {number} Perimeter. + */ +function linearRingLength(flatCoordinates, offset, end, stride) { + let perimeter = lineStringLength(flatCoordinates, offset, end, stride); + const dx = flatCoordinates[end - stride] - flatCoordinates[offset]; + const dy = flatCoordinates[end - stride + 1] - flatCoordinates[offset + 1]; + perimeter += Math.sqrt(dx * dx + dy * dy); + return perimeter; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/linechunk.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/linechunk.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "lineChunk": () => (/* binding */ lineChunk) +/* harmony export */ }); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../math.js */ "./node_modules/@biigle/ol/math.js"); + + +/** + * Creates chunks of equal length from a linestring + * @param {number} chunkLength Length of each chunk. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Start offset of the `flatCoordinates`. + * @param {number} end End offset of the `flatCoordinates`. + * @param {number} stride Stride. + * @return {Array>} Chunks of linestrings with stride 2. + */ +function lineChunk(chunkLength, flatCoordinates, offset, end, stride) { + const chunks = []; + let cursor = offset; + let chunkM = 0; + let currentChunk = flatCoordinates.slice(offset, 2); + while (chunkM < chunkLength && cursor + stride < end) { + const [x1, y1] = currentChunk.slice(-2); + const x2 = flatCoordinates[cursor + stride]; + const y2 = flatCoordinates[cursor + stride + 1]; + const segmentLength = Math.sqrt( + (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1), + ); + chunkM += segmentLength; + if (chunkM >= chunkLength) { + const m = (chunkLength - chunkM + segmentLength) / segmentLength; + const x = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(x1, x2, m); + const y = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(y1, y2, m); + currentChunk.push(x, y); + chunks.push(currentChunk); + currentChunk = [x, y]; + if (chunkM == chunkLength) { + cursor += stride; + } + chunkM = 0; + } else if (chunkM < chunkLength) { + currentChunk.push( + flatCoordinates[cursor + stride], + flatCoordinates[cursor + stride + 1], + ); + cursor += stride; + } else { + const missing = segmentLength - chunkM; + const x = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(x1, x2, missing / segmentLength); + const y = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(y1, y2, missing / segmentLength); + currentChunk.push(x, y); + chunks.push(currentChunk); + currentChunk = [x, y]; + chunkM = 0; + cursor += stride; + } + } + if (chunkM > 0) { + chunks.push(currentChunk); + } + return chunks; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/orient.js": +/*!*****************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/orient.js ***! + \*****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "inflateEnds": () => (/* binding */ inflateEnds), +/* harmony export */ "linearRingIsClockwise": () => (/* binding */ linearRingIsClockwise), +/* harmony export */ "linearRingsAreOriented": () => (/* binding */ linearRingsAreOriented), +/* harmony export */ "linearRingssAreOriented": () => (/* binding */ linearRingssAreOriented), +/* harmony export */ "orientLinearRings": () => (/* binding */ orientLinearRings), +/* harmony export */ "orientLinearRingsArray": () => (/* binding */ orientLinearRingsArray) +/* harmony export */ }); +/* harmony import */ var _reverse_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./reverse.js */ "./node_modules/@biigle/ol/geom/flat/reverse.js"); +/** + * @module ol/geom/flat/orient + */ + + +/** + * Is the linear ring oriented clockwise in a coordinate system with a bottom-left + * coordinate origin? For a coordinate system with a top-left coordinate origin, + * the ring's orientation is clockwise when this function returns false. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {boolean|undefined} Is clockwise. + */ +function linearRingIsClockwise(flatCoordinates, offset, end, stride) { + // https://stackoverflow.com/q/1165647/clockwise-method#1165943 + // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrlinearring.cpp + let edge = 0; + let x1 = flatCoordinates[end - stride]; + let y1 = flatCoordinates[end - stride + 1]; + for (; offset < end; offset += stride) { + const x2 = flatCoordinates[offset]; + const y2 = flatCoordinates[offset + 1]; + edge += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + return edge === 0 ? undefined : edge > 0; +} + +/** + * Determines if linear rings are oriented. By default, left-hand orientation + * is tested (first ring must be clockwise, remaining rings counter-clockwise). + * To test for right-hand orientation, use the `right` argument. + * + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Array of end indexes. + * @param {number} stride Stride. + * @param {boolean} [right] Test for right-hand orientation + * (counter-clockwise exterior ring and clockwise interior rings). + * @return {boolean} Rings are correctly oriented. + */ +function linearRingsAreOriented( + flatCoordinates, + offset, + ends, + stride, + right, +) { + right = right !== undefined ? right : false; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const isClockwise = linearRingIsClockwise( + flatCoordinates, + offset, + end, + stride, + ); + if (i === 0) { + if ((right && isClockwise) || (!right && !isClockwise)) { + return false; + } + } else { + if ((right && !isClockwise) || (!right && isClockwise)) { + return false; + } + } + offset = end; + } + return true; +} + +/** + * Determines if linear rings are oriented. By default, left-hand orientation + * is tested (first ring must be clockwise, remaining rings counter-clockwise). + * To test for right-hand orientation, use the `right` argument. + * + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Array of array of end indexes. + * @param {number} stride Stride. + * @param {boolean} [right] Test for right-hand orientation + * (counter-clockwise exterior ring and clockwise interior rings). + * @return {boolean} Rings are correctly oriented. + */ +function linearRingssAreOriented( + flatCoordinates, + offset, + endss, + stride, + right, +) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + if (!linearRingsAreOriented(flatCoordinates, offset, ends, stride, right)) { + return false; + } + if (ends.length) { + offset = ends[ends.length - 1]; + } + } + return true; +} + +/** + * Orient coordinates in a flat array of linear rings. By default, rings + * are oriented following the left-hand rule (clockwise for exterior and + * counter-clockwise for interior rings). To orient according to the + * right-hand rule, use the `right` argument. + * + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {boolean} [right] Follow the right-hand rule for orientation. + * @return {number} End. + */ +function orientLinearRings( + flatCoordinates, + offset, + ends, + stride, + right, +) { + right = right !== undefined ? right : false; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + const isClockwise = linearRingIsClockwise( + flatCoordinates, + offset, + end, + stride, + ); + const reverse = + i === 0 + ? (right && isClockwise) || (!right && !isClockwise) + : (right && !isClockwise) || (!right && isClockwise); + if (reverse) { + (0,_reverse_js__WEBPACK_IMPORTED_MODULE_0__.coordinates)(flatCoordinates, offset, end, stride); + } + offset = end; + } + return offset; +} + +/** + * Orient coordinates in a flat array of linear rings. By default, rings + * are oriented following the left-hand rule (clockwise for exterior and + * counter-clockwise for interior rings). To orient according to the + * right-hand rule, use the `right` argument. + * + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Array of array of end indexes. + * @param {number} stride Stride. + * @param {boolean} [right] Follow the right-hand rule for orientation. + * @return {number} End. + */ +function orientLinearRingsArray( + flatCoordinates, + offset, + endss, + stride, + right, +) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + offset = orientLinearRings( + flatCoordinates, + offset, + endss[i], + stride, + right, + ); + } + return offset; +} + +/** + * Return a two-dimensional endss + * @param {Array} flatCoordinates Flat coordinates + * @param {Array} ends Linear ring end indexes + * @return {Array>} Two dimensional endss array that can + * be used to construct a MultiPolygon + */ +function inflateEnds(flatCoordinates, ends) { + const endss = []; + let offset = 0; + let prevEndIndex = 0; + let startOrientation; + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + // classifies an array of rings into polygons with outer rings and holes + const orientation = linearRingIsClockwise(flatCoordinates, offset, end, 2); + if (startOrientation === undefined) { + startOrientation = orientation; + } + if (orientation === startOrientation) { + endss.push(ends.slice(prevEndIndex, i + 1)); + } else { + if (endss.length === 0) { + continue; + } + endss[endss.length - 1].push(ends[prevEndIndex]); + } + prevEndIndex = i + 1; + offset = end; + } + return endss; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/reverse.js": +/*!******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/reverse.js ***! + \******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "coordinates": () => (/* binding */ coordinates) +/* harmony export */ }); +/** + * @module ol/geom/flat/reverse + */ + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + */ +function coordinates(flatCoordinates, offset, end, stride) { + while (offset < end - stride) { + for (let i = 0; i < stride; ++i) { + const tmp = flatCoordinates[offset + i]; + flatCoordinates[offset + i] = flatCoordinates[end - stride + i]; + flatCoordinates[end - stride + i] = tmp; + } + offset += stride; + end -= stride; + } +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/segments.js": +/*!*******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/segments.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "forEach": () => (/* binding */ forEach) +/* harmony export */ }); +/** + * @module ol/geom/flat/segments + */ + +/** + * This function calls `callback` for each segment of the flat coordinates + * array. If the callback returns a truthy value the function returns that + * value immediately. Otherwise the function returns `false`. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {function(import("../../coordinate.js").Coordinate, import("../../coordinate.js").Coordinate): T} callback Function + * called for each segment. + * @return {T|boolean} Value. + * @template T + */ +function forEach(flatCoordinates, offset, end, stride, callback) { + let ret; + offset += stride; + for (; offset < end; offset += stride) { + ret = callback( + flatCoordinates.slice(offset - stride, offset), + flatCoordinates.slice(offset, offset + stride), + ); + if (ret) { + return ret; + } + } + return false; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/simplify.js": +/*!*******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/simplify.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "douglasPeucker": () => (/* binding */ douglasPeucker), +/* harmony export */ "douglasPeuckerArray": () => (/* binding */ douglasPeuckerArray), +/* harmony export */ "douglasPeuckerMultiArray": () => (/* binding */ douglasPeuckerMultiArray), +/* harmony export */ "quantize": () => (/* binding */ quantize), +/* harmony export */ "quantizeArray": () => (/* binding */ quantizeArray), +/* harmony export */ "quantizeMultiArray": () => (/* binding */ quantizeMultiArray), +/* harmony export */ "radialDistance": () => (/* binding */ radialDistance), +/* harmony export */ "simplifyLineString": () => (/* binding */ simplifyLineString), +/* harmony export */ "snap": () => (/* binding */ snap) +/* harmony export */ }); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/geom/flat/simplify + */ +// Based on simplify-js https://github.com/mourner/simplify-js +// Copyright (c) 2012, Vladimir Agafonkin +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. + + + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} squaredTolerance Squared tolerance. + * @param {boolean} highQuality Highest quality. + * @param {Array} [simplifiedFlatCoordinates] Simplified flat + * coordinates. + * @return {Array} Simplified line string. + */ +function simplifyLineString( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + highQuality, + simplifiedFlatCoordinates, +) { + simplifiedFlatCoordinates = + simplifiedFlatCoordinates !== undefined ? simplifiedFlatCoordinates : []; + if (!highQuality) { + end = radialDistance( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0, + ); + flatCoordinates = simplifiedFlatCoordinates; + offset = 0; + stride = 2; + } + simplifiedFlatCoordinates.length = douglasPeucker( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + 0, + ); + return simplifiedFlatCoordinates; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} squaredTolerance Squared tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @return {number} Simplified offset. + */ +function douglasPeucker( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset, +) { + const n = (end - offset) / stride; + if (n < 3) { + for (; offset < end; offset += stride) { + simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset]; + simplifiedFlatCoordinates[simplifiedOffset++] = + flatCoordinates[offset + 1]; + } + return simplifiedOffset; + } + /** @type {Array} */ + const markers = new Array(n); + markers[0] = 1; + markers[n - 1] = 1; + /** @type {Array} */ + const stack = [offset, end - stride]; + let index = 0; + while (stack.length > 0) { + const last = stack.pop(); + const first = stack.pop(); + let maxSquaredDistance = 0; + const x1 = flatCoordinates[first]; + const y1 = flatCoordinates[first + 1]; + const x2 = flatCoordinates[last]; + const y2 = flatCoordinates[last + 1]; + for (let i = first + stride; i < last; i += stride) { + const x = flatCoordinates[i]; + const y = flatCoordinates[i + 1]; + const squaredDistance = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.squaredSegmentDistance)(x, y, x1, y1, x2, y2); + if (squaredDistance > maxSquaredDistance) { + index = i; + maxSquaredDistance = squaredDistance; + } + } + if (maxSquaredDistance > squaredTolerance) { + markers[(index - offset) / stride] = 1; + if (first + stride < index) { + stack.push(first, index); + } + if (index + stride < last) { + stack.push(index, last); + } + } + } + for (let i = 0; i < n; ++i) { + if (markers[i]) { + simplifiedFlatCoordinates[simplifiedOffset++] = + flatCoordinates[offset + i * stride]; + simplifiedFlatCoordinates[simplifiedOffset++] = + flatCoordinates[offset + i * stride + 1]; + } + } + return simplifiedOffset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {number} squaredTolerance Squared tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @param {Array} simplifiedEnds Simplified ends. + * @return {number} Simplified offset. + */ +function douglasPeuckerArray( + flatCoordinates, + offset, + ends, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEnds, +) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + simplifiedOffset = douglasPeucker( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + ); + simplifiedEnds.push(simplifiedOffset); + offset = end; + } + return simplifiedOffset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {number} squaredTolerance Squared tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @param {Array>} simplifiedEndss Simplified endss. + * @return {number} Simplified offset. + */ +function douglasPeuckerMultiArray( + flatCoordinates, + offset, + endss, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEndss, +) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + /** @type {Array} */ + const simplifiedEnds = []; + simplifiedOffset = douglasPeuckerArray( + flatCoordinates, + offset, + ends, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEnds, + ); + simplifiedEndss.push(simplifiedEnds); + offset = ends[ends.length - 1]; + } + return simplifiedOffset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} squaredTolerance Squared tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @return {number} Simplified offset. + */ +function radialDistance( + flatCoordinates, + offset, + end, + stride, + squaredTolerance, + simplifiedFlatCoordinates, + simplifiedOffset, +) { + if (end <= offset + stride) { + // zero or one point, no simplification possible, so copy and return + for (; offset < end; offset += stride) { + simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset]; + simplifiedFlatCoordinates[simplifiedOffset++] = + flatCoordinates[offset + 1]; + } + return simplifiedOffset; + } + let x1 = flatCoordinates[offset]; + let y1 = flatCoordinates[offset + 1]; + // copy first point + simplifiedFlatCoordinates[simplifiedOffset++] = x1; + simplifiedFlatCoordinates[simplifiedOffset++] = y1; + let x2 = x1; + let y2 = y1; + for (offset += stride; offset < end; offset += stride) { + x2 = flatCoordinates[offset]; + y2 = flatCoordinates[offset + 1]; + if ((0,_math_js__WEBPACK_IMPORTED_MODULE_0__.squaredDistance)(x1, y1, x2, y2) > squaredTolerance) { + // copy point at offset + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + x1 = x2; + y1 = y2; + } + } + if (x2 != x1 || y2 != y1) { + // copy last point + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + } + return simplifiedOffset; +} + +/** + * @param {number} value Value. + * @param {number} tolerance Tolerance. + * @return {number} Rounded value. + */ +function snap(value, tolerance) { + return tolerance * Math.round(value / tolerance); +} + +/** + * Simplifies a line string using an algorithm designed by Tim Schaub. + * Coordinates are snapped to the nearest value in a virtual grid and + * consecutive duplicate coordinates are discarded. This effectively preserves + * topology as the simplification of any subsection of a line string is + * independent of the rest of the line string. This means that, for examples, + * the common edge between two polygons will be simplified to the same line + * string independently in both polygons. This implementation uses a single + * pass over the coordinates and eliminates intermediate collinear points. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} tolerance Tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @return {number} Simplified offset. + */ +function quantize( + flatCoordinates, + offset, + end, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset, +) { + // do nothing if the line is empty + if (offset == end) { + return simplifiedOffset; + } + // snap the first coordinate (P1) + let x1 = snap(flatCoordinates[offset], tolerance); + let y1 = snap(flatCoordinates[offset + 1], tolerance); + offset += stride; + // add the first coordinate to the output + simplifiedFlatCoordinates[simplifiedOffset++] = x1; + simplifiedFlatCoordinates[simplifiedOffset++] = y1; + // find the next coordinate that does not snap to the same value as the first + // coordinate (P2) + let x2, y2; + do { + x2 = snap(flatCoordinates[offset], tolerance); + y2 = snap(flatCoordinates[offset + 1], tolerance); + offset += stride; + if (offset == end) { + // all coordinates snap to the same value, the line collapses to a point + // push the last snapped value anyway to ensure that the output contains + // at least two points + // FIXME should we really return at least two points anyway? + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + return simplifiedOffset; + } + } while (x2 == x1 && y2 == y1); + while (offset < end) { + // snap the next coordinate (P3) + const x3 = snap(flatCoordinates[offset], tolerance); + const y3 = snap(flatCoordinates[offset + 1], tolerance); + offset += stride; + // skip P3 if it is equal to P2 + if (x3 == x2 && y3 == y2) { + continue; + } + // calculate the delta between P1 and P2 + const dx1 = x2 - x1; + const dy1 = y2 - y1; + // calculate the delta between P3 and P1 + const dx2 = x3 - x1; + const dy2 = y3 - y1; + // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from + // P1 in the same direction then P2 is on the straight line between P1 and + // P3 + if ( + dx1 * dy2 == dy1 * dx2 && + ((dx1 < 0 && dx2 < dx1) || dx1 == dx2 || (dx1 > 0 && dx2 > dx1)) && + ((dy1 < 0 && dy2 < dy1) || dy1 == dy2 || (dy1 > 0 && dy2 > dy1)) + ) { + // discard P2 and set P2 = P3 + x2 = x3; + y2 = y3; + continue; + } + // either P1, P2, and P3 are not colinear, or they are colinear but P3 is + // between P3 and P1 or on the opposite half of the line to P2. add P2, + // and continue with P1 = P2 and P2 = P3 + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + x1 = x2; + y1 = y2; + x2 = x3; + y2 = y3; + } + // add the last point (P2) + simplifiedFlatCoordinates[simplifiedOffset++] = x2; + simplifiedFlatCoordinates[simplifiedOffset++] = y2; + return simplifiedOffset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array} ends Ends. + * @param {number} stride Stride. + * @param {number} tolerance Tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @param {Array} simplifiedEnds Simplified ends. + * @return {number} Simplified offset. + */ +function quantizeArray( + flatCoordinates, + offset, + ends, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEnds, +) { + for (let i = 0, ii = ends.length; i < ii; ++i) { + const end = ends[i]; + simplifiedOffset = quantize( + flatCoordinates, + offset, + end, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + ); + simplifiedEnds.push(simplifiedOffset); + offset = end; + } + return simplifiedOffset; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {Array>} endss Endss. + * @param {number} stride Stride. + * @param {number} tolerance Tolerance. + * @param {Array} simplifiedFlatCoordinates Simplified flat + * coordinates. + * @param {number} simplifiedOffset Simplified offset. + * @param {Array>} simplifiedEndss Simplified endss. + * @return {number} Simplified offset. + */ +function quantizeMultiArray( + flatCoordinates, + offset, + endss, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEndss, +) { + for (let i = 0, ii = endss.length; i < ii; ++i) { + const ends = endss[i]; + /** @type {Array} */ + const simplifiedEnds = []; + simplifiedOffset = quantizeArray( + flatCoordinates, + offset, + ends, + stride, + tolerance, + simplifiedFlatCoordinates, + simplifiedOffset, + simplifiedEnds, + ); + simplifiedEndss.push(simplifiedEnds); + offset = ends[ends.length - 1]; + } + return simplifiedOffset; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/straightchunk.js": +/*!************************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/straightchunk.js ***! + \************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "matchingChunk": () => (/* binding */ matchingChunk) +/* harmony export */ }); +/** + * @module ol/geom/flat/straightchunk + */ + +/** + * @param {number} maxAngle Maximum acceptable angle delta between segments. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @return {Array} Start and end of the first suitable chunk of the + * given `flatCoordinates`. + */ +function matchingChunk(maxAngle, flatCoordinates, offset, end, stride) { + let chunkStart = offset; + let chunkEnd = offset; + let chunkM = 0; + let m = 0; + let start = offset; + let acos, i, m12, m23, x1, y1, x12, y12, x23, y23; + for (i = offset; i < end; i += stride) { + const x2 = flatCoordinates[i]; + const y2 = flatCoordinates[i + 1]; + if (x1 !== undefined) { + x23 = x2 - x1; + y23 = y2 - y1; + m23 = Math.sqrt(x23 * x23 + y23 * y23); + if (x12 !== undefined) { + m += m12; + acos = Math.acos((x12 * x23 + y12 * y23) / (m12 * m23)); + if (acos > maxAngle) { + if (m > chunkM) { + chunkM = m; + chunkStart = start; + chunkEnd = i; + } + m = 0; + start = i - stride; + } + } + m12 = m23; + x12 = x23; + y12 = y23; + } + x1 = x2; + y1 = y2; + } + m += m23; + return m > chunkM ? [start, i] : [chunkStart, chunkEnd]; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/textpath.js": +/*!*******************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/textpath.js ***! + \*******************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "drawTextOnPath": () => (/* binding */ drawTextOnPath) +/* harmony export */ }); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../math.js */ "./node_modules/@biigle/ol/math.js"); +/* harmony import */ var _transform_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./transform.js */ "./node_modules/@biigle/ol/geom/flat/transform.js"); +/** + * @module ol/geom/flat/textpath + */ + + + +/** + * @param {Array} flatCoordinates Path to put text on. + * @param {number} offset Start offset of the `flatCoordinates`. + * @param {number} end End offset of the `flatCoordinates`. + * @param {number} stride Stride. + * @param {string} text Text to place on the path. + * @param {number} startM m along the path where the text starts. + * @param {number} maxAngle Max angle between adjacent chars in radians. + * @param {number} scale The product of the text scale and the device pixel ratio. + * @param {function(string, string, Object):number} measureAndCacheTextWidth Measure and cache text width. + * @param {string} font The font. + * @param {Object} cache A cache of measured widths. + * @param {number} rotation Rotation to apply to the flatCoordinates to determine whether text needs to be reversed. + * @return {Array>|null} The result array (or null if `maxAngle` was + * exceeded). Entries of the array are x, y, anchorX, angle, chunk. + */ +function drawTextOnPath( + flatCoordinates, + offset, + end, + stride, + text, + startM, + maxAngle, + scale, + measureAndCacheTextWidth, + font, + cache, + rotation, +) { + let x2 = flatCoordinates[offset]; + let y2 = flatCoordinates[offset + 1]; + let x1 = 0; + let y1 = 0; + let segmentLength = 0; + let segmentM = 0; + + function advance() { + x1 = x2; + y1 = y2; + offset += stride; + x2 = flatCoordinates[offset]; + y2 = flatCoordinates[offset + 1]; + segmentM += segmentLength; + segmentLength = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + } + do { + advance(); + } while (offset < end - stride && segmentM + segmentLength < startM); + + let interpolate = + segmentLength === 0 ? 0 : (startM - segmentM) / segmentLength; + const beginX = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(x1, x2, interpolate); + const beginY = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(y1, y2, interpolate); + + const startOffset = offset - stride; + const startLength = segmentM; + const endM = startM + scale * measureAndCacheTextWidth(font, text, cache); + while (offset < end - stride && segmentM + segmentLength < endM) { + advance(); + } + interpolate = segmentLength === 0 ? 0 : (endM - segmentM) / segmentLength; + const endX = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(x1, x2, interpolate); + const endY = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(y1, y2, interpolate); + + // Keep text upright + let reverse; + if (rotation) { + const flat = [beginX, beginY, endX, endY]; + (0,_transform_js__WEBPACK_IMPORTED_MODULE_1__.rotate)(flat, 0, 4, 2, rotation, flat, flat); + reverse = flat[0] > flat[2]; + } else { + reverse = beginX > endX; + } + + const PI = Math.PI; + const result = []; + const singleSegment = startOffset + stride === offset; + + offset = startOffset; + segmentLength = 0; + segmentM = startLength; + x2 = flatCoordinates[offset]; + y2 = flatCoordinates[offset + 1]; + + let previousAngle; + // All on the same segment + if (singleSegment) { + advance(); + + previousAngle = Math.atan2(y2 - y1, x2 - x1); + if (reverse) { + previousAngle += previousAngle > 0 ? -PI : PI; + } + const x = (endX + beginX) / 2; + const y = (endY + beginY) / 2; + result[0] = [x, y, (endM - startM) / 2, previousAngle, text]; + return result; + } + + // rendering across line segments + text = text.replace(/\n/g, ' '); // ensure rendering in single-line as all calculations below don't handle multi-lines + + for (let i = 0, ii = text.length; i < ii; ) { + advance(); + let angle = Math.atan2(y2 - y1, x2 - x1); + if (reverse) { + angle += angle > 0 ? -PI : PI; + } + if (previousAngle !== undefined) { + let delta = angle - previousAngle; + delta += delta > PI ? -2 * PI : delta < -PI ? 2 * PI : 0; + if (Math.abs(delta) > maxAngle) { + return null; + } + } + previousAngle = angle; + + const iStart = i; + let charLength = 0; + for (; i < ii; ++i) { + const index = reverse ? ii - i - 1 : i; + const len = scale * measureAndCacheTextWidth(font, text[index], cache); + if ( + offset + stride < end && + segmentM + segmentLength < startM + charLength + len / 2 + ) { + break; + } + charLength += len; + } + if (i === iStart) { + continue; + } + const chars = reverse + ? text.substring(ii - iStart, ii - i) + : text.substring(iStart, i); + interpolate = + segmentLength === 0 + ? 0 + : (startM + charLength / 2 - segmentM) / segmentLength; + const x = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(x1, x2, interpolate); + const y = (0,_math_js__WEBPACK_IMPORTED_MODULE_0__.lerp)(y1, y2, interpolate); + result.push([x, y, charLength / 2, angle, chars]); + startM += charLength; + } + return result; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/geom/flat/transform.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/geom/flat/transform.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "rotate": () => (/* binding */ rotate), +/* harmony export */ "scale": () => (/* binding */ scale), +/* harmony export */ "transform2D": () => (/* binding */ transform2D), +/* harmony export */ "translate": () => (/* binding */ translate) +/* harmony export */ }); +/** + * @module ol/geom/flat/transform + */ + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {import("../../transform.js").Transform} transform Transform. + * @param {Array} [dest] Destination. + * @return {Array} Transformed coordinates. + */ +function transform2D( + flatCoordinates, + offset, + end, + stride, + transform, + dest, +) { + dest = dest ? dest : []; + let i = 0; + for (let j = offset; j < end; j += stride) { + const x = flatCoordinates[j]; + const y = flatCoordinates[j + 1]; + dest[i++] = transform[0] * x + transform[2] * y + transform[4]; + dest[i++] = transform[1] * x + transform[3] * y + transform[5]; + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} angle Angle. + * @param {Array} anchor Rotation anchor point. + * @param {Array} [dest] Destination. + * @return {Array} Transformed coordinates. + */ +function rotate( + flatCoordinates, + offset, + end, + stride, + angle, + anchor, + dest, +) { + dest = dest ? dest : []; + const cos = Math.cos(angle); + const sin = Math.sin(angle); + const anchorX = anchor[0]; + const anchorY = anchor[1]; + let i = 0; + for (let j = offset; j < end; j += stride) { + const deltaX = flatCoordinates[j] - anchorX; + const deltaY = flatCoordinates[j + 1] - anchorY; + dest[i++] = anchorX + deltaX * cos - deltaY * sin; + dest[i++] = anchorY + deltaX * sin + deltaY * cos; + for (let k = j + 2; k < j + stride; ++k) { + dest[i++] = flatCoordinates[k]; + } + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} + +/** + * Scale the coordinates. + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} sx Scale factor in the x-direction. + * @param {number} sy Scale factor in the y-direction. + * @param {Array} anchor Scale anchor point. + * @param {Array} [dest] Destination. + * @return {Array} Transformed coordinates. + */ +function scale( + flatCoordinates, + offset, + end, + stride, + sx, + sy, + anchor, + dest, +) { + dest = dest ? dest : []; + const anchorX = anchor[0]; + const anchorY = anchor[1]; + let i = 0; + for (let j = offset; j < end; j += stride) { + const deltaX = flatCoordinates[j] - anchorX; + const deltaY = flatCoordinates[j + 1] - anchorY; + dest[i++] = anchorX + sx * deltaX; + dest[i++] = anchorY + sy * deltaY; + for (let k = j + 2; k < j + stride; ++k) { + dest[i++] = flatCoordinates[k]; + } + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} + +/** + * @param {Array} flatCoordinates Flat coordinates. + * @param {number} offset Offset. + * @param {number} end End. + * @param {number} stride Stride. + * @param {number} deltaX Delta X. + * @param {number} deltaY Delta Y. + * @param {Array} [dest] Destination. + * @return {Array} Transformed coordinates. + */ +function translate( + flatCoordinates, + offset, + end, + stride, + deltaX, + deltaY, + dest, +) { + dest = dest ? dest : []; + let i = 0; + for (let j = offset; j < end; j += stride) { + dest[i++] = flatCoordinates[j] + deltaX; + dest[i++] = flatCoordinates[j + 1] + deltaY; + for (let k = j + 2; k < j + stride; ++k) { + dest[i++] = flatCoordinates[k]; + } + } + if (dest && dest.length != i) { + dest.length = i; + } + return dest; +} + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/has.js": +/*!****************************************!*\ + !*** ./node_modules/@biigle/ol/has.js ***! + \****************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "CREATE_IMAGE_BITMAP": () => (/* binding */ CREATE_IMAGE_BITMAP), +/* harmony export */ "DEVICE_PIXEL_RATIO": () => (/* binding */ DEVICE_PIXEL_RATIO), +/* harmony export */ "FIREFOX": () => (/* binding */ FIREFOX), +/* harmony export */ "IMAGE_DECODE": () => (/* binding */ IMAGE_DECODE), +/* harmony export */ "MAC": () => (/* binding */ MAC), +/* harmony export */ "PASSIVE_EVENT_LISTENERS": () => (/* binding */ PASSIVE_EVENT_LISTENERS), +/* harmony export */ "SAFARI": () => (/* binding */ SAFARI), +/* harmony export */ "SAFARI_BUG_237906": () => (/* binding */ SAFARI_BUG_237906), +/* harmony export */ "WEBKIT": () => (/* binding */ WEBKIT), +/* harmony export */ "WORKER_OFFSCREEN_CANVAS": () => (/* binding */ WORKER_OFFSCREEN_CANVAS) +/* harmony export */ }); +/** + * @module ol/has + */ + +const ua = + typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined' + ? navigator.userAgent.toLowerCase() + : ''; + +/** + * User agent string says we are dealing with Firefox as browser. + * @type {boolean} + */ +const FIREFOX = ua.includes('firefox'); + +/** + * User agent string says we are dealing with Safari as browser. + * @type {boolean} + */ +const SAFARI = ua.includes('safari') && !ua.includes('chrom'); + +/** + * https://bugs.webkit.org/show_bug.cgi?id=237906 + * @type {boolean} + */ +const SAFARI_BUG_237906 = + SAFARI && + (ua.includes('version/15.4') || + /cpu (os|iphone os) 15_4 like mac os x/.test(ua)); + +/** + * User agent string says we are dealing with a WebKit engine. + * @type {boolean} + */ +const WEBKIT = ua.includes('webkit') && !ua.includes('edge'); + +/** + * User agent string says we are dealing with a Mac as platform. + * @type {boolean} + */ +const MAC = ua.includes('macintosh'); + +/** + * The ratio between physical pixels and device-independent pixels + * (dips) on the device (`window.devicePixelRatio`). + * @const + * @type {number} + * @api + */ +const DEVICE_PIXEL_RATIO = + typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1; + +/** + * The execution context is a worker with OffscreenCanvas available. + * @const + * @type {boolean} + */ +const WORKER_OFFSCREEN_CANVAS = + typeof WorkerGlobalScope !== 'undefined' && + typeof OffscreenCanvas !== 'undefined' && + self instanceof WorkerGlobalScope; //eslint-disable-line + +/** + * Image.prototype.decode() is supported. + * @type {boolean} + */ +const IMAGE_DECODE = + typeof Image !== 'undefined' && Image.prototype.decode; + +/** + * createImageBitmap() is supported. + * @type {boolean} + */ +const CREATE_IMAGE_BITMAP = typeof createImageBitmap === 'function'; + +/** + * @type {boolean} + */ +const PASSIVE_EVENT_LISTENERS = (function () { + let passive = false; + try { + const options = Object.defineProperty({}, 'passive', { + get: function () { + passive = true; + }, + }); + + // @ts-ignore Ignore invalid event type '_' + window.addEventListener('_', null, options); + // @ts-ignore Ignore invalid event type '_' + window.removeEventListener('_', null, options); + } catch (error) { + // passive not supported + } + return passive; +})(); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/interaction/Interaction.js": +/*!************************************************************!*\ + !*** ./node_modules/@biigle/ol/interaction/Interaction.js ***! + \************************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__), +/* harmony export */ "pan": () => (/* binding */ pan), +/* harmony export */ "zoomByDelta": () => (/* binding */ zoomByDelta) +/* harmony export */ }); +/* harmony import */ var _Object_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Object.js */ "./node_modules/@biigle/ol/Object.js"); +/* harmony import */ var _Property_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Property.js */ "./node_modules/@biigle/ol/interaction/Property.js"); +/* harmony import */ var _easing_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../easing.js */ "./node_modules/@biigle/ol/easing.js"); +/** + * @module ol/interaction/Interaction + */ + + + + +/*** + * @template Return + * @typedef {import("../Observable").OnSignature & + * import("../Observable").OnSignature & + * import("../Observable").CombinedOnSignature} InteractionOnSignature + */ + +/** + * Object literal with config options for interactions. + * @typedef {Object} InteractionOptions + * @property {function(import("../MapBrowserEvent.js").default):boolean} handleEvent + * Method called by the map to notify the interaction that a browser event was + * dispatched to the map. If the function returns a falsy value, propagation of + * the event to other interactions in the map's interactions chain will be + * prevented (this includes functions with no explicit return). The interactions + * are traversed in reverse order of the interactions collection of the map. + */ + +/** + * @classdesc + * Abstract base class; normally only used for creating subclasses and not + * instantiated in apps. + * User actions that change the state of the map. Some are similar to controls, + * but are not associated with a DOM element. + * For example, {@link module:ol/interaction/KeyboardZoom~KeyboardZoom} is + * functionally the same as {@link module:ol/control/Zoom~Zoom}, but triggered + * by a keyboard event not a button element event. + * Although interactions do not have a DOM element, some of them do render + * vectors and so are visible on the screen. + * @api + */ +class Interaction extends _Object_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {InteractionOptions} [options] Options. + */ + constructor(options) { + super(); + + /*** + * @type {InteractionOnSignature} + */ + this.on; + + /*** + * @type {InteractionOnSignature} + */ + this.once; + + /*** + * @type {InteractionOnSignature} + */ + this.un; + + if (options && options.handleEvent) { + this.handleEvent = options.handleEvent; + } + + /** + * @private + * @type {import("../Map.js").default|null} + */ + this.map_ = null; + + this.setActive(true); + } + + /** + * Return whether the interaction is currently active. + * @return {boolean} `true` if the interaction is active, `false` otherwise. + * @observable + * @api + */ + getActive() { + return /** @type {boolean} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].ACTIVE)); + } + + /** + * Get the map associated with this interaction. + * @return {import("../Map.js").default|null} Map. + * @api + */ + getMap() { + return this.map_; + } + + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event}. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + * @api + */ + handleEvent(mapBrowserEvent) { + return true; + } + + /** + * Activate or deactivate the interaction. + * @param {boolean} active Active. + * @observable + * @api + */ + setActive(active) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].ACTIVE, active); + } + + /** + * Remove the interaction from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {import("../Map.js").default|null} map Map. + */ + setMap(map) { + this.map_ = map; + } +} + +/** + * @param {import("../View.js").default} view View. + * @param {import("../coordinate.js").Coordinate} delta Delta. + * @param {number} [duration] Duration. + */ +function pan(view, delta, duration) { + const currentCenter = view.getCenterInternal(); + if (currentCenter) { + const center = [currentCenter[0] + delta[0], currentCenter[1] + delta[1]]; + view.animateInternal({ + duration: duration !== undefined ? duration : 250, + easing: _easing_js__WEBPACK_IMPORTED_MODULE_2__.linear, + center: view.getConstrainedCenter(center), + }); + } +} + +/** + * @param {import("../View.js").default} view View. + * @param {number} delta Delta from previous zoom level. + * @param {import("../coordinate.js").Coordinate} [anchor] Anchor coordinate in the user projection. + * @param {number} [duration] Duration. + */ +function zoomByDelta(view, delta, anchor, duration) { + const currentZoom = view.getZoom(); + + if (currentZoom === undefined) { + return; + } + + const newZoom = view.getConstrainedZoom(currentZoom + delta); + const newResolution = view.getResolutionForZoom(newZoom); + + if (view.getAnimating()) { + view.cancelAnimations(); + } + view.animate({ + resolution: newResolution, + anchor: anchor, + duration: duration !== undefined ? duration : 250, + easing: _easing_js__WEBPACK_IMPORTED_MODULE_2__.easeOut, + }); +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (Interaction); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/interaction/Pointer.js": +/*!********************************************************!*\ + !*** ./node_modules/@biigle/ol/interaction/Pointer.js ***! + \********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "centroid": () => (/* binding */ centroid), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Interaction_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Interaction.js */ "./node_modules/@biigle/ol/interaction/Interaction.js"); +/* harmony import */ var _MapBrowserEventType_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../MapBrowserEventType.js */ "./node_modules/@biigle/ol/MapBrowserEventType.js"); +/** + * @module ol/interaction/Pointer + */ + + + +/** + * @typedef {Object} Options + * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleDownEvent] + * Function handling "down" events. If the function returns `true` then a drag + * sequence is started. + * @property {function(import("../MapBrowserEvent.js").default):void} [handleDragEvent] + * Function handling "drag" events. This function is called on "move" events + * during a drag sequence. + * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleEvent] + * Method called by the map to notify the interaction that a browser event was + * dispatched to the map. The function may return `false` to prevent the + * propagation of the event to other interactions in the map's interactions + * chain. + * @property {function(import("../MapBrowserEvent.js").default):void} [handleMoveEvent] + * Function handling "move" events. This function is called on "move" events. + * This functions is also called during a drag sequence, so during a drag + * sequence both the `handleDragEvent` function and this function are called. + * If `handleDownEvent` is defined and it returns true this function will not + * be called during a drag sequence. + * @property {function(import("../MapBrowserEvent.js").default):boolean} [handleUpEvent] + * Function handling "up" events. If the function returns `false` then the + * current drag sequence is stopped. + * @property {function(boolean):boolean} [stopDown] + * Should the down event be propagated to other interactions, or should be + * stopped? + */ + +/** + * @classdesc + * Base class that calls user-defined functions on `down`, `move` and `up` + * events. This class also manages "drag sequences". + * + * When the `handleDownEvent` user function returns `true` a drag sequence is + * started. During a drag sequence the `handleDragEvent` user function is + * called on `move` events. The drag sequence ends when the `handleUpEvent` + * user function is called and returns `false`. + * @api + */ +class PointerInteraction extends _Interaction_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + + super( + /** @type {import("./Interaction.js").InteractionOptions} */ (options), + ); + + if (options.handleDownEvent) { + this.handleDownEvent = options.handleDownEvent; + } + + if (options.handleDragEvent) { + this.handleDragEvent = options.handleDragEvent; + } + + if (options.handleMoveEvent) { + this.handleMoveEvent = options.handleMoveEvent; + } + + if (options.handleUpEvent) { + this.handleUpEvent = options.handleUpEvent; + } + + if (options.stopDown) { + this.stopDown = options.stopDown; + } + + /** + * @type {boolean} + * @protected + */ + this.handlingDownUpSequence = false; + + /** + * @type {Array} + * @protected + */ + this.targetPointers = []; + } + + /** + * Returns the current number of pointers involved in the interaction, + * e.g. `2` when two fingers are used. + * @return {number} The number of pointers. + * @api + */ + getPointerCount() { + return this.targetPointers.length; + } + + /** + * Handle pointer down events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + * @protected + */ + handleDownEvent(mapBrowserEvent) { + return false; + } + + /** + * Handle pointer drag events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @protected + */ + handleDragEvent(mapBrowserEvent) {} + + /** + * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may call into + * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are + * detected. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Map browser event. + * @return {boolean} `false` to stop event propagation. + * @api + */ + handleEvent(mapBrowserEvent) { + if (!mapBrowserEvent.originalEvent) { + return true; + } + + let stopEvent = false; + this.updateTrackedPointers_(mapBrowserEvent); + if (this.handlingDownUpSequence) { + if (mapBrowserEvent.type == _MapBrowserEventType_js__WEBPACK_IMPORTED_MODULE_1__["default"].POINTERDRAG) { + this.handleDragEvent(mapBrowserEvent); + // prevent page scrolling during dragging + mapBrowserEvent.originalEvent.preventDefault(); + } else if (mapBrowserEvent.type == _MapBrowserEventType_js__WEBPACK_IMPORTED_MODULE_1__["default"].POINTERUP) { + const handledUp = this.handleUpEvent(mapBrowserEvent); + this.handlingDownUpSequence = + handledUp && this.targetPointers.length > 0; + } + } else { + if (mapBrowserEvent.type == _MapBrowserEventType_js__WEBPACK_IMPORTED_MODULE_1__["default"].POINTERDOWN) { + const handled = this.handleDownEvent(mapBrowserEvent); + this.handlingDownUpSequence = handled; + stopEvent = this.stopDown(handled); + } else if (mapBrowserEvent.type == _MapBrowserEventType_js__WEBPACK_IMPORTED_MODULE_1__["default"].POINTERMOVE) { + this.handleMoveEvent(mapBrowserEvent); + } + } + return !stopEvent; + } + + /** + * Handle pointer move events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @protected + */ + handleMoveEvent(mapBrowserEvent) {} + + /** + * Handle pointer up events. + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @return {boolean} If the event was consumed. + * @protected + */ + handleUpEvent(mapBrowserEvent) { + return false; + } + + /** + * This function is used to determine if "down" events should be propagated + * to other interactions or should be stopped. + * @param {boolean} handled Was the event handled by the interaction? + * @return {boolean} Should the `down` event be stopped? + */ + stopDown(handled) { + return handled; + } + + /** + * @param {import("../MapBrowserEvent.js").default} mapBrowserEvent Event. + * @private + */ + updateTrackedPointers_(mapBrowserEvent) { + if (mapBrowserEvent.activePointers) { + this.targetPointers = mapBrowserEvent.activePointers; + } + } +} + +/** + * @param {Array} pointerEvents List of events. + * @return {{clientX: number, clientY: number}} Centroid pixel. + */ +function centroid(pointerEvents) { + const length = pointerEvents.length; + let clientX = 0; + let clientY = 0; + for (let i = 0; i < length; i++) { + clientX += pointerEvents[i].clientX; + clientY += pointerEvents[i].clientY; + } + return {clientX: clientX / length, clientY: clientY / length}; +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (PointerInteraction); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/interaction/Property.js": +/*!*********************************************************!*\ + !*** ./node_modules/@biigle/ol/interaction/Property.js ***! + \*********************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * @module ol/interaction/Property + */ + +/** + * @enum {string} + */ +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = ({ + ACTIVE: 'active', +}); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/layer/Base.js": +/*!***********************************************!*\ + !*** ./node_modules/@biigle/ol/layer/Base.js ***! + \***********************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Object_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Object.js */ "./node_modules/@biigle/ol/Object.js"); +/* harmony import */ var _Property_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Property.js */ "./node_modules/@biigle/ol/layer/Property.js"); +/* harmony import */ var _util_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../util.js */ "./node_modules/@biigle/ol/util.js"); +/* harmony import */ var _asserts_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../asserts.js */ "./node_modules/@biigle/ol/asserts.js"); +/* harmony import */ var _math_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../math.js */ "./node_modules/@biigle/ol/math.js"); +/** + * @module ol/layer/Base + */ + + + + + + +/** + * A css color, or a function called with a view resolution returning a css color. + * + * @typedef {string|function(number):string} BackgroundColor + * @api + */ + +/** + * @typedef {import("../ObjectEventType").Types|'change:extent'|'change:maxResolution'|'change:maxZoom'| + * 'change:minResolution'|'change:minZoom'|'change:opacity'|'change:visible'|'change:zIndex'} BaseLayerObjectEventTypes + */ + +/*** + * @template Return + * @typedef {import("../Observable").OnSignature & + * import("../Observable").OnSignature & + * import("../Observable").CombinedOnSignature} BaseLayerOnSignature + */ + +/** + * @typedef {Object} Options + * @property {string} [className='ol-layer'] A CSS class name to set to the layer element. + * @property {number} [opacity=1] Opacity (0, 1). + * @property {boolean} [visible=true] Visibility. + * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering. The layer will not be + * rendered outside of this extent. + * @property {number | undefined} [zIndex] The z-index for layer rendering. At rendering time, the layers + * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed + * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()` + * method was used. + * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be + * visible. + * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will + * be visible. + * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be + * visible. + * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will + * be visible. + * @property {BackgroundColor} [background] Background color for the layer. If not specified, no background + * will be rendered. + * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`. + */ + +/** + * @classdesc + * Abstract base class; normally only used for creating subclasses and not + * instantiated in apps. + * Note that with {@link module:ol/layer/Base~BaseLayer} and all its subclasses, any property set in + * the options is set as a {@link module:ol/Object~BaseObject} property on the layer object, so + * is observable, and has get/set accessors. + * + * @api + */ +class BaseLayer extends _Object_js__WEBPACK_IMPORTED_MODULE_0__["default"] { + /** + * @param {Options} options Layer options. + */ + constructor(options) { + super(); + + /*** + * @type {BaseLayerOnSignature} + */ + this.on; + + /*** + * @type {BaseLayerOnSignature} + */ + this.once; + + /*** + * @type {BaseLayerOnSignature} + */ + this.un; + + /** + * @type {BackgroundColor|false} + * @private + */ + this.background_ = options.background; + + /** + * @type {Object} + */ + const properties = Object.assign({}, options); + if (typeof options.properties === 'object') { + delete properties.properties; + Object.assign(properties, options.properties); + } + + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].OPACITY] = + options.opacity !== undefined ? options.opacity : 1; + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_2__.assert)( + typeof properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].OPACITY] === 'number', + 'Layer opacity must be a number', + ); + + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].VISIBLE] = + options.visible !== undefined ? options.visible : true; + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].Z_INDEX] = options.zIndex; + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MAX_RESOLUTION] = + options.maxResolution !== undefined ? options.maxResolution : Infinity; + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MIN_RESOLUTION] = + options.minResolution !== undefined ? options.minResolution : 0; + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MIN_ZOOM] = + options.minZoom !== undefined ? options.minZoom : -Infinity; + properties[_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MAX_ZOOM] = + options.maxZoom !== undefined ? options.maxZoom : Infinity; + + /** + * @type {string} + * @private + */ + this.className_ = + properties.className !== undefined ? properties.className : 'ol-layer'; + delete properties.className; + + this.setProperties(properties); + + /** + * @type {import("./Layer.js").State} + * @private + */ + this.state_ = null; + } + + /** + * Get the background for this layer. + * @return {BackgroundColor|false} Layer background. + */ + getBackground() { + return this.background_; + } + + /** + * @return {string} CSS class name. + */ + getClassName() { + return this.className_; + } + + /** + * This method is not meant to be called by layers or layer renderers because the state + * is incorrect if the layer is included in a layer group. + * + * @param {boolean} [managed] Layer is managed. + * @return {import("./Layer.js").State} Layer state. + */ + getLayerState(managed) { + /** @type {import("./Layer.js").State} */ + const state = + this.state_ || + /** @type {?} */ ({ + layer: this, + managed: managed === undefined ? true : managed, + }); + const zIndex = this.getZIndex(); + state.opacity = (0,_math_js__WEBPACK_IMPORTED_MODULE_3__.clamp)(Math.round(this.getOpacity() * 100) / 100, 0, 1); + state.visible = this.getVisible(); + state.extent = this.getExtent(); + state.zIndex = zIndex === undefined && !state.managed ? Infinity : zIndex; + state.maxResolution = this.getMaxResolution(); + state.minResolution = Math.max(this.getMinResolution(), 0); + state.minZoom = this.getMinZoom(); + state.maxZoom = this.getMaxZoom(); + this.state_ = state; + + return state; + } + + /** + * @abstract + * @param {Array} [array] Array of layers (to be + * modified in place). + * @return {Array} Array of layers. + */ + getLayersArray(array) { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_4__.abstract)(); + } + + /** + * @abstract + * @param {Array} [states] Optional list of layer + * states (to be modified in place). + * @return {Array} List of layer states. + */ + getLayerStatesArray(states) { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_4__.abstract)(); + } + + /** + * Return the {@link module:ol/extent~Extent extent} of the layer or `undefined` if it + * will be visible regardless of extent. + * @return {import("../extent.js").Extent|undefined} The layer extent. + * @observable + * @api + */ + getExtent() { + return /** @type {import("../extent.js").Extent|undefined} */ ( + this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].EXTENT) + ); + } + + /** + * Return the maximum resolution of the layer. Returns Infinity if + * the layer has no maximum resolution set. + * @return {number} The maximum resolution of the layer. + * @observable + * @api + */ + getMaxResolution() { + return /** @type {number} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MAX_RESOLUTION)); + } + + /** + * Return the minimum resolution of the layer. Returns 0 if + * the layer has no minimum resolution set. + * @return {number} The minimum resolution of the layer. + * @observable + * @api + */ + getMinResolution() { + return /** @type {number} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MIN_RESOLUTION)); + } + + /** + * Return the minimum zoom level of the layer. Returns -Infinity if + * the layer has no minimum zoom set. + * @return {number} The minimum zoom level of the layer. + * @observable + * @api + */ + getMinZoom() { + return /** @type {number} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MIN_ZOOM)); + } + + /** + * Return the maximum zoom level of the layer. Returns Infinity if + * the layer has no maximum zoom set. + * @return {number} The maximum zoom level of the layer. + * @observable + * @api + */ + getMaxZoom() { + return /** @type {number} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MAX_ZOOM)); + } + + /** + * Return the opacity of the layer (between 0 and 1). + * @return {number} The opacity of the layer. + * @observable + * @api + */ + getOpacity() { + return /** @type {number} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].OPACITY)); + } + + /** + * @abstract + * @return {import("../source/Source.js").State} Source state. + */ + getSourceState() { + return (0,_util_js__WEBPACK_IMPORTED_MODULE_4__.abstract)(); + } + + /** + * Return the value of this layer's `visible` property. To find out whether the layer + * is visible on a map, use `isVisible()` instead. + * @return {boolean} The value of the `visible` property of the layer. + * @observable + * @api + */ + getVisible() { + return /** @type {boolean} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].VISIBLE)); + } + + /** + * Return the Z-index of the layer, which is used to order layers before + * rendering. Returns undefined if the layer is unmanaged. + * @return {number|undefined} The Z-index of the layer. + * @observable + * @api + */ + getZIndex() { + return /** @type {number|undefined} */ (this.get(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].Z_INDEX)); + } + + /** + * Sets the background color. + * @param {BackgroundColor} [background] Background color. + */ + setBackground(background) { + this.background_ = background; + this.changed(); + } + + /** + * Set the extent at which the layer is visible. If `undefined`, the layer + * will be visible at all extents. + * @param {import("../extent.js").Extent|undefined} extent The extent of the layer. + * @observable + * @api + */ + setExtent(extent) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].EXTENT, extent); + } + + /** + * Set the maximum resolution at which the layer is visible. + * @param {number} maxResolution The maximum resolution of the layer. + * @observable + * @api + */ + setMaxResolution(maxResolution) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MAX_RESOLUTION, maxResolution); + } + + /** + * Set the minimum resolution at which the layer is visible. + * @param {number} minResolution The minimum resolution of the layer. + * @observable + * @api + */ + setMinResolution(minResolution) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MIN_RESOLUTION, minResolution); + } + + /** + * Set the maximum zoom (exclusive) at which the layer is visible. + * Note that the zoom levels for layer visibility are based on the + * view zoom level, which may be different from a tile source zoom level. + * @param {number} maxZoom The maximum zoom of the layer. + * @observable + * @api + */ + setMaxZoom(maxZoom) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MAX_ZOOM, maxZoom); + } + + /** + * Set the minimum zoom (inclusive) at which the layer is visible. + * Note that the zoom levels for layer visibility are based on the + * view zoom level, which may be different from a tile source zoom level. + * @param {number} minZoom The minimum zoom of the layer. + * @observable + * @api + */ + setMinZoom(minZoom) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].MIN_ZOOM, minZoom); + } + + /** + * Set the opacity of the layer, allowed values range from 0 to 1. + * @param {number} opacity The opacity of the layer. + * @observable + * @api + */ + setOpacity(opacity) { + (0,_asserts_js__WEBPACK_IMPORTED_MODULE_2__.assert)(typeof opacity === 'number', 'Layer opacity must be a number'); + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].OPACITY, opacity); + } + + /** + * Set the visibility of the layer (`true` or `false`). + * @param {boolean} visible The visibility of the layer. + * @observable + * @api + */ + setVisible(visible) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].VISIBLE, visible); + } + + /** + * Set Z-index of the layer, which is used to order layers before rendering. + * The default Z-index is 0. + * @param {number} zindex The z-index of the layer. + * @observable + * @api + */ + setZIndex(zindex) { + this.set(_Property_js__WEBPACK_IMPORTED_MODULE_1__["default"].Z_INDEX, zindex); + } + + /** + * Clean up. + */ + disposeInternal() { + if (this.state_) { + this.state_.layer = null; + this.state_ = null; + } + super.disposeInternal(); + } +} + +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (BaseLayer); + + +/***/ }), + +/***/ "./node_modules/@biigle/ol/layer/BaseVector.js": +/*!*****************************************************!*\ + !*** ./node_modules/@biigle/ol/layer/BaseVector.js ***! + \*****************************************************/ +/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _Layer_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Layer.js */ "./node_modules/@biigle/ol/layer/Layer.js"); +/* harmony import */ var rbush__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! rbush */ "./node_modules/rbush/rbush.min.js"); +/* harmony import */ var _style_Style_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../style/Style.js */ "./node_modules/@biigle/ol/style/Style.js"); +/* harmony import */ var _render_canvas_style_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../render/canvas/style.js */ "./node_modules/@biigle/ol/render/canvas/style.js"); +/** + * @module ol/layer/BaseVector + */ + + + + + +/** + * @template {import("../source/Vector.js").default|import("../source/VectorTile.js").default} VectorSourceType + * @typedef {Object} Options + * @property {string} [className='ol-layer'] A CSS class name to set to the layer element. + * @property {number} [opacity=1] Opacity (0, 1). + * @property {boolean} [visible=true] Visibility. + * @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering. The layer will not be + * rendered outside of this extent. + * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers + * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed + * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()` + * method was used. + * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be + * visible. + * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will + * be visible. + * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be + * visible. + * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will + * be visible. + * @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting + * features before rendering. By default features are drawn in the order that they are created. Use + * `null` to avoid the sort, but get an undefined draw order. + * @property {number} [renderBuffer=100] The buffer in pixels around the viewport extent used by the + * renderer when getting features from the vector source for the rendering or hit-detection. + * Recommended value: the size of the largest symbol, line width or label. + * @property {VectorSourceType} [source] Source. + * @property {import("../Map.js").default} [map] Sets the layer as overlay on a map. The map will not manage + * this layer in its layers collection, and the layer will be rendered on top. This is useful for + * temporary layers. The standard way to add a layer to a map and have it managed by the map is to + * use [map.addLayer()]{@link import("../Map.js").default#addLayer}. + * @property {boolean|string|number} [declutter=false] Declutter images and text. Any truthy value will enable + * decluttering. Within a layer, a feature rendered before another has higher priority. All layers with the + * same `declutter` value will be decluttered together. The priority is determined by the drawing order of the + * layers with the same `declutter` value. Higher in the layer stack means higher priority. To declutter distinct + * layers or groups of layers separately, use different truthy values for `declutter`. + * @property {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. When set to `null`, only + * features that have their own style will be rendered. See {@link module:ol/style/Style~Style} for the default style + * which will be used if this is not set. + * @property {import("./Base.js").BackgroundColor} [background] Background color for the layer. If not specified, no background + * will be rendered. + * @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will + * be recreated during animations. This means that no vectors will be shown clipped, but the + * setting will have a performance impact for large amounts of vector data. When set to `false`, + * batches will be recreated when no animation is active. + * @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will + * be recreated during interactions. See also `updateWhileAnimating`. + * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`. + */ + +/** + * @enum {string} + * @private + */ +const Property = { + RENDER_ORDER: 'renderOrder', +}; + +/** + * @classdesc + * Vector data that is rendered client-side. + * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject} + * property on the layer object; for example, setting `title: 'My Title'` in the + * options means that `title` is observable, and has get/set accessors. + * + * @template {import("../source/Vector.js").default|import("../source/VectorTile.js").default} VectorSourceType + * @template {import("../renderer/canvas/VectorLayer.js").default|import("../renderer/canvas/VectorTileLayer.js").default|import("../renderer/canvas/VectorImageLayer.js").default|import("../renderer/webgl/PointsLayer.js").default} RendererType + * @extends {Layer} + * @api + */ +class BaseVectorLayer extends _Layer_js__WEBPACK_IMPORTED_MODULE_1__["default"] { + /** + * @param {Options} [options] Options. + */ + constructor(options) { + options = options ? options : {}; + + const baseOptions = Object.assign({}, options); + + delete baseOptions.style; + delete baseOptions.renderBuffer; + delete baseOptions.updateWhileAnimating; + delete baseOptions.updateWhileInteracting; + super(baseOptions); + + /** + * @private + * @type {string} + */ + this.declutter_ = options.declutter ? String(options.declutter) : undefined; + + /** + * @type {number} + * @private + */ + this.renderBuffer_ = + options.renderBuffer !== undefined ? options.renderBuffer : 100; + + /** + * User provided style. + * @type {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike} + * @private + */ + this.style_ = null; + + /** + * Style function for use within the library. + * @type {import("../style/Style.js").StyleFunction|undefined} + * @private + */ + this.styleFunction_ = undefined; + + this.setStyle(options.style); + + /** + * @type {boolean} + * @private + */ + this.updateWhileAnimating_ = + options.updateWhileAnimating !== undefined + ? options.updateWhileAnimating + : false; + + /** + * @type {boolean} + * @private + */ + this.updateWhileInteracting_ = + options.updateWhileInteracting !== undefined + ? options.updateWhileInteracting + : false; + } + + /** + * @return {string} Declutter group. + */ + getDeclutter() { + return this.declutter_; + } + + /** + * Get the topmost feature that intersects the given pixel on the viewport. Returns a promise + * that resolves with an array of features. The array will either contain the topmost feature + * when a hit was detected, or it will be empty. + * + * The hit detection algorithm used for this method is optimized for performance, but is less + * accurate than the one used in [map.getFeaturesAtPixel()]{@link import("../Map.js").default#getFeaturesAtPixel}. + * Text is not considered, and icons are only represented by their bounding box instead of the exact + * image. + * + * @param {import("../pixel.js").Pixel} pixel Pixel. + * @return {Promise>} Promise that resolves with an array of features. + * @api + */ + getFeatures(pixel) { + return super.getFeatures(pixel); + } + + /** + * @return {number|undefined} Render buffer. + */ + getRenderBuffer() { + return this.renderBuffer_; + } + + /** + * @return {function(import("../Feature.js").default, import("../Feature.js").default): number|null|undefined} Render + * order. + */ + getRenderOrder() { + return /** @type {import("../render.js").OrderFunction|null|undefined} */ ( + this.get(Property.RENDER_ORDER) + ); + } + + /** + * Get the style for features. This returns whatever was passed to the `style` + * option at construction or to the `setStyle` method. + * @return {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null|undefined} Layer style. + * @api + */ + getStyle() { + return this.style_; + } + + /** + * Get the style function. + * @return {import("../style/Style.js").StyleFunction|undefined} Layer style function. + * @api + */ + getStyleFunction() { + return this.styleFunction_; + } + + /** + * @return {boolean} Whether the rendered layer should be updated while + * animating. + */ + getUpdateWhileAnimating() { + return this.updateWhileAnimating_; + } + + /** + * @return {boolean} Whether the rendered layer should be updated while + * interacting. + */ + getUpdateWhileInteracting() { + return this.updateWhileInteracting_; + } + + /** + * Render declutter items for this layer + * @param {import("../Map.js").FrameState} frameState Frame state. + * @param {import("../layer/Layer.js").State} layerState Layer state. + */ + renderDeclutter(frameState, layerState) { + const declutterGroup = this.getDeclutter(); + if (declutterGroup in frameState.declutter === false) { + frameState.declutter[declutterGroup] = new rbush__WEBPACK_IMPORTED_MODULE_0__(9); + } + this.getRenderer().renderDeclutter(frameState, layerState); + } + + /** + * @param {import("../render.js").OrderFunction|null|undefined} renderOrder + * Render order. + */ + setRenderOrder(renderOrder) { + this.set(Property.RENDER_ORDER, renderOrder); + } + + /** + * Set the style for features. This can be a single style object, an array + * of styles, or a function that takes a feature and resolution and returns + * an array of styles. If set to `null`, the layer has no style (a `null` style), + * so only features that have their own styles will be rendered in the layer. Call + * `setStyle()` without arguments to reset to the default style. See + * [the ol/style/Style module]{@link module:ol/style/Style~Style} for information on the default style. + * + * If your layer has a static style, you can use [flat style]{@link module:ol/style/flat~FlatStyle} object + * literals instead of using the `Style` and symbolizer constructors (`Fill`, `Stroke`, etc.): + * ```js + * vectorLayer.setStyle({ + * "fill-color": "yellow", + * "stroke-color": "black", + * "stroke-width": 4 + * }) + * ``` + * + * @param {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. + * @api + */ + setStyle(style) { + this.style_ = style === undefined ? _style_Style_js__WEBPACK_IMPORTED_MODULE_2__.createDefaultStyle : style; + const styleLike = toStyleLike(style); + this.styleFunction_ = + style === null ? undefined : (0,_style_Style_js__WEBPACK_IMPORTED_MODULE_2__.toFunction)(styleLike); + this.changed(); + } +} + +/** + * Coerce the allowed style types into a shorter list of types. Flat styles, arrays of flat + * styles, and arrays of rules are converted into style functions. + * + * @param {import("../style/Style.js").StyleLike|import("../style/flat.js").FlatStyleLike|null} [style] Layer style. + * @return {import("../style/Style.js").StyleLike|null} The style. + */ +function toStyleLike(style) { + if (style === undefined) { + return _style_Style_js__WEBPACK_IMPORTED_MODULE_2__.createDefaultStyle; + } + if (!style) { + return null; + } + if (typeof style === 'function') { + return style; + } + if (style instanceof _style_Style_js__WEBPACK_IMPORTED_MODULE_2__["default"]) { + return style; + } + if (!Array.isArray(style)) { + return (0,_render_canvas_style_js__WEBPACK_IMPORTED_MODULE_3__.flatStylesToStyleFunction)([style]); + } + if (style.length === 0) { + return []; + } + + const length = style.length; + const first = style[0]; + + if (first instanceof _style_Style_js__WEBPACK_IMPORTED_MODULE_2__["default"]) { + /** + * @type {Array