@etu-wiki/sharp-iiif-shims 0.1.7 → 0.1.9
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.
- package/dist/index.mjs +1 -1
- package/package.json +2 -3
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ge=Object.create;var ee=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var pe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var de=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var we=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of fe(e))!me.call(r,s)&&s!==i&&ee(r,s,{get:()=>e[s],enumerable:!(t=ue(e,s))||t.enumerable});return r};var ye=(r,e,i)=>(i=r!=null?ge(pe(r)):{},we(e||!r||!r.__esModule?ee(i,"default",{value:r,enumerable:!0}):i,r));var se=de((Oe,X)=>{"use strict";var U=Object.defineProperty,ze=Object.getOwnPropertyDescriptor,$e=Object.getOwnPropertyNames,ve=Object.prototype.hasOwnProperty,Pe=(r,e)=>{for(var i in e)U(r,i,{get:e[i],enumerable:!0})},be=(r,e,i,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of $e(e))!ve.call(r,s)&&s!==i&&U(r,s,{get:()=>e[s],enumerable:!(t=ze(e,s))||t.enumerable});return r},xe=r=>be(U({},"__esModule",{value:!0}),r),ie={};Pe(ie,{default:()=>re});X.exports=xe(ie);var a="[1-9][0-9]*",te="[0-9]*",S="(?=.*[1-9])\\d+(\\.\\d+)?",N="\\d+(\\.\\d+)?",C=(r=>(r.jpg="image/jpeg",r.jpeg="image/jpeg",r.png="image/png",r.webp="image/webp",r.tif="image/tiff",r.tiff="image/tiff",r.gif="image/gif",r.jp2="image/jp2",r.pdf="application/pdf",r))(C||{}),R={version:["1.0","1.1","2.0","2.1","3.0"],level:["0","1","2"],region:["full","square",`${te},${te},${a},${a}`,`pct:${N},${N},${S},${S}`],rotation:`!?${N}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},Ie={1:["full",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],1.1:["full",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],2:["full",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],2.1:["full","max",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`],3:["max",`${a},`,`,${a}`,`pct:${S}`,`${a},${a}`,`!${a},${a}`,"\\^max",`\\^${a},`,`\\^,${a}`,`\\^pct:${S}`,`\\^${a},${a}`,`\\^!${a},${a}`]},O=/^pct:([\d,]+)/,re=class{constructor(r,e,i,t,s,o,n){this.version=r,this.level=e,this.maxArea=i,this.maxWidth=t,this.maxHeight=s,this.tileWidth=o,this.tileHeight=n,this.validate("version",r),this.validate("level",e),R.size=Ie[Number(r)]}validator(r){var e=R[r];return e instanceof Array&&(e=e.join("|")),new RegExp("^("+e+")$")}validate(r,e){if(!this.validator(r).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(O.test(r))return this._regionPct(r.match(O)[1],e);{let i=r.split(",").map(t=>Number(t));return this._regionXYWH(i,e)}}_regionSquare(r){let e,i,t=r.width,s=r.height;if(t!==s){let o=Math.min(t,s),n=Math.abs(Math.floor((t-s)/2));return t>s?(e=n,i=0):(e=0,i=n),this._regionXYWH([e,i,o,o],r)}return null}_regionPct(r,e){let i=r.split(",").map((t,s)=>{let o=Number(t)/100;return s===0||s===2?Math.ceil(e.width*o):s===1||s===3?Math.ceil(e.height*o):null});return this._regionXYWH(i,e)}_regionXYWH(r,e){let i=e.width,t=e.height,[s,o,n,l]=r;return s+n>i&&(n=i-s),o+l>t&&(l=t-o),{x:s,y:o,w:n,h:l}}normalizeSizeParams(r,e){let i=r,t=e.width,s=e.height;if(!e||!t&&!s)throw Error(`invalid region dimensions: ${JSON.stringify(e,null,2)}`);this.validate("size",i);let o=!1;i.charAt(0)==="^"&&(o=!0,i=i.substring(1));let n=null;if(i==="full"||(i==="max"?n=this._sizeMaxScale(e):O.test(i)?n=this._sizePctScale(i.match(O)[1]):i.charAt(0)==="!"&&(i=i.substring(1),n=this._sizeBangScale(i,o,e)),n===1))return null;if(n){let l=Math.ceil(t*n),h=Math.ceil(s*n);return this._sizeWH(`${l},${h}`,o,e)}else return this._sizeWH(i,o,e)}_sizeBangScale(r,e,i){let t=i.width,s=i.height,[o,n]=r.split(",").map(h=>h===""?null:Number(h)),l=Math.min(o/t,n/s);if(o>t&&n>s&&!e)throw Error("should not upscale without ^");return l}_sizeMaxScale(r){let e=r.width,i=r.height,t=1;return this.maxArea&&this.maxArea<e*i&&(t=Math.sqrt(this.maxArea/(e*i))),this.maxWidth&&this.maxWidth<e&&(t=Math.min(t,this.maxWidth/e)),this.maxHeight&&this.maxHeight<i&&(t=Math.min(t,this.maxHeight/i)),t}_sizePctScale(r){return Number(r)/100}_sizeWH(r,e,i){let t=i.width,s=i.height,[o,n]=r.split(",").map(l=>l===""?null:Number(l));if(o?n||(n=Math.ceil(s*o/t),n=n===0?1:n):(o=Math.ceil(t*n/s),o=o===0?1:o),(o>t||n>s)&&!e)throw Error("should not upscale without ^");return{width:o,height:n}}normalizeRotationParams(r){this.validate("rotation",r);let e=!1;if(r==="0")return null;r[0]==="!"&&(e=!0);let i=Number(r.replace(/^!/,""));return{isMirror:e,degree:i}}normalizeQualityParams(r){return this.validate("quality",r),r==="native"||r==="default"?null:r}normalizeFormatParams(r,e){if((this.version==="1.0"||this.version==="1.1"||this.version==="2.0"||this.version==="2.1")&&!r)return"png";this.validate("format",r);let i=C[r],t=C[e];return i===t?null:r}getContentType(r){return C[r]}generateImageInfoTemp(r,e){let i={},t={};i.info=t;let s=this.version;return s==="1.0"?(t.identifier=r,t.width=e.width,t.height=e.height,t.scale_factors=this.factors(e),t.tile_width=this.tileWidth,t.tile_height=this.tileHeight,t.formats=R.format,t.qualities=R.quality,t.profile=this.uriPattern("compliance"),i.contentType="application/json",i.body=JSON.stringify(t)):(s==="1.1"?(t["@context"]=this.uriPattern("context"),t["@id"]=r,t.width=e.width,t.height=e.height,t.scale_factors=this.factors(e),t.tile_width=this.tileWidth,t.tile_height=this.tileHeight,t.formats=R.format,t.qualities=R.quality,t.profile=this.uriPattern("compliance")):s==="2.0"||s==="2.1"?(t["@context"]=this.uriPattern("context"),t["@id"]=r,t.protocol="http://iiif.io/api/image",t.width=e.width,t.height=e.height,this.level==="0"?t.sizes=this.sizes(e):t.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],t.profile=[this.uriPattern("compliance")]):s==="3.0"&&(t["@context"]=[this.uriPattern("context")],t.id=r,t.type="ImageService3",t.protocol="http://iiif.io/api/image",t.width=e.width,t.height=e.height,this.level==="0"?t.sizes=this.sizes(e):t.tiles=[{scaleFactors:this.factors(e),width:this.tileWidth,height:this.tileHeight}],t.profile=this.uriPattern("compliance")),i.contentType="application/ld+json"),i}factors(r){let e=1,i=[];for(;this.tileWidth*e<=r.width||this.tileHeight*e<=r.height;)i.push(e),e*=2;return i.length===0&&i.push(1),i}uriPattern(r){let e="",i="";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}`,i="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`,i="http://iiif.io/api/image/2/context.json"):this.version==="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}]}};X.exports=re});var oe=ye(se(),1);import _ from"sharp";import{addDecoder as Be,BaseDecoder as He,fromCustomClient as ne,fromUrl as We,BaseClient as ae,BaseResponse as le}from"geotiff";var Me=1e8,Se=1e4,je=1e4,qe=512,Re=512,_e={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 He{async decode(e,i){let t=Array.isArray(e.BitsPerSample)?e.BitsPerSample.length:e.SamplesPerPixel||4,s=_(i,{sequentialRead:!0}),n=(await s.metadata()).channels||4;t===4&&n<4&&s.ensureAlpha?s=s.ensureAlpha():t===3&&n>3&&s.removeAlpha&&(s=s.removeAlpha());let{data:l,info:h}=await s.raw().toBuffer({resolveWithObject:!0});if(h.channels!==t){let m=h.width*h.height,z=Buffer.alloc(m*t),u=l;for(let c=0;c<m;c+=1){let p=c*h.channels,d=c*t;for(let g=0;g<t;g+=1)g<h.channels?z[d+g]=u[p+g]:z[d+g]=g===3?255:0}return z.buffer.slice(z.byteOffset,z.byteOffset+z.byteLength)}return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}};Be(50001,()=>Promise.resolve(Y));var Q=class extends le{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}},G=class extends ae{constructor(e,i){super(e),this.objectKey=e,this.ossClient=i}async request({headers:e={}}={}){let i=await this.ossClient.get(this.objectKey,{headers:e,timeout:3e4});return new Q(i)}};async function Fe(r,e){let i=new G(r,e);return ne(i)}var J=class extends le{constructor(e,i){super(),this.response=e,this.arrayBuffer=i}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(e){return this.response.headers.get(e)||""}getData(){return this.arrayBuffer}},K=class extends ae{constructor(e,i){super(e),this.ipfsUrl=e,this.verifiedFetch=i}async request({headers:e={}}={}){let i=new AbortController,t=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),i.abort()},3e4);try{let s=await this.verifiedFetch(this.ipfsUrl,{headers:e,signal:i.signal,session:!1});if(!s.ok)throw new Error(`Failed to fetch from IPFS: ${s.status} ${s.statusText}`);let o=await s.arrayBuffer();return clearTimeout(t),new J(s,o)}catch(s){throw clearTimeout(t),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 Ae(r,e){let i=new K(r,e);return await ne(i)}var V=class extends oe.default{constructor(e,i,t=!1,s=Me,o=Se,n=je,l=qe,h=Re){super(e,i,s,o,n,l,h),this.enableHD=t}regionImpl(e,i){e&&(i=i.extract({left:e.x,top:e.y,width:e.w,height:e.h}))}sizeImpl(e,i){e&&(i=i.resize({...e,fit:"fill"}))}rotationImpl(e,i){e&&(e.isMirror&&(i=i.flop()),i=i.rotate(e.degree))}qualityFormatImpl(e,i,t,s,o){e&&(e==="color"?t=t.toColorspace("srgb"):e==="gray"||e==="grey"?t=t.grayscale():e==="bitonal"&&(t=t.threshold())),i&&(t=t.toFormat(i)),s==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(t=t.toColorspace("b-w").png({colors:2}))}async generateImageTile(e,i,t){let s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),z=s.pop(),u=s.pop(),c={width:i.width,height:i.height},p=super.normalizeRegionParams(z,c),d=super.normalizeSizeParams(m,{width:p?p.w:c.width,height:p?p.h:c.height}),{x:g,y:P,w:I,h:v}=p??{x:0,y:0,w:c.width,h:c.height},{width:B,height:H}=d;console.log(`Attempting to fetch from URL: ${t}`);let b;typeof t=="string"?(console.log("Using standard HTTP fetch"),b=await We(t)):typeof u=="string"&&u.startsWith("bafy")?(console.log("Detected CID id, using fromIPFS"),b=await Ae(`ipfs://${u}`,t)):b=await Fe(u,t);let f=await b.getImage();console.log(`Source dimensions: ${f.getWidth()} x ${f.getHeight()}`),console.log(`Extracting region: x=${g}, y=${P}, w=${I}, h=${v}`),console.log(`Output size: ${B} x ${H}`);let w=await b.getImageCount();console.log(`Total images (including overviews): ${w}`);let q=f.getSamplesPerPixel(),x;q>=3?(x=[0,1,2],q>=4&&x.push(3)):x=[0],console.log("Using automatic overview selection based on resolution...");let E=Math.max(I/B,v/H),j=f,W=1;for(let A=0;A<w;A++){let T=await b.getImage(A),D=f.getWidth()/T.getWidth();D<=E&&D>W&&(W=D,j=T)}console.log(`Selected overview with scale: ${W.toFixed(2)}x`),console.log(`Overview dimensions: ${j.getWidth()} x ${j.getHeight()}`);let M=[Math.floor(g/W),Math.floor(P/W),Math.floor((g+I)/W),Math.floor((P+v)/W)],y;try{y=await j.readRasters({window:M,width:B,height:H,samples:x,interleave:!0,resampleMethod:"bilinear"})}catch(A){console.log(`Failed to read from overview, falling back to main image: ${A}`);let T=[g,P,g+I,P+v];y=await f.readRasters({window:T,width:B,height:H,samples:x,interleave:!0,resampleMethod:"bilinear"})}let $=x.length,L=Buffer.from(y.buffer,y.byteOffset,y.byteLength),F=_(L,{raw:{width:B,height:H,channels:$}}),he=super.normalizeRotationParams(h);this.rotationImpl(he,F);let ce=super.normalizeQualityParams(n),Z=super.normalizeFormatParams(l,i.format);this.qualityFormatImpl(ce,Z,F,l,i);let k={};return k.body=F,k.contentType=super.getContentType(Z),k}iiifTransform(e,i){let t=this.enableHD?_({limitInputPixels:!1,sequentialRead:!0}):_(),s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),z=s.pop(),u=!1,c=t,p={width:i.width,height:i.height};i&&i.orientation&&(u=!0,c=c.rotate(),i.orientation>=5&&(p={width:i.height,height:i.width}));let d=super.normalizeRegionParams(z,p);this.regionImpl(d,c);let g=super.normalizeSizeParams(m,{width:d?d.w:p.width,height:d?d.h:p.height});this.sizeImpl(g,c);let P=super.normalizeRotationParams(h);this.rotationImpl(P,c);let I=super.normalizeQualityParams(n),v=super.normalizeFormatParams(l,i.format);return this.qualityFormatImpl(I,v,c,l,i),d||g||P||I||v||u?c:(console.log("skip iiif transform"),null)}async generateIiifImage(e,i,t){let s=e.split("/"),o=s.pop(),n=o.split(".")[0],l=o.split(".")[1],h=s.pop(),m=s.pop(),z=s.pop(),u=super.normalizeRegionParams(z,t),c=super.normalizeSizeParams(m,{width:u?u.w:t.width,height:u?u.h:t.height}),p=super.normalizeRotationParams(h),d=super.normalizeQualityParams(n),g=super.normalizeFormatParams(l,t.format),{x:P,y:I,w:v,h:B}=u||{x:0,y:0,w:t.width,h:t.height},{width:H,height:b}=c||{width:t.width,height:t.height},f=0,w;if(t.pages&&t.pages>1){let x=H/v,E=b/B,j=Math.max(x,E);if(j>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),f=0;else{f=t.pages-1;let M=Math.pow(2,t.pages-1),y=t.width/M,$=t.height/M;for(;f>0;){let L=v*(y/t.width),F=B*($/t.height);if(L>=H*1.1&&F>=b*1.1)break;f--,y*=2,$*=2}console.log(`Pyramid optimization: selected page ${f}/${t.pages-1} (scale: ${j.toFixed(2)}x, target: ${H}x${b})`)}let W=this.enableHD?{limitInputPixels:!1,page:f,sequentialRead:!0,failOn:"none"}:{page:f,sequentialRead:!0,failOn:"none"};if(w=_(i,W),u&&f>0){let M=await w.metadata(),y=M.width/t.width,$={x:Math.floor(P*y),y:Math.floor(I*y),w:Math.floor(v*y),h:Math.floor(B*y)};$.w=Math.min($.w,M.width-$.x),$.h=Math.min($.h,M.height-$.y),this.regionImpl($,w)}else this.regionImpl(u,w)}else{let x=this.enableHD?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};w=_(i,x),this.regionImpl(u,w)}this.sizeImpl(c,w),this.rotationImpl(p,w),this.qualityFormatImpl(d,g,w,l,t);let q={};return q.body=w,q.contentType=super.getContentType(g),q}generateImageInfo(e,i,t=""){let s=this.version,o=this.level,n={width:i.width,height:i.height};i&&i.orientation&&i.orientation>=5&&(console.log(i.orientation),n={width:i.height,height:i.width});let l=super.generateImageInfoTemp(e,n),h=l.info;if((s==="2.0"||s==="2.1")&&(h.profile=[super.uriPattern("compliance")],o==="2")){let m={};m.formats=["jpg","png","webp","jp2","pdf","tif"],m.qualities=["color","gray","bitonal","default","native","grey"],m.supports=_e[Number(s)],h.profile.push(m)}return s==="3.0"&&t&&(h.extraFormats=[t],h.preferredFormats=[t]),t&&(h.formats=[t]),l}};export{V as default};
|
|
1
|
+
import A from"sharp";var a="[1-9][0-9]*",te="[0-9]*",M="(?=.*[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},${a},${a}`,`pct:${U},${U},${M},${M}`],rotation:`!?${U}`,quality:["color","gray","bitonal","default","native","grey"],format:["jpg","png","webp","tif","gif","jp2","pdf"],size:[""]},he={1:["full",`${a},`,`,${a}`,`pct:${M}`,`${a},${a}`,`!${a},${a}`],1.1:["full",`${a},`,`,${a}`,`pct:${M}`,`${a},${a}`,`!${a},${a}`],2:["full",`${a},`,`,${a}`,`pct:${M}`,`${a},${a}`,`!${a},${a}`],2.1:["full","max",`${a},`,`,${a}`,`pct:${M}`,`${a},${a}`,`!${a},${a}`],3:["max",`${a},`,`,${a}`,`pct:${M}`,`${a},${a}`,`!${a},${a}`,"\\^max",`\\^${a},`,`\\^,${a}`,`\\^pct:${M}`,`\\^${a},${a}`,`\\^!${a},${a}`]},j=/^pct:([\d,]+)/,ie=class{constructor(s,i,t,e,r,o,n){this.version=s,this.level=i,this.maxArea=t,this.maxWidth=e,this.maxHeight=r,this.tileWidth=o,this.tileHeight=n,this.validate("version",s),this.validate("level",i),q.size=he[Number(s)]}validator(s){let i=q[s];return i instanceof Array&&(i=i.join("|")),new RegExp("^("+i+")$")}validate(s,i){if(!this.validator(s).test(i))throw Error(`invalid IIIF url ${s}: ${i}`);return!0}normalizeRegionParams(s,i){if(this.validate("region",s),s==="full")return null;if(s==="square")return this._regionSquare(i);if(j.test(s))return this._regionPct(s.match(j)[1],i);{let t=s.split(",").map(e=>Number(e));return this._regionXYWH(t,i)}}_regionSquare(s){let i,t,e=s.width,r=s.height;if(e!==r){let o=Math.min(e,r),n=Math.abs(Math.floor((e-r)/2));return e>r?(i=n,t=0):(i=0,t=n),this._regionXYWH([i,t,o,o],s)}return null}_regionPct(s,i){let t=s.split(",").map((e,r)=>{let o=Number(e)/100;return r===0||r===2?Math.ceil(i.width*o):r===1||r===3?Math.ceil(i.height*o):null});return this._regionXYWH(t,i)}_regionXYWH(s,i){let t=i.width,e=i.height,[r,o,n,l]=s;if(r+n>t&&(n=t-r),o+l>e&&(l=e-o),n<=0)throw Error(`invalid IIIF width ${n}`);if(l<=0)throw Error(`invalid IIIF height ${l}`);return{x:r,y:o,w:n,h:l}}normalizeSizeParams(s,i){let t=s,e=i.width,r=i.height;if(!i||!e&&!r)throw Error(`invalid region dimensions: ${JSON.stringify(i,null,2)}`);this.validate("size",t);let o=!1;t.charAt(0)==="^"&&(o=!0,t=t.substring(1));let n=null;if(t==="full"||(t==="max"?n=this._sizeMaxScale(i):j.test(t)?n=this._sizePctScale(t.match(j)[1]):t.charAt(0)==="!"&&(t=t.substring(1),n=this._sizeBangScale(t,o,i)),n===1))return null;if(n){let l=Math.ceil(e*n),h=Math.ceil(r*n);return this._sizeWH(`${l},${h}`,o,i)}else return this._sizeWH(t,o,i)}_sizeBangScale(s,i,t){let e=t.width,r=t.height,[o,n]=s.split(",").map(h=>h===""?null:Number(h)),l=Math.min(o/e,n/r);if(o>e&&n>r&&!i)throw Error("should not upscale without ^");return l}_sizeMaxScale(s){let i=s.width,t=s.height,e=1;return this.maxArea&&this.maxArea<i*t&&(e=Math.sqrt(this.maxArea/(i*t))),this.maxWidth&&this.maxWidth<i&&(e=Math.min(e,this.maxWidth/i)),this.maxHeight&&this.maxHeight<t&&(e=Math.min(e,this.maxHeight/t)),e}_sizePctScale(s){return Number(s)/100}_sizeWH(s,i,t){let e=t.width,r=t.height,[o,n]=s.split(",").map(l=>l===""?null:Number(l));if(o?n||(n=Math.ceil(r*o/e),n=n===0?1:n):(o=Math.ceil(e*n/r),o=o===0?1:o),(o>e||n>r)&&!i)throw Error("should not upscale without ^");return{width:o,height:n}}normalizeRotationParams(s){this.validate("rotation",s);let i=!1;if(s==="0")return null;s[0]==="!"&&(i=!0);let t=Number(s.replace(/^!/,""));return{isMirror:i,degree:t}}normalizeQualityParams(s){return this.validate("quality",s),s==="native"||s==="default"?null:s}normalizeFormatParams(s,i){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=G[s],e=G[i];return t===e?null:s}getContentType(s){return G[s]}generateImageInfoTemp(s,i){let t={},e={};t.info=e;let r=this.version;return r==="1.0"?(e.identifier=s,e.width=i.width,e.height=i.height,e.scale_factors=this.factors(i),e.tile_width=this.tileWidth,e.tile_height=this.tileHeight,e.formats=q.format,e.qualities=q.quality,e.profile=this.uriPattern("compliance"),t.contentType="application/json",t.body=JSON.stringify(e)):(r==="1.1"?(e["@context"]=this.uriPattern("context"),e["@id"]=s,e.width=i.width,e.height=i.height,e.scale_factors=this.factors(i),e.tile_width=this.tileWidth,e.tile_height=this.tileHeight,e.formats=q.format,e.qualities=q.quality,e.profile=this.uriPattern("compliance")):r==="2.0"||r==="2.1"?(e["@context"]=this.uriPattern("context"),e["@id"]=s,e.protocol="http://iiif.io/api/image",e.width=i.width,e.height=i.height,this.level==="0"?e.sizes=this.sizes(i):e.tiles=[{scaleFactors:this.factors(i),width:this.tileWidth,height:this.tileHeight}],e.profile=[this.uriPattern("compliance")]):r==="3.0"&&(e["@context"]=[this.uriPattern("context")],e.id=s,e.type="ImageService3",e.protocol="http://iiif.io/api/image",e.width=i.width,e.height=i.height,this.level==="0"?e.sizes=this.sizes(i):e.tiles=[{scaleFactors:this.factors(i),width:this.tileWidth,height:this.tileHeight}],e.profile=this.uriPattern("compliance")),t.contentType="application/ld+json"),t}factors(s){let i=1,t=[];for(;this.tileWidth*i<=s.width||this.tileHeight*i<=s.height;)t.push(i),i*=2;return t.length===0&&t.push(1),t}uriPattern(s){let i="",t="";return this.version==="1.0"?i=`http://library.stanford.edu/iiif/image-api/compliance.html#level${this.level}`:this.version==="1.1"?(i=`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"?(i=`http://iiif.io/api/image/2/level${this.level}.json`,t="http://iiif.io/api/image/2/context.json"):this.version==="3.0"&&(i=`level${this.level}`,t="http://iiif.io/api/image/3/context.json"),s==="compliance"?i:s==="context"?t:""}sizes(s){return[{width:s.width,height:s.height}]}};import{addDecoder as ce,BaseDecoder as ge,fromCustomClient as re,fromUrl as ue,BaseClient as oe,BaseResponse as ne}from"geotiff";var fe=1e8,pe=1e4,me=1e4,de=512,we=512,ye={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 ge{async decode(i,t){let e=Array.isArray(i.BitsPerSample)?i.BitsPerSample.length:i.SamplesPerPixel||4,r=A(t,{sequentialRead:!0}),n=(await r.metadata()).channels||4;e===4&&n<4&&r.ensureAlpha?r=r.ensureAlpha():e===3&&n>3&&r.removeAlpha&&(r=r.removeAlpha());let{data:l,info:h}=await r.raw().toBuffer({resolveWithObject:!0});if(h.channels!==e){let m=h.width*h.height,c=Buffer.alloc(m*e),g=l;for(let u=0;u<m;u+=1){let w=u*h.channels,z=u*e;for(let f=0;f<e;f+=1)f<h.channels?c[z+f]=g[w+f]:c[z+f]=f===3?255:0}return c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength)}return l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength)}};ce(50001,()=>Promise.resolve(Y));var K=class extends ne{constructor(i){super(),this.result=i}get ok(){return this.result.res.status>=200&&this.result.res.status<300}get status(){return this.result.res.status}getHeader(i){return this.result.res.headers[i.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(i,t){super(i),this.objectKey=i,this.ossClient=t}async request({headers:i={}}={}){let t=await this.ossClient.get(this.objectKey,{headers:i,timeout:3e4});return new K(t)}};async function $e(s,i){let t=new Q(s,i);return re(t)}var ze=new Map,Pe=new Map,O=new Map,E=new Map,J=class extends ne{constructor(i,t){super(),this.response=i,this.arrayBuffer=t}get ok(){return this.response.ok}get status(){return this.response.status}getHeader(i){return this.response.headers.get(i)||""}getData(){return this.arrayBuffer}},Z=class extends oe{constructor(i,t,e,r){super(i),this.ipfsUrl=i,this.verifiedFetch=t,this.peerCache=e,this.inFlightRequests=r}extractCID(i){let t=i.match(/(?:ipfs:\/\/|\/ipfs\/)([a-zA-Z0-9]+)/);return t?t[1]:null}async request({headers:i={}}={}){let t=this.extractCID(this.ipfsUrl),e=t?this.peerCache?.get(t):null,r=e==="discovering",o=e&&Array.isArray(e)&&e.length>0,n=e&&Array.isArray(e),l=n?3e4:6e4,h=new AbortController,m=setTimeout(()=>{console.log("[IPFSClient] Request timeout, aborting..."),h.abort()},l);try{let c={headers:i,signal:h.signal,session:!1};t&&(n?console.log(`[IPFSClient] Using fast path for previously accessed ${t}`):(console.log(`[IPFSClient] First fetch for ${t}, using HTTP gateways...`),this.peerCache&&this.peerCache.set(t,"discovering")));let g=await this.verifiedFetch(this.ipfsUrl,c);if(!g.ok)throw new Error(`Failed to fetch from IPFS: ${g.status} ${g.statusText}`);let u=await g.arrayBuffer();return clearTimeout(m),t&&this.peerCache&&this.peerCache.get(t)==="discovering"&&(this.peerCache.set(t,[]),console.log(`[IPFSClient] Marked ${t} as discovered`)),new J(g,u)}catch(c){throw clearTimeout(m),t&&this.peerCache&&this.peerCache.get(t)==="discovering"&&this.peerCache.delete(t),console.error("[IPFSClient] Error during request:",c),c instanceof Error&&(console.error("[IPFSClient] Error name:",c.name),console.error("[IPFSClient] Error message:",c.message),console.error("[IPFSClient] Error stack:",c.stack)),c&&typeof c=="object"&&"errors"in c&&console.error("[IPFSClient] AggregateError details:",c.errors),c}}};async function se(s,i,t){let e=`${t}:${i}`,r=E.get(e);if(r)return r instanceof Promise?await r:r;let o=s.getImage(i);E.set(e,o);try{let n=await o;return E.set(e,n),n}catch(n){throw E.delete(e),n}}async function ve(s,i){let t=O.get(s);if(t)return t instanceof Promise?(console.log(`[fromIPFS] Waiting for in-flight GeoTIFF creation for ${s}`),await t):(console.log(`[fromIPFS] Using cached GeoTIFF client for ${s}`),t);console.log(`[fromIPFS] Creating new GeoTIFF client for ${s}`);let e=(async()=>{let r=new Z(s,i,ze,Pe),o=await re(r,{cacheSize:128*1024*1024,blockSize:65536});return O.set(s,o),o})();O.set(s,e);try{return await e}catch(r){throw O.delete(s),r}}var V=class extends ie{constructor(i,t,e=!1,r=fe,o=pe,n=me,l=de,h=we){super(i,t,r,o,n,l,h),this.enableHD=e}regionImpl(i,t){i&&(t=t.extract({left:i.x,top:i.y,width:i.w,height:i.h}))}sizeImpl(i,t){i&&(t=t.resize({...i,fit:"fill"}))}rotationImpl(i,t){i&&(i.isMirror&&(t=t.flop()),t=t.rotate(i.degree))}qualityFormatImpl(i,t,e,r,o){i&&(i==="color"?e=e.toColorspace("srgb"):i==="gray"||i==="grey"?e=e.grayscale():i==="bitonal"&&(e=e.threshold())),t&&(e=e.toFormat(t)),r==="png"&&(o.paletteBitDepth===1||o.space==="b-w")&&(e=e.toColorspace("b-w").png({colors:2}))}async generateImageTile(i,t,e){let r=i.split("/"),o=r.pop(),n=o.split(".")[0],l=o.split(".")[1],h=r.pop(),m=r.pop(),c=r.pop(),g=r.pop(),u={width:t.width,height:t.height},w=super.normalizeRegionParams(c,u),z=super.normalizeSizeParams(m,{width:w?w.w:u.width,height:w?w.h:u.height}),{x:f,y:v,w:I,h:P}=w??{x:0,y:0,w:u.width,h:u.height},{width:b,height:S}=z;console.log(`Attempting to fetch from URL: ${e}`);let x,y;typeof e=="string"?(console.log("Using standard HTTP fetch"),x=await ue(e),y=e):typeof g=="string"&&g.startsWith("bafy")?(console.log("Detected CID id, using fromIPFS"),y=`ipfs://${g}`,x=await ve(y,e)):(x=await $e(g,e),y=`oss://${g}`);let p=await se(x,0,y);console.log(`Source dimensions: ${p.getWidth()} x ${p.getHeight()}`),console.log(`Extracting region: x=${f}, y=${v}, w=${I}, h=${P}`),console.log(`Output size: ${b} x ${S}`);let C=await x.getImageCount();console.log(`Total images (including overviews): ${C}`);let H=p.getSamplesPerPixel(),F;H>=3?(F=[0,1,2],H>=4&&F.push(3)):F=[0],console.log("Using automatic overview selection based on resolution...");let T=Math.max(I/b,P/S),W=p,$=1;for(let R=0;R<C;R++){let _=await se(x,R,y),X=p.getWidth()/_.getWidth();X<=T&&X>$&&($=X,W=_)}console.log(`Selected overview with scale: ${$.toFixed(2)}x`),console.log(`Overview dimensions: ${W.getWidth()} x ${W.getHeight()}`);let B=[Math.floor(f/$),Math.floor(v/$),Math.floor((f+I)/$),Math.floor((v+P)/$)],d;try{d=await W.readRasters({window:B,width:b,height:S,samples:F,interleave:!0,resampleMethod:"bilinear"})}catch(R){console.log(`Failed to read from overview, falling back to main image: ${R}`);let _=[f,v,f+I,v+P];d=await p.readRasters({window:_,width:b,height:S,samples:F,interleave:!0,resampleMethod:"bilinear"})}let k=F.length,L=Buffer.from(d.buffer,d.byteOffset,d.byteLength),D=A(L,{raw:{width:b,height:S,channels:k}}),ae=super.normalizeRotationParams(h);this.rotationImpl(ae,D);let le=super.normalizeQualityParams(n),ee=super.normalizeFormatParams(l,t.format);this.qualityFormatImpl(le,ee,D,l,t);let N={};return N.body=D,N.contentType=super.getContentType(ee),N}iiifTransform(i,t){let e=this.enableHD?A({limitInputPixels:!1,sequentialRead:!0}):A(),r=i.split("/"),o=r.pop(),n=o.split(".")[0],l=o.split(".")[1],h=r.pop(),m=r.pop(),c=r.pop(),g=!1,u=e,w={width:t.width,height:t.height};t&&t.orientation&&(g=!0,u=u.rotate(),t.orientation>=5&&(w={width:t.height,height:t.width}));let z=super.normalizeRegionParams(c,w);this.regionImpl(z,u);let f=super.normalizeSizeParams(m,{width:z?z.w:w.width,height:z?z.h:w.height});this.sizeImpl(f,u);let v=super.normalizeRotationParams(h);this.rotationImpl(v,u);let I=super.normalizeQualityParams(n),P=super.normalizeFormatParams(l,t.format);return this.qualityFormatImpl(I,P,u,l,t),z||f||v||I||P||g?u:(console.log("skip iiif transform"),null)}async generateIiifImage(i,t,e){let r=i.split("/"),o=r.pop(),n=o.split(".")[0],l=o.split(".")[1],h=r.pop(),m=r.pop(),c=r.pop(),g=super.normalizeRegionParams(c,e),u=super.normalizeSizeParams(m,{width:g?g.w:e.width,height:g?g.h:e.height}),w=super.normalizeRotationParams(h),z=super.normalizeQualityParams(n),f=super.normalizeFormatParams(l,e.format),{x:v,y:I,w:P,h:b}=g||{x:0,y:0,w:e.width,h:e.height},{width:S,height:x}=u||{width:e.width,height:e.height},y=0,p;if(e.pages&&e.pages>1){let H=S/P,F=x/b,T=Math.max(H,F);if(T>=.95)console.log("Pyramid optimization: using full resolution page (scale \u2248 1.0)"),y=0;else{y=e.pages-1;let $=Math.pow(2,e.pages-1),B=e.width/$,d=e.height/$;for(;y>0;){let k=P*(B/e.width),L=b*(d/e.height);if(k>=S*1.1&&L>=x*1.1)break;y--,B*=2,d*=2}console.log(`Pyramid optimization: selected page ${y}/${e.pages-1} (scale: ${T.toFixed(2)}x, target: ${S}x${x})`)}let W=this.enableHD?{limitInputPixels:!1,page:y,sequentialRead:!0,failOn:"none"}:{page:y,sequentialRead:!0,failOn:"none"};if(p=A(t,W),g&&y>0){let $=await p.metadata(),B=$.width/e.width,d={x:Math.floor(v*B),y:Math.floor(I*B),w:Math.floor(P*B),h:Math.floor(b*B)};d.w=Math.min(d.w,$.width-d.x),d.h=Math.min(d.h,$.height-d.y),this.regionImpl(d,p)}else this.regionImpl(g,p)}else{let H=this.enableHD?{limitInputPixels:!1,sequentialRead:!0,failOn:"none"}:{sequentialRead:!0,failOn:"none"};p=A(t,H),this.regionImpl(g,p)}this.sizeImpl(u,p),this.rotationImpl(w,p),this.qualityFormatImpl(z,f,p,l,e);let C={};return C.body=p,C.contentType=super.getContentType(f),C}generateImageInfo(i,t,e=""){let r=this.version,o=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 l=super.generateImageInfoTemp(i,n),h=l.info;if((r==="2.0"||r==="2.1")&&(h.profile=[super.uriPattern("compliance")],o==="2")){let m={};m.formats=["jpg","png","webp","jp2","pdf","tif"],m.qualities=["color","gray","bitonal","default","native","grey"],m.supports=ye[Number(r)],h.profile.push(m)}return r==="3.0"&&e&&(h.extraFormats=[e],h.preferredFormats=[e]),e&&(h.formats=[e]),l}};export{V 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
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -30,8 +30,7 @@
|
|
|
30
30
|
"dist"
|
|
31
31
|
],
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@etu-wiki/iiif-image-shims": "^0.0.
|
|
34
|
-
"@helia/verified-fetch": "^3.2.3",
|
|
33
|
+
"@etu-wiki/iiif-image-shims": "^0.0.28",
|
|
35
34
|
"geotiff": "^2.1.3"
|
|
36
35
|
},
|
|
37
36
|
"peerDependencies": {
|