@aboutgeo/pdiiif 0.0.0-stage → 0.2.7
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/README.md +169 -2
- package/dist/__tests__/parser.test.d.ts +1 -0
- package/dist/__tests__/pdf.spec.d.ts +1 -0
- package/dist/__tests__/region.test.d.ts +1 -0
- package/dist/__tests__/setupJest.d.ts +0 -0
- package/dist/assets/optimization.worker-C8u4PFfM.js +886 -0
- package/dist/assets/optimization.worker-C8u4PFfM.js.map +1 -0
- package/dist/convert.d.ts +223 -0
- package/dist/download.d.ts +115 -0
- package/dist/iiif.d.ts +110 -0
- package/dist/index.cjs +65 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +11137 -0
- package/dist/index.mjs.map +1 -0
- package/dist/io.d.ts +75 -0
- package/dist/log.d.ts +21 -0
- package/dist/metrics.d.ts +10 -0
- package/dist/ocr.d.ts +36 -0
- package/dist/optimization.d.ts +48 -0
- package/dist/optimization.worker.d.ts +1 -0
- package/dist/pdf/annos-text.d.ts +19 -0
- package/dist/pdf/annos.d.ts +4 -0
- package/dist/pdf/common.d.ts +48 -0
- package/dist/pdf/generator.d.ts +197 -0
- package/dist/pdf/image.d.ts +34 -0
- package/dist/pdf/parser.d.ts +131 -0
- package/dist/pdf/pkzip.d.ts +23 -0
- package/dist/pdf/png.d.ts +34 -0
- package/dist/pdf/util.d.ts +18 -0
- package/dist/res/licenses.d.ts +7 -0
- package/dist/res/srgbColorspace.d.ts +2 -0
- package/dist/util.d.ts +8 -0
- package/dist/version.d.ts +2 -0
- package/package.json +149 -4
- package/src/__tests__/fixtures/deep_toc.json +2953 -0
- package/src/__tests__/fixtures/flat_toc.json +2917 -0
- package/src/__tests__/fixtures/physdim.json +294 -0
- package/src/__tests__/fixtures/region_target.json +58 -0
- package/src/__tests__/fixtures/wunder.jpg +0 -0
- package/src/__tests__/parser.test.ts +42 -0
- package/src/__tests__/pdf.spec.ts +216 -0
- package/src/__tests__/region.test.ts +194 -0
- package/src/__tests__/setupJest.ts +2 -0
- package/src/convert.ts +1098 -0
- package/src/download.ts +703 -0
- package/src/global.d.ts +10 -0
- package/src/iiif.ts +605 -0
- package/src/index.ts +7 -0
- package/src/io.ts +243 -0
- package/src/log.ts +51 -0
- package/src/metrics.ts +47 -0
- package/src/ocr.ts +176 -0
- package/src/optimization.ts +201 -0
- package/src/optimization.worker.ts +118 -0
- package/src/pdf/annos-text.ts +382 -0
- package/src/pdf/annos.ts +240 -0
- package/src/pdf/common.ts +158 -0
- package/src/pdf/generator.ts +1665 -0
- package/src/pdf/image.ts +340 -0
- package/src/pdf/parser.ts +811 -0
- package/src/pdf/pkzip.ts +228 -0
- package/src/pdf/png.ts +397 -0
- package/src/pdf/util.ts +111 -0
- package/src/res/licenses.ts +266 -0
- package/src/res/srgbColorspace.ts +405 -0
- package/src/types.d.ts +6 -0
- package/src/util.ts +55 -0
- package/src/version.ts +1 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"use strict";var ll=Object.defineProperty;var cl=(e,t,r)=>t in e?ll(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var v=(e,t,r)=>cl(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const hr=require("prom-client"),ul=require("events"),dn=require("util"),hl=require("zlib"),fl=require("crypto");class fs{constructor(t="warn"){v(this,"level");this.level=t}setLevel(t){this.level=t}debug(t,...r){this.level==="debug"&&console.debug(t,...r)}info(t,...r){this.level!=="error"&&this.level!=="warn"&&console.info(t,...r)}warn(t,...r){this.level!=="error"&&console.warn(t,...r)}error(t,...r){console.error(t,...r)}}let k=new fs;function dl(e){k=e}const pl=new Error("request for lock canceled");var gl=function(e,t,r,i){function n(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function o(c){try{h(i.next(c))}catch(u){a(u)}}function l(c){try{h(i.throw(c))}catch(u){a(u)}}function h(c){c.done?s(c.value):n(c.value).then(o,l)}h((i=i.apply(e,t||[])).next())})};class ml{constructor(t,r=pl){this._value=t,this._cancelError=r,this._weightedQueues=[],this._weightedWaiters=[]}acquire(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise((r,i)=>{this._weightedQueues[t-1]||(this._weightedQueues[t-1]=[]),this._weightedQueues[t-1].push({resolve:r,reject:i}),this._dispatch()})}runExclusive(t,r=1){return gl(this,void 0,void 0,function*(){const[i,n]=yield this.acquire(r);try{return yield t(i)}finally{n()}})}waitForUnlock(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);return new Promise(r=>{this._weightedWaiters[t-1]||(this._weightedWaiters[t-1]=[]),this._weightedWaiters[t-1].push(r),this._dispatch()})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(t){this._value=t,this._dispatch()}release(t=1){if(t<=0)throw new Error(`invalid weight ${t}: must be positive`);this._value+=t,this._dispatch()}cancel(){this._weightedQueues.forEach(t=>t.forEach(r=>r.reject(this._cancelError))),this._weightedQueues=[]}_dispatch(){var t;for(let r=this._value;r>0;r--){const i=(t=this._weightedQueues[r-1])===null||t===void 0?void 0:t.shift();if(!i)continue;const n=this._value,s=r;this._value-=r,r=this._value+1,i.resolve([n,this._newReleaser(s)])}this._drainUnlockWaiters()}_newReleaser(t){let r=!1;return()=>{r||(r=!0,this.release(t))}}_drainUnlockWaiters(){for(let t=this._value;t>0;t--)this._weightedWaiters[t-1]&&(this._weightedWaiters[t-1].forEach(r=>r()),this._weightedWaiters[t-1]=[])}}var vl=function(e,t,r,i){function n(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function o(c){try{h(i.next(c))}catch(u){a(u)}}function l(c){try{h(i.throw(c))}catch(u){a(u)}}function h(c){c.done?s(c.value):n(c.value).then(o,l)}h((i=i.apply(e,t||[])).next())})};class yl{constructor(t){this._semaphore=new ml(1,t)}acquire(){return vl(this,void 0,void 0,function*(){const[,t]=yield this._semaphore.acquire();return t})}runExclusive(t){return this._semaphore.runExclusive(()=>t())}isLocked(){return this._semaphore.isLocked()}waitForUnlock(){return this._semaphore.waitForUnlock()}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}var Ct;let W=(Ct=class{},v(Ct,"Text",1),v(Ct,"ProcessingInstruction",2),v(Ct,"SGMLDeclaration",4),v(Ct,"Doctype",8),v(Ct,"Comment",16),v(Ct,"OpenTagStart",32),v(Ct,"Attribute",64),v(Ct,"OpenTag",128),v(Ct,"CloseTag",256),v(Ct,"Cdata",512),Ct),Wr=class{constructor(t,r=0){v(this,"data");v(this,"cache",{});v(this,"ptr");this.data=t,this.ptr=r}},bl=class{constructor(t,r){v(this,"line");v(this,"character");this.line=t,this.character=r}};var pn;(function(e){e[e.Normal=0]="Normal",e[e.JSX=1]="JSX"})(pn||(pn={}));let ds=class extends Wr{constructor(r,i=0){super(r,i);v(this,"type");v(this,"name");v(this,"value");this.type=r[i],i+=1;const n=St(r,i);i+=4,this.name=new Ee(r,i),i+=n,this.value=new Ee(r,i)}toJSON(){const{name:r,value:i,type:n}=this;return{name:r,value:i,type:n}}toString(){const{name:r,value:i}=this;return`${r}="${i}"`}},wl=class extends Wr{constructor(r,i=0){super(r,i);v(this,"target");v(this,"content");i+=16;const n=St(r,i);i+=4,this.target=new Ee(r,i),i+=n,this.content=new Ee(r,i)}get start(){return this.cache.start||(this.cache.start=re(this.data,this.ptr))}get end(){return this.cache.end||(this.cache.end=re(this.data,this.ptr+8))}toJSON(){const{start:r,end:i,target:n,content:s}=this;return{start:r,end:i,target:n,content:s}}toString(){const{target:r,content:i}=this;return`<? ${r} ${i} ?>`}},Ee=class extends Wr{get start(){return this.cache.start||(this.cache.start=re(this.data,this.ptr))}get end(){return this.cache.end||(this.cache.end=re(this.data,this.ptr+8))}get value(){if(this.cache.value)return this.cache.value;const t=St(this.data,this.ptr+16);return this.cache.value=ps(this.data,this.ptr+20,t)}toJSON(){const{start:t,end:r,value:i}=this;return{start:t,end:r,value:i}}toString(){return this.value}},xl=class extends Wr{get openStart(){return this.cache.openStart||(this.cache.openStart=re(this.data,this.ptr+8))}get openEnd(){return this.cache.openEnd||(this.cache.openEnd=re(this.data,this.ptr+16))}get closeStart(){return this.cache.closeStart||(this.cache.closeStart=re(this.data,this.ptr+24))}get closeEnd(){return this.cache.closeEnd||(this.cache.closeEnd=re(this.data,this.ptr+32))}get selfClosing(){return!!this.data[this.ptr+40]}get name(){if(this.cache.name)return this.cache.name;const t=St(this.data,this.ptr+41);return this.cache.name=ps(this.data,this.ptr+45,t)}get attributes(){if(this.cache.attributes)return this.cache.attributes;let t=St(this.data,this.ptr);const r=St(this.data,t);t+=4;const i=[];for(let n=0;n<r;n++){const s=St(this.data,t);t+=4,i[n]=new ds(this.data,t),t+=s}return this.cache.attributes=i}get textNodes(){if(this.cache.textNodes)return this.cache.textNodes;let t=St(this.data,this.ptr+4);const r=St(this.data,t),i=[];t+=4;for(let n=0;n<r;n++){const s=St(this.data,t);t+=4,i[n]=new Ee(this.data,t),t+=s}return this.cache.textNodes=i}toJSON(){const{openStart:t,openEnd:r,closeStart:i,closeEnd:n,name:s,attributes:a,textNodes:o,selfClosing:l}=this;return{openStart:t,openEnd:r,closeStart:i,closeEnd:n,name:s,attributes:a,textNodes:o,selfClosing:l}}get value(){return this.name}};var yi;let bi=(yi=class{constructor(t=0,r={highWaterMark:32*1024}){v(this,"events");v(this,"wasmSaxParser");v(this,"eventHandler");v(this,"options");v(this,"writeBuffer");v(this,"eventTrap",(t,r,i)=>{if(!this.wasmSaxParser)return;const n=new Uint8Array(this.wasmSaxParser.memory.buffer,r,i).slice();let s;switch(t){case W.Attribute:s=new ds(n);break;case W.ProcessingInstruction:s=new wl(n);break;case W.OpenTag:case W.CloseTag:case W.OpenTagStart:s=new xl(n);break;case W.Text:case W.Cdata:case W.Comment:case W.Doctype:case W.SGMLDeclaration:s=new Ee(n);break;default:throw new Error("No reader for this event type")}this.eventHandler&&this.eventHandler(t,s)});this.options=r;const i=this;Object.defineProperties(this,{events:{get:()=>~~t,set:n=>{t=~~n,i.wasmSaxParser&&i.wasmSaxParser.parser(t)},configurable:!1,enumerable:!0}})}write(t){if(!this.wasmSaxParser)return;const{write:r,memory:i}=this.wasmSaxParser;(!this.writeBuffer||this.writeBuffer.buffer!==i.buffer)&&(this.writeBuffer=new Uint8Array(i.buffer)),this.writeBuffer.set(t,0),r(0,t.byteLength)}end(){var t;this.writeBuffer=void 0,(t=this.wasmSaxParser)==null||t.end()}async prepareWasm(t){let r;if(t instanceof Uint8Array?r=await WebAssembly.instantiate(t,{env:{memoryBase:0,tableBase:0,memory:new WebAssembly.Memory({initial:10}),table:new WebAssembly.Table({initial:1,element:"anyfunc"}),event_listener:this.eventTrap}}):r=await WebAssembly.instantiateStreaming(t),r&&typeof this.events=="number"){const{parser:i}=this.wasmSaxParser=r.instance.exports;return i(this.events),!0}throw new Error("Failed to instantiate the parser.")}},v(yi,"textDecoder"),yi);const ps=(e,t,r)=>globalThis.hasOwnProperty("Buffer")?Buffer.from(e.buffer,e.byteOffset+t,r).toString():(bi.textDecoder||(bi.textDecoder=new TextDecoder)).decode(e.subarray(t,t+r)),St=(e,t)=>e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t],re=(e,t=0)=>{const r=St(e,t),i=St(e,t+4);return new bl(r,i)};function gs(e){return{...e,type:"line",children:[],get words(){return this.children.filter(t=>typeof t!="string")},get text(){return this.children.map(t=>typeof t=="string"?t:t.text).join("")}}}function Cl(e){return{...e,type:"paragraph",children:[],get lines(){return this.children},get words(){return this.children.flatMap(t=>t.words)},get text(){var t;const r=[];for(const[i,n]of this.children.entries())r.push(n.text),i<this.children.length-1&&!((t=n.words.slice(-1)[0])!=null&&t.hyphenStart)&&r.push(" ");return r.join("")}}}function ms(e){return{...e,type:"block",children:[],get paragraphs(){return this.children.filter(t=>"lines"in t)},get lines(){return this.children.reduce((t,r)=>("lines"in r?t.push(...r.lines):"words"in r&&t.push(r),t),[])},get words(){return this.lines.flatMap(t=>t.words)},get text(){var t;const r=[];for(const[i,n]of this.children.entries())r.push(n.text),i<this.children.length-1&&!((t=n.words.slice(-1)[0])!=null&&t.hyphenStart)&&(n.type==="line"?r.push(" "):r.push(`
|
|
2
|
+
`));return r.join("")}}}function vs(e){return{...e,type:"page",children:[],get blocks(){return this.children.filter(t=>"paragraphs"in t)},get paragraphs(){return this.children.reduce((t,r)=>("paragraphs"in r?t.push(...r.paragraphs):"lines"in r&&t.push(r),t),[])},get lines(){return this.children.reduce((t,r)=>("lines"in r?t.push(...r.lines):"words"in r&&t.push(r),t),[])},get words(){return this.children.flatMap(t=>t.words)},get text(){var t;const r=[];for(const[i,n]of this.children.entries())r.push(n.text),i<this.children.length-1&&!((t=n.words.slice(-1)[0])!=null&&t.hyphenStart)&&(n.type==="line"?r.push(" "):r.push(`
|
|
3
|
+
`));return r.join("")}}}var Qi="2.2.4",Ur=null;async function ys(e=()=>fetch(`https://unpkg.com/sax-wasm@${Qi}/lib/sax-wasm.wasm`).then(t=>t.arrayBuffer()).then(t=>new Uint8Array(t))){Ur=await e()}function er(){return Ur!==null}async function bs(e,t){const r=new kl(e,new Set([W.OpenTag,W.Text,W.CloseTag]),{highWaterMark:65536});if(!er())throw new Error("XML parser WASM not initialized, call initialize() first!");if(!await r.prepareWasm(Ur))throw new Error("Failed to initialize parser with WASM");return r}var Sl=/&#(\d+);/g,Al=/&#x([A-Fa-f0-9]+);/g,ws={amp:"&",apos:"'",quot:'"',lt:"<",gt:">"},$l=new RegExp(`&(${Object.keys(ws).join("|")});`,"g");function Fr(e){return e=e.replace($l,function(t,r){return ws[r]}),e=e.replace(Sl,function(t,r){const i=parseInt(r,10);return String.fromCharCode(i)}),e=e.replace(Al,function(t,r){const i=parseInt(r,16);return String.fromCharCode(i)}),e}function xs(e){const t=new TextEncoder;return new ReadableStream({start(r){r.enqueue(e instanceof Uint8Array?e:t.encode(e)),r.close()}})}function qt(e,t){var r;const i=e.attributes.find(n=>n.name.value===t);return(r=i==null?void 0:i.value)==null?void 0:r.value}function Yi(e){return Object.fromEntries(e.attributes.map(t=>[t.name.value,t.value.value]))}var kl=class{constructor(e,t,r){this.accumulator=[],this.readable=e;let i;if(t){i=0;for(const n of t)i|=n}this.saxParser=new bi(i,r),this.saxParser.eventHandler=(n,s)=>this.accumulator.push([n,s])}prepareWasm(e){return this.saxParser.prepareWasm(Ur)}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){const e=this.readable.getReader();try{for(;;){const t=await e.read();if(t.done)break;for(this.saxParser.write(t.value);this.accumulator.length>0;)yield this.accumulator.shift()}}finally{e.releaseLock()}for(;this.accumulator.length>0;)yield this.accumulator.shift()}};function Br(e,t="log",r){console[t](`At line ${r.openStart.line}, column ${r.openStart.character}: ${e}`)}function cr(e){const t=qt(e,"title");return t?t.split(";").map(i=>i.trim()).reduce((i,n)=>{const s=n.split(" ")[0];return s==="bbox"?i[s]=n.split(" ").slice(1,5).map(a=>Number.parseInt(a,10)):(i[s]=n.split(" ").slice(1,5).join(" "),i[s].startsWith('"')&&i[s].endsWith('"')&&(i[s]=i[s].slice(1,-1))),i},{}):{}}function zr(e,t){return e.split(" ").map(r=>Number.parseFloat(r)).reduce((r,i)=>{const n=r.slice(-1)[0];return!n||n.length===2?r.push([i]):n.push(i),r},[]).map(([r,i])=>({x:t*r,y:t*i}))}async function qr(e,t,r){let i=0,n;for(;i>=0&&!(n=await e.next()).done;){const[s,a]=n.value;if(s===W.Text&&t.has("text")){const h=r.elementStack.slice(-1)[0];if(typeof h!="string"&&h.type==="line"){const c=a.value.replace(/\s+/g," "),u=c===" ";(h.children.length>0||!u)&&!(h.children.slice(-1)[0]===" "&&u)&&h.children.push(c)}}if(s===W.CloseTag&&i--,s!==W.OpenTag)continue;i++;const o=a,l=Vi(o);if(l!==null){if(!t.has(l)){Br(`Unexpected hOCR element type: ${l}, expected one of [${Array.from(t).join(", ")}]`,"warn",o);continue}switch(l){case"block":await Ol(e,o,r),i--;break;case"paragraph":await Il(e,o,r),i--;break;case"line":await jl(e,o,r),i--;break;case"word":await Pl(e,o,r),i--;break}}}r.elementStack.pop()}async function _l(e,t,r,i){var n;const s=cr(t),a=s.bbox;r.scaleFactor=i?Tl(a,i):1;const o=vs({features:[],width:a[2]*r.scaleFactor,height:a[3]*r.scaleFactor});"ppageno"in s&&(o.physicalPageNumber=Number.parseInt(s.ppageno,10)),"lpageno"in s&&(o.logicalPageNumber=s.lpageno),"image"in s&&(o.imageSource={fileName:s.image}),"x_source"in s&&(o.imageSource||(o.imageSource={}),o.imageSource.documentIdentifier=s.x_source),"imagemd5"in s&&(o.imageSource||(o.imageSource={}),o.imageSource.checksum=s.imagemd5,o.imageSource.checksumType="MD5"),"scan_res"in s&&(o.imageSource||(o.imageSource={}),o.imageSource.ppi=Number.parseInt(s.scan_res.split(" ")[0],10)),r.elementStack.push(o),await qr(e,new Set(["block","paragraph","line"]),r);for(const l of["blocks","paragraphs","lines"])((n=o[l])!=null?n:[]).some(h=>h.polygon!==void 0)&&o.features.push("POLYGONS");return o.words.some(l=>l.choices!==void 0)&&o.features.push("CHOICES"),o.words.some(l=>l.hyphenStart)&&o.features.push("HYPHEN"),o.words.some(l=>l.confidence!==void 0)&&o.features.push("CONFIDENCE"),o}async function Ol(e,t,r){const i=cr(t),[n,s,a,o]=i.bbox.map(h=>h*r.scaleFactor),l=ms({x:n,y:s,width:a-n,height:o-s});"poly"in i&&(l.polygon=zr(i.poly,r.scaleFactor)),r.elementStack.slice(-1)[0].children.push(l),r.elementStack.push(l),await qr(e,new Set(["paragraph","line"]),r)}async function Il(e,t,r){const i=cr(t);let n,s,a,o;if(i.bbox){const c=i.bbox.map(u=>u*r.scaleFactor);n=c[0],s=c[1],a=c[2]-n,o=c[3]-s}const l=Cl({x:n,y:s,width:a,height:o});"poly"in i&&(l.polygon=zr(i.poly,r.scaleFactor)),r.elementStack.slice(-1)[0].children.push(l),r.elementStack.push(l),await qr(e,new Set(["line"]),r)}async function jl(e,t,r){const i=cr(t);if(!("bbox"in i)){Br("Missing bbox attribute on line element","warn",t);return}const[n,s,a,o]=i.bbox.map(u=>u*r.scaleFactor),l=gs({x:n,y:s,width:a-n,height:o-s});if("poly"in i&&(l.polygon=zr(i.poly,r.scaleFactor)),"baseline"in i){const u=i.baseline.split(" "),f=Number.parseFloat(u[0]),d=Number.parseInt(u[1],10),p=l.x,g=l.y;l.baseline=[{x:p,y:g+d},{x:p+l.width,y:g+d+l.width*f}]}if(r.elementStack.slice(-1)[0].children.push(l),r.elementStack.push(l),await qr(e,new Set(["word","text"]),r),l.children.slice(-1)[0]===" "&&(l.children=l.children.slice(0,-1)),l.words.some(u=>u.confidence!==void 0&&u.confidence>1))for(const u of l.words)u.confidence!==void 0&&(u.confidence/=100)}async function Pl(e,t,r){const i=cr(t),[n,s,a,o]=i.bbox.map(f=>f*r.scaleFactor);let l="",h,c=0;for(;c>=0;){const f=await e.next();if(f.done)throw new Error("Unexpected end of stream while parsing word");const[d,p]=f.value;if(d===W.OpenTag){c++;const g=p;g.name==="span"&&Vi(g)==="alternatives"&&(h=[])}else if(d===W.CloseTag){c--;const g=p;if(h&&g.name==="ins")l=g.textNodes.map(m=>m.value.trim()).join("");else if(h&&g.name==="del"){const m=qt(g,"nlp"),y={text:g.textNodes.map(b=>b.value.trim()).join("")};y.text.includes("&")&&(y.text=Fr(y.text)),m&&(y.probability=Math.exp(-Number.parseFloat(m))),h.push(y)}}else if(d===W.Text&&!h){const g=p.value;l+=g.trim()}}if(!l.length){Br("Word element has no text, skipping.","debug",t);return}const u={type:"word",x:n,y:s,width:a-n,height:o-s,text:l};h!=null&&h.length&&(u.choices=h),u.hyphenStart=u.text.endsWith(""),u.hyphenStart&&(u.text=u.text.slice(0,-1)),u.text.includes("&")&&(u.text=Fr(u.text)),"poly"in i&&(u.polygon=zr(i.poly,r.scaleFactor)),"x_wconf"in i&&(u.confidence=Number.parseFloat(i.x_wconf)),r.elementStack.slice(-1)[0].children.push(u)}function Tl(e,t){if(e[2]===t.width&&e[3]===t.height)return 1;const r=t.width/e[2],i=t.height/e[3],n=Math.round(i*e[2]),s=Math.round(r*e[3]);return(n!==t.width||s!==t.height)&&console.warn(`Differing scale factors for x and y axis while parsing hOCR, will use X factor: x=${r}, y=${i}`),r}function Vi(e){switch(qt(e,"class")){case"ocr_page":return"page";case"ocr_carea":case"ocrx_block":return"block";case"ocr_par":return"paragraph";case"ocr_line":case"ocrx_line":return"line";case"ocrx_word":return"word";case"ocrx_cinfo":return"char";case"alternatives":return"alternatives";case"alt":return"alt";default:return null}}async function*Fl(e,t){var r;if(Array.isArray(t)){const h=t;t=c=>{var u;return(u=h[c])!=null?u:null}}const i=typeof e=="string"||e instanceof Uint8Array?xs(e):e,n=await bs(i),s={scaleFactor:1,elementStack:[]};let a=0;const o=n.iterate();let l;for(;!(l=await o.next()).done;){const[h,c]=l.value;if(h!==W.OpenTag||c.name!=="div"||Vi(c)!=="page")continue;const u=await _l(o,c,s,(r=t==null?void 0:t(a,Yi(c)))!=null?r:void 0);u&&(yield u)}}var El=["HEIGHT","WIDTH","HPOS","VPOS","WC"];function Rl(e,t){return Object.fromEntries(e.attributes.filter(r=>!t||t.includes(r.name.value)).map(r=>[r.name.value,El.includes(r.name.value)?Number.parseFloat(r.value.value):r.value.value]))}function Hr(e){const t=Rl(e,["HEIGHT","WIDTH","HPOS","VPOS"]);return{height:t.HEIGHT,width:t.WIDTH,x:t.HPOS,y:t.VPOS}}async function Ml(e,t,r,i){var n;const s=Hr(r);if(!s.width||!s.height)throw new Error("Could not get Page dimensions");const a=i?i.width/s.width:1,o=i?i.height/s.height:1;a!==o&&console.warn(`Scale factors differ: x=${a} vs y=${o}, using X scale factor.`),t.scaleFactor=a;const l=vs({features:[],width:s.width*a,height:s.height*a});t.elementStack.push(l);const h=Yi(r);"PHYSICAL_IMG_NR"in h&&(l.physicalPageNumber=Number.parseInt(h.PHYSICAL_IMG_NR)),"PRINTED_IMG_NR"in h&&(l.logicalPageNumber=h.PRINTED_IMG_NR);let c=0,u;for(;c>=0&&!(u=await e.next()).done;){const[f,d]=u.value;if(f===W.CloseTag)c--;else if(f!==W.OpenTag)continue;c++,d.name==="TextBlock"&&await Nl(e,t,d)}t.elementStack.pop();for(const f of["blocks","paragraphs","lines"])((n=l[f])!=null?n:[]).some(d=>d.polygon!==void 0)&&l.features.push("POLYGONS");return l.words.some(f=>f.choices!==void 0)&&l.features.push("CHOICES"),l.words.some(f=>f.hyphenStart)&&l.features.push("HYPHEN"),l.words.some(f=>f.confidence!==void 0)&&l.features.push("CONFIDENCE"),t.sourceImageInformation&&(l.imageSource=t.sourceImageInformation,t.sourceImageInformation=void 0),l}async function Nl(e,t,r){const i=Hr(r),n=ms({x:i.x?i.x*t.scaleFactor:-1,y:i.y?i.y*t.scaleFactor:-1,width:i.width?i.width*t.scaleFactor:-1,height:i.height?i.height*t.scaleFactor:-1});t.elementStack.slice(-1)[0].children.push(n),t.elementStack.push(n);let s=0,a;for(;s>=0&&!(a=await e.next()).done;){const[o,l]=a.value;if(o===W.CloseTag)s--;else if(o!==W.OpenTag)continue;s++;const h=l;if(h.name==="TextLine")await Dl(e,t,l);else if(h.name==="Shape"){const c=await Ji(e,t);c!=null&&(n.polygon=c)}}t.elementStack.pop()}async function Dl(e,t,r){const i=Hr(r),n=gs({x:i.x?i.x*t.scaleFactor:-1,y:i.y?i.y*t.scaleFactor:-1,width:i.width?i.width*t.scaleFactor:-1,height:i.height?i.height*t.scaleFactor:-1});t.elementStack.slice(-1)[0].children.push(n),t.elementStack.push(n);let s=0,a;for(;s>=0&&!(a=await e.next()).done;){const[o,l]=a.value;if(o===W.CloseTag&&s--,o!==W.OpenTag)continue;s++;const h=l;if(h.name==="String")await Ll(e,t,l),s--;else if(h.name==="SP")n.children.push(" ");else if(h.name==="Shape"){const c=await Ji(e,t);c!=null&&(n.polygon=c)}}t.elementStack.pop(),n.children.find(o=>o===" ")||(n.children=n.children.flatMap((o,l)=>l===n.children.length-1?[o]:[o," "]))}async function Ji(e,t,r){let i=null,n=0,s;for(;n>=0&&!(s=await e.next()).done;){const[o,l]=s.value;if(o===W.CloseTag&&n--,o!==W.OpenTag)continue;n++;const h=l;if(h.name==="Polygon"){const c=qt(h,"POINTS");if(!c){Br("<Polygon> without POINTS attribute, ignoring","warn",h);continue}i=c.split(" ").map(u=>u.split(/(,| )/).map(f=>Number.parseFloat(f))).reduce((u,[f])=>{const d=u.slice(-1)[0];return!d||d.length===2?u.push([f]):d.push(f),u},[]).map(([u,f])=>({x:u*t.scaleFactor,y:f*t.scaleFactor}))}}const a=t.elementStack.slice(-1)[0];if(a.x<0||a.y<0||a.width<0||a.height<0)if(i)a.x=Math.min(...i.map(o=>o.x)),a.y=Math.min(...i.map(o=>o.y)),a.width=Math.max(...i.map(o=>o.x))-a.x,a.height=Math.max(...i.map(o=>o.y))-a.y;else throw new Error(`Could not get dimensions for ${a.type}, no HPOS/VPOS/WIDTH/HEIGHT attribs and no associated Shape`);return i}async function Ll(e,t,r){const i=Hr(r);let n=qt(r,"CONTENT");if(!n)throw new Error("Could not get String text");n.includes("&")&&(n=Fr(n));const s={type:"word",x:i.x?i.x*t.scaleFactor:-1,y:i.y?i.y*t.scaleFactor:-1,width:i.width?i.width*t.scaleFactor:-1,height:i.height?i.height*t.scaleFactor:-1,text:n};t.elementStack.push(s),qt(r,"SUBS_TYPE")==="HypPart1"&&(s.hyphenStart=!0);const o=qt(r,"WC");o!==void 0&&(s.confidence=Number.parseFloat(o));let l=0,h;for(;l>=0&&!(h=await e.next()).done;){const[u,f]=h.value;if(u===W.CloseTag){if(l--,f.name==="ALTERNATIVE"){"choices"in s||(s.choices=[]);let d=f.textNodes.filter(p=>p.value.trim()!=="").map(p=>p.value.trim()).join("");d.includes("&")&&(d=Fr(d)),s.choices.push({text:d})}}else if(u===W.OpenTag&&(l++,f.name==="Shape")){const d=await Ji(e,t);l--,d!=null&&(s.polygon=d)}}t.elementStack.slice(-2)[0].children.push(s),t.elementStack.pop()}async function Wl(e,t,r){let i=0,n;for(t.sourceImageInformation={};i>=0&&!(n=await e.next()).done;){const[s,a]=n.value,o=a;if(s===W.CloseTag){if(i--,o.name==="fileName")t.sourceImageInformation.fileName=o.textNodes.map(l=>l.value).join("");else if(o.name==="fileIdentifier"){let l=o.textNodes.map(c=>c.value).join("");const h=qt(o,"fileIdentifierLocation");h&&(l=`${h}:${l}`),t.sourceImageInformation.fileIdentifier=l}else if(o.name==="documentIdentifier"){let l=o.textNodes.map(c=>c.value).join("");const h=qt(o,"documentIdentifierLocation");h&&(l=`${h}:${l}`),t.sourceImageInformation.documentIdentifier=l}}else s===W.OpenTag&&i++}}async function*Ul(e,t){var r;if(Array.isArray(t)){const h=t;t=c=>{var u;return(u=h[c])!=null?u:null}}const i=typeof e=="string"||e instanceof Uint8Array?xs(e):e,n=await bs(i),s={scaleFactor:1,elementStack:[]},a=n.iterate();let o,l=0;for(;!(o=await a.next()).done;){const[h,c]=o.value;if(h===W.CloseTag&&c.name==="MeasurementUnit"){const f=c.textNodes[0].value.trim();if(f!=="pixel"&&!t)throw new Error(`Measurement unit ${f} requires a reference size.`)}if(h!==W.OpenTag)continue;const u=c;if(u.name==="Page"){const f=await Ml(a,s,c,(r=t==null?void 0:t(l,Yi(c)))!=null?r:void 0);f&&(yield f,l++)}else u.name==="sourceImageInformation"&&await Wl(a,s)}}let Tt=null;function gn(){return typeof window<"u"&&window.performance?window.performance.now():Date.now()}function xe(e){return e!=null&&e!==null&&e!==void 0}const Bl=(()=>{const e=new Int32Array(256);for(let t=0;t<256;++t){let r=t,i=9;for(;--i;)r=(r&1&&-306674912)^r>>>1;e[t]=r}return e})();function Cs(e){let t=-1;for(let r=0;r<e.length;++r)t=Bl[t&255^e[r]]^t>>>8;return~t}function Xi(){var e;return typeof process<"u"&&typeof((e=process.versions)==null?void 0:e.node)<"u"}function Ss(e){Tt=e}function zl(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){return e!=="x"?e:((Math.random()*16|0)&3|8).toString(16)})}let Nt;Xi()&&(Nt={pageGenerationDuration:new hr.Histogram({name:"pdiiif_page_generation_duration_seconds",help:"Latency for generating the PDF for a single page",buckets:[.001,.005,.015,.05,.1,.5,1,2],labelNames:["status"]}),imageFetchDuration:new hr.Histogram({name:"pdiiif_image_fetch_duration_seconds",help:"Latency for fetching data from IIIF Image API endpoints",buckets:[.01,.05,.15,.5,1,5,10],labelNames:["status","iiif_host","limited"]}),imageInfoDuration:new hr.Histogram({name:"pdiiif_image_info_duration_seconds",help:"Latency for fetching info from IIIF Image API endpoints",buckets:[.01,.05,.15,.5,1,5,10],labelNames:["status","iiif_host","limited"]}),ocrFetchDuration:new hr.Histogram({name:"pdiiif_ocr_fetch_duration_seconds",help:"Latency for fetching OCR data",buckets:[.01,.05,.15,.5,1,5,10],labelNames:["status","ocr_host","limited"]})});const fr={},Ki={get(e){return e},setMetaValue([e,t,r],i){let n=Ki.getResourceMeta(e,t),s=n?n[r]:void 0,a=typeof i=="function"?i(s):i;fr[e]={...fr[e]||{},[t]:{...(fr[e]||{})[t]||{},[r]:a}}},getResourceMeta:(e,t)=>{let r=fr[e];if(r)return t?r[t]:r},async load(e){let t=typeof e=="string"?e:e.id;return fetch(t).then(r=>r.json())},subscribe(e){return()=>{}},requestStatus(e){}};function rr(e){"@babel/helpers - typeof";return rr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rr(e)}function ql(e,t){if(rr(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t);if(rr(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Hl(e){var t=ql(e,"string");return rr(t)=="symbol"?t:t+""}function ut(e,t,r){return(t=Hl(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}const Gl={},mn=e=>{let t,r=new Set,i=(o,l)=>{let h=typeof o=="function"?o(t):o;if(!Object.is(h,t)){let c=t;t=l??(typeof h!="object"||!h)?h:Object.assign({},t,h),r.forEach(u=>u(t,c))}},n=()=>t,s={setState:i,getState:n,getInitialState:()=>a,subscribe:o=>(r.add(o),()=>r.delete(o)),destroy:()=>{(Gl?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),r.clear()}},a=t=e(i,n,s);return s},As=e=>e?mn(e):mn;function $s(e){return{all:e=e||new Map,on:function(t,r){var i=e.get(t);i?i.push(r):e.set(t,[r])},off:function(t,r){var i=e.get(t);i&&(r?i.splice(i.indexOf(r)>>>0,1):e.set(t,[]))},emit:function(t,r){var i=e.get(t);i&&i.slice().map(function(n){n(r)}),(i=e.get("*"))&&i.slice().map(function(n){n(t,r)})}}}const ks="http://library.stanford.edu/iiif/image-api/compliance.html#level0",_s="http://library.stanford.edu/iiif/image-api/compliance.html#level1",Os="http://library.stanford.edu/iiif/image-api/compliance.html#level2",Is="http://library.stanford.edu/iiif/image-api/conformance.html#level0",js="http://library.stanford.edu/iiif/image-api/conformance.html#level1",Ps="http://library.stanford.edu/iiif/image-api/conformance.html#level2",Ts="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",Fs="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1",Es="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2",Rs="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level0",Ms="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1",Ns="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2",Ds="http://iiif.io/api/image/1/level0.json",Ls="http://iiif.io/api/image/1/profiles/level0.json",Ws="http://iiif.io/api/image/1/level1.json",Us="http://iiif.io/api/image/1/profiles/level1.json",Bs="http://iiif.io/api/image/1/level2.json",zs="http://iiif.io/api/image/1/profiles/level2.json",qs="http://iiif.io/api/image/2/level0.json",Hs="http://iiif.io/api/image/2/profiles/level0.json",Gs="http://iiif.io/api/image/2/level1.json",Qs="http://iiif.io/api/image/2/profiles/level1.json",Ys="http://iiif.io/api/image/2/level2.json",Vs="http://iiif.io/api/image/2/profiles/level2.json",Js="level0",Xs="level1",Ks="level2",Zs="http://iiif.io/api/image/2/level0",ta="http://iiif.io/api/image/2/level1",ea="http://iiif.io/api/image/2/level2",Gr=[ea,Os,Ps,Es,Ns,Bs,zs,Ys,Vs,Ks],Zi=[...Gr,ta,_s,js,Fs,Ms,Ws,Us,Gs,Qs,Xs],ra=[Zs,ta,ea,ks,_s,Os,Is,js,Ps,Ts,Fs,Es,Rs,Ms,Ns,Ds,Ls,Ws,Us,Bs,zs,qs,Hs,Gs,Qs,Ys,Vs,Js,Xs,Ks],Ql=ra,ia=[Zs,ks,Is,Ts,Rs,Ds,Ls,qs,Hs,Js],Yl={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["sizeByWhListed"]},Vl={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPx","regionSquare","sizeByWhListed","sizeByH","sizeByW","sizeByWh"]},Jl={extraFormats:["jpg","png"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPct","regionByPx","regionSquare","rotationBy90s","sizeByWhListed","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"]};function Xl(e){try{if(e==="full")return{full:!0};if(e==="square")return{square:!0};let t=e.startsWith("pct:"),r=e.substr(t?4:0).split(","),i=r.map(n=>parseFloat(n));return{x:i[0],y:i[1],w:i[2],h:i[3],percent:t}}catch{throw Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+e)}}function Kl(e){let t={upscaled:!1,max:!1,confined:!1};if(e[0]==="^"&&(t.upscaled=!0,e=e.slice(1)),e==="max"||e==="full")return t.max=!0,t.serialiseAsFull=e==="full",t;if(e[0]==="!"&&(t.confined=!0,e=e.slice(1)),e[0]==="p")return t.percentScale=parseFloat(e.slice(4)),t;let r=e.split(",").map(i=>i.trim());return r.length&&(r[0]!==""&&(t.width=parseInt(r[0],10)),r[1]!==""&&(t.height=parseInt(r[1],10))),t}function Zl(e){let t={angle:0};if(e[0]==="!"&&(t.mirror=!0,e=e.substr(1)),t.angle=parseFloat(e)%360,Number.isNaN(t.angle))throw Error(`Invalid rotation ${e}`);return t}function tc(e,t=""){let r=e.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!r)throw Error(`Invalid or unknown input ${e}`);let i=r[2],n=r[3],s=r[4];if(s[0]==="/"&&(s=s.substring(1)),t.length>0){if(t[0]==="/"&&(t=t.substring(1)),t!==s.substring(0,t.length))throw Error(`Path does not start with prefix (path: ${s}, prefix: ${t})`);s=s.substring(t.length)}return{scheme:i,server:n,path:s,prefix:t}}function ec(e,t=""){let{path:r,scheme:i,server:n,prefix:s}=tc(e,t),a=r.split("/").reverse(),[o,l,h,c,...u]=a,f=u.reverse().filter(Boolean).join("/");if(a.length===1||o==="")return{type:"base",scheme:i,server:n,prefix:s,identifier:f};if(o==="info.json"){let[,...g]=a;return{type:"info",scheme:i,server:n,prefix:s,identifier:g.reverse().filter(Boolean).join("/")}}if(i===void 0||n===void 0||r===void 0||c===void 0||h===void 0||l===void 0||o===void 0)throw Error("Invalid image service URL");let[d="",p=""]=o.split(".");return{type:"image",scheme:i,server:n,prefix:s,identifier:f,originalPath:r,region:Xl(c),size:Kl(h),rotation:Zl(l),quality:d,format:p}}function rc(e){return Gr.indexOf(e)!==-1?Jl:Zi.indexOf(e)!==-1?Vl:Yl}function ic(e){let t=e?Array.isArray(e.profile)?e.profile:[e.profile]:[],r={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let i of t)if(typeof i=="string"&&(i=rc(i)),!!i){if(i.formats)for(let n of i.formats)r.extraFormats.indexOf(n)===-1&&r.extraFormats.push(n);if(i.qualities)for(let n of i.qualities)r.extraQualities.indexOf(n)===-1&&r.extraQualities.push(n);if(i.supports)for(let n of i.supports)r.extraFeatures.indexOf(n)===-1&&r.extraFeatures.push(n);if(i.maxHeight&&(r.maxHeight=i.maxHeight),i.maxWidth&&(r.maxWidth=i.maxWidth),i.maxArea&&(r.maxArea=i.maxArea),i.extraFormats)for(let n of i.extraFormats)r.extraFormats.indexOf(n)===-1&&r.extraFormats.push(n);if(i.extraQualities)for(let n of i.extraQualities)r.extraQualities.indexOf(n)===-1&&r.extraQualities.push(n);if(i.extraFeatures)for(let n of i.extraFeatures)r.extraFeatures.indexOf(n)===-1&&r.extraFeatures.push(n);i.maxHeight&&(r.maxHeight=i.maxHeight),i.maxWidth&&(r.maxWidth=i.maxWidth),i.maxArea&&(r.maxArea=i.maxArea)}if(e.extraFormats)for(let i of e.extraFormats)r.extraFormats.indexOf(i)===-1&&r.extraFormats.push(i);if(e.extraFeatures)for(let i of e.extraFeatures)r.extraFeatures.indexOf(i)===-1&&r.extraFeatures.push(i);if(e.extraQualities)for(let i of e.extraQualities)r.extraQualities.indexOf(i)===-1&&r.extraQualities.push(i);return r}function vn(e){let t=Array.isArray(e.profile)?e.profile:[e.profile];for(let r of t)if(typeof r=="string"&&ia.indexOf(r)!==-1)return!0;return!1}function J(e){if(e["@id"])return e["@id"];if(e.id)return e.id}function Qr(e){if(!e||!e.profile||!J(e))return!1;let t=Array.isArray(e.profile)?e.profile:[e.profile];for(let r of t)if(typeof r=="string"&&ra.indexOf(r)!==-1)return!0;return!1}function nc(e){if(!Qr(e))return!1;let t=Array.isArray(e.profile)?e.profile:[e.profile];for(let r of t)if(typeof r=="string"){if(Zi.indexOf(r)!==-1)return!0}else{let i=[...r.supports||[],...r.extraFeatures||[]];if(i.indexOf("regionByPx")!==-1&&(i.indexOf("sizeByW")!==-1||i.indexOf("sizeByWh")!==-1))return!0}return!1}function sc({x:e=0,y:t=0,w:r,h:i,full:n,square:s,percent:a}){return"full"}function ac({max:e,percentScale:t,upscaled:r,confined:i,width:n,height:s,serialiseAsFull:a,version:o}){let l=[];return r&&l.push("^"),e?(l.push(a?"full":"max"),l.join("")):(i&&l.push("!"),t&&l.push(`pct:${t}`),n&&l.push(`${n}`),l.push(","),s&&o===3&&l.push(`${s}`),l.join(""))}function oc(e){return`${e.mirror?"!":""}${(e.angle||0)%360}`}function lc(e,t){let r=e.prefix.startsWith("/")?e.prefix.substring(1):e.prefix,i=`${e.scheme}://${e.server}/${r?`${r}/`:""}${e.identifier}`,{size:n}=e,{region:s,rotation:a,format:o,quality:l}=e;return[i,sc(s),ac(n),oc(a),`${l}.${o}`].filter(Boolean).join("/")}function ge(e){return e.endsWith("info.json")?e:e.endsWith("/")?`${e}info.json`:`${e}/info.json`}function cc(e){let t=ec(ge(e.id));if(t.type!=="info")throw Error("Invalid service URL");let r=ic(e);return{identifier:t.identifier,originalPath:"",server:t.server,prefix:t.prefix,scheme:t.scheme,type:"image",quality:r.extraQualities.indexOf("default")===-1?r.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function uc(e,t,r){let i=r.length,n=[];for(let s=0;s<i;s++){let a=r[s];if(!a)continue;let o=a.width;n.push(e/o)}return n}function hc(e,t,r){let i=r.length,n=[];for(let s=0;s<i;s++){let a=r[s];a&&n.push({width:Math.floor(e/a),height:Math.floor(t/a)})}return n}function Zr(e,t){if(t&&t.profile){let r=t.profile;if(r){let i=Array.isArray(r)?r:[r];if(i.includes(`level${e}`)||i.includes(`http://iiif.io/api/image/2/level${e}.json`)||i.includes(`http://iiif.io/api/image/1/level${e}.json`)||i.includes(`http://iiif.io/api/image/1/profiles/level${e}.json`))return!0;if(e===2){for(let n of i)if(Gr.includes(n))return!0}if(e===1){for(let n of i)if(Zi.includes(n))return!0}if(e===0){for(let n of i)if(ia.includes(n))return!0}}}return!1}function wi(e){return Qr(e)?Zr(2,e)?2:Zr(1,e)?1:Zr(0,e)?0:null:null}function na(e){let t=e.service?Array.isArray(e.service)?e.service:[e.service]:[],r=t.length,i=[];for(let n=0;n<r;n++)Qr(t[n])&&i.push(t[n]);return i}function fc(e){if(e["@type"])return e["@type"];if(e.type)return e.type}function Ce(e){let t=e.replace(/(https?:\/\/)?(www.)?/i,"");return t.indexOf("/")===-1?t:t.split("/")[0]}function dc(e,t,r){let i=e>t?e:t,n=r.length,s=[];for(let a=0;a<n;a++){let o=r[a];if(!o||o.scaleFactors.length===0)continue;let l=o.scaleFactors[0];if(!l)continue;let h=i/l,c=[l];for(;h>=o.width;)l*=2,c.push(l),h/=2;s.push({...o,scaleFactors:c})}return s}function ti(e,t,r){let i=cc({"@context":e.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:ge(J(e)),profile:e.level===null||e.level===void 0?"level0":`level${e.level}`,type:e.version===3?"ImageService3":"ImageService2"});return i.size.max=!1,i.size.width=t,i.size.height=r,{id:lc(i),type:"fixed",width:t,height:r||e.height/(e.width||1)*t,unsafe:e.width>t}}function pc(e,t,r){let i=e.width?e.width:e.maxWidth;return r.height<=e.maxHeight&&r.width<=e.maxWidth&&r.height>=e.minHeight&&r.width>=e.minWidth&&(!t||Math.abs(r.width-i)<Math.abs(t.width-i))}function gc(e,t){let r=[],i=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},e),n=(c,u=0)=>i.explain?r.push(Array(u).fill(0).map(f=>" ").join("")+c().trim()):void 0,s=[],a=[],o=null;n(()=>`Using configuration: ${JSON.stringify(i,null,2)}`);let l=(c,u)=>{if(n(()=>"Swapping choice",3),pc(i,u,c)){if(i.preferFixedSize&&c.unsafe){n(()=>`We found an image that was marked as unsafe, but it was the best size. (${c.id})`,4),a.push(c);return}i.returnAllOptions&&u&&a.push(u),n(()=>`We found a new image that was the best size. (${c.id})`,4),o=c}else i.returnAllOptions&&a.push(c)};n(()=>`The input shows we have ${t.length} list(s) of candidates to choose from.`);let h=t.length;for(let c=0;c<h;c++){let u=t[c]();n(()=>`Candidate group ${c}: ${JSON.stringify(u,null,2)}`,1);let f=u.length;n(()=>`Checking candidate list number ${c} and found ${f} potential ways of creating image(s)`,1);for(let d=0;d<f;d++){let p=u[d];n(()=>`-> Checking candidate ${d}`,1),p.type==="unknown"&&i.atAnyCost&&(n(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),s.push(p)),p.type==="fixed"&&(p.unsafe?(n(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),s.push(p)):(n(()=>"We've found a fixed size image, checking if it matches the request",2),l(p,o))),p.type==="fixed-service"&&(i.unsafeImageService?(n(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2),l(ti(p,i.width,i.height),o)):(n(()=>"Checking for an image from the tile source 3",2),l(ti(p,p.width,p.height),o))),p.type==="variable"&&p.maxWidth&&l(ti({id:p.id,type:"fixed-service",width:p.maxWidth,height:p.maxWidth,level:p.level,version:p.version},p.maxWidth),o)}if(o&&!i.returnAllOptions){if(o.unsafe||i.allowUnsafe)continue;n(()=>`We found a match in choice list number ${c}, no searching any more`);break}}return i.atAnyCost&&a.length===0?(n(()=>o?`We found an image! ${o.id} of type ${o.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:o||s[0]||null,fallback:s.slice(1),log:r}):i.returnAllOptions?(n(()=>"Returning all options that we have found"),{best:(i.atAnyCost?o||a[0]||s[0]:o||a[0])||null,fallback:[...a,...s],log:r}):(n(()=>"Returning the best image that we found, and a fallback"),{best:o||a[0]||null,fallback:o?a:a.slice(1),log:r})}function sa(e){return(e["@context"]?Array.isArray(e["@context"])?e["@context"]:[e["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function mc(e){return Qr(e)?(e&&e.sizes?e.sizes:[]).map(t=>({id:J(e),type:"fixed-service",height:t.height,width:t.width,level:wi(e),version:sa(e)?3:2})):[]}function vc(e){if(!nc(e))return[];let t=[],r=Array.isArray(e.profile)?e.profile:[e.profile],i=r.length;for(let n=0;n<i;n++){let s=r[n];if(s&&typeof s!="string"&&(s.maxHeight||s.maxWidth))return[{id:J(e),type:"variable",minWidth:0,minHeight:0,maxHeight:s.maxHeight||s.maxWidth,maxWidth:s.maxWidth||s.maxHeight,level:wi(e),version:e["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(e.tiles){let n=e.tiles.length;for(let s=0;s<n;s++){let a=e.tiles[s];a&&(a.height||a.width)&&t.push({id:J(e),type:"variable",minHeight:0,minWidth:0,maxHeight:a.height||a.width,maxWidth:a.width,level:wi(e),version:sa(e)?3:2})}}return t}function yn(e){let t=[],r=e.length;for(let i=0;i<r;i++){let n=e[i];if(!n)continue;let s=mc(n);s.length&&t.push(...s);let a=vc(n);a.length&&t.push(...a)}return t}function bn(e){let t=e.match(/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/);if(t&&t[4]&&t[5]){let r=t[1],i=parseInt(t[4],10),n=parseInt(t[5],10),s=t[7];if((r==="max"||r==="full")&&i&&n&&s)return{type:"fixed",id:e,height:n,width:i}}return{type:"unknown",id:e}}function xi(e){if(typeof e=="string")return bn(e);let t=fc(e);if(t!=="Image"&&t!=="sc:Image")return null;let r=e,i=J(r);return i?i&&r.width&&r.height?{id:i,type:"fixed",width:r.width,height:r.height,unsafe:!0}:bn(i):null}function yc(e,t=!0,r){let i=[],n=xi(e);if(n===null)return i;let s=e;if(i.push(n),t&&s&&s.width&&s.height){let a=[],o=na(s);for(let l of o){let h={id:J(l),width:s.width,height:s.height};if(r.canLoadSync(h)){let c=r.loadServiceSync(h);c&&(c.height||(c.height=s.height),c.width||(c.width=s.width),a.push(...yn([c])))}}if(a.length)return i.push(...a),i}return s.service&&i.push(...yn(s.service)),i}function bc(e,t){if(e.length!==t.length)return!1;if(e.length===0&&t.length===0)return!0;let r=e.length,i=!0;for(let s=0;s<r;s++){let a=e[s],o=t[s];if(a.width!==o.width||a.height!==o.height){i=!1;break}}if(i)return!0;let n=0;for(let s=0;s<r;s++)for(let a=0;a<r;a++)if(e[s].width===t[a].width&&e[s].height===t[a].height){n++;break}return n===r}var aa=class{constructor(t={}){ut(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),ut(this,"fetchingCount",0),ut(this,"imageServices",{}),ut(this,"knownImageServers",{}),this.config=Object.assign(this.config,t)}setConfig(t){Object.assign(this.config,t)}sample(t,r,i=!0){let n=Ce(J(t)),s=ge(J(t)),a=this.knownImageServers[n];return this.imageServices[s]=Object.assign(t,{real:!0}),!a&&t.tiles&&!vn(t)?(this.knownImageServers[n]={verifications:0,malformed:!1,root:n,preLoaded:i,sampledId:J(t),verified:!1,server:null,result:{context:t["@context"]||[],sampledProfile:t.profile,resourceServiceRatio:r&&t.height?r.height/t.height:1,sampledSizes:t.sizes||[],sizeRatios:uc(t.width,t.height,t.sizes||[]),sampledTiles:t.tiles||[]}},!0):this.verify(t)}preLoad(t,r=!0){this.knownImageServers[t.root]=t,r&&(this.knownImageServers[t.root].malformed=!1,this.knownImageServers[t.root].verifications=this.config.verificationsRequired)}predict(t,r=!1,i=!1){let n=t==null?void 0:t.source,s=Ce(J(t)),a=this.knownImageServers[s],o=ge(J(t));return this.imageServices[o]?this.imageServices[o]||null:!this.config.approximateServices||!a||!a.result||!(n!=null&&n.height||t.height)||!(n!=null&&n.width||t.width)||!i&&(a.malformed||a.verifications<this.config.verificationsRequired)||t.source&&vn(t.source)?null:(this.imageServices[o]||(this.imageServices[o]={"@context":a.result.context,"@id":J(t),id:J(t),protocol:"http://iiif.io/api/image",tiles:(n==null?void 0:n.tiles)||dc(t.width,t.height,a.result.sampledTiles),sizes:(n==null?void 0:n.sizes)||hc(Math.round(t.width/a.result.resourceServiceRatio),Math.round(t.height/a.result.resourceServiceRatio),a.result.sizeRatios),profile:(n==null?void 0:n.profile)||a.result.sampledProfile,height:(n==null?void 0:n.height)||t.height,width:(n==null?void 0:n.width)||t.width,real:!1}),this.imageServices[o]||null)}async getThumbnailFromResource(t,r,i=!0,n=[]){let s=t?await this.getImageCandidates(t,i):[];return gc(r,[()=>n,()=>s])}async getImageCandidates(t,r=!0){let i=t;if(r&&i&&i.height&&i.width){let n=na(i);for(let s of n){let a={id:J(s),width:s.width?s.width:i.width,height:s.height?s.height:i.height,source:s};await this.loadService(a)}}return yc(t,r,this)}async verify(t){let r=this.predict(t,!1,!0),i=await this.fetchService(J(t));if(!r)return!1;let n=r.height===i.height&&r.width===i.width&&r["@context"]===i["@context"]&&bc(r.sizes||[],i.sizes||[]);if(n){let s=Ce(J(t)),a=this.knownImageServers[s];a&&(a.verifications+=1,a.verifications>=this.config.verificationsRequired&&(a.verified=!0))}return n}canLoadSync(t){let r=typeof t=="string"?t:J(t),i=ge(r);if(this.imageServices[i])return!0;let n=this.knownImageServers[Ce(r)];return!!(n&&!n.malformed&&n.verifications>=this.config.verificationsRequired)}async markAsMalformed(t){return this.knownImageServers[Ce(J(t))].malformed=!0,this.loadService(t,!0)}async fetchService(t,r=!1){let i=ge(t),n=this.imageServices[i];if(n&&(!r||n.real))return n;if(!this.config.enableFetching)throw Error("Fetching is not enabled");let s=await this.fetch(i).then(a=>a.json());return!s.id&&s["@id"]&&(s.id=s["@id"]),s.id!==t&&(s.id=t,s["@id"]&&(s["@id"]=t)),this.imageServices[i]=Object.assign(s,{real:!0}),this.imageServices[i]}async fetch(t,r){return fetch(t,r)}async loadService(t,r=!1){if(!this.config.disableThrottling){let s=!0;for(;s;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(a=>setTimeout(a,500));else{s=!1;break}}let i=this.knownImageServers[Ce(J(t))];if(i&&!i.malformed&&!r){await i.result;let s=this.loadServiceSync(t);if(s)return s}this.fetchingCount++;let n=await this.fetchService(J(t),r);return this.fetchingCount--,n.real&&this.sample(n,t),n}loadServiceSync(t){let r=ge(J(t));return this.imageServices[r]?this.imageServices[r]:this.config.approximateServices?this.predict(t):null}};function wc(e={}){let t=e.events||$s(),r=e.loader||new aa;return{store:As((i,n)=>({loaded:{},loadServiceSync:(s,a,o)=>{let l=s.id||s["@id"],h=n().loaded[l];if(h&&h.status==="done")return h.service;if(h&&h.status==="loading")return null;if(h&&h.status==="error")throw Error("Failed to load image service");let c={id:J(s),width:s.width||(a==null?void 0:a.width)||0,height:s.height||(a==null?void 0:a.height)||0,source:s},u=r.loadServiceSync(c);return u?(i(f=>({loaded:{...f.loaded,[l]:{status:"done",service:u,real:!0}}})),t.emit("image-service.loaded",{id:l,service:u})):o&&n().loadService(s,a).then(()=>{}),u},loadService:async(s,a)=>{let o=s.id||s["@id"],l=n().loaded[o];if(l&&l.status==="done")return l.service;if(l&&l.status==="loading")return new Promise((h,c)=>{let u=f=>{f.id===o&&(t.off("image-service.loaded",u),h(f.service||s))};t.on("image-service.loaded",u)});if(l&&l.status==="error"&&!(a!=null&&a.force))throw Error("Failed to load image service");t.emit("image-service.loading",{id:o});try{let h={id:J(s),width:s.width||0,height:s.height||0,source:s},c=await r.loadService(h,a==null?void 0:a.force);return i(u=>({loaded:{...u.loaded,[o]:{status:"done",service:c,real:c.real}}})),t.emit("image-service.loaded",{id:o,service:c}),c}catch(h){throw t.emit("image-service.error",{id:o,error:h}),h}}})),events:t}}wc();const xc=new aa;function Cc(e=Ki,t={}){let r=t.imageServiceLoader||xc;async function i(n,s,a=!1,o=[],l){let h=()=>r.getThumbnailFromResource(void 0,s,a,o);if(!n)return await r.getThumbnailFromResource(void 0,s,a,o);if(typeof n=="string"){let u=xi(n);return u&&o.push(u),await r.getThumbnailFromResource(void 0,s,a,o)}let c=e.get(n,{skipSelfReturn:!1});if(typeof c=="string")return{best:xi(c),fallback:[],log:[]};if(!c)return await h();switch(await(async u=>{if(u&&u.thumbnail&&u.thumbnail.length){let f=e.get(u.thumbnail[0]),d=await r.getImageCandidates(f,a);d&&d.length&&o.push(...d)}})(c),c.type){case"Annotation":{let u=Array.isArray(c.body)?c.body:[c.body],f=e.get(u[0]);return l&&!f.width&&(f.width=l.width,f.height=l.height),await r.getThumbnailFromResource(f,s,a,o)}case"Canvas":{let u=c;return i(u.items[0],s,a,o,{width:u.width,height:u.height})}case"AnnotationPage":return i(c.items[0],s,a,o,l);case"Choice":{let u=c;return!u.items||u.items[0]?await h():i(u.items[0],s,a,o,l)}case"Collection":{let u=c.items[0];return u?i(u,s,a,o,l):await h()}case"Manifest":{let u=c.items[0];return u?i(u,s,a,o,l):await h()}case"SpecificResource":case"Image":case"Dataset":case"Sound":case"Text":case"TextualBody":case"Video":return l&&!c.width&&(c.width=l.width,c.height=l.height),r.getThumbnailFromResource(c,s,a,o)}return await h()}return{getBestThumbnailAtSize:i}}function ir(e){"@babel/helpers - typeof";return ir=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ir(e)}function Sc(e,t){if(ir(e)!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,t);if(ir(i)!="object")return i;throw TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Ac(e){var t=Sc(e,"string");return ir(t)=="symbol"?t:t+""}function Zt(e,t,r){return(t=Ac(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Bt(e){return Array.isArray(e)?e:e?[e]:[]}function Lt(e){for(let t in e)(e[t]===void 0||e[t]===null)&&delete e[t];return e}function Ht(e){return typeof e=="string"?!1:e&&!e.type&&"source"in e?(e.type="SpecificResource",!0):!!e&&e.type==="SpecificResource"}function dr(...e){return t=>e.reduce((r,i)=>i(r),t)}const wn=["Collection","Manifest","Canvas","AnnotationPage","AnnotationCollection","Annotation","ContentResource","Range","Service","Selector","Agent"];function $c(e,t){if(e==null)throw Error("Null or undefined is not a valid entity.");if(Array.isArray(e))throw Error("Array is not a valid entity");if(typeof e!="object"){if(t)return t;throw Error(`${typeof e} is not a valid entity`)}if(typeof e.type=="string"){let r=wn.indexOf(e.type);if(r!==-1)return wn[r]}if(e.profile)return"Service";throw Error("Resource type is not known")}var kc=class oa{constructor(t,r={}){Zt(this,"traversals",void 0),Zt(this,"options",void 0),Zt(this,"_traverseManifest",dr(this.traverseManifestItems.bind(this),this.traverseNavPlace.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this),this.traverseLinkedCanvases.bind(this),this.traverseManifestStructures.bind(this),this.traverseInlineAnnotationPages.bind(this))),Zt(this,"_traverseCanvas",dr(this.traverseCanvasItems.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this),this.traverseLinkedCanvases.bind(this),this.traverseInlineAnnotationPages.bind(this))),Zt(this,"_traverseAnnotationPage",dr(this.traverseAnnotationPageItems.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this))),Zt(this,"_traverseRange",dr(this.traverseRangeRanges.bind(this),this.traverseLinking.bind(this),this.traverseDescriptive.bind(this),this.traverseLinkedCanvases.bind(this))),this.traversals={collection:[],manifest:[],canvas:[],annotationCollection:[],annotationPage:[],annotation:[],contentResource:[],choice:[],range:[],service:[],agent:[],specificResource:[],geoJson:[],...t},this.options={allowUndefinedReturn:!1,...r}}static all(t){return new oa({collection:[t],manifest:[t],canvas:[t],annotationCollection:[t],annotationPage:[t],annotation:[t],contentResource:[t],choice:[t],range:[t],service:[t],geoJson:[t],specificResource:[t],agent:[t]})}traverseDescriptive(t){return t.thumbnail&&(t.thumbnail=Bt(t.thumbnail).map(r=>this.traverseType(r,{parent:t},this.traversals.contentResource))),t.provider&&(t.provider=t.provider.map(r=>this.traverseAgent(r,t))),t}traverseLinking(t){return t.seeAlso&&(t.seeAlso=Bt(t.seeAlso).map(r=>this.traverseType(r,{parent:t},this.traversals.contentResource))),t.service&&(t.service=Bt(t.service).map(r=>this.traverseService(r))),t.services&&(t.services=Bt(t.services).map(r=>this.traverseService(r,t))),t.logo&&(t.logo=Bt(t.logo).map(r=>this.traverseType(r,{parent:t},this.traversals.contentResource))),t.homepage&&(t.homepage=Bt(t.homepage).map(r=>this.traverseContentResource(r,t))),t.partOf&&(t.partOf=t.partOf.map(r=>typeof r=="string"||!r.type?this.traverseType(r,{parent:t},this.traversals.contentResource):r.type==="Canvas"?this.traverseType(r,{parent:t},this.traversals.canvas):r.type==="AnnotationCollection"?this.traverseType(r,{parent:t},this.traversals.annotationCollection):r.type==="Collection"?this.traverseType(r,{parent:t},this.traversals.collection):this.traverseType(r,{parent:t},this.traversals.contentResource))),t.start&&(Ht(t.start)?t.start=this.traverseSpecificResource(t.start,"Canvas",t):t.start=this.traverseType(t.start,{parent:t},this.traversals.canvas)),t.rendering&&(t.rendering=t.rendering.map(r=>this.traverseType(r,{parent:t},this.traversals.contentResource))),t.supplementary&&(t.supplementary=t.supplementary.map(r=>this.traverseType(r,{parent:t},this.traversals.contentResource))),t}traverseCollectionItems(t){return t.items&&t.items.map(r=>r.type==="Collection"?this.traverseCollection(r):this.traverseManifest(r)),t}traverseCollection(t,r){return this.traverseType(this.traverseDescriptive(this.traverseNavPlace(this.traverseInlineAnnotationPages(this.traverseLinking(this.traverseLinkedCanvases(this.traverseCollectionItems(t)))))),{parent:r},this.traversals.collection)}traverseGeoJson(t,r){return this.traverseType(t,{parent:r},this.traversals.geoJson)}traverseNavPlace(t){return t.navPlace&&(t.navPlace=this.traverseGeoJson(t.navPlace,t)),t}traverseManifestItems(t){return t.items&&(t.items=t.items.map(r=>this.traverseCanvas(r))),t}traverseManifestStructures(t){return t.structures&&(t.structures=t.structures.map(r=>this.traverseRange(r))),t}traverseManifest(t,r){return this.traverseType(this._traverseManifest(t),{parent:r},this.traversals.manifest)}traverseCanvasItems(t){return t.items=(t.items||[]).map(r=>this.traverseAnnotationPage(r,t)),t}traverseInlineAnnotationPages(t){return typeof t=="string"||!t||t.annotations&&(t.annotations=t.annotations.map(r=>this.traverseAnnotationPage(r,t))),t}traverseCanvas(t,r){return this.traverseType(this._traverseCanvas(t),{parent:r},this.traversals.canvas)}traverseAnnotationPageItems(t){return t.items&&(t.items=t.items.map(r=>this.traverseAnnotation(r,t))),t}traverseAnnotationPage(t,r){return this.traverseType(this._traverseAnnotationPage(t),{parent:r},this.traversals.annotationPage)}traverseAnnotationBody(t){return Array.isArray(t.body)?t.body=t.body.map(r=>this.traverseContentResource(r,t)):t.body&&(t.body=this.traverseContentResource(t.body,t)),t}traverseLinkedCanvases(t){return t.placeholderCanvas&&(t.placeholderCanvas=this.traverseCanvas(t.placeholderCanvas)),t.accompanyingCanvas&&(t.accompanyingCanvas=this.traverseCanvas(t.accompanyingCanvas)),t}traverseAnnotation(t,r){return this.traverseType(this.traverseLinking(this.traverseAnnotationBody(this.traverseDescriptive(t))),{parent:r},this.traversals.annotation)}traverseContentResourceLinking(t){return typeof t=="string"||!t||t&&t.service&&(t.service=Bt(t.service||[]).map(r=>this.traverseService(r,t))),t}traverseContentResource(t,r){return t.type==="Choice"&&(t.items=t.items.map(i=>this.traverseContentResource(i,t))),Ht(t)?this.traverseSpecificResource(t,"ContentResource"):this.traverseType(this.traverseInlineAnnotationPages(this.traverseContentResourceLinking(this.traverseDescriptive(t))),{parent:r},this.traversals.contentResource)}traverseSpecificResource(t,r,i){let n=t.source;return typeof t.source=="string"&&(n={id:t.source,type:r||"unknown"}),this.traverseType({...t,source:r==="Canvas"||n.type==="Canvas"?this.traverseType(n,{parent:i},this.traversals.canvas):r==="ContentResource"?this.traverseContentResource(n,{parent:i}):this.traverseUnknown(n,{parent:i,typeHint:r})},{parent:i},this.traversals.specificResource)}traverseRangeRanges(t){return t.items&&(t.items=t.items.map(r=>typeof r=="string"?this.traverseCanvas({id:r,type:"Canvas"},t):Ht(r)?this.traverseSpecificResource(r,"Canvas",t):r.type==="Manifest"?this.traverseManifest(r,t):this.traverseRange(r,t))),t}traverseRange(t,r){return this.traverseType(this._traverseRange(t),{parent:r},this.traversals.range)}traverseAgent(t,r){return this.traverseType(this.traverseDescriptive(this.traverseLinking(t)),{parent:r},this.traversals.agent)}traverseType(t,r,i){return i.reduce((n,s)=>{let a=s(n,r);return a===void 0&&!this.options.allowUndefinedReturn?n:a},t)}traverseService(t,r){let i=Object.assign({},t);return i&&i.service&&(i.service=Bt(i.service).map(n=>this.traverseService(n))),this.traverseType(i,{parent:r},this.traversals.service)}traverseUnknown(t,{parent:r,typeHint:i}={}){let n=$c(t,i);switch(n){case"Collection":return this.traverseCollection(t,r);case"Manifest":return this.traverseManifest(t,r);case"Canvas":return this.traverseCanvas(t,r);case"AnnotationPage":return this.traverseAnnotationPage(t,r);case"Annotation":return this.traverseAnnotation(t,r);case"ContentResource":return this.traverseContentResource(t,r);case"Range":return this.traverseRange(t,r);case"Service":return this.traverseService(t,r);case"Agent":return this.traverseAgent(t,r);default:throw Error(`Unknown or unsupported resource type of ${n}`)}}};const xn=["sc:Collection","sc:Manifest","sc:Canvas","sc:AnnotationList","oa:Annotation","sc:Range","sc:Layer","sc:Sequence","oa:Choice","Service","ContentResource"];function _c(e){if(e==null)throw Error("Null or undefined is not a valid entity.");if(Array.isArray(e))throw Error("Array is not a valid entity");if(typeof e!="object")throw Error(`${typeof e} is not a valid entity`);if(typeof e["@type"]=="string"){let t=xn.indexOf(e["@type"]);if(t!==-1)return xn[t]}if(e.profile)return"Service";if(e.format||e["@type"])return"ContentResource";throw Error("Resource type is not known")}var Oc=class la{constructor(t,r={}){Zt(this,"traversals",void 0),Zt(this,"options",void 0),this.traversals={collection:[],manifest:[],canvas:[],annotationList:[],sequence:[],annotation:[],contentResource:[],choice:[],range:[],service:[],layer:[],...t},this.options={convertPropsToArray:!0,mergeMemberProperties:!0,allowUndefinedReturn:!1,...r}}static all(t){return new la({collection:[t],manifest:[t],canvas:[t],annotationList:[t],sequence:[t],annotation:[t],contentResource:[t],choice:[t],range:[t],service:[t],layer:[t]})}traverseCollection(t){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseCollectionItems(t))),this.traversals.collection)}traverseCollectionItems(t){if(this.options.mergeMemberProperties){let r=[...(t.manifests||[]).map(s=>typeof s=="string"?{"@id":s,"@type":"sc:Manifest"}:(s["@type"]||(s["@type"]="sc:Manifest"),s)),...(t.collections||[]).map(s=>typeof s=="string"?{"@id":s,"@type":"sc:Collection"}:s),...t.members||[]],i=[],n=r.filter(s=>i.includes(s["@id"])?!1:(i.push(s["@id"]),!0));delete t.collections,delete t.manifests,t.members=n}return t.manifests&&(t.manifests=t.manifests.map(r=>{let i=r;return typeof r=="string"&&(i={"@id":r,"@type":"sc:Manifest"}),i["@type"]||(i["@type"]="sc:Manifest"),this.traverseManifest(i)})),t.collections&&(t.collections=t.collections.map(r=>this.traverseCollection(typeof r=="string"?{"@id":r,"@type":"sc:Collection"}:r))),t.members&&(t.members=t.members.map(r=>typeof r=="string"?r:r["@type"]==="sc:Collection"?this.traverseCollection(r):r["@type"]==="sc:Manifest"?this.traverseManifest(r):this.traverseUnknown(r))),t}traverseManifest(t){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseManifestItems(t))),this.traversals.manifest)}traverseManifestItems(t){return t.sequences&&(t.sequences=t.sequences.map(r=>this.traverseSequence(r))),t.structures&&(t.structures=t.structures.map(r=>this.traverseRange(r))),t}traverseSequence(t){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseSequenceItems(t))),this.traversals.sequence)}traverseSequenceItems(t){return t.canvases&&(t.canvases=t.canvases.map(r=>this.traverseCanvas(r))),t}traverseCanvas(t){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseCanvasItems(t))),this.traversals.canvas)}traverseCanvasItems(t){return t.images&&(t.images=t.images.map(r=>(r.on&&r["@type"]!=="oa:Annotation"&&r["@type"]!=="Annotation"&&(r["@type"]="oa:Annotation"),this.traverseAnnotation(r)))),t.otherContent&&(t.otherContent=t.otherContent.map(r=>this.traverseAnnotationList(r))),t}traverseRange(t){return t["@type"]!=="sc:Range"&&(t["@type"]="sc:Range"),this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseRangeItems(t))),this.traversals.range)}traverseRangeItems(t){if(this.options.mergeMemberProperties){let r=[...(t.ranges||[]).map(i=>typeof i=="string"?{"@id":i,"@type":"sc:Range"}:i),...(t.canvases||[]).map(i=>typeof i=="string"?{"@id":i,"@type":"sc:Canvas"}:i),...t.members||[]];delete t.ranges,delete t.canvases,t.members=r.length?r.map(i=>this.traverseUnknown(i)):void 0}return t}traverseAnnotationList(t){let r=typeof t=="string"?{"@id":t,"@type":"sc:AnnotationList"}:t;return this.traverseType(this.traverseDescriptive(this.traverseAnnotationListItems(r)),this.traversals.annotationList)}traverseAnnotationListItems(t){return t.resources&&(t.resources=t.resources.map(r=>this.traverseAnnotation(r))),t}traverseAnnotation(t){return this.traverseType(this.traverseDescriptive(this.traverseLinking(this.traverseAnnotationItems(t))),this.traversals.annotation)}traverseAnnotationItems(t){return t.resource&&(Array.isArray(t.resource)?t.resource=t.resource.map(r=>this.traverseContentResource(r)):t.resource=this.traverseContentResource(t.resource)),t.on,t}traverseLayer(t){return this.traverseType(this.traverseLinking(this.traverseLayerItems(t)),this.traversals.layer)}traverseLayerItems(t){return t.otherContent&&(t.otherContent=t.otherContent.map(r=>this.traverseAnnotationList(r))),t}traverseChoice(t){return this.traverseType(this.traverseChoiceItems(t),this.traversals.choice)}traverseChoiceItems(t){return t.default&&t.default!=="rdf:nil"&&(t.default=this.traverseContentResource(t.default)),t.item&&t.item!=="rdf:nil"&&(t.item=t.item.map(r=>this.traverseContentResource(r))),t}traverseService(t){return this.traverseType(this.traverseLinking(t),this.traversals.service)}traverseContentResource(t){return t["@type"]==="oa:Choice"?this.traverseChoice(t):this.traverseType(this.traverseDescriptive(this.traverseLinking(t)),this.traversals.contentResource)}traverseUnknown(t){if(!t["@type"]||typeof t=="string")return t;switch(_c(t)){case"sc:Collection":return this.traverseCollection(t);case"sc:Manifest":return this.traverseManifest(t);case"sc:Canvas":return this.traverseCanvas(t);case"sc:Sequence":return this.traverseSequence(t);case"sc:Range":return this.traverseRange(t);case"oa:Annotation":return this.traverseAnnotation(t);case"sc:AnnotationList":return this.traverseAnnotationList(t);case"sc:Layer":return this.traverseLayer(t);case"Service":return this.traverseService(t);case"oa:Choice":return this.traverseChoice(t);case"ContentResource":return this.traverseContentResource(t)}return t.profile?this.traverseService(t):t}traverseImageResource(t){let r=Array.isArray(t),i=Array.isArray(t)?t:[t],n=[];for(let s of i)typeof s=="string"?n.push(this.traverseContentResource({"@id":s,"@type":"dctypes:Image"})):n.push(this.traverseContentResource(s));return!r&&!this.options.convertPropsToArray?n[0]:n}traverseDescriptive(t){return t.thumbnail&&(t.thumbnail=this.traverseImageResource(t.thumbnail)),t.logo&&(t.logo=this.traverseImageResource(t.logo)),t}traverseOneOrMoreServices(t){let r=Array.isArray(t),i=Array.isArray(t)?t:[t],n=[];for(let s of i)n.push(this.traverseService(s));return!r&&!this.options.convertPropsToArray?n[0]:n}traverseLinking(t){return t.related&&(t.related=this.traverseOneOrManyType(t.related,this.traversals.contentResource)),t.rendering&&(t.rendering=this.traverseOneOrManyType(t.rendering,this.traversals.contentResource)),t.service&&(t.service=this.traverseOneOrMoreServices(t.service)),t.seeAlso&&(t.seeAlso=this.traverseOneOrManyType(t.seeAlso,this.traversals.contentResource)),t.within&&(typeof t.within=="string"||(t.within=this.traverseOneOrManyType(t.within,this.traversals.contentResource))),t.startCanvas&&(typeof t.startCanvas=="string"?t.startCanvas=this.traverseType({"@id":t.startCanvas,"@type":"sc:Canvas"},this.traversals.canvas):t.startCanvas&&this.traverseType(t.startCanvas,this.traversals.canvas)),t.contentLayer&&(typeof t.contentLayer=="string"?t.contentLayer=this.traverseLayer({"@id":t.contentLayer,"@type":"sc:Layer"}):t.contentLayer=this.traverseLayer(t.contentLayer)),t}traverseOneOrManyType(t,r){if(!Array.isArray(t))if(this.options.convertPropsToArray)t=[t];else return this.traverseType(t,r);return t.map(i=>this.traverseType(i,r))}traverseType(t,r){return r.reduce((i,n)=>{let s=n(i);return s===void 0&&!this.options.allowUndefinedReturn?i:s},t)}};const Ic=["http://iiif.io/api/image/2/level1","http://iiif.io/api/image/2/level2","http://library.stanford.edu/iiif/image-api/compliance.html#level1","http://library.stanford.edu/iiif/image-api/compliance.html#level2","http://library.stanford.edu/iiif/image-api/conformance.html#level1","http://library.stanford.edu/iiif/image-api/conformance.html#level2","http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1","http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2","http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1","http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2","http://iiif.io/api/image/1/level1.json","http://iiif.io/api/image/1/profiles/level1.json","http://iiif.io/api/image/1/level2.json","http://iiif.io/api/image/1/profiles/level2.json","http://iiif.io/api/image/2/level1.json","http://iiif.io/api/image/2/profiles/level1.json","http://iiif.io/api/image/2/level2.json","http://iiif.io/api/image/2/profiles/level2.json","level1","level2"],Ci={attributionLabel:"Attribution",providerId:"http://example.org/provider",providerName:""};function jc(e){if(typeof e=="string")return[e];if(!e)return[];let t=Array.isArray(e)?e:[e],r=[];for(let i of t){if(typeof i=="string"){r.push(i);continue}r.push({"@language":i["@language"]||i.language,"@value":i["@value"]||i.value})}return r}function we(e,t="none"){if(!e)return{none:[""]};let r=jc(e),i={};for(let n of r){if(typeof n=="string"){i[t]=i[t]?i[t]:[],i[t].push(n||"");continue}if(!n["@language"]){i[t]=i[t]?i[t]:[],i[t].push(n["@value"]||"");continue}let s=n["@language"];i[s]=i[s]?i[s]:[],i[s].push(n["@value"]||"")}return Object.keys(i).length===0?{none:[""]}:i}function ca(e){if(Array.isArray(e))return ca(e.find(t=>typeof t=="string"));if(Gr.indexOf(e)!==-1)return"level2";if(Ic.indexOf(e)!==-1)return"level1";if(Ql.indexOf(e)!==-1)return"level0";if(typeof e=="string")return e}function Pc(e){let t=Array.isArray(e)?e:[e];for(let r of t)switch(r){case"http://iiif.io/api/image/2/context.json":case"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2":return"ImageService2";case"http://iiif.io/api/image/1/context.json":case"http://library.stanford.edu/iiif/image-api/1.1/context.json":return"ImageService1";case"http://iiif.io/api/annex/openannotation/context.json":return"ImageApiSelector"}}function Tc(e){switch(e){case"http://iiif.io/api/image/2/level0.json":case"http://iiif.io/api/image/2/level1.json":case"http://iiif.io/api/image/2/level2.json":return"ImageService2";case"http://iiif.io/api/auth/1/kiosk":case"http://iiif.io/api/auth/1/login":case"http://iiif.io/api/auth/1/clickthrough":case"http://iiif.io/api/auth/1/external":case"http://iiif.io/api/auth/0/kiosk":case"http://iiif.io/api/auth/0/login":case"http://iiif.io/api/auth/0/clickthrough":case"http://iiif.io/api/auth/0/external":return"AuthCookieService1";case"http://iiif.io/api/auth/1/token":case"http://iiif.io/api/auth/0/token":return"AuthTokenService1";case"http://iiif.io/api/auth/1/logout":case"http://iiif.io/api/auth/0/logout":return"AuthLogoutService1";case"http://iiif.io/api/search/1/search":case"http://iiif.io/api/search/0/search":return"SearchService1";case"http://iiif.io/api/search/1/autocomplete":case"http://iiif.io/api/search/0/autocomplete":return"AutoCompleteService1"}}function Cn(e){for(let t of["sc","oa","dcterms","dctypes","iiif"])if(e.startsWith(`${t}:`))return e.slice(t.length+1);return e}const Fc=["Collection","Manifest","Annotation","AnnotationPage","Range","Service"];function tn(e){let t=e["@id"]||e.id,r=e["@type"]||e.type,i=e.profile||void 0,n=e["@context"]||void 0;if(i){let s=Tc(i);if(s)return s}if(n){let s=Pc(n);if(s)return s}if(r){if(Array.isArray(r)){if(r.indexOf("oa:CssStylesheet")!==-1)return"CssStylesheet";if(r.indexOf("cnt:ContentAsText")!==-1)return"TextualBody";r=r[0]}for(let s of["sc","oa","dcterms","dctypes","iiif"])if(r.startsWith(`${s}:`)){r=r.slice(s.length+1);break}switch(r){case"Layer":return"AnnotationCollection";case"AnnotationList":return"AnnotationPage";case"cnt:ContentAsText":return"TextualBody"}}if(r&&Fc.indexOf(r)!==-1)return r;if(e.format){if(e.format.startsWith("image/"))return"Image";if(e.format.startsWith("text/")||e.format==="application/pdf")return"Text";if(e.format.startsWith("application/"))return"Dataset"}return t&&(t.endsWith(".jpg")||t.endsWith(".png")||t.endsWith(".jpeg"))?"Image":r||"unknown"}const Ec=/^|["'\\>]http(s)?:\/\/(creativecommons.org|rightsstatements.org)\/[^"'\\<\n]+/gm;function Rc(e){let t=e.match(Ec);return t?t[0]:e}function Mc(e,t="Rights/License",r="none"){let i=null,n=[],s=Array.isArray(e)?e:[e];for(let a of s){let o=a?Rc(a):void 0;if(o&&(o.indexOf("creativecommons.org")!==-1||o.indexOf("rightsstatements.org")!==-1)){i=o.startsWith("https://")?`http://${o.slice(8)}`:o;continue}o&&n.push({label:{[r]:[t]},value:{[r]:[o]}})}return[i,n]}const Nc=["http://iiif.io/api/presentation/2/context.json","http://iiif.io/api/image/2/context.json","http://iiif.io/api/image/1/context.json","http://library.stanford.edu/iiif/image-api/1.1/context.json","http://iiif.io/api/search/1/context.json","http://iiif.io/api/search/0/context.json","http://iiif.io/api/auth/1/context.json","http://iiif.io/api/auth/0/context.json","http://iiif.io/api/annex/openannotation/context.json"];function Dc(e){if(e){let t=Array.isArray(e)?e:[e],r=[];for(let i of t)i==="http://iiif.io/api/presentation/2/context.json"&&r.push("http://iiif.io/api/presentation/3/context.json"),Nc.indexOf(i)===-1&&r.push(i);if(t.length)return r.length===1?r[0]:r}}function Lc(e){return e?e.map(t=>({label:we(t.label),value:we(t.value)})):[]}let Sn=0;function ua(e,t){let r=encodeURI(e.id||e["@id"]||"").trim();return r&&t?`${r}/${t}`:r||(Sn++,`http://example.org/${e["@type"]}${t?`/${t}`:""}/${Sn}`)}function Qt(e){let t=[...e.behavior||[]];e.viewingHint&&t.push(e.viewingHint);let r;return Array.isArray(e.motivation)?r=e.motivation.map(Cn):e.motivation&&(r=Cn(e.motivation)),{"@context":e["@context"]?Dc(e["@context"]):void 0,id:(e["@id"]||ua(e)).trim(),type:tn(e),behavior:t.length?t:void 0,height:e.height?e.height:void 0,width:e.width?e.width:void 0,motivation:r,viewingDirection:e.viewingDirection,profile:e.profile,format:e.format?e.format:void 0,duration:void 0,timeMode:void 0}}function Yt(e){let[t,r]=Mc(e.license),i=[...e.metadata?Lc(e.metadata):[],...r];return{rights:t,metadata:i.length?i:void 0,label:e.label?we(e.label):void 0,requiredStatement:e.attribution?{label:we(Ci.attributionLabel),value:we(e.attribution)}:void 0,navDate:e.navDate,summary:e.description?we(e.description):void 0,thumbnail:Wc(e.thumbnail)}}function Wc(e){return e&&(Array.isArray(e)?e:[e]).map(r=>typeof r=="string"?{id:r,type:"Image"}:(r.type==="unknown"&&(r.type="Image"),r))}function Uc(e){if(!e.within)return;let t=Array.isArray(e.within)?e.within:[e.within],r=[];for(let i of t)if(typeof i=="string"){if(i)switch(e["@type"]){case"sc:Manifest":r.push({id:i,type:"Collection"});break}}else i["@id"]&&r.push({id:i["@id"],type:tn(i)});return r.length?r:void 0}function le(e){let t=e.related?Array.isArray(e.related)?e.related:[e.related]:[],r=e.contentLayer;return{provider:e.logo||t.length?[{id:Ci.providerId,type:"Agent",homepage:t.length?[t[0]]:void 0,logo:e.logo?Array.isArray(e.logo)?e.logo:[e.logo]:void 0,label:we(Ci.providerName)}]:void 0,partOf:Uc(e),rendering:e.rendering,seeAlso:e.seeAlso,start:e.startCanvas,service:e.service?Bt(e.service):void 0,supplementary:r?[r]:void 0}}function Bc(e){return{chars:e.chars,format:e.format?e.format:void 0,language:e.language}}function ei(e,t){return e?typeof e=="string"?{id:e,type:t}:typeof(e==null?void 0:e["@id"])=="string"?{id:e["@id"],type:t}:typeof e.id=="string"?{id:e.id,type:t}:null:null}function zc(e){let t={};if(e.first){let r=ei(e.first,"Collection");r&&(t.first=r)}if((e.total||e.total===0)&&(t.total=e.total),e.prev){let r=ei(e.prev,"Collection");r&&(t.prev=r)}if(e.next){let r=ei(e.next,"Collection");r&&(t.next=r)}return t}function qc(e){let t=[];for(let r of e){let i={...r};i.items&&i.items.length===0&&delete i.items,t.push(i)}return t}function Hc(e){return Lt({...Qt(e),...Yt(e),...le(e),...zc(e),items:qc(e.members)})}function Gc(e){let t=[],r=[],i,n;for(let a of e.sequences||[])a.canvases.length&&t.push(...a.canvases),a.behavior&&r.push(...a.behavior),a.viewingDirection&&(n=a.viewingDirection),a.startCanvas&&(i=a.startCanvas);let s=Qt(e);return r.length&&(s.behavior?s.behavior.push(...r):s.behavior=r),Lt({...s,...Yt(e),...le(e),viewingDirection:n,start:i,items:t,structures:Qc(e.structures)})}function Qc(e){if(!e)return e;let t=new Map;for(let i of e)t.set(i.id,i);let r=[];for(let i of e)if(i.items){let n=i.items.map(s=>typeof s=="string"?(r.push(s),t.get(s)||s):s&&s.id?(r.push(s.id),t.get(s.id)||s):s);i.items=n}return e.filter(i=>r.indexOf(i.id)===-1)}function Yc(e){return Lt({...Qt(e),...Yt(e),...le(e),annotations:e.otherContent&&e.otherContent.length?e.otherContent:void 0,items:e.images&&e.images.length?[{id:ua(e,"annotation-page"),type:"AnnotationPage",items:e.images}]:void 0})}function Vc(e){return Lt({...Qt(e),...Yt(e),...le(e),items:e.resources&&e.resources.length?e.resources:void 0})}function Jc(e){return!e.canvases||e.canvases.length===0?{canvases:[],behavior:[]}:{canvases:e.canvases,behavior:e.viewingHint?[e.viewingHint]:[],viewingDirection:e.viewingDirection,startCanvas:e.startCanvas}}function Xc(e){function t(r){if(Array.isArray(r)){if(r.length>1)return{type:"List",items:r.map(t)};r=r[0]}if(typeof r=="string")return encodeURI(r).trim();if("@type"in r){let i;if(typeof r.full=="string")i=r.full;else if(r.full["@type"]==="dctypes:Image")i={id:r.full["@id"],type:"Image"};else if(r.full["@type"]==="sc:Canvas")i={id:r.full["@id"],type:"Canvas"};else throw Error(`Unsupported source type on annotation: ${r.full["@type"]}`);return{type:"SpecificResource",source:i,selector:Si(r.selector)}}else return encodeURI(r["@id"]).trim()}return Lt({...Qt(e),...Yt(e),...le(e),target:t(e.on),body:Array.isArray(e.resource)?e.resource.map(An):An(e.resource)})}function An(e){return e.type==="Choice"?e:ha(e)}function ha(e){let t=e;return Lt({...Qt(t),...Yt(t),...le(t),...Bc(t)})}function Kc(e){let t=[];return e.default&&e.default!=="rdf:nil"&&t.push(e.default),e.item&&e.item!=="rdf:nil"&&t.push(...e.item),Lt({...Qt(e),...Yt(e),items:t})}function Zc(e){return Lt({...Qt(e),...Yt(e),...le(e),items:e.members})}function tu(e){let{"@id":t,"@type":r,"@context":i,profile:n,...s}=e,a={};return t&&(a["@id"]=t),a["@type"]=tn(e),a["@type"]==="unknown"&&(i&&i.length&&(a["@context"]=i),a["@type"]="Service"),n&&(a.profile=ca(n)),Lt({...a,...s})}function eu(e){return Lt({...Qt(e),...Yt(e),...le(e)})}const ru=new Oc({collection:[Hc],manifest:[Gc],canvas:[Yc],annotationList:[Vc],sequence:[Jc],annotation:[Xc],contentResource:[ha],choice:[Kc],range:[Zc],service:[tu],layer:[eu]});function fa(e){return e&&e["@context"]&&(e["@context"]==="http://iiif.io/api/presentation/2/context.json"||Array.isArray(e["@context"])&&e["@context"].indexOf("http://iiif.io/api/presentation/2/context.json")!==-1||e["@context"]==="http://www.shared-canvas.org/ns/context.json")||e["@context"]==="http://iiif.io/api/image/2/context.json"||e["@id"]&&e["@type"]==="sc:Collection"||e["@id"]&&e["@type"]==="sc:Manifest"?(e["@context"]||(e["@context"]="http://iiif.io/api/presentation/2/context.json"),ru.traverseUnknown(e)):e}function Si(e){if((Array.isArray(e["@type"])&&e["@type"].includes("oa:SvgSelector")||e["@type"]=="oa:SvgSelector")&&("chars"in e||"value"in e))return{type:"SvgSelector",value:"chars"in e?e.chars:e.value};if(e["@type"]==="oa:FragmentSelector")return{type:"FragmentSelector",value:e.value};if(e["@type"]==="oa:Choice")return[Si(e.default),...(Array.isArray(e.item)?e.item:[e.item]).map(Si)];if(e["@type"]=="iiif:ImageApiSelector")return{type:"ImageApiSelector",region:"region"in e?e.region:void 0,rotation:"rotation"in e?e.rotation:void 0};throw Error(`Unsupported selector type: ${e["@type"]}`)}function Yr(e,t){let r="unknown";if(!e)return;if(typeof e=="string")return{id:e,type:r};if(Ht(e))return Yr(e.source);let i=e.type||e["@type"],n=e.id||e["@id"];if(i&&i.indexOf(":")!==-1&&(i=i.split(":").pop()),n&&i)return{id:n,type:i}}const He={},at="iiif-parser:hasPart",Gt="iiif-parser:partOf",Ge="iiif-parser:isExternal",Pt="__$UNSET$__",da="__$UNWRAP$__",P=[];Object.freeze(P),Object.freeze(He);function iu(e){if(e===He||Object.keys(e).length===0)return!0;for(let t in e)return!1;return!0}function en(e,t){if(t&&t["@explicit"]){let r={},i=Object.keys(t);for(let n of i)n===Gt||n==="@explicit"||(iu(t[n])?r[n]=e[n]:r[n]=t[n]);return r}return e}function pa(e,t,r){let i=Yr(t);if(!i)return[void 0,void 0];let n=e.requests[i.id],s=i.type||e.mapping[i.id];if(!s||n&&n.resourceUri&&(!e.entities[s]||!e.entities[s][n.resourceUri]))return[void 0,void 0];let a=e.entities[s][n?n.resourceUri:i.id];if(i.type&&!a)return pa(e,{id:i.id},r);if(a&&a[at]){let o=a[at].find(h=>r?h[Gt]===r.id:h[Gt]===a.id);return[en(a,o),a]}return[a,a]}const nu={id:"https://iiif-parser/annotation-page",type:"AnnotationPage",behavior:P,label:null,thumbnail:P,summary:null,requiredStatement:null,metadata:P,rights:null,provider:P,items:P,seeAlso:P,homepage:P,rendering:P,service:P},su={id:"https://iiif-parser/empty-canvas",type:"Canvas",label:null,behavior:P,thumbnail:P,accompanyingCanvas:null,placeholderCanvas:null,summary:null,requiredStatement:null,metadata:P,rights:null,navDate:null,provider:P,items:P,annotations:P,seeAlso:P,homepage:P,partOf:P,rendering:P,service:P,duration:0,height:0,width:0},au={id:"https://iiif-parser/empty-collection",type:"Collection",label:null,viewingDirection:"left-to-right",behavior:P,thumbnail:P,accompanyingCanvas:null,placeholderCanvas:null,summary:null,requiredStatement:null,metadata:P,rights:null,navDate:null,provider:P,items:P,annotations:P,seeAlso:P,homepage:P,partOf:P,rendering:P,service:P,services:P},ou={id:"https://iiif-parser/empty-manifest",type:"Manifest",annotations:P,behavior:P,homepage:P,items:P,label:null,metadata:P,navDate:null,provider:P,partOf:P,accompanyingCanvas:null,placeholderCanvas:null,rendering:P,requiredStatement:null,rights:null,seeAlso:P,service:P,services:P,start:null,structures:P,summary:null,thumbnail:P,viewingDirection:"left-to-right"},lu={id:"https://iiif-parser/empty-canvas",type:"Range",label:null,behavior:P,thumbnail:P,accompanyingCanvas:null,placeholderCanvas:null,summary:null,requiredStatement:null,metadata:P,rights:null,navDate:null,provider:P,items:P,annotations:P,seeAlso:P,homepage:P,partOf:P,rendering:P,service:P,start:null,supplementary:null,viewingDirection:"left-to-right"},cu={id:"https://iiif-parser/empty-agent",type:"Agent",label:{},logo:P,seeAlso:P,homepage:P},uu={id:"https://iiif-parser/empty-service",type:"UnknownService"};function xr(e){let[t,r]=(e||"").split("#");return!r||!hu(r)?[e||"",""]:[t,r]}function hu(e){return e.includes("xywh=")||e.includes("t=")}function Cr(e,t={}){if(Array.isArray(e))return Cr(e[0]);if(typeof e=="string"){let[r,i]=xr(e);return i?{type:"SpecificResource",source:{id:r,type:t.typeHint||"Unknown"},selector:{type:"FragmentSelector",value:i}}:{type:"SpecificResource",source:{id:r,type:t.typeMap&&t.typeMap[r]||t.typeHint||"Unknown"}}}if(e.type==="Choice"||e.type==="List"||e.type==="Composite"||e.type==="Independents")return Cr(e.items[0]);if(!e.type&&"source"in e&&(e.type="SpecificResource"),e.type==="SpecificResource"){e.source.type==="Canvas"&&e.source.partOf&&typeof e.source.partOf=="string"&&(e.source.partOf=[{id:e.source.partOf,type:"Manifest"}]);let r=typeof e.source=="string"?e.source:e.source.id,[,i]=xr(r);if(i){let n=Cr(r,t);n&&(e.selector=n.selector,e.source=n.source)}return e.selector?{...e,type:"SpecificResource",source:e.source,selector:e.selector}:{...e,type:"SpecificResource",source:e.source}}if(e.id){e.type==="Canvas"&&e.partOf&&typeof e.partOf=="string"&&(e.partOf=[{id:e.partOf,type:"Manifest"}]);let[r,i]=xr(e.id);return i?{type:"SpecificResource",source:{...e,id:r},selector:{type:"FragmentSelector",value:i}}:{type:"SpecificResource",source:{...e,id:r}}}return{type:"SpecificResource",source:e}}function fu(){return{Collection:{},Manifest:{},Canvas:{},AnnotationPage:{},AnnotationCollection:{},Annotation:{},ContentResource:{},Range:{},Service:{},Selector:{},Agent:{}}}function ga(e,t){if(typeof e=="string")return{id:e,type:t};if(!e.id)throw Error(`Invalid resource does not have an ID (${JSON.stringify(e)}, ${t})`);return e}function du(e,t){return(r,i)=>{let n=e[r]?e[r]:{};return(s,a)=>{let o=ga(s,i||r);return o&&o.id&&r?(n[o.id]=n[o.id]?$i(n[o.id],o,{parent:a.parent,isTopLevel:t.id===o.id}):$i({id:o.id,type:o.type},o,{parent:a.parent,isTopLevel:t.id===o.id}),{id:o.id,type:r==="ContentResource"?r:o.type}):o}}}function Ai(e,t,r){if(!t)return e;if(Array.isArray(e)){if(!Array.isArray(t))throw Error("Cannot merge array with non-array");let i=[...e];for(let n of t)if(n["@id"]&&!n.id&&(n.id=n["@id"]),n["@type"]&&!n.type&&(n.type=n["@type"]),n!=null)if(Array.isArray(n))i.push(n);else if(typeof n=="object"&&n.id&&n.type){let s=i.findIndex(a=>a.id===n.id&&a.type===n.type);s>=0&&(i[s]=Ai(i[s],n))}else e.indexOf(n)===-1&&i.push(n);return i}else if(typeof e=="object"){if(Array.isArray(t)||typeof t!="object")throw Error("Cannot merge object with non-object");let i={...e},n=[],s=[],a=Object.keys(e).filter(h=>h!==at&&h!=="id"&&h!=="type"),o={},l={};for(let[h,c]of Object.entries(t)){if(h===at||h==="id"||h==="type")continue;let u=i[h];u===c?s.push(h):u===P||!u?(n.push(h),i[h]=c):(u&&c&&(o[h]=u,l[h]=c),i[h]=Ai(u,c),i[h]===o[h]&&(s.push(h),delete o[h]))}if(r&&(r.parent&&r.parent.id||r.isTopLevel)){let h=[],c={};if(r.parent?c[Gt]=r.parent.id:r.isTopLevel&&(c[Gt]=e.id),i[at]&&i[at].length){let u=!(i[at]||[]).find(d=>d["@explicit"]),f=n.length>0||s.length!==a.length;if(u&&f)for(let d of i[at]){let p={...d},g=Object.keys(o);if(p){p["@explicit"]=!0;for(let m of a)m!==at&&(p[m]=He);for(let m of g)p[m]=o[m]}h.push(p)}else h.push(...i[at]);if(f){let d=Object.keys(l);c["@explicit"]=!0;for(let p of n)c[p]=He;for(let p of s)c[p]=He;for(let p of d)c[p]=l[p]}}c.id=i.id,c.type=i.type,h.push(c),i[at]=h}return i}else if(e)return e;return t}function $i(e,t,r){if(typeof e=="string")return e;if(t.id!==e.id||t.type!==e.type){if(t.type==="ImageService3")return t;if(e.type==="ImageService3")return e;throw Error(`Can only merge entities with identical identifiers and type! ${t.type}(${t.id}) => ${e.type}(${e.id})`)}return Ai({...e},t,r)}function pu(e){return(t,r)=>i=>{let{id:n,type:s}=ga(i,r||t);if(n===void 0)throw Error("Found invalid entity without an ID.");return t==="ContentResource"||t==="Service"?e[n]=t:e[n]=s,i}}function gu(e){let t=Object.assign({},e);if(t["@id"]&&(t.id=t["@id"]),t["@type"]&&(t.type=t["@type"]),t.service){let r=[];t.service=Array.isArray(t.service)?t.service:[t.service];for(let i of t.service)r.push({id:i["@id"]||i.id,type:i["@type"]||i.type});t.service=r}return Object.assign({},uu,t)}function mu(e){return t=>{e.Service=e.Service?e.Service:{};let r=t.id||t["@id"],i=gu(t);return i&&i.id&&(e.Service[i.id]?e.Service[r]=$i(e.Service[r],i):e.Service[r]=i),t}}function vu(e){let t=JSON.stringify(e),r=5381,i=t.length;for(;i;)r=r*33^t.charCodeAt(--i);let n=r>>>0,s=n.toString(16);return s.length%2?"0"+s:s}function ri(e){return t=>typeof t=="string"?{id:t,type:e}:t.id?t.type?t:{type:e,...t}:{id:`vault://${vu(t)}`,type:e,...t}}function Se(e){return t=>({...e,...t})}function Ne(e){return Array.isArray(e)?e:[e]}function yu(e){return e.body&&(e.body=Ne(e.body)),e.seeAlso&&(e.seeAlso=Ne(e.seeAlso)),e.audience&&(e.audience=Ne(e.audience)),e.accessibility&&(e.accessibility=Ne(e.accessibility)),e.motivation&&(e.motivation=Ne(e.motivation)),e}function ma(e,{typeHint:t,partOfTypeHint:r}={}){if(typeof e=="string"&&(e={id:e,type:t||"unknown"}),Ht(e))return typeof e.source=="string"&&(e.source={id:e.source,type:t||"unknown"}),e.source.type==="Canvas"&&e.source.partOf&&typeof e.source.partOf=="string"&&(e.source.partOf=[{id:e.source.partOf,type:r||"Manifest"}]),e;let i,[n,s]=xr(e.id);return e.id=n,s&&s&&(i={type:"FragmentSelector",value:s}),{type:"SpecificResource",source:e,selector:i}}function bu(e){let t=Object.assign({},e);return e&&e.items&&(t.items=e.items.map(r=>typeof r=="string"||r.type==="Canvas"?ma(r):r)),t}function wu(e){let t=Object.assign({},e);return t.start?(t.start=ma(t.start,{typeHint:"Canvas"}),t):e}function xu(e){let t=Object.assign({},e);return t.target?(t.target=Cr(t.target,{typeHint:"Canvas"}),t):e}function Cu(e){return e}function ii(e){return e.items===void 0&&(e[Ge]=!0),e}function Su(e){let t=fa(e),r=fu(),i={},n=du(r,t),s=pu(i),a=new kc({collection:[ii,Se(au),s("Collection"),n("Collection")],manifest:[ii,Se(ou),wu,s("Manifest"),n("Manifest")],canvas:[Se(su),s("Canvas"),n("Canvas")],annotationPage:[ii,ri("AnnotationPage"),Se(nu),s("AnnotationPage"),n("AnnotationPage")],annotation:[ri("Annotation"),yu,xu,s("Annotation"),n("Annotation")],contentResource:[ri("ContentResource"),s("ContentResource"),n("ContentResource")],range:[Se(lu),bu,s("Range","Canvas"),n("Range","Canvas")],agent:[Se(cu),s("Agent"),n("Agent")],specificResource:[Cu],service:[mu(r)]}),o=a.traverseUnknown(t);return{entities:r,resource:o,mapping:i}}function Au(e){let t={};for(let[r,i]of e){if(r===da&&i!==Pt)return i;i!==Pt&&i!=null&&(t[r]=i)}return t}function $u(e,t,r){if(!t.type||!t.id)throw Error("Unknown entity");if(!r[t.type])throw Error(`Serializer not found for ${t.type}`);function i(n,s,a=0){let o=r[n.type];if(!o)return Pt;if(a>20)throw Error("Circular reference: "+n.id+" "+n.type);let[l,h]=pa(e,n.type?n:n.id,s)||(n.id&&n.type?n:null);if(!l)return Pt;let c=o(l,e,{parent:s,isTopLevel:t.id===n.id,fullResource:h}),u=c.next();for(;!u.done;){let f=u.value,d=Pt;if(f)if(Array.isArray(f)){let p=[];for(let g of f)p.push(i(g,n,a+1));d=p}else d=i(f,n,a+1);u=c.next(d)}return u.value===Pt?Pt:Au(u.value)}return i(t)}function Qe(e,{allowSourceString:t=!0,allowString:r=!1,allowedStringType:i}={}){let n=s=>{if(t&&s&&s.source&&typeof s.source!="string"){let a=Object.keys(s.source);if(s.source.id&&s.source.type&&a.length===2)return{...s,source:s.source.id}}return s};if(e){if(e.source&&e.source.partOf)return n(e);let s=Object.keys(e);if(s.length===2&&e.type&&e.source||s.length===3&&e.type&&e.source&&s.indexOf("selector")!==-1&&!e.selector)return r&&(!i||i===e.source.type)?e.source.id:e.source.type==="ContentResource"?{type:"SpecificResource",source:e.source.id}:e.source;if(e.selector&&!Array.isArray(e.selector)&&typeof e.selector!="string"&&typeof e.styleClass!="string"&&e.selector.type==="FragmentSelector"){let a=`${e.source.id}#${e.selector.value}`;return r?a:{id:a,type:e.source.type}}}return n(e)}function ke(e){if(!e)return;let t=Object.keys(e);if(t.length!==0){if(t.length===1){let r=t[0];if(!r)return"";let i=(e[r]||[]).join("");return r==="@none"||r==="none"||r==="en"?i:{"@language":r,"@value":i}}return t.map(r=>({"@language":r,"@value":(e[r]||[]).join("")}))}}function va(e){return Array.isArray(e)?e.map(t=>va(t)):typeof e=="string"?e:e.type&&e.type==="Canvas"?e.id:e}function ne(e,t=!1){if(e)return e.length>1&&!t?e:e[0]||void 0}function ku(e){if(e){if(typeof e=="string")return{"@id":e};if("@id"in e){let t={...e};return delete t["@type"],t}return{"@context":"http://iiif.io/api/image/2/context.json","@id":e.id,profile:`http://iiif.io/api/image/2/profiles/${e.profile}.json`}}}function ue(e,t){return[["@id",e.id],["@type",t],["format",e.format],["height",e.height],["width",e.width],["viewingDirection",e.viewingDirection==="left-to-right"?void 0:e.viewingDirection],["license",e.license?e.license:void 0]]}function*he(e){let t=e.provider?yield e.provider[0]:void 0;return[["label",ke(e.label)],["metadata",e.metadata&&e.metadata.length?e.metadata.map(r=>({label:ke(r.label)||"",value:ke(r.value)||""})):void 0],["description",ke(e.summary)],["thumbnail",ne(yield e.thumbnail)],["navDate",e.navDate],["logo",t?ne(t.logo):void 0],["homepage",t?t.homepage:void 0],["attribution",e.requiredStatement?ke(e.requiredStatement.value):void 0]]}function*De(e){let t=e.start&&e.start.type&&e.start.type==="SpecificResource"?Qe(e.start):e.start;return[["seeAlso",ne(yield e.seeAlso)],["service",ne((e.service||[]).map(ku))],["rendering",ne(yield e.rendering)],["startCanvas",t?t.id:void 0]]}function _u(e){return e.type==="SpecificResource"}function Ou(e){return e&&e.type==="FragmentSelector"}function Iu(e){if(e&&_u(e)){let t=e.id,r=e.selector?Array.isArray(e.selector)?e.selector[0]:e.selector:void 0;return Ou(r)&&(t+="#"+r.value),t}return e==null?void 0:e.id}const ju={Manifest:function*(e,t,{isTopLevel:r}){return[...r?[["@context","http://iiif.io/api/presentation/2/context.json"]]:[],...ue(e,"sc:Manifest"),...yield*he(e),...yield*De(e),["sequences",[{"@id":`${e.id}/sequence0`,"@type":"sc:Sequence",canvases:yield e.items}]],["structures",yield e.structures]]},Canvas:function*(e){let t=yield e.items,r=t[0];return[...ue(e,"sc:Canvas"),...yield*he(e),...yield*De(e),["images",r?[r.resources]:void 0],["annotations",e.annotations&&e.annotations.length?ne(yield e.annotations):void 0]]},AnnotationPage:function*(e){return[...ue(e,"sc:AnnotationList"),...yield*he(e),["resources",e.items&&e.items.length?ne(yield e.items):void 0]]},Annotation:function*(e){return[["@id",e.id],["@type","oa:Annotation"],["motivation","sc:painting"],["on",va(e.target)],["resource",ne(yield e.body,!0)]]},ContentResource:function*(e){switch(e.type){case"Image":return[...ue(e,"dctypes:Image"),...yield*he(e),...yield*De(e)];case"Text":case"Dataset":default:return[...ue(e,void 0),...yield*he(e)]}},AnnotationCollection:function*(e){return[["@id",e.id],["@type","sc:Layer"],["label",ke(e.label)]]},Collection:function*(e){return[...ue(e,"sc:Collection"),...yield*he(e),...yield*De(e),["members",yield*e.items]]},Range:function*(e){let t=[],r=[];if(e.items)for(let i of e.items){let n=i.type==="SpecificResource"?i.source:i;if(n){let s=yield n;t.push({"@id":Iu(i),"@type":n.type,label:s?s.label:void 0,within:e.id}),n.type==="Canvas"&&r.push(n.id)}}return[...ue(e,"sc:Range"),...yield*he(e),...yield*De(e),["canvases",r.length===t.length?r:void 0],["members",r.length===t.length?void 0:t]]}};function fe(e){var t;return[["id",(t=e.id)!=null&&t.startsWith("vault://")?void 0:e.id],["type",e.type],["format",e.format],["profile",e.profile],["height",e.height||void 0],["width",e.width||void 0],["duration",e.duration||void 0],["viewingDirection",e.viewingDirection==="left-to-right"?void 0:e.viewingDirection],["behavior",e.behavior&&e.behavior.length?e.behavior:void 0],["timeMode",e.timeMode],["motivation",Array.isArray(e.motivation)?e.motivation[0]:e.motivation],["backgroundColor",e.backgroundColor||void 0],[at,Pt]]}function nt(e){if(e===Pt||!e||e.length===0)return;let t=e.filter(r=>r!==Pt);if(t.length!==0)return t}function ya(e){if(e&&e.type&&e.type==="ImageService2"){let{id:t,type:r,profile:i,...n}=e,s=typeof i=="string"?i:Array.isArray(i)?i.find(a=>typeof a=="string"):"";return{"@id":t,"@type":r,profile:s?s.startsWith("http")?s:`http://iiif.io/api/image/2/${s}.json`:"http://iiif.io/api/image/2/level0.json",...n}}return e}function $n(e){if(Array.isArray(e)||(e=e?[e]:[]),!(!e||e.length===0))return e.map(ya)}function*Jt(e){return[["label",e.label],["metadata",nt(e.metadata)],["summary",e.summary],["requiredStatement",e.requiredStatement],["rights",Array.isArray(e.rights)?e.rights[0]||void 0:e.rights||void 0],["navDate",e.navDate],["language",e.language],["thumbnail",nt(yield e.thumbnail)],["placeholderCanvas",yield e.placeholderCanvas],["accompanyingCanvas",yield e.accompanyingCanvas],["provider",nt(yield e.provider)]]}function*Xt(e,t){let r=[];for(let i of e.partOf||[])i.type==="Manifest"&&(t==null?void 0:t.type)==="Manifest"||r.push(yield i);return[["seeAlso",nt(yield e.seeAlso)],["service",nt($n(e.service))],["services",nt($n(e.services))],["rendering",nt(yield e.rendering)],["supplementary",nt(yield e.supplementary)],["homepage",nt(yield e.homepage)],["logo",nt(yield e.logo)],["partOf",nt(r)],["start",e.start?Qe(e.start):e.start]]}const Pu={Manifest:function*(e,t,{isTopLevel:r}){if(!r)return[...fe(e),...yield*Jt(e),["navPlace",e.navPlace]];let i="http://iiif.io/api/presentation/3/context.json";return(e.navPlace||kn(e))&&(i=["http://iiif.io/api/presentation/3/context.json","http://iiif.io/api/extension/navplace/context.json"]),[["@context",e["@context"]?e["@context"]:i],...fe(e),...yield*Jt(e),...yield*Xt(e),["items",yield e.items],["structures",nt(yield e.structures)],["annotations",nt(yield e.annotations)],["navPlace",e.navPlace]]},Canvas:function*(e,t,{parent:r}){return r&&r.type!=="Manifest"&&r.type!=="Canvas"?[["id",e.id]]:[...fe(e),...yield*Jt(e),...yield*Xt(e,r),["items",yield e.items],["annotations",nt(yield e.annotations)],["navPlace",e.navPlace]]},Agent:function*(e){return[["id",e.id],["type","Agent"],["label",e.label],...yield*Xt(e)]},AnnotationPage:function*(e){var i;let t=Object.entries(e).map(([n,s])=>[n,Array.isArray(s)?nt(s):s]).filter(([n,s])=>n!=="items"&&n!=="id"&&n!==at&&n!==Gt&&n!==Ge),r=yield e.items;return[["id",(i=e.id)!=null&&i.startsWith("vault://")?void 0:e.id],...t,...yield*Xt(e),["items",r.length||e[Ge]===!1?r:Pt]]},Service:function*(e){return[[da,ya(e)]]},Annotation:function*(e){let t=Object.entries(e).map(([i,n])=>i==="motivation"?[i,Array.isArray(n)?n[0]:n]:i==="target"?[i,Qe(n,{allowString:!0,allowSourceString:!0,allowedStringType:"Canvas"})]:[i,Array.isArray(n)?nt(n):n]).filter(([i])=>i!=="body"&&i!==at&&i!==Ge),r;if(Array.isArray(e.body)){let i=[];for(let n of e.body)if(n&&Ht(n)){let s={...n};n.source.type==="Canvas"?s.source=n.source:s.source=yield n.source,i.push(Qe(s,{allowSourceString:!0}))}else i.push(yield n);r=i}else e.body&&Ht(e.body)?(r={...e.body},r.source=yield e.body.source):r=yield e.body;return[...t,...yield*Jt(e),...yield*Xt(e),["body",r.length===1?r[0]:r]]},ContentResource:function*(e){return Tu([...fe(e),...yield*Jt(e),...yield*Xt(e),["annotations",nt(yield e.annotations)],["items",nt(yield e.items)]],e)},AnnotationCollection:function*(e){return[["id",e.id],["type","AnnotationCollection"],["label",e.label]]},Collection:function*(e,t,{isTopLevel:r}){if(r){let i="http://iiif.io/api/presentation/3/context.json";return(e.navPlace||kn(e))&&(i=["http://iiif.io/api/extension/navplace/context.json","http://iiif.io/api/presentation/3/context.json"]),[["@context",i],...fe(e),...yield*Jt(e),...yield*Xt(e),["items",nt(yield e.items)],["navPlace",e.navPlace]]}return[...fe(e),...yield*Jt(e),["navPlace",e.navPlace]]},Range:function*(e){let t=[];for(let r of e.items)r.type==="Range"?t.push(yield r):r&&r.type==="SpecificResource"?t.push(Qe(r)):t.push(r);return[...fe(e),...yield*Jt(e),...yield*Xt(e),["items",t],["annotations",nt(yield e.annotations)],["navPlace",e.navPlace]]}};function Tu(e,t){let r=Object.keys(t),i=e.map(([n])=>n);for(let n of r)n===at||n===Ge||i.indexOf(n)===-1&&t[n]!==void 0&&e.push([n,t[n]]);return e}function kn(e){if(!e.items||!Array.isArray(e.items))return!1;for(let t of e.items)if(t.navPlace)return!0;return!1}function Fu(e,t,r=[],i=!1,n=[]){if(n.length&&(t=t.filter(a=>n.indexOf(a)===-1)),!t||t.length===0)return;if(t.length===1)return t[0];if(!e)return t.indexOf("none")===-1?t[0]:"none";if(t.indexOf(e)!==-1)return e;let s=e.indexOf("-")===-1?null:e.slice(0,e.indexOf("-"));if(s&&t.indexOf(s)!==-1)return s;for(let a of r)if(t.indexOf(a)!==-1)return a;if(!i&&e){let a=t.map(o=>o.indexOf("-")===-1?null:o.slice(0,o.indexOf("-"))).indexOf(e);if(a!==-1)return t[a];for(let o of r){let l=o.indexOf("-")===-1?null:o.slice(0,o.indexOf("-")),h=l?t.indexOf(l):-1;if(h!==-1)return t[h]}}return t.indexOf("none")===-1?t.indexOf("@none")===-1?t[0]:"@none":"none"}function ba(e,t,r={}){let{strictFallback:i=!1,defaultText:n="",separator:s=`
|
|
4
|
+
`,fallbackLanguages:a=[],closest:o,skipLanguages:l}=r,h=o?t:Fu(t,Object.keys(e||{}),a,i,l);if(!e)return n;if(typeof e=="string")return e;let c=h?e[h]:void 0;if(c&&h){if(typeof c=="string")return c;if(c.length===1&&c[0]===""){let u=r.skipLanguages||[];return ba(e,t,{...r,skipLanguages:[...u,h]})}return c.join(s)}return""}var Eu=Object.create,wa=Object.defineProperty,Ru=Object.getOwnPropertyDescriptor,Mu=Object.getOwnPropertyNames,Nu=Object.getPrototypeOf,Du=Object.prototype.hasOwnProperty,xa=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Lu=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(var n=Mu(t),s=0,a=n.length,o;s<a;s++)o=n[s],!Du.call(e,o)&&o!==r&&wa(e,o,{get:(l=>t[l]).bind(null,o),enumerable:!(i=Ru(t,o))||i.enumerable});return e},Ca=(e,t,r)=>(r=e==null?{}:Eu(Nu(e)),Lu(wa(r,"default",{value:e,enumerable:!0}),e));const Wu=/^(-?(?:\d+|\d*\.\d+))(px|%)?$/,Uu=/^(-?(?:\d+|\d*\.\d+))(deg|rad|turn)?$/,_n=/([a-zA-Z0-9]+)\(([^)]*)\)/g;function Bu(e){if(e==="%")return"percent";if(!e||e==="px")return"pixel"}function je(e){let t=Wu.exec(e.trim());if(t)return{value:Number.parseFloat(t[1]),unit:Bu(t[2])}}function zu(e){let[t,r=t]=e.trim().split(/\s+/),i=je(t),n=je(r);if(!i||!n)return;let s={x:i.value,y:n.value};return i.unit&&i.unit===n.unit?s.unit=i.unit:(i.unit&&(s.xUnit=i.unit),n.unit&&(s.yUnit=n.unit)),s}function qu(e){let t=Uu.exec(e.trim());if(!t)return;let r=Number.parseFloat(t[1]),i=t[2]||"deg";return i==="rad"?r*180/Math.PI:i==="turn"?r*360:r}function ni(e,t){return e?{x:e.x+t.x,y:e.y+t.y,...e.unit&&e.unit===t.unit?{unit:e.unit}:{}}:t}function Hu(e){let t={},r=e.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim(),i=/([^{]+)\{([^}]+)\}/g,n;for(;(n=i.exec(r))!==null;){let s=n[1].trim(),a=n[2].trim(),o=s.match(/\.([a-zA-Z0-9_-]+)/);if(!o)continue;let l=o[1],h=a.split(";").filter(u=>u.trim()),c={};for(let u of h){let[f,d]=u.split(":").map(p=>p.trim());if(!(!f||!d))switch(f){case"background-color":c.backgroundColor=d;break;case"opacity":c.opacity=parseFloat(d);break;case"box-shadow":c.boxShadow=d;break;case"border-color":c.borderColor=d;break;case"border-width":c.borderWidth=d;break;case"border-style":c.borderStyle=d;break;case"outline-color":c.outlineColor=d;break;case"outline-width":c.outlineWidth=d;break;case"outline-offset":c.outlineOffset=d;break;case"outline-style":c.outlineStyle=d;break;case"border":c.border=d;break;case"outline":c.outline=d;break;case"background":c.background=d;break;case"transform":c.transform=d;break;case"transform-origin":c.transformOrigin=d;break}}t[l]=c}return t}function On(e){let t={};return e&&(e.fill&&(t.backgroundColor=e.fill,e.fillOpacity),e.stroke&&(t.borderColor=e.stroke),e.strokeWidth&&(t.borderWidth=e.strokeWidth)),t}function Gu(e){if(e)return zu(e)}function Qu(e){let t={};if(!e)return t;t.transform=e;let r;for(_n.lastIndex=0;(r=_n.exec(e))!==null;){let i=r[1].toLowerCase(),n=r[2].split(",").flatMap(s=>s.trim().split(/\s+/)).filter(Boolean);if(i==="rotate"){let s=qu(n[0]||"");s!==void 0&&(t.rotation=s);continue}if(i==="translatex"){let s=je(n[0]||"");s&&(t.translate=ni(t.translate,{x:s.value,y:0,...s.unit?{unit:s.unit}:{}}));continue}if(i==="translatey"){let s=je(n[0]||"");s&&(t.translate=ni(t.translate,{x:0,y:s.value,...s.unit?{unit:s.unit}:{}}));continue}if(i==="translate"){let s=je(n[0]||""),a=je(n[1]||"0");if(s&&a){let o={x:s.value,y:a.value};s.unit&&s.unit===a.unit?o.unit=s.unit:(s.unit&&(o.xUnit=s.unit),a.unit&&(o.yUnit=a.unit)),t.translate=ni(t.translate,o)}}}return t}function Yu(e){let t=Qu(e==null?void 0:e.transform),r=Gu(e==null?void 0:e.transformOrigin);return e!=null&&e.transformOrigin&&(t.transformOrigin=e.transformOrigin),r&&(t.rotationOrigin=r),t}function Sr(e){let t=Yu(e),r={};return t.rotation!==void 0&&(r.rotation=t.rotation),t.rotationOrigin&&(r.rotationOrigin=t.rotationOrigin),t.translate&&(r.translate=t.translate),(t.rotation!==void 0||t.rotationOrigin||t.translate||t.transform||t.transformOrigin)&&(r.transform=t),r}const In=new Map;function Vu(e,t){let r=In.get(e);if((r==null?void 0:r.css)===t)return r.styleMap;let i=Hu(t);return In.set(e,{css:t,styleMap:Object.fromEntries(Object.entries(i).map(([n,s])=>[n,s]))}),i}function Ar(e,t,r={}){if(!e||!t)return On(r||{});let i=On(r||{}),n=Object.entries(t);for(let[s,a]of n){if(!a)continue;let o=Vu(s,a),l=Object.entries(o);for(let[h,c]of l)h===e&&Object.assign(i,c)}return i}function Ju(e,t,r,i=1){return new Sa(e,t,r).subdivide(i)}function Xu(e,t,r,i,n=1){return new Zu(new Float64Array([e.x,e.y,t.x,t.y,r.x,r.y,i.x,i.y])).subdivide(n)}function Ku(e){return e.x*e.x+e.y*e.y}function Ye(e){let t=.67;return e/(1-t+(t**4+.25*e*e)**.25)}function Pe(e){let t=.39;return e*(1-t+Math.sqrt(t*t+.25*e*e))}var Sa=class{constructor(t,r,i){ut(this,"start",void 0),ut(this,"control",void 0),ut(this,"end",void 0),this.start=t,this.control=r,this.end=i}eval(t){let r=1-t;return{x:this.start.x*r*r+2*this.control.x*r*t+this.end.x*t*t,y:this.start.y*r*r+2*this.control.y*r*t+this.end.y*t*t}}mapToBasic(){let{x:t,y:r}=this.start,{x:i,y:n}=this.control,{x:s,y:a}=this.end,o=2*i-t-s,l=2*n-r-a,h=(i-t)*o+(n-r)*l,c=(s-i)*o+(a-n)*l,u=(s-t)*l-(a-r)*o,f=h/u,d=c/u;return{x0:t,x2:s,scale:Math.abs(u)/(Math.hypot(o,l)*Math.abs(d-f)),cross:u}}subdivide(t){let r=this.mapToBasic(),i=Ye(r.x0),n=Ye(r.x2),s=.5*Math.abs(n-i)*Math.sqrt(r.scale/t),a=Math.ceil(s),o=Pe(i),l=Pe(n),h=[0];for(let c=1;c<a;c++){let u=(Pe(i+(n-i)*c/a)-o)/(l-o);h.push(u)}return h.push(1),h.map(c=>this.eval(c))}},Zu=class Aa{constructor(t){ut(this,"c",void 0),this.c=t}weightsum(t,r,i,n){return{x:t*this.c[0]+r*this.c[2]+i*this.c[4]+n*this.c[6],y:t*this.c[1]+r*this.c[3]+i*this.c[5]+n*this.c[7]}}eval(t){let r=1-t,i=r*r*r,n=3*r*r*t,s=3*r*t*t,a=t*t*t;return this.weightsum(i,n,s,a)}deriv(t){let r=1-t,i=-3*r*r,n=3*t*t,s=-6*t*r-i,a=6*t*r-n;return this.weightsum(i,s,a,n)}midpoint_quadbez(){let t=this.weightsum(-.25,.75,.75,-.25);return new Sa({x:this.c[0],y:this.c[1]},t,{x:this.c[6],y:this.c[7]})}subsegment(t,r){let i=new Float64Array(8),n=this.eval(t),s=this.eval(r);i[0]=n.x,i[1]=n.y;let a=(r-t)/3,o=this.deriv(t);i[2]=n.x+a*o.x,i[3]=n.y+a*o.y;let l=this.deriv(r);return i[4]=s.x-a*l.x,i[5]=s.y-a*l.y,i[6]=s.x,i[7]=s.y,new Aa(i)}subdivide(t){let r=.1*t,i=t-r,n=Math.sqrt(i),s=Ku(this.weightsum(1,-3,3,-1)),a=Math.ceil((s/(432*r*r))**(1/6)),o=[],l=0;for(let p=0;p<a;p++){let g=p/a,m=(p+1)/a,y=this.subsegment(g,m).midpoint_quadbez(),b=y.mapToBasic(),w=Ye(b.x0),_=Ye(b.x2),C=Math.sqrt(b.scale),$=Math.abs(_-w)*C;if(Math.sign(b.x0)!=Math.sign(b.x2)){let A=n/C,x=n*Math.abs(_-w)/Ye(A);$=Math.max($,x)}o.push({quad:y,a0:w,a2:_,val:$}),l+=$}let h=.5*l/n,c=Math.ceil(h),u=[{x:this.c[0],y:this.c[1]}],f=0,d=0;for(let p=1;p<c;p++){let g=l*p/c;for(;f+o[d].val<g;)f+=o[d].val,d++;let m=o[d].a0,y=o[d].a2,b=Pe(m),w=Pe(y),_=(Pe(m+(y-m)*(g-f)/o[d].val)-b)/(w-b);u.push(o[d].quad.eval(_))}return u.push({x:this.c[6],y:this.c[7]}),u}},th=function(){function e(t,r){var i=[],n=!0,s=!1,a=void 0;try{for(var o=t[Symbol.iterator](),l;!(n=(l=o.next()).done)&&(i.push(l.value),!(r&&i.length===r));n=!0);}catch(h){s=!0,a=h}finally{try{!n&&o.return&&o.return()}finally{if(s)throw a}}return i}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw TypeError("Invalid attempt to destructure non-iterable instance")}}(),Ve=Math.PI*2,si=function(e,t,r,i,n,s,a){var o=e.x,l=e.y;o*=t,l*=r;var h=i*o-n*l,c=n*o+i*l;return{x:h+s,y:c+a}},eh=function(e,t){var r=t===1.5707963267948966?.551915024494:t===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(t/4),i=Math.cos(e),n=Math.sin(e),s=Math.cos(e+t),a=Math.sin(e+t);return[{x:i-n*r,y:n+i*r},{x:s+a*r,y:a-s*r},{x:s,y:a}]},jn=function(e,t,r,i){var n=e*i-t*r<0?-1:1,s=e*r+t*i;return s>1&&(s=1),s<-1&&(s=-1),n*Math.acos(s)},rh=function(e,t,r,i,n,s,a,o,l,h,c,u){var f=n**2,d=s**2,p=c**2,g=u**2,m=f*d-f*g-d*p;m<0&&(m=0),m/=f*g+d*p,m=Math.sqrt(m)*(a===o?-1:1);var y=m*n/s*u,b=m*-s/n*c,w=h*y-l*b+(e+r)/2,_=l*y+h*b+(t+i)/2,C=(c-y)/n,$=(u-b)/s,A=(-c-y)/n,x=(-u-b)/s,S=jn(1,0,C,$),I=jn(C,$,A,x);return o===0&&I>0&&(I-=Ve),o===1&&I<0&&(I+=Ve),[w,_,S,I]},ih=function(e){var t=e.px,r=e.py,i=e.cx,n=e.cy,s=e.rx,a=e.ry,o=e.xAxisRotation,l=o===void 0?0:o,h=e.largeArcFlag,c=h===void 0?0:h,u=e.sweepFlag,f=u===void 0?0:u,d=[];if(s===0||a===0)return[];var p=Math.sin(l*Ve/360),g=Math.cos(l*Ve/360),m=g*(t-i)/2+p*(r-n)/2,y=-p*(t-i)/2+g*(r-n)/2;if(m===0&&y===0)return[];s=Math.abs(s),a=Math.abs(a);var b=m**2/s**2+y**2/a**2;b>1&&(s*=Math.sqrt(b),a*=Math.sqrt(b));var w=th(rh(t,r,i,n,s,a,c,f,p,g,m,y),4),_=w[0],C=w[1],$=w[2],A=w[3],x=Math.abs(A)/(Ve/4);Math.abs(1-x)<1e-7&&(x=1);var S=Math.max(Math.ceil(x),1);A/=S;for(var I=0;I<S;I++)d.push(eh($,A)),$+=A;return d.map(function(O){var E=si(O[0],s,a,g,p,_,C),N=E.x,M=E.y,U=si(O[1],s,a,g,p,_,C),B=U.x,D=U.y,X=si(O[2],s,a,g,p,_,C);return{x1:N,y1:M,x2:B,y2:D,x:X.x,y:X.y}})},nh=xa((e,t)=>{t.exports=n;var r={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},i=/([astvzqmhlc])([^astvzqmhlc]*)/gi;function n(o){var l=[];return o.replace(i,function(h,c,u){var f=c.toLowerCase();for(u=a(u),f=="m"&&u.length>2&&(l.push([c].concat(u.splice(0,2))),f="l",c=c=="m"?"l":"L");;){if(u.length==r[f])return u.unshift(c),l.push(u);if(u.length<r[f])throw Error("malformed path data");l.push([c].concat(u.splice(0,r[f])))}}),l}var s=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;function a(o){var l=o.match(s);return l?l.map(Number):[]}}),sh=xa((e,t)=>{t.exports=r;function r(i){var n=0,s=0,a=0,o=0;return i.map(function(l){l=l.slice();var h=l[0],c=h.toUpperCase();if(h!=c)switch(l[0]=c,h){case"a":l[6]+=a,l[7]+=o;break;case"v":l[1]+=o;break;case"h":l[1]+=a;break;default:for(var u=1;u<l.length;)l[u++]+=a,l[u++]+=o}switch(c){case"Z":a=n,o=s;break;case"H":a=l[1];break;case"V":o=l[1];break;case"M":a=n=l[1],o=s=l[2];break;default:a=l[l.length-2],o=l[l.length-1]}return l})}}),ah=Ca(nh()),oh=Ca(sh());function lh(e){let t=(0,oh.default)((0,ah.default)(e)),r,i=0,n=0,s=0,a=0,o,l,h=0,c=0,u=[];for(let f=0;f<t.length;f++){let d=t[f],p=d[0];switch(p){case"M":i=d[1],n=d[2];break;case"H":d=["L",d[1],n];break;case"V":d=["L",i,d[1]];break;case"S":{let g=h,m=c;(r==="C"||r=="S")&&(g+=g-s,m+=m-a),d=["C",g,m,d[1],d[2],d[3],d[4]]}break;case"T":r==="Q"||r=="T"?(o=h*2-o,l=c*2-l):(o=h,l=c),d=["Q",o,l,d[1],d[2]];break;case"Q":o=d[1],l=d[2];break;case"A":{let g=ih({px:h,py:c,cx:d[6],cy:d[7],rx:d[1],ry:d[2],xAxisRotation:d[3],largeArcFlag:d[4],sweepFlag:d[5]});if(!g.length)continue;for(let[m,y]of g.entries())d=["C",y.x1,y.y1,y.x2,y.y2,y.x,y.y],m<g.length-1&&u.push(d);d=d}break;case"Z":d=["L",i,n];break}r=p,h=d[d.length-2],c=d[d.length-1],["C","Q","A"].indexOf(p)>-1?(s=d[d.length-4],a=d[d.length-3]):(s=h,a=c),u.push(d)}return u}const ch=/&?(xywh=)?(pixel:|percent:|pct:)?([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?),([0-9]+(?:\.[0-9]+)?)/,Pn=/&?(t=)(npt:)?([0-9]+(\.[0-9]+)?)?(,([0-9]+(\.[0-9]+)?))?/,Tn=/^rgba\((\d+),(\d+),(\d+),([0-9.]+)\)$/;function $r(e,{domParser:t,svgPreprocessor:r,iiifRenderingHints:i,loadedStylesheets:n}={},{styleClass:s}={}){if(Array.isArray(e))return mt(e.reduce((a,o)=>{let{selector:l,selectors:h,iiifRenderingHints:c}=$r(o,{domParser:t,svgPreprocessor:r,iiifRenderingHints:i,loadedStylesheets:n},{styleClass:s});return l&&(a.selector?(!a.selector.temporal&&l.temporal&&(a.selector.temporal=l.temporal),!a.selector.spatial&&l.spatial&&(a.selector.spatial=l.spatial),!a.selector.svg&&l.svg&&(a.selector.svg=l.svg),!a.selector.svgShape&&l.svgShape&&(a.selector.svgShape=l.svgShape)):a.selector=l,a.selectors.push(...h)),c&&(a.iiifRenderingHints=a.iiifRenderingHints||{type:"ImageApiSelector"},Object.assign(a.iiifRenderingHints,c)),a},{selector:null,selectors:[],iiifRenderingHints:i}));if(!e)return mt({selector:null,selectors:[],iiifRenderingHints:i});if(typeof e=="string"){let[a,o]=kr(e);return o?$r({type:"FragmentSelector",value:o},{svgPreprocessor:r,iiifRenderingHints:i,domParser:t,loadedStylesheets:n},{styleClass:s}):mt({selector:null,selectors:[],iiifRenderingHints:i})}if(e.type){if(e.type==="PointSelector"&&(e.t||e.t===0)){let a={type:"TemporalSelector",temporal:{startTime:e.t}};return mt({selector:a,selectors:[a],iiifRenderingHints:i})}if(e.type==="PointSelector"&&e.x&&e.y){let a={type:"PointSelector",spatial:{x:e.x,y:e.y}};return mt({selector:a,selectors:[a],iiifRenderingHints:i})}}if(dh(e)){let a=[];if(e.region){let o=$r({type:"FragmentSelector",value:"xywh="+e.region},{domParser:t,svgPreprocessor:r,iiifRenderingHints:i,loadedStylesheets:n},{styleClass:s});a.push(...o.selectors)}return mt({selector:a[0],selectors:a,iiifRenderingHints:i?{...i,...e}:e})}if(e.type==="FragmentSelector"){let a=ch.exec(e.value);if(a){let l=Ar(s,n),h={type:"BoxSelector",spatial:{unit:a[2]==="percent:"||a[2]==="pct:"?"percent":"pixel",x:Number.parseFloat(a[3]),y:Number.parseFloat(a[4]),width:Number.parseFloat(a[5]),height:Number.parseFloat(a[6])},boxStyle:l,...Sr(l)},c=e.value.match(Pn);if(c){let u=Ar(s,n);h={type:"TemporalBoxSelector",spatial:h.spatial,temporal:{startTime:c[3]?Number.parseFloat(c[3]):0,endTime:c[6]?Number.parseFloat(c[6]):void 0},boxStyle:u,...Sr(u)}}return mt({selector:h,selectors:[h],iiifRenderingHints:i})}let o=e.value.match(Pn);if(o){let l={type:"TemporalSelector",temporal:{startTime:o[3]?Number.parseFloat(o[3]):0,endTime:o[6]?Number.parseFloat(o[6]):void 0}};return mt({selector:l,selectors:[l],iiifRenderingHints:i})}return mt({selector:null,selectors:[],iiifRenderingHints:i})}if(e.type==="SvgSelector"&&"value"in e){t||(typeof window<"u"?t=new window.DOMParser:console.warn("No DOMParser available, cannot parse SVG selector, `points`, `spatial` and `style` will be unavailable and the SVG will not be normalized."));let a=[],o,l,h=(r==null?void 0:r(e.value))??e.value,c;if(t){let d=t.parseFromString(e.value,"image/svg+xml").querySelector("svg");if(!d)return console.warn(`Illegal SVG selector: ${e.value}`),mt({selector:null,selectors:[],iiifRenderingHints:i});let p;try{p=$a(d)}catch{return mt({selector:null,selectors:[],iiifRenderingHints:i})}p&&(a=p.points,c=p.shapeType,o=[Math.min(...a.map(g=>g[0])),Math.min(...a.map(g=>g[1])),Math.max(...a.map(g=>g[0])),Math.max(...a.map(g=>g[1]))],{style:l,svg:h}=fh(p.element)??{svg:h})}let u=Ar(s,n,l),f={type:"SvgSelector",svg:h,svgShape:c,style:l,boxStyle:u,...Sr(u),points:a.length?a:void 0,spatial:o?{unit:"pixel",x:o[0],y:o[1],width:o[2]-o[0],height:o[3]-o[1]}:void 0};return mt({selector:f,selectors:[f],iiifRenderingHints:i})}return mt({selector:null,selectors:[],iiifRenderingHints:i})}function uh(e){let t=e.map(i=>i[0]).reduce((i,n)=>(i[n]+=1,i),{C:0,Q:0,L:0,M:0}),r=new Set(e.map(i=>i[0]));if(t.C>0||t.Q>0)return"path";if(t.L>0&&(r.size===1||r.size===2&&r.has("M"))){if(t.L===4)return"rect";let i=e.slice(-1)[0];return e[0][0]==="M"&&i[0]==="L"&&i[1]==e[0][1]&&i[2]===e[0][2]||i[1]===0&&i[2]===0?"polygon":"polyline"}return"path"}function $a(e){var t;for(let r of Array.from(e.children))switch(r==null?void 0:r.tagName.toLowerCase()){case"g":{let i=$a(r);if(i)return i}continue;case"path":{let i=r.getAttribute("d");if(!i)continue;let n=lh(i);return{element:r,points:hh(n),shapeType:uh(n)}}case"circle":{let i=Number.parseFloat(r.getAttribute("cx")??"0"),n=Number.parseFloat(r.getAttribute("cy")??"0"),s=Number.parseFloat(r.getAttribute("r")??"0");if(!s)continue;let a=[];for(let o=0;o<=360;o+=12){let l=o*Math.PI/180;a.push([i+s*Math.cos(l),n+s*Math.sin(l)])}return{element:r,points:a,shapeType:"circle"}}case"ellipse":{let i=Number.parseFloat(r.getAttribute("cx")??"0"),n=Number.parseFloat(r.getAttribute("cy")??"0"),s=Number.parseFloat(r.getAttribute("rx")??"0"),a=Number.parseFloat(r.getAttribute("ry")??"0");if(!s&&!a)continue;let o=[];for(let l=0;l<=360;l+=12){let h=Math.tan(l/360*Math.PI),c=s*(1-h**2)/(1+h**2),u=a*2*h/(1+h**2);o.push([i+c,n+u])}return{element:r,points:o,shapeType:"ellipse"}}case"line":{let i=Number.parseFloat(r.getAttribute("x0")??"0"),n=Number.parseFloat(r.getAttribute("y0")??"0"),s=Number.parseFloat(r.getAttribute("x1")??"0"),a=Number.parseFloat(r.getAttribute("y1")??"0");if(i===s&&n===a)continue;return{element:r,points:[[i,n],[s,a]],shapeType:"polyline"}}case"polygon":case"polyline":{let i=((t=r.getAttribute("points"))==null?void 0:t.split(" ").map(s=>s.split(",").map(Number.parseFloat)))??[];if(!i.length)continue;let n="polyline";return r.tagName.toLowerCase()==="polygon"&&(i.push(i[0]),n="polygon"),{element:r,points:i,shapeType:n}}case"rect":{let i=Number.parseFloat(r.getAttribute("x")??"0"),n=Number.parseFloat(r.getAttribute("y")??"0"),s=Number.parseFloat(r.getAttribute("width")??"0"),a=Number.parseFloat(r.getAttribute("height")??"0");if(!s||!a)continue;return{element:r,points:[[i,n],[i+s,n],[i+s,n+a],[i,n+a],[i,n]],shapeType:"rect"}}default:continue}return null}function hh(e){let t=[];for(let r=0;r<e.length;r++){let i=t[t.length-1]??[0,0],n=e[r];switch(n[0]){case"M":case"L":t.push([n[1],n[2]]);continue;case"C":t.push(...Xu({x:i[0],y:i[1]},{x:n[1],y:n[2]},{x:n[3],y:n[4]},{x:n[5],y:n[6]}).map(s=>[s.x,s.y]).slice(1));continue;case"Q":t.push(...Ju({x:i[0],y:i[1]},{x:n[1],y:n[2]},{x:n[3],y:n[4]}).map(s=>[s.x,s.y]).slice(1));continue}}return t}function fh(e){let t={};if(e.hasAttribute("fill")?(t.fill=e.getAttribute("fill"),e.removeAttribute("fill")):e.style&&e.style.fill&&(t.fill=e.style.fill),t.fill){let i=Tn.exec(t.fill);i&&(t.fillOpacity=Number.parseFloat(i[4]),t.fill=`rgb(${i[1]}, ${i[2]}, ${i[3]})`)}if(e.hasAttribute("fill-opacity")?(t.fillOpacity=Number.parseFloat(e.getAttribute("fill-opacity")),e.removeAttribute("fill-opacity")):e.style&&e.style.fillOpacity&&(t.fillOpacity=Number.parseFloat(e.style.fillOpacity)),e.hasAttribute("stroke")?(t.stroke=e.getAttribute("stroke"),e.removeAttribute("stroke")):e.style&&e.style.stroke&&(t.stroke=e.style.stroke),t.stroke){let i=Tn.exec(t.stroke);i&&(t.strokeOpacity=Number.parseFloat(i[4]),t.stroke=`rgb(${i[1]}, ${i[2]}, ${i[3]})`)}e.hasAttribute("stroke-opacity")?(t.strokeOpacity=Number.parseFloat(e.getAttribute("stroke-opacity")),e.removeAttribute("stroke-opacity")):e.style&&e.style.strokeOpacity&&(t.strokeOpacity=Number.parseFloat(e.style.strokeOpacity)),e.hasAttribute("stroke-width")?(t.strokeWidth=e.getAttribute("stroke-width"),e.removeAttribute("stroke-width")):e.style&&e.style.strokeWidth&&(t.strokeWidth=e.style.strokeWidth),e.hasAttribute("stroke-dasharray")?(t.strokeDasharray=e.getAttribute("stroke-dasharray"),e.removeAttribute("stroke-dasharray")):e.style&&e.style.strokeDasharray&&(t.strokeDasharray=e.style.strokeDasharray);let r=e;for(;r.tagName.toLowerCase()!=="svg";)if(r=r.parentElement,r===null)throw Error("Could not find root SVG element");return{svg:r.outerHTML,style:Object.keys(t).length>0?t:void 0}}function dh(e){if(!e)return!1;let t=e.type||e["@type"];return t==="iiif:ImageApiSelector"||t==="ImageApiSelector"}function kr(e){let[t,r]=e.split("#");return!r||!ph(r)?[e,""]:[t,r]}function ph(e){return e.includes("xywh=")||e.includes("t=")}function mt(e){if(e.iiifRenderingHints){let t=e.iiifRenderingHints;if(t.rotation){let r=gh(`${t.rotation}`);if(r)if(e.selectors.length)for(let i of e.selectors)i.rotation=r;else e.selectors.push({type:"RotationSelector",rotation:r})}}else delete e.iiifRenderingHints;return e}function gh(e){let t=Number.parseFloat(e);return t&&e.startsWith("!")&&(t=360-t),t&&(t%=360),t===t&&t||0}function _e(e,t={}){if(Array.isArray(e))return _e(e[0],t);if(typeof e=="string"){let[r,i]=kr(e);return i?_e({type:"SpecificResource",source:{id:r,type:t.typeMap&&t.typeMap[r]||t.defaultType||"Canvas"},selector:{type:"FragmentSelector",value:i}},t):{type:"SpecificResource",source:{id:r,type:t.typeMap&&t.typeMap[r]||t.defaultType||"Canvas"},selector:null,selectors:[]}}if(e.type==="Choice"||e.type==="List"||e.type==="Composite"||e.type==="Independents")return _e(e.items[0],t);if(!e.type&&"source"in e&&(e.type="SpecificResource"),e.type==="SpecificResource"){e.source.type==="Canvas"&&e.source.partOf&&typeof e.source.partOf=="string"&&(e.source.partOf=[{id:e.source.partOf,type:"Manifest"}]);let r=e.styleClass||t.styleClass,i={selector:null,selectors:[]};if(typeof e.source=="string"){let[,a]=kr(e.source);if(a){let o=_e(e.source,{...t,styleClass:r});e.source=o.source,i={selector:o.selector,selectors:o.selectors}}}let{selector:n,selectors:s}=e.selector?$r(e.selector,t,{styleClass:r}):i;return{type:"SpecificResource",source:e.source,selector:n,selectors:s}}if(e.id){e.type==="Canvas"&&e.partOf&&typeof e.partOf=="string"&&(e.partOf=[{id:e.partOf,type:"Manifest"}]);let[r,i]=kr(e.id);return i?_e({type:"SpecificResource",source:{...e,id:r},selector:{type:"FragmentSelector",value:i}},t):{type:"SpecificResource",source:{...e,id:r},selector:null,selectors:[]}}return{type:"SpecificResource",source:e,selector:null,selectors:[]}}function mh(e){return e.type==="SpecificResource"?[e.source,{selector:e.selector,...e.styleClass?{styleClass:e.styleClass}:{}}]:[e,{selector:null}]}function vh(e){if(!e)return;let t=Array.isArray(e)?e:[e],r={};for(let i of t){if((i==null?void 0:i.type)!=="CssStylesheet"||!("value"in i))continue;let n=Array.isArray(i.value)?i.value.join(`
|
|
5
|
+
`):i.value;n&&(r[i.id||`inline-${Object.keys(r).length}`]=n)}return Object.keys(r).length?r:void 0}function yh(e=Ki){function t(n){let s=n?typeof n=="string"?e.get(n):n:null;if(!s)return[];let a=e.get(s.items,{parent:s}),o=[];for(let l of a)o.push(...e.get(l.items,{parent:l}));return o}function r(n,s=[]){let a=Array.isArray(n)?n:t(n),o=[],l={items:[],type:"complex-choice"},h=[];for(let c of a){if(c.type!=="Annotation")throw Error("getPaintables() accept either a canvas or list of annotations");let u=Array.from(Array.isArray(c.body)?c.body:[c.body]);for(let f of u){let[d,{selector:p,styleClass:g}]=mh(f),m=e.get(d),y=(m.type||"unknown").toLowerCase();if(y==="choice"){let C=e.get(m.items,{parent:m.id}),$=s.length?s.map(A=>C.find(x=>x.id===A)).filter(Boolean):[C[0]];$.length===0&&$.push(C[0]),l.items.push({type:"single-choice",items:C.map(A=>({id:A.id,label:A.label,selected:$.indexOf(A)!==-1})),label:d.label}),u.push(...$);continue}o.indexOf(y)===-1&&o.push(y);let b=g?vh(c.stylesheet):void 0,w=g?Ar(g,b):void 0,_=w?Sr(w):{};h.push({type:y,annotationId:c.id,annotation:c,resource:m,target:c.target,selector:p,...g?{styleClass:g}:{},...w&&Object.keys(w).length?{style:w}:{},..._})}}return{types:o,items:h,choice:l.items.length<2?l.items[0]||null:l,allChoices:l.items.length?l:null}}function i(n){let{choice:s}=r(n);return s}return{getAllPaintingAnnotations:t,getPaintables:r,extractChoices:i}}function bh(e,t){return Ht(e)?typeof e.source=="string"?{...e,source:t}:{...e,source:{...e.source||{},id:t}}:{...e,id:t}}const Z=function(e){return function(){let t={type:e,getType:()=>e,toString:()=>e};return(r,i)=>({...t,...r!==void 0&&{payload:r},...i!==void 0&&{meta:i}})}},ka="@iiif/IMPORT_ENTITIES",_a="@iiif/MODIFY_ENTITY_FIELD",Oa="@iiif/REORDER_ENTITY_FIELD",Ia="@iiif/MOVE_ENTITY",ki="@iiif/MOVE_ENTITIES",ja="@iiif/ADD_REFERENCE",_i="@iiif/UPDATE_REFERENCE",Pa="@iiif/CHANGE_REFERENCE_IDENTIFIER",Ta="@iiif/REMOVE_REFERENCE",Fa="@iiif/ADD_METADATA",Ea="@iiif/REMOVE_METADATA",Oi="@iiif/UPDATE_METADATA",Ra="@iiif/REORDER_METADATA",Ma=Z(ka)(),wh=Z(_a)(),xh=Z(Oa)(),Ch=Z(Ia)(),Sh=Z(ki)(),Ah=Z(ja)(),$h=Z(Ta)(),kh=Z(_i)(),_h=Z(Pa)(),Oh=Z(Fa)(),Ih=Z(Oi)(),jh=Z(Ea)(),Ph=Z(Ra)(),Th={importEntities:Ma,modifyEntityField:wh,reorderEntityField:xh,addReference:Ah,removeReference:$h,updateReference:kh,changeReferenceIdentifier:_h,addMetadata:Oh,removeMetadata:jh,updateMetadata:Ih,reorderMetadata:Ph,moveEntity:Ch,moveEntities:Sh},Na="@iiif/ADD_MAPPING",Da="@iiif/ADD_MAPPINGS",Fh=Z(Na)(),Eh=Z(Da)(),Ii="RESOURCE_ERROR",La="RESOURCE_LOADING",ji="RESOURCE_READY",Wa="@iiif/REQUEST_RESOURCE",Ua="@iiif/REQUEST_ERROR",Ba="@iiif/REQUEST_MISMATCH",za="@iiif/REQUEST_COMPLETE",Rh="@iiif/REQUEST_OFFLINE_RESOURCE",Mh=Z(Wa)(),Pi=Z(Ua)(),Nh=Z(Ba)(),Dh=Z(za)(),rn="@iiif/BATCH",Lh="@iiif/BATCH_IMPORT",Ti=Z(rn)(),qa="@iiif/SET_META_VALUE",Ha="@iiif/SET_META_VALUE_DYNAMIC",Ga="@iiif/UNSET_META_VALUE",Fn={setMetaValue:Z(qa)(),setMetaValueDynamic:Z(Ha)(),unsetMetaValue:Z(Ga)()},Wh=(e,t)=>{let{entities:r,resource:i,mapping:n}=Su(t);if(i.id===void 0)return[Pi({id:e,message:"ID is not defined in resource."})];let s=[Ma({entities:r}),Eh({mapping:n})];return i.id!==e&&(s.push(Fh({id:e,type:i.type})),s.push(Nh({requestId:e,actualId:i.id}))),s.push(Dh({id:e})),s},En=Number.isNaN||function(e){return typeof e=="number"&&e!==e};function Uh(e,t){return!!(e===t||En(e)&&En(t))}function Rn(e,t){if(!Array.isArray(e)||!Array.isArray(t))return e===t;if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Uh(e[r],t[r]))return!1;return!0}function ai(e,t,r){let i=e.iiif.requests[t],n=e.iiif.mapping[t];if(!n||!e.iiif.entities[n][i.resourceUri])return;let s=e.iiif.entities[n][i.resourceUri];return s&&s[at]?en(s,s[at].find(a=>a[Gt]===s.id)):s}function Bh(e){return e&&typeof e.then=="function"}function Mn(e,t,{waitTimeout:r=30}={}){return(i,n,s)=>{let a=e.getStore(),o=a.getState(),l=o.iiif.requests[i];if(l){if(l.loadingState===ji){let c=ai(o,i);if(c)return c}switch(l.loadingState){case Ii:break;case La:return(async()=>{let c,u=!1;try{let f=await Promise.race([new Promise((d,p)=>{u||(c=a.subscribe(()=>{let g=a.getState();if(g.iiif.requests[i].loadingState===Ii){p();return}if(g.iiif.requests[i].loadingState===ji){let m=ai(g,i);m?d(m):p()}}))}),new Promise((d,p)=>setTimeout(()=>{u=!0,p()},r*60*1e3))]);if(c&&c(),f)return f}catch{c&&c()}})()}}e.dispatch(Mh({id:i}));let h=c=>{if(!c)return;!c.id&&!c["@id"]&&(c["@type"]&&(c["@id"]=i),c.id=i);let u=Wh(i,c);return e.dispatch(Ti({actions:u})),ai(a.getState(),i)};try{let c=t(i,n);return Bh(c)?(async()=>{try{let u=await c;return s&&(u=s(u)),h(u)}catch(u){throw e.dispatch(Pi({id:i,message:u.toString()})),u}})():h(s?s(c):c)}catch(c){throw e.dispatch(Pi({id:i,message:c.toString()})),c}}}function Qa(){return{Collection:{},Manifest:{},Canvas:{},AnnotationPage:{},AnnotationCollection:{},Annotation:{},ContentResource:{},Range:{},Service:{},Selector:{},Agent:{}}}const oi={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},zh=(e,t)=>(r,i,n)=>(n.dispatch=s=>(r(a=>e(a,s),!1,s),s),n.dispatchFromDevtools=!0,{dispatch:(...s)=>n.dispatch(...s),...t}),Fi=new Map,pr=e=>{let t=Fi.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([r,i])=>[r,i.getState()])):{}},qh=(e,t,r)=>{if(e===void 0)return{type:"untracked",connection:t.connect(r)};let i=Fi.get(r.name);if(i)return{type:"tracked",store:e,...i};let n={connection:t.connect(r),stores:{}};return Fi.set(r.name,n),{type:"tracked",store:e,...n}},Hh=(e,t={})=>(r,i,n)=>{let{enabled:s,anonymousActionType:a,store:o,...l}=t,h;try{h=(s??(oi?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!h)return(oi?"production":void 0)!=="production"&&s&&console.warn("[zustand devtools middleware] Please install/enable Redux devtools extension"),e(r,i,n);let{connection:c,...u}=qh(o,h,l),f=!0;n.setState=(g,m,y)=>{let b=r(g,m);if(!f)return b;let w=y===void 0?{type:a||"anonymous"}:typeof y=="string"?{type:y}:y;return o===void 0?(c==null||c.send(w,i()),b):(c==null||c.send({...w,type:`${o}/${w.type}`},{...pr(l.name),[o]:n.getState()}),b)};let d=(...g)=>{let m=f;f=!1,r(...g),f=m},p=e(n.setState,i,n);if(u.type==="untracked"?c==null||c.init(p):(u.stores[u.store]=n,c==null||c.init(Object.fromEntries(Object.entries(u.stores).map(([g,m])=>[g,g===u.store?p:m.getState()])))),n.dispatchFromDevtools&&typeof n.dispatch=="function"){let g=!1,m=n.dispatch;n.dispatch=(...y)=>{(oi?"production":void 0)!=="production"&&y[0].type==="__setState"&&!g&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),g=!0),m(...y)}}return c.subscribe(g=>{var m;switch(g.type){case"ACTION":if(typeof g.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return li(g.payload,y=>{if(y.type==="__setState"){if(o===void 0){d(y.state);return}Object.keys(y.state).length!==1&&console.error(`
|
|
6
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
7
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
8
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
9
|
+
`);let b=y.state[o];if(b==null)return;JSON.stringify(n.getState())!==JSON.stringify(b)&&d(b);return}n.dispatchFromDevtools&&typeof n.dispatch=="function"&&n.dispatch(y)});case"DISPATCH":switch(g.payload.type){case"RESET":return d(p),o===void 0?c==null?void 0:c.init(n.getState()):c==null?void 0:c.init(pr(l.name));case"COMMIT":if(o===void 0){c==null||c.init(n.getState());return}return c==null?void 0:c.init(pr(l.name));case"ROLLBACK":return li(g.state,y=>{if(o===void 0){d(y),c==null||c.init(n.getState());return}d(y[o]),c==null||c.init(pr(l.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return li(g.state,y=>{if(o===void 0){d(y);return}JSON.stringify(n.getState())!==JSON.stringify(y[o])&&d(y[o])});case"IMPORT_STATE":{let{nextLiftedState:y}=g.payload,b=(m=y.computedStates.slice(-1)[0])==null?void 0:m.state;if(!b)return;d(o===void 0?b:b[o]),c==null||c.send(null,y);return}case"PAUSE_RECORDING":return f=!f}return}}),p},li=(e,t)=>{let r;try{r=JSON.parse(e)}catch(i){console.error("[zustand devtools middleware] Could not parse the received json",i)}r!==void 0&&t(r)},Gh=e=>(t,r,i)=>{let n=i.subscribe;return i.subscribe=(s,a,o)=>{let l=s;if(a){let h=(o==null?void 0:o.equalityFn)||Object.is,c=s(i.getState());l=u=>{let f=s(u);if(!h(c,f)){let d=c;a(c=f,d)}},o!=null&&o.fireImmediately&&a(c,c)}return n(l)},e(t,r,i)},Qh=(e={},t)=>{switch(t.type){case Na:return{...e,[t.payload.id]:t.payload.type};case Da:return{...e,...t.payload.mapping};default:return e}};function Le(e,t,r,i){return!(!e[r]||!e[r][t]||!e[r][t][i]||!Array.isArray(e[r][t][i]))}function Yh(e,t){let r={},i=[];for(let[n,s]of Object.entries(e||{})){i.push(n);let a=(t||{})[n];if(!a||a.length===0){r[n]=s;continue}r[n]=a}for(let[n,s]of Object.entries(t||{}))i.indexOf(n)===-1&&(r[n]=s);return r}function F(e){return e.payload||{}}function Vh(e,t,r){if(!e[t]||!Array.isArray(e[t]))return null;let i=r.index===void 0?e[t].findIndex(n=>{var s;return n?((s=Yr(n))==null?void 0:s.id)===r.id:!1}):r.index;return i===-1?null:{entity:e[t][i],index:i}}function Nn(e,t){var r;if(!(!(t!=null&&t.id)||!(t!=null&&t.type)))return(r=e[t.type])==null?void 0:r[t.id]}function gr(e,t){return e===void 0?t:e}const Ya=(e=Qa(),t)=>{var i,n;let r=(s,a)=>({...e,[F(t).type]:{...e[F(t).type],[F(t).id]:{...s,...a}}});switch(t.type){case _a:{if(!e[F(t).type]||!e[F(t).type][F(t).id])return e;let s=e[F(t).type][F(t).id];return typeof s=="string"?e:r(s,{[F(t).key]:F(t).value})}case Oa:{if(!Le(e,F(t).id,F(t).type,F(t).key))return e;let s=e[F(t).type][F(t).id];if(typeof s=="string")return e;let a=Array.from(s[F(t).key]),[o]=a.splice(F(t).startIndex,1);return a.splice(F(t).endIndex,0,o),r(s,{[F(t).key]:a})}case ki:{let s=F(t).subjects,a=F(t).from,o=F(t).to||a,l=Nn(e,a),h=(o==null?void 0:o.key)||a.key;if(!Le(e,a.id,a.type,a.key)||!Le(e,o.id,o.type,o.key))return e;let c=[],u=[];if(s.type==="slice"){let b=s.startIndex,w=s.length;c=Array.from(l[a.key]),u=c.splice(b,w)}else{let b=Array.from(l[a.key]);for(let w of s.items){let _=Vh(l,a.key,w);_&&(u.push(_.entity),b[_.index]=null),c=b.filter(C=>C!==null)}}let f={...l,[a.key]:c},d={...e,[a.type]:{...e[a.type],[a.id]:f}},p=Nn(d,o);if(!p)return e;let g=(o==null?void 0:o.index)===void 0?p[h].length:o.index,m=Array.from(p[o.key]);m.splice(g,0,...u);let y={...p,[h]:m};return{...d,[o.type]:{...d[o.type],[o.id]:y}}}case Ia:return Ya(e,{type:ki,payload:{subjects:{type:"list",items:[F(t).subject]},from:F(t).from,to:F(t).to}});case Pa:{let{id:s,index:a,key:o,newIdentifier:l,reference:h,type:c}=F(t),u=e[c][s],f=Yr(h);if(!u||!u[o]||!f||a<0)return e;let d=u[o],p=d[a],g=(i=e[f.type])==null?void 0:i[f.id];if(!g||!p)return e;let m=bh(p,l),y=Array.from(d);y.splice(gr(a,y.length+1),1,m);let b=r(u,{[o]:y}),w={...g,id:l};w["iiif-parser:hasPart"]&&(w["iiif-parser:hasPart"]=w["iiif-parser:hasPart"].filter(C=>C["iiif-parser:partOf"]===s).map(C=>({...C,id:l})));let _={...b[f.type],[l]:w};return b[f.type]=_,b}case ka:{let s=Object.keys(F(t).entities),a={...e};for(let o of s){let l=F(t).entities[o],h={...e[o]||{}},c=!1,u=Object.keys(l||{})||[];if(l&&u){for(let f of u)c=!0,h[f]=e[o][f]?Yh(e[o][f],l[f]):l[f];c&&(a[o]=h)}}return a}case ja:{if(!Le(e,F(t).id,F(t).type,F(t).key))return e;let s=e[F(t).type][F(t).id],a=Array.from(s[F(t).key]);return a.splice(gr(F(t).index,a.length+1),0,F(t).reference),r(s,{[F(t).key]:a})}case _i:case Ta:{if(!Le(e,F(t).id,F(t).type,F(t).key))return e;let s=e[F(t).type][F(t).id],a=Array.from(s[F(t).key]),o=gr(F(t).index,a.findIndex(l=>l&&l.id===F(t).reference.id));return o===-1||((n=a[o])==null?void 0:n.id)!==F(t).reference.id?e:(t.type===_i?a.splice(o,1,F(t).reference):a.splice(o,1),r(s,{[F(t).key]:a}))}case Fa:{let s=e[F(t).type][F(t).id];if(!s)return e;let a=Array.from(s.metadata||[]),o=F(t);return a.splice(gr(t.payload.beforeIndex,a.length+1),0,{label:o.label,value:o.label}),r(s,{metadata:a})}case Ra:{let s=e[F(t).type][F(t).id];if(typeof s=="string"||!s)return e;let a=Array.from(s.metadata||[]),[o]=a.splice(F(t).startIndex,1);return a.splice(F(t).endIndex,0,o),r(s,{metadata:a})}case Oi:case Ea:{let s=e[F(t).type][F(t).id],a=Array.from(s.metadata||[]),o=F(t).atIndex;return o===void 0||o===-1||!a[o]?e:(t.type===Oi?a.splice(o,1,{label:F(t).label,value:F(t).value}):a.splice(o,1),r(s,{metadata:a}))}default:return e}},Jh=(e={},t)=>{switch(t.type){case Wa:case Rh:return{...e,[t.payload.id]:{requestUri:t.payload.id,loadingState:La,uriMismatch:!1,resourceUri:t.payload.id}};case Ba:return{...e,[t.payload.requestId]:{...e[t.payload.requestId]||{},uriMismatch:!0,resourceUri:t.payload.actualId},[t.payload.actualId]:{requestUri:t.payload.requestId,loadingState:e[t.payload.requestId].loadingState,uriMismatch:!0,resourceUri:t.payload.actualId}};case Ua:return{...e,[t.payload.id]:{...e[t.payload.id]||{},loadingState:Ii,error:t.payload.message}};case za:return{...e,[t.payload.id]:{...e[t.payload.id]||{},loadingState:ji,error:void 0}}}return e},Xh=(e={},t)=>{let{id:r,updateValue:i,value:n,meta:s,key:a}=t&&t.payload||{};switch(t.type){case qa:return{...e,[r]:{...e[r]||{},[s]:{...e[r]&&e[r][s]||{},[a]:n}}};case Ha:return{...e,[r]:{...e[r]||{},[s]:{...e[r]&&e[r][s]||{},[a]:e[r]&&e[r][s]?i(e[r][s][a]):i(void 0)}}};case Ga:return e[r]&&e[r][s]&&e[r][s][a]?{...e,[r]:{...e[r]||{},[s]:{...e[r]&&e[r][s]||{},[a]:void 0}}}:e;default:return e}};function Va(e={}){let t=Object.keys(e);return function(r={},i){let n=!1,s={};for(let a=0;a<t.length;a++){let o=t[a];s[o]=e[o](r[o],i),n=n||s[o]!==r[o]}return n?s:r}}function Kh(e){return(t,r)=>r&&r.type===rn?r.payload.actions.reduce(e,t):r&&r.type===Lh?{...t,iiif:{...t.iiif,...r.payload.state}}:e(t,r)}const Zh=Va({mapping:Qh,entities:Ya,requests:Jh,meta:Xh});function tf(){return{iiif:{entities:Qa(),meta:{},mapping:{},requests:{}}}}function ef(e={}){let{enableDevtools:t=!1,iiifStoreName:r="iiif",defaultState:i=tf(),customReducers:n={}}=e,s=Kh(Va({[r]:Zh,...n}));return As(Gh((typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION__?Hh:(a,o)=>a)(zh(s,i),{enabled:t})))}function ft(e,t,r,i=!0){t[Te]=t[Te]||[],t[Te].push(e);let n=new Map;Object.defineProperty(t,e,{enumerable:i,get(){if(t[me][e]===void 0)return;let s=t[me][e];if(!s)return s;let a=r.get(t[me][e],{parent:this.id?{id:this.id,type:this.type}:void 0});return n.has(a)||(n.clear(),n.set(a,ve(a,r))),n.get(a)},set(s){t[me][e]!==s&&(this[pe]?r.modifyEntityField({id:this.id,type:this.type},e,Ja(s)):this[me][e]=s)}})}const me=Symbol.for("_refs_"),pe=Symbol.for("_reactive_"),Te=Symbol.for("_defined_"),Dn=Symbol.for("_parent_");function rf(e,t=!1,r){let i={id:"",type:"unknown",[Te]:[],[me]:{},[Dn]:null,[pe]:null,is(n){return typeof n=="string"?this.id===n:n.id?n.id===this.id:!1},reactive(){if(!this[pe])return this[pe]=this.subscribe(()=>this.refresh(),!0),()=>{this.unreactive()}},refresh(){if(this.id){let n=this.unwrap();for(let s of Object.keys(n||{}))this[Te].includes(s)?this[me][s]=n[s]:this[s]=n[s]}},unreactive(){this[pe]&&(this[pe](),this[pe]=null)},unwrap(){if(!this.id)throw Error("Invalid object");let n=this[Dn];return e.get(this.id,{parent:n?{id:n,type:"unknown"}:void 0})},toPresentation3(){return e.toPresentation3(this.unwrap())},toPresentation2(){return e.toPresentation2(this.unwrap())},valueOf(){return this.unwrap()},toJSON(){let n=this;return{...n,items:n.items,annotations:n.annotations,structures:n.structures,seeAlso:n.seeAlso,service:n.service,services:n.services,rendering:n.rendering,partOf:n.partOf,start:n.start,supplementary:n.supplementary,homepage:n.homepage,thumbnail:n.thumbnail,placeholderCanvas:n.placeholderCanvas,accompanyingCanvas:n.accompanyingCanvas,provider:n.provider}},subscribe(n,s=!0){return e.subscribe(()=>this.id?e.get(this.id):null,n,s)}};return ft("items",i,e),ft("annotations",i,e),ft("structures",i,e),ft("seeAlso",i,e),ft("rendering",i,e),ft("partOf",i,e),ft("start",i,e,!1),ft("supplementary",i,e),ft("homepage",i,e),ft("thumbnail",i,e),ft("placeholderCanvas",i,e,!1),ft("accompanyingCanvas",i,e,!1),ft("provider",i,e),ft("body",i,e),ft("logo",i,e),i}function nf(e){return!!e[Te]}function Ja(e){return Array.isArray(e)?e.map(t=>Ja(t)):!e||!e.type?e:{id:e.id,type:e.type}}function ve(e,t,r=!1,i){if(Array.isArray(e))return e.map(o=>ve(o,t,r));if(!e||!e.type||!e.id)return e;let n=rf(t,r),s=Object.create(n),a=Object.assign(s,e);return r&&a.reactive(),a}function Ln(e){switch(e){case"Image":case"Video":case"Sound":case"Dataset":case"Text":case"Composite":case"List":case"Independents":case"Audience":return"ContentResource";case"ImageService1":case"ImageService2":case"ImageService3":return"Service"}return e}var sf=class{constructor(t,r){ut(this,"options",void 0),ut(this,"store",void 0),ut(this,"emitter",void 0),ut(this,"isBatching",!1),ut(this,"batchQueue",[]),ut(this,"remoteFetcher",void 0),ut(this,"staticFetcher",void 0),ut(this,"defaultFetcher",i=>fetch(i).then(n=>{if(n.status===200)return n.json();{let s=Error(`${n.status} ${n.statusText}`);throw s.name="HTTPError",s}})),this.options=Object.assign({reducers:{},customFetcher:this.defaultFetcher,enableDevtools:!0},t||{}),this.store=r||ef({customReducers:this.options.reducers,defaultState:this.options.defaultState,enableDevtools:this.options.enableDevtools}),this.emitter=$s(),this.remoteFetcher=Mn(this,this.options.customFetcher),this.staticFetcher=Mn(this,(i,n)=>n)}batch(t){this.isBatching=!0;try{t(this),this.isBatching=!1,this.dispatch(Ti({actions:this.batchQueue}))}catch(r){throw this.batchQueue=[],this.isBatching=!1,r}this.batchQueue=[]}async asyncBatch(t){this.isBatching=!0;try{await t(this),this.isBatching=!1,this.dispatch(Ti({actions:this.batchQueue}))}catch(r){throw this.batchQueue=[],this.isBatching=!1,r}this.batchQueue=[]}modifyEntityField(t,r,i){this.dispatch(Th.modifyEntityField({id:t.id,type:t.type,key:r,value:i}))}dispatch(t){if(this.isBatching)this.batchQueue.push(t);else{if(t.type===rn){for(let n of t.payload.actions)this.emitter.emit(n.type,{action:n,state:this.store.getState()});this.store.dispatch(t);let i=this.getState();for(let n of t.payload.actions)this.emitter.emit(`after:${n.type}`,{action:n,state:i});return}this.emitter.emit(t.type,{action:t,state:this.store.getState()}),this.store.dispatch(t);let r=this.store.getState();this.emitter.emit(`after:${t.type}`,{action:t,state:r});return}}on(t,r){return this.emitter.on(t,r),()=>{this.emitter.off(t,r)}}serialize(t,r){return $u(this.getState().iiif,t,r)}toPresentation2(t){return this.serialize(t,ju)}toPresentation3(t){return this.serialize(t,Pu)}hydrate(t,r,i={}){return this.get(t,r,{...i,skipSelfReturn:!1})}get(t,r,i={}){typeof r!="string"&&(i=r||{},r=void 0);let{skipSelfReturn:n=!0}=i||{},s=i.parent?typeof i.parent=="string"?i.parent:i.parent.id:void 0;if(Array.isArray(t))return t.map(u=>this.get(u,i));let a=this.getState();if(Ht(t)&&!i.preserveSpecificResources&&(t=t.source),typeof t=="string"){let u=Ln(r||a.iiif.mapping[t]);if(!u)return n?null:{id:t,type:"unknown"};t={id:t,type:u}}if(t&&t.partOf&&!s&&!i.skipPartOfCheck){let u=Array.isArray(t.partOf)?t.partOf[0]:t.partOf;u&&(typeof u=="string"&&(s=u),typeof u.id=="string"&&(s=u.id))}let o=Ln(r||(t==null?void 0:t.type)),l=t==null?void 0:t.id,h=a.iiif.entities[o];if(!h){let u=a.iiif.requests[l];return u&&u.resourceUri!==l?this.get(u.resourceUri,i):n?null:t}let c=h[t.id];return c&&c[at]?en(c,c[at].find(u=>s?u[Gt]===s:u[Gt]===c.id)):h[t.id]||(n?null:t)}select(t){return t(this.getState())}getStore(){return this.store}getState(){return this.store.getState()}deep(t,r){if(t===void 0)return this.get(r,{skipSelfReturn:!1});if(typeof t=="function")try{let n=t(this.get(r,{skipSelfReturn:!1})),s=a=>this.deep(a,n);return s.size=Array.isArray(n)?n.length:1,s}catch{let n=s=>this.deep(s,void 0);return n.size=0,n}let i=n=>this.deep(n,t);return i.size=Array.isArray(t)?t.length:1,i}loadManifest(t,r,i){let n=typeof t=="string"?t:t.id;return this.load(n,r,i)}loadCollection(t,r,i){let n=typeof t=="string"?t:t.id;return this.load(n,r,i)}load(t,r,i){let n=typeof t=="string"?t:t.id;return r?Promise.resolve(this.staticFetcher(n,r,i)):Promise.resolve(this.remoteFetcher(n,{},i))}loadSync(t,r,i){let n=typeof t=="string"?t:t.id;return this.staticFetcher(n,r,i)}loadManifestSync(t,r,i){let n=typeof t=="string"?t:t.id;return this.loadSync(n,r,i)}loadCollectionSync(t,r,i){let n=typeof t=="string"?t:t.id;return this.loadSync(n,r,i)}areInputsEqual(t,r){return Rn(t,r)}subscribe(t,r,i){return i===void 0&&(r===void 0||r===!1||r===!0)&&(i=r,r=t,t=n=>n),this.store.subscribe(t,n=>r(n,this),{equalityFn:Rn,fireImmediately:!i})}async ensureLoaded(t){let r=typeof t=="string"?t:t.id;this.requestStatus(r)||await this.load(r)}requestStatus(t){return this.select(r=>r.iiif.requests[t])}getPaginationState(t){let r=typeof t=="string"?t:t.id;if(!r)return null;let i=this.getResourceMeta(r,"@vault/pagination");if(i!=null&&i.state)return i.state;let n=this.get(t);if(n.first){let s={currentPage:null,currentPageIndex:null,isFetching:!1,isFullyLoaded:!1,next:n.first,page:1,pages:[],previous:null,totalItems:n.total,currentLength:0};return this.setMetaValue([r,"@vault/pagination","state"],s),s}return null}async loadNextPage(t,r){var d;let i=typeof t=="string"?t:t.id;if(!i)return[null,null];let n=this.getPaginationState(t);if(!n||n.isFullyLoaded||!n.next)return[null,null];if(n.isFetching)return[n,null];let s=typeof n.next=="string"?n.next:n.next.id,a=n.currentPage,o={...n,isFetching:!0};this.setMetaValue([i,"@vault/pagination","state"],o);let l;try{l=await this.loadCollection(s,r,p=>{let{id:g,"@id":m,...y}=p||{};return m?{"@id":s,...y}:{id:s,...y}})}catch(p){let g={...n,isFetching:!1,error:p};return this.setMetaValue([i,"@vault/pagination","state"],g),[g,null]}if(!l){let p={...n,isFetching:!1,error:Error("Collection not found")};return this.setMetaValue([i,"@vault/pagination","state"],p),[p,null]}let h=this.get(i),c=[...h.items||[],...l.items||[]].map(p=>({id:p.id,type:p.type}));this.modifyEntityField({id:i,type:"Collection"},"items",c);let u=this.getPaginationState(t);if(!u)throw Error("Pagination state not found");let f={...u,isFetching:!1,error:null,currentPage:l.id,next:((d=l.next)==null?void 0:d.id)||null,currentPageIndex:u.pages.length,currentLength:c.length,pages:[...u.pages,{id:l.id,type:"Collection",startIndex:h.items.length,pageLength:l.items.length,order:typeof u.currentPageIndex=="number"?u.currentPageIndex+1:0}],isFullyLoaded:!l.next,previous:a,page:u.pages.length+1};return this.setMetaValue([i,"@vault/pagination","state"],f),[f,l]}getResourceMeta(t,r){let i=this.getState().iiif.meta[t];if(i)return r?i[r]:i}getObject(t,r,i={}){let{reactive:n,...s}=i;return ve(this.get(t,r,s),this,n)}async loadObject(t,r){return ve(await this.load(t,r),this)}async loadManifestObject(t,r){return ve(await this.loadManifest(t,r),this)}async loadCollectionObject(t,r){return ve(await this.loadCollection(t,r),this)}wrapObject(t){return ve(this.get(t,{skipSelfReturn:!1}),this)}isWrapped(t){return nf(t)}setMetaValue([t,r,i],n){this.dispatch(typeof n=="function"?Fn.setMetaValueDynamic({id:t,meta:r,key:i,updateValue:n}):Fn.setMetaValue({id:t,meta:r,key:i,value:n}))}};function af(){return typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}function of(e){let t=af();try{let i=t.IIIF_VAULT;if(i)return i}catch{}let r=new sf(e);try{t.IIIF_VAULT=r}catch{}return r}const lf=fa;var cf=Object.defineProperty,uf=(e,t,r)=>t in e?cf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,mr=(e,t,r)=>(uf(e,typeof t!="symbol"?t+"":t,r),r);function ye(e){return e.endsWith("info.json")?e:e.endsWith("/")?`${e}info.json`:`${e}/info.json`}var hf="http://library.stanford.edu/iiif/image-api/compliance.html#level0",Xa="http://library.stanford.edu/iiif/image-api/compliance.html#level1",Ka="http://library.stanford.edu/iiif/image-api/compliance.html#level2",ff="http://library.stanford.edu/iiif/image-api/conformance.html#level0",Za="http://library.stanford.edu/iiif/image-api/conformance.html#level1",to="http://library.stanford.edu/iiif/image-api/conformance.html#level2",df="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0",eo="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level1",ro="http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level2",pf="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level0",io="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level1",no="http://library.stanford.edu/iiif/image-api/1.1/conformance.html#level2",gf="http://iiif.io/api/image/1/level0.json",mf="http://iiif.io/api/image/1/profiles/level0.json",so="http://iiif.io/api/image/1/level1.json",ao="http://iiif.io/api/image/1/profiles/level1.json",oo="http://iiif.io/api/image/1/level2.json",lo="http://iiif.io/api/image/1/profiles/level2.json",vf="http://iiif.io/api/image/2/level0.json",yf="http://iiif.io/api/image/2/profiles/level0.json",co="http://iiif.io/api/image/2/level1.json",uo="http://iiif.io/api/image/2/profiles/level1.json",ho="http://iiif.io/api/image/2/level2.json",fo="http://iiif.io/api/image/2/profiles/level2.json",bf="level0",po="level1",go="level2",wf="http://iiif.io/api/image/2/level0",mo="http://iiif.io/api/image/2/level1",vo="http://iiif.io/api/image/2/level2",xf="https://iiif.io/api/image/1.1/compliance/#level0",yo="https://iiif.io/api/image/1.1/compliance/#level1",bo="https://iiif.io/api/image/1.1/compliance/#level2",wo=[vo,Ka,to,ro,no,oo,lo,ho,fo,go,bo],xo=[...wo,mo,Xa,Za,eo,io,so,ao,co,uo,po,yo],Cf=[wf,mo,vo,hf,Xa,Ka,ff,Za,to,df,eo,ro,pf,io,no,gf,mf,so,ao,oo,lo,vf,yf,co,uo,ho,fo,bf,po,go,xf,yo,bo],Sf={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["sizeByWhListed"]},Af={extraFormats:["jpg"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPx","regionSquare","sizeByWhListed","sizeByH","sizeByW","sizeByWh"]},$f={extraFormats:["jpg","png"],extraQualities:["default"],extraFeatures:["baseUriRedirect","cors","jsonldMediaType","regionByPct","regionByPx","regionSquare","rotationBy90s","sizeByWhListed","sizeByConfinedWh","sizeByH","sizeByPct","sizeByW","sizeByWh"]};function kf(e){return wo.indexOf(e)!==-1?$f:xo.indexOf(e)!==-1?Af:Sf}function _f(e){let t=e?Array.isArray(e.profile)?e.profile:[e.profile]:[],r={extraQualities:[],extraFormats:[],extraFeatures:[]};for(let i of t)if(typeof i=="string"&&(i=kf(i)),!!i){if(i.formats)for(let n of i.formats)r.extraFormats.indexOf(n)===-1&&r.extraFormats.push(n);if(i.qualities)for(let n of i.qualities)r.extraQualities.indexOf(n)===-1&&r.extraQualities.push(n);if(i.supports)for(let n of i.supports)r.extraFeatures.indexOf(n)===-1&&r.extraFeatures.push(n);if(i.maxHeight&&(r.maxHeight=i.maxHeight),i.maxWidth&&(r.maxWidth=i.maxWidth),i.maxArea&&(r.maxArea=i.maxArea),i.extraFormats)for(let n of i.extraFormats)r.extraFormats.indexOf(n)===-1&&r.extraFormats.push(n);if(i.extraQualities)for(let n of i.extraQualities)r.extraQualities.indexOf(n)===-1&&r.extraQualities.push(n);if(i.extraFeatures)for(let n of i.extraFeatures)r.extraFeatures.indexOf(n)===-1&&r.extraFeatures.push(n);i.maxHeight&&(r.maxHeight=i.maxHeight),i.maxWidth&&(r.maxWidth=i.maxWidth),i.maxArea&&(r.maxArea=i.maxArea)}if(e.extraFormats)for(let i of e.extraFormats)r.extraFormats.indexOf(i)===-1&&r.extraFormats.push(i);if(e.extraFeatures)for(let i of e.extraFeatures)r.extraFeatures.indexOf(i)===-1&&r.extraFeatures.push(i);if(e.extraQualities)for(let i of e.extraQualities)r.extraQualities.indexOf(i)===-1&&r.extraQualities.push(i);return r}function Of(e){try{if(e==="full")return{full:!0};if(e==="square")return{square:!0};let t=e.startsWith("pct:"),r=e.substr(t?4:0).split(",").map(i=>parseFloat(i));return{x:r[0],y:r[1],w:r[2],h:r[3],percent:t}}catch{throw new Error("Expected 'full', 'square' or 'x,y,w,h'. Found "+e)}}function If(e){let t={upscaled:!1,max:!1,confined:!1};if(e[0]==="^"&&(t.upscaled=!0,e=e.slice(1)),e==="max"||e==="full")return t.max=!0,t.serialiseAsFull=e==="full",t;if(e[0]==="!"&&(t.confined=!0,e=e.slice(1)),e[0]==="p")return t.percentScale=parseFloat(e.slice(4)),t;let r=e.split(",").map(i=>i.trim());return r.length&&typeof r[0]<"u"&&(r[0]!==""&&(t.width=parseInt(r[0],10)),typeof r[1]<"u"&&r[1]!==""?(t.height=parseInt(r[1],10),t.version=2):t.version=3),t}function jf(e){let t={angle:0};if(e[0]==="!"&&(t.mirror=!0,e=e.substr(1)),t.angle=parseFloat(e)%360,Number.isNaN(t.angle))throw new Error(`Invalid rotation ${e}`);return t}function Pf(e,t=""){let r=e.match(/^(([a-zA-Z]+):\/\/([^/]+))?((.*)+)/);if(!r)throw new Error(`Invalid or unknown input ${e}`);let i=r[2],n=r[3],s=r[4];if(s[0]==="/"&&(s=s.substring(1)),t.length>0){if(t[0]==="/"&&(t=t.substring(1)),t!==s.substring(0,t.length))throw new Error(`Path does not start with prefix (path: ${s}, prefix: ${t})`);s=s.substring(t.length)}return{scheme:i,server:n,path:s,prefix:t}}function Tf(e,t=""){let{path:r,scheme:i,server:n,prefix:s}=Pf(e,t),a=(r||"").split("/").reverse(),[o,l,h,c,...u]=a,f=u.reverse().filter(Boolean).join("/");if(a.length===1||o==="")return{type:"base",scheme:i,server:n,prefix:s,identifier:f};if(o==="info.json"){let[,...p]=a;return{type:"info",scheme:i,server:n,prefix:s,identifier:p.reverse().filter(Boolean).join("/")}}let d=(o||"").split(".");if(typeof d[1]>"u"||typeof d[0]>"u"||typeof c>"u"||typeof h>"u"||typeof l>"u")throw new Error("Invalid image request");return{type:"image",scheme:i,server:n,prefix:s,identifier:f,originalPath:r,region:Of(c),size:If(h),rotation:jf(l),quality:d[0],format:d[1]}}function Ff(e){let t=Tf(ye(e.id));if(t.type!=="info")throw new Error("Invalid service URL");let r=_f(e);return{identifier:t.identifier,originalPath:"",server:t.server,prefix:t.prefix,scheme:t.scheme,type:"image",quality:r.extraQualities.indexOf("default")===-1?r.extraQualities[0]:"default",region:{full:!0},size:{max:!0,upscaled:!1,confined:!1},format:"jpg",rotation:{angle:0}}}function Ef(e,t,r){let i=r.length,n=[];for(let s=0;s<i;s++){let a=r[s];if(a){let o=a.width;n.push(e/o)}}return n}function Rf(e,t,r){let i=r.length,n=[];for(let s=0;s<i;s++){let a=r[s];a&&n.push({width:Math.floor(e/a),height:Math.floor(t/a)})}return n}function et(e){if(e["@id"])return e["@id"];if(e.id)return e.id}function Vr(e){if(!e||!e.profile||!et(e))return!1;let t=Array.isArray(e.profile)?e.profile:[e.profile];for(let r of t)if(typeof r=="string"&&Cf.indexOf(r)!==-1)return!0;return!1}function Mf(e){if(!Vr(e))return!1;let t=Array.isArray(e.profile)?e.profile:[e.profile];for(let r of t)if(typeof r=="string"){if(xo.indexOf(r)!==-1)return!0}else{let i=[...r.supports||[],...r.extraFeatures||[]];if(i.indexOf("regionByPx")!==-1&&(i.indexOf("sizeByW")!==-1||i.indexOf("sizeByWh")!==-1))return!0}return!1}function _r(e,t){if(t&&t.profile){let r=t.profile;if(r){let i=Array.isArray(r)?r:[r];return i.includes(`level${e}`)||i.includes(`http://iiif.io/api/image/2/level${e}.json`)||i.includes(`http://iiif.io/api/image/1/level${e}.json`)||i.includes(`http://iiif.io/api/image/1/profiles/level${e}.json`)}}return!1}function Ei(e){return Vr(e)?_r(0,e)?0:_r(1,e)?1:_r(2,e)?2:null:null}function Co(e){return(e["@context"]?Array.isArray(e["@context"])?e["@context"]:[e["@context"]]:[]).indexOf("http://iiif.io/api/image/3/context.json")!==-1}function Nf(e){if(!Mf(e))return[];let t=[],r=Array.isArray(e.profile)?e.profile:[e.profile],i=r.length;for(let n=0;n<i;n++){let s=r[n];if(s&&typeof s!="string"&&(s.maxHeight||s.maxWidth))return[{id:et(e),type:"variable",minWidth:0,minHeight:0,maxHeight:s.maxHeight||s.maxWidth,maxWidth:s.maxWidth||s.maxHeight,level:Ei(e),version:e["@context"]==="http://iiif.io/api/image/3/context.json"?3:2}]}if(e.tiles){let n=e.tiles.length;for(let s=0;s<n;s++){let a=e.tiles[s];a&&(a.height||a.width)&&t.push({id:et(e),type:"variable",minHeight:0,minWidth:0,maxHeight:a.height||a.width,maxWidth:a.width,level:Ei(e),version:Co(e)?3:2})}}return t}function Wn(e){let t=/^.*\/(full)\/(((\d+),(\d+)?)|max)\/(\d+)\/default\.(jpg|png|jpeg)$/,r=e.match(t);if(r&&r[4]&&r[5]){let i=r[1],n=parseInt(r[4],10),s=parseInt(r[5],10),a=r[7];if((i==="max"||i==="full")&&n&&s&&a)return{type:"fixed",id:e,height:s,width:n}}return{type:"unknown",id:e}}function Df(e){if(e["@type"])return e["@type"];if(e.type)return e.type}function Lf(e){if(typeof e=="string")return Wn(e);let t=Df(e);if(t!=="Image"&&t!=="sc:Image")return null;let r=e,i=et(r);return i?i&&r.width&&r.height?{id:i,type:"fixed",width:r.width,height:r.height,unsafe:!0}:Wn(i):null}function Wf(e){return Vr(e)?(e&&e.sizes?e.sizes:[]).map(t=>({id:et(e),type:"fixed-service",height:t.height,width:t.width,level:Ei(e),version:Co(e)?3:2})):[]}function Un(e){let t=[],r=e.length;for(let i=0;i<r;i++){let n=e[i];if(!n)continue;let s=Wf(n);s.length&&t.push(...s);let a=Nf(n);a.length&&t.push(...a)}return t}function So(e){let t=e.service?Array.isArray(e.service)?e.service:[e.service]:[],r=t.length,i=[];for(let n=0;n<r;n++)Vr(t[n])&&i.push(t[n]);return i}function Uf(e,t=!0,r){let i=[],n=Lf(e);if(n===null)return i;let s=e;if(i.push(n),t&&s&&s.width&&s.height){let a=[],o=So(s);for(let l of o){let h={id:et(l),width:s.width,height:s.height};if(r.canLoadSync(h)){let c=r.loadServiceSync(h);c&&(c.height||(c.height=s.height),c.width||(c.width=s.width),a.push(...Un([c])))}}if(a.length)return i.push(...a),i}return s.service&&i.push(...Un(s.service)),i}function Bf({x:e=0,y:t=0,w:r,h:i,full:n,square:s,percent:a}){return"full"}function zf({max:e,percentScale:t,upscaled:r,confined:i,width:n,height:s,serialiseAsFull:a,version:o}){let l=[];return r&&l.push("^"),e?(l.push(a?"full":"max"),l.join("")):(i&&l.push("!"),t&&l.push(`pct:${t}`),n&&l.push(`${n}`),l.push(","),s&&o===3&&l.push(`${s}`),l.join(""))}function qf(e){return`${e.mirror?"!":""}${(e.angle||0)%360}`}function Hf(e,t){let r=e.prefix.startsWith("/")?e.prefix.substr(1):e.prefix,i=`${e.scheme}://${e.server}/${r?`${r}/`:""}${e.identifier}`,{size:n}=e,{region:s,rotation:a,format:o,quality:l}=e;return[i,Bf(s),zf(n),qf(a),`${l}.${o}`].filter(Boolean).join("/")}function ci(e,t,r){let i=Ff({"@context":e.version===3?"http://iiif.io/api/image/3/context.json":"http://iiif.io/api/image/2/context.json",id:ye(et(e)),profile:e.level===null||typeof e.level>"u"?"level0":`level${e.level}`,type:e.version===3?"ImageService3":"ImageService2"});return i.size.max=!1,i.size.width=t,i.size.height=r,{id:Hf(i),type:"fixed",width:t,height:r||e.height/(e.width||1)*t,unsafe:e.width>t}}function Ae(e){let t=e.replace(/(https?:\/\/)?(www.)?/i,"");return t.indexOf("/")!==-1?t.split("/")[0]:t}function Gf(e,t,r){let i=e.width?e.width:e.maxWidth;return r.height<=e.maxHeight&&r.width<=e.maxWidth&&r.height>=e.minHeight&&r.width>=e.minWidth&&(!t||Math.abs(r.width-i)<Math.abs(t.width-i))}function Qf(e,t){let r=[],i=Object.assign({unsafeImageService:!1,atAnyCost:!0,fallback:!0,minHeight:64,minWidth:64,maxHeight:1/0,maxWidth:1/0,returnAllOptions:!1,preferFixedSize:!1,allowUnsafe:!1,explain:!1,height:0,width:0},e),n=(c,u=0)=>i.explain?r.push(new Array(u).fill(0).map(f=>" ").join("")+c().trim()):void 0,s=[],a=[],o=null;n(()=>`Using configuration: ${JSON.stringify(i,null,2)}`);let l=(c,u)=>{if(n(()=>"Swapping choice",3),Gf(i,u,c)){if(i.preferFixedSize&&c.unsafe){n(()=>`We found an image that was marked as unsafe, but it was the best size. (${c.id})`,4),a.push(c);return}i.returnAllOptions&&u&&a.push(u),n(()=>`We found a new image that was the best size. (${c.id})`,4),o=c}else i.returnAllOptions&&a.push(c)};n(()=>`The input shows we have ${t.length} list(s) of candidates to choose from.`);let h=t.length;for(let c=0;c<h;c++){let u=t[c]();n(()=>`Candidate group ${c}: ${JSON.stringify(u,null,2)}`,1);let f=u.length;n(()=>`Checking candidate list number ${c} and found ${f} potential ways of creating image(s)`,1);for(let d=0;d<f;d++){let p=u[d];if(n(()=>`-> Checking candidate ${d}`,1),p.type==="unknown"&&i.atAnyCost&&(n(()=>`We've found an unknown image type, adding this to the "last resort" list`,2),s.push(p)),p.type==="fixed"&&(p.unsafe?(n(()=>`We've found an unsafe fixed image type, adding this to the "last resort" list`,2),s.push(p)):(n(()=>"We've found a fixed size image, checking if it matches the request",2),l(p,o))),p.type==="fixed-service")if(i.unsafeImageService){n(()=>"Checking for an image from the tile source, without calculating the right height and width (unsafeImageService)",2);let g=ci(p,i.width,i.height);l(g,o)}else{n(()=>"Checking for an image from the tile source 3",2);let g=ci(p,p.width,p.height);l(g,o)}if(p.type==="variable"&&p.maxWidth){let g=ci({id:p.id,width:p.maxWidth,height:p.maxWidth,level:p.level,version:p.version},p.maxWidth);l(g,o)}}if(o&&!i.returnAllOptions){if(o.unsafe||i.allowUnsafe)continue;n(()=>`We found a match in choice list number ${c}, no searching any more`);break}}return i.atAnyCost&&a.length===0?(n(()=>o?`We found an image! ${o.id} of type ${o.type}`:'We found no images, but "atAnyCost" is set, so returning that'),{best:o||s[0]||null,fallback:s.slice(1),log:r}):i.returnAllOptions?(n(()=>"Returning all options that we have found"),{best:(i.atAnyCost?o||a[0]||s[0]:o||a[0])||null,fallback:[...a,...s],log:r}):(n(()=>"Returning the best image that we found, and a fallback"),{best:o||a[0]||null,fallback:o?a:a.slice(1),log:r})}function Yf(e,t,r){let i=e>t?e:t,n=r.length,s=[];for(let a=0;a<n;a++){let o=r[a];if(!o||o.scaleFactors.length===0)continue;let l=o.scaleFactors[0];if(!l)continue;let h=i/l,c=[l];for(;h>=o.width;)l=l*2,c.push(l),h=h/2;s.push({...o,scaleFactors:c})}return s}function Vf(e,t){if(e.length!==t.length)return!1;if(e.length===0&&t.length===0)return!0;let r=e.length,i=!0;for(let s=0;s<r;s++){let a=e[s],o=t[s];if(a.width!==o.width||a.height!==o.height){i=!1;break}}if(i)return!0;let n=0;for(let s=0;s<r;s++)for(let a=0;a<r;a++)if(e[s].width===t[a].width&&e[s].height===t[a].height){n++;break}return n===r}function Bn(e){return _r(0,e)}var Ao=class{constructor(e={}){mr(this,"config",{verificationsRequired:1,approximateServices:!1,enableFetching:!0,disableThrottling:!1}),mr(this,"fetchingCount",0),mr(this,"imageServices",{}),mr(this,"knownImageServers",{}),this.config=Object.assign(this.config,e)}setConfig(e){Object.assign(this.config,e)}sample(e,t,r=!0){let i=Ae(et(e)),n=ye(et(e)),s=this.knownImageServers[i];return this.imageServices[n]=Object.assign(e,{real:!0}),!s&&e.tiles&&!Bn(e)?(this.knownImageServers[i]={verifications:0,malformed:!1,root:i,preLoaded:r,sampledId:et(e),verified:!1,server:null,result:{context:e["@context"]||[],sampledProfile:e.profile,resourceServiceRatio:t&&e.height?t.height/e.height:1,sampledSizes:e.sizes||[],sizeRatios:Ef(e.width,e.height,e.sizes||[]),sampledTiles:e.tiles||[]}},!0):this.verify(e)}preLoad(e,t=!0){this.knownImageServers[e.root]=e,t&&(this.knownImageServers[e.root].malformed=!1,this.knownImageServers[e.root].verifications=this.config.verificationsRequired)}predict(e,t=!1,r=!1){let i=e==null?void 0:e.source,n=Ae(et(e)),s=this.knownImageServers[n],a=ye(et(e));return this.imageServices[a]?this.imageServices[a]||null:!this.config.approximateServices||!s||!s.result||!(i!=null&&i.height||e.height)||!(i!=null&&i.width||e.width)||!r&&(s.malformed||s.verifications<this.config.verificationsRequired)||Bn(e.source)?null:(this.imageServices[a]||(this.imageServices[a]={"@context":s.result.context,"@id":et(e),id:et(e),protocol:"http://iiif.io/api/image",tiles:(i==null?void 0:i.tiles)||Yf(e.width,e.height,s.result.sampledTiles),sizes:(i==null?void 0:i.sizes)||Rf(Math.round(e.width/s.result.resourceServiceRatio),Math.round(e.height/s.result.resourceServiceRatio),s.result.sizeRatios),profile:(i==null?void 0:i.profile)||s.result.sampledProfile,height:(i==null?void 0:i.height)||e.height,width:(i==null?void 0:i.width)||e.width,real:!1}),this.imageServices[a]||null)}async getThumbnailFromResource(e,t,r=!0,i=[]){let n=e?await this.getImageCandidates(e,r):[];return Qf(t,[()=>i,()=>n])}async getImageCandidates(e,t=!0){let r=e;if(t&&r&&r.height&&r.width){let i=So(r);for(let n of i){let s={id:et(n),width:n.width?n.width:r.width,height:n.height?n.height:r.height,source:n};await this.loadService(s)}}return Uf(e,t,this)}async verify(e){let t=this.predict(e,!1,!0),r=await this.fetchService(et(e));if(!t)return!1;let i=t.height===r.height&&t.width===r.width&&t["@context"]===r["@context"]&&Vf(t.sizes||[],r.sizes||[]);if(i){let n=Ae(et(e)),s=this.knownImageServers[n];s&&(s.verifications+=1,s.verifications>=this.config.verificationsRequired&&(s.verified=!0))}return i}canLoadSync(e){let t=typeof e=="string"?e:et(e),r=ye(t);if(this.imageServices[r])return!0;let i=this.knownImageServers[Ae(t)];return!!(i&&!i.malformed&&i.verifications>=this.config.verificationsRequired)}async markAsMalformed(e){return this.knownImageServers[Ae(et(e))].malformed=!0,this.loadService(e,!0)}async fetchService(e,t=!1){let r=ye(e),i=this.imageServices[r];if(i&&(!t||i.real))return i;if(!this.config.enableFetching)throw new Error("Fetching is not enabled");let n=await this.fetch(r).then(s=>s.json());return!n.id&&n["@id"]&&(n.id=n["@id"]),n.id!==e&&(n.id=e,n["@id"]&&(n["@id"]=e)),this.imageServices[r]=Object.assign(n,{real:!0}),this.imageServices[r]}async fetch(e,t){return fetch(e,t)}async loadService(e,t=!1){if(!this.config.disableThrottling){let n=!0;for(;n;)if(this.fetchingCount>=this.config.verificationsRequired)await new Promise(s=>setTimeout(s,500));else{n=!1;break}}let r=this.knownImageServers[Ae(et(e))];if(r&&!r.malformed&&!t){await r.result;let n=this.loadServiceSync(e);if(n)return n}this.fetchingCount++;let i=await this.fetchService(et(e),t);return this.fetchingCount--,i.real&&this.sample(i,e),i}loadServiceSync(e){let t=ye(et(e));return this.imageServices[t]?this.imageServices[t]:this.config.approximateServices?this.predict(e):null}};new Ao;const Jf=["commenting","describing","tagging","no-purpose"],Ri={commenting:"Comment",describing:"Description",tagging:"Tags"},H=of();function Rt(e,t,r){let i=!1;r||(r="<<<SNIP>>>",i=!0);const n=ba(e,t[0]??"none",{defaultText:"",fallbackLanguages:t.slice(1),separator:r});return i?n.split(r).filter(s=>s.length>0):n}class Xf extends Ao{async fetch(t,r){return fetch(t,r)}}const Kf=Cc(H,{imageServiceLoader:new Xf}),{extractChoices:Zf}=yh(H);async function td(e,t){var i;return(i=(await Kf.getBestThumbnailAtSize(e,{maxWidth:t,maxHeight:t})).best)==null?void 0:i.id}function ed(e){return e.type!==void 0&&["Dataset","Image","Video","Sound","Text","unknown"].indexOf(e.type)>=0&&e.profile!==void 0}function rd(e){return typeof e.profile=="string"&&e.profile==="http://iiif.io/api/annex/services/physdim"}function zn(e){var t;return typeof e=="string"?e.indexOf("level2")>=0:(((t=e.supports)==null?void 0:t.indexOf("sizeByWh"))??-1)>=0}async function id(e){const t=`${e["@id"]??e.id}/info.json`;return await(await fetch(t)).json()}function $o(e){return H.get(e.annotations).flatMap(t=>H.get(t.items)).filter(t=>Array.isArray(t.motivation)?t.motivation.find(r=>Ri[r]!==void 0)!==void 0:Ri[t.motivation??"invalid"]!==void 0).map(t=>_o(t)).filter(t=>t!==void 0)}function ko(e){const t=ld(e),r=nn(e);return{canvas:{id:e.id,type:"Canvas"},images:t,ocr:r?{id:r.id}:void 0,numAnnotations:$o(e).length}}function qn(e){let t=Array.isArray(e.name)?e.name.join("; "):e.name;return t||(t=e.nickname??"unknown"),e.email?`${t} <${e.email}>`:t}function nd(e){return Array.isArray(e)?typeof e[0]=="string"?e.join("; "):e.map(t=>qn(t)).join("; "):typeof e=="string"?e:qn(e)}function _o(e,t){if(!e.target)return;const r=e.body.map(l=>H.get(l.id)),i=r.map(l=>l.creator).filter(l=>l!==void 0).map(nd),n=r.map(l=>l.modified).filter(l=>l!==void 0).map(l=>new Date(l).getTime());if(typeof e.target=="string")return;const s=Array.isArray(e.target)?H.get(e.target.map(l=>l.id)):e.target,a=_e(s),o=sd(r);if(!o)throw"No valid textual content in annotation.";return{id:e.id,target:a,markup:o,lastModified:n.length>0?new Date(Math.max(...n)):void 0,author:i.length>0?i.join("; "):void 0}}function sd(e){const t={};for(const i of e){if(i.type!=="TextualBody"||i.format!=="text/plain"&&i.format!=="text/html"||i.value===void 0)continue;let{purpose:n}=i;Array.isArray(n)?n=n[0]:n||(n="no-purpose"),t[n]||(t[n]=[]);const s=i.format==="text/plain"?i.value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):i.value;t[n].push(s)}if(Object.keys(t).length===0)return;const r=[];for(const i of Jf){const n=Ri[i];if(t[i])if(t[i].length>1){n&&r.push(`<p><b>${n}:</b></p>`);for(const s of t[i])r.push(`<p>${s}</p>`)}else r.push("<p>"),n&&r.push(`<b>${n}:</b> `),r.push(`${t[i][0]}</p>`)}if(r.length!==0)return r.join(`
|
|
10
|
+
`)}function Hn(e){const[t,r]=e.split("#xywh=");if(r){const[i,n,s,a]=r.split(",").map(o=>parseInt(o,10));return{x:i,y:n,width:s,height:a}}else{const i=H.get(t);return{x:0,y:0,width:i.width,height:i.height}}}function Gn(e){var t,r,i;if(e.format==="image/jpeg")return"jpeg";if(e.format==="image/png")return"png";if(e.format===void 0){if((t=e.id)!=null&&t.endsWith(".jpg")||(r=e.id)!=null&&r.endsWith(".jpeg"))return"jpeg";if((i=e.id)!=null&&i.endsWith(".png"))return"png"}else return"unsupported"}function ad(e){const t=Array.isArray(e)?e:[e];for(const r of t)if(!(!r||typeof r!="object"))if(r.type==="ImageApiSelector"){if((r.rotation||r.size||r.quality||r.format)&&k.warn("Only the region of an ImageApiSelector is supported, ignoring size, rotation, quality and format."),typeof r.region=="string"&&r.region!=="full")return r.region}else if(r.type==="FragmentSelector"&&typeof r.value=="string"&&r.value.startsWith("xywh=")){const[,i,n]=r.value.match(/^xywh=(?:(pixel|percent):)?(.+)$/)??[];if(n)return i==="percent"?`pct:${n}`:n}else k.warn(`Unsupported selector type '${r.type}', painting the whole image.`)}function od(e){var r;if((e==null?void 0:e.type)==="SpecificResource"){const i=typeof e.source=="string"?e.source:(r=e.source)==null?void 0:r.id,n=i?H.get(i):null;return(n==null?void 0:n.type)!=="Image"?void 0:{resource:n,region:ad(e.selector)}}const t=e!=null&&e.id?H.get(e.id):null;if((t==null?void 0:t.type)==="Image")return{resource:t}}function ld(e){var n;const t=[],r=H.get(e.items).flatMap(s=>H.get(s.items));for(const s of r){const a=s.target;let o;if(typeof a=="string")o=Hn(a);else if(a.type==="SpecificResource"){const l=a.source,h=typeof l=="string"?l:l.id,u=(n=(Array.isArray(a.selector)?a.selector:[a.selector]).find(f=>{var d;return(f==null?void 0:f.type)==="FragmentSelector"&&((d=f.value)==null?void 0:d.startsWith("xywh="))}))==null?void 0:n.value;o=Hn(u?`${h}#${u.replace("xywh=pixel:","xywh=")}`:h)}else{console.error(`Unsupported target type for annotation on canvas ${e.id}: '${a.type}'`);continue}for(const l of s.body){const h=od(l);if(!h)continue;const{resource:c,region:u}=h;t.push({resource:c,...o,...u?{region:u}:{},format:Gn(c),nativeWidth:c.width,nativeHeight:c.height})}}const i=Zf(r);if((i==null?void 0:i.type)!=="single-choice")return t;for(const s of i.items){const a=H.get(s.id);a.type==="Image"&&t.push({resource:a,x:0,y:0,width:e.width,height:e.height,nativeWidth:a.width,nativeHeight:a.height,format:Gn(a),choiceInfo:{enabled:s.selected??!1,optional:!0,label:a.label,visibleByDefault:s.selected??!1}})}return t}async function cd(e,t,r){let i;const n=t.indexOf("<alto")>=0;n?i=Ul(t,[r]):i=Fl(t,[r]);const s=(await i.next()).value;return s?{...s,id:e,markup:t,mimeType:n?"application/xml+alto":"text/vnd.hocr+html"}:null}const ud=e=>{var t;return e.format==="application/xml+alto"||((t=e.profile)==null?void 0:t.startsWith("http://www.loc.gov/standards/alto/"))},hd=e=>{var t,r;return e.format==="text/vnd.hocr+html"||e.profile==="https://github.com/kba/hocr-spec/blob/master/hocr-spec.md"||((t=e.profile)==null?void 0:t.startsWith("http://kba.cloud/hocr-spec/"))||((r=e.profile)==null?void 0:r.startsWith("http://kba.github.io/hocr-spec/"))};async function fd(e){const t=await fetch(e);if(t.status!==404){if(t.status!=200)throw new Error(`Could not fetch OCR markup from ${e}, got status code ${t.status}`);return t.text()}}function nn(e){const t=H.get(e.seeAlso.map(r=>r.id));return t.push(...H.get(e.rendering.map(r=>r.id))),t.filter(ed).find(r=>ud(r)||hd(r))}async function dd(e,t){const r=nn(e);if(r){const i=Nt==null?void 0:Nt.ocrFetchDuration.startTimer({ocr_host:new URL(r.id).host});let n;try{if(n=await fd(r.id),i==null||i({status:"success",limited:Re.isLimited(r.id).toString()}),!n)return}catch(s){throw i==null||i({status:"error",limited:Re.isLimited(r.id).toString()}),s}return await cd(r.id,n,{width:e.width,height:e.height})??void 0}}const Oo=300,pd='application/ld+json;q=0.9;profile="http://iiif.io/api/presentation/3/context.json", application/ld+json;q=0.7;profile="http://iiif.io/api/presentation/2/context.json", application/ld+json;q=0.5, application/json;q=0.2';class gd{constructor(){v(this,"hostMutexes",new Map);v(this,"callbacks",[])}getMutex(t){return this.hostMutexes.get(t)}limitHost(t){const r=new yl;return this.hostMutexes.set(t,r),this.callbacks.forEach(i=>i(t,!0)),r}unlimitHost(t){this.hostMutexes.delete(t),this.callbacks.forEach(r=>r(t,!1))}subscribe(t){return this.callbacks.push(t),this.callbacks.length-1}unsubscribe(t){this.callbacks.splice(t,1)}isLimited(t){return this.hostMutexes.has(new URL(t).host)}}const Re=new gd;async function Mi(e,t,r=3){const{host:i}=new URL(e);let n=Re.getMutex(i),s=-1,a,o=5e3,l;const h=await(n==null?void 0:n.acquire());try{do{if(a=await fetch(e,t),a.ok)break;s++;const c=a==null?void 0:a.headers.get("retry-after");xe(c)?Number.isInteger(c)?o=Number.parseInt(c,10)*1e3:o=Date.parse(c)-Date.now():o=Math.pow(Math.random()*2*o,s);const u=g=>[g,`x-${g}`,`x-${g.replace("ratelimit","rate-limit")}`].map(y=>a==null?void 0:a.headers.get(y)).filter(xe).map(y=>Number.parseInt(y,10)).find(y=>y!=null),f=u("ratelimit-limit"),d=u("ratelimit-remaining"),p=u("ratelimit-reset");if(f!==void 0&&d!==void 0&&p!==void 0){n=Re.limitHost(i);const g=p/(f-d);d>0?o=2*d*g*1e3:o=g*1e3}await new Promise(g=>setTimeout(g,o+100))}while(s<r)}finally{n&&await new Promise(c=>setTimeout(c,o+100)),h==null||h()}if(!a)throw l;return a}function md(e,t=1){let r;const i=e.id!==void 0,n=e.maxWidth??e.width;let s=Math.floor(t*n);const a=e.width/e.height,o=Array.isArray(e.profile)?e.profile.find(zn)!==void 0:zn(e.profile);if(t<1&&!o)e.sizes?(s=Math.min(...e.sizes.map(l=>Math.abs(s-l.width))),r=`${s},`):r=`${n},`;else if(t==1)if(r=i||e.maxWidth||e.maxArea?"max":"full",e.maxWidth)s=e.maxWidth;else if(e.maxHeight)s=Math.round(a*e.maxHeight);else if(e.maxArea){const l=e.width*e.height,h=e.maxArea/l;s=Math.round(h*e.width)}else s=e.width;else r=`${s},`;return{iiifSize:r,width:s,height:s/a}}function vd(e,t,r){const i=u=>{const f=u.split(","),d=f.map(p=>p.trim()===""?NaN:Number(p));return f.length===4&&d.every(Number.isFinite)?d:void 0},n=u=>new Error(`Invalid image region '${e}': ${u}`,{cause:{type:"invalid-region"}});if(e==="full")return;let s,a,o,l;if(e.startsWith("pct:")){const u=i(e.substring(4));if(!u)throw n("expected four numbers");[s,a,o,l]=u.map(f=>f/100)}else{if(!t||!r){k.warn(`Cannot crop to region '${e}', image dimensions are unknown. Painting the whole image.`);return}if(e==="square"){const u=Math.min(t,r);[s,a,o,l]=[(t-u)/2/t,(r-u)/2/r,u/t,u/r]}else{const u=i(e);if(!u)throw n("expected four numbers");[s,a,o,l]=[u[0]/t,u[1]/r,u[2]/t,u[3]/r]}}if(o<=0||l<=0)throw n("width and height must be positive");const h=Math.min(s+o,1),c=Math.min(a+l,1);if(s=Math.max(s,0),a=Math.max(a,0),s>=h||a>=c)throw n("region lies outside of the image");if(!(s===0&&a===0&&h===1&&c===1))return{x:s,y:a,width:h-s,height:c-a}}function sn(e){const t=e.find(rd);if(!t)return null;const{physicalScale:r,physicalUnits:i}=t;let n;return i==="in"?n=1/r:i==="mm"?n=25.4/r:i==="cm"?n=2.54/r:n=Oo,n}function vr(e){return e.cause!==void 0}async function yd(e,{scaleFactor:t,abortSignal:r,sizeOnly:i=!1},n){var g,m,y;if(r!=null&&r.aborted)throw k.debug("Abort signalled, aborting before initiating image data fetching."),new Error("Aborted due to client request",{cause:{type:"abort"}});if(e.type!=="Image")throw new Error(`Can only fetch image resources, got ${e.type}`);let s;"service"in e&&(s=(g=e.service)==null?void 0:g.find(b=>{var w,_;return(((w=b==null?void 0:b.type)==null?void 0:w.startsWith("ImageService"))??!1)||(((_=b==null?void 0:b["@type"])==null?void 0:_.startsWith("ImageService"))??!1)}));let a,o,l=!1,h;if(s){s.width||(s=await id(s));const b=md(s,t);o=`${s.id??s["@id"]}/full/${b.iiifSize}/0/default.jpg`,a=sn(s.service??[])??void 0,a&&(a=a*(b.width/s.width)),b.width<s.width&&(l=!0)}else if(e.id&&["image/jpeg","image/png"].indexOf(e.format??"unknown")>=0)o=e.id;else return k.error(`No JPEG or PNG image identifier for resource ${e.id} could be found!`),null;n&&(h=vd(n,(s==null?void 0:s.width)??e.width,(s==null?void 0:s.height)??e.height));let c,u,f=!0,d=null;const p=Nt==null?void 0:Nt.imageFetchDuration.startTimer({iiif_host:new URL(o).host});try{const b=await Mi(o,{method:"GET",signal:r});if(b.status>=400)throw new Error(`Failed to fetch page image from ${o}, server returned status ${b.status}`,{cause:{type:"http-status",status:b.status}});if(r!=null&&r.aborted)throw new Error("Aborted due to client request",{cause:{type:"abort"}});if(u=Number.parseInt(b.headers.get("Content-Length")??"-1"),c=i&&u>=0?void 0:await b.arrayBuffer(),(m=b.headers.get("Content-Type"))!=null&&m.startsWith("image/jpeg"))d="jpeg";else if((y=b.headers.get("Content-Type"))!=null&&y.startsWith("image/png"))d="png";else throw new Error("Unsupported image content type",{cause:{type:"content-type"}});u<0&&(u=(c==null?void 0:c.byteLength)??-1),p==null||p({status:"success",limited:Re.isLimited(o).toString()})}catch(b){if(typeof document<"u"&&await bd(o)){if(!i)throw new Error("Data requested, but no CORS for the image endpoint",{cause:{type:"no-cors"}})}else throw k.error(`Failed to fetch image data from ${o}: ${b}`),p==null||p({status:"error",limited:Re.isLimited(o).toString(),cause:b instanceof Error?b.cause.type:b}),b;f=!1,k.warn(`Failed to fetch image data from ${o}: CORS headers missing!`);const _=await Mi(o,{method:"GET",signal:r,mode:"no-cors"});u=Number.parseInt(_.headers.get("Content-Length")??"-1")}return{data:c,ppi:a,numBytes:u,corsAvailable:f,format:d,downscaled:l,...h?{crop:h}:{}}}async function bd(e){const t=document.createElement("img");return t.src=e,new Promise(r=>{t.onload=()=>r(!0),t.onerror=()=>r(!1)})}async function Io(e){const t=e.start;if(!t)return;let r,i;if(typeof t=="string"){const[c,u]=t.split("#xywh=");if(!u)return c;r=c,i=`xywh=${u}`}else{if(t.type==="SpecificResource")return t.id;{const c=H.get(t.id);if(typeof c=="string"||c.type!=="FragmentSelector"){k.warn(`Unsupported selector type, cannot determine start canvas for ${e.id}`);return}const u=c;if(u.conformsTo!=="http://www.w3.org/TR/media-frags/"){k.warn(`Unsupported selector type, cannot determine start canvas for ${e.id} (fragment selector type was ${u.conformsTo})`);return}r=u.value}}if(!i||!r){k.error(`Couldn't parse either canvas identifier or selector for ${e.id} start canvas.`);return}const[n,s,a,o]=i.substring(5).split(",").map(c=>Number.parseInt(c,10)),l=H.get(r),h=sn(l.service)??Oo;return{id:r,ppi:h,dimensions:{width:l.width,height:l.height},position:{x:n,y:s,width:a,height:o}}}async function jo(e,t,{scaleFactor:r,ppiOverride:i,abortSignal:n,sizeOnly:s=!1}){const a=t.map(f=>yd(f.resource,{scaleFactor:r,abortSignal:n,sizeOnly:s},f.region)),o=await Promise.allSettled(a),l=o.reduce((f,d,p)=>{if(d.status!=="fulfilled"||d.value===null)return f;const g=t[p];return f.push({...g,...d.value}),f},[]),h=o.filter(f=>f.status==="rejected").map((f,d)=>({...t[d],cause:f.reason})),c=i;i||sn(e.service);let u;if(!s)try{u=await dd(e,void 0)}catch(f){k.warn(`Failed to fetch text for canvas ${e.id}: ${f}`)}return{canvas:e,images:l,imageFailures:h,ppi:c,text:u,annotations:$o(e)}}async function an(e){try{return await(await fetch(e,{headers:{Accept:pd}})).json()}catch{return await(await fetch(e)).json()}}function on(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Po={exports:{}};(function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function n(l,h,c){this.fn=l,this.context=h,this.once=c||!1}function s(l,h,c,u,f){if(typeof c!="function")throw new TypeError("The listener must be a function");var d=new n(c,u||l,f),p=r?r+h:h;return l._events[p]?l._events[p].fn?l._events[p]=[l._events[p],d]:l._events[p].push(d):(l._events[p]=d,l._eventsCount++),l}function a(l,h){--l._eventsCount===0?l._events=new i:delete l._events[h]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var h=[],c,u;if(this._eventsCount===0)return h;for(u in c=this._events)t.call(c,u)&&h.push(r?u.slice(1):u);return Object.getOwnPropertySymbols?h.concat(Object.getOwnPropertySymbols(c)):h},o.prototype.listeners=function(h){var c=r?r+h:h,u=this._events[c];if(!u)return[];if(u.fn)return[u.fn];for(var f=0,d=u.length,p=new Array(d);f<d;f++)p[f]=u[f].fn;return p},o.prototype.listenerCount=function(h){var c=r?r+h:h,u=this._events[c];return u?u.fn?1:u.length:0},o.prototype.emit=function(h,c,u,f,d,p){var g=r?r+h:h;if(!this._events[g])return!1;var m=this._events[g],y=arguments.length,b,w;if(m.fn){switch(m.once&&this.removeListener(h,m.fn,void 0,!0),y){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,c),!0;case 3:return m.fn.call(m.context,c,u),!0;case 4:return m.fn.call(m.context,c,u,f),!0;case 5:return m.fn.call(m.context,c,u,f,d),!0;case 6:return m.fn.call(m.context,c,u,f,d,p),!0}for(w=1,b=new Array(y-1);w<y;w++)b[w-1]=arguments[w];m.fn.apply(m.context,b)}else{var _=m.length,C;for(w=0;w<_;w++)switch(m[w].once&&this.removeListener(h,m[w].fn,void 0,!0),y){case 1:m[w].fn.call(m[w].context);break;case 2:m[w].fn.call(m[w].context,c);break;case 3:m[w].fn.call(m[w].context,c,u);break;case 4:m[w].fn.call(m[w].context,c,u,f);break;default:if(!b)for(C=1,b=new Array(y-1);C<y;C++)b[C-1]=arguments[C];m[w].fn.apply(m[w].context,b)}}return!0},o.prototype.on=function(h,c,u){return s(this,h,c,u,!1)},o.prototype.once=function(h,c,u){return s(this,h,c,u,!0)},o.prototype.removeListener=function(h,c,u,f){var d=r?r+h:h;if(!this._events[d])return this;if(!c)return a(this,d),this;var p=this._events[d];if(p.fn)p.fn===c&&(!f||p.once)&&(!u||p.context===u)&&a(this,d);else{for(var g=0,m=[],y=p.length;g<y;g++)(p[g].fn!==c||f&&!p[g].once||u&&p[g].context!==u)&&m.push(p[g]);m.length?this._events[d]=m.length===1?m[0]:m:a(this,d)}return this},o.prototype.removeAllListeners=function(h){var c;return h?(c=r?r+h:h,this._events[c]&&a(this,c)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=r,o.EventEmitter=o,e.exports=o})(Po);var wd=Po.exports;const xd=on(wd);class To extends Error{constructor(t){super(t),this.name="TimeoutError"}}let Cd=class extends Error{constructor(t){super(),this.name="AbortError",this.message=t}};const Qn=e=>globalThis.DOMException===void 0?new Cd(e):new DOMException(e),Yn=e=>{const t=e.reason===void 0?Qn("This operation was aborted."):e.reason;return t instanceof Error?t:Qn(t)};function Sd(e,t,r,i){let n;const s=new Promise((a,o)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(t===Number.POSITIVE_INFINITY){a(e);return}if(i={customTimers:{setTimeout,clearTimeout},...i},i.signal){const{signal:l}=i;l.aborted&&o(Yn(l)),l.addEventListener("abort",()=>{o(Yn(l))})}n=i.customTimers.setTimeout.call(void 0,()=>{const l=`Promise timed out after ${t} milliseconds`,h=r instanceof Error?r:new To(l);typeof e.cancel=="function"&&e.cancel(),o(h)},t),(async()=>{try{a(await e)}catch(l){o(l)}finally{i.customTimers.clearTimeout.call(void 0,n)}})()});return s.clear=()=>{clearTimeout(n),n=void 0},s}function Ad(e,t,r){let i=0,n=e.length;for(;n>0;){const s=Math.trunc(n/2);let a=i+s;r(e[a],t)<=0?(i=++a,n-=s+1):n=s}return i}var de=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},zt;class $d{constructor(){zt.set(this,[])}enqueue(t,r){r={priority:0,...r};const i={priority:r.priority,run:t};if(this.size&&de(this,zt,"f")[this.size-1].priority>=r.priority){de(this,zt,"f").push(i);return}const n=Ad(de(this,zt,"f"),i,(s,a)=>a.priority-s.priority);de(this,zt,"f").splice(n,0,i)}dequeue(){const t=de(this,zt,"f").shift();return t==null?void 0:t.run}filter(t){return de(this,zt,"f").filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return de(this,zt,"f").length}}zt=new WeakMap;var K=function(e,t,r,i,n){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r},j=function(e,t,r,i){if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!i:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?i:r==="a"?i.call(e):i?i.value:t.get(e)},it,Je,Xe,ee,Er,Ke,Or,It,ze,vt,Ir,yt,Ze,te,jr,Vn,Jn,Fo,Xn,Kn,Pr,ui,hi,Rr,Eo,Tr;class Ro extends Error{}class Mo extends xd{constructor(t){var r,i,n,s;if(super(),it.add(this),Je.set(this,void 0),Xe.set(this,void 0),ee.set(this,0),Er.set(this,void 0),Ke.set(this,void 0),Or.set(this,0),It.set(this,void 0),ze.set(this,void 0),vt.set(this,void 0),Ir.set(this,void 0),yt.set(this,0),Ze.set(this,void 0),te.set(this,void 0),jr.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:$d,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(i=(r=t.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&i!==void 0?i:""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(n=t.interval)===null||n===void 0?void 0:n.toString())!==null&&s!==void 0?s:""}\` (${typeof t.interval})`);K(this,Je,t.carryoverConcurrencyCount,"f"),K(this,Xe,t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,"f"),K(this,Er,t.intervalCap,"f"),K(this,Ke,t.interval,"f"),K(this,vt,new t.queueClass,"f"),K(this,Ir,t.queueClass,"f"),this.concurrency=t.concurrency,this.timeout=t.timeout,K(this,jr,t.throwOnTimeout===!0,"f"),K(this,te,t.autoStart===!1,"f")}get concurrency(){return j(this,Ze,"f")}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);K(this,Ze,t,"f"),j(this,it,"m",Rr).call(this)}async add(t,r={}){return r={timeout:this.timeout,throwOnTimeout:j(this,jr,"f"),...r},new Promise((i,n)=>{j(this,vt,"f").enqueue(async()=>{var s,a,o;K(this,yt,(a=j(this,yt,"f"),a++,a),"f"),K(this,ee,(o=j(this,ee,"f"),o++,o),"f");try{if(!((s=r.signal)===null||s===void 0)&&s.aborted)throw new Ro("The task was aborted.");let l=t({signal:r.signal});r.timeout&&(l=Sd(Promise.resolve(l),r.timeout)),r.signal&&(l=Promise.race([l,j(this,it,"m",Eo).call(this,r.signal)]));const h=await l;i(h),this.emit("completed",h)}catch(l){if(l instanceof To&&!r.throwOnTimeout){i();return}n(l),this.emit("error",l)}finally{j(this,it,"m",Fo).call(this)}},r),this.emit("add"),j(this,it,"m",Pr).call(this)})}async addAll(t,r){return Promise.all(t.map(async i=>this.add(i,r)))}start(){return j(this,te,"f")?(K(this,te,!1,"f"),j(this,it,"m",Rr).call(this),this):this}pause(){K(this,te,!0,"f")}clear(){K(this,vt,new(j(this,Ir,"f")),"f")}async onEmpty(){j(this,vt,"f").size!==0&&await j(this,it,"m",Tr).call(this,"empty")}async onSizeLessThan(t){j(this,vt,"f").size<t||await j(this,it,"m",Tr).call(this,"next",()=>j(this,vt,"f").size<t)}async onIdle(){j(this,yt,"f")===0&&j(this,vt,"f").size===0||await j(this,it,"m",Tr).call(this,"idle")}get size(){return j(this,vt,"f").size}sizeBy(t){return j(this,vt,"f").filter(t).length}get pending(){return j(this,yt,"f")}get isPaused(){return j(this,te,"f")}}Je=new WeakMap,Xe=new WeakMap,ee=new WeakMap,Er=new WeakMap,Ke=new WeakMap,Or=new WeakMap,It=new WeakMap,ze=new WeakMap,vt=new WeakMap,Ir=new WeakMap,yt=new WeakMap,Ze=new WeakMap,te=new WeakMap,jr=new WeakMap,it=new WeakSet,Vn=function(){return j(this,Xe,"f")||j(this,ee,"f")<j(this,Er,"f")},Jn=function(){return j(this,yt,"f")<j(this,Ze,"f")},Fo=function(){var t;K(this,yt,(t=j(this,yt,"f"),t--,t),"f"),j(this,it,"m",Pr).call(this),this.emit("next")},Xn=function(){j(this,it,"m",hi).call(this),j(this,it,"m",ui).call(this),K(this,ze,void 0,"f")},Kn=function(){const t=Date.now();if(j(this,It,"f")===void 0){const r=j(this,Or,"f")-t;if(r<0)K(this,ee,j(this,Je,"f")?j(this,yt,"f"):0,"f");else return j(this,ze,"f")===void 0&&K(this,ze,setTimeout(()=>{j(this,it,"m",Xn).call(this)},r),"f"),!0}return!1},Pr=function(){if(j(this,vt,"f").size===0)return j(this,It,"f")&&clearInterval(j(this,It,"f")),K(this,It,void 0,"f"),this.emit("empty"),j(this,yt,"f")===0&&this.emit("idle"),!1;if(!j(this,te,"f")){const t=!j(this,it,"a",Kn);if(j(this,it,"a",Vn)&&j(this,it,"a",Jn)){const r=j(this,vt,"f").dequeue();return r?(this.emit("active"),r(),t&&j(this,it,"m",ui).call(this),!0):!1}}return!1},ui=function(){j(this,Xe,"f")||j(this,It,"f")!==void 0||(K(this,It,setInterval(()=>{j(this,it,"m",hi).call(this)},j(this,Ke,"f")),"f"),K(this,Or,Date.now()+j(this,Ke,"f"),"f"))},hi=function(){j(this,ee,"f")===0&&j(this,yt,"f")===0&&j(this,It,"f")&&(clearInterval(j(this,It,"f")),K(this,It,void 0,"f")),K(this,ee,j(this,Je,"f")?j(this,yt,"f"):0,"f"),j(this,it,"m",Rr).call(this)},Rr=function(){for(;j(this,it,"m",Pr).call(this););},Eo=async function(t){return new Promise((r,i)=>{t.addEventListener("abort",()=>{i(new Ro("The task was aborted."))},{once:!0})})},Tr=async function(t,r){return new Promise(i=>{const n=()=>{r&&!r()||(this.off(t,n),i())};this.on(t,n)})};var kd=function(t){for(var r=[],i=1;i<arguments.length;i++)r[i-1]=arguments[i];var n=[],s=typeof t=="string"?[t]:t.slice();s[s.length-1]=s[s.length-1].replace(/\r?\n([\t ]*)$/,"");for(var a=0;a<s.length;a++){var o=void 0;(o=s[a].match(/\n[\t ]+/g))&&n.push.apply(n,o)}if(n.length)for(var l=Math.min.apply(Math,n.map(function(u){return u.length-1})),h=new RegExp(`
|
|
11
|
+
[ ]{`+l+"}","g"),a=0;a<s.length;a++)s[a]=s[a].replace(h,`
|
|
12
|
+
`);s[0]=s[0].replace(/^\r?\n/,"");for(var c=s[0],a=0;a<r.length;a++)c+=r[a]+s[a+1];return c};const _d=on(kd);var ht=Uint8Array,wt=Uint16Array,ln=Int32Array,Jr=new ht([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xr=new ht([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Ni=new ht([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),No=function(e,t){for(var r=new wt(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];for(var n=new ln(r[30]),i=1;i<30;++i)for(var s=r[i];s<r[i+1];++s)n[s]=s-r[i]<<5|i;return{b:r,r:n}},Do=No(Jr,2),Lo=Do.b,Di=Do.r;Lo[28]=258,Di[258]=28;var Wo=No(Xr,0),Od=Wo.b,Zn=Wo.r,Li=new wt(32768);for(var Y=0;Y<32768;++Y){var Kt=(Y&43690)>>1|(Y&21845)<<1;Kt=(Kt&52428)>>2|(Kt&13107)<<2,Kt=(Kt&61680)>>4|(Kt&3855)<<4,Li[Y]=((Kt&65280)>>8|(Kt&255)<<8)>>1}var Dt=function(e,t,r){for(var i=e.length,n=0,s=new wt(t);n<i;++n)e[n]&&++s[e[n]-1];var a=new wt(t);for(n=1;n<t;++n)a[n]=a[n-1]+s[n-1]<<1;var o;if(r){o=new wt(1<<t);var l=15-t;for(n=0;n<i;++n)if(e[n])for(var h=n<<4|e[n],c=t-e[n],u=a[e[n]-1]++<<c,f=u|(1<<c)-1;u<=f;++u)o[Li[u]>>l]=h}else for(o=new wt(i),n=0;n<i;++n)e[n]&&(o[n]=Li[a[e[n]-1]++]>>15-e[n]);return o},oe=new ht(288);for(var Y=0;Y<144;++Y)oe[Y]=8;for(var Y=144;Y<256;++Y)oe[Y]=9;for(var Y=256;Y<280;++Y)oe[Y]=7;for(var Y=280;Y<288;++Y)oe[Y]=8;var nr=new ht(32);for(var Y=0;Y<32;++Y)nr[Y]=5;var Id=Dt(oe,9,0),jd=Dt(oe,9,1),Pd=Dt(nr,5,0),Td=Dt(nr,5,1),fi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Ot=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(t&7)&r},di=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},cn=function(e){return(e+7)/8|0},Uo=function(e,t,r){return(r==null||r>e.length)&&(r=e.length),new ht(e.subarray(t,r))},Fd=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],jt=function(e,t,r){var i=new Error(t||Fd[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,jt),!r)throw i;return i},Ed=function(e,t,r,i){var n=e.length,s=0;if(!n||t.f&&!t.l)return r||new ht(0);var a=!r,o=a||t.i!=2,l=t.i;a&&(r=new ht(n*3));var h=function(_t){var Vt=r.length;if(_t>Vt){var Et=new ht(Math.max(Vt*2,_t));Et.set(r),r=Et}},c=t.f||0,u=t.p||0,f=t.b||0,d=t.l,p=t.d,g=t.m,m=t.n,y=n*8;do{if(!d){c=Ot(e,u,1);var b=Ot(e,u+1,3);if(u+=3,b)if(b==1)d=jd,p=Td,g=9,m=5;else if(b==2){var $=Ot(e,u,31)+257,A=Ot(e,u+10,15)+4,x=$+Ot(e,u+5,31)+1;u+=14;for(var S=new ht(x),I=new ht(19),O=0;O<A;++O)I[Ni[O]]=Ot(e,u+O*3,7);u+=A*3;for(var E=fi(I),N=(1<<E)-1,M=Dt(I,E,1),O=0;O<x;){var U=M[Ot(e,u,N)];u+=U&15;var w=U>>4;if(w<16)S[O++]=w;else{var B=0,D=0;for(w==16?(D=3+Ot(e,u,3),u+=2,B=S[O-1]):w==17?(D=3+Ot(e,u,7),u+=3):w==18&&(D=11+Ot(e,u,127),u+=7);D--;)S[O++]=B}}var X=S.subarray(0,$),Q=S.subarray($);g=fi(X),m=fi(Q),d=Dt(X,g,1),p=Dt(Q,m,1)}else jt(1);else{var w=cn(u)+4,_=e[w-4]|e[w-3]<<8,C=w+_;if(C>n){l&&jt(0);break}o&&h(f+_),r.set(e.subarray(w,C),f),t.b=f+=_,t.p=u=C*8,t.f=c;continue}if(u>y){l&&jt(0);break}}o&&h(f+131072);for(var dt=(1<<g)-1,V=(1<<m)-1,pt=u;;pt=u){var B=d[di(e,u)&dt],R=B>>4;if(u+=B&15,u>y){l&&jt(0);break}if(B||jt(2),R<256)r[f++]=R;else if(R==256){pt=u,d=null;break}else{var q=R-254;if(R>264){var O=R-257,z=Jr[O];q=Ot(e,u,(1<<z)-1)+Lo[O],u+=z}var ot=p[di(e,u)&V],ct=ot>>4;ot||jt(3),u+=ot&15;var Q=Od[ct];if(ct>3){var z=Xr[ct];Q+=di(e,u)&(1<<z)-1,u+=z}if(u>y){l&&jt(0);break}o&&h(f+131072);var Ft=f+q;if(f<Q){var Wt=s-Q,ce=Math.min(Q,Ft);for(Wt+f<0&&jt(3);f<ce;++f)r[f]=i[Wt+f]}for(;f<Ft;++f)r[f]=r[f-Q]}}t.l=d,t.p=pt,t.b=f,t.f=c,d&&(c=1,t.m=g,t.d=p,t.n=m)}while(!c);return f!=r.length&&a?Uo(r,0,f):r.subarray(0,f)},Ut=function(e,t,r){r<<=t&7;var i=t/8|0;e[i]|=r,e[i+1]|=r>>8},We=function(e,t,r){r<<=t&7;var i=t/8|0;e[i]|=r,e[i+1]|=r>>8,e[i+2]|=r>>16},pi=function(e,t){for(var r=[],i=0;i<e.length;++i)e[i]&&r.push({s:i,f:e[i]});var n=r.length,s=r.slice();if(!n)return{t:zo,l:0};if(n==1){var a=new ht(r[0].s+1);return a[r[0].s]=1,{t:a,l:1}}r.sort(function(C,$){return C.f-$.f}),r.push({s:-1,f:25001});var o=r[0],l=r[1],h=0,c=1,u=2;for(r[0]={s:-1,f:o.f+l.f,l:o,r:l};c!=n-1;)o=r[r[h].f<r[u].f?h++:u++],l=r[h!=c&&r[h].f<r[u].f?h++:u++],r[c++]={s:-1,f:o.f+l.f,l:o,r:l};for(var f=s[0].s,i=1;i<n;++i)s[i].s>f&&(f=s[i].s);var d=new wt(f+1),p=Wi(r[c-1],d,0);if(p>t){var i=0,g=0,m=p-t,y=1<<m;for(s.sort(function($,A){return d[A.s]-d[$.s]||$.f-A.f});i<n;++i){var b=s[i].s;if(d[b]>t)g+=y-(1<<p-d[b]),d[b]=t;else break}for(g>>=m;g>0;){var w=s[i].s;d[w]<t?g-=1<<t-d[w]++-1:++i}for(;i>=0&&g;--i){var _=s[i].s;d[_]==t&&(--d[_],++g)}p=t}return{t:new ht(d),l:p}},Wi=function(e,t,r){return e.s==-1?Math.max(Wi(e.l,t,r+1),Wi(e.r,t,r+1)):t[e.s]=r},ts=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new wt(++t),i=0,n=e[0],s=1,a=function(l){r[i++]=l},o=1;o<=t;++o)if(e[o]==n&&o!=t)++s;else{if(!n&&s>2){for(;s>138;s-=138)a(32754);s>2&&(a(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(a(n),--s;s>6;s-=6)a(8304);s>2&&(a(s-3<<5|8208),s=0)}for(;s--;)a(n);s=1,n=e[o]}return{c:r.subarray(0,i),n:t}},Ue=function(e,t){for(var r=0,i=0;i<t.length;++i)r+=e[i]*t[i];return r},Bo=function(e,t,r){var i=r.length,n=cn(t+2);e[n]=i&255,e[n+1]=i>>8,e[n+2]=e[n]^255,e[n+3]=e[n+1]^255;for(var s=0;s<i;++s)e[n+s+4]=r[s];return(n+4+i)*8},es=function(e,t,r,i,n,s,a,o,l,h,c){Ut(t,c++,r),++n[256];for(var u=pi(n,15),f=u.t,d=u.l,p=pi(s,15),g=p.t,m=p.l,y=ts(f),b=y.c,w=y.n,_=ts(g),C=_.c,$=_.n,A=new wt(19),x=0;x<b.length;++x)++A[b[x]&31];for(var x=0;x<C.length;++x)++A[C[x]&31];for(var S=pi(A,7),I=S.t,O=S.l,E=19;E>4&&!I[Ni[E-1]];--E);var N=h+5<<3,M=Ue(n,oe)+Ue(s,nr)+a,U=Ue(n,f)+Ue(s,g)+a+14+3*E+Ue(A,I)+2*A[16]+3*A[17]+7*A[18];if(l>=0&&N<=M&&N<=U)return Bo(t,c,e.subarray(l,l+h));var B,D,X,Q;if(Ut(t,c,1+(U<M)),c+=2,U<M){B=Dt(f,d,0),D=f,X=Dt(g,m,0),Q=g;var dt=Dt(I,O,0);Ut(t,c,w-257),Ut(t,c+5,$-1),Ut(t,c+10,E-4),c+=14;for(var x=0;x<E;++x)Ut(t,c+3*x,I[Ni[x]]);c+=3*E;for(var V=[b,C],pt=0;pt<2;++pt)for(var R=V[pt],x=0;x<R.length;++x){var q=R[x]&31;Ut(t,c,dt[q]),c+=I[q],q>15&&(Ut(t,c,R[x]>>5&127),c+=R[x]>>12)}}else B=Id,D=oe,X=Pd,Q=nr;for(var x=0;x<o;++x){var z=i[x];if(z>255){var q=z>>18&31;We(t,c,B[q+257]),c+=D[q+257],q>7&&(Ut(t,c,z>>23&31),c+=Jr[q]);var ot=z&31;We(t,c,X[ot]),c+=Q[ot],ot>3&&(We(t,c,z>>5&8191),c+=Xr[ot])}else We(t,c,B[z]),c+=D[z]}return We(t,c,B[256]),c+D[256]},Rd=new ln([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),zo=new ht(0),Md=function(e,t,r,i,n,s){var a=s.z||e.length,o=new ht(i+a+5*(1+Math.ceil(a/7e3))+n),l=o.subarray(i,o.length-n),h=s.l,c=(s.r||0)&7;if(t){c&&(l[0]=s.r>>3);for(var u=Rd[t-1],f=u>>13,d=u&8191,p=(1<<r)-1,g=s.p||new wt(32768),m=s.h||new wt(p+1),y=Math.ceil(r/3),b=2*y,w=function(gt){return(e[gt]^e[gt+1]<<y^e[gt+2]<<b)&p},_=new ln(25e3),C=new wt(288),$=new wt(32),A=0,x=0,S=s.i||0,I=0,O=s.w||0,E=0;S+2<a;++S){var N=w(S),M=S&32767,U=m[N];if(g[M]=U,m[N]=M,O<=S){var B=a-S;if((A>7e3||I>24576)&&(B>423||!h)){c=es(e,l,0,_,C,$,x,I,E,S-E,c),I=A=x=0,E=S;for(var D=0;D<286;++D)C[D]=0;for(var D=0;D<30;++D)$[D]=0}var X=2,Q=0,dt=d,V=M-U&32767;if(B>2&&N==w(S-V))for(var pt=Math.min(f,B)-1,R=Math.min(32767,S),q=Math.min(258,B);V<=R&&--dt&&M!=U;){if(e[S+X]==e[S+X-V]){for(var z=0;z<q&&e[S+z]==e[S+z-V];++z);if(z>X){if(X=z,Q=V,z>pt)break;for(var ot=Math.min(V,z-2),ct=0,D=0;D<ot;++D){var Ft=S-V+D&32767,Wt=g[Ft],ce=Ft-Wt&32767;ce>ct&&(ct=ce,U=Ft)}}}M=U,U=g[M],V+=M-U&32767}if(Q){_[I++]=268435456|Di[X]<<18|Zn[Q];var _t=Di[X]&31,Vt=Zn[Q]&31;x+=Jr[_t]+Xr[Vt],++C[257+_t],++$[Vt],O=S+X,++A}else _[I++]=e[S],++C[e[S]]}}for(S=Math.max(S,O);S<a;++S)_[I++]=e[S],++C[e[S]];c=es(e,l,h,_,C,$,x,I,E,S-E,c),h||(s.r=c&7|l[c/8|0]<<3,c-=7,s.h=m,s.p=g,s.i=S,s.w=O)}else{for(var S=s.w||0;S<a+h;S+=65535){var Et=S+65535;Et>=a&&(l[c/8|0]=h,Et=a),c=Bo(l,c+1,e.subarray(S,Et))}s.i=a}return Uo(o,0,i+cn(c)+n)},qo=function(){var e=1,t=0;return{p:function(r){for(var i=e,n=t,s=r.length|0,a=0;a!=s;){for(var o=Math.min(a+2655,s);a<o;++a)n+=i+=r[a];i=(i&65535)+15*(i>>16),n=(n&65535)+15*(n>>16)}e=i,t=n},d:function(){return e%=65521,t%=65521,(e&255)<<24|(e&65280)<<8|(t&255)<<8|t>>8}}},Nd=function(e,t,r,i,n){if(!n&&(n={l:1},t.dictionary)){var s=t.dictionary.subarray(-32768),a=new ht(s.length+e.length);a.set(s),a.set(e,s.length),e=a,n.w=s.length}return Md(e,t.level==null?6:t.level,t.mem==null?n.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,i,n)},Ho=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8},Dd=function(e,t){var r=t.level,i=r==0?0:r<6?1:r==9?3:2;if(e[0]=120,e[1]=i<<6|(t.dictionary&&32),e[1]|=31-(e[0]<<8|e[1])%31,t.dictionary){var n=qo();n.p(t.dictionary),Ho(e,2,n.d())}},Ld=function(e,t){return((e[0]&15)!=8||e[0]>>4>7||(e[0]<<8|e[1])%31)&&jt(6,"invalid zlib data"),(e[1]>>5&1)==1&&jt(6,"invalid zlib data: "+(e[1]&32?"need":"unexpected")+" dictionary"),(e[1]>>3&4)+2};function qe(e,t){t||(t={});var r=qo();r.p(e);var i=Nd(e,t,t.dictionary?6:2,4);return Dd(i,t),Ho(i,i.length-4,r.d()),i}function Wd(e,t){return Ed(e.subarray(Ld(e),-4),{i:2},t,t)}var Ud=typeof TextDecoder<"u"&&new TextDecoder,Bd=0;try{Ud.decode(zo,{stream:!0}),Bd=1}catch{}let kt,sr;typeof TextEncoder<"u"&&typeof TextDecoder<"u"?(kt=new TextEncoder,sr=new TextDecoder):(kt=new dn.TextEncoder,sr=new dn.TextDecoder);let Mr;Xi()?Mr=fl.webcrypto:Mr=crypto;const Go=(()=>{const e=new Uint8Array(4),t=new Uint32Array(e.buffer);return!((t[0]=1)&e[0])})();function rs(e){const t=new Uint8Array(e);if(Mr!==void 0)Mr.getRandomValues(t);else{const r=new Uint32Array(t.buffer);for(let i=0;i<r.length;i++)r[i]=Math.floor(Math.random()*2**32)}return t}async function yr(e){const t=e instanceof Uint8Array?e:kt.encode(e);let r;if(Xi())r=await new Promise((i,n)=>hl.deflate(t,(s,a)=>s?n(s):i(a)));else{if(typeof CompressionStream>"u")try{let s;return e instanceof Uint8Array?s=e:s=kt.encode(e),r=qe(s),Promise.resolve({stream:r,dict:{Length:r.length,Filter:"/FlateDecode"}})}catch(s){return k.warn(`Failed to use JS deflate implementation, data will be written uncompressed: ${s}`),Promise.resolve({stream:e,dict:{Length:e.length}})}const i=new CompressionStream("deflate"),n=new Blob([t]).stream().pipeThrough(i);r=new Uint8Array(await new Response(n).arrayBuffer())}return{dict:{Length:r.length,Filter:"/FlateDecode"},stream:r}}const is=2;class Fe{constructor(t){v(this,"refObj");this.refObj=t}}function L(e){const t=typeof e=="number"?e:e.num;return new Fe(t)}function zd(e){for(let t=0,r=e.length;t<r;t++)if(e.charCodeAt(t)>127)return!0;return!1}function Ui(e,t=!0){const r=new Uint16Array(e.length+(t?1:0));for(let n=t?1:0;n<r.length;n++)r[n]=e.charCodeAt(n-(t?1:0));const i=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(!Go)for(let n=t?2:0,s=i.length-1;n<s;n+=2){const a=i[n];i[n]=i[n+1],i[n+1]=a}return t&&(i[0]=254,i[1]=255),i}function qd(e){if(e>-1e21&&e<1e21)return Math.round(e*1e6)/1e6;throw new Error(`unsupported number: ${e}`)}function $t(e,t=0){if(typeof e=="string")return e[0]==="("&&e[e.length-1]===")"&&zd(e)?$t(Ui(e.substring(1,e.length-1))):e;if(e instanceof Uint8Array)return`<${Array.from(e).map(r=>r.toString(16).padStart(2,"0").toUpperCase()).join("")}>`;if(e instanceof Date)return`(${`D:${e.getUTCFullYear().toString(10).padStart(4,"0")}`+(e.getUTCMonth()+1).toString(10).padStart(2,"0")+e.getUTCDate().toString(10).padStart(2,"0")+e.getUTCHours().toString(10).padStart(2,"0")+e.getUTCMinutes().toString(10).padStart(2,"0")+e.getUTCSeconds().toString(10).padStart(2,"0")+"Z"})`;if(Array.isArray(e))return`[${e.map(r=>$t(r,t+1)).join(" ")}]`;if(e instanceof Fe){if(e.refObj===-1)throw new Error("Cannot serialize a deferred object reference");return`${e.refObj} 0 R`}else if({}.toString.call(e)==="[object Object]"){const r=" ".repeat(is*t),i=r+" ".repeat(is);return`<<
|
|
13
|
+
${Object.entries(e).map(([n,s])=>`${i}/${n} ${$t(s,t+1)}`).join(`
|
|
14
|
+
`)}
|
|
15
|
+
${r}>>`}else return typeof e=="number"?qd(e).toString(10):`${e}`}class Hd{constructor(t){v(this,"_writer");v(this,"bytesWritten",0);this._writer=t}write(t){return this.bytesWritten+=t.length,this._writer.write(t)}close(){return this._writer.close()}waitForDrain(){return this._writer.waitForDrain()}}class Gd{constructor(t){v(this,"_writer");this._writer=t.getWriter()}write(t){return this._writer.write(t)}waitForDrain(){return this._writer.ready}close(){return this._writer.close()}}class ns{constructor(){v(this,"_parts");v(this,"_blob");this._parts=[]}write(t){return this._blob?Promise.reject("Cannot write to closed BlobWriter."):(this._parts.push(t),Promise.resolve())}waitForDrain(){return this._blob?Promise.reject("Cannot wait on a closed BlobWriter."):Promise.resolve()}close(){return this._blob?Promise.reject("BlobWriter is already closed"):(this._blob=new Blob(this._parts),this._parts=[],Promise.resolve())}get blob(){if(!this._blob)throw"BlobWriter must be closed first!";return this._blob}}class Qd{constructor(t){v(this,"_writable");v(this,"_drainWaiters",[]);this._writable=t,this._writable.on("drain",()=>{k.debug("Drained writer.");for(const r of this._drainWaiters)r();this._drainWaiters=[]}),this._writable.on("close",()=>{for(const r of this._drainWaiters)r();this._drainWaiters=[]})}async write(t){let r=!1;const i=new Promise((n,s)=>{this._writable.writable||s("Cannot write to closed NodeWriter."),r=!this._writable.write(t,a=>a?s(a):n())});return r?(k.debug("Waiting for writer to drain"),await this.waitForDrain()):await i}waitForDrain(){return new Promise(t=>this._drainWaiters.push(t))}close(){return new Promise(t=>this._writable.end(()=>t()))}}class Yd{constructor(t){v(this,"_buf");this._buf=t}read(t,r,i,n){const s=this._buf.subarray(i,i+n);return t.set(s,r),Promise.resolve(s.length)}size(){return Promise.resolve(this._buf.length)}}const Lr=class Lr{constructor(t){v(this,"palette");v(this,"imgData");v(this,"transparency");v(this,"text");v(this,"width");v(this,"height");v(this,"bits");v(this,"colorType");v(this,"compressionMethod");v(this,"filterMethod");v(this,"interlaceMethod");v(this,"colors");v(this,"hasAlphaChannel");v(this,"pixelBitlength");v(this,"colorSpace");v(this,"data");v(this,"pos");v(this,"decode",()=>{const t=new Uint8Array(this.width*this.height*4),r=this.decodePixels();return this.copyImageDataToBuffer(t,r),t});v(this,"copyImageDataToBuffer",(t,r)=>{let i=this.colors,n,s=this.hasAlphaChannel;this.palette.length&&(n=this.decodePalette(),i=4,s=!0);const a=t,o=a.length,l=n||r;let h=0,c=0;if(i===1)for(;h<o;){let u=n?r[h/4]*4:c;const f=l[u++];a[h++]=f,a[h++]=f,a[h++]=f,a[h++]=s?l[u++]:255,c=u}else for(;h<o;){let u=n?r[h/4]*4:c;a[h++]=l[u++],a[h++]=l[u++],a[h++]=l[u++],a[h++]=s?l[u++]:255,c=u}});v(this,"decodePixels",()=>{const t=Wd(this.imgData),r=this.width,i=this.height,n=this.pixelBitlength/8,s=n*this.width,a=new Uint8Array(s*this.height),o=t.length;let l=0;function h(c,u,f,d,p=!1){const g=Math.ceil((r-c)/f),m=Math.ceil((i-u)/d),y=n*g,b=p?a:new Uint8Array(y*m);let w=0,_=0;for(;w<m&&l<o;){switch(t[l++]){case 0:for(let C=0;C<y;C++)b[_++]=t[l++];break;case 1:for(let C=0;C<y;C++){const $=t[l++],A=C<n?0:b[_-n];b[_++]=($+A)%256}break;case 2:for(let C=0;C<y;C++){const $=t[l++],A=(C-C%n)/n,x=(w-1)*y+A*n+C%n,S=w&&b[x];b[_++]=(S+$)%256}break;case 3:for(let C=0;C<y;C++){const $=t[l++],A=(C-C%n)/n,x=C<n?0:b[_-n],S=(w-1)*y+A*n+C%n,I=w&&b[S];b[_++]=($+Math.floor((x+I)/2))%256}break;case 4:for(let C=0;C<y;C++){const $=t[l++],A=(C-C%n)/n,x=C<n?0:b[_-n];let S,I;if(w===0)S=I=0;else{const B=(w-1)*y+A*n+C%n,D=(w-1)*y+(A-1)*n+C%n;S=b[B],I=A&&b[D]}const O=x+S-I,E=Math.abs(O-x),N=Math.abs(O-S),M=Math.abs(O-I);let U;E<=N&&E<=M?U=x:N<=M?U=S:U=I,b[_++]=($+U)%256}break;default:throw new Error(`Invalid filter algorithm: ${t[l-1]}`)}if(!p){let C=((u+w*d)*r+c)*n,$=w*y;for(let A=0;A<g;A++){for(let x=0;x<n;x++)a[C++]=b[$++];C+=(f-1)*n}}w++}}return this.interlaceMethod===0?h(0,0,1,1,!0):(h(0,0,8,8),h(4,0,8,8),h(0,4,4,8),h(2,0,4,4),h(0,2,2,4),h(1,0,2,2),h(0,1,1,2)),a});v(this,"read",t=>{const r=[];for(let i=0;i<t;i++)r[i]=this.data[this.pos++];return r});v(this,"readUInt32",()=>{const t=this.data[this.pos++]<<24,r=this.data[this.pos++]<<16,i=this.data[this.pos++]<<8,n=this.data[this.pos++];return t|r|i|n});v(this,"decodePalette",()=>{const t=this.palette,r=this.transparency.indexed||[],i=new Uint8Array(r.length+t.length);let n=0,s=0;for(let a=0;a<t.length;a++){i[n++]=t[a],i[n++]=t[a+1],i[n++]=t[a+2];const o=r[s++];i[n++]=o!==void 0?o:255}return i});this.data=t,this.pos=8,this.palette=[];const r=[];for(this.transparency={},this.text={};;){const i=this.readUInt32();let n="";for(let s=0;s<4;s++)n+=String.fromCharCode(this.data[this.pos++]);switch(n){case"IHDR":{this.width=this.readUInt32(),this.height=this.readUInt32(),this.bits=this.data[this.pos++],this.colorType=this.data[this.pos++],this.compressionMethod=this.data[this.pos++],this.filterMethod=this.data[this.pos++],this.interlaceMethod=this.data[this.pos++];break}case"PLTE":{this.palette=this.read(i);break}case"IDAT":{for(let s=0;s<i;s++)r.push(this.data[this.pos++]);break}case"tRNS":{switch(this.transparency={},this.colorType){case 3:{if(this.transparency.indexed=this.read(i),255-this.transparency.indexed.length>0)for(let a=0;a<255;a++)this.transparency.indexed.push(255);break}case 0:{this.transparency.grayscale=this.read(i)[0];break}case 2:{this.transparency.rgb=this.read(i);break}}break}case"tEXt":{const s=this.read(i),a=s.indexOf(0),o=String.fromCharCode(...s.slice(0,a));this.text[o]=String.fromCharCode(...s.slice(a+1));break}case"IEND":{const s={0:1,3:1,4:1,2:3,6:3};this.colors=s[this.colorType],this.hasAlphaChannel=[4,6].includes(this.colorType);const a=this.colors+(this.hasAlphaChannel?1:0);this.pixelBitlength=this.bits*a,this.colorSpace={1:"DeviceGray",3:"DeviceRGB"}[this.colors],this.imgData=new Uint8Array(r);return}default:this.pos+=i}if(this.pos+=4,this.pos>this.data.length)throw new Error("Incomplete or corrupt PNG file")}}};v(Lr,"load",t=>new Lr(t));let Bi=Lr;function Be(e,t=0){const r=new Uint16Array(e.slice(t,t+2).buffer)[0];return Go?r:(r&255)<<8|r>>8&255}class un{static open(t){if(t.length>2&&t[0]===255&&t[1]===216)return new ar(t);if(t.length>8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10)return new Vd(t);throw new Error("Unknown image format.")}}const be=class be extends un{constructor(r){super();v(this,"data");v(this,"bits");v(this,"width");v(this,"height");v(this,"colorSpace");let i;if(this.data=r,Be(this.data,0)!==65496)throw"SOI not found in JPEG";let n=2;for(;n<this.data.length&&(i=Be(this.data,n),n+=2,!be.MARKERS.includes(i));)n+=Be(this.data,n);if(!i||!be.MARKERS.includes(i))throw"Invalid JPEG.";n+=2,this.bits=this.data[n++],this.height=Be(this.data,n),n+=2,this.width=Be(this.data,n),n+=2;const s=this.data[n++];if([1,3,4].indexOf(s)<0)throw"Bad number of channels, only 1, 3 or 4 are supported";this.colorSpace=be.COLOR_SPACE_MAP[s]}toObjects(r){const i={Type:"/XObject",Subtype:"/Image",BitsPerComponent:this.bits,Width:this.width,Height:this.height,ColorSpace:`/${this.colorSpace}`,Filter:"/DCTDecode",Length:this.data.length};return this.colorSpace==="DeviceCMYK"&&(i.Decode=[1,0,1,0,1,0,1,0]),[{num:r,data:$t(i),stream:this.data}]}};v(be,"MARKERS",[65472,65473,65474,65475,65477,65478,65479,65480,65481,65482,65483,65484,65485,65486,65487]),v(be,"COLOR_SPACE_MAP",{1:"DeviceGray",3:"DeviceRGB",4:"DeviceCMYK"});let ar=be;class Vd extends un{constructor(r,i){super();v(this,"label");v(this,"image");v(this,"width");v(this,"height");v(this,"imgData");this.label=i,this.image=new Bi(r),this.width=this.image.width,this.height=this.image.height,this.imgData=this.image.imgData}toObjects(r){var c,u;let i=!1;const n=this.image.hasAlphaChannel,s=this.image.interlaceMethod===1,a=[];let o=r;const l={num:o++};a.push(l);const h={Type:"/XObject",Subtype:"/Image",BitsPerComponent:n?8:this.image.bits,Width:this.width,Height:this.height,Filter:"/FlateDecode"};if(n||(h.DecodeParms={Predictor:s?1:15,Colors:this.image.colors,BitsPerComponent:this.image.bits,Columns:this.width}),this.image.palette.length===0)h.ColorSpace=`/${this.image.colorSpace}`;else{const f={num:o++,data:$t({Length:this.image.palette.length}),stream:new Uint8Array(this.image.palette)};a.push(f),h.ColorSpace=["/Indexed","/DeviceRGB",this.image.palette.length/3-1,L(f)]}if(this.image.transparency.grayscale!=null){const f=this.image.transparency.grayscale;h.Mask=[f,f]}else if(this.image.transparency.rgb){const{rgb:f}=this.image.transparency,d=[];for(let p of f)d.push(p,p);h.Mask=d}else if(this.image.transparency.indexed){const f=this.loadIndexedAlphaChannel(o++);h.SMask=L(f),a.push(f),i=!0}else if(n){const[f,d]=this.splitAlphaChannel(o++);l.stream=qe(f),h.Length=((c=l.stream)==null?void 0:c.length)??0,h.SMask=L(d),a.push(d)}if(s&&!i&&!l.stream?(l.stream=qe(this.image.decodePixels()),h.Length=((u=l.stream)==null?void 0:u.length)??0):l.stream||(l.stream=this.imgData,h.Length=l.stream.length),l.data=$t(h),a.length<3)for(let f=a.length;f<3;f++)a.push({num:o++});return a}splitAlphaChannel(r){const i=this.image.decodePixels(),n=this.image.colors,s=this.width*this.height,a=new Uint8Array(s*n),o=new Uint8Array(s);let l=0,h=0,c=0;const u=i.length,f=this.image.bits===16?1:0;for(;l<u;){for(let p=0;p<n;p++)a[c++]=i[l++],l+=f;o[h++]=i[l++],l+=f}const d=qe(o);return[a,{num:r,data:$t({Type:"/XObject",Subtype:"/Image",Width:this.width,Height:this.height,BitsPerComponent:8,Decode:[0,1],ColorSpace:"/DeviceGray",Filter:"/FlateDecode",Length:d.length}),stream:d}]}loadIndexedAlphaChannel(r){const i=this.image.decodePixels(),n=this.image.transparency.indexed,s=new Uint8Array(this.width*this.height);let a=0;for(let l=0,h=i.length;l<h;l++)s[a++]=n[i[l]];const o=qe(s);return{num:r,data:$t({Type:"/XObject",Subtype:"/Image",Width:this.width,Height:this.height,BitsPerComponent:8,Decode:[0,1],ColorSpace:"/DeviceGray",Filter:"/FlateDecode",Length:o.length}),stream:o}}}Uint8Array.prototype.findLastIndex||(Uint8Array.prototype.findLastIndex=function(e){let t=this.length;for(;t--;)if(e(this[t],t,this))return t;return-1});const Jd={n:`
|
|
16
|
+
`,r:"\r",t:" ",b:"\b",f:"\f","(":"(",")":")","\\":"\\"};async function*Qo(e,t,r){const i=new Uint8Array(r);if(t+=await e.read(i,0,t,i.length),!Mt(i,0,"xref"))throw"Invalid crossreference section, did not start with `xref` line.";const n=i.findIndex((u,f)=>Mt(i,f,"trailer")),s=sr.decode(i.subarray(0,n)).split(/[\r ]?\n/).slice(1);let a;for(const u of s)if(u.length===18){if(!a)throw"Invalid crossreference section, entry outside of subsection.";const f=u.trim().split(" ");a.entries.push([Number.parseInt(f[0],10),Number.parseInt(f[1],10),f[2]==="n"])}else{if(a){if(a.numObjs!==a.entries.length)throw`Invalid subsection, expected ${a.numObjs} objects, found ${a.entries.length}!`;yield a,a=void 0}if(u.length===0||u.indexOf("trailer")>=0)break;const[f,d]=u.trimEnd().split(" ").map(p=>Number.parseInt(p,10));a={startNum:f,numObjs:d,entries:[]}}a&&(yield a);const o=i.subarray(n),l=o.findIndex((u,f)=>Mt(o,f,"<<")),h=o.findIndex((u,f)=>Mt(o,f,">>")),c=new zi(o.subarray(l,h+2)).read();if(c.Prev){const u=c.Prev;yield*Qo(e,u,t-u)}}function Mt(e,t,r,i=!1){if(i){for(let n=r.length-1;n>=0;n--)if(e[t+n]!==r.charCodeAt(n))return!1}else for(let n=0;n<r.length;n++)if(e[t+n]!==r.charCodeAt(n))return!1;return!0}function $e(e){return!isNaN(parseInt(e,10))}function br(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}class zi{constructor(t){v(this,"start",0);v(this,"current",0);v(this,"buf");this.buf=t}getChar(){return String.fromCharCode(this.buf[this.current])}matchValue(t){return sr.decode(this.buf.subarray(this.current,this.current+kt.encode(t).length))===t}matchInteger(t=!0){this.start=this.current;let r,i=!0;const n=[];for(;!this.matchWhiteSpace(r=this.getChar())&&!this.matchDelimiter(r);){if(r==="+"||r==="-"){if(this.current-this.start>0){i=!1;break}}else if(!$e(r)){i=!1;break}this.current++,n.push(r)}return t&&(this.current=this.start),i?n.join(""):void 0}read(){let t=this.getChar();switch(this.matchWhiteSpace(t)&&(this.skipWhiteSpace(),t=this.getChar()),this.getChar()){case"[":return this.readArray();case"<":return this.matchValue("<<")?this.readDict():this.readHexString();case"(":return this.readLiteralString();case"/":return this.readName();case"t":if(this.matchValue("true"))return this.current+=4,!0;throw new Error("Unexpected character while parsing");case"f":if(this.matchValue("false"))return this.current+=5,!1;throw new Error("Unexpected character while parsing");case"n":if(this.matchValue("null"))return this.current+=4,null;throw new Error("Unexpected character while parsing");case".":return this.readRealNumber();default:if(this.matchIndirectObject())return this.readIndirectObject();if(this.matchRealNumber())return this.readRealNumber();if(this.matchInteger())return this.readInteger();throw new Error(`Encountered unexpected character during parsing: '${t}'`)}}matchWhiteSpace(t){return t===" "||t==="\0"||t===`
|
|
17
|
+
`||t==="\r"||t===`\r
|
|
18
|
+
`||t=="\f"}readInteger(){const t=this.matchInteger(!1);if(t===void 0)throw new Error("Failed to read integer.");return Number.parseInt(t,10)}readIndirectObject(){const t=this.matchIndirectObject(!1);if(t===void 0)throw new Error("Failed to read indirect object");return new Fe(Number.parseInt(t.split(" ")[0]))}matchIndirectObject(t=!0){this.start=this.current;let r=this.getChar();const i=[],n=()=>{if(!$e(r))return!1;for(i.push(r),this.current++;$e(r=this.getChar());)i.push(r),this.current++;return!0},s=()=>this.skipWhiteSpace(),o=!n()||!s()||(i.push(" "),r=this.getChar(),!n())||!s()||(i.push(" "),this.getChar()!=="R")?!1:(i.push("R"),this.current++,!0);if(t&&(this.current=this.start),o)return i.join("")}matchRealNumber(t=!0){this.start=this.current;let r=!0,i=!1,n=!1;const s=[];let a;for(;;){if(a=this.getChar(),a==="."){if(n){r=!1;break}n=!0}else if($e(a))i=!0;else if(a==="-"||a==="+"){if(this.current-this.start>0)break}else break;s.push(a),this.current++}if(t&&(this.current=this.start),!!r&&i&&n)return s.join("")}readRealNumber(){const t=this.matchRealNumber(!1);if(!t)throw new Error("Could not read real number.");return Number.parseFloat(t)}skipWhiteSpace(){let t=!1;for(;!this.atEnd()&&this.matchWhiteSpace(this.getChar());)this.current++,t=!0;return t}atEnd(){return this.current>=this.buf.length}readName(){const t=["/"];this.current++;let r;for(;!this.matchWhiteSpace(r=this.getChar())&&!this.matchDelimiter(r);)if(r==="#"){const i=this.buf[this.current++],n=this.buf[this.current++];if(!br(i)||!br(n))throw new Error("Illegal character escape in name.");t.push(String.fromCharCode(Number.parseInt(String.fromCharCode(i)+String.fromCharCode(n),16)))}else t.push(r),this.current++;return t.join("")}matchDelimiter(t){return"[]{}()<>/%".indexOf(t)>=0}readHexString(){this.current++;const t=[];for(;this.getChar()!==">";){const r=this.buf[this.current++],i=this.buf[this.current++];if(!br(r)||!br(i))throw new Error(`Invalid value in hex string: '${r}${i}`);t.push(Number.parseInt(String.fromCharCode(r)+String.fromCharCode(i),16))}return this.current++,new Uint8Array(t)}readLiteralString(){this.current++;const t=[];let r=0,i;for(;;){if(i=this.getChar(),i==="\\"){if(this.current++,i=this.getChar(),$e(i)){let n=[i];for(this.current++;$e(this.getChar());)n.push(this.getChar()),this.current++;n.length>3&&(this.current-=n.length-3,n=n.slice(0,3)),this.current--,i=String.fromCharCode(Number.parseInt(n.join(""),8))}else if(i=Jd[i],i===void 0)throw new Error(`Illegal escape sequence in string literal: '\\${i}`)}else if(i==="(")r++;else if(i===")"&&(r--,r<0))return this.current++,t.join("");t.push(i),this.current++}}readDict(){this.current+=2;const t={};for(this.skipWhiteSpace();this.getChar()!==">";){const r=this.read();if(typeof r!="string"||!r.startsWith("/"))throw new Error(`Dictionary keys must be name objects, got '${r}`);this.skipWhiteSpace();const i=this.read();i!==null&&(t[r.substring(1)]=i),this.skipWhiteSpace()}return this.current+=2,t}readArray(){this.current++;const t=[];for(;this.getChar()!=="]";)t.push(this.read()),this.skipWhiteSpace();return this.current++,t}}class hn{constructor(t,r,i,n){v(this,"reader");v(this,"objectOffsets");v(this,"sortedOffsets");v(this,"pdfSize");v(this,"objGenerations");v(this,"infoNum");v(this,"catalogNum");this.reader=t,this.objectOffsets=r,this.sortedOffsets=[...r].sort((s,a)=>s-a),this.objGenerations=i,this.catalogNum=n.Root.refObj,this.infoNum=n.Info.refObj}static async parse(t){const r=new Uint8Array(1024),n=await t.size()-r.length;await t.read(r,0,n,r.length);const s=r.length-(r[r.length-1]===70?5:6);if(!Mt(r,s,"%%EOF"))throw"Invalid PDF, missing EOF comment at end of file";const a=r.findLastIndex((d,p)=>Mt(r,p,"startxref"));if(a<0)throw"Invalid PDF, missing startxref marker in file trailer.";const o=[],l=[],h=Number.parseInt(sr.decode(r.subarray(a+9,s)).trim(),10),c=r.findLastIndex((d,p)=>Mt(r,p,">>"))+2,u=r.findLastIndex((d,p)=>Mt(r,p,"<<")),f=new zi(r.subarray(u,c)).read();for await(const{startNum:d,entries:p}of Qo(t,h,n+c-h))for(const[g,[m,y,b]]of p.entries()){const w=g+d;(o[w]??-1)>y||(o[w]=y,b?l[w]=m:l[w]=-1)}if(l.length!==f.Size)throw`Trailer dictionary has different number of objects than crossreference tables, ${l.length} vs. ${f.Size}`;return new hn(t,l,o,f)}async catalog(){const t=await this.getObject(this.catalogNum);if(!t)throw`Document has no catalog object (num as per trailer: ${this.catalogNum}!`;return t.data}async info(){const t=await this.getObject(this.infoNum);if(!t)throw`Document has no info object (num as per trailer: ${this.infoNum}!`;return t.data}async*_pagesFromPagesObj(t){for(const r of t.Kids){const i=await this.getObject(r.refObj,!0);if(!i)throw`Could not find Page object with number ${r.refObj}`;const n=i.data;n.Type==="/Pages"?yield*this._pagesFromPagesObj(n):yield i}}async*pages(){const r=(await this.catalog()).Pages,i=await this.getObject(r.refObj);if(!i)throw`Could not find Pages object with number ${r.refObj}`;const n=i.data;yield*this._pagesFromPagesObj(n)}async*annotations(t){const r=t.Annots;if(r)for(const i of r){const n=await this.getObject(i.refObj);if(!n)throw`Could not find Annotation object with number ${i.refObj}`;yield n.data}}resolveRef(t){return this.getObject(t.refObj,!0)}async getObject(t,r=!1){const i=this.objectOffsets[t];if(!i)return;this.pdfSize||(this.pdfSize=await this.reader.size());const n=this.sortedOffsets[this.sortedOffsets.indexOf(i)+1]??this.pdfSize,s=new Uint8Array(n-i);await this.reader.read(s,0,i,s.length);const a=s.findIndex((f,d)=>Mt(s,d,"endobj"));let o=s.findIndex((f,d)=>Mt(s,d,"stream"));o>=0&&(o+=6,s[o]===13?o+=2:o+=1);const l=`${t} ${this.objGenerations[t]} obj`,c=new zi(s.subarray(l.length,o<0?a:o)).read();if(typeof c!="object"||c===null)throw new Error("Illegal PDF object, does not start with a dictionary.");let u;if(r&&o>0){const f=c.Length;if(f===void 0)throw new Error("Illegal stream object, missing Length entry in object dictionary.");u=s.subarray(o,o+f)}return{num:t,data:c,stream:u}}}const fn="0.2.6";function Xd({creationDate:e=new Date,filename:t,data:r,compressedData:i,extraDataLength:n}){const s=e.getHours()<<11|e.getDay()<<5|Math.round(e.getSeconds()/2),a=e.getFullYear()-1980<<9|e.getMonth()+1<<5|e.getDate(),o=Cs(r),l=kt.encode(t),h=i?i.length-2:r.length;return new Uint8Array([80,75,3,4,20,0,0,0,i?8:0,0,s&255,s>>8,a&255,a>>8,o&255,o>>8&255,o>>16&255,o>>24&255,h&255,h>>8&255,h>>16&255,h>>24&255,r.length&255,r.length>>8&255,r.length>>16&255,r.length>>24&255,l.length&255,l.length>>8,n+4&255,n+4>>8,...l,255,255,n&255,n>>8])}function Kd({files:e,trailingLength:t,offset:r}){const i=e.map(Zd),n=i.reduce((s,a)=>s+a.length,0);return i.push(new Uint8Array([80,75,5,6,0,0,0,0,e.length&255,e.length>>8,e.length&255,e.length>>8,n&255,n>>8&255,n>>16&255,n>>24&255,r&255,r>>8&255,r>>16&255,r>>24&255,t&255,t>>8])),new Uint8Array(i.reduce((s,a)=>(s.push(...a),s),[]))}function Zd(e){const t=e.creationDate.getHours()<<11|e.creationDate.getMinutes()<<5|Math.round(e.creationDate.getSeconds()/2),r=e.creationDate.getFullYear()-1980<<9|e.creationDate.getMonth()+1<<5|e.creationDate.getDate(),i=kt.encode(e.filename);return new Uint8Array([80,75,1,2,23,3,20,0,0,0,e.deflated?8:0,0,t&255,t>>8,r&255,r>>8,e.crc32&255,e.crc32>>8&255,e.crc32>>16&255,e.crc32>>24&255,e.compressedDataLength&255,e.compressedDataLength>>8&255,e.compressedDataLength>>16&255,e.compressedDataLength>>24&255,e.dataLength&255,e.dataLength>>8&255,e.dataLength>>16&255,e.dataLength>>24&255,i.length&255,i.length>>8,0,0,0,0,0,0,0,0,0,0,164,129,e.localHeaderOffset&255,e.localHeaderOffset>>8&255,e.localHeaderOffset>>16&255,e.localHeaderOffset>>24&255,...i])}var Yo={exports:{}},Vo={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},Jo={exports:{}},tp=function(t){return!t||typeof t=="string"?!1:t instanceof Array||Array.isArray(t)||t.length>=0&&(t.splice instanceof Function||Object.getOwnPropertyDescriptor(t,t.length-1)&&t.constructor.name!=="String")},ep=tp,rp=Array.prototype.concat,ip=Array.prototype.slice,ss=Jo.exports=function(t){for(var r=[],i=0,n=t.length;i<n;i++){var s=t[i];ep(s)?r=rp.call(r,ip.call(s)):r.push(s)}return r};ss.wrap=function(e){return function(){return e(ss(arguments))}};var np=Jo.exports,tr=Vo,ur=np,Xo=Object.hasOwnProperty,Ko=Object.create(null);for(var gi in tr)Xo.call(tr,gi)&&(Ko[tr[gi]]=gi);var xt=Yo.exports={to:{},get:{}};xt.get=function(e){var t=e.substring(0,3).toLowerCase(),r,i;switch(t){case"hsl":r=xt.get.hsl(e),i="hsl";break;case"hwb":r=xt.get.hwb(e),i="hwb";break;default:r=xt.get.rgb(e),i="rgb";break}return r?{model:i,value:r}:null};xt.get.rgb=function(e){if(!e)return null;var t=/^#([a-f0-9]{3,4})$/i,r=/^#([a-f0-9]{6})([a-f0-9]{2})?$/i,i=/^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,n=/^rgba?\(\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*,?\s*([+-]?[\d\.]+)\%\s*(?:[,|\/]\s*([+-]?[\d\.]+)(%?)\s*)?\)$/,s=/^(\w+)$/,a=[0,0,0,1],o,l,h;if(o=e.match(r)){for(h=o[2],o=o[1],l=0;l<3;l++){var c=l*2;a[l]=parseInt(o.slice(c,c+2),16)}h&&(a[3]=parseInt(h,16)/255)}else if(o=e.match(t)){for(o=o[1],h=o[3],l=0;l<3;l++)a[l]=parseInt(o[l]+o[l],16);h&&(a[3]=parseInt(h+h,16)/255)}else if(o=e.match(i)){for(l=0;l<3;l++)a[l]=parseInt(o[l+1],0);o[4]&&(o[5]?a[3]=parseFloat(o[4])*.01:a[3]=parseFloat(o[4]))}else if(o=e.match(n)){for(l=0;l<3;l++)a[l]=Math.round(parseFloat(o[l+1])*2.55);o[4]&&(o[5]?a[3]=parseFloat(o[4])*.01:a[3]=parseFloat(o[4]))}else return(o=e.match(s))?o[1]==="transparent"?[0,0,0,0]:Xo.call(tr,o[1])?(a=tr[o[1]],a[3]=1,a):null:null;for(l=0;l<3;l++)a[l]=se(a[l],0,255);return a[3]=se(a[3],0,1),a};xt.get.hsl=function(e){if(!e)return null;var t=/^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d\.]+)%\s*,?\s*([+-]?[\d\.]+)%\s*(?:[,|\/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=e.match(t);if(r){var i=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=se(parseFloat(r[2]),0,100),a=se(parseFloat(r[3]),0,100),o=se(isNaN(i)?1:i,0,1);return[n,s,a,o]}return null};xt.get.hwb=function(e){if(!e)return null;var t=/^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/,r=e.match(t);if(r){var i=parseFloat(r[4]),n=(parseFloat(r[1])%360+360)%360,s=se(parseFloat(r[2]),0,100),a=se(parseFloat(r[3]),0,100),o=se(isNaN(i)?1:i,0,1);return[n,s,a,o]}return null};xt.to.hex=function(){var e=ur(arguments);return"#"+wr(e[0])+wr(e[1])+wr(e[2])+(e[3]<1?wr(Math.round(e[3]*255)):"")};xt.to.rgb=function(){var e=ur(arguments);return e.length<4||e[3]===1?"rgb("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+")":"rgba("+Math.round(e[0])+", "+Math.round(e[1])+", "+Math.round(e[2])+", "+e[3]+")"};xt.to.rgb.percent=function(){var e=ur(arguments),t=Math.round(e[0]/255*100),r=Math.round(e[1]/255*100),i=Math.round(e[2]/255*100);return e.length<4||e[3]===1?"rgb("+t+"%, "+r+"%, "+i+"%)":"rgba("+t+"%, "+r+"%, "+i+"%, "+e[3]+")"};xt.to.hsl=function(){var e=ur(arguments);return e.length<4||e[3]===1?"hsl("+e[0]+", "+e[1]+"%, "+e[2]+"%)":"hsla("+e[0]+", "+e[1]+"%, "+e[2]+"%, "+e[3]+")"};xt.to.hwb=function(){var e=ur(arguments),t="";return e.length>=4&&e[3]!==1&&(t=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+t+")"};xt.to.keyword=function(e){return Ko[e.slice(0,3)]};function se(e,t,r){return Math.min(Math.max(t,e),r)}function wr(e){var t=Math.round(e).toString(16).toUpperCase();return t.length<2?"0"+t:t}var sp=Yo.exports;const or=Vo,Zo={};for(const e of Object.keys(or))Zo[or[e]]=e;const T={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};var tl=T;for(const e of Object.keys(T)){if(!("channels"in T[e]))throw new Error("missing channels property: "+e);if(!("labels"in T[e]))throw new Error("missing channel labels property: "+e);if(T[e].labels.length!==T[e].channels)throw new Error("channel and label counts mismatch: "+e);const{channels:t,labels:r}=T[e];delete T[e].channels,delete T[e].labels,Object.defineProperty(T[e],"channels",{value:t}),Object.defineProperty(T[e],"labels",{value:r})}T.rgb.hsl=function(e){const t=e[0]/255,r=e[1]/255,i=e[2]/255,n=Math.min(t,r,i),s=Math.max(t,r,i),a=s-n;let o,l;s===n?o=0:t===s?o=(r-i)/a:r===s?o=2+(i-t)/a:i===s&&(o=4+(t-r)/a),o=Math.min(o*60,360),o<0&&(o+=360);const h=(n+s)/2;return s===n?l=0:h<=.5?l=a/(s+n):l=a/(2-s-n),[o,l*100,h*100]};T.rgb.hsv=function(e){let t,r,i,n,s;const a=e[0]/255,o=e[1]/255,l=e[2]/255,h=Math.max(a,o,l),c=h-Math.min(a,o,l),u=function(f){return(h-f)/6/c+1/2};return c===0?(n=0,s=0):(s=c/h,t=u(a),r=u(o),i=u(l),a===h?n=i-r:o===h?n=1/3+t-i:l===h&&(n=2/3+r-t),n<0?n+=1:n>1&&(n-=1)),[n*360,s*100,h*100]};T.rgb.hwb=function(e){const t=e[0],r=e[1];let i=e[2];const n=T.rgb.hsl(e)[0],s=1/255*Math.min(t,Math.min(r,i));return i=1-1/255*Math.max(t,Math.max(r,i)),[n,s*100,i*100]};T.rgb.cmyk=function(e){const t=e[0]/255,r=e[1]/255,i=e[2]/255,n=Math.min(1-t,1-r,1-i),s=(1-t-n)/(1-n)||0,a=(1-r-n)/(1-n)||0,o=(1-i-n)/(1-n)||0;return[s*100,a*100,o*100,n*100]};function ap(e,t){return(e[0]-t[0])**2+(e[1]-t[1])**2+(e[2]-t[2])**2}T.rgb.keyword=function(e){const t=Zo[e];if(t)return t;let r=1/0,i;for(const n of Object.keys(or)){const s=or[n],a=ap(e,s);a<r&&(r=a,i=n)}return i};T.keyword.rgb=function(e){return or[e]};T.rgb.xyz=function(e){let t=e[0]/255,r=e[1]/255,i=e[2]/255;t=t>.04045?((t+.055)/1.055)**2.4:t/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,i=i>.04045?((i+.055)/1.055)**2.4:i/12.92;const n=t*.4124+r*.3576+i*.1805,s=t*.2126+r*.7152+i*.0722,a=t*.0193+r*.1192+i*.9505;return[n*100,s*100,a*100]};T.rgb.lab=function(e){const t=T.rgb.xyz(e);let r=t[0],i=t[1],n=t[2];r/=95.047,i/=100,n/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,i=i>.008856?i**(1/3):7.787*i+16/116,n=n>.008856?n**(1/3):7.787*n+16/116;const s=116*i-16,a=500*(r-i),o=200*(i-n);return[s,a,o]};T.hsl.rgb=function(e){const t=e[0]/360,r=e[1]/100,i=e[2]/100;let n,s,a;if(r===0)return a=i*255,[a,a,a];i<.5?n=i*(1+r):n=i+r-i*r;const o=2*i-n,l=[0,0,0];for(let h=0;h<3;h++)s=t+1/3*-(h-1),s<0&&s++,s>1&&s--,6*s<1?a=o+(n-o)*6*s:2*s<1?a=n:3*s<2?a=o+(n-o)*(2/3-s)*6:a=o,l[h]=a*255;return l};T.hsl.hsv=function(e){const t=e[0];let r=e[1]/100,i=e[2]/100,n=r;const s=Math.max(i,.01);i*=2,r*=i<=1?i:2-i,n*=s<=1?s:2-s;const a=(i+r)/2,o=i===0?2*n/(s+n):2*r/(i+r);return[t,o*100,a*100]};T.hsv.rgb=function(e){const t=e[0]/60,r=e[1]/100;let i=e[2]/100;const n=Math.floor(t)%6,s=t-Math.floor(t),a=255*i*(1-r),o=255*i*(1-r*s),l=255*i*(1-r*(1-s));switch(i*=255,n){case 0:return[i,l,a];case 1:return[o,i,a];case 2:return[a,i,l];case 3:return[a,o,i];case 4:return[l,a,i];case 5:return[i,a,o]}};T.hsv.hsl=function(e){const t=e[0],r=e[1]/100,i=e[2]/100,n=Math.max(i,.01);let s,a;a=(2-r)*i;const o=(2-r)*n;return s=r*n,s/=o<=1?o:2-o,s=s||0,a/=2,[t,s*100,a*100]};T.hwb.rgb=function(e){const t=e[0]/360;let r=e[1]/100,i=e[2]/100;const n=r+i;let s;n>1&&(r/=n,i/=n);const a=Math.floor(6*t),o=1-i;s=6*t-a,a&1&&(s=1-s);const l=r+s*(o-r);let h,c,u;switch(a){default:case 6:case 0:h=o,c=l,u=r;break;case 1:h=l,c=o,u=r;break;case 2:h=r,c=o,u=l;break;case 3:h=r,c=l,u=o;break;case 4:h=l,c=r,u=o;break;case 5:h=o,c=r,u=l;break}return[h*255,c*255,u*255]};T.cmyk.rgb=function(e){const t=e[0]/100,r=e[1]/100,i=e[2]/100,n=e[3]/100,s=1-Math.min(1,t*(1-n)+n),a=1-Math.min(1,r*(1-n)+n),o=1-Math.min(1,i*(1-n)+n);return[s*255,a*255,o*255]};T.xyz.rgb=function(e){const t=e[0]/100,r=e[1]/100,i=e[2]/100;let n,s,a;return n=t*3.2406+r*-1.5372+i*-.4986,s=t*-.9689+r*1.8758+i*.0415,a=t*.0557+r*-.204+i*1.057,n=n>.0031308?1.055*n**(1/2.4)-.055:n*12.92,s=s>.0031308?1.055*s**(1/2.4)-.055:s*12.92,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,n=Math.min(Math.max(0,n),1),s=Math.min(Math.max(0,s),1),a=Math.min(Math.max(0,a),1),[n*255,s*255,a*255]};T.xyz.lab=function(e){let t=e[0],r=e[1],i=e[2];t/=95.047,r/=100,i/=108.883,t=t>.008856?t**(1/3):7.787*t+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,i=i>.008856?i**(1/3):7.787*i+16/116;const n=116*r-16,s=500*(t-r),a=200*(r-i);return[n,s,a]};T.lab.xyz=function(e){const t=e[0],r=e[1],i=e[2];let n,s,a;s=(t+16)/116,n=r/500+s,a=s-i/200;const o=s**3,l=n**3,h=a**3;return s=o>.008856?o:(s-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,a=h>.008856?h:(a-16/116)/7.787,n*=95.047,s*=100,a*=108.883,[n,s,a]};T.lab.lch=function(e){const t=e[0],r=e[1],i=e[2];let n;n=Math.atan2(i,r)*360/2/Math.PI,n<0&&(n+=360);const a=Math.sqrt(r*r+i*i);return[t,a,n]};T.lch.lab=function(e){const t=e[0],r=e[1],n=e[2]/360*2*Math.PI,s=r*Math.cos(n),a=r*Math.sin(n);return[t,s,a]};T.rgb.ansi16=function(e,t=null){const[r,i,n]=e;let s=t===null?T.rgb.hsv(e)[2]:t;if(s=Math.round(s/50),s===0)return 30;let a=30+(Math.round(n/255)<<2|Math.round(i/255)<<1|Math.round(r/255));return s===2&&(a+=60),a};T.hsv.ansi16=function(e){return T.rgb.ansi16(T.hsv.rgb(e),e[2])};T.rgb.ansi256=function(e){const t=e[0],r=e[1],i=e[2];return t===r&&r===i?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(i/255*5)};T.ansi16.rgb=function(e){let t=e%10;if(t===0||t===7)return e>50&&(t+=3.5),t=t/10.5*255,[t,t,t];const r=(~~(e>50)+1)*.5,i=(t&1)*r*255,n=(t>>1&1)*r*255,s=(t>>2&1)*r*255;return[i,n,s]};T.ansi256.rgb=function(e){if(e>=232){const s=(e-232)*10+8;return[s,s,s]}e-=16;let t;const r=Math.floor(e/36)/5*255,i=Math.floor((t=e%36)/6)/5*255,n=t%6/5*255;return[r,i,n]};T.rgb.hex=function(e){const r=(((Math.round(e[0])&255)<<16)+((Math.round(e[1])&255)<<8)+(Math.round(e[2])&255)).toString(16).toUpperCase();return"000000".substring(r.length)+r};T.hex.rgb=function(e){const t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];let r=t[0];t[0].length===3&&(r=r.split("").map(o=>o+o).join(""));const i=parseInt(r,16),n=i>>16&255,s=i>>8&255,a=i&255;return[n,s,a]};T.rgb.hcg=function(e){const t=e[0]/255,r=e[1]/255,i=e[2]/255,n=Math.max(Math.max(t,r),i),s=Math.min(Math.min(t,r),i),a=n-s;let o,l;return a<1?o=s/(1-a):o=0,a<=0?l=0:n===t?l=(r-i)/a%6:n===r?l=2+(i-t)/a:l=4+(t-r)/a,l/=6,l%=1,[l*360,a*100,o*100]};T.hsl.hcg=function(e){const t=e[1]/100,r=e[2]/100,i=r<.5?2*t*r:2*t*(1-r);let n=0;return i<1&&(n=(r-.5*i)/(1-i)),[e[0],i*100,n*100]};T.hsv.hcg=function(e){const t=e[1]/100,r=e[2]/100,i=t*r;let n=0;return i<1&&(n=(r-i)/(1-i)),[e[0],i*100,n*100]};T.hcg.rgb=function(e){const t=e[0]/360,r=e[1]/100,i=e[2]/100;if(r===0)return[i*255,i*255,i*255];const n=[0,0,0],s=t%1*6,a=s%1,o=1-a;let l=0;switch(Math.floor(s)){case 0:n[0]=1,n[1]=a,n[2]=0;break;case 1:n[0]=o,n[1]=1,n[2]=0;break;case 2:n[0]=0,n[1]=1,n[2]=a;break;case 3:n[0]=0,n[1]=o,n[2]=1;break;case 4:n[0]=a,n[1]=0,n[2]=1;break;default:n[0]=1,n[1]=0,n[2]=o}return l=(1-r)*i,[(r*n[0]+l)*255,(r*n[1]+l)*255,(r*n[2]+l)*255]};T.hcg.hsv=function(e){const t=e[1]/100,r=e[2]/100,i=t+r*(1-t);let n=0;return i>0&&(n=t/i),[e[0],n*100,i*100]};T.hcg.hsl=function(e){const t=e[1]/100,i=e[2]/100*(1-t)+.5*t;let n=0;return i>0&&i<.5?n=t/(2*i):i>=.5&&i<1&&(n=t/(2*(1-i))),[e[0],n*100,i*100]};T.hcg.hwb=function(e){const t=e[1]/100,r=e[2]/100,i=t+r*(1-t);return[e[0],(i-t)*100,(1-i)*100]};T.hwb.hcg=function(e){const t=e[1]/100,i=1-e[2]/100,n=i-t;let s=0;return n<1&&(s=(i-n)/(1-n)),[e[0],n*100,s*100]};T.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]};T.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]};T.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]};T.gray.hsl=function(e){return[0,0,e[0]]};T.gray.hsv=T.gray.hsl;T.gray.hwb=function(e){return[0,100,e[0]]};T.gray.cmyk=function(e){return[0,0,0,e[0]]};T.gray.lab=function(e){return[e[0],0,0]};T.gray.hex=function(e){const t=Math.round(e[0]/100*255)&255,i=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(i.length)+i};T.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]};const Nr=tl;function op(){const e={},t=Object.keys(Nr);for(let r=t.length,i=0;i<r;i++)e[t[i]]={distance:-1,parent:null};return e}function lp(e){const t=op(),r=[e];for(t[e].distance=0;r.length;){const i=r.pop(),n=Object.keys(Nr[i]);for(let s=n.length,a=0;a<s;a++){const o=n[a],l=t[o];l.distance===-1&&(l.distance=t[i].distance+1,l.parent=i,r.unshift(o))}}return t}function cp(e,t){return function(r){return t(e(r))}}function up(e,t){const r=[t[e].parent,e];let i=Nr[t[e].parent][e],n=t[e].parent;for(;t[n].parent;)r.unshift(t[n].parent),i=cp(Nr[t[n].parent][n],i),n=t[n].parent;return i.conversion=r,i}var hp=function(e){const t=lp(e),r={},i=Object.keys(t);for(let n=i.length,s=0;s<n;s++){const a=i[s];t[a].parent!==null&&(r[a]=up(a,t))}return r};const qi=tl,fp=hp,Oe={},dp=Object.keys(qi);function pp(e){const t=function(...r){const i=r[0];return i==null?i:(i.length>1&&(r=i),e(r))};return"conversion"in e&&(t.conversion=e.conversion),t}function gp(e){const t=function(...r){const i=r[0];if(i==null)return i;i.length>1&&(r=i);const n=e(r);if(typeof n=="object")for(let s=n.length,a=0;a<s;a++)n[a]=Math.round(n[a]);return n};return"conversion"in e&&(t.conversion=e.conversion),t}dp.forEach(e=>{Oe[e]={},Object.defineProperty(Oe[e],"channels",{value:qi[e].channels}),Object.defineProperty(Oe[e],"labels",{value:qi[e].labels});const t=fp(e);Object.keys(t).forEach(i=>{const n=t[i];Oe[e][i]=gp(n),Oe[e][i].raw=pp(n)})});var mp=Oe;const Ie=sp,bt=mp,el=["keyword","gray","hex"],Hi={};for(const e of Object.keys(bt))Hi[[...bt[e].labels].sort().join("")]=e;const Dr={};function lt(e,t){if(!(this instanceof lt))return new lt(e,t);if(t&&t in el&&(t=null),t&&!(t in bt))throw new Error("Unknown model: "+t);let r,i;if(e==null)this.model="rgb",this.color=[0,0,0],this.valpha=1;else if(e instanceof lt)this.model=e.model,this.color=[...e.color],this.valpha=e.valpha;else if(typeof e=="string"){const n=Ie.get(e);if(n===null)throw new Error("Unable to parse color from string: "+e);this.model=n.model,i=bt[this.model].channels,this.color=n.value.slice(0,i),this.valpha=typeof n.value[i]=="number"?n.value[i]:1}else if(e.length>0){this.model=t||"rgb",i=bt[this.model].channels;const n=Array.prototype.slice.call(e,0,i);this.color=Gi(n,i),this.valpha=typeof e[i]=="number"?e[i]:1}else if(typeof e=="number")this.model="rgb",this.color=[e>>16&255,e>>8&255,e&255],this.valpha=1;else{this.valpha=1;const n=Object.keys(e);"alpha"in e&&(n.splice(n.indexOf("alpha"),1),this.valpha=typeof e.alpha=="number"?e.alpha:0);const s=n.sort().join("");if(!(s in Hi))throw new Error("Unable to parse color from object: "+JSON.stringify(e));this.model=Hi[s];const{labels:a}=bt[this.model],o=[];for(r=0;r<a.length;r++)o.push(e[a[r]]);this.color=Gi(o)}if(Dr[this.model])for(i=bt[this.model].channels,r=0;r<i;r++){const n=Dr[this.model][r];n&&(this.color[r]=n(this.color[r]))}this.valpha=Math.max(0,Math.min(1,this.valpha)),Object.freeze&&Object.freeze(this)}lt.prototype={toString(){return this.string()},toJSON(){return this[this.model]()},string(e){let t=this.model in Ie.to?this:this.rgb();t=t.round(typeof e=="number"?e:1);const r=t.valpha===1?t.color:[...t.color,this.valpha];return Ie.to[t.model](r)},percentString(e){const t=this.rgb().round(typeof e=="number"?e:1),r=t.valpha===1?t.color:[...t.color,this.valpha];return Ie.to.rgb.percent(r)},array(){return this.valpha===1?[...this.color]:[...this.color,this.valpha]},object(){const e={},{channels:t}=bt[this.model],{labels:r}=bt[this.model];for(let i=0;i<t;i++)e[r[i]]=this.color[i];return this.valpha!==1&&(e.alpha=this.valpha),e},unitArray(){const e=this.rgb().color;return e[0]/=255,e[1]/=255,e[2]/=255,this.valpha!==1&&e.push(this.valpha),e},unitObject(){const e=this.rgb().object();return e.r/=255,e.g/=255,e.b/=255,this.valpha!==1&&(e.alpha=this.valpha),e},round(e){return e=Math.max(e||0,0),new lt([...this.color.map(yp(e)),this.valpha],this.model)},alpha(e){return e!==void 0?new lt([...this.color,Math.max(0,Math.min(1,e))],this.model):this.valpha},red:tt("rgb",0,st(255)),green:tt("rgb",1,st(255)),blue:tt("rgb",2,st(255)),hue:tt(["hsl","hsv","hsl","hwb","hcg"],0,e=>(e%360+360)%360),saturationl:tt("hsl",1,st(100)),lightness:tt("hsl",2,st(100)),saturationv:tt("hsv",1,st(100)),value:tt("hsv",2,st(100)),chroma:tt("hcg",1,st(100)),gray:tt("hcg",2,st(100)),white:tt("hwb",1,st(100)),wblack:tt("hwb",2,st(100)),cyan:tt("cmyk",0,st(100)),magenta:tt("cmyk",1,st(100)),yellow:tt("cmyk",2,st(100)),black:tt("cmyk",3,st(100)),x:tt("xyz",0,st(95.047)),y:tt("xyz",1,st(100)),z:tt("xyz",2,st(108.833)),l:tt("lab",0,st(100)),a:tt("lab",1),b:tt("lab",2),keyword(e){return e!==void 0?new lt(e):bt[this.model].keyword(this.color)},hex(e){return e!==void 0?new lt(e):Ie.to.hex(this.rgb().round().color)},hexa(e){if(e!==void 0)return new lt(e);const t=this.rgb().round().color;let r=Math.round(this.valpha*255).toString(16).toUpperCase();return r.length===1&&(r="0"+r),Ie.to.hex(t)+r},rgbNumber(){const e=this.rgb().color;return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255},luminosity(){const e=this.rgb().color,t=[];for(const[r,i]of e.entries()){const n=i/255;t[r]=n<=.04045?n/12.92:((n+.055)/1.055)**2.4}return .2126*t[0]+.7152*t[1]+.0722*t[2]},contrast(e){const t=this.luminosity(),r=e.luminosity();return t>r?(t+.05)/(r+.05):(r+.05)/(t+.05)},level(e){const t=this.contrast(e);return t>=7?"AAA":t>=4.5?"AA":""},isDark(){const e=this.rgb().color;return(e[0]*2126+e[1]*7152+e[2]*722)/1e4<128},isLight(){return!this.isDark()},negate(){const e=this.rgb();for(let t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten(e){const t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken(e){const t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate(e){const t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate(e){const t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten(e){const t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken(e){const t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale(){const e=this.rgb().color,t=e[0]*.3+e[1]*.59+e[2]*.11;return lt.rgb(t,t,t)},fade(e){return this.alpha(this.valpha-this.valpha*e)},opaquer(e){return this.alpha(this.valpha+this.valpha*e)},rotate(e){const t=this.hsl();let r=t.color[0];return r=(r+e)%360,r=r<0?360+r:r,t.color[0]=r,t},mix(e,t){if(!e||!e.rgb)throw new Error('Argument to "mix" was not a Color instance, but rather an instance of '+typeof e);const r=e.rgb(),i=this.rgb(),n=t===void 0?.5:t,s=2*n-1,a=r.alpha()-i.alpha(),o=((s*a===-1?s:(s+a)/(1+s*a))+1)/2,l=1-o;return lt.rgb(o*r.red()+l*i.red(),o*r.green()+l*i.green(),o*r.blue()+l*i.blue(),r.alpha()*n+i.alpha()*(1-n))}};for(const e of Object.keys(bt)){if(el.includes(e))continue;const{channels:t}=bt[e];lt.prototype[e]=function(...r){return this.model===e?new lt(this):r.length>0?new lt(r,e):new lt([...bp(bt[this.model][e].raw(this.color)),this.valpha],e)},lt[e]=function(...r){let i=r[0];return typeof i=="number"&&(i=Gi(r,t)),new lt(i,e)}}function vp(e,t){return Number(e.toFixed(t))}function yp(e){return function(t){return vp(t,e)}}function tt(e,t,r){e=Array.isArray(e)?e:[e];for(const i of e)(Dr[i]||(Dr[i]=[]))[t]=r;return e=e[0],function(i){let n;return i!==void 0?(r&&(i=r(i)),n=this[e](),n.color[t]=i,n):(n=this[e]().color[t],r&&(n=r(n)),n)}}function st(e){return function(t){return Math.max(0,Math.min(e,t))}}function bp(e){return Array.isArray(e)?e:[e]}function Gi(e,t){for(let r=0;r<t;r++)typeof e[r]!="number"&&(e[r]=0);return e}var wp=lt;const rl=on(wp);class G{}v(G,"Text",1),v(G,"ProcessingInstruction",2),v(G,"SGMLDeclaration",4),v(G,"Doctype",8),v(G,"Comment",16),v(G,"OpenTagStart",32),v(G,"Attribute",64),v(G,"OpenTag",128),v(G,"CloseTag",256),v(G,"Cdata",512);class Kr{constructor(t,r=0){v(this,"data");v(this,"cache",{});v(this,"ptr");this.data=t,this.ptr=r}}class xp{constructor(t,r){v(this,"line");v(this,"character");this.line=t,this.character=r}}var as;(function(e){e[e.Normal=0]="Normal",e[e.JSX=1]="JSX"})(as||(as={}));class il extends Kr{constructor(r,i=0){super(r,i);v(this,"type");v(this,"name");v(this,"value");this.type=r[i],i+=1;const n=At(r,i);i+=4,this.name=new Me(r,i),i+=n,this.value=new Me(r,i)}toJSON(){const{name:r,value:i,type:n}=this;return{name:r,value:i,type:n}}toString(){const{name:r,value:i}=this;return`${r}="${i}"`}}class Cp extends Kr{constructor(r,i=0){super(r,i);v(this,"target");v(this,"content");i+=16;const n=At(r,i);i+=4,this.target=new Me(r,i),i+=n,this.content=new Me(r,i)}get start(){return this.cache.start||(this.cache.start=ie(this.data,this.ptr))}get end(){return this.cache.end||(this.cache.end=ie(this.data,this.ptr+8))}toJSON(){const{start:r,end:i,target:n,content:s}=this;return{start:r,end:i,target:n,content:s}}toString(){const{target:r,content:i}=this;return`<? ${r} ${i} ?>`}}class Me extends Kr{get start(){return this.cache.start||(this.cache.start=ie(this.data,this.ptr))}get end(){return this.cache.end||(this.cache.end=ie(this.data,this.ptr+8))}get value(){if(this.cache.value)return this.cache.value;const t=At(this.data,this.ptr+16);return this.cache.value=nl(this.data,this.ptr+20,t)}toJSON(){const{start:t,end:r,value:i}=this;return{start:t,end:r,value:i}}toString(){return this.value}}class Sp extends Kr{get openStart(){return this.cache.openStart||(this.cache.openStart=ie(this.data,this.ptr+8))}get openEnd(){return this.cache.openEnd||(this.cache.openEnd=ie(this.data,this.ptr+16))}get closeStart(){return this.cache.closeStart||(this.cache.closeStart=ie(this.data,this.ptr+24))}get closeEnd(){return this.cache.closeEnd||(this.cache.closeEnd=ie(this.data,this.ptr+32))}get selfClosing(){return!!this.data[this.ptr+40]}get name(){if(this.cache.name)return this.cache.name;const t=At(this.data,this.ptr+41);return this.cache.name=nl(this.data,this.ptr+45,t)}get attributes(){if(this.cache.attributes)return this.cache.attributes;let t=At(this.data,this.ptr);const r=At(this.data,t);t+=4;const i=[];for(let n=0;n<r;n++){const s=At(this.data,t);t+=4,i[n]=new il(this.data,t),t+=s}return this.cache.attributes=i}get textNodes(){if(this.cache.textNodes)return this.cache.textNodes;let t=At(this.data,this.ptr+4);const r=At(this.data,t),i=[];t+=4;for(let n=0;n<r;n++){const s=At(this.data,t);t+=4,i[n]=new Me(this.data,t),t+=s}return this.cache.textNodes=i}toJSON(){const{openStart:t,openEnd:r,closeStart:i,closeEnd:n,name:s,attributes:a,textNodes:o,selfClosing:l}=this;return{openStart:t,openEnd:r,closeStart:i,closeEnd:n,name:s,attributes:a,textNodes:o,selfClosing:l}}get value(){return this.name}}class lr{constructor(t=0){v(this,"events");v(this,"wasmSaxParser");v(this,"eventHandler");v(this,"writeBuffer");v(this,"eventTrap",(t,r,i)=>{if(!this.wasmSaxParser)return;const n=new Uint8Array(this.wasmSaxParser.memory.buffer,r,i),s=new Uint8Array(n);let a;switch(t){case G.Attribute:a=new il(s);break;case G.ProcessingInstruction:a=new Cp(s);break;case G.OpenTag:case G.CloseTag:case G.OpenTagStart:a=new Sp(s);break;case G.Text:case G.Cdata:case G.Comment:case G.Doctype:case G.SGMLDeclaration:a=new Me(s);break;default:throw new Error("No reader for this event type")}this.eventHandler&&this.eventHandler(t,a)});const r=this;Object.defineProperties(this,{events:{get:()=>~~t,set:i=>{t=~~i,r.wasmSaxParser&&r.wasmSaxParser.parser(t)},configurable:!1,enumerable:!0}})}async*parse(t){let r=[];for(this.eventHandler=function(i,n){r.push([i,n])};;){const i=await t.read();if(i.done)return this.end();if(this.write(i.value),r.length){for(const n of r)yield n;r.length=0}}}write(t){if(!this.wasmSaxParser)return;const{write:r,memory:i}=this.wasmSaxParser;(!this.writeBuffer||this.writeBuffer.buffer!==i.buffer)&&(this.writeBuffer=new Uint8Array(i.buffer)),this.writeBuffer.set(t,0),r(0,t.byteLength)}end(){var t;this.writeBuffer=void 0,(t=this.wasmSaxParser)==null||t.end()}async prepareWasm(t){let r;const i={memory:new WebAssembly.Memory({initial:10,shared:!0,maximum:150}),table:new WebAssembly.Table({initial:1,element:"anyfunc"}),event_listener:this.eventTrap};if(t instanceof Uint8Array?r=await WebAssembly.instantiate(t,{env:i}):r=await WebAssembly.instantiateStreaming(t,{env:i}),r&&typeof this.events=="number"){const{parser:n}=this.wasmSaxParser=r.instance.exports;return n(this.events),!0}throw new Error("Failed to instantiate the parser.")}}v(lr,"textDecoder");const nl=(e,t,r)=>globalThis.hasOwnProperty("Buffer")?Buffer.from(e.buffer,e.byteOffset+t,r).toString():(lr.textDecoder||(lr.textDecoder=new TextDecoder)).decode(e.subarray(t,t+r)),At=(e,t)=>e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t],ie=(e,t=0)=>{const r=At(e,t),i=At(e,t+4);return new xp(r,i)},Ap=/(?<val>\d+(?:\.\d+)?)\s*(?<unit>[[a-z%]+)?/;async function $p(e){if(!Tt)throw new Error("SAX parser WebAssembly has not been initialized");const t=new lr(G.Text);await t.prepareWasm(Tt);const r=[];return t.eventHandler=(i,n)=>{r.push(n.value)},t.write(kt.encode(e)),t.end(),r.join("").trim()}function mi(e,t,r){if(!e.spatial)return null;const i=t-e.spatial.y-e.spatial.height,n=t-e.spatial.y;return{Subtype:"/Square",Rect:[e.spatial.x*r,i*r,(e.spatial.x+e.spatial.width)*r,n*r]}}function kp(e){return rl(e).rgb().array()}function _p(e,t,r){const i=Ap.exec(e);if(!i||!i.groups)return null;const n=parseFloat(i.groups.val),s=i.groups.unit;if(!s)return n*t;switch(s){case"%":return null;case"px":return t*n;default:return console.warn(`Unsupported CSS length unit: ${s}`),null}}function Op(e,t){const r={};if((e.stroke||e.strokeDasharray||e.strokeWidth)&&(r.BS={Type:"/Border",W:e.strokeWidth??1,S:e.strokeDasharray?"/D":"/S"},e.strokeDasharray&&(r.BS.D=e.strokeDasharray)),e.fill){const i=kp(e.fill);i&&(r.IC=i.map(n=>n/255))}if(e.strokeWidth){const i=_p(e.strokeWidth,t);r.BS={Type:"/Border",W:i}}return r}function os(e,t,r){var n,s;const i=e.style?Op(e.style,t):{};switch(e.type){case"BoxSelector":return{Subtype:"/Square",...mi(e,r,t),...i};case"PointSelector":{const a=e;if(!a.x||!a.y)throw"Only PointSelectors with both x and y coordinates are supported!";return{Subtype:"/Circle",BS:{Type:"/Border",W:2,S:"/S"},IC:[1,1,1],Rect:[a.x*t-.5,a.y*t-.5,a.x*t+1,a.y*t+1]}}case"SvgSelector":{const a=e;switch(a.svgShape){case"rect":return{Subtype:"/Square",...mi(a,r,t),...i};case"circle":case"ellipse":return{Subtype:"/Circle",Rect:mi(a,r,t),...i};case"polyline":case"polygon":return{Subtype:a.svgShape==="polyline"?"/PolyLine":"/Polygon",Vertices:((n=a.points)==null?void 0:n.flatMap(([o,l])=>[o*t,(r-l)*t]))??[],...i};case"path":return{Subtype:"/Ink",InkList:((s=a.points)==null?void 0:s.flatMap(([o,l])=>[o*t,(r-l)*t]))??[],...i};default:throw new Error("not implemented yet")}}default:throw`${e.type} selector is currently not supported`}}async function Ip(e,t,r){const i={Type:"/Annot",NM:`(${e.id})`,Contents:`(${await $p(e.markup)})`,F:4,C:[1,0,0],CA:1,Border:[0,0,5]};return e.author&&(i.T=`(${e.author})`),e.lastModified&&(i.M=e.lastModified),e.target.selector?[{...i,...os(e.target.selector,t,r)}]:e.target.selectors&&e.target.selectors.length>0?e.target.selectors.map(n=>({...i,...os(n,t,r)})):[]}const jp={Helvetica:["Helvetica","Helvetica-Bold","Helvetica-Oblique","Helvetica-BoldOblique"],"Times-Roman":["Times-Roman","Times-Bold","Times-Italic","Times-BoldItalic"],Courier:["Courier","Courier-Bold","Courier-Oblique","Courier-BoldOblique"]};function sl(e,t,r){const i=t?r?"BoldItalic":"Bold":r?"Italic":"Regular";return`annFont${e.replace(/[^a-zA-Z0-9]/g,"")}${i}`}function ls(e){return jp[e].map((t,r)=>({resourceName:sl(e,r%2===1,r>=2),baseFont:t}))}async function Pp(e){var a,o;if(!Tt)throw new Error("SAX parser WebAssembly has not been initialized");const t=new lr(G.Text|G.OpenTag|G.CloseTag);await t.prepareWasm(Tt);const i=[{name:"",style:{bold:!1,italic:!1,underline:!1}}],n=[],s=()=>{n.length>0&&!n[n.length-1].lineBreak&&n.push({text:"",...i[i.length-1].style,lineBreak:!0})};for(t.eventHandler=(l,h)=>{if(l===G.Text){const d=h.value.replace(/\s+/g," ");if(d){const p=i[i.length-1].style;n.push({text:d,...p})}return}const c=h,u=c.name.toLowerCase();if(l===G.OpenTag){if(u==="br"){s();return}["p","div","li"].includes(u)&&s(),c.selfClosing||i.push({name:u,style:Tp(c,i[i.length-1].style)});return}let f=-1;for(let d=i.length-1;d>0;d--)if(i[d].name===u){f=d;break}f>0&&i.splice(f),["p","div","li"].includes(u)&&s()},t.write(kt.encode(e)),t.end();(a=n[0])!=null&&a.lineBreak;)n.shift();for(;(o=n[n.length-1])!=null&&o.lineBreak;)n.pop();return n.length>0&&(n[0].text=n[0].text.trimStart(),n[n.length-1].text=n[n.length-1].text.trimEnd()),n.filter(l=>l.lineBreak||l.text.length>0)}function Tp(e,t){var s;const r={...t},i=e.name.toLowerCase();i==="b"||i==="strong"?r.bold=!0:i==="i"||i==="em"?r.italic=!0:i==="u"&&(r.underline=!0);const n=(s=e.attributes.find(a=>a.name.value.toLowerCase()==="style"))==null?void 0:s.value.value;if(!n)return r;for(const a of n.split(";")){const[o,...l]=a.split(":"),h=o==null?void 0:o.trim().toLowerCase(),c=l.join(":").trim();if(h==="font-weight")r.bold=c==="bold"||Number.parseInt(c,10)>=600;else if(h==="font-style")r.italic=c==="italic"||c==="oblique";else if(h==="text-decoration")r.underline=c.split(/\s+/).includes("underline");else if(h==="color")try{const[u,f,d]=rl(c).rgb().array();r.color=[u/255,f/255,d/255]}catch{}}return r}function Fp(e){const t={"€":128,"‚":130,ƒ:131,"„":132,"…":133,"†":134,"‡":135,"ˆ":136,"‰":137,Š:138,"‹":139,Œ:140,Ž:142,"‘":145,"’":146,"“":147,"”":148,"•":149,"–":150,"—":151,"˜":152,"™":153,š:154,"›":155,œ:156,ž:158,Ÿ:159};return`<${Array.from(e,i=>{const n=i.codePointAt(0)??63,s=n>=32&&n<=126||n>=160&&n<=255;return t[i]??(s?n:63)}).map(i=>i.toString(16).padStart(2,"0")).join("")}>`}function cs(e,t,r){const i=" !.,:;|ijlItfr'",n="MW@%&";return Array.from(e).reduce((s,a)=>t==="Courier"?s+.6:a===" "||i.includes(a)?s+.28:n.includes(a)?s+.82:/[A-Z0-9]/.test(a)?s+.62:s+.52,0)*r}function Ep(e){return e.target.selector?[e.target.selector]:e.target.selectors??[]}async function Rp(e,t,r,i,n){const s=await Pp(e.markup),a=[],o=10,l=12,h=2;for(const c of Ep(e)){const u=c.spatial;if(!u||u.width===void 0||u.height===void 0||u.width<=0||u.height<=0)continue;const f=u.unit==="percent"?i/100:1,d=u.unit==="percent"?r/100:1,p=u.x*f*t,g=u.y*d*t,m=u.width*f*t,y=u.height*d*t,b=Math.max(0,m-h*2),w=[[]];let _=0;const C=()=>{w[w.length-1].length>0&&(w.push([]),_=0)};for(const x of s){if(x.lineBreak){C();continue}const S=x.text.match(/\s+|[^\s]+/g)??[];for(const I of S){const O=/^\s+$/.test(I),E=cs(I,n,o);if(!(O&&w[w.length-1].length===0)){if(!O&&_+E>b&&_>0&&C(),O&&_+E>b){C();continue}w[w.length-1].push({...x,text:I}),_+=E}}}const $=r*t-g-h-o,A=r*t-g-y+h;for(const[x,S]of w.entries()){const I=$-x*l;if(I<A)break;if(S.length===0)continue;const O=p+h;a.push(`BT 1 0 0 1 ${O} ${I} Tm`);let E=O;const N=[];for(const M of S){const U=sl(n,M.bold,M.italic);a.push(`/${U} ${o} Tf`);const B=M.color??[0,0,0];a.push(`${B.join(" ")} rg`),a.push(`${Fp(M.text)} Tj`);const D=cs(M.text,n,o);M.underline&&N.push({x1:E,x2:E+D,color:M.color}),E+=D}a.push("ET");for(const M of N){const U=M.color??[0,0,0];a.push(`q ${U.join(" ")} RG 0.5 w ${M.x1} ${I-1.5} m ${M.x2} ${I-1.5} l S Q`)}}}return a}const Mp=`pdiiif v${fn}`,vi=2,us=new Uint8Array([0,1,0,0,0,10,0,128,0,3,0,32,79,83,47,50,86,222,200,148,0,0,1,40,0,0,0,96,99,109,97,112,0,10,0,52,0,0,1,144,0,0,0,30,103,108,121,102,21,34,65,36,0,0,1,184,0,0,0,24,104,101,97,100,11,120,241,101,0,0,0,172,0,0,0,54,104,104,101,97,12,2,4,2,0,0,0,228,0,0,0,36,104,109,116,120,4,0,0,0,0,0,1,136,0,0,0,8,108,111,99,97,0,12,0,0,0,0,1,176,0,0,0,6,109,97,120,112,0,4,0,5,0,0,1,8,0,0,0,32,110,97,109,101,242,235,22,218,0,0,1,208,0,0,0,75,112,111,115,116,0,1,0,1,0,0,2,28,0,0,0,32,0,1,0,0,0,1,0,0,176,148,113,16,95,15,60,245,4,7,8,0,0,0,0,0,207,154,252,110,0,0,0,0,212,195,167,242,0,0,0,0,4,0,8,0,0,0,0,16,0,2,0,0,0,0,0,0,0,1,0,0,8,0,255,255,0,0,4,0,0,0,0,0,4,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,1,0,0,0,2,0,4,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,1,144,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,71,79,79,71,0,64,0,0,0,0,0,1,255,255,0,0,0,1,0,1,128,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,4,0,0,0,0,0,0,2,0,1,0,0,0,0,0,20,0,3,0,0,0,0,0,20,0,6,0,10,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,1,0,0,0,0,4,0,8,0,0,3,0,0,49,33,17,33,4,0,252,0,8,0,0,0,0,3,0,42,0,0,0,3,0,0,0,5,0,22,0,0,0,1,0,0,0,0,0,5,0,11,0,22,0,3,0,1,4,9,0,5,0,22,0,0,0,86,0,101,0,114,0,115,0,105,0,111,0,110,0,32,0,49,0,46,0,48,86,101,114,115,105,111,110,32,49,46,48,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);class Np{constructor({writer:t,metadata:r,canvasInfos:i,langPref:n,pageLabels:s,outline:a=[],readingDirection:o="left-to-right",hasText:l=!1,annotationsAsText:h=!1,annotationFont:c="Helvetica",initialCanvas:u,manifestJson:f,zipPolyglot:d=!1,zipBaseDir:p}){v(this,"_offset",0);v(this,"_objects",[]);v(this,"_nextObjNo",1);v(this,"_objRefs",{});v(this,"_offsets",[]);v(this,"_writer");v(this,"_pagesStarted",!1);v(this,"_canvasInfos",[]);v(this,"_firstPageObjectNum");v(this,"_pageLabels");v(this,"_numCoverPages",0);v(this,"_outline",[]);v(this,"_hasText",!1);v(this,"_strucTree",[]);v(this,"_pageMCIds",new Map);v(this,"_nextStructParentId",0);v(this,"_pageParentIds",new Map);v(this,"_langPref");v(this,"_initialCanvas");v(this,"_polyglot");v(this,"_manifestJson");v(this,"_zipCatalog");v(this,"_zipBaseDir");v(this,"_readingDirection");v(this,"_annotationsAsText");v(this,"_annotationFont");v(this,"_deferredReferences",new Map);this._writer=t,this._canvasInfos=i,this._pageLabels=s,this._outline=a,this._hasText=l,this._annotationsAsText=h,this._annotationFont=c,this._readingDirection=o,this._langPref=n,this._initialCanvas=u,this._polyglot=d,this._zipBaseDir=p,this._manifestJson=f;const g={...Object.entries(r).filter((m,y)=>y!==void 0).reduce((m,[y,b])=>(m[y]=`(${b})`,m),{}),Producer:`(${Mp})`};this._addObject(g,"Info")}async setup(){const t={Type:"/Catalog"};this._addObject(t,"Catalog");const r=this._addObject({Type:"/Pages",Count:this._canvasInfos.length},"Pages");if(t.Pages=L(r),this._hasText&&(t.MarkInfo={Type:"/MarkInfo",Marked:!0}),this._outline.length>0){t.PageMode="/UseOutlines";const i={Type:"/Outlines",Count:0},n=this._addObject(i);t.Outlines=L(n);let s;for(const[a,o]of this._outline.entries()){const[l,h]=this._addOutline(o,n,s);i.Count+=1+h,a===0?i.First=L(l):a===this._outline.length-1&&(i.Last=L(l)),s=l}}else t.PageMode="/UseThumbs";if(t.ViewerPreferences={Direction:this._readingDirection==="right-to-left"?"/R2L":"/L2R"},this._hasText&&await this._setupHiddenTextFont(),this._annotationsAsText)for(const{resourceName:i,baseFont:n}of ls(this._annotationFont))this._addObject({Type:"/Font",Subtype:"/Type1",BaseFont:`/${n}`,Encoding:"/WinAnsiEncoding"},i)}async _setupHiddenTextFont(){const t=this._addObject({Type:"/Font",Subtype:"/Type0",BaseFont:"/GlyphLessFont",Encoding:"/Identity-H"},"Type0Font"),r=this._addObject({type:"/Font",Subtype:"/CIDFontType2",BaseFont:"/GlyphLessFont",DW:1e3/vi,CIDSystemInfo:{Ordering:"(Identity)",Registry:"(Adobe)",Supplement:0}});t.data.DescendantFonts=[L(r)];const i=new Uint8Array(128*1024);for(let u=0;u<i.length;u++)i[u]=u%2?1:0;const n=await yr(i),s=this._addObject(n.dict,void 0,n.stream);r.data.CIDToGIDMap=L(s);const a=_d`
|
|
19
|
+
/CIDInit /ProcSet findresource begin
|
|
20
|
+
12 dict begin
|
|
21
|
+
begincmap
|
|
22
|
+
/CIDSystemInfo
|
|
23
|
+
<<
|
|
24
|
+
/Registry (Adobe)
|
|
25
|
+
/Ordering (UCS)
|
|
26
|
+
/Supplement 0
|
|
27
|
+
>> def
|
|
28
|
+
/CMapName /Identity-H def
|
|
29
|
+
/CMapType 2 def
|
|
30
|
+
1 begincodespacerange
|
|
31
|
+
<0000> <FFFF>
|
|
32
|
+
endcodespacerange
|
|
33
|
+
1 beginbfrange
|
|
34
|
+
<0000> <FFFF> <0000>
|
|
35
|
+
endbfrange
|
|
36
|
+
endcmap
|
|
37
|
+
CMapName currentdict /CMap defineresource pop
|
|
38
|
+
end
|
|
39
|
+
end`,o=this._addObject({Length:a.length},void 0,a);t.data.ToUnicode=L(o);const l=this._addObject({Type:"/FontDescriptor",FontName:"/GlyphLessFont",FontBBox:[0,0,1e3/vi,1e3],Ascent:1e3,CapHeight:1e3,Descent:-1,Flags:5,ItalicAngle:0,StemV:80});r.data.FontDescriptor=L(l);const h=await yr(us),c=this._addObject({Length1:us.length,...h.dict},void 0,h.stream);l.data.FontFile2=L(c)}_registerEmbeddedFilesInCatalog(){const t=this._objects[this._objRefs.Catalog.refObj].data,r=["(manifest.json)",L(this._firstPageObjectNum-(this._polyglot?3:2))];for(const[i,n]of this._canvasInfos.entries()){if(!n.ocr)continue;let a=this.getCanvasObjectNumber(i)+this.getObjectsPerCanvas(i)-2;this._polyglot&&(a-=1),r.push(`(${n.ocr.id})`),r.push(L(a))}if(!t.Names)t.Names={EmbeddedFiles:{Names:r}};else{const n=t.Names.EmbeddedFiles;n.Names=n.Names.concat(r)}}_makeDeferredReference(t){if(!this._deferredReferences.has(t)){const r=L(-1);this._deferredReferences.set(t,r)}return this._deferredReferences.get(t)}_addOutline(t,r,i){var o;let n;if(typeof t.startCanvas=="string"){const l=this._canvasInfos.findIndex(h=>h.canvas.id===t.startCanvas);if(l<0)throw Error(`Could not find canvas with id ${t.startCanvas} in manifest!`);n=[l,"/Fit"]}else{const l=t.startCanvas.id,h=72/t.startCanvas.ppi,c=t.startCanvas.position,{width:u,height:f}=t.startCanvas.dimensions,d=this._canvasInfos.findIndex(p=>p.canvas.id===l);if(d<0)throw Error(`Could not find canvas with id ${l} in manifest!`);n=[d,"/FitR",h*c.x,h*c.y,h*(u-(c.x+c.width)),h*(f-(c.y+c.height))]}const s={Title:`( ${t.label} )`,Parent:L(r),Dest:n},a=this._addObject(s);if(i&&(s.Prev=L(i),i.data.Next=L(a)),(o=t.children)!=null&&o.length){let l;s.Count=0;for(const[h,c]of t.children.entries()){const[u,f]=this._addOutline(c,a,l);h===0?s.First=L(u):h===t.children.length-1&&(s.Last=L(u)),s.Count=s.Count+1+f,l=u}}return[a,s.Count??0]}_addObject(t,r,i){const n=a=>typeof a=="object"&&a!==null;if(i){if(!n(t))throw new Error("PDF Objects with a stream must have a dictionary as its value");t.Length||(t.Length=i.length)}const s={num:this._nextObjNo,data:t,stream:i};return this._nextObjNo++,this._objects[s.num]=s,r&&(this._objRefs[r]=L(s)),s}async _transplantObject(t,r,i={}){const n=async a=>{if(a instanceof Fe){const o=await t.resolveRef(a);if(o===void 0)throw`Could not resolve reference to object '${a.refObj}'`;if(i[o.num])return i[o.num];const l=o.data,h=this._addObject(l,void 0,o.stream),c=new Fe(h.num);return i[o.num]=c,h.data=await n(l),l.Type==="/Page"&&(h.data.Parent=this._objRefs.Pages),c}else{if(typeof a=="string"&&a[0]!="/")return`(${a})`;if(Array.isArray(a)){const o=[];for(const l of a)o.push(await n(l));return o}else if(typeof a=="object"&&a!==null){const o={};for(const[l,h]of Object.entries(a))l==="StructParent"||l==="StructParents"||(o[l]=await n(h));return o}}return a},s=new Fe(r.num);return await n(s)}async insertCoverPages(t){if(this._pagesStarted)throw"Cover pages must be inserted before writing the first regular page";const r=new Yd(new Uint8Array(t)),i=await hn.parse(r),n=this._objects[this._objRefs.Pages.refObj].data;n.Kids=[];for await(const s of i.pages()){const a=s.data;delete a.StructParents,delete a.Parent;const o=await this._transplantObject(i,s);n.Kids.push(o),n.Count+=1,this._numCoverPages+=1}}async _embedResource(t,r,i,n){const s={Type:"/Filespec",F:`(${t})`,UF:Ui(t),Desc:`(${r})`,EF:{F:L(this._nextObjNo+(this._polyglot?2:1))}},a=await yr(n),o={Type:"/EmbeddedFile",Subtype:`(${i})`,...a.dict};if(this._addObject(s),this._polyglot){let l;typeof n=="string"?l=kt.encode(n):l=n;const h=this._getSerializedSize({num:this._nextObjNo+2,data:{...o,...a.dict},stream:a.stream},!0);this._insertZipHeaderDummyObject({filename:t,data:l,deflatedData:a.dict.Filter?a.stream:void 0,bytesUntilActualData:h+2})}this._addObject(o,void 0,a.stream)}async _embedManifest(t){let r="application/ld+json";if(Array.isArray(t["@context"])){const i=t["@context"].find(n=>n.startsWith("http://iiif.io/api/presentation"));i&&(r+=`;profile="${i}"`)}else t["@context"]&&(r+=`;profile="${t["@context"]}"`);await this._embedResource("manifest.json","IIIF Manifest this PDF is based on",r,JSON.stringify(t))}async finalizePdfHeader(){const t=this._objects[this._objRefs.Catalog.refObj].data;this._pageLabels&&(t.PageLabels=L(this._addObject({Nums:this._pageLabels.map((n,s)=>n?[s+this._numCoverPages,{P:`( ${n} )`}]:void 0).filter(n=>n!==void 0).flat()})));const i=this._objects[this._objRefs.Pages.refObj].data;i.Kids||(i.Kids=[]),this._firstPageObjectNum=this._nextObjNo,this._manifestJson&&(this._firstPageObjectNum+=2,this._polyglot&&this._firstPageObjectNum++);for(const[n]of this._canvasInfos.entries())i.Kids.push(L(this.getCanvasObjectNumber(n)));if(this._objects.filter(n=>{var s;return((s=n.data)==null?void 0:s.Dest)!==void 0}).forEach(n=>{const s=n.data.Dest;typeof s[0]=="number"&&(s[0]=L(this.getCanvasObjectNumber(s[0])))}),this._hasText&&(t.StructTreeRoot=L(this._nextObjNo+this.totalCanvasObjects)),this._canvasInfos.some(n=>n.images.some(s=>s.choiceInfo))){const n=[],s=[],a=[],o=[];for(const[l,{images:h}]of this._canvasInfos.entries()){let u=this.getCanvasObjectNumber(l)+2+h.length;this._polyglot&&(u+=h.length);let f=0;const d=[];for(const p of h){if(!p.choiceInfo)continue;const g=L(u+f);p.choiceInfo.enabled?n.push(g):s.push(g),a.push(g),d.push(g),f++}o.push(d)}t.OCProperties={OCGs:a,D:{BaseState:"/OFF",ON:n,OFF:s,RBGroups:o}}}if(typeof this._initialCanvas=="string")t.OpenAction=[L(this.getCanvasObjectNumber(this._canvasInfos.findIndex(n=>n.canvas.id===this._initialCanvas)))];else if(this._initialCanvas){const n=72/this._initialCanvas.ppi,s=this._initialCanvas.position,{width:a,height:o}=this._initialCanvas.dimensions;t.OpenAction=[L(this.getCanvasObjectNumber(this._canvasInfos.findIndex(l=>l.canvas.id===this._initialCanvas))),"/FitR",n*s.x,n*s.y,n*(a-(s.x+s.width)),n*(o-(s.y+s.height))]}this._registerEmbeddedFilesInCatalog(),await this._flush(),this._manifestJson&&(await this._embedManifest(this._manifestJson),await this._flush())}async renderPage(t,{width:r,height:i},n,s,a,o=300){var C;this._pagesStarted||(k.debug("Initial page, finalizing PDF header structures."),await this.finalizePdfHeader(),this._pagesStarted=!0);const l=72/o,h={Type:"/Page",Parent:this._objRefs.Pages,MediaBox:[0,0,l*r,l*i],Resources:{ProcSet:["/PDF","/Text","/ImageB","/ImageI","/ImageC"]}};this._hasText&&(h.StructParents=this._nextStructParentId,this._pageParentIds.set(this._nextObjNo,this._nextStructParentId),this._nextStructParentId++);const c={};if(a&&this._objRefs.Type0Font&&(c["f-0-0"]=this._objRefs.Type0Font),this._annotationsAsText)for(const{resourceName:$}of ls(this._annotationFont))c[$]=this._objRefs[$];Object.keys(c).length>0&&(h.Resources.Font=c);const u=this._addObject(h),f=[],d={};for(const[$,A]of n.entries()){if(vr(A))continue;const{x,y:S,width:I,height:O,choiceInfo:E,crop:N}=A,M=l*I,U=l*O,B=l*x,D=l*(i-O-S),X=`/Im${$+1}`;if(E!=null&&E.optional){const Q=`/oc${Object.keys(d).length+1}`;d[X]=Q,f.push(`/OC ${Q} BDC`)}if(N){const Q=M/N.width,dt=U/N.height,V=B-N.x*Q,pt=D-(1-N.y-N.height)*dt;f.push(`q ${B} ${D} ${M} ${U} re W n`),f.push(`${Q} 0 0 ${dt} ${V} ${pt} cm`)}else f.push(`q ${M} 0 0 ${U} ${B} ${D} cm`);f.push(`${X} Do`),f.push("Q"),E!=null&&E.optional&&f.push("EMC")}if(a&&f.push(this._renderOcrText(a,l)),this._annotationsAsText&&(s!=null&&s.length)){const $=await Promise.all(s.map(A=>Rp(A,l,i,r,this._annotationFont)));f.push(...$.flat())}k.debug("Trying to compress content stream.");const p=await yr(f.join(`
|
|
40
|
+
`)),g=this._addObject(p.dict,void 0,p.stream);u.data.Contents=L(g);const m=u.data.Resources,y={},b={};for(const[$,A]of n.entries()){if(vr(A))continue;const x=`/Im${$+1}`;if(y[x.substring(1)]=this._makeDeferredReference(x),(C=A.choiceInfo)!=null&&C.optional){const S=d[x];b[S.substring(1)]=this._makeDeferredReference(S)}}m.XObject=y,Object.keys(b).length>0&&(m.Properties=b),k.debug("Creating image objects.");const w=this._canvasInfos.findIndex($=>$.canvas.id===t);for(const[$,A]of n.entries()){if(vr(A)){this._addObject({}),this._polyglot&&this._addObject({});continue}const x=new Uint8Array(A.data),S=un.open(x),I=S.toObjects(this._polyglot?this._nextObjNo+1:this._nextObjNo);if(A.format!=="jpeg"&&S instanceof ar){let N=I.slice(-1)[0].num;for(let M=0;I.length<3;M++)I.push({num:N++})}const O=I[0],E=`/Im${$+1}`;if(this._deferredReferences.get(E).refObj=O.num,this._polyglot)if(S instanceof ar){const N=this._getSerializedSize(O,!0),M=`img/canvas-${w}-${$}.jpg`;this._insertZipHeaderDummyObject({filename:M,data:x,bytesUntilActualData:N})}else this._addObject({});I.forEach(N=>this._objects.push(N)),this._nextObjNo=I.slice(-1)[0].num+1}if(n.some($=>{var A;return(A=$==null?void 0:$.choiceInfo)==null?void 0:A.optional})){k.debug("Creating optional content groups for page");for(const[$,A]of n.entries()){const x=`/Im${$+1}`;if(A!=null&&A.choiceInfo){if(vr(A)){this._addObject({});continue}this._deferredReferences.get(d[x]).refObj=this._nextObjNo,this._addObject({Type:"/OCG",Name:A.choiceInfo.label?`(${Rt(A.choiceInfo.label,this._langPref,"/")})`:void 0,Intent:"/View",Usage:A.choiceInfo.visibleByDefault?"/ON":"/OFF"})}}}const _=this._canvasInfos[w];if(a!=null&&a.markup){const $=this._canvasInfos.findIndex(x=>x.canvas.id===t);let A=`ocr/canvas-${$}`;a.mimeType.indexOf("html")>=0?A+=".html":A+=".xml",await this._embedResource(A,`OCR for canvas #${$}`,a.mimeType,a.markup)}else _!=null&&_.ocr&&(this._addObject({}),this._addObject({}),this._polyglot&&this._addObject({}));!this._annotationsAsText&&s&&s.length>0&&(k.debug("Creating annotations for page"),h.Annots=(await Promise.all(s.map($=>Ip($,l,i)))).flat().map($=>L(this._addObject($)))),k.debug("Flushing data for page"),await this._flush(),k.debug("Finished rendering page")}_renderOcrText(t,r){const i=t.height,n=[];n.push("BT"),n.push("3 Tr");const s=this._nextObjNo-1;let a=0;const o=[],l=(h,c)=>{if(h.type==="block")o.push({type:"Sect",children:[],pageObjNum:s,mcs:[]});else if(h.type==="paragraph")o.push({type:"P",children:[],pageObjNum:s,mcs:[]}),c&&c.children.push(o.slice(-1)[0]);else if(h.type==="line"){n.push(...this.renderOcrLine(h,a,r,i,s)),c&&c.children.push({type:"Span",children:[],pageObjNum:s,mcs:[a]}),a++;return}for(const u of h.children)l(u,o.slice(-1)[0])};return l(t),this._strucTree.push(...o),n.push("ET"),n.join(`
|
|
41
|
+
`)}renderOcrLine(t,r,i,n,s){const a="/f-0-0",u=[];u.push(`/Span << /MCID ${r} >> BDC`);const f=t.height*i*.75;u.push(`${a} ${f} Tf`);const d=t.x*i,p=n-t.y-t.height*.75,g=p*i;u.push(`1 0 0 1 ${d} ${g} Tm`);let m=0,y=0;for(const b of t.words){if(!b.text||!b.width)continue;const w=(b.x-t.x)*i,C=(n-b.y-b.height*.75-p)*i,$=b.width*i,A=b.height*i,x=w-m,S=C-y;u.push(`${x*1+S*0} ${x*0+S*1} Td`),m=w,y=C;const I=Math.pow(Math.pow($,2)+Math.pow(A,2),.5),O=b.text.length;u.push(`${vi*(100*I/(f*O))} Tz`);const E=$t(Ui(b.text+" ",!1));u.push(`[ ${E} ] TJ`)}return u.push("EMC"),u.push(""),this._pageMCIds.has(s)||this._pageMCIds.set(s,[]),this._pageMCIds.get(s).push(r),u}get bytesWritten(){return this._offset}get totalCanvasObjects(){return this._canvasInfos.reduce((t,r,i)=>t+this.getCanvasObjectNumber(i),0)}getObjectsPerCanvas(t){const{images:r,ocr:i,numAnnotations:n}=this._canvasInfos[t];let s=r.map(a=>a.format==="jpeg"?1:3).reduce((a,o)=>a+o,0)+2+r.filter(a=>a.choiceInfo!==void 0).length+(this._annotationsAsText?0:n);return this._polyglot&&(s=s+r.length+(i?1:0)),i&&(s+=2),s}getCanvasObjectNumber(t){let r=this._firstPageObjectNum;for(const[i]of this._canvasInfos.entries()){if(i===t)return r;r+=this.getObjectsPerCanvas(i)}throw new Error(`Canvas #${t} not found.`)}async _flush(){this._offsets.length===0&&(k.debug("Writing PDF header"),await this._write(`%PDF-1.5
|
|
42
|
+
%Þ¾ï
|
|
43
|
+
`));for(const t of this._objects)t&&(k.debug(`Serializing object #${t.num}`),await this._serializeObject(t));this._objects=[]}_getSerializedSize({num:t,data:r,stream:i},n=!1){let s=0;if(s+=`${t} 0 obj
|
|
44
|
+
`.length,r&&(s+=$t(r).length),i){if(s+=8,n)return s;typeof i=="string"?s+=kt.encode(i).byteLength:s+=i.byteLength,s+=10}return s+=8,s}async _serializeObject(t){this._offsets.push(this._offset);const{num:r,data:i,stream:n}=t;await this._write(`${r} 0 obj
|
|
45
|
+
`),i&&await this._write($t(i)),n&&(await this._write(`
|
|
46
|
+
stream
|
|
47
|
+
`),await this._write(n),await this._write(`
|
|
48
|
+
endstream`)),await this._write(`
|
|
49
|
+
endobj
|
|
50
|
+
`)}async _write(t){if(this._writer===void 0)throw new Error("Cannot perform mutating operations on an already closed PDFGenerator.");const r=typeof t=="string"?kt.encode(t):t;this._offset+=r.byteLength,await this._writer.write(t)}async _writeStructureTree(){const t={Nums:[]},r=L(this._addObject(t)),i={Type:"/StructTreeRoot",K:[],ParentTree:r,ParentTreeNextKey:this._nextStructParentId},n=new Map,s=L(this._addObject(i)),a=async(o,l,h)=>{const c={Type:"/StructElem",S:`/${o.type}`,P:h,Pg:L(o.pageObjNum),K:[]};n.has(o.pageObjNum)||n.set(o.pageObjNum,[]);const u=L(this._addObject(c));if(l.K.push(u),o.children.length>0)for(const f of o.children)await a(f,c,u);else o.mcs.length==1?c.K=o.mcs[0]:o.mcs.length>0&&(c.K=o.mcs);if(o.mcs.length>0){const f=n.get(o.pageObjNum);for(const d of o.mcs)f[d]=u}this._objects.length>1e3&&await this._flush()};for(const o of this._strucTree)await a(o,i,s);for(const[o,l]of n){const h=this._pageParentIds.get(o);t.Nums.push(h,L(this._addObject(l)))}await this._flush()}async end(){if(!this._writer)return;k.debug("Writing xref table");const t=[[0,65535,"f"],...this._offsets.map(a=>[a,0,"n"])],r=t.map(([a,o,l])=>[a.toString(10).padStart(10,"0"),o.toString(10).padStart(5,"0"),l,""].join(" ")).join(`
|
|
51
|
+
`),i=this._offset;await this._write(`xref
|
|
52
|
+
0 ${t.length}
|
|
53
|
+
${r}
|
|
54
|
+
`);const n={Size:t.length,Root:this._objRefs.Catalog,Info:this._objRefs.Info,ID:[rs(32),rs(32)]};await this._write(`
|
|
55
|
+
trailer
|
|
56
|
+
${$t(n)}`);const s=`startxref
|
|
57
|
+
${i}
|
|
58
|
+
%%EOF`;if(this._polyglot&&this._zipCatalog){k.debug("Writing zip end of central directory"),await this._write(`9990 0 obj
|
|
59
|
+
<<>>
|
|
60
|
+
stream
|
|
61
|
+
`);const a=`
|
|
62
|
+
endstream
|
|
63
|
+
endobj
|
|
64
|
+
`;await this._write(Kd({files:this._zipCatalog,trailingLength:s.length+a.length,offset:this._offset})),await this._write(a)}await this._flush(),k.debug("Writing trailer"),await this._write(s),k.debug("Flushing"),await this._flush(),k.debug("PDF finished, closing writer"),await this._writer.close(),k.debug("Writer closed"),this._writer=void 0}_insertZipHeaderDummyObject({filename:t,data:r,deflatedData:i,bytesUntilActualData:n}){this._zipBaseDir&&(t=`${this._zipBaseDir}/${t}`);const s=this._offset+this._objects.reduce((h,c)=>h+this._getSerializedSize(c),0),a=new Date;n+=18;const o=this._addObject({},void 0,Xd({filename:t,data:r,compressedData:i,extraDataLength:n,creationDate:a})),l=s+this._getSerializedSize(o,!0);this._zipCatalog||(this._zipCatalog=[]),this._zipCatalog.push({localHeaderOffset:l,deflated:(i==null?void 0:i.length)!==r.length,creationDate:new Date,crc32:Cs(r),dataLength:r.length,compressedDataLength:i?i.length-2:r.length,filename:t})}}const Dp={"http://creativecommons.org/licenses/by-nc-sa/2.0/fr/":{text:"Creative Commons Attribution-NonCommercial-ShareAlike 2.0 France (CC-BY-NC-SA-2.0-FR)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by-sa/4.0/":{text:"Creative Commons Attribution Share Alike 4.0 International (CC-BY-SA-4.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by/3.0/de/":{text:"Creative Commons Attribution 3.0 Germany (CC-BY-3.0-DE)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nc-nd/3.0/":{text:"Creative Commons Attribution Non Commercial No Derivatives 3.0 Unported (CC-BY-NC-ND-3.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/licenses/by/1.0/":{text:"Creative Commons Attribution 1.0 Generic (CC-BY-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nd/1.0/":{text:"Creative Commons Attribution No Derivatives 1.0 Generic (CC-BY-ND-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nd.svg"},"http://creativecommons.org/licenses/by-nc-sa/3.0/de/":{text:"Creative Commons Attribution Non Commercial Share Alike 3.0 Germany (CC-BY-NC-SA-3.0-DE)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by-nc-sa/1.0/":{text:"Creative Commons Attribution Non Commercial Share Alike 1.0 Generic (CC-BY-NC-SA-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by-nd/4.0/":{text:"Creative Commons Attribution No Derivatives 4.0 International (CC-BY-ND-4.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nd.svg"},"http://creativecommons.org/licenses/by-sa/3.0/at/":{text:"Creative Commons Attribution Share Alike 3.0 Austria (CC-BY-SA-3.0-AT)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by/3.0/at/":{text:"Creative Commons Attribution 3.0 Austria (CC-BY-3.0-AT)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by/3.0/":{text:"Creative Commons Attribution 3.0 Unported (CC-BY-3.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nc/2.0/":{text:"Creative Commons Attribution Non Commercial 2.0 Generic (CC-BY-NC-2.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc.svg"},"http://creativecommons.org/licenses/by-nc-sa/2.5/":{text:"Creative Commons Attribution Non Commercial Share Alike 2.5 Generic (CC-BY-NC-SA-2.5)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by-nc/2.5/":{text:"Creative Commons Attribution Non Commercial 2.5 Generic (CC-BY-NC-2.5)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc.svg"},"http://creativecommons.org/licenses/by-nd-nc/1.0/":{text:"Creative Commons Attribution Non Commercial No Derivatives 1.0 Generic (CC-BY-NC-ND-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/licenses/by-nd/3.0/":{text:"Creative Commons Attribution No Derivatives 3.0 Unported (CC-BY-ND-3.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nd.svg"},"http://creativecommons.org/licenses/by-sa/2.5/":{text:"Creative Commons Attribution Share Alike 2.5 Generic (CC-BY-SA-2.5)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by-nc-sa/2.0/uk/":{text:"Creative Commons Attribution Non Commercial Share Alike 2.0 England and Wales (CC-BY-NC-SA-2.0-UK)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by/2.0/":{text:"Creative Commons Attribution 2.0 Generic (CC-BY-2.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nd/2.5/":{text:"Creative Commons Attribution No Derivatives 2.5 Generic (CC-BY-ND-2.5)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nd.svg"},"http://creativecommons.org/licenses/by-nc-nd/2.0/":{text:"Creative Commons Attribution Non Commercial No Derivatives 2.0 Generic (CC-BY-NC-ND-2.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/licenses/by-nc-sa/3.0/igo/":{text:"Creative Commons Attribution Non Commercial Share Alike 3.0 IGO (CC-BY-NC-SA-3.0-IGO)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/publicdomain//":{text:"Creative Commons Public Domain Dedication and Certification (CC-PDDC)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/publicdomain.svg"},"http://creativecommons.org/licenses/by-nc-sa/2.0/":{text:"Creative Commons Attribution Non Commercial Share Alike 2.0 Generic (CC-BY-NC-SA-2.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by-nc-nd/3.0/de/":{text:"Creative Commons Attribution Non Commercial No Derivatives 3.0 Germany (CC-BY-NC-ND-3.0-DE)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/licenses/by-nc/3.0/":{text:"Creative Commons Attribution Non Commercial 3.0 Unported (CC-BY-NC-3.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc.svg"},"http://creativecommons.org/licenses/by-nc/3.0/de/":{text:"Creative Commons Attribution Non Commercial 3.0 Germany (CC-BY-NC-3.0-DE)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc.svg"},"http://creativecommons.org/licenses/by-sa/1.0/":{text:"Creative Commons Attribution Share Alike 1.0 Generic (CC-BY-SA-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by-nd/3.0/de/":{text:"Creative Commons Attribution No Derivatives 3.0 Germany (CC-BY-ND-3.0-DE)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nd.svg"},"http://creativecommons.org/licenses/by-nc-nd/2.5/":{text:"Creative Commons Attribution Non Commercial No Derivatives 2.5 Generic (CC-BY-NC-ND-2.5)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/licenses/by-sa/3.0/":{text:"Creative Commons Attribution Share Alike 3.0 Unported (CC-BY-SA-3.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by-nc-sa/4.0/":{text:"Creative Commons Attribution Non Commercial Share Alike 4.0 International (CC-BY-NC-SA-4.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by-sa/2.0/":{text:"Creative Commons Attribution Share Alike 2.0 Generic (CC-BY-SA-2.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by-sa/2.1/jp/":{text:"Creative Commons Attribution Share Alike 2.1 Japan (CC-BY-SA-2.1-JP)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by/2.5/":{text:"Creative Commons Attribution 2.5 Generic (CC-BY-2.5)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-sa/2.0/uk/":{text:"Creative Commons Attribution Share Alike 2.0 England and Wales (CC-BY-SA-2.0-UK)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by/3.0/nl/":{text:"Creative Commons Attribution 3.0 Netherlands (CC-BY-3.0-NL)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nc-sa/3.0/":{text:"Creative Commons Attribution Non Commercial Share Alike 3.0 Unported (CC-BY-NC-SA-3.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-sa.svg"},"http://creativecommons.org/licenses/by/4.0/":{text:"Creative Commons Attribution 4.0 International (CC-BY-4.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by/3.0/us/":{text:"Creative Commons Attribution 3.0 United States (CC-BY-3.0-US)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nc-nd/4.0/":{text:"Creative Commons Attribution Non Commercial No Derivatives 4.0 International (CC-BY-NC-ND-4.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/licenses/by-sa/3.0/de/":{text:"Creative Commons Attribution Share Alike 3.0 Germany (CC-BY-SA-3.0-DE)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-sa.svg"},"http://creativecommons.org/licenses/by-nc-nd/3.0/igo/":{text:"Creative Commons Attribution Non Commercial No Derivatives 3.0 IGO (CC-BY-NC-ND-3.0-IGO)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc-nd.svg"},"http://creativecommons.org/publicdomain/zero/1.0/":{text:"Creative Commons Zero v1.0 Universal (CC0-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/cc-zero.svg"},"http://creativecommons.org/publicdomain/mark/1.0/":{text:"Public Domain Mark 1.0: No Copyright",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/publicdomain.svg"},"http://creativecommons.org/licenses/by/2.5/au/":{text:"Creative Commons Attribution 2.5 Australia (CC-BY-2.5-AU)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by.svg"},"http://creativecommons.org/licenses/by-nd/2.0/":{text:"Creative Commons Attribution No Derivatives 2.0 Generic (CC-BY-ND-2.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nd.svg"},"http://creativecommons.org/licenses/by-nc/1.0/":{text:"Creative Commons Attribution Non Commercial 1.0 Generic (CC-BY-NC-1.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc.svg"},"http://creativecommons.org/licenses/by-nc/4.0/":{text:"Creative Commons Attribution Non Commercial 4.0 International (CC-BY-NC-4.0)",logo:"https://mirrors.creativecommons.org/presskit/buttons/88x31/svg/by-nc.svg"},"http://rightsstatements.org/vocab/InC/1.0/":{text:"In Copyright",logo:"https://rightsstatements.org/files/buttons/InC.dark.svg"},"http://rightsstatements.org/vocab/InC-OW-EU/1.0/":{text:"In Copyright - EU Orphan Work",logo:"https://rightsstatements.org/files/buttons/InC-OW-EU.dark.svg"},"http://rightsstatements.org/vocab/InC-EDU/1.0/":{text:"In Copyright - Educational Use Permitted",logo:"https://rightsstatements.org/files/buttons/InC-EDU.dark.svg"},"http://rightsstatements.org/vocab/InC-NC/1.0/":{text:"In Copyright - Non-Commercial Use Permitted",logo:"https://rightsstatements.org/files/buttons/InC-NC.dark.svg"},"http://rightsstatements.org/vocab/InC-RUU/1.0/":{text:"In Copyright - Rights-holder(s) Unlocatable or Unidentifiable",logo:"https://rightsstatements.org/files/buttons/InC-RUU.dark.svg"},"http://rightsstatements.org/vocab/NoC-CR/1.0/":{text:"No Copyright - Contractual Restrictions",logo:"https://rightsstatements.org/files/buttons/NoC-CR.dark.svg"},"http://rightsstatements.org/vocab/NoC-NC/1.0/":{text:"No Copyright - Non-Commercial Use Only",logo:"https://rightsstatements.org/files/buttons/NoC-NC.dark.svg"},"http://rightsstatements.org/vocab/NoC-OKLR/1.0/":{text:"No Copyright - Other Known Legal Restrictions",logo:"https://rightsstatements.org/files/buttons/NoC-OKLR.dark.svg"},"http://rightsstatements.org/vocab/NoC-US/1.0/":{text:"No Copyright - United States",logo:"https://rightsstatements.org/files/buttons/NoC-US.dark.svg"},"http://rightsstatements.org/vocab/CNE/1.0/":{text:"Copyright Not Evaluated",logo:"https://rightsstatements.org/files/buttons/CNE.dark.svg"},"http://rightsstatements.org/vocab/UND/1.0/":{text:"Copyright Undetermined",logo:"https://rightsstatements.org/files/buttons/UND.dark.svg"},"http://rightsstatements.org/vocab/NKC/1.0/":{text:"No Known Copyright",logo:"https://rightsstatements.org/files/buttons/NKC.dark.svg"}};function Lp(e){return e=e.replace(/^https:/,"http:").replace(/\/deed\.[a-z]{2}$/,""),e.endsWith("/")||(e+="/"),Dp[e]}function Wp(e){return new Worker(""+(typeof document>"u"?require("url").pathToFileURL(__dirname+"/assets/optimization.worker-C8u4PFfM.js").href:new URL("assets/optimization.worker-C8u4PFfM.js",document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"&&document.currentScript.src||document.baseURI).href),{type:"module",name:e==null?void 0:e.name})}class Up{constructor(t){v(this,"workers",[]);v(this,"queue",[]);v(this,"pendingTasks",new Map);v(this,"busyWorkers",new Set);this.size=t}start(){for(let t=0;t<this.size;t++){const r=new Wp;r.onmessage=this.handleMessage.bind(this,r),r.onerror=this.handleError.bind(this,r),this.workers.push(r)}}stop(){this.workers.forEach(t=>t.terminate()),this.workers=[],this.queue=[],this.busyWorkers.clear()}dispatch(t){return new Promise((r,i)=>{this.queue.push({resolve:r,reject:i,task:{id:zl(),data:t}}),this.processQueue()})}processQueue(){if(this.queue.length===0)return;const t=this.workers.find(i=>!this.busyWorkers.has(i));if(!t)return;const r=this.queue.shift();this.pendingTasks.set(r.task.id,r),this.busyWorkers.add(t),t.postMessage(r.task)}handleMessage(t,r){k.debug("worker: received message",r.data);const i=this.pendingTasks.get(r.data.input.id);i?(i.resolve(r.data.result),k.debug("worker: resolved job",i.task.id),this.pendingTasks.delete(i.task.id),this.busyWorkers.delete(t),this.processQueue()):k.warn(`worker: unknown job, known jobs: ${[...this.pendingTasks.keys()].join(", ")}`,r.data.input.id)}handleError(t,r){const i=r.error,n=this.queue.find(s=>s.task.id===i.taskId);n&&(n.reject(i.cause),this.busyWorkers.delete(t),this.processQueue())}}let ae=null,hs=!1;function al(e=navigator.hardwareConcurrency){ae===null&&(ae=new Up(e),ae.start())}async function Bp(e){if(ae===null&&al(),hs)return;const t=await e();let r=[];for(let i=0;i<ae.size;i++)r.push(ae.dispatch({mozjpegWasm:t}));k.debug("main: mozjpegWasm sent to workers"),await Promise.all(r),k.debug("main: workers initialized with MozJPEG encoder"),hs=!0}async function ol(e){return ae===null&&al(),ae.dispatch(e)}function zp(e,t){if(e.length<=t)return e;const r=e.reduce((s,{width:a,height:o})=>s+a*o,0)/e.length,i=e.filter(s=>Math.abs(r-s.width*s.height)<=.25*r);if(i.length<=t)return i;const n=[];for(;n.length<t;){const s=i[Math.floor(Math.random()*i.length)];n.indexOf(s)<0&&n.push(s)}return n.sort((s,a)=>e.indexOf(s)-e.indexOf(a))}async function qp({manifest:e,concurrency:t=1,scaleFactor:r,filterCanvases:i=()=>!0,numSamples:n=8,optimization:s,saxWasmLoader:a=async()=>fetch(`https://unpkg.com/sax-wasm@${Qi}/lib/sax-wasm.wasm`).then(h=>h.arrayBuffer()).then(h=>new Uint8Array(h)),mozjpegWasmLoader:o=async()=>fetch("https://unpkg.com/@jsquash/jpeg@1.5.0/codec/enc/mozjpeg_enc.wasm").then(h=>h.arrayBuffer()).then(h=>new Uint8Array(h)),sampleCanvases:l}){let h;typeof e=="string"?h=e:h=e.id??e["@id"];const c=await an(h),u=await H.loadManifest(h,c);if(!u)throw new Error(`Failed to load manifest from ${h}`);let f;Array.isArray(i)?f=x=>i.indexOf(x)>=0:f=i;const d=H.get(u.items.filter(x=>f(x.id)).map(x=>x.id)),p=d.reduce((x,S)=>x+S.width*S.height,0);l!=null&&l.length||(l=zp(d,n));const g=l.reduce((x,S)=>x+S.width*S.height,0);if(!Tt||!er()){if(!Tt){const x=await a();Ss(x)}er()||(await ys(()=>Promise.resolve(Tt)),k.debug.bind(k),k.info.bind(k),k.warn.bind(k),k.error.bind(k),void 0)}const m=new Mo({concurrency:t}),y=await Promise.all(l.map(x=>m.add(async()=>{const S=ko(x);return jo(x,S.images,{scaleFactor:r,sizeOnly:s===void 0})})));let b;if(s){s.method==="mozjpeg"&&await Bp(o);const x=y.filter(O=>O!==void 0).flatMap(O=>O.images),S=x.reduce((O,E)=>O+E.data.byteLength,0);await Promise.all(x.map(async O=>{const E=await ol({imageData:new Uint8Array(O.data),imageFormat:O.format==="jpeg"?"image/jpeg":"image/png",...s});O.data=E.jpegData.buffer,O.format="jpeg"})),b=x.reduce((O,E)=>O+E.data.byteLength,0)/S}const w=y.filter(xe).flatMap(x=>x.images).every(x=>x.corsAvailable),_=y.filter(xe).flatMap(x=>x.images).reduce((x,S)=>{var I;return x+(((I=S==null?void 0:S.data)==null?void 0:I.byteLength)??S.numBytes)},0),$=y.filter(xe).flatMap(x=>x.images)[0];return{size:_/g*p,corsSupported:w,sampleImageData:$.data?new Uint8Array($.data):void 0,sampleImageMimeType:$.format,sampleCanvases:l,optimizationResult:b}}async function Hp(e,t,r){const i=t.map(c=>c.id),n=c=>{var u;return typeof c!="string"&&(c.type==="Canvas"||c.type=="SpecificResource"&&((u=c.source)==null?void 0:u.type)==="Canvas")},s=c=>typeof c!="string"&&c.type=="Range",a=new Set,o=async c=>{if(a.has(c.id))return;const u=c.items.filter(n).map(m=>m.type==="SpecificResource"?m.source:m).filter(m=>i.indexOf(m==null?void 0:m.id)>=0).sort((m,y)=>i.indexOf(m.id)>i.indexOf(y.id)?-1:1)[0],f=Rt(c.label??"<untitled>",r,"; "),d=H.get(c.items.filter(s)),p=(await Promise.all(d.map(o))).filter(xe);let g;if(c.start&&(g=await Io(c)),a.add(c.id),!(p.length===0&&!u))return!g&&u?g=u.id:g||(g=p[0].startCanvas),{label:f,startCanvas:g,children:p}};let l=H.get(e.structures);const h=l.find(c=>c.behavior.indexOf("top")>=0);return h&&(l=[h]),(await Promise.all(l.map(o))).filter(xe)??[]}class Gp{constructor(t,r,i,n,s){v(this,"canvasPixels",0);v(this,"pixelsWritten",0);v(this,"pixelBytesFactor",0);v(this,"pixelScaleFactor",0);v(this,"timeStart");v(this,"pdfGen");v(this,"totalPages");v(this,"totalCanvasPixels",0);v(this,"countingStream");v(this,"onProgress");v(this,"onNotification");this.totalCanvasPixels=t.reduce((a,o)=>a+o.width*o.height,0),this.totalPages=t.length,this.pdfGen=i,this.countingStream=r,this.onProgress=n,this.onNotification=s}get writeOutstanding(){return this.pdfGen.bytesWritten>this.countingStream.bytesWritten}emitProgress(t,r){var l;this.timeStart||(this.timeStart=gn());const i=this.pdfGen.bytesWritten;let n;t===this.totalPages?n=i:t>0&&(n=Math.floor(this.pixelBytesFactor*this.pixelScaleFactor*this.totalCanvasPixels));const s=this.countingStream.bytesWritten,a=i/((gn()-this.timeStart)/1e3);let o=Number.POSITIVE_INFINITY;n&&(o=(n-s)/a),(l=this.onProgress)==null||l.call(this,{messageCode:r,pagesWritten:t,totalPages:this.totalPages,bytesWritten:s,bytesPushed:i,estimatedFileSize:n,writeSpeed:a,remainingDuration:o})}emitNotification(t){var r;(r=this.onNotification)==null||r.call(this,t)}updatePixels(t,r){this.pixelsWritten+=t,this.canvasPixels+=r,this.pixelScaleFactor=this.pixelsWritten/this.canvasPixels,this.pixelBytesFactor=this.pdfGen.bytesWritten/this.pixelsWritten}}async function Qp(e,t,r,i){var h,c,u,f,d,p,g;const n={title:Rt(e.label??"<untitled>",t,"; "),manifestUrl:e.id,pdiiifVersion:fn},s=await td(e,512);if(s){n.thumbnail={url:s};const m=H.get(e.thumbnail.map(y=>y.id))[0];m&&"type"in m&&(n.thumbnail.iiifImageService=(c=(h=m.service)==null?void 0:h.find(y=>{var b;return((b=y==null?void 0:y.type)==null?void 0:b.startsWith("ImageService"))??!1}))==null?void 0:c.id)}const a=H.get(e.provider)[0],o=e.requiredStatement;a&&(n.provider={label:Rt(a.label,t,"; "),homepage:(f=(u=a.homepage)==null?void 0:u[0])==null?void 0:f.id,logo:(p=(d=a.logo)==null?void 0:d[0])==null?void 0:p.id},n.provider.label==="Unknown"&&(n.provider.label="")),o!=null&&o.label&&(n.requiredStatement={label:Rt(o.label,t,"; "),value:Rt(o.value,t,"; ")});const l=e.rights;if(l){const m=Lp(l);n.rights={text:(m==null?void 0:m.text)??l,url:l,logo:m==null?void 0:m.logo}}if(n.metadata=((g=e.metadata)==null?void 0:g.map(m=>{const y=Rt(m.label,t,"; "),b=Rt(m.value,t,"|||").split("|||");if(!(!y||b.length===0))return b.length===1?[y,b[0]]:[y,b]}).filter(m=>m!==void 0))??[],i)return await i(n);if(r){const y=await(await Mi(r,{method:"POST",headers:{"Content-Type":"application/json; charset=utf-8"},body:JSON.stringify(n)})).arrayBuffer();return new Uint8Array(y)}else throw"Either `endpoint` or `callback` must be specified!"}async function Yp(e,t,{fetchCanvasAnnotations:r=()=>Promise.resolve([]),filterCanvases:i=()=>!0,languagePreference:n=[Intl.DateTimeFormat().resolvedOptions().locale],scaleFactor:s,metadata:a={},onProgress:o,onNotification:l,ppi:h,concurrency:c=1,abortController:u=new AbortController,coverPageCallback:f,coverPageEndpoint:d,polyglotZipPdf:p,polyglotZipBaseDir:g,annotationsAsText:m,annotationFont:y,optimization:b,saxWasmLoader:w=async()=>fetch(`https://unpkg.com/sax-wasm@${Qi}/lib/sax-wasm.wasm`).then(C=>C.arrayBuffer()).then(C=>new Uint8Array(C)),mozjpegWasmLoader:_=async()=>fetch("https://unpkg.com/@jsquash/jpeg@1.5.0/codec/enc/mozjpeg_enc.wasm").then(C=>C.arrayBuffer()).then(C=>new Uint8Array(C))}){typeof process<"u"&&ul.setMaxListeners(100,u.signal);let C;t?typeof t.destroy=="function"?(k.debug("Writing to Node writable stream"),C=new Qd(t),t.on("close",()=>u.abort())):(k.debug("Writing to file system"),C=new Gd(t)):(k.debug("Writing to Blob"),C=new ns);const $=new Hd(C),A={fileSizeBytes:0,numPages:0};let x;Array.isArray(i)?x=R=>i.indexOf(R)>=0:x=i;let S,I;typeof e=="string"?(S=e,I=await an(S)):(S=e["@id"]??e.id,I=e);const O=await H.loadManifest(S,I);if(!O)throw new Error(`Failed to load manifest from ${S}`);const E={...a};!E.Title&&O.label&&(E.Title=Rt(O.label,n,"; "));const N=H.get(O.items.filter(R=>x(R.id))),M=!!N.find(R=>!!nn(R)),U=N.map(R=>R.label?Rt(R.label,n,"; "):"");if(!Tt||!er()){if(!Tt){const R=await w();Ss(R)}er()||(await ys(()=>Promise.resolve(Tt)),k.debug.bind(k),k.info.bind(k),k.warn.bind(k),k.error.bind(k),void 0)}k.debug(`Setting up queue with ${c} concurrent canvas fetches.`);const B=new Mo({concurrency:c});u.signal.addEventListener("abort",()=>B.clear(),{once:!0});const D=N.map(ko),X=N.map((R,q)=>B.add(async()=>{const z=D[q],ot=await jo(R,z.images,{scaleFactor:s,ppiOverride:h,abortSignal:u.signal});return b&&await Promise.all((ot==null?void 0:ot.images.map(async ct=>{const Ft=await ol({imageData:new Uint8Array(ct.data),imageFormat:ct.format==="jpeg"?"image/jpeg":"image/png",...b});k.debug("main: Got optimized image",ct.resource.id),ct.data=Ft.jpegData,ct.format="jpeg"}))??[]),ot})),Q=await Hp(O,N,n),dt=new Np({writer:$,metadata:E,canvasInfos:N.map((R,q)=>({canvasIdx:q,...D[q]})),langPref:n,pageLabels:U,outline:Q,hasText:M,initialCanvas:await Io(O),readingDirection:O.viewingDirection==="right-to-left"?"right-to-left":"left-to-right",manifestJson:I,zipPolyglot:p,zipBaseDir:g,annotationsAsText:m,annotationFont:y});k.debug("Initialising PDF generator."),await dt.setup();const V=new Gp(N,$,dt,o,l);if(V.emitProgress(0),f||d){k.debug("Generating cover page"),V.emitProgress(0,"generate-cover-page");try{const R=await Qp(O,n,d,f);k.debug("Inserting cover page into PDF"),await dt.insertCoverPages(R)}catch(R){throw k.error("Error while generating cover page",R),u.abort(),R}}V.emitProgress(0,"generate-pages");for(let R=0;R<N.length;R++){if(u.signal.aborted){k.debug("Abort signalled, aborting while waiting for image data.");break}try{k.debug(`Waiting for data for canvas #${R}`);const q=await X[R];if(!q)throw"Aborted";const z=H.get(q.canvas),ot=D[R],{images:ct,ppi:Ft,text:Wt,annotations:ce,imageFailures:_t}=q;if(_t.length>0){A.failedImages||(A.failedImages=[]);const gt={canvasIndex:R,numFailed:_t.length,numTotal:ct.length+_t.length,details:Object.fromEntries(_t.map(rt=>[rt.resource.id??"<unknown>",rt.cause instanceof Error?rt.cause.toString():rt.cause]))};A.failedImages.push(gt),V.emitNotification({code:"image-download-failure",...gt})}if(ot.ocr&&!(Wt!=null&&Wt.markup)){A.failedOcr||(A.failedOcr=[]);const gt={canvasIndex:R,ocrUrl:ot.ocr.id};A.failedOcr.push(gt),V.emitNotification({code:"ocr-download-failure",...gt})}const Vt=await r(z.id);if(Vt!=null){const gt=await Promise.all(Vt.map(rt=>("id"in rt||(rt=lf(rt)),H.load(rt.id,rt))));gt&>.filter(rt=>rt!==void 0).map(rt=>_o(rt,n)).filter(rt=>rt!==void 0).forEach(rt=>ce.push(rt))}const Et=Nt==null?void 0:Nt.pageGenerationDuration.startTimer();k.debug(`Rendering canvas #${R} into PDF`),await dt.renderPage(q.canvas.id,{width:z.width,height:z.height},[...ct,..._t],ce,Wt,Ft),Et==null||Et(),V.updatePixels(ct.reduce((gt,rt)=>gt+rt.width*rt.height,0),z.width*z.height),A.numPages++}catch(q){throw q!=="Aborted"&&k.error("Failed to render page",q),B.clear(),u.signal.aborted||u.abort(),q}finally{delete X[R]}V.emitProgress(R+1)}k.debug("Finalizing PDF");const pt=dt.end();if(!u.signal.aborted){let R=!1;pt.then(()=>R=!0);const q=async()=>{if(!R)for(V.emitProgress(N.length,"finishing");!R&&V.writeOutstanding;)await C.waitForDrain()};R||(await C.waitForDrain(),await q())}return k.debug("Waiting for writer to close."),await pt,A.fileSizeBytes=$.bytesWritten,C instanceof ns?{...A,data:C.blob}:A}exports.ConsoleLogger=fs;exports.convertManifest=Yp;exports.estimatePdfSize=qp;exports.fetchManifestJson=an;exports.setLogger=dl;exports.vault=H;exports.version=fn;
|
|
65
|
+
//# sourceMappingURL=index.cjs.map
|