@etu-wiki/sharp-iiif-shims 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +1 -1
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import W from"sharp";var z="[1-9][0-9]*",te="[0-9]*",_="(?=.*[1-9])\\d+(\\.\\d+)?",U="\\d+(\\.\\d+)?",G={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",tif:"image/tiff",tiff:"image/tiff",gif:"image/gif",jp2:"image/jp2",pdf:"application/pdf"},q={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${te},${te},${z},${z}`,`pct:${U},${U},${_},${_}`],rotation:`!?${U}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:["^full$",`^${z},$`,`^,${z}$`,`^pct:${_}$`,`^${z},${z}$`,`^!${z},${z}$`,"^max$","^\\^max$",`^\\^${z},$`,`^\\^,${z}$`,`^\\^pct:${_}$`,`^\\^${z},${z}$`,`^\\^!${z},${z}$`]},j=/^pct:([\d,]+)/,ie=class{constructor(r,t,e,i,s,o){this.level=r,this.maxArea=t,this.maxWidth=e,this.maxHeight=i,this.tileWidth=s,this.tileHeight=o,this.validate("level",r)}validate(r,t){let e=q[r];if(e instanceof Array&&(e=e.join("|")),!new RegExp("^("+e+")$").test(t))throw Error(`invalid IIIF url ${r}: ${t}`);return!0}normalizeRegionParams(r,t){if(this.validate("region",r),r==="full")return null;if(r==="square")return this._regionSquare(t);if(j.test(r))return this._regionPct(r.match(j)[1],t);{let e=r.split(",").map(i=>Number(i));return this._regionXYWH(e,t)}}_regionSquare(r){let t,e,i=r.width,s=r.height;if(i!==s){let o=Math.min(i,s),n=Math.abs(Math.floor((i-s)/2));return i>s?(t=n,e=0):(t=0,e=n),this._regionXYWH([t,e,o,o],r)}return null}_regionPct(r,t){let e=r.split(",").map((i,s)=>{let o=Number(i)/100;return s===0||s===2?Math.ceil(t.width*o):s===1||s===3?Math.ceil(t.height*o):null});return this._regionXYWH(e,t)}_regionXYWH(r,t){let e=t.width,i=t.height,[s,o,n,l]=r;if(s+n>e&&(n=e-s),o+l>i&&(l=i-o),n<=0)throw Error(`invalid IIIF width ${n}`);if(l<=0)throw Error(`invalid IIIF height ${l}`);return{x:s,y:o,w:n,h:l}}normalizeSizeParams(r,t){let e=r,i=t.width,s=t.height;if(!t||!i&&!s)throw Error(`invalid region dimensions: ${JSON.stringify(t,null,2)}`);this.validate("size",e);let o=!1;e.charAt(0)==="^"&&(o=!0,e=e.substring(1));let n=null;if(e==="full"||(e==="max"?n=this._sizeMaxScale(t):j.test(e)?n=this._sizePctScale(e.match(j)[1]):e.charAt(0)==="!"&&(e=e.substring(1),n=this._sizeBangScale(e,o,t)),n===1))return null;if(n){let l=Math.ceil(i*n),a=Math.ceil(s*n);return this._sizeWH(`${l},${a}`,o,t)}else return this._sizeWH(e,o,t)}_sizeBangScale(r,t,e){let i=e.width,s=e.height,[o,n]=r.split(",").map(a=>a===""?null:Number(a)),l=Math.min(o/i,n/s);if(o>i&&n>s&&!t)throw Error("should not upscale without ^");return l}_sizeMaxScale(r){let t=r.width,e=r.height,i=1;return this.maxArea&&this.maxArea<t*e&&(i=Math.sqrt(this.maxArea/(t*e))),this.maxWidth&&this.maxWidth<t&&(i=Math.min(i,this.maxWidth/t)),this.maxHeight&&this.maxHeight<e&&(i=Math.min(i,this.maxHeight/e)),i}_sizePctScale(r){return Number(r)/100}_sizeWH(r,t,e){let i=e.width,s=e.height,[o,n]=r.split(",").map(l=>l===""?null:Number(l));if(o?n||(n=Math.ceil(s*o/i),n=n===0?1:n):(o=Math.ceil(i*n/s),o=o===0?1:o),(o>i||n>s)&&!t)throw Error("should not upscale without ^");return{width:o,height:n}}normalizeRotationParams(r){this.validate("rotation",r);let t=!1;if(r==="0")return null;r[0]==="!"&&(t=!0);let e=Number(r.replace(/^!/,""));return{isMirror:t,degree:e}}normalizeQualityParams(r){return this.validate("quality",r),r==="native"||r==="default"?null:r}normalizeFormatParams(r,t){this.validate("format",r);let e=G[r],i=G[t];return e===i?null:r}getContentType(r){return G[r]}generateImageInfoTemp(r,t,e){this.validate("version",e);let i={},s={};return i.info=s,e==="1.0"?(s.identifier=r,s.width=t.width,s.height=t.height,s.scale_factors=this.factors(t),s.tile_width=this.tileWidth,s.tile_height=this.tileHeight,s.formats=q.format,s.qualities=q.quality,s.profile=this.uriPattern("compliance",e),i.contentType="application/json",i.body=JSON.stringify(s)):(e==="1.1"?(s["@context"]=this.uriPattern("context",e),s["@id"]=r,s.width=t.width,s.height=t.height,s.scale_factors=this.factors(t),s.tile_width=this.tileWidth,s.tile_height=this.tileHeight,s.formats=q.format,s.qualities=q.quality,s.profile=this.uriPattern("compliance",e)):e==="2.0"||e==="2.1"?(s["@context"]=this.uriPattern("context",e),s["@id"]=r,s.protocol="http://iiif.io/api/image",s.width=t.width,s.height=t.height,this.level==="0"?s.sizes=this.sizes(t):s.tiles=[{scaleFactors:this.factors(t),width:this.tileWidth,height:this.tileHeight}],s.profile=[this.uriPattern("compliance",e)]):e==="3.0"&&(s["@context"]=[this.uriPattern("context",e)],s.id=r,s.type="ImageService3",s.protocol="http://iiif.io/api/image",s.width=t.width,s.height=t.height,this.level==="0"?s.sizes=this.sizes(t):s.tiles=[{scaleFactors:this.factors(t),width:this.tileWidth,height:this.tileHeight}],s.profile=this.uriPattern("compliance",e)),i.contentType="application/ld+json"),i}factors(r){let t=1,e=[];for(;this.tileWidth*t<=r.width||this.tileHeight*t<=r.height;)e.push(t),t*=2;return e.length===0&&e.push(1),e}uriPattern(r,t){let e="",i="";return t==="1.0"?e=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:t==="1.1"?(e=`http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level${this.level}`,i="http://library.stanford.edu/iiif/image-api/1.1/context.json"):t==="2.0"||t==="2.1"?(e=`http://iiif.io/api/image/2/level${this.level}.json`,i="http://iiif.io/api/image/2/context.json"):t==="3.0"&&(e=`level${this.level}`,i="http://iiif.io/api/image/3/context.json"),r==="compliance"?e:r==="context"?i:""}sizes(r){return[{width:r.width,height:r.height}]}};import{addDecoder as he,BaseDecoder as ce,fromCustomClient as re,fromUrl as ge,BaseClient as oe,BaseResponse as ne}from"geotiff";var ue=1e8,fe=1e4,pe=1e4,me=512,de=512,we={2:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByWhListed","sizeByForcedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"],2.1:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByConfinedWh","sizeByDistortedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeByWhListed","sizeByForcedWh"],3:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeUpscaling"]},Y=class extends ce{async decode(t,e){let i=Array.isArray(t.BitsPerSample)?t.BitsPerSample.length:t.SamplesPerPixel||4,s=W(e,{sequentialRead:!0}),n=(await s.metadata()).channels||4;i===4&&n<4&&s.ensureAlpha?s=s.ensureAlpha():i===3&&n>3&&s.removeAlpha&&(s=s.removeAlpha());let{data:l,info:a}=await s.raw().toBuffer({resolveWithObject:!0});if(a.channels!==i){let g=a.width*a.height,d=Buffer.alloc(g*i),c=l;for(let h=0;h<g;h+=1){let w=h*a.channels,P=h*i;for(let u=0;u<i;u+=1)u<a.channels?d[P+u]=c[w+u]:d[P+u]=u===3?255:0}return d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength)}return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}};he(50001,()=>Promise.resolve(Y));var K=class extends ne{constructor(t){super(),this.result=t}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(t){return this.result.res.headers[t.toLowerCase()]}getData(){return Buffer.isBuffer(this.result.content)?this.result.content.buffer.slice(this.result.content.byteOffset,this.result.content.byteOffset+this.result.content.byteLength):this.result.content}},Q=class extends oe{constructor(t,e){super(t),this.objectKey=t,this.ossClient=e}async request({headers:t={}}={}){let e=await this.ossClient.get(this.objectKey,{headers:t,timeout:3e4});return new K(e)}};async function ye(r,t){let e=new Q(r,t);return re(e)}var ze=new Map,O=new Map,E=new Map,J=class extends ne{constructor(t,e){super(),this.response=t,this.arrayBuffer=e}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(t){return this.response.headers.get(t)||""}getData(){return this.arrayBuffer}},Z=class extends oe{constructor(t,e,i){super(t),this.ipfsUrl=t,this.verifiedFetch=e,this.peerCache=i}extractCID(t){let e=t.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return e?e[1]:null}async request({headers:t={}}={}){console.log(t);let e=this.extractCID(this.ipfsUrl),i=e?this.peerCache?.get(e):null,s=i&&Array.isArray(i),o=s?3e4:6e4,n=new AbortController,l=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),n.abort()},o);try{let a={headers:t,signal:n.signal,session:!1};e&&(s?console.log(`[IPFSClient] Using fast path for previously accessed ${e}`):(console.log(`[IPFSClient] First fetch for ${e}, using HTTP gateways...`),this.peerCache&&this.peerCache.set(e,"discovering")));let g=await this.verifiedFetch(this.ipfsUrl,a);if(!g.ok)throw new Error(`Failed to fetch from IPFS: ${g.status} ${g.statusText}`);let d=await g.arrayBuffer();return clearTimeout(l),e&&this.peerCache&&this.peerCache.get(e)==="discovering"&&(this.peerCache.set(e,[]),console.log(`[IPFSClient] Marked ${e} as discovered`)),new J(g,d)}catch(a){throw clearTimeout(l),e&&this.peerCache&&this.peerCache.get(e)==="discovering"&&this.peerCache.delete(e),console.error("[IPFSClient] Error during request:",a),a instanceof Error&&(console.error("[IPFSClient] Error name:",a.name),console.error("[IPFSClient] Error message:",a.message),console.error("[IPFSClient] Error stack:",a.stack)),a&&typeof a=="object"&&"errors"in a&&console.error("[IPFSClient] AggregateError details:",a.errors),a}}};async function se(r,t,e){let i=`${e}:${t}`,s=E.get(i);if(s)return s instanceof Promise?await s:s;let o=r.getImage(t);E.set(i,o);try{let n=await o;return E.set(i,n),n}catch(n){throw E.delete(i),n}}async function Pe(r,t){let e=O.get(r);if(e)return e instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${r}`),await e):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${r}`),e);console.log(`[fromIPFS] Creating new GeoTIFF client for ${r}`);let i=(async()=>{let s=new Z(r,t,ze),o=await re(s);return O.set(r,o),o})();O.set(r,i);try{return await i}catch(s){throw O.delete(r),s}}var V=class extends ie{constructor(t,e=ue,i=fe,s=pe,o=me,n=de){super(t,e,i,s,o,n)}regionImpl(t,e){t&&(e=e.extract({left:t.x,top:t.y,width:t.w,height:t.h}))}sizeImpl(t,e){t&&(e=e.resize({...t,fit:"fill"}))}rotationImpl(t,e){t&&(t.isMirror&&(e=e.flop()),e=e.rotate(t.degree))}qualityFormatImpl(t,e,i,s,o){t&&(t==="color"?i=i.toColorspace("srgb"):t==="gray"||t==="grey"?i=i.grayscale():t==="bitonal"&&(i=i.threshold())),e&&(i=i.toFormat(e)),s==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateImageTile(t,e,i){let s=t.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],a=s.pop(),g=s.pop(),d=s.pop(),c=s.pop(),h={width:e.width,height:e.height},w=super.normalizeRegionParams(d,h),P=super.normalizeSizeParams(g,{width:w?w.w:h.width,height:w?w.h:h.height}),{x:u,y:I,w:b,h:$}=w??{x:0,y:0,w:h.width,h:h.height},{width:v,height:B}=P;console.log(`Attempting to fetch from URL: ${i}`);let x,m;typeof i=="string"?(console.log("Using standard HTTP fetch"),x=await ge(i),m=i):typeof c=="string"&&c.startsWith("bafy")?(console.log("Detected CID id, using fromIPFS"),m=`ipfs://${c}`,x=await Pe(m,i)):(x=await ye(c,i),m=`oss://${c}`);let f=await se(x,0,m);console.log(`Source dimensions: ${f.getWidth()} x ${f.getHeight()}`),console.log(`Extracting region: x=${u}, y=${I}, w=${b}, h=${$}`),console.log(`Output size: ${v} x ${B}`);let M=await x.getImageCount();console.log(`Total images (including overviews): ${M}`);let C=f.getSamplesPerPixel(),F;C>=3?(F=[0,1,2],C>=4&&F.push(3)):F=[0],console.log("Using automatic overview selection based on resolution...");let A=Math.max(b/v,$/B),H=f,y=1;for(let T=0;T<M;T++){let R=await se(x,T,m),X=f.getWidth()/R.getWidth();X<=A&&X>y&&(y=X,H=R)}console.log(`Selected overview with scale: ${y.toFixed(2)}x`),console.log(`Overview dimensions: ${H.getWidth()} x ${H.getHeight()}`);let S=[Math.floor(u/y),Math.floor(I/y),Math.floor((u+b)/y),Math.floor((I+$)/y)],p;try{p=await H.readRasters({window:S,width:v,height:B,samples:F,interleave:!0,resampleMethod:"bilinear"})}catch(T){console.log(`Failed to read from overview, falling back to main image: ${T}`);let R=[u,I,u+b,I+$];p=await f.readRasters({window:R,width:v,height:B,samples:F,interleave:!0,resampleMethod:"bilinear"})}let k=F.length,L=Buffer.from(p.buffer,p.byteOffset,p.byteLength),D=W(L,{raw:{width:v,height:B,channels:k}}),ae=super.normalizeRotationParams(a);this.rotationImpl(ae,D);let le=super.normalizeQualityParams(n),ee=super.normalizeFormatParams(l,e.format);this.qualityFormatImpl(le,ee,D,l,e);let N={};return N.body=D,N.contentType=super.getContentType(ee),N}iiifTransform(t,e){let i=e.isHDImage?W({limitInputPixels:!1,sequentialRead:!0}):W(),s=t.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],a=s.pop(),g=s.pop(),d=s.pop(),c=!1,h=i,w={width:e.width,height:e.height};e&&e.orientation&&(c=!0,h=h.rotate(),e.orientation>=5&&(w={width:e.height,height:e.width}));let P=super.normalizeRegionParams(d,w);this.regionImpl(P,h);let u=super.normalizeSizeParams(g,{width:P?P.w:w.width,height:P?P.h:w.height});this.sizeImpl(u,h);let I=super.normalizeRotationParams(a);this.rotationImpl(I,h);let b=super.normalizeQualityParams(n),$=super.normalizeFormatParams(l,e.format);return this.qualityFormatImpl(b,$,h,l,e),P||u||I||b||$||c?h:(console.log("skip iiif transform"),null)}async generateIiifImage(t,e,i){let s=t.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],a=s.pop(),g=s.pop(),d=s.pop(),c=super.normalizeRegionParams(d,i),h=super.normalizeSizeParams(g,{width:c?c.w:i.width,height:c?c.h:i.height}),w=super.normalizeRotationParams(a),P=super.normalizeQualityParams(n),u=super.normalizeFormatParams(l,i.format),{x:I,y:b,w:$,h:v}=c||{x:0,y:0,w:i.width,h:i.height},{width:B,height:x}=h||{width:i.width,height:i.height},m=0,f;if(i.pages&&i.pages>1){let C=B/$,F=x/v,A=Math.max(C,F);if(A>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),m=0;else{m=i.pages-1;let y=Math.pow(2,i.pages-1),S=i.width/y,p=i.height/y;for(;m>0;){let k=$*(S/i.width),L=v*(p/i.height);if(k>=B*1.1&&L>=x*1.1)break;m--,S*=2,p*=2}console.log(`Pyramid optimization: selected page ${m}/${i.pages-1} (scale: ${A.toFixed(2)}x, target: ${B}x${x})`)}let H=i.isHDImage?{limitInputPixels:!1,page:m,sequentialRead:!0,failOn:"none"}:{page:m,sequentialRead:!0,failOn:"none"};if(f=W(e,H),c&&m>0){let y=await f.metadata(),S=y.width/i.width,p={x:Math.floor(I*S),y:Math.floor(b*S),w:Math.floor($*S),h:Math.floor(v*S)};p.w=Math.min(p.w,y.width-p.x),p.h=Math.min(p.h,y.height-p.y),this.regionImpl(p,f)}else this.regionImpl(c,f)}else{let C=i.isHDImage?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};f=W(e,C),this.regionImpl(c,f)}this.sizeImpl(h,f),this.rotationImpl(w,f),this.qualityFormatImpl(P,u,f,l,i);let M={};return M.body=f,M.contentType=super.getContentType(u),M}generateImageInfo(t,e,i="",s){let o=this.level,n={width:e.width,height:e.height};e&&e.orientation&&e.orientation>=5&&(console.log(e.orientation),n={width:e.height,height:e.width});let l=super.generateImageInfoTemp(t,n,s),a=l.info;if((s==="2.0"||s==="2.1")&&(a.profile=[super.uriPattern("compliance",s)],o==="2")){let g={};g.formats=["jpg","png","webp","jp2","pdf","tif"],g.qualities=["color","gray","bitonal","default","native","grey"],g.supports=we[Number(s)],a.profile.push(g)}return s==="3.0"&&i&&(a.extraFormats=[i],a.preferredFormats=[i]),i&&(a.formats=[i]),l}};export{V as default};
1
+ import R from"sharp";var p="[1-9][0-9]*",V="[0-9]*",C="(?=.*[1-9])\\d+(\\.\\d+)?",N="\\d+(\\.\\d+)?",X={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",webp:"image/webp",tif:"image/tiff",tiff:"image/tiff",gif:"image/gif",jp2:"image/jp2",pdf:"application/pdf"},A={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${V},${V},${p},${p}`,`pct:${N},${N},${C},${C}`],rotation:`!?${N}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:["^full$",`^${p},$`,`^,${p}$`,`^pct:${C}$`,`^${p},${p}$`,`^!${p},${p}$`,"^max$","^\\^max$",`^\\^${p},$`,`^\\^,${p}$`,`^\\^pct:${C}$`,`^\\^${p},${p}$`,`^\\^!${p},${p}$`]},j=/^pct:([\d,]+)/,tt=class{constructor(r,e,t,o,i,s){this.level=r,this.maxArea=e,this.maxWidth=t,this.maxHeight=o,this.tileWidth=i,this.tileHeight=s,this.validate("level",r)}validate(r,e){let t=A[r];if(t instanceof Array&&(t=t.join("|")),!new RegExp("^("+t+")$").test(e))throw Error(`invalid IIIF url ${r}: ${e}`);return!0}normalizeRegionParams(r,e){if(this.validate("region",r),r==="full")return null;if(r==="square")return this._regionSquare(e);if(j.test(r))return this._regionPct(r.match(j)[1],e);{let t=r.split(",").map(o=>Number(o));return this._regionXYWH(t,e)}}_regionSquare(r){let e,t,o=r.width,i=r.height;if(o!==i){let s=Math.min(o,i),n=Math.abs(Math.floor((o-i)/2));return o>i?(e=n,t=0):(e=0,t=n),this._regionXYWH([e,t,s,s],r)}return null}_regionPct(r,e){let t=r.split(",").map((o,i)=>{let s=Number(o)/100;return i===0||i===2?Math.ceil(e.width*s):i===1||i===3?Math.ceil(e.height*s):null});return this._regionXYWH(t,e)}_regionXYWH(r,e){let t=e.width,o=e.height,[i,s,n,a]=r;if(i+n>t&&(n=t-i),s+a>o&&(a=o-s),n<=0)throw Error(`invalid IIIF width ${n}`);if(a<=0)throw Error(`invalid IIIF height ${a}`);return{x:i,y:s,w:n,h:a}}normalizeSizeParams(r,e){let t=r,o=e.width,i=e.height;if(!e||!o&&!i)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",t);let s=!1;t.charAt(0)==="^"&&(s=!0,t=t.substring(1));let n=null;if(t==="full"||(t==="max"?n=this._sizeMaxScale(e):j.test(t)?n=this._sizePctScale(t.match(j)[1]):t.charAt(0)==="!"&&(t=t.substring(1),n=this._sizeBangScale(t,s,e)),n===1))return null;if(n){let a=Math.ceil(o*n),l=Math.ceil(i*n);return this._sizeWH(`${a},${l}`,s,e)}else return this._sizeWH(t,s,e)}_sizeBangScale(r,e,t){let o=t.width,i=t.height,[s,n]=r.split(",").map(l=>l===""?null:Number(l)),a=Math.min(s/o,n/i);if(s>o&&n>i&&!e)throw Error("should not upscale without ^");return a}_sizeMaxScale(r){let e=r.width,t=r.height,o=1;return this.maxArea&&this.maxArea<e*t&&(o=Math.sqrt(this.maxArea/(e*t))),this.maxWidth&&this.maxWidth<e&&(o=Math.min(o,this.maxWidth/e)),this.maxHeight&&this.maxHeight<t&&(o=Math.min(o,this.maxHeight/t)),o}_sizePctScale(r){return Number(r)/100}_sizeWH(r,e,t){let o=t.width,i=t.height,[s,n]=r.split(",").map(a=>a===""?null:Number(a));if(s?n||(n=Math.ceil(i*s/o),n=n===0?1:n):(s=Math.ceil(o*n/i),s=s===0?1:s),(s>o||n>i)&&!e)throw Error("should not upscale without ^");return{width:s,height:n}}normalizeRotationParams(r){this.validate("rotation",r);let e=!1;if(r==="0")return null;r[0]==="!"&&(e=!0);let t=Number(r.replace(/^!/,""));return{isMirror:e,degree:t}}normalizeQualityParams(r){return this.validate("quality",r),r==="native"||r==="default"?null:r}normalizeFormatParams(r,e){this.validate("format",r);let t=X[r],o=X[e];return t===o?null:r}getContentType(r){return X[r]}generateImageInfoTemp(r,e,t){this.validate("version",t);let o={},i={};return o.info=i,t==="1.0"?(i.identifier=r,i.width=e.width,i.height=e.height,i.scale_factors=this.factors(e),i.tile_width=this.tileWidth,i.tile_height=this.tileHeight,i.formats=A.format,i.qualities=A.quality,i.profile=this.uriPattern("compliance",t),o.contentType="application/json",o.body=JSON.stringify(i)):(t==="1.1"?(i["@context"]=this.uriPattern("context",t),i["@id"]=r,i.width=e.width,i.height=e.height,i.scale_factors=this.factors(e),i.tile_width=this.tileWidth,i.tile_height=this.tileHeight,i.formats=A.format,i.qualities=A.quality,i.profile=this.uriPattern("compliance",t)):t==="2.0"||t==="2.1"?(i["@context"]=this.uriPattern("context",t),i["@id"]=r,i.protocol="http://iiif.io/api/image",i.width=e.width,i.height=e.height,this.level==="0"?i.sizes=this.sizes(e):i.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],i.profile=[this.uriPattern("compliance",t)]):t==="3.0"&&(i["@context"]=[this.uriPattern("context",t)],i.id=r,i.type="ImageService3",i.protocol="http://iiif.io/api/image",i.width=e.width,i.height=e.height,this.level==="0"?i.sizes=this.sizes(e):i.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],i.profile=this.uriPattern("compliance",t)),o.contentType="application/ld+json"),o}factors(r){let e=1,t=[];for(;this.tileWidth*e<=r.width||this.tileHeight*e<=r.height;)t.push(e),e*=2;return t.length===0&&t.push(1),t}uriPattern(r,e){let t="",o="";return e==="1.0"?t=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:e==="1.1"?(t=`http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level${this.level}`,o="http://library.stanford.edu/iiif/image-api/1.1/context.json"):e==="2.0"||e==="2.1"?(t=`http://iiif.io/api/image/2/level${this.level}.json`,o="http://iiif.io/api/image/2/context.json"):e==="3.0"&&(t=`level${this.level}`,o="http://iiif.io/api/image/3/context.json"),r==="compliance"?t:r==="context"?o:""}sizes(r){return[{width:r.width,height:r.height}]}};import{addDecoder as nt,BaseDecoder as at,fromCustomClient as et,fromUrl as lt,BaseClient as it,BaseResponse as ot}from"geotiff";var ht=1e8,ct=1e4,gt=1e4,ut=512,ft=512,pt={2:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByWhListed","sizeByForcedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"],2.1:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeAboveFull","sizeByConfinedWh","sizeByDistortedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeByWhListed","sizeByForcedWh"],3:["baseUriRedirect","canonicalLinkHeader","cors","jsonldMediaType","mirroring","profileLinkHeader","regionByPct","regionByPx","regionSquare","rotationArbitrary","rotationBy90s","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh","sizeUpscaling"]},G=class extends at{async decode(e,t){let o=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,i=R(t,{sequentialRead:!0}),n=(await i.metadata()).channels||4;o===4&&n<4&&i.ensureAlpha?i=i.ensureAlpha():o===3&&n>3&&i.removeAlpha&&(i=i.removeAlpha());let{data:a,info:l}=await i.raw().toBuffer({resolveWithObject:!0});if(l.channels!==o){let m=l.width*l.height,z=Buffer.alloc(m*o),g=a;for(let h=0;h<m;h+=1){let f=h*l.channels,d=h*o;for(let c=0;c<o;c+=1)c<l.channels?z[d+c]=g[f+c]:z[d+c]=c===3?255:0}return z.buffer.slice(z.byteOffset,z.byteOffset+z.byteLength)}return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}};nt(50001,()=>Promise.resolve(G));var U=class extends ot{constructor(e){super(),this.result=e}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(e){return this.result.res.headers[e.toLowerCase()]}getData(){return Buffer.isBuffer(this.result.content)?this.result.content.buffer.slice(this.result.content.byteOffset,this.result.content.byteOffset+this.result.content.byteLength):this.result.content}},Y=class extends it{constructor(e,t){super(e),this.objectKey=e,this.ossClient=t}async request({headers:e={}}={}){let t=await this.ossClient.get(this.objectKey,{headers:e,timeout:3e4});return new U(t)}};async function mt(r,e){let t=new Y(r,e);return et(t)}var O=new Map,Q=class extends ot{constructor(e,t){super(),this.response=e,this.arrayBuffer=t}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(e){return this.response.headers.get(e)||""}getData(){return this.arrayBuffer}},J=class extends it{constructor(e,t){super(e),this.ipfsUrl=e,this.verifiedFetch=t}extractCID(e){let t=e.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return t?t[1]:null}async request({headers:e={}}={}){console.log(e);let t=6e4,o=new AbortController,i=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),o.abort()},t);try{let s={headers:e,signal:o.signal,session:!1},n=await this.verifiedFetch(this.ipfsUrl,s);if(!n.ok)throw new Error(`Failed to fetch from IPFS: ${n.status} ${n.statusText}`);let a=await n.arrayBuffer();return clearTimeout(i),new Q(n,a)}catch(s){throw clearTimeout(i),console.error("[IPFSClient] Error during request:",s),s instanceof Error&&(console.error("[IPFSClient] Error name:",s.name),console.error("[IPFSClient] Error message:",s.message),console.error("[IPFSClient] Error stack:",s.stack)),s&&typeof s=="object"&&"errors"in s&&console.error("[IPFSClient] AggregateError details:",s.errors),s}}};async function dt(r,e){let t=O.get(r);if(t)return t instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${r}`),await t):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${r}`),t);console.log(`[fromIPFS] Creating new GeoTIFF client for ${r}`);let o=(async()=>{let i=new J(r,e),s=await et(i);return O.set(r,s),s})();O.set(r,o);try{return await o}catch(i){throw O.delete(r),i}}var K=class extends tt{constructor(e,t=ht,o=ct,i=gt,s=ut,n=ft){super(e,t,o,i,s,n)}regionImpl(e,t){e&&(t=t.extract({left:e.x,top:e.y,width:e.w,height:e.h}))}sizeImpl(e,t){e&&(t=t.resize({...e,fit:"fill"}))}rotationImpl(e,t){e&&(e.isMirror&&(t=t.flop()),t=t.rotate(e.degree))}qualityFormatImpl(e,t,o,i,s){e&&(e==="color"?o=o.toColorspace("srgb"):e==="gray"||e==="grey"?o=o.grayscale():e==="bitonal"&&(o=o.threshold())),t&&(o=o.toFormat(t)),i==="png"&&(s.paletteBitDepth===1||s.space==="b-w")&&(o=o.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,t,o){let i=e.split("/"),s=i.pop(),n=s.split(".")[0],a=s.split(".")[1],l=i.pop(),m=i.pop(),z=i.pop(),g=i.pop(),h={width:t.width,height:t.height},f=super.normalizeRegionParams(z,h),d=super.normalizeSizeParams(m,{width:f?f.w:h.width,height:f?f.h:h.height}),{x:c,y:x,w:v,h:$}=f??{x:0,y:0,w:h.width,h:h.height},{width:B,height:H}=d;console.log(`Attempting to fetch from URL: ${o}`);let I;if(typeof o=="string")console.log("Using standard HTTP fetch"),I=await lt(o);else if(typeof g=="string"&&g.startsWith("bafy")){console.log("Detected CID id, using fromIPFS");let S=`ipfs://${g}`;I=await dt(S,o)}else I=await mt(g,o);let u=await I.getImage(0);console.log(`Source dimensions: ${u.getWidth()} x ${u.getHeight()}`),console.log(`Extracting region: x=${c}, y=${x}, w=${v}, h=${$}`),console.log(`Output size: ${B} x ${H}`);let w=await I.getImageCount();console.log(`Total images (including overviews): ${w}`);let q=u.getSamplesPerPixel(),b;q>=3?(b=[0,1,2],q>=4&&b.push(3)):b=[0],console.log("Using automatic overview selection based on resolution...");let E=Math.max(v/B,$/H),F=u,W=1;for(let S=0;S<w;S++){let _=await I.getImage(S),D=u.getWidth()/_.getWidth();D<=E&&D>W&&(W=D,F=_)}console.log(`Selected overview with scale: ${W.toFixed(2)}x`),console.log(`Overview dimensions: ${F.getWidth()} x ${F.getHeight()}`);let M=[Math.floor(c/W),Math.floor(x/W),Math.floor((c+v)/W),Math.floor((x+$)/W)],y;try{y=await F.readRasters({window:M,width:B,height:H,samples:b,interleave:!0,resampleMethod:"bilinear"})}catch(S){console.log(`Failed to read from overview, falling back to main image: ${S}`);let _=[c,x,c+v,x+$];y=await u.readRasters({window:_,width:B,height:H,samples:b,interleave:!0,resampleMethod:"bilinear"})}let P=b.length,L=Buffer.from(y.buffer,y.byteOffset,y.byteLength),T=R(L,{raw:{width:B,height:H,channels:P}}),rt=super.normalizeRotationParams(l);this.rotationImpl(rt,T);let st=super.normalizeQualityParams(n),Z=super.normalizeFormatParams(a,t.format);this.qualityFormatImpl(st,Z,T,a,t);let k={};return k.body=T,k.contentType=super.getContentType(Z),k}iiifTransform(e,t){let o=t.isHDImage?R({limitInputPixels:!1,sequentialRead:!0}):R(),i=e.split("/"),s=i.pop(),n=s.split(".")[0],a=s.split(".")[1],l=i.pop(),m=i.pop(),z=i.pop(),g=!1,h=o,f={width:t.width,height:t.height};t&&t.orientation&&(g=!0,h=h.rotate(),t.orientation>=5&&(f={width:t.height,height:t.width}));let d=super.normalizeRegionParams(z,f);this.regionImpl(d,h);let c=super.normalizeSizeParams(m,{width:d?d.w:f.width,height:d?d.h:f.height});this.sizeImpl(c,h);let x=super.normalizeRotationParams(l);this.rotationImpl(x,h);let v=super.normalizeQualityParams(n),$=super.normalizeFormatParams(a,t.format);return this.qualityFormatImpl(v,$,h,a,t),d||c||x||v||$||g?h:(console.log("skip iiif transform"),null)}async generateIiifImage(e,t,o){let i=e.split("/"),s=i.pop(),n=s.split(".")[0],a=s.split(".")[1],l=i.pop(),m=i.pop(),z=i.pop(),g=super.normalizeRegionParams(z,o),h=super.normalizeSizeParams(m,{width:g?g.w:o.width,height:g?g.h:o.height}),f=super.normalizeRotationParams(l),d=super.normalizeQualityParams(n),c=super.normalizeFormatParams(a,o.format),{x,y:v,w:$,h:B}=g||{x:0,y:0,w:o.width,h:o.height},{width:H,height:I}=h||{width:o.width,height:o.height},u=0,w;if(o.pages&&o.pages>1){let b=H/$,E=I/B,F=Math.max(b,E);if(F>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),u=0;else{u=o.pages-1;let M=Math.pow(2,o.pages-1),y=o.width/M,P=o.height/M;for(;u>0;){let L=$*(y/o.width),T=B*(P/o.height);if(L>=H*1.1&&T>=I*1.1)break;u--,y*=2,P*=2}console.log(`Pyramid optimization: selected page ${u}/${o.pages-1} (scale: ${F.toFixed(2)}x, target: ${H}x${I})`)}let W=o.isHDImage?{limitInputPixels:!1,page:u,sequentialRead:!0,failOn:"none"}:{page:u,sequentialRead:!0,failOn:"none"};if(w=R(t,W),g&&u>0){let M=await w.metadata(),y=M.width/o.width,P={x:Math.floor(x*y),y:Math.floor(v*y),w:Math.floor($*y),h:Math.floor(B*y)};P.w=Math.min(P.w,M.width-P.x),P.h=Math.min(P.h,M.height-P.y),this.regionImpl(P,w)}else this.regionImpl(g,w)}else{let b=o.isHDImage?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};w=R(t,b),this.regionImpl(g,w)}this.sizeImpl(h,w),this.rotationImpl(f,w),this.qualityFormatImpl(d,c,w,a,o);let q={};return q.body=w,q.contentType=super.getContentType(c),q}generateImageInfo(e,t,o="",i){let s=this.level,n={width:t.width,height:t.height};t&&t.orientation&&t.orientation>=5&&(console.log(t.orientation),n={width:t.height,height:t.width});let a=super.generateImageInfoTemp(e,n,i),l=a.info;if((i==="2.0"||i==="2.1")&&(l.profile=[super.uriPattern("compliance",i)],s==="2")){let m={};m.formats=["jpg","png","webp","jp2","pdf","tif"],m.qualities=["color","gray","bitonal","default","native","grey"],m.supports=pt[Number(i)],l.profile.push(m)}return i==="3.0"&&o&&(l.extraFormats=[o],l.preferredFormats=[o]),o&&(l.formats=[o]),a}};export{K as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@etu-wiki/sharp-iiif-shims",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",