/*! @alxcube/lens 2.0.1 © 2020-2023 Alexander Alexandrov License: Apache-2.0 */ (function(n,C){typeof exports=="object"&&typeof module<"u"?C(exports):typeof define=="function"&&define.amd?define(["exports"],C):C((n=typeof globalThis<"u"?globalThis:n||self).lens={})})(this,function(n){"use strict";class C{constructor(e){if(this.neighborsCount=e,![2,3,4].includes(this.neighborsCount))throw new RangeError(`Neighbors count must be 2, 3 or 4. ${this.neighborsCount} given`)}interpolate(e,t,i){let s,o;const a=this.neighborsCount;switch(a){case 2:s=Math.floor(t),o=Math.floor(i);break;case 3:s=Math.floor(t+.5)-1,o=Math.floor(i+.5)-1;break;case 4:s=Math.floor(t)-1,o=Math.floor(i)-1}const h=s+a,c=o+a,l=[0,0,0,0];for(let f=o;f(r[r.AVERAGE=1]="AVERAGE",r[r.AVERAGE_9=2]="AVERAGE_9",r[r.AVERAGE_16=3]="AVERAGE_16",r[r.BACKGROUND=4]="BACKGROUND",r[r.INTEGER=8]="INTEGER",r))(w||{});class ye{create(e){switch(e){case w.AVERAGE:return new C(2);case w.AVERAGE_9:return new C(3);case w.AVERAGE_16:return new C(4);case w.BACKGROUND:return new xe;case w.INTEGER:return new ve}throw new TypeError(`Unknown interpolation method: ${e}`)}}class Re{constructor(e,t){this.colorResamplerFactoriesPool=e,this.resampleFilterResolver=t}resolve(e,t,i={}){const{preferredResampler:s,filter:o,matteColor:a,interpolationMethod:h,virtualPixelMethod:c}=i,l=this.getColorResamplerFactory(s,o);let g;return o&&l.supportsEwa&&(g=this.resampleFilterResolver.resolve(o,i)),l.create(e,t,{resampleFilter:g,matteColor:a,interpolationMethod:h,virtualPixelMethod:c})}getColorResamplerFactory(e,t){let i;if(e!==void 0){const o=this.colorResamplerFactoriesPool.get(e);if(o.requiresResampleFilter&&!t)throw new TypeError(`Preferred color resampler "${e}" requires ResampleFilter`);return o}if(t!==void 0&&(i=this.colorResamplerFactoriesPool.items().find(o=>o.supportsEwa),i))return i;const s=this.colorResamplerFactoriesPool.items().filter(o=>!o.requiresResampleFilter);if(!s.length)throw new Error("No color resampler factories in pool.");return s[0]}}function Ce(r){return typeof r=="object"&&r!==null&&typeof r.getResampledColor=="function"&&typeof r.setScaling=="function"&&typeof r.getScaling=="function"}class x{constructor(e){this.decorated=e,this.width=this.decorated.width,this.height=this.decorated.height,{x1:this.offsetX,y1:this.offsetY}=this.decorated.getViewport()}getPixelColor(e,t){return e=Math.floor(e-this.offsetX),t=Math.floor(t-this.offsetY),e>=0&&e=0&&t=0&&e=0&&t=this.height)return this.decorated.getPixelColor(Math.max(0,Math.min(this.width-1,e)),Math.max(0,Math.min(this.height-1,t)));const i=e%this.width,s=t%this.height;return this.decorated.getPixelColor(i<0?this.width+i:i,s<0?this.height+s:s)}}class Ee extends x{getVirtualPixelColor(e,t){if(t<0||t>=this.height)return this.decorated.getBackgroundColor();const i=e%this.width,s=t%this.height;return this.decorated.getPixelColor(i<0?this.width+i:i,s<0?this.height+s:s)}}class Fe extends x{getVirtualPixelColor(e,t){const i=2*this.width,s=2*this.height,o=e%i,a=t%s;let h=o<0?i+o:o,c=a<0?s+a:a;return h>this.width-1&&(h=this.width-(h-this.width)-1),c>this.height-1&&(c=this.height-(c-this.height)-1),this.decorated.getPixelColor(h,c)}}class Ve extends x{getVirtualPixelColor(){return this.decorated.getPixelColor(Math.floor(Math.random()*this.width),Math.floor(Math.random()*this.height))}}class Ie extends x{getVirtualPixelColor(e,t){const i=e%this.width,s=t%this.height;return this.decorated.getPixelColor(i<0?this.width+i:i,s<0?this.height+s:s)}}class Te extends x{getVirtualPixelColor(e,t){if(e<0||e>=this.width)return this.decorated.getPixelColor(Math.max(0,Math.min(this.width-1,e)),Math.max(0,Math.min(this.height-1,t)));const i=e%this.width,s=t%this.height;return this.decorated.getPixelColor(i<0?this.width+i:i,s<0?this.height+s:s)}}class be extends x{getVirtualPixelColor(e,t){if(e<0||e>=this.width)return this.decorated.getBackgroundColor();const i=e%this.width,s=t%this.height;return this.decorated.getPixelColor(i<0?this.width+i:i,s<0?this.height+s:s)}}var d=(r=>(r[r.BACKGROUND=1]="BACKGROUND",r[r.EDGE=3]="EDGE",r[r.MIRROR=4]="MIRROR",r[r.RANDOM=5]="RANDOM",r[r.TILE=6]="TILE",r[r.TRANSPARENT=7]="TRANSPARENT",r[r.BLACK=9]="BLACK",r[r.GRAY=10]="GRAY",r[r.WHITE=11]="WHITE",r[r.HORIZONTAL_TILE=12]="HORIZONTAL_TILE",r[r.VERTICAL_TILE=13]="VERTICAL_TILE",r[r.HORIZONTAL_TILE_EDGE=14]="HORIZONTAL_TILE_EDGE",r[r.VERTICAL_TILE_EDGE=15]="VERTICAL_TILE_EDGE",r))(d||{});class Be{decorate(e,t){switch(t){case d.BACKGROUND:return new Pe(e);case d.EDGE:return new Ae(e);case d.MIRROR:return new Fe(e);case d.RANDOM:return new Ve(e);case d.TILE:return new Ie(e);case d.TRANSPARENT:return new H(e,[0,0,0,0]);case d.BLACK:return new H(e,[0,0,0,e.getQuantumRange()]);case d.GRAY:return new H(e,[Math.floor(e.getQuantumRange()/2),Math.floor(e.getQuantumRange()/2),Math.floor(e.getQuantumRange()/2),e.getQuantumRange()]);case d.WHITE:return new H(e,[e.getQuantumRange(),e.getQuantumRange(),e.getQuantumRange(),e.getQuantumRange()]);case d.HORIZONTAL_TILE:return new Ee(e);case d.VERTICAL_TILE:return new be(e);case d.HORIZONTAL_TILE_EDGE:return new Me(e);case d.VERTICAL_TILE_EDGE:return new Te(e);default:throw new TypeError(`Unknown Virtual Pixel Method "${t}" given.`)}}}function Le(r){return typeof r=="object"&&r!==null&&typeof r.getAverageColor=="function"}function Se(r){return typeof r=="object"&&r!==null&&typeof r.getBackgroundColor=="function"}function Oe(r){return typeof r=="object"&&r!==null&&typeof r.getPixelColor=="function"&&typeof r.setPixelColor=="function"&&typeof r.getQuantumRange=="function"}function De(r){return typeof Oe(r)&&typeof r.width=="number"&&typeof r.height=="number"}class y{constructor(e,t,i,s){this.x1=e,this.y1=t,this.x2=i,this.y2=s}static fromLiteral(e){let t,i,s,o;return"width"in e&&"height"in e?(t=e.x||0,i=e.y||0,s=t+e.width-1,o=i+e.height-1):(t=e.x1,i=e.y1,s=e.x2,o=e.y2),new y(t,i,s,o)}getWidth(){return this.x2-this.x1+1}getHeight(){return this.y2-this.y1+1}getArea(){return this.getWidth()*this.getHeight()}expand(e,t){return this.x1=Math.min(this.x1,e),this.x2=Math.max(this.x2,e),this.y1=Math.min(this.y1,t),this.y2=Math.max(this.y2,t),this}clone(){return new y(this.x1,this.y1,this.x2,this.y2)}fixBounds(){return this.x1=Math.floor(this.x1-.5),this.y1=Math.floor(this.y1-.5),this.x2=Math.ceil(this.x2-.5),this.y2=Math.ceil(this.y2-.5),this}scale(e){const t=this.getWidth()*e,i=this.getHeight()*e;return this.x1=this.x1*e,this.y1=this.y1*e,this.x2=this.x1+t-1,this.y2=this.y1+i-1,this}reset(){const e=this.getWidth(),t=this.getHeight();return this.x1=0,this.y1=0,this.x2=this.x1+e-1,this.y2=this.y1+t-1,this}offset(e,t){return this.x1+=e,this.y1+=t,this.x2+=e,this.y2+=t,this}}function _(r){if(typeof r!="object"||r===null)return!1;const e=r;return"x1"in e&&typeof e.x1=="number"&&"y1"in e&&typeof e.y1=="number"&&"x2"in e&&typeof e.x2=="number"&&"y2"in e&&typeof e.y2=="number"||"width"in e&&typeof e.width=="number"&&"height"in e&&typeof e.height=="number"&&(!("x"in e)||typeof e.x=="number")&&(!("y"in e)||typeof e.y=="number")}function ke(r){return De(r)&&typeof r.getViewport=="function"}function Ne(r){return Ce(r)&&typeof r.getWeightLookupTable=="function"}const P=Number.EPSILON===void 0?Math.pow(2,-52):Number.EPSILON,Ge=Number.MAX_VALUE,b=Math.PI/2,B=2*Math.PI;function se(r,e,t=.5){const i=1-t,s=[0,0,0,0];for(let o=0;o<4;o++)s[o]=Math.round(r[o]*t+e[o]*i);return s}function We(){const r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}function oe(r){return Math.PI*r/180}function Q(r){const e=r<0?-1:1;return e*r>=P?1/r:e/P}function He(r,e){(function(l,g){const f=l.length;l.forEach(u=>{if(u.length!==f)throw new TypeError("Matrix must be square")}),g.forEach(u=>{if(u.length!==f)throw new TypeError("Augment matrix vector length must be same as matrix rank")})})(r,e),r=_e(r),e=_e(e);const t=r.length,i=e.length,s=new Array(t).fill(0),o=new Array(t).fill(0),a=new Array(t).fill(0);let h=0,c=0;for(let l=0;l1&&qe():Math.abs(r[u][p])>=g&&(g=Math.abs(r[u][p]),c=u,h=p);if(a[h]++,c!==h){for(let u=0;u=0;l--)if(s[l]!==o[l])for(let g=0;ge.slice())}function qe(){throw new TypeError("Can't solve given matrix using Gauss-Jordan method")}class Y{constructor(e,t=1){this.coefficients=[],this.results=[];for(let i=0;i{const s=()=>{e.onload=null,e.onerror=null};e.onload=()=>{s(),t(e)},e.onerror=()=>{s(),i(new Error(`Couldn't load image "${r}"`))},e.src=r})}class q extends Error{constructor(e){super(e),this.name="LensException",typeof Error.captureStackTrace=="function"?Error.captureStackTrace(this,this.constructor):this.stack=new Error(e).stack}}class Xe extends q{constructor(e){super(e),this.name="AbortException"}}class F extends q{constructor(e){super(e),this.name="InvalidArgument"}}class $ extends q{constructor(e){super(e),this.name="InvalidArgumentsLength"}}function je(r,e,t){return[t[0]*r+t[1]*e+t[2],t[3]*r+t[4]*e+t[5]]}function ne(r){const e=Q(r[0]*r[4]-r[1]*r[3]);if(!e)throw new F("Given matrix can't be inverted");return[e*r[4],e*-r[1],e*(r[1]*r[5]-r[2]*r[4]),e*-r[3],e*r[0],e*(r[2]*r[3]-r[0]*r[5])]}class S{constructor(e){this.matrix=e,this.isConstantPartialDerivatives=!0,this.forwardMatrix=ne(e)}static fromForwardMatrix(e){return new S(ne(e))}reverseMap(e,t){return[this.matrix[0]*e+this.matrix[1]*t+this.matrix[2],this.matrix[3]*e+this.matrix[4]*t+this.matrix[5]]}getValidity(){return 1}getPartialDerivatives(){return[this.matrix[0],this.matrix[1],this.matrix[3],this.matrix[4]]}forwardMap(e,t){return je(e,t,this.forwardMatrix)}getBestFitViewport(e){const t=e.x1,i=e.y1,s=e.x2+1,o=e.y2+1,[a,h]=this.forwardMap(t,i),c=new y(a,h,a,h);return[[s,i],[s,o],[t,o]].forEach(l=>c.expand(...this.forwardMap(...l))),c.fixBounds(),c}}class Qe{create(e){if(!e.length||e.length%4!=0)throw new $(`Number of arguments must be multiple of 4 and at least 4 arguments (1 control point) expected.${e.length} arguments given.`);if(e.length===4)return new S([1,0,e[0]-e[2],0,1,e[1]-e[3]]);{const t=new Y(3,2);for(let s=0;sP?[this.angleToWidth/(B*i),0,0,this.radiusToHeight]:[this.viewportWidthX2,0,0,this.radiusToHeight]}getBestFitViewport(e){let t=this.c0-this.c1/2,i=Math.cos(t),s=Math.sin(t),o=this.c2*i,a=this.c2*s;const h=new y(o,a,o,a);for(o=(this.c2-this.c3)*i,a=(this.c2-this.c3)*s,h.expand(o,a),t=this.c0+this.c1/2,i=Math.cos(t),s=Math.sin(t),o=this.c2*i,a=this.c2*s,h.expand(o,a),o=(this.c2-this.c3)*i,a=(this.c2-this.c3)*s,h.expand(o,a),t=Math.ceil((this.c0-this.c1/2)/b)*b;t=1&&e[0]=3&&e[2]!==void 0&&e[2]=1?oe(e[0]):b,e.length>=2&&e[1]!==void 0&&(i+=oe(e[1])),i/=B,i-=Math.round(i),i*=B,a=t.getHeight()-1,o=t.getWidth()/s+a/2,e.length>=3&&e[2]!==void 0&&e[3]!==void 0&&(e.length>=4?a=e[2]-e[3]:a*=e[2]/o,o=e[2]);const h=(t.getWidth()-1)/2;return new $e(t,i,s,o,a,h)}}function he(r){const e=Q(r[0]*r[4]-r[3]*r[1]);if(!e)throw new F("Given matrix can't be inverted");return[e*(r[4]-r[7]*r[5]),e*(r[7]*r[2]-r[1]),e*(r[1]*r[5]-r[4]*r[2]),e*(r[6]*r[5]-r[3]),e*(r[0]-r[6]*r[2]),e*(r[3]*r[2]-r[0]*r[5]),e*(r[3]*r[7]-r[6]*r[4]),e*(r[6]*r[1]-r[0]*r[7])]}function Ze(r,e,t){const i=t[0]*r+t[1]*e+t[2],s=t[3]*r+t[4]*e+t[5],o=t[6]*r+t[7]*e+1;return[i/o,s/o]}class U{constructor(e,t){this.isConstantPartialDerivatives=!1,this.matrix=e,this.denominator=t,this.forwardMatrix=he(e),this.absC6=Math.abs(e[6]),this.absC7=Math.abs(e[7])}static fromForwardMatrix(e){const t=he(e),i=t[6]*e[2]+t[7]*e[5]+1<0?-1:1;return new U(t,i)}reverseMap(e,t){const i=this.matrix[0]*e+this.matrix[1]*t+this.matrix[2],s=this.matrix[3]*e+this.matrix[4]*t+this.matrix[5],o=this.matrix[6]*e+this.matrix[7]*t+1;return[i/o,s/o]}getValidity(e,t,i){const s=this.matrix[6]*e+this.matrix[7]*t+1;let o=s*this.denominator<0?0:1;const a=2*Math.abs(s);return this.absC6>this.absC7?ac.expand(...this.forwardMap(...l))),c.fixBounds(),c}}class ze{create(e){if(e.length<16||e.length%4!=0)throw new $(`Number of arguments must be multiple of 4 and at least 16 arguments (4 control points) expected. ${e.length} arguments given.`);const t=new Y(8,1);for(let o=0;o5||s!=Math.floor(s)&&s-1.5>P)throw new F(`Invalid polynomial order: ${s}`);return Math.floor((s+1)*(s+2)/2)}(e[0]);if(e.length<1+4*t)throw new $(`Polynomial distortion of order ${e[0]} requires at least ${t} control point pairs (1 + ${4*t} arguments)`);const i=new Y(t,2);for(let s=1;s(r.AFFINE="Affine",r.AFFINE_PROJECTION="AffineProjection",r.PERSPECTIVE="Perspective",r.PERSPECTIVE_PROJECTION="PerspectiveProjection",r.ARC="Arc",r.POLYNOMIAL="Polynomial",r))(A||{});function ot(r){return K(r)&&typeof r.getPartialDerivatives=="function"&&typeof r.isConstantPartialDerivatives=="boolean"}function Z(r,e){return Math.max(0,Math.min(e,r))}class at{constructor(e,t,i,s,o,a,h=[0,0,0,0],c){if(!ot(t))throw new F("Pixel Mapper must implement ReversePixelMapperWithEwaSupport in order to use Elliptical Weighted Average re-sampling.");this.supportSq=s*s,this.matteColor=h,this.weightLookupTable=i,this.weightLookupTableSize=i.length,this.image=e,this.pixelMapper=t,this.imageViewport=this.image.getViewport(),this.imageArea=this.imageViewport.getArea(),this.imageVirtualPixelMethod=c,this.imageAverageColor=null,this.A=0,this.B=0,this.C=0,this.F=0,this.uLimit=0,this.vLimit=0,this.uWidth=0,this.slope=0,this.ellipseIsSetUp=!1,this.limitReached=!1,this.scaling=1,this.quantumRange=e.getQuantumRange(),this.averageInterpolator=o,this.defaultInterpolator=a}getWeightLookupTable(){return this.weightLookupTable}getScaling(){return this.scaling}setScaling(e){return this.scaling=e,this}getResampledColor(e,t){e=(e+.5)*this.scaling,t=(t+.5)*this.scaling;const i=this.pixelMapper.getValidity(e,t,this.scaling);if(i>0){const[s,o]=this.pixelMapper.reverseMap(e,t);if(!this.pixelMapper.isConstantPartialDerivatives||!this.ellipseIsSetUp){const h=this.pixelMapper.getPartialDerivatives(e,t);this.setupEllipse(h[0],h[1],h[2],h[3]),this.ellipseIsSetUp=!0}const a=this.getWeightedAverage(s-.5,o-.5);return i<1?se(a,this.matteColor,i):a}return this.matteColor}setupEllipse(e,t,i,s){this.limitReached=!1;const o=this.scaling;return this.initEllipse(e*o,t*o,i*o,s*o).scaleEllipse()}initEllipse(e,t,i,s){const[o,a,h,c,l,g]=function(f,u,p,m){const R=f*f+u*u,J=f*p+u*m,de=J,V=p*p+m*m,k=f*m-u*p,ee=k+k,E=R+V,I=(E+ee)*(E-ee),N=Math.sqrt(I>0?I:0),T=.5*(E+N),G=.5*(E-N),v=T-R,j=T-V,te=v*v,re=j*j,W=te>=re?J:j,fe=te>=re?v:de,ie=Math.sqrt(W*W+fe*fe),kt=ie>0?W/ie:1,Nt=ie>0?fe/ie:0,me=T<=1?1:Math.sqrt(T),we=G<=1?1:Math.sqrt(G);return[kt*me,Nt*me,-Nt*we,kt*we,me,we]}(e,t,i,s);return this.A=a*a+c*c,this.B=-2*(o*a+h*c),this.C=o*o+h*h,this.F=l*g,this.F*=this.F,this.limitReached=4*this.A*this.C-this.B*this.B>Ge,this}scaleEllipse(){if(!this.limitReached){if(this.F*=this.supportSq,this.uLimit=Math.sqrt(this.C*this.F/(this.A*this.C-.25*this.B*this.B)),this.vLimit=Math.sqrt(this.A*this.F/(this.A*this.C-.25*this.B*this.B)),this.uWidth=Math.sqrt(this.F/this.A),this.slope=-this.B/(2*this.A),this.uWidth*this.vLimit>4*this.imageArea)return this.limitReached=!0,this;const e=this.weightLookupTableSize/this.F;this.A*=e,this.B*=e,this.C*=e}return this}getWeightedAverage(e,t){if(this.doesntNeedResampling(e,t))return this.image.getPixelColor(e,t);if(this.limitReached)switch(this.imageVirtualPixelMethod){case d.EDGE:case d.HORIZONTAL_TILE_EDGE:case d.VERTICAL_TILE_EDGE:return this.averageInterpolator.interpolate(this.image,e,t);case d.HORIZONTAL_TILE:case d.VERTICAL_TILE:return this.image.getPixelColor(this.imageViewport.x1-1,this.imageViewport.y1-1);default:return this.getImageAverageColor()}let i=0,s=0,o=0,a=0,h=0,c=0;const l=Math.ceil(t-this.vLimit),g=Math.floor(t+this.vLimit);let f=e+(l-t)*this.slope-this.uWidth;const u=2*this.uWidth+1,p=this.A,m=this.B,R=this.image,J=this.weightLookupTable,de=2*p;for(let V=l;Vthis.imageViewport.y2||e-this.uLimit>this.imageViewport.x2&&t+this.vLimitthis.imageViewport.x2&&t-this.vLimit>this.imageViewport.y2;case d.HORIZONTAL_TILE:return t+this.vLimitthis.imageViewport.y2;case d.VERTICAL_TILE:return e+this.uLimitthis.imageViewport.x2;default:return!1}}getImageAverageColor(){return this.imageAverageColor===null&&(this.imageAverageColor=this.image.getAverageColor()),this.imageAverageColor}outOfImageBounds(e,t){return e+this.uLimitthis.imageViewport.x2||t+this.vLimitthis.imageViewport.y2}}class nt{constructor(e){this.colorInterpolatorFactory=e,this.supportsEwa=!0,this.requiresResampleFilter=!0}create(e,t,i={}){const{resampleFilter:s,matteColor:o=[0,0,0,0],interpolationMethod:a=w.AVERAGE,virtualPixelMethod:h=d.TRANSPARENT}=i;if(!s)throw new TypeError("EWA resampler requires ResampleFilter.");const c=function(u){const p=[],m=u.getWorkingSupport()*Math.sqrt(1/ht);for(let R=0;R0){const[s,o]=this.pixelMapper.reverseMap(e,t),a=this.interpolator.interpolate(this.image,s-.5,o-.5);return i<1?se(a,this.matteColor,i):a}return this.matteColor}}class ct{constructor(e){this.colorInterpolatorFactory=e,this.supportsEwa=!1,this.requiresResampleFilter=!1}create(e,t,i={}){const{matteColor:s=[0,0,0,0],interpolationMethod:o=w.AVERAGE}=i;return new lt(e,t,this.colorInterpolatorFactory.create(o),s)}}class ut{constructor(e){this.parsersPool=e}parse(e,t=255){for(const i of this.parsersPool.items()){const s=i.parse(e,t);if(s)return s}}}class gt{parse(e,t=255){/^#[a-f\d]{3}$/i.test(e)&&(e="#"+e.slice(1).split("").map(s=>s.repeat(2)).join(""));const i=e.match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i);if(i)return[Math.round(parseInt(i[1],16)/255*t),Math.round(parseInt(i[2],16)/255*t),Math.round(parseInt(i[3],16)/255*t),i[4]?Math.round(parseInt(i[4],16)/255*t):t]}}function ce(r){return!!Array.isArray(r)&&r.length===4&&r.every(e=>typeof e=="number")}function ue(r){return Array.isArray(r)&&r.length===2&&typeof r[0]=="number"&&typeof r[1]=="number"}class pt{parse(e,t=255){if(!/^\s*rgba?/.test(e))return;const i=e.replace(/\s/g,"").match(/(\d+(\.\d+)?%?)|(\.\d+%?)/g);if(!i||i.length<3)return;i.length===3&&i.push("1");const s=i.map((o,a)=>{const h=parseFloat(o);return a===3?Math.round(h*t):o.indexOf("%")!==-1?Math.round(h/100*t):Math.round(h/255*t)}).filter(o=>!isNaN(o));return ce(s)?s:void 0}}class dt{parse(e){if(e==="transparent")return[0,0,0,0]}}class ft{constructor(e,t){this.asyncTimeout=e,this.abortSignal=t}async process(e,t){const i=this.createProcessScope(e,t);return this.doProcess(i,this.asyncTimeout),await i.deferred.promise,e.commit(),e}createProcessScope(e,t){const i=e.getViewport(),s=Math.floor(i.x1),o=Math.floor(i.x2),a=Math.floor(i.y2),h=s,c=Math.floor(i.y1);return{deferred:We(),image:e,resampler:t,startX:s,endX:o,endY:a,currentX:h,currentY:c}}doProcess(e,t){if(this.abortSignal&&this.abortSignal.aborted)return void e.deferred.reject(this.abortSignal.reason instanceof Error?this.abortSignal.reason:new Xe(String(this.abortSignal.reason)));const i=Date.now(),{image:s,resampler:o,startX:a,endX:h,endY:c}=e;let{currentX:l,currentY:g}=e;for(;g<=c;){for(;l<=h;)if(s.setPixelColor(l,g,o.getResampledColor(l,g)),l++,Date.now()-i>=t)return e.currentX=l,e.currentY=g,void setTimeout(this.doProcess.bind(this,e,t),0);g++,l=a}e.deferred.resolve()}}class mt{constructor(e,t){this.processor=e,this.superSamplingFactor=t}async process(e,t){this.superSamplingFactor!==1&&t.setScaling(1/this.superSamplingFactor);const i=await this.processor.process(e,t);return this.superSamplingFactor!==1?i.scale(1/this.superSamplingFactor):i}}class wt{constructor(e,t){this.width=e,this.height=t,this.viewport=new y(0,0,this.width-1,this.height-1),this.backgroundColor=[0,0,0,0],this.quantumRange=255}getViewport(){return this.viewport}setViewport(e){return this.viewport=e,this}getBackgroundColor(){return this.backgroundColor}setBackgroundColor(e){return this.backgroundColor=e,this}getQuantumRange(){return this.quantumRange}getBlank(e){const t=this.prepareBlank(e.getWidth(),e.getHeight());return t.setViewport(e),this.duplicateProps(t)}scale(e){const t=this.viewport.clone();t.scale(e);const i=this.resize(t.getWidth(),t.getHeight());return i.setViewport(t),this.duplicateProps(i)}duplicateProps(e){return e.setBackgroundColor(this.backgroundColor),e}}class xt{constructor(e){this.factoriesPool=e}resolve(e){const t=this.factoriesPool.items().find(s=>s.match(e));if(t)return t.create(e);const i=Object.prototype.toString.call(e).slice(8,-1);throw new TypeError(`No matching image adapter factory for resource of type ${i}`)}}function X(r){const e=r.getContext("2d",{willReadFrequently:!0});if(!e)throw new Error("Couldn't get canvas context");return e}class O extends wt{constructor(e){super(e.width,e.height),this.canvas=e,this.imageData=X(e).getImageData(0,0,e.width,e.height),this.data=this.imageData.data}static createFromImage(e){const t=L(e.width,e.height);return X(t).drawImage(e,0,0),new O(t)}static async createFromUrl(e){const t=await Ue(e);return this.createFromImage(t)}static async createFromBlob(e){const t=await createImageBitmap(e);return this.createFromImage(t)}getPixelColor(e,t){const i=4*(t*this.width+e);return[this.data[i],this.data[i+1],this.data[i+2],this.data[i+3]]}setPixelColor(e,t,i){const s=4*(t*this.width+e);this.data[s]=i[0],this.data[s+1]=i[1],this.data[s+2]=i[2],this.data[s+3]=i[3]}getAverageColor(){const e=X(L(1,1));return e.drawImage(this.canvas,0,0,this.width,this.height,0,0,1,1),Array.prototype.slice.call(e.getImageData(0,0,1,1).data)}resize(e,t){const i=L(e,t,!this.isOffscreen());return X(i).drawImage(this.canvas,0,0,this.width,this.height,0,0,e,t),new O(i)}getResource(){return this.canvas}prepareBlank(e,t){return new O(L(e,t,!this.isOffscreen()))}commit(){X(this.canvas).putImageData(this.imageData,0,0)}isOffscreen(){return typeof OffscreenCanvas!==void 0&&this.canvas instanceof OffscreenCanvas}}class vt{match(e){return typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas}create(e){return new O(e)}}function yt(r){return ke(r)&&Le(r)&&Se(r)&&typeof r.setViewport=="function"&&typeof r.setBackgroundColor=="function"&&typeof r.getBlank=="function"&&typeof r.scale=="function"&&typeof r.getResource=="function"&&typeof r.commit=="function"}class D{constructor(e){this.adapter=e,{x1:this.offsetX,y1:this.offsetY}=e.getViewport(),{width:this.width,height:this.height}=e}getAdapter(){return this.adapter}getPixelColor(e,t){return this.adapter.getPixelColor(Math.floor(e-this.offsetX),Math.floor(t-this.offsetY))}setPixelColor(e,t,i){this.adapter.setPixelColor(Math.floor(e-this.offsetX),Math.floor(t-this.offsetY),i)}getViewport(){return this.adapter.getViewport()}setViewport(e){this.adapter.setViewport(e),{x1:this.offsetX,y1:this.offsetY}=e}getBackgroundColor(){return this.adapter.getBackgroundColor()}setBackgroundColor(e){this.adapter.setBackgroundColor(e)}getAverageColor(){return this.adapter.getAverageColor()}getQuantumRange(){return this.adapter.getQuantumRange()}getBlank(e){const t=this.adapter.getBlank(e);return new D(t)}scale(e){const t=this.adapter.scale(e);return new D(t)}getResource(){return this.adapter.getResource()}commit(){return this.adapter.commit()}}class Rt{constructor(e,t){this.processor=e,this.repage=t}async process(e,t){const i=await this.processor.process(e,t);return i.getViewport().reset(),ue(this.repage)?i.getViewport().offset(...this.repage):_(this.repage)&&i.setViewport(y.fromLiteral(this.repage)),i}}class Ct{create(e={}){const{asyncTimeout:t=50,outputScaling:i=1,repage:s=!1,abortSignal:o}=e;let a=new ft(t,o);return i!==1&&(a=new mt(a,i)),s&&(a=new Rt(a,ue(s)||_(s)?s:void 0)),a}}class Pt{constructor(e,t){this.outputViewportResolver=e,this.distortionProcessorFactory=t}async distort(e,t,i,s={}){const{viewport:o=!1,outputScaling:a=1,repage:h,asyncTimeout:c=50,abortSignal:l}=s,g=this.createTargetImage(e,t,o,a),f=new D(g),u=this.distortionProcessorFactory.create({outputScaling:a,repage:h,asyncTimeout:c,abortSignal:l}),p=await u.process(f,i);return p instanceof D?p.getAdapter():p}createTargetImage(e,t,i,s){const o=this.outputViewportResolver.resolve(e,t,i);return s!==1&&o.scale(s),e.getBlank(o)}}class At{constructor(e,t,i,s,o,a){this.reversePixelMapperResolver=e,this.colorResamplerResolver=t,this.distortionController=i,this.imageAdapterResolver=s,this.colorStringParser=o,this.virtualPixelDecoratorApplicator=a}async distort(e,t,i,s){const[o,a,h]=this.clarifyArguments(e,t,i,s);this.setImageAdapterOptions(o,h);const c=this.getColorResampler(o,a,h),l=Date.now(),g=await this.distortionController.distort(o,a,c,h),f=Date.now();return{image:g,distortion:a,startTimestamp:l,endTimestamp:f,duration:f-l,weightLookupTable:Ne(c)?c.getWeightLookupTable():void 0}}resolveImageAdapter(e){return yt(e)?e:this.imageAdapterResolver.resolve(e)}clarifyArguments(e,t,i,s){const o=this.resolveImageAdapter(e);let a,h;if(K(t)){if(Array.isArray(i))throw new TypeError("Argument 3 should be options object or undefined when passing ReversePixelMapper as second argument");a=t,h=i}else{if(!Array.isArray(i))throw new TypeError("Missing distortion arguments");a=this.reversePixelMapperResolver.resolve(t,i,o.getViewport()),h=s}return[o,a,h||{}]}getColorResampler(e,t,i){const{matteColor:s,filter:o="RobidouxSharp",preferredResampler:a,virtualPixelMethod:h=d.TRANSPARENT,interpolationMethod:c=w.AVERAGE}=i,l=this.resolveColor(s,e.getQuantumRange()),g=this.virtualPixelDecoratorApplicator.decorate(e,h);return this.colorResamplerResolver.resolve(g,t,{preferredResampler:a,matteColor:l,filter:o,interpolationMethod:c,virtualPixelMethod:h})}setImageAdapterOptions(e,t){const{imageBackgroundColor:i,imageViewportOffset:s}=t;e.setBackgroundColor(this.resolveColor(i,e.getQuantumRange())),s&&e.getViewport().offset(...s)}resolveColor(e,t,i=[0,0,0,0]){return e===void 0?i:ce(e)?e:this.colorStringParser.parse(e,t)||i}}class Mt{constructor(e){this.outputViewportStrategiesPool=e}resolve(e,t,i){const s=this.outputViewportStrategiesPool.items();s.sort((a,h)=>a.priority-h.priority);const o=s.find(a=>a.match(t,i));if(!o)throw new Error("Couldn't find matching output viewport resolution strategy");return o.getOutputViewport(e,t,i)}}class Et{constructor(){this.priority=2}match(e,t){return le(e)&&(e.forceBestFit||t==="bestFit"||t===!0)}getOutputViewport(e,t){if(le(t))return t.getBestFitViewport(e.getViewport());throw new TypeError("Given ReversePixelMapper don't support best-fit output viewport")}}class Ft{constructor(){this.priority=3}getOutputViewport(e){return e.getViewport().clone()}match(){return!0}}class Vt{constructor(){this.priority=1}match(e,t){return _(t)}getOutputViewport(e,t,i){if(_(i))return y.fromLiteral(i);throw new TypeError("'viewport argument should be ViewportLiteral")}}class M{constructor(){this.storage=new Map}has(e){return this.storage.has(e)}get(e){const t=this.storage.get(e);if(t===void 0)throw new RangeError(`Item with key "${e}" was not found in pool.`);return t}add(e,t,i=!1){if(this.storage.has(e)&&!i)throw new TypeError(`Item with key "${e}" already exists in pool`);this.storage.set(e,t)}remove(e){this.storage.delete(e)}keys(){return Array.from(this.storage.keys())}items(){return Array.from(this.storage.values())}}class It{constructor(e,t,i,s,o=1,a){this.filterFunction=e,this.windowingFunction=t,this.support=i,this.scale=s,this.blur=o,this.windowSupport=a!==void 0?a:this.support}getWorkingSupport(){return this.support*this.blur}getWeight(e){const t=e/this.blur;return(t(r.ROBIDOUX="Robidoux",r.ROBIDOUX_SHARP="RobidouxSharp",r.BOX="Box",r))(St||{});class z{constructor(){this.parent=null,this.services=new Map,this.backups=[]}register(e,t){this.services.set(e,t)}unregister(e){this.services.delete(e)}resolve(e){const t=this.services.get(e);if(t===void 0){if(this.parent)return this.parent.resolve(e);throw new RangeError(`Service "${e}" was not found in container.`)}return typeof t=="function"?t(this):t}backup(){const e=new Map(this.services);this.backups.push(e)}restore(){const e=this.backups.pop();e&&(this.services.clear(),this.services=e)}createChild(){const e=new z;return e.parent=this,e}}class Ot{create(){return function(){return 1}}}class Dt{create(e,t){const i=(6-2*e)/6,s=(12*e-18+6*t)/6,o=(12-9*e-6*t)/6,a=(8*e+24*t)/6,h=(-12*e-48*t)/6,c=(6*e+30*t)/6,l=(-1*e-6*t)/6;return function(g){if(typeof g=="number"){if(g<1)return i+g*(g*(s+g*o));if(g<2)return a+g*(h+g*(c+g*l))}return 0}}}var ge=(r=>(r.BOX="Box",r.CUBIC_BC="CubicBC",r))(ge||{});const pe=function(r=[]){const e=new z;return r.forEach(t=>t.register(e)),e}([{register(r){let e=!1;r.register("ColorResamplerResolver",t=>{if(!e){const i=t.resolve("ColorInterpolatorFactory"),s=new M;s.add("ewa",new nt(i)),s.add("point",new ct(i)),t.register("ColorResamplerFactoriesPool",s),e=!0}return new Re(t.resolve("ColorResamplerFactoriesPool"),t.resolve("ResampleFilterResolver"))})}},{register(r){const e=new M;e.add("transparent",new dt),e.add("hex",new gt),e.add("rgba",new pt),r.register("ColorStringParsersPool",e),r.register("ColorStringParser",t=>new ut(t.resolve("ColorStringParsersPool")))}},{register(r){r.register("DistortionProcessorFactory",()=>new Ct),r.register("DistortionController",e=>new Pt(e.resolve("OutputViewportResolver"),e.resolve("DistortionProcessorFactory"))),r.register("DistortionService",e=>new At(e.resolve("ReversePixelMapperResolver"),e.resolve("ColorResamplerResolver"),e.resolve("DistortionController"),e.resolve("ImageAdapterResolver"),e.resolve("ColorStringParser"),e.resolve("VirtualPixelDecoratorApplicator")))}},{register(r){const e=new M;e.add("BrowserCanvas",new vt),r.register("ImageAdapterFactoriesPool",e),r.register("ImageAdapterResolver",t=>new xt(t.resolve("ImageAdapterFactoriesPool")))}},{register(r){const e=new M;e.add("user-provided",new Vt),e.add("best-fit",new Et),e.add("source-image",new Ft),r.register("OutputViewportStrategiesPool",e),r.register("OutputViewportResolver",t=>new Mt(t.resolve("OutputViewportStrategiesPool")))}},{register(r){const e=new M;e.add(A.ARC,new Ke),e.add(A.AFFINE,new Qe),e.add(A.AFFINE_PROJECTION,new Ye),e.add(A.PERSPECTIVE,new ze),e.add(A.PERSPECTIVE_PROJECTION,new Je),e.add(A.POLYNOMIAL,new tt),r.register("ReversePixelMapperFactoriesPool",e),r.register("ReversePixelMapperResolver",t=>new st(t.resolve("ReversePixelMapperFactoriesPool")))}},{register(r){const e=new M;e.add("Robidoux",{filterFunctionFactory:"CubicBC",filterFunctionFactoryArgs:[.3782157550939987,.3108921224530007],windowFunctionFactory:"Box",windowFunctionFactoryArgs:[],support:2,scale:1.1685777620836932}),e.add("RobidouxSharp",{filterFunctionFactory:"CubicBC",filterFunctionFactoryArgs:[.2620145123990142,.3689927438004929],windowFunctionFactory:"Box",windowFunctionFactoryArgs:[],support:2,scale:1.105822933719019}),e.add("Box",{filterFunctionFactory:"Box",filterFunctionFactoryArgs:[],windowFunctionFactory:"Box",windowFunctionFactoryArgs:[],support:.5,scale:.5}),r.register("ResampleFilterPresetsPool",e),r.register("ResampleFilterFactory",t=>new Tt(t.resolve("WeightingFunctionFactoriesPool"))),r.register("ResampleFilterResolver",t=>new Lt(t.resolve("ResampleFilterPresetsPool"),t.resolve("ResampleFilterFactory")))}},{register(r){const e=new M;e.add(ge.BOX,new Ot),e.add(ge.CUBIC_BC,new Dt),r.register("WeightingFunctionFactoriesPool",e)}},{register(r){r.register("ColorInterpolatorFactory",new ye)}},{register(r){r.register("VirtualPixelDecoratorApplicator",new Be)}}]);n.AbortException=Xe,n.AbstractImageAdapter=wt,n.AbstractVirtualPixelDecorator=x,n.Affine=S,n.AffineFactory=Qe,n.AffineProjectionFactory=Ye,n.Arc=$e,n.ArcFactory=Ke,n.AverageInterpolator=C,n.BackgroundInterpolator=xe,n.BackgroundVirtualPixel=Pe,n.BaseColorInterpolatorFactory=ye,n.BaseColorResamplerResolver=Re,n.BaseDistortionProcessorFactory=Ct,n.BaseImageAdapterResolver=xt,n.BaseOutputViewportResolver=Mt,n.BasePool=M,n.BaseResampleFilter=It,n.BaseResampleFilterFactory=Tt,n.BaseResampleFilterResolver=Lt,n.BaseReversePixelMapperResolver=st,n.BaseServiceContainer=z,n.BaseVirtualPixelDecoratorApplicator=Be,n.BestFitViewport=Et,n.BoxFactory=Ot,n.Canvas=O,n.CanvasFactory=vt,n.CompositeColorStringParser=ut,n.ConstantVirtualPixel=H,n.CubicBCFactory=Dt,n.Distortion=A,n.DistortionController=Pt,n.DistortionService=At,n.EPSILON=P,n.EdgeVirtualPixel=Ae,n.EwaResampler=at,n.EwaResamplerFactory=nt,n.FilterName=St,n.HexColorStringParser=gt,n.HorizontalTileEdgeVirtualPixel=Me,n.HorizontalTileVirtualPixel=Ee,n.IntegerInterpolator=ve,n.InterpolationMethod=w,n.InvalidArgument=F,n.InvalidArgumentsLength=$,n.InvalidMethodCall=class extends q{constructor(r){super(r),this.name="InvalidMethodCall"}},n.LeastSquares=Y,n.LensException=q,n.MAXIMUM_VALUE=Ge,n.M_2PI=B,n.M_PI2=b,n.MirrorVirtualPixel=Fe,n.Perspective=U,n.PerspectiveFactory=ze,n.PerspectiveProjectionFactory=Je,n.PointResampler=lt,n.PointResamplerFactory=ct,n.Polynomial=et,n.PolynomialFactory=tt,n.RandomVirtualPixel=Ve,n.RepageProxy=Rt,n.ReversePixelMappingProcessor=ft,n.RgbaColorStringParser=pt,n.SourceImageViewport=Ft,n.SuperSamplingProxy=mt,n.TileVirtualPixel=Ie,n.TransparentStringParser=dt,n.UserProvidedViewport=Vt,n.VERSION="2.0.1",n.VerticalTileEdgeVirtualPixel=Te,n.VerticalTileVirtualPixel=be,n.Viewport=y,n.VirtualPixelMethod=d,n.VirtualViewportProxy=D,n.applyAffineMatrix=je,n.applyPerspectiveMatrix=Ze,n.blendColors=se,n.createDeferred=We,n.degreesToRadians=oe,n.distort=function(r,e,t,i){return pe.resolve("DistortionService").distort(r,e,t,i)},n.distortUnwrap=async function(r,e,t,i){return(await pe.resolve("DistortionService").distort(r,e,t,i)).image.getResource()},n.gaussJordanElimination=He,n.invertAffineMatrix=ne,n.invertPerspectiveMatrix=he,n.isBestFitReversePixelMapper=le,n.isColor=ce,n.isColorResampler=Ce,n.isEwaColorResampler=Ne,n.isEwaReversePixelMapper=ot,n.isHasAverageColor=Le,n.isHasBackgroundColor=Se,n.isImageAdapter=yt,n.isPixelAccessor=Oe,n.isPixelAccessorWithDimensions=De,n.isPoint=ue,n.isResampleFilter=bt,n.isResampleFilterPreset=Bt,n.isReversePixelMapper=K,n.isViewportLiteral=_,n.isVirtualViewportPixelAccessor=ke,n.makeCanvas=L,n.perceptibleReciprocal=Q,n.preloadHtmlImage=Ue,n.serviceContainer=pe,n.toHTMLCanvasElement=function(r){if(r instanceof HTMLCanvasElement)return r;const e=L(r.width,r.height,!0),t=e.getContext("2d");if(!t)throw new Error("Couldn't get canvas context");return t.drawImage(r,0,0),e},Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}); //# sourceMappingURL=lens.umd.cjs.map