@etu-wiki/sharp-iiif-shims 0.1.3 → 0.1.4

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
- var me=Object.create;var re=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var ye=Object.getPrototypeOf,ze=Object.prototype.hasOwnProperty;var be=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ve=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!ze.call(s,r)&&r!==t&&re(s,r,{get:()=>e[r],enumerable:!(i=de(e,r))||i.enumerable});return s};var $e=(s,e,t)=>(t=s!=null?me(ye(s)):{},ve(e||!s||!s.__esModule?re(t,"default",{value:s,enumerable:!0}):t,s));var le=be((Le,J)=>{"use strict";var G=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Pe=Object.getOwnPropertyNames,Ie=Object.prototype.hasOwnProperty,Be=(s,e)=>{for(var t in e)G(s,t,{get:e[t],enumerable:!0})},He=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pe(e))!Ie.call(s,r)&&r!==t&&G(s,r,{get:()=>e[r],enumerable:!(i=xe(e,r))||i.enumerable});return s},Me=s=>He(G({},"__esModule",{value:!0}),s),ae={};Be(ae,{default:()=>ne});J.exports=Me(ae);var n="[1-9][0-9]*",oe="[0-9]*",j="(?=.*[1-9])\\d+(\\.\\d+)?",Q="\\d+(\\.\\d+)?",Y=(s=>(s.jpg="image/jpeg",s.jpeg="image/jpeg",s.png="image/png",s.webp="image/webp",s.tif="image/tiff",s.tiff="image/tiff",s.gif="image/gif",s.jp2="image/jp2",s.pdf="application/pdf",s))(Y||{}),O={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${oe},${oe},${n},${n}`,`pct:${Q},${Q},${j},${j}`],rotation:`!?${Q}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},We={1:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],1.1:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],2:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],2.1:["full","max",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],3:["max",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`,"\\^max",`\\^${n},`,`\\^,${n}`,`\\^pct:${j}`,`\\^${n},${n}`,`\\^!${n},${n}`]},X=/^pct:([\d,]+)/,ne=class{constructor(s,e,t,i,r,o,a){this.version=s,this.level=e,this.maxArea=t,this.maxWidth=i,this.maxHeight=r,this.tileWidth=o,this.tileHeight=a,this.validate("version",s),this.validate("level",e),O.size=We[Number(s)]}validator(s){var e=O[s];return e instanceof Array&&(e=e.join("|")),new RegExp("^("+e+")$")}validate(s,e){if(!this.validator(s).test(e))throw Error(`invalid IIIF url ${s}: ${e}`);return!0}normalizeRegionParams(s,e){if(this.validate("region",s),s==="full")return null;if(s==="square")return this._regionSquare(e);if(X.test(s))return this._regionPct(s.match(X)[1],e);{let t=s.split(",").map(i=>Number(i));return this._regionXYWH(t,e)}}_regionSquare(s){let e,t,i=s.width,r=s.height;if(i!==r){let o=Math.min(i,r),a=Math.abs(Math.floor((i-r)/2));return i>r?(e=a,t=0):(e=0,t=a),this._regionXYWH([e,t,o,o],s)}return null}_regionPct(s,e){let t=s.split(",").map((i,r)=>{let o=Number(i)/100;return r===0||r===2?Math.ceil(e.width*o):r===1||r===3?Math.ceil(e.height*o):null});return this._regionXYWH(t,e)}_regionXYWH(s,e){let t=e.width,i=e.height,[r,o,a,h]=s;return r+a>t&&(a=t-r),o+h>i&&(h=i-o),{x:r,y:o,w:a,h}}normalizeSizeParams(s,e){let t=s,i=e.width,r=e.height;if(!e||!i&&!r)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",t);let o=!1;t.charAt(0)==="^"&&(o=!0,t=t.substring(1));let a=null;if(t==="full"||(t==="max"?a=this._sizeMaxScale(e):X.test(t)?a=this._sizePctScale(t.match(X)[1]):t.charAt(0)==="!"&&(t=t.substring(1),a=this._sizeBangScale(t,o,e)),a===1))return null;if(a){let h=Math.ceil(i*a),c=Math.ceil(r*a);return this._sizeWH(`${h},${c}`,o,e)}else return this._sizeWH(t,o,e)}_sizeBangScale(s,e,t){let i=t.width,r=t.height,[o,a]=s.split(",").map(c=>c===""?null:Number(c)),h=Math.min(o/i,a/r);if(o>i&&a>r&&!e)throw Error("should not upscale without ^");return h}_sizeMaxScale(s){let e=s.width,t=s.height,i=1;return this.maxArea&&this.maxArea<e*t&&(i=Math.sqrt(this.maxArea/(e*t))),this.maxWidth&&this.maxWidth<e&&(i=Math.min(i,this.maxWidth/e)),this.maxHeight&&this.maxHeight<t&&(i=Math.min(i,this.maxHeight/t)),i}_sizePctScale(s){return Number(s)/100}_sizeWH(s,e,t){let i=t.width,r=t.height,[o,a]=s.split(",").map(h=>h===""?null:Number(h));if(o?a||(a=Math.ceil(r*o/i),a=a===0?1:a):(o=Math.ceil(i*a/r),o=o===0?1:o),(o>i||a>r)&&!e)throw Error("should not upscale without ^");return{width:o,height:a}}normalizeRotationParams(s){this.validate("rotation",s);let e=!1;if(s==="0")return null;s[0]==="!"&&(e=!0);let t=Number(s.replace(/^!/,""));return{isMirror:e,degree:t}}normalizeQualityParams(s){return this.validate("quality",s),s==="native"||s==="default"?null:s}normalizeFormatParams(s,e){if((this.version==="1.0"||this.version==="1.1"||this.version==="2.0"||this.version==="2.1")&&!s)return"png";this.validate("format",s);let t=Y[s],i=Y[e];return t===i?null:s}getContentType(s){return Y[s]}generateImageInfoTemp(s,e){let t={},i={};t.info=i;let r=this.version;return r==="1.0"?(i.identifier=s,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=O.format,i.qualities=O.quality,i.profile=this.uriPattern("compliance"),t.contentType="application/json",t.body=JSON.stringify(i)):(r==="1.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=s,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=O.format,i.qualities=O.quality,i.profile=this.uriPattern("compliance")):r==="2.0"||r==="2.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=s,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")]):r==="3.0"&&(i["@context"]=[this.uriPattern("context")],i.id=s,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.contentType="application/ld+json"),t}factors(s){let e=1,t=[];for(;this.tileWidth*e<=s.width||this.tileHeight*e<=s.height;)t.push(e),e*=2;return t.length===0&&t.push(1),t}uriPattern(s){let e="",t="";return this.version==="1.0"?e=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:this.version==="1.1"?(e=`http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level${this.level}`,t="http://library.stanford.edu/iiif/image-api/1.1/context.json"):this.version==="2.0"||this.version==="2.1"?(e=`http://iiif.io/api/image/2/level${this.level}.json`,t="http://iiif.io/api/image/2/context.json"):this.version==="3.0"&&(e=`level${this.level}`,t="http://iiif.io/api/image/3/context.json"),s==="compliance"?e:s==="context"?t:""}sizes(s){return[{width:s.width,height:s.height}]}};J.exports=ne});var ge=$e(le(),1);import b from"sharp";import{addDecoder as Se,BaseDecoder as je,fromCustomClient as ue,fromUrl as Re,BaseClient as fe,BaseResponse as pe}from"geotiff";import{verifiedFetch as qe}from"@helia/verified-fetch";var _e=1e8,he=1e4,ce=1e4,Te=512,Fe=512,Ae={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"]},K=class extends je{async decode(e,t){let i=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,r=b(t,{sequentialRead:!0}),a=(await r.metadata()).channels||4;i===4&&a<4&&r.ensureAlpha?r=r.ensureAlpha():i===3&&a>3&&r.removeAlpha&&(r=r.removeAlpha());let{data:h,info:c}=await r.raw().toBuffer({resolveWithObject:!0});if(c.channels!==i){let w=c.width*c.height,z=Buffer.alloc(w*i),M=h;for(let l=0;l<w;l+=1){let u=l*c.channels,p=l*i;for(let g=0;g<i;g+=1)g<c.channels?z[p+g]=M[u+g]:z[p+g]=g===3?255:0}return z.buffer.slice(z.byteOffset,z.byteOffset+z.byteLength)}return h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength)}};Se(50001,()=>Promise.resolve(K));var V=class extends pe{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}},Z=class extends fe{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 V(t)}};async function Ce(s,e){let t=new Z(s,e);return ue(t)}var ee=class extends pe{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}},te=class extends fe{constructor(e){super(e),this.ipfsUrl=e}async request({headers:e={}}={}){let t=new AbortController,i=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),t.abort()},3e4);try{let r=await qe(this.ipfsUrl,{headers:e});if(!r.ok)throw new Error(`Failed to fetch from IPFS: ${r.status} ${r.statusText}`);let o=await r.arrayBuffer();return clearTimeout(i),new ee(r,o)}catch(r){throw clearTimeout(i),console.error("[IPFSClient] Error during request:",r),r instanceof Error&&(console.error("[IPFSClient] Error name:",r.name),console.error("[IPFSClient] Error message:",r.message),console.error("[IPFSClient] Error stack:",r.stack)),r&&typeof r=="object"&&"errors"in r&&console.error("[IPFSClient] AggregateError details:",r.errors),r}}};async function Oe(s){let e=new te(s);return await ue(e)}var ie=class extends ge.default{constructor(e,t,i=!1,r=_e,o=he,a=ce,h=Te,c=Fe){super(e,t,r,o,a,h,c),this.enableHD=i}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,i,r,o){e&&(e==="color"?i=i.toColorspace("srgb"):e==="gray"||e==="grey"?i=i.grayscale():e==="bitonal"&&(i=i.threshold())),t&&(i=i.toFormat(t)),r==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,t,i){let r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),M=r.pop(),l={width:t.width,height:t.height},u=super.normalizeRegionParams(z,l),p=super.normalizeSizeParams(w,{width:u?u.w:l.width,height:u?u.h:l.height}),{x:g,y:f,w:y,h:B}=u??{x:0,y:0,w:l.width,h:l.height},{width:R,height:H}=p;console.log(`Attempting to fetch from URL: ${i}`);let $;typeof i=="string"?i.startsWith("ipfs://")?(console.log("Detected IPFS protocol URL, using verified-fetch"),$=await Oe(i)):(console.log("Using standard HTTP fetch"),$=await Re(i)):$=await Ce(M,i);let x=await $.getImage();console.log(`Source dimensions: ${x.getWidth()} x ${x.getHeight()}`),console.log(`Extracting region: x=${g}, y=${f}, w=${y}, h=${B}`),console.log(`Output size: ${R} x ${H}`);let T=await $.getImageCount();console.log(`Total images (including overviews): ${T}`);let k=x.getSamplesPerPixel(),W;k>=3?(W=[0,1,2],k>=4&&W.push(3)):W=[0],console.log("Using automatic overview selection based on resolution...");let D=Math.max(y/R,B/H),d=x,v=1;for(let I=0;I<T;I++){let q=await $.getImage(I),S=x.getWidth()/q.getWidth();S<=D&&S>v&&(v=S,d=q)}console.log(`Selected overview with scale: ${v.toFixed(2)}x`),console.log(`Overview dimensions: ${d.getWidth()} x ${d.getHeight()}`);let E=[Math.floor(g/v),Math.floor(f/v),Math.floor((g+y)/v),Math.floor((f+B)/v)],P;try{P=await d.readRasters({window:E,width:R,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}catch(I){console.log(`Failed to read from overview, falling back to main image: ${I}`);let q=[g,f,g+y,f+B];P=await x.readRasters({window:q,width:R,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}let F=W.length,N=Buffer.from(P.buffer,P.byteOffset,P.byteLength),A=b(N,{raw:{width:R,height:H,channels:F}}),m=super.normalizeRotationParams(c);this.rotationImpl(m,A);let U=super.normalizeQualityParams(a),L=super.normalizeFormatParams(h,t.format);this.qualityFormatImpl(U,L,A,h,t);let C={};return C.body=A,C.contentType=super.getContentType(L),C}iiifTransform(e,t){let i=this.enableHD?b({limitInputPixels:!1,sequentialRead:!0}):b(),r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),M=!1,l=i,u={width:t.width,height:t.height};t&&t.orientation&&(M=!0,l=l.rotate(),t.orientation>=5&&(u={width:t.height,height:t.width}));let p=super.normalizeRegionParams(z,u);this.regionImpl(p,l);let g=super.normalizeSizeParams(w,{width:p?p.w:u.width,height:p?p.h:u.height});this.sizeImpl(g,l);let f=super.normalizeRotationParams(c);this.rotationImpl(f,l);let y=super.normalizeQualityParams(a),B=super.normalizeFormatParams(h,t.format);return this.qualityFormatImpl(y,B,l,h,t),p||g||f||y||B||M?l:(console.log("skip iiif transform"),null)}async generateIiifImage(e,t,i=256){let r=this.enableHD?b(t,{limitInputPixels:!1,sequentialRead:!0}):b(t),o=e.split("/"),a=o.pop(),h=a.split(".")[0],c=a.split(".")[1],w=o.pop(),z=o.pop(),M=o.pop(),l=await r.metadata(),u={width:l.width,height:l.height},p={},g=r,f=super.normalizeRegionParams(M,u);this.regionImpl(f,g);let y=super.normalizeSizeParams(z,{width:f?f.w:u.width,height:f?f.h:u.height});this.sizeImpl(y,g);let{x:B,y:R,w:H,h:$}=f||{x:0,y:0,w:u.width,h:u.height},{width:x,height:T}=y||{width:u.width,height:u.height};try{if(H*$>x*T*i&&x<he&&T<ce&&l.pages&&l.pages>1){console.log("thumbnail");let d=Math.max(x/H,T/$),[v,E,P,F]=[Math.round(B*d),Math.round(R*d),Math.round(H*d),Math.round($*d)],[N,A]=[Math.round(u.width*d),Math.round(u.height*d)];console.log("rawMeta.pages: "+l.pages);let m=Math.max(0,l.pages-1);console.log("selectedPage1: "+m),m>=l.pages&&(console.log("Warning: Selected page exceeds available pages, using last available page"),m=Math.max(0,l.pages-1));let U=this.enableHD?await b(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).metadata():await b(t,{page:m}).metadata(),L=U.width,C=U.height;for(;m>0&&(C<A||L<N);)C*=2,L*=2,m--;(m<0||m>=l.pages)&&(console.log("Warning: Invalid page index after calculation, using page 0"),m=0),console.log("selectedPage2: "+m);let I={width:N,height:A,fastShrinkOnLoad:!1},q=this.enableHD?await b(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).resize(I).toBuffer():await b(t,{page:m}).resize(I).toBuffer(),S=this.enableHD?b(q,{limitInputPixels:!1,sequentialRead:!0}):b(q),_=await S.metadata();console.log(_),E+F>_.height&&(F=_.height-E,console.log("adjested sh: "+F)),v+P>_.width&&(P=_.width-v,console.log("adjusted sw: "+P));let se={x:v,y:E,w:P,h:F};this.regionImpl(se,S),this.sizeImpl(y,S),console.log(_.width,_.height,I.width,I.height,se,y),g=S}}catch(d){console.trace(d),console.log(d)}let k=super.normalizeRotationParams(w);this.rotationImpl(k,g);let W=super.normalizeQualityParams(h);console.log(c,l.format);let D=super.normalizeFormatParams(c,l.format);return this.qualityFormatImpl(W,D,g,c,l),console.log("pipeline "+g),p.body=g,p.contentType=super.getContentType(D),p}generateImageInfo(e,t,i=""){let r=this.version,o=this.level,a={width:t.width,height:t.height};t&&t.orientation&&t.orientation>=5&&(console.log(t.orientation),a={width:t.height,height:t.width});let h=super.generateImageInfoTemp(e,a),c=h.info;if((r==="2.0"||r==="2.1")&&(c.profile=[super.uriPattern("compliance")],o==="2")){let w={};w.formats=["jpg","png","webp","jp2","pdf","tif"],w.qualities=["color","gray","bitonal","default","native","grey"],w.supports=Ae[Number(r)],c.profile.push(w)}return r==="3.0"&&i&&(c.extraFormats=[i],c.preferredFormats=[i]),i&&(c.formats=[i]),h}};export{ie as default};
1
+ var we=Object.create;var ae=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var ze=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,be=Object.prototype.hasOwnProperty;var xe=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var $e=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ze(e))!be.call(s,r)&&r!==t&&ae(s,r,{get:()=>e[r],enumerable:!(i=ye(e,r))||i.enumerable});return s};var Pe=(s,e,t)=>(t=s!=null?we(ve(s)):{},$e(e||!s||!s.__esModule?ae(t,"default",{value:s,enumerable:!0}):t,s));var ce=xe((Ne,K)=>{"use strict";var J=Object.defineProperty,Ie=Object.getOwnPropertyDescriptor,Be=Object.getOwnPropertyNames,He=Object.prototype.hasOwnProperty,Me=(s,e)=>{for(var t in e)J(s,t,{get:e[t],enumerable:!0})},We=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Be(e))!He.call(s,r)&&r!==t&&J(s,r,{get:()=>e[r],enumerable:!(i=Ie(e,r))||i.enumerable});return s},Se=s=>We(J({},"__esModule",{value:!0}),s),le={};Me(le,{default:()=>he});K.exports=Se(le);var n="[1-9][0-9]*",ne="[0-9]*",j="(?=.*[1-9])\\d+(\\.\\d+)?",G="\\d+(\\.\\d+)?",Y=(s=>(s.jpg="image/jpeg",s.jpeg="image/jpeg",s.png="image/png",s.webp="image/webp",s.tif="image/tiff",s.tiff="image/tiff",s.gif="image/gif",s.jp2="image/jp2",s.pdf="application/pdf",s))(Y||{}),O={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${ne},${ne},${n},${n}`,`pct:${G},${G},${j},${j}`],rotation:`!?${G}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},je={1:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],1.1:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],2:["full",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],2.1:["full","max",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`],3:["max",`${n},`,`,${n}`,`pct:${j}`,`${n},${n}`,`!${n},${n}`,"\\^max",`\\^${n},`,`\\^,${n}`,`\\^pct:${j}`,`\\^${n},${n}`,`\\^!${n},${n}`]},X=/^pct:([\d,]+)/,he=class{constructor(s,e,t,i,r,o,a){this.version=s,this.level=e,this.maxArea=t,this.maxWidth=i,this.maxHeight=r,this.tileWidth=o,this.tileHeight=a,this.validate("version",s),this.validate("level",e),O.size=je[Number(s)]}validator(s){var e=O[s];return e instanceof Array&&(e=e.join("|")),new RegExp("^("+e+")$")}validate(s,e){if(!this.validator(s).test(e))throw Error(`invalid IIIF url ${s}: ${e}`);return!0}normalizeRegionParams(s,e){if(this.validate("region",s),s==="full")return null;if(s==="square")return this._regionSquare(e);if(X.test(s))return this._regionPct(s.match(X)[1],e);{let t=s.split(",").map(i=>Number(i));return this._regionXYWH(t,e)}}_regionSquare(s){let e,t,i=s.width,r=s.height;if(i!==r){let o=Math.min(i,r),a=Math.abs(Math.floor((i-r)/2));return i>r?(e=a,t=0):(e=0,t=a),this._regionXYWH([e,t,o,o],s)}return null}_regionPct(s,e){let t=s.split(",").map((i,r)=>{let o=Number(i)/100;return r===0||r===2?Math.ceil(e.width*o):r===1||r===3?Math.ceil(e.height*o):null});return this._regionXYWH(t,e)}_regionXYWH(s,e){let t=e.width,i=e.height,[r,o,a,h]=s;return r+a>t&&(a=t-r),o+h>i&&(h=i-o),{x:r,y:o,w:a,h}}normalizeSizeParams(s,e){let t=s,i=e.width,r=e.height;if(!e||!i&&!r)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",t);let o=!1;t.charAt(0)==="^"&&(o=!0,t=t.substring(1));let a=null;if(t==="full"||(t==="max"?a=this._sizeMaxScale(e):X.test(t)?a=this._sizePctScale(t.match(X)[1]):t.charAt(0)==="!"&&(t=t.substring(1),a=this._sizeBangScale(t,o,e)),a===1))return null;if(a){let h=Math.ceil(i*a),c=Math.ceil(r*a);return this._sizeWH(`${h},${c}`,o,e)}else return this._sizeWH(t,o,e)}_sizeBangScale(s,e,t){let i=t.width,r=t.height,[o,a]=s.split(",").map(c=>c===""?null:Number(c)),h=Math.min(o/i,a/r);if(o>i&&a>r&&!e)throw Error("should not upscale without ^");return h}_sizeMaxScale(s){let e=s.width,t=s.height,i=1;return this.maxArea&&this.maxArea<e*t&&(i=Math.sqrt(this.maxArea/(e*t))),this.maxWidth&&this.maxWidth<e&&(i=Math.min(i,this.maxWidth/e)),this.maxHeight&&this.maxHeight<t&&(i=Math.min(i,this.maxHeight/t)),i}_sizePctScale(s){return Number(s)/100}_sizeWH(s,e,t){let i=t.width,r=t.height,[o,a]=s.split(",").map(h=>h===""?null:Number(h));if(o?a||(a=Math.ceil(r*o/i),a=a===0?1:a):(o=Math.ceil(i*a/r),o=o===0?1:o),(o>i||a>r)&&!e)throw Error("should not upscale without ^");return{width:o,height:a}}normalizeRotationParams(s){this.validate("rotation",s);let e=!1;if(s==="0")return null;s[0]==="!"&&(e=!0);let t=Number(s.replace(/^!/,""));return{isMirror:e,degree:t}}normalizeQualityParams(s){return this.validate("quality",s),s==="native"||s==="default"?null:s}normalizeFormatParams(s,e){if((this.version==="1.0"||this.version==="1.1"||this.version==="2.0"||this.version==="2.1")&&!s)return"png";this.validate("format",s);let t=Y[s],i=Y[e];return t===i?null:s}getContentType(s){return Y[s]}generateImageInfoTemp(s,e){let t={},i={};t.info=i;let r=this.version;return r==="1.0"?(i.identifier=s,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=O.format,i.qualities=O.quality,i.profile=this.uriPattern("compliance"),t.contentType="application/json",t.body=JSON.stringify(i)):(r==="1.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=s,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=O.format,i.qualities=O.quality,i.profile=this.uriPattern("compliance")):r==="2.0"||r==="2.1"?(i["@context"]=this.uriPattern("context"),i["@id"]=s,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")]):r==="3.0"&&(i["@context"]=[this.uriPattern("context")],i.id=s,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.contentType="application/ld+json"),t}factors(s){let e=1,t=[];for(;this.tileWidth*e<=s.width||this.tileHeight*e<=s.height;)t.push(e),e*=2;return t.length===0&&t.push(1),t}uriPattern(s){let e="",t="";return this.version==="1.0"?e=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:this.version==="1.1"?(e=`http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level${this.level}`,t="http://library.stanford.edu/iiif/image-api/1.1/context.json"):this.version==="2.0"||this.version==="2.1"?(e=`http://iiif.io/api/image/2/level${this.level}.json`,t="http://iiif.io/api/image/2/context.json"):this.version==="3.0"&&(e=`level${this.level}`,t="http://iiif.io/api/image/3/context.json"),s==="compliance"?e:s==="context"?t:""}sizes(s){return[{width:s.width,height:s.height}]}};K.exports=he});var fe=Pe(ce(),1);import v from"sharp";import{addDecoder as Fe,BaseDecoder as Re,fromCustomClient as pe,fromUrl as qe,BaseClient as me,BaseResponse as de}from"geotiff";import{createVerifiedFetch as _e}from"@helia/verified-fetch";var Te=1e8,ge=1e4,ue=1e4,Ae=512,Ce=512,Q=null,V=null;async function Oe(){if(!Q){let s=await _e();Q=s.fetch||s,V=s.helia}return Q}async function Ve(){V&&(await V.stop(),V=null,Q=null)}var Ee={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"]},Z=class extends Re{async decode(e,t){let i=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,r=v(t,{sequentialRead:!0}),a=(await r.metadata()).channels||4;i===4&&a<4&&r.ensureAlpha?r=r.ensureAlpha():i===3&&a>3&&r.removeAlpha&&(r=r.removeAlpha());let{data:h,info:c}=await r.raw().toBuffer({resolveWithObject:!0});if(c.channels!==i){let w=c.width*c.height,z=Buffer.alloc(w*i),M=h;for(let l=0;l<w;l+=1){let u=l*c.channels,p=l*i;for(let g=0;g<i;g+=1)g<c.channels?z[p+g]=M[u+g]:z[p+g]=g===3?255:0}return z.buffer.slice(z.byteOffset,z.byteOffset+z.byteLength)}return h.buffer.slice(h.byteOffset,h.byteOffset+h.byteLength)}};Fe(50001,()=>Promise.resolve(Z));var ee=class extends de{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}},te=class extends me{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 ee(t)}};async function Le(s,e){let t=new te(s,e);return pe(t)}var ie=class extends de{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}},se=class extends me{constructor(e){super(e),this.ipfsUrl=e}async request({headers:e={}}={}){let t=new AbortController,i=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),t.abort()},3e4);try{let o=await(await Oe())(this.ipfsUrl,{headers:e,signal:t.signal,session:!1});if(!o.ok)throw new Error(`Failed to fetch from IPFS: ${o.status} ${o.statusText}`);let a=await o.arrayBuffer();return clearTimeout(i),new ie(o,a)}catch(r){throw clearTimeout(i),console.error("[IPFSClient] Error during request:",r),r instanceof Error&&(console.error("[IPFSClient] Error name:",r.name),console.error("[IPFSClient] Error message:",r.message),console.error("[IPFSClient] Error stack:",r.stack)),r&&typeof r=="object"&&"errors"in r&&console.error("[IPFSClient] AggregateError details:",r.errors),r}}};async function ke(s){let e=new se(s);return await pe(e)}var re=class extends fe.default{constructor(e,t,i=!1,r=Te,o=ge,a=ue,h=Ae,c=Ce){super(e,t,r,o,a,h,c),this.enableHD=i}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,i,r,o){e&&(e==="color"?i=i.toColorspace("srgb"):e==="gray"||e==="grey"?i=i.grayscale():e==="bitonal"&&(i=i.threshold())),t&&(i=i.toFormat(t)),r==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(i=i.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,t,i){let r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),M=r.pop(),l={width:t.width,height:t.height},u=super.normalizeRegionParams(z,l),p=super.normalizeSizeParams(w,{width:u?u.w:l.width,height:u?u.h:l.height}),{x:g,y:f,w:y,h:B}=u??{x:0,y:0,w:l.width,h:l.height},{width:F,height:H}=p;console.log(`Attempting to fetch from URL: ${i}`);let x;typeof i=="string"?i.startsWith("ipfs://")?(console.log("Detected IPFS protocol URL, using verified-fetch"),x=await ke(i)):(console.log("Using standard HTTP fetch"),x=await qe(i)):x=await Le(M,i);let $=await x.getImage();console.log(`Source dimensions: ${$.getWidth()} x ${$.getHeight()}`),console.log(`Extracting region: x=${g}, y=${f}, w=${y}, h=${B}`),console.log(`Output size: ${F} x ${H}`);let _=await x.getImageCount();console.log(`Total images (including overviews): ${_}`);let k=$.getSamplesPerPixel(),W;k>=3?(W=[0,1,2],k>=4&&W.push(3)):W=[0],console.log("Using automatic overview selection based on resolution...");let D=Math.max(y/F,B/H),d=$,b=1;for(let I=0;I<_;I++){let R=await x.getImage(I),S=$.getWidth()/R.getWidth();S<=D&&S>b&&(b=S,d=R)}console.log(`Selected overview with scale: ${b.toFixed(2)}x`),console.log(`Overview dimensions: ${d.getWidth()} x ${d.getHeight()}`);let E=[Math.floor(g/b),Math.floor(f/b),Math.floor((g+y)/b),Math.floor((f+B)/b)],P;try{P=await d.readRasters({window:E,width:F,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}catch(I){console.log(`Failed to read from overview, falling back to main image: ${I}`);let R=[g,f,g+y,f+B];P=await $.readRasters({window:R,width:F,height:H,samples:W,interleave:!0,resampleMethod:"bilinear"})}let T=W.length,N=Buffer.from(P.buffer,P.byteOffset,P.byteLength),A=v(N,{raw:{width:F,height:H,channels:T}}),m=super.normalizeRotationParams(c);this.rotationImpl(m,A);let U=super.normalizeQualityParams(a),L=super.normalizeFormatParams(h,t.format);this.qualityFormatImpl(U,L,A,h,t);let C={};return C.body=A,C.contentType=super.getContentType(L),C}iiifTransform(e,t){let i=this.enableHD?v({limitInputPixels:!1,sequentialRead:!0}):v(),r=e.split("/"),o=r.pop(),a=o.split(".")[0],h=o.split(".")[1],c=r.pop(),w=r.pop(),z=r.pop(),M=!1,l=i,u={width:t.width,height:t.height};t&&t.orientation&&(M=!0,l=l.rotate(),t.orientation>=5&&(u={width:t.height,height:t.width}));let p=super.normalizeRegionParams(z,u);this.regionImpl(p,l);let g=super.normalizeSizeParams(w,{width:p?p.w:u.width,height:p?p.h:u.height});this.sizeImpl(g,l);let f=super.normalizeRotationParams(c);this.rotationImpl(f,l);let y=super.normalizeQualityParams(a),B=super.normalizeFormatParams(h,t.format);return this.qualityFormatImpl(y,B,l,h,t),p||g||f||y||B||M?l:(console.log("skip iiif transform"),null)}async generateIiifImage(e,t,i=256){let r=this.enableHD?v(t,{limitInputPixels:!1,sequentialRead:!0}):v(t),o=e.split("/"),a=o.pop(),h=a.split(".")[0],c=a.split(".")[1],w=o.pop(),z=o.pop(),M=o.pop(),l=await r.metadata(),u={width:l.width,height:l.height},p={},g=r,f=super.normalizeRegionParams(M,u);this.regionImpl(f,g);let y=super.normalizeSizeParams(z,{width:f?f.w:u.width,height:f?f.h:u.height});this.sizeImpl(y,g);let{x:B,y:F,w:H,h:x}=f||{x:0,y:0,w:u.width,h:u.height},{width:$,height:_}=y||{width:u.width,height:u.height};try{if(H*x>$*_*i&&$<ge&&_<ue&&l.pages&&l.pages>1){console.log("thumbnail");let d=Math.max($/H,_/x),[b,E,P,T]=[Math.round(B*d),Math.round(F*d),Math.round(H*d),Math.round(x*d)],[N,A]=[Math.round(u.width*d),Math.round(u.height*d)];console.log("rawMeta.pages: "+l.pages);let m=Math.max(0,l.pages-1);console.log("selectedPage1: "+m),m>=l.pages&&(console.log("Warning: Selected page exceeds available pages, using last available page"),m=Math.max(0,l.pages-1));let U=this.enableHD?await v(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).metadata():await v(t,{page:m}).metadata(),L=U.width,C=U.height;for(;m>0&&(C<A||L<N);)C*=2,L*=2,m--;(m<0||m>=l.pages)&&(console.log("Warning: Invalid page index after calculation, using page 0"),m=0),console.log("selectedPage2: "+m);let I={width:N,height:A,fastShrinkOnLoad:!1},R=this.enableHD?await v(t,{limitInputPixels:!1,page:m,sequentialRead:!0}).resize(I).toBuffer():await v(t,{page:m}).resize(I).toBuffer(),S=this.enableHD?v(R,{limitInputPixels:!1,sequentialRead:!0}):v(R),q=await S.metadata();console.log(q),E+T>q.height&&(T=q.height-E,console.log("adjested sh: "+T)),b+P>q.width&&(P=q.width-b,console.log("adjusted sw: "+P));let oe={x:b,y:E,w:P,h:T};this.regionImpl(oe,S),this.sizeImpl(y,S),console.log(q.width,q.height,I.width,I.height,oe,y),g=S}}catch(d){console.trace(d),console.log(d)}let k=super.normalizeRotationParams(w);this.rotationImpl(k,g);let W=super.normalizeQualityParams(h);console.log(c,l.format);let D=super.normalizeFormatParams(c,l.format);return this.qualityFormatImpl(W,D,g,c,l),console.log("pipeline "+g),p.body=g,p.contentType=super.getContentType(D),p}generateImageInfo(e,t,i=""){let r=this.version,o=this.level,a={width:t.width,height:t.height};t&&t.orientation&&t.orientation>=5&&(console.log(t.orientation),a={width:t.height,height:t.width});let h=super.generateImageInfoTemp(e,a),c=h.info;if((r==="2.0"||r==="2.1")&&(c.profile=[super.uriPattern("compliance")],o==="2")){let w={};w.formats=["jpg","png","webp","jp2","pdf","tif"],w.qualities=["color","gray","bitonal","default","native","grey"],w.supports=Ee[Number(r)],c.profile.push(w)}return r==="3.0"&&i&&(c.extraFormats=[i],c.preferredFormats=[i]),i&&(c.formats=[i]),h}};export{Ve as closeVerifiedFetch,re as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@etu-wiki/sharp-iiif-shims",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",