@namahapdf/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ import'./chunk-X7U5LSSK.js';import Bn from'zlib';import {TextAlignment,PDFDocument,StandardFonts,rgb,degrees,PDFRef,PDFRawStream,PDFName,PDFNumber,PDFString}from'pdf-lib';import {ed25519}from'@noble/curves/ed25519';var mt=class{constructor(){this.processors=new Map;}registerProcessor(e){this.processors.set(e.name,e),console.log(`[AvniEngine] Registered processor: ${e.name}`);}async runPipeline(e,n){let r=[],i=e;for(let s of n.tasks){let o=this.processors.get(s.processorName);if(!o)throw new Error(`Processor ${s.processorName} not found`);console.log(`[AvniEngine] Executing ${o.name}...`);let a=Date.now(),c=await o.process(i,s.params),l=Date.now();if(c.metrics={duration:l-a,originalSize:i.size,newSize:c.document.size},r.push(c),!c.success){console.error(`[AvniEngine] Pipeline failed at ${o.name}: ${c.error}`);break}i=c.document;}return r}getAvailableProcessors(){return Array.from(this.processors.keys())}},Di=new mt;var Gt=t=>({type:"name",value:t.startsWith("/")?t.slice(1):t}),Xt=()=>({type:"null"}),Xe=t=>({type:"boolean",value:t}),Yt=t=>({type:"integer",value:t}),Ht=t=>({type:"real",value:t}),pt=(t,e)=>({type:"string",value:t,encoding:e}),Kt=(t,e=0)=>({type:"ref",objNum:t,genNum:e});var xt=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="integer",In=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="real",Vt=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="string",M=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="dict",U=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="stream",q=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="ref",j=t=>typeof t=="object"&&t!==null&&"type"in t&&t.type==="array",gt=t=>xt(t)||In(t),A=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="integer"||t.type==="real"?t.value:null;function Un(t){return !t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null}function wi(t){if(!t)return [];let e=Un(t);return e?[e]:j(t)?t.items.map(n=>Un(n)).filter(n=>n!==null):[]}function Ln(t){return t&&M(t)?t:null}function Si(t,e){if(e<=0)return [];if(!t)return new Array(e).fill(null);let n=Ln(t);if(n)return new Array(e).fill(n);if(j(t)){let r=t.items.map(i=>Ln(i));return r.length>=e?r.slice(0,e):[...r,...new Array(e-r.length).fill(null)]}return new Array(e).fill(null)}function Re(t,e){return t?A(t.entries.get(e)):null}function Fi(t){let e=new TextDecoder("latin1").decode(t),n=e.indexOf(">"),r=(n>=0?e.slice(0,n):e).replace(/\s+/g,"");if(r.length===0)return new Uint8Array(0);let i=r.length%2===0?r:`${r}0`,s=new Uint8Array(i.length/2);for(let o=0;o<s.length;o++){let a=Number.parseInt(i.slice(o*2,o*2+2),16);if(Number.isNaN(a))throw new Error("Invalid ASCIIHex stream data");s[o]=a;}return s}function vi(t){let e=new TextDecoder("latin1").decode(t),n=[],r=[];for(let i=0;i<e.length;i++){let s=e[i];if(s==="~"&&e[i+1]===">")break;if(/\s/.test(s))continue;if(s==="z"){if(r.length!==0)throw new Error("Invalid ASCII85 stream data");n.push(0,0,0,0);continue}let o=s.charCodeAt(0);if(!(o<33||o>117)&&(r.push(o-33),r.length===5)){let a=0;for(let c of r)a=a*85+c;n.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),r=[];}}if(r.length>0){let i=r.length;for(;r.length<5;)r.push(84);let s=0;for(let a of r)s=s*85+a;let o=[s>>>24&255,s>>>16&255,s>>>8&255,s&255];n.push(...o.slice(0,i-1));}return new Uint8Array(n)}function Ci(t){let e=[];for(let n=0;n<t.length;){let r=t[n++];if(r===128)break;if(r<128){let o=r+1;for(let a=0;a<o&&n<t.length;a++)e.push(t[n++]);continue}let i=257-r;if(n>=t.length)break;let s=t[n++];for(let o=0;o<i;o++)e.push(s);}return new Uint8Array(e)}function Ai(t,e,n){let r=t+e-n,i=Math.abs(r-t),s=Math.abs(r-e),o=Math.abs(r-n);return i<=s&&i<=o?t:s<=o?e:n}function $n(t,e,n,r){let i=Math.max(1,Math.ceil(e*n/8)),s=Math.ceil(r*e*n/8);if(s<=0)return t;let o=s+1,a=Math.floor(t.length/o);if(a<=0)return t;let c=new Uint8Array(a*s),l=new Uint8Array(s);for(let f=0;f<a;f++){let d=t[f*o],u=t.subarray(f*o+1,f*o+1+s),h=c.subarray(f*s,(f+1)*s);switch(d){case 0:{h.set(u);break}case 1:{for(let m=0;m<s;m++){let p=m>=i?h[m-i]:0;h[m]=u[m]+p&255;}break}case 2:{for(let m=0;m<s;m++)h[m]=u[m]+l[m]&255;break}case 3:{for(let m=0;m<s;m++){let p=m>=i?h[m-i]:0,x=l[m];h[m]=u[m]+Math.floor((p+x)/2)&255;}break}case 4:{for(let m=0;m<s;m++){let p=m>=i?h[m-i]:0,x=l[m],g=m>=i?l[m-i]:0;h[m]=u[m]+Ai(p,x,g)&255;}break}default:{h.set(u);break}}l=h.slice();}return c}function Mi(t){let e=[{bytes:t,trimmed:0,skippedHeader:false}];t.length>2&&e.push({bytes:t.subarray(2),trimmed:0,skippedHeader:true});let n=Math.min(64,Math.max(0,t.length-1));for(let r=1;r<=n;r++){let i=t.subarray(0,t.length-r);e.push({bytes:i,trimmed:r,skippedHeader:false}),i.length>2&&e.push({bytes:i.subarray(2),trimmed:r,skippedHeader:true});}for(let r of e){try{return {inflated:new Uint8Array(Bn.inflateSync(Buffer.from(r.bytes))),mode:"zlib",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}try{return {inflated:new Uint8Array(Bn.inflateRawSync(Buffer.from(r.bytes))),mode:"raw",trimmed:r.trimmed,skippedHeader:r.skippedHeader}}catch{}}return null}function ki(t,e){var s,o,a,c;let n=Mi(t);if(!n){let l=Array.from(t.subarray(0,Math.min(8,t.length))).map(u=>`0x${u.toString(16).padStart(2,"0")}`).join(" "),f=Math.max(0,t.length-8),d=Array.from(t.subarray(f)).map(u=>`0x${u.toString(16).padStart(2,"0")}`).join(" ");throw new Error(`FlateDecode failed after zlib/raw retries (including tail-trim recovery). len=${t.length} first=[${l}] last=[${d}]`)}let r=n.inflated;if(n.trimmed>0||n.skippedHeader){let l=[];n.trimmed>0&&l.push(`trimmed ${n.trimmed} byte(s)`),n.skippedHeader&&l.push("skipped first 2 header byte(s)"),console.warn(`[StreamDecoder] FlateDecode recovered (${l.join(", ")}) using ${n.mode} mode`);}if(((s=Re(e,"Predictor"))!=null?s:1)>=10){let l=(o=Re(e,"Colors"))!=null?o:1,f=(a=Re(e,"BitsPerComponent"))!=null?a:8,d=(c=Re(e,"Columns"))!=null?c:1;return $n(r,l,f,d)}return r}function Ri(t,e){var p,x,g,b;let s=0,o=9,a=258,c=[];for(let P=0;P<256;P++)c[P]=[P];let l=()=>{if(Math.floor(s/8)>=t.length)return null;let y=0;for(let D=0;D<o;D++){let v=s+D,F=t[Math.floor(v/8)]>>7-v%8&1;y=y<<1|F;}return s+=o,y},f=()=>{c.length=0;for(let P=0;P<256;P++)c[P]=[P];o=9,a=258;},d=[],u=null;for(;;){let P=l();if(P===null||P===257)break;if(P===256){f(),u=null;continue}let y;if(c[P])y=c[P];else if(u)y=[...u,u[0]];else break;d.push(...y),u&&(c[a++]=[...u,y[0]],a===1<<o&&o<12&&o++),u=y;}let h=new Uint8Array(d);if(((p=Re(e,"Predictor"))!=null?p:1)>=10){let P=(x=Re(e,"Colors"))!=null?x:1,y=(g=Re(e,"BitsPerComponent"))!=null?g:8,D=(b=Re(e,"Columns"))!=null?b:1;return $n(h,P,y,D)}return h}var _=class{static async decodeStream(e){return this.decodeStreamSync(e)}static decodeStreamSync(e){var c,l;let n=e.dict.entries.get("Filter"),r=e.dict.entries.get("DecodeParms"),i=wi(n),s=Si(r,i.length),o=(c=e.rawBytes)!=null?c:e.data;if(!o)throw new Error("Stream has no byte payload");if(i.length===0)return o;let a=o;for(let f=0;f<i.length;f++)a=this.applyFilterSync(i[f],a,(l=s[f])!=null?l:null);return a}static createLazyDecoder(e,n){return async()=>{let r={type:"stream",dict:e,rawBytes:n,decode:async()=>n};return this.decodeStreamSync(r)}}static applyFilterSync(e,n,r){switch(e){case "FlateDecode":case "Fl":return ki(n,r);case "ASCII85Decode":case "A85":return vi(n);case "ASCIIHexDecode":case "AHx":return Fi(n);case "LZWDecode":case "LZW":return Ri(n,r);case "DCTDecode":case "DCT":return n;case "JPXDecode":return console.warn("[StreamDecoder] JPXDecode not yet supported; returning raw bytes"),n;case "RunLengthDecode":case "RL":return Ci(n);case "CCITTFaxDecode":case "CCF":return console.warn("[StreamDecoder] CCITTFaxDecode not yet supported; returning raw bytes"),n;case "Crypt":return n;default:return console.warn(`[StreamDecoder] Unknown filter: ${e}; returning raw bytes`),n}}};var Se=class{constructor(e){this.pos=0;this.bytes=e;}skipWhitespace(){for(;this.pos<this.bytes.length;){let e=this.bytes[this.pos];if(e===0||e===9||e===10||e===12||e===13||e===32)this.pos++;else if(e===37)for(;this.pos<this.bytes.length&&this.bytes[this.pos]!==10&&this.bytes[this.pos]!==13;)this.pos++;else break}}peek(){return this.skipWhitespace(),this.pos<this.bytes.length?this.bytes[this.pos]:void 0}peekRaw(e=0){let n=this.pos+e;return n<this.bytes.length?this.bytes[n]:void 0}read(){return this.skipWhitespace(),this.pos<this.bytes.length?this.bytes[this.pos++]:void 0}readRaw(){return this.pos<this.bytes.length?this.bytes[this.pos++]:void 0}readWord(){this.skipWhitespace();let e=this.pos;for(;this.pos<this.bytes.length;){let n=this.bytes[this.pos];if(n===0||n===9||n===10||n===12||n===13||n===32||n===60||n===62||n===40||n===41||n===123||n===125||n===91||n===93||n===47||n===37)break;this.pos++;}return new TextDecoder().decode(this.bytes.subarray(e,this.pos))}readUntil(e){let n=this.pos,r=new TextEncoder().encode(e),i=r.length;for(;this.pos<=this.bytes.length-i;){let s=true;for(let o=0;o<i;o++)if(this.bytes[this.pos+o]!==r[o]){s=false;break}if(s){let o=this.bytes.subarray(n,this.pos);return this.pos+=i,o}this.pos++;}throw new Error(`Could not find sequence: ${e}`)}getRemainingBytes(){return this.bytes.subarray(this.pos)}getBytes(){return this.bytes}getPosition(){return this.pos}setPosition(e){this.pos=e;}};function Oi(t){let e=t.peekRaw(),n=t.peekRaw(1);if(e===13&&n===10){t.readRaw(),t.readRaw();return}if(e===10||e===13){t.readRaw();return}console.warn(`[WARN] No newline after 'stream' keyword at tokenizer position ${t.getPosition()}`);}function Ti(t){let e=t.getBytes(),n=t.getPosition(),r=[101,110,100,115,116,114,101,97,109];for(let i=n;i<=e.length-r.length;i++){let s=true;for(let d=0;d<r.length;d++)if(e[i+d]!==r[d]){s=false;break}if(!s)continue;let o=i>0?e[i-1]:10,a=i+r.length<e.length?e[i+r.length]:10;if(!(o===10||o===13||o===32||o===9)||!(a===10||a===13||a===32||a===9||a===62))continue;let f=i;return f>n&&e[f-1]===10&&(f-=1),f>n&&e[f-1]===13&&(f-=1),t.setPosition(i+r.length),e.subarray(n,f)}throw new Error("Could not find 'endstream' marker for stream object")}function _n(t){let e=t.readWord();return parseFloat(e)}function Ei(t){if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))throw new Error(`Invalid numeric token: ${t}`);let e=parseFloat(t);if(!Number.isFinite(e))throw new Error(`Invalid numeric value: ${t}`);return /^[+-]?\d+$/.test(t)?Yt(e):Ht(e)}function ji(t){t.skipWhitespace();let e=t.readWord(),n=Ei(e);if(!xt(n))return n;let r=t.getPosition();try{t.skipWhitespace();let i=t.readWord();if(!/^[+-]?\d+$/.test(i))return t.setPosition(r),n;if(t.skipWhitespace(),t.readWord()==="R")return Kt(n.value,parseInt(i,10))}catch{return t.setPosition(r),n}return t.setPosition(r),n}function Nn(t){let e=t.peek();if(e===40){t.read();let n=[],r=1;for(;r>0&&t.peekRaw()!==void 0;){let i=t.readRaw();if(i===40)r++;else if(i===41){if(r--,r===0)break;n.push(i);}else if(i===92){let s=t.peekRaw();if(s===void 0)break;if(s>=48&&s<=55){let o="";for(let a=0;a<3;a++){let c=t.peekRaw();if(c!==void 0&&c>=48&&c<=55)o+=String.fromCharCode(t.readRaw());else break}n.push(parseInt(o,8)&255);continue}t.readRaw(),s===110?n.push(10):s===114?n.push(13):s===116?n.push(9):s===98?n.push(8):s===102?n.push(12):s===40?n.push(40):s===41?n.push(41):s===92?n.push(92):s===10||(s===13?t.peekRaw()===10&&t.readRaw():n.push(s));}else n.push(i);}return pt(new Uint8Array(n),"literal")}else if(e===60){t.read();let n=[];for(;t.peekRaw()!==62;){let i=t.readRaw();if(i===void 0)throw new Error("Unexpected EOF in hex string");if(i===0||i===9||i===10||i===12||i===13||i===32)continue;let s=Ii(i);s!==-1&&n.push(s);}t.readRaw(),n.length%2===1&&n.push(0);let r=new Uint8Array(n.length/2);for(let i=0,s=0;i<n.length;i+=2,s++)r[s]=n[i]<<4|n[i+1];return pt(r,"hex")}throw new Error("Invalid string format")}function Ii(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1}function Bi(t){if(t.peek()!==47)throw new Error("Expected / for name");t.read();let n=t.readWord();return Gt(n)}function Ui(t){if(t.peek()!==91)throw new Error("Expected [ for array");t.read();let n=[];for(;t.peek()!==93;)n.push(he(t));return t.read(),{type:"array",items:n}}function Li(t){if(t.peek()!==60)throw new Error("Expected < for dict");if(t.read(),t.peek()!==60)throw new Error("Expected << for dict");t.read();let n=new Map;for(;;){if(t.skipWhitespace(),t.peekRaw()===62&&t.peekRaw(1)===62){t.readRaw(),t.readRaw();break}let r=he(t);if(!r||typeof r!="object"||r.type!=="name")throw new Error("Dictionary key must be a name");let i=r.value,s=he(t);n.set(i,s);}return {type:"dict",entries:n}}function he(t){let e=t.peek();if(e===void 0)throw new Error("Unexpected EOF while reading object");if(e===110){let n=t.readWord();if(n==="null")return Xt();if(n==="true")return Xe(true);if(n==="false")return Xe(false);throw new Error("Unknown keyword: "+n)}if(e===116||e===102){let n=t.readWord();if(n==="true")return Xe(true);if(n==="false")return Xe(false)}if(e===45||e===43||e===46||e>=48&&e<=57)return ji(t);if(e===40)return Nn(t);if(e===47)return Bi(t);if(e===91)return Ui(t);if(e===60){if(t.peekRaw(1)!==60)return Nn(t);let r=Li(t),i=t.getPosition();try{if(t.skipWhitespace(),t.readWord()==="stream"){Oi(t);let o,a=r.entries.get("Length"),c=A(a);if(typeof c=="number"){let l=t.getPosition();o=t.getRemainingBytes().subarray(0,c),t.setPosition(l+c),t.skipWhitespace();let f=t.readWord();f!=="endstream"&&console.warn(`[WARN] Expected 'endstream' but got '${f}' - stream may be malformed`);}else o=Ti(t);return {type:"stream",dict:r,rawBytes:o,data:o,decode:_.createLazyDecoder(r,o)}}else return t.setPosition(i),r}catch{return t.setPosition(i),r}}throw new Error(`Unknown object type at byte ${e}`)}function Wn(t){let e=_n(t),n=_n(t);if(t.readWord()!=="obj")throw new Error("Expected obj keyword");let i=he(t),s=t.readWord();if(s!=="endobj"){let o=t.getRemainingBytes(),a=o.subarray(0,Math.min(8192,o.length)),c=new TextDecoder("latin1").decode(a),l=c.search(/\bendobj\b/);if(l===-1){let f=c.replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Expected endobj keyword (got '${s||"<EOF>"}'). Nearby: "${f}"`)}t.setPosition(t.getPosition()+l+6),console.warn(`[ObjectReader] Recovered non-immediate endobj for ${Math.floor(e)} ${Math.floor(n)} obj (first token: '${s||"<EOF>"}')`);}return {objNum:Math.floor(e),genNum:Math.floor(n),object:i}}function bt(t,e,n){let r=new TextDecoder("latin1");if(!Number.isFinite(e)||e<0||e>=t.length)throw new Error(`Invalid object offset ${e} (file size: ${t.length})`);let i=4096,s=8192,o=Math.max(0,e-i),a=Math.min(t.length,e+s),c=t.subarray(o,a),l=r.decode(c),f=/(\d+)\s+(\d+)\s+obj\b/g,d,u=[];for(;(d=f.exec(l))!==null;){let b=o+d.index,P=Math.abs(b-e),y=parseInt(d[1],10);u.push({absolutePos:b,matched:d[0],distance:P,objNum:y});}if(u.length===0){let b=Math.max(0,e-64),P=Math.min(t.length,e+128),y=r.decode(t.subarray(b,P)).replace(/[\r\n\t]+/g," ").slice(0,220);throw new Error(`Could not find object header near offset ${e} (searched ${o}-${a}). Snippet: "${y}"`)}if(n!==void 0&&!u.some(b=>b.objNum===n)){let b=r.decode(t),P=String(n),y=new RegExp(`(?<![0-9])${P}\\s+\\d+\\s+obj\\b`,"g"),D;for(;(D=y.exec(b))!==null;){let v=D.index;if(u.some(F=>F.absolutePos===v))continue;let S=Math.abs(v-e);u.push({absolutePos:v,matched:D[0].trim(),distance:S,objNum:n});}}u.sort((b,P)=>{let y=n!==void 0&&b.objNum===n?0:1,D=n!==void 0&&P.objNum===n?0:1;return y!==D?y-D:b.distance-P.distance});let h=Math.min(12,u.length),m=[];for(let b=0;b<h;b++){let P=u[b];try{let y=new Se(t.subarray(P.absolutePos)),D=Wn(y);if(n!==void 0&&D.objNum!==n)throw new Error(`Parsed object ${D.objNum} but expected ${n}`);return b>0&&console.warn(`[ObjectReader] Offset ${e} resolved via fallback candidate #${b+1}: ${P.matched} at ${P.absolutePos}`),{...D,objectOffset:P.absolutePos}}catch(y){let D=y instanceof Error?y.message:String(y);m.push(`#${b+1} ${P.matched} @${P.absolutePos}: ${D}`);}}let p=Math.max(0,e-64),x=Math.min(t.length,e+256),g=r.decode(t.subarray(p,x)).replace(/[\r\n\t]+/g," ").slice(0,280);throw new Error(`Failed to read indirect object near offset ${e}. Tried ${h}/${u.length} candidates. Errors: ${m.join(" || ")}. Snippet: "${g}"`)}function zt(t){let e=A(t.entries.get("XRefStm"));return e===null?null:Math.floor(e)}function $i(t){return t===0||t===9||t===10||t===12||t===13||t===32}function yt(t,e){let n=e;for(;n<t.length&&$i(t[n]);)n++;return n}function Gn(t,e){let n=e;for(;n<t.length&&t[n]!==10&&t[n]!==13;)n++;let r=new TextDecoder("latin1").decode(t.subarray(e,n));return n<t.length&&t[n]===13&&n++,n<t.length&&t[n]===10&&n++,{line:r,next:n}}function Jt(t,e,n){e:for(let r=n;r<=t.length-e.length;r++){for(let i=0;i<e.length;i++)if(t[r+i]!==e[i])continue e;return r}return -1}function Xn(t){return t===void 0?true:t===0||t===9||t===10||t===12||t===13||t===32||t===60||t===62||t===40||t===41||t===91||t===93||t===123||t===125||t===47||t===37}function Zt(t,e,n){if(e<0||e+n.length>t.length)return false;for(let s=0;s<n.length;s++)if(t[e+s]!==n[s])return false;let r=e>0?t[e-1]:void 0,i=e+n.length<t.length?t[e+n.length]:void 0;return Xn(r)&&Xn(i)}function Vn(t,e,n){let r=Math.max(0,n);for(;r<=t.length-e.length;){let i=Jt(t,e,r);if(i===-1)return -1;if(Zt(t,i,e))return i;r=i+1;}return -1}function _i(t,e,n,r){let i=[],s=Math.max(0,n),o=Math.min(t.length-e.length,Math.max(s,r));for(;s<=o;){let a=Jt(t,e,s);if(a===-1||a>o)break;Zt(t,a,e)&&i.push(a),s=a+1;}return i}function Yn(t,e,n,r){let i=Math.max(0,n-r),s=Math.min(t.length,n+r),o=_i(t,e,i,s);return o.length===0?-1:(o.sort((a,c)=>Math.abs(a-n)-Math.abs(c-n)),o[0])}function Ni(t,e,n,r){let i=Math.min(r,t.length);for(let s=Math.max(n,0);s<=i-e.length;s++){let o=true;for(let a=0;a<e.length;a++)if(t[s+a]!==e[a]){o=false;break}if(o){let a=s;for(let c=s+1;c<=i-e.length;c++){let l=true;for(let f=0;f<e.length;f++)if(t[c+f]!==e[f]){l=false;break}l&&(a=c);}return a}}return -1}function qt(t,e){let n=new Se(t.subarray(e)),r=he(n);if(!M(r))throw new Error("Trailer object is not a dictionary");return r}function Be(t){if(t===null)return "null";if(t===void 0)return "undefined";if(Array.isArray(t))return `Array(len=${t.length})`;if(typeof t=="number")return "number";if(typeof t!="object")return typeof t;let e=t;return typeof e.type=="string"?Array.isArray(e.items)?`PDFObject(type=${e.type}, items=${e.items.length})`:typeof e.value!="undefined"?`PDFObject(type=${e.type}, value=${String(e.value)})`:`PDFObject(type=${e.type})`:"object"}function Wi(t){return !t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null}function zn(t,e){console.debug("[XRefTable]",t,e!=null?e:{});}function Hn(t,e){console.warn("[XRefTable]",t,e!=null?e:{});}function Kn(t,e){if(!t)throw new Error(`/${e} missing`);if(j(t)){let i=[];for(let s of t.items){let o=A(s);if(o===null)throw new Error(`/${e} must contain only numbers`);i.push(Math.floor(o));}return i}if(Array.isArray(t))return t.map(i=>Math.floor(Number(i)||0));if(typeof t=="number")return [Math.floor(t)];let n=A(t);if(n!==null)return [Math.floor(n)];let r=t;if(Array.isArray(r.items))return r.items.map(i=>Math.floor(Number(i)||0));throw new Error(`/${e} must be an array, got ${Be(t)}`)}function qn(t){let e=t.length,n=Math.min(1024*1024,e),r=new TextDecoder("latin1").decode(t.subarray(e-n,e)),i=r.lastIndexOf("startxref");if(i!==-1){let s=r.slice(i+9).match(/\d+/);if(s)return parseInt(s[0],10)}throw new Error("PDF missing startxref offset")}function et(t,e){let n=new TextDecoder("latin1"),r=new Uint8Array([120,114,101,102]),i=e,s=Vn(t,r,i);if(s===-1||s-e>32){let a=n.decode(t.subarray(e,Math.min(e+20,t.length)));throw new Error(`Expected 'xref' keyword near offset ${e}, found: ${a}`)}for(i=s+r.length;i<t.length&&(t[i]===13||t[i]===10);)i++;let o=new Map;for(;i<t.length;){for(;i<t.length&&(t[i]===13||t[i]===10);)i++;let a=i;for(;i<t.length&&t[i]!==13&&t[i]!==10;)i++;let c=n.decode(t.subarray(a,i)).trim();for(;i<t.length&&(t[i]===13||t[i]===10);)i++;if(!c)continue;if(c==="trailer"||c.startsWith("trailer")||c==="railer"||c.startsWith("railer")){let u=c.startsWith("railer")?Math.max(0,a-1):a,h=yt(t,u+7),m=qt(t,h),p=m.entries.get("Prev"),x=A(p),g=x===null?null:Math.floor(x),b=zt(m);if(o.size===0&&g===null&&b===null)throw new Error("No valid xref entries found");return {entries:o,trailer:m,prevXRefOffset:g,offset:e,xrefStmOffset:b}}if(c==="%%EOF"||c.startsWith("startxref")){let u=new Uint8Array([116,114,97,105,108,101,114]),h=Ni(t,u,e,a);if(h!==-1){let m=yt(t,h+7),p=qt(t,m),x=p.entries.get("Prev"),g=A(x),b=g===null?null:Math.floor(g),P=zt(p);if(o.size===0&&b===null&&P===null)throw new Error("No valid xref entries found");return {entries:o,trailer:p,prevXRefOffset:b,offset:e,xrefStmOffset:P}}throw new Error("Reached EOF before trailer in traditional xref section")}let l=c.match(/^(\d+)\s+(\d+)$/);if(!l){if(/^\d+$/.test(c)){let u=new Uint8Array([116,114,97,105,108,101,114]),h=Jt(t,u,Math.max(0,a-1));if(h!==-1&&h-a<=256){let m=yt(t,h+7),p=qt(t,m),x=p.entries.get("Prev"),g=A(x),b=g===null?null:Math.floor(g),P=zt(p);if(o.size===0&&b===null&&P===null)throw new Error("No valid xref entries found");return {entries:o,trailer:p,prevXRefOffset:b,offset:e,xrefStmOffset:P}}continue}throw new Error(`Invalid xref subsection header: ${c}`)}let f=parseInt(l[1],10),d=parseInt(l[2],10);for(let u=0;u<d;u++){if(i+20>t.length)throw new Error(`Truncated xref at entry ${f+u}`);let h=i,m=n.decode(t.subarray(i,i+20));i+=20;let p=m.substring(0,10),x=m.substring(11,16),g=m[17],b=0,P=0,y="f";if(/^\d{10}$/.test(p)&&/^\d{5}$/.test(x)&&(g==="n"||g==="f"))b=parseInt(p,10),P=parseInt(x,10),y=g;else {i=h;let D=Gn(t,i);i=D.next;let v=0;for(;v<3&&D.line.trim()==="";)D=Gn(t,i),i=D.next,v++;let S=D.line.match(/^\s*(\d{10})\s+(\d{5})\s+([nf])\b/);if(!S)throw new Error(`Malformed fixed-width xref entry: ${m}`);b=parseInt(S[1],10),P=parseInt(S[2],10),y=S[3];}o.set(f+u,{type:"uncompressed",offset:b,genNum:P,inUse:y==="n"});}}throw new Error("trailer keyword not found after xref entries")}function Gi(t,e){let{stream:n,resolvedObj:r}=Xi(t,e),i=n.dict,s=Wi(i.entries.get("Type"));s!=="XRef"&&Hn("Resolved stream is not /Type /XRef",{offset:e,resolvedObj:r,type:s}),zn("Parsing xref stream",{offset:e,resolvedObj:r,type:s,wShape:Be(i.entries.get("W")),indexShape:Be(i.entries.get("Index")),sizeShape:Be(i.entries.get("Size"))});let o,a;{let D=i.entries.get("W"),v=i.entries.get("Size"),S=A(v),F=i.entries.get("Index");try{if(o=Kn(D,"W"),o.length!==3)throw new Error("/W must contain three integers");if(S===null)throw new Error("XRef stream missing /Size");if(a=F?Kn(F,"Index"):[0,Math.floor(S)],a.length%2!==0)throw new Error("/Index must have even number of elements")}catch(w){let C=w instanceof Error?w.message:String(w);throw Hn("Failed parsing /W or /Index in xref stream",{offset:e,resolvedObj:r,error:C,wShape:Be(D),indexShape:Be(F),sizeShape:Be(v)}),w}}let c=new Map,[l,f,d]=o,u=l+f+d,h=_.decodeStreamSync(n),m=0;for(let D=0;D<a.length;D+=2){let v=a[D],S=a[D+1];for(let F=0;F<S;F++){if(m+u>h.length)throw new Error("XRef stream data is shorter than expected from /W and /Index");let w=L=>{let $=0;for(let H=0;H<L;H++)$=$<<8|h[m++];return $},C=l===0?1:w(l),O=w(f),E=w(d),I=v+F;C===0?c.set(I,{type:"uncompressed",offset:0,genNum:E,inUse:false}):C===1?c.set(I,{type:"uncompressed",offset:O,genNum:E,inUse:true}):C===2&&c.set(I,{type:"compressed",streamNum:O,indexNum:E,genNum:0,inUse:true});}}let p=i.entries.get("Prev"),x=A(p),g=x===null?null:Math.floor(x),b=new Map(i.entries),P=new Set(["W","Index","Filter","DecodeParms","Length","Columns","Predictor","Type","DL"]);for(let D of P)b.delete(D);return {entries:c,trailer:{type:"dict",entries:b},prevXRefOffset:g,offset:e}}function Xi(t,e){let n=[0,-64,64,-256,256,-1024,1024,-4096,4096,-8192,8192],r=new Set,i=[],s=[];for(let o of n){let a=e+o;if(!(a<0||a>=t.length))try{let c=bt(t,a),l=`${c.objNum}.${c.genNum}`;if(r.has(l))continue;if(r.add(l),!U(c.object)){i.push(`offset ${a}: ${l} is not a stream`);continue}let f=c.object,d=f.dict.entries.has("W"),u=f.dict.entries.has("Size"),h=f.dict.entries.get("Type"),m=h&&typeof h=="object"&&"type"in h&&h.type==="name"?h.value:null,p=m==="XRef";if(d&&u)return zn("Resolved xref stream candidate",{requestedOffset:e,probeOffset:a,object:`${c.objNum} ${c.genNum} obj`,type:m}),{stream:f,resolvedObj:`${c.objNum} ${c.genNum} obj`};s.push(`offset ${a}: ${l} stream type=${m!=null?m:"unknown"} hasW=${d} hasSize=${u} isTypeXRef=${p}`);}catch(c){let l=c instanceof Error?c.message:String(c);i.push(`offset ${a}: ${l}`);}}throw new Error(`Could not resolve xref stream with /W and /Size near startxref ${e}. Non-xref streams: ${s.join(" || ")||"none"}. Failures: ${i.join(" || ")||"none"}`)}function Jn(t,e){let n=new Uint8Array([120,114,101,102]),r=yt(t,e);if(Zt(t,r,n))return et(t,r);let i=Vn(t,n,Math.max(0,e));if(i!==-1&&i-e<=2048)return et(t,i);let s=Yn(t,n,e,32768);if(s!==-1)return et(t,s);if(new TextDecoder("latin1").decode(t.subarray(e,Math.min(e+64,t.length))).trimStart().startsWith("xref"))return et(t,e);try{return Gi(t,e)}catch(a){let c=Yn(t,n,e,131072);if(c!==-1)return et(t,c);throw a}}function Qt(t){let e=[],n=new Set,r=[qn(t)];for(;r.length>0;){let i=r.shift();if(i===null||n.has(i))continue;n.add(i);let s=Jn(t,i);e.push(s),s.xrefStmOffset!=null&&r.push(s.xrefStmOffset),s.prevXRefOffset!=null&&r.push(s.prevXRefOffset);}return e}var Yi=new Uint8Array([40,191,78,94,78,117,138,65,100,0,78,86,255,250,1,8,46,46,0,182,208,104,62,128,47,12,169,254,100,83,105,122]);function en(t){let e=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],n=[3614090360,3905402710,606105819,3250441966,4118548399,1200080426,2821735955,4249261313,1770035416,2336552879,4294925233,2304563134,1804603682,4254626195,2792965006,1236535329,4129170786,3225465664,643717713,3921069994,3593408605,38016083,3634488961,3889429448,568446438,3275163606,4107603335,1163531501,2850285829,4243563512,1735328473,2368359562,4294588738,2272392833,1839030562,4259657740,2763975236,1272893353,4139469664,3200236656,681279174,3936430074,3572445317,76029189,3654602809,3873151461,530742520,3299628645,4096336452,1126891415,2878612391,4237533241,1700485571,2399980690,4293915773,2240044497,1873313359,4264355552,2734768916,1309151649,4149444226,3174756917,718787259,3951481745],r=1732584193,i=4023233417,s=2562383102,o=271733878,a=t.length,c=(56-(a+1)%64+64)%64,l=new Uint8Array(a+1+c+8);l.set(t),l[a]=128;let f=a*8;l[l.length-8]=f&255,l[l.length-7]=f>>>8&255,l[l.length-6]=f>>>16&255,l[l.length-5]=f>>>24&255;let d=new DataView(l.buffer);for(let m=0;m<l.length;m+=64){let p=r,x=i,g=s,b=o,P=new Uint32Array(16);for(let y=0;y<16;y++)P[y]=d.getUint32(m+y*4,true);for(let y=0;y<64;y++){let D,v;y<16?(D=x&g|~x&b,v=y):y<32?(D=b&x|~b&g,v=(5*y+1)%16):y<48?(D=x^g^b,v=(3*y+5)%16):(D=g^(x|~b),v=7*y%16);let S=b;b=g,g=x;let F=p+D+n[y]+P[v]|0;x=x+(F<<e[y]|F>>>32-e[y])|0,p=S;}r=r+p|0,i=i+x|0,s=s+g|0,o=o+b|0;}let u=new Uint8Array(16),h=new DataView(u.buffer);return h.setUint32(0,r,true),h.setUint32(4,i,true),h.setUint32(8,s,true),h.setUint32(12,o,true),u}function Hi(t,e){let n=new Uint8Array(256);for(let o=0;o<256;o++)n[o]=o;let r=0;for(let o=0;o<256;o++){r=(r+n[o]+t[o%t.length])%256;let a=n[o];n[o]=n[r],n[r]=a;}let i=new Uint8Array(e.length),s=0;r=0;for(let o=0;o<e.length;o++){s=(s+1)%256,r=(r+n[s])%256;let a=n[s];n[s]=n[r],n[r]=a,i[o]=e[o]^n[(n[s]+n[r])%256];}return i}var Oe=new Uint8Array([99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22]),Ki=new Uint8Array([82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125]);function Vi(t){let e=t.length/4,n=e+6,r=new Uint32Array(4*(n+1));for(let s=0;s<e;s++)r[s]=t[4*s]<<24|t[4*s+1]<<16|t[4*s+2]<<8|t[4*s+3];let i=[0,1,2,4,8,16,32,64,128,27,54];for(let s=e;s<4*(n+1);s++){let o=r[s-1];if(s%e===0){let a=o>>>24&255,c=o>>>16&255,l=o>>>8&255,f=o&255;o=Oe[c]<<24|Oe[l]<<16|Oe[f]<<8|Oe[a],o^=i[s/e]<<24;}else if(e>6&&s%e===4){let a=o>>>24&255,c=o>>>16&255,l=o>>>8&255,f=o&255;o=Oe[a]<<24|Oe[c]<<16|Oe[l]<<8|Oe[f];}r[s]=r[s-e]^o;}return r}function Zn(t){for(let e=0;e<16;e++)t[e]=Ki[t[e]];}function Qn(t){let e;e=t[13],t[13]=t[9],t[9]=t[5],t[5]=t[1],t[1]=e,e=t[2],t[2]=t[10],t[10]=e,e=t[6],t[6]=t[14],t[14]=e,e=t[3],t[3]=t[7],t[7]=t[11],t[11]=t[15],t[15]=e;}var zi=t=>(t<<1^(t>>>7&1)*27)&255;function se(t,e){let n=0,r=t;for(let i=0;i<8;i++)e>>>i&1&&(n^=r),r=zi(r);return n}function qi(t){for(let e=0;e<4;e++){let n=e*4,r=t[n],i=t[n+1],s=t[n+2],o=t[n+3];t[n]=se(r,14)^se(i,11)^se(s,13)^se(o,9),t[n+1]=se(r,9)^se(i,14)^se(s,11)^se(o,13),t[n+2]=se(r,13)^se(i,9)^se(s,14)^se(o,11),t[n+3]=se(r,11)^se(i,13)^se(s,9)^se(o,14);}}function tn(t,e,n){for(let r=0;r<4;r++){let i=e[n*4+r];t[r*4]^=i>>>24&255,t[r*4+1]^=i>>>16&255,t[r*4+2]^=i>>>8&255,t[r*4+3]^=i&255;}}function Ji(t,e,n){let r=new Uint8Array(16);r.set(t),tn(r,e,n);for(let i=n-1;i>=1;i--)Qn(r),Zn(r),tn(r,e,i),qi(r);return Qn(r),Zn(r),tn(r,e,0),r}function Zi(t,e){if(e.length<16)return e;let n=Vi(t),r=t.length/4+6,i=e.subarray(0,16),s=e.subarray(16),o=s.length/16,a=new Uint8Array(s.length),c=i;for(let f=0;f<o;f++){let d=f*16,u=s.subarray(d,d+16),h=Ji(u,n,r);for(let m=0;m<16;m++)a[d+m]=h[m]^c[m];c=u;}let l=a[a.length-1];if(l>0&&l<=16){let f=true;for(let d=a.length-l;d<a.length;d++)if(a[d]!==l){f=false;break}if(f)return a.subarray(0,a.length-l)}return a}var Pt=class{constructor(e,n){this.fileKey=new Uint8Array(0);this.v=0;this.r=0;this.isAes=false;this.parseEncryptDict(e,n);}parseEncryptDict(e,n){var b,P,y,D;let r=e.entries.get("V"),i=e.entries.get("R"),s=e.entries.get("Length"),o=e.entries.get("O"),a=e.entries.get("U"),c=e.entries.get("P"),l=e.entries.get("EncryptMetadata");this.v=(b=A(r))!=null?b:0,this.r=(P=A(i))!=null?P:0;let d=((y=A(s))!=null?y:40)/8,u=o&&"value"in o&&o.value instanceof Uint8Array?o.value:new Uint8Array(0),h=a&&"value"in a&&a.value instanceof Uint8Array?a.value:new Uint8Array(0),m=(D=A(c))!=null?D:0,p=l&&"value"in l?l.value:true,x=e.entries.get("CF"),g=e.entries.get("StmF");if(g&&"value"in g&&g.value==="AESV2")this.isAes=true;else if(x&&M(x)){let v=x.entries.get("StdCF");if(v&&M(v)){let S=v.entries.get("CFM");S&&"value"in S&&S.value==="AESV2"&&(this.isAes=true);}}(this.v===5||this.r===5||this.r===6)&&(this.isAes=true),this.fileKey=this.deriveFileKey(new Uint8Array(0),d,u,h,m,n,p);}deriveFileKey(e,n,r,i,s,o,a=true){let c=new Uint8Array(32);c.set(e.subarray(0,Math.min(32,e.length))),e.length<32&&c.set(Yi.subarray(0,32-e.length),e.length);let l=[];l.push(...c),l.push(...r),l.push(s&255),l.push(s>>>8&255),l.push(s>>>16&255),l.push(s>>>24&255),o&&o.length>0&&l.push(...o),this.r>=3&&!a&&l.push(255,255,255,255);let f=en(new Uint8Array(l));if(this.r>=3){let u=f.subarray(0,n);for(let h=0;h<50;h++)u=en(u).subarray(0,n);return u}return f.subarray(0,n)}deriveObjectKey(e,n){let r=new Uint8Array(5);r[0]=e&255,r[1]=e>>>8&255,r[2]=e>>>16&255,r[3]=n&255,r[4]=n>>>8&255;let i=new Uint8Array(this.fileKey.length+r.length+(this.isAes?4:0));i.set(this.fileKey),i.set(r,this.fileKey.length),this.isAes&&i.set([115,65,108,84],this.fileKey.length+r.length);let s=en(i),o=Math.min(16,this.fileKey.length+5);return s.subarray(0,o)}decrypt(e,n,r){return this.isAes?Zi(this.deriveObjectKey(n,r),e):Hi(this.deriveObjectKey(n,r),e)}};var Te=class{constructor(e){this.document=null;this.objectStreamCache=new Map;this.encryptRef=null;this.decryptionHandler=null;this.bytes=e;}parse(){if(this.document)return this.document;try{let e=this.extractVersion(),n=this.parseXRefTables();if(n.length===0)throw new Error("No valid xref tables found in PDF");let r=new Map;for(let a=n.length-1;a>=0;a--)for(let[c,l]of n[a].entries)r.set(c,l);let i=n[0].trailer,s=this.extractRootRef(i);this.document={rawBytes:this.bytes,xrefTables:new Map([[0,r]]),objectCache:new Map,rootRef:s,trailer:i,version:e};let o=i.entries.get("Encrypt");if(o){let a=null;if(q(o)){this.encryptRef=o;let c=this.loadObject(o);M(c)&&(a=c);}else M(o)&&(a=o);if(a){let c,l=i.entries.get("ID");if(l&&j(l)&&l.items.length>0){let f=l.items[0];Vt(f)&&(c=f.value);}this.decryptionHandler=new Pt(a,c);}}return this.document}catch(e){throw console.error("[ERROR] Parse failed:",e),e}}extractVersion(){let r=new TextDecoder().decode(this.bytes.subarray(0,20)).match(/%PDF-(\d+\.\d+)/);if(!r)throw new Error("Invalid PDF header - no %PDF-X.Y found");return r[1]}parseXRefTables(){return Qt(this.bytes)}extractRootRef(e){let n=e.entries.get("Root");if(!n)throw console.error("[ERROR] Trailer has no Root entry. Trailer entries:",Array.from(e.entries.keys())),new Error("Trailer missing /Root reference");if(typeof n!="object"||n.type!=="ref")throw console.error("[ERROR] Root is not a reference object:",n),new Error("Trailer /Root is not a valid reference");return n}loadObject(e){if(!this.document)throw new Error("Parse PDF first");let n=`${e.objNum}.${e.genNum}`;if(this.document.objectCache.has(n))return this.document.objectCache.get(n);let r=this.document.xrefTables.get(0);if(!r)throw new Error("No xref table found");let i=r.get(e.objNum);if(!i)throw new Error(`Object ${e.objNum} not found in xref`);if(i.type==="uncompressed"){if(!i.inUse)throw new Error(`Object ${e.objNum} is marked free in xref`);if(i.offset===0){let s={type:"dict",entries:new Map};throw this.document.objectCache.set(n,s),new Error(`Object ${e.objNum} has ghost xref entry (offset 0)`)}try{let{object:s,objectOffset:o}=bt(this.bytes,i.offset,e.objNum),a=U(s)?this.repairStreamBytesFromLengthRef(s,o):s,c=this.decryptObject(a,e.objNum,e.genNum);return this.document.objectCache.set(n,c),c}catch(s){console.warn(`[PDFParser] Failed to load object ${e.objNum}: ${s}`);let o={type:"dict",entries:new Map};throw this.document.objectCache.set(n,o),s}}else {if(!i.inUse)throw new Error(`Object ${e.objNum} is marked free in compressed xref entry`);let s=i.streamNum;if(!this.objectStreamCache.has(s)){let a=this.loadObjectStream(s,r);this.objectStreamCache.set(s,a);}let o=this.document.objectCache.get(n);if(!o)throw new Error(`Object ${e.objNum} not found in object stream ${s}`);return o}}loadObjectStream(e,n){var x,g;let r=n.get(e);if(!r||r.type!=="uncompressed"||!r.inUse)throw new Error(`Object stream ${e} not found or not in-use/uncompressed`);let i={type:"ref",objNum:e,genNum:0},s=this.loadObject(i);if(!U(s))throw new Error(`Object ${e} is not a stream`);let o=s.dict.entries.get("Type");if(!o||o.type!=="name"||o.value!=="ObjStm")throw new Error(`Object ${e} is not an /ObjStm`);let a=s.dict.entries.get("N"),c=s.dict.entries.get("First");if(!a||!gt(a)||!c||!gt(c))throw new Error(`Object stream ${e} missing numeric /N or /First`);let l=Math.floor(a.value),f=Math.floor(c.value);if(l<0||f<0)throw new Error(`Object stream ${e} has invalid /N or /First values`);let d=s,u;try{u=_.decodeStreamSync(d);}catch(b){let P=d.dict.entries.get("Filter"),y=d.dict.entries.get("Length"),D=(g=(x=d.rawBytes)!=null?x:d.data)!=null?g:new Uint8Array(0),v=Array.from(D.subarray(0,8)).map(C=>C.toString(16).padStart(2,"0")).join(" "),S=Math.max(0,D.length-8),F=Array.from(D.subarray(S)).map(C=>C.toString(16).padStart(2,"0")).join(" "),w=b instanceof Error?b.message:String(b);throw new Error(`Object stream ${e} decode failed: ${w}; Filter=${JSON.stringify(P)} Length=${JSON.stringify(y)} rawLen=${D.length} first8=[${v}] last8=[${F}]`)}if(f>u.length)throw new Error(`Object stream ${e} /First (${f}) exceeds decoded length (${u.length})`);let m=new TextDecoder("latin1").decode(u.subarray(0,f)).match(/\d+/g)||[];if(m.length<l*2)throw new Error(`Object stream ${e} header has ${m.length} numbers, expected at least ${l*2}`);let p=new Map;for(let b=0;b<l;b++){let P=parseInt(m[b*2],10),y=parseInt(m[b*2+1],10),D=f+y;if(!(!Number.isFinite(P)||!Number.isFinite(y)||y<0||D>u.length))try{let v=new Se(u.subarray(D)),S=he(v);p.set(P,S),this.document.objectCache.set(`${P}.0`,S);}catch(v){console.warn(`[WARN] Failed to parse object ${P} from object stream ${e}:`,v);}}return p}repairStreamBytesFromLengthRef(e,n){var l,f;let r=e.dict.entries.get("Length");if(!r||!q(r))return e;let i=null;try{let d=this.loadObject(r);i=A(d);}catch{return e}if(i===null)return e;let s=Math.max(0,Math.floor(i)),o=this.findStreamDataStart(n);if(o<0||o+s>this.bytes.length)return e;let a=(l=e.rawBytes)!=null?l:e.data;if(a&&a.length===s)return e;let c=this.bytes.subarray(o,o+s);return console.warn(`[PDFParser] Repaired stream bytes via indirect /Length at offset ${n}: resolved length=${s}, previous length=${(f=a==null?void 0:a.length)!=null?f:0}`),{type:"stream",dict:e.dict,rawBytes:c,data:c,decode:_.createLazyDecoder(e.dict,c)}}findStreamDataStart(e){let n=[115,116,114,101,97,109],r=Math.min(this.bytes.length-n.length,e+1024*1024);for(let i=Math.max(0,e);i<=r;i++){let s=true;for(let d=0;d<n.length;d++)if(this.bytes[i+d]!==n[d]){s=false;break}if(!s)continue;let o=i>0?this.bytes[i-1]:32,a=this.bytes[i+n.length];if(!(o===10||o===13||o===32||o===9||o===62)||!(a===10||a===13||a===32||a===9))continue;let f=i+n.length;return this.bytes[f]===13&&this.bytes[f+1]===10?f+=2:(this.bytes[f]===10||this.bytes[f]===13)&&(f+=1),f}return -1}decryptObject(e,n,r){return !this.decryptionHandler||this.encryptRef&&n===this.encryptRef.objNum?e:this.decryptObjectRecursive(e,n,r)}decryptObjectRecursive(e,n,r){var i,s;if(!this.decryptionHandler)return e;if(e.type==="string"){let o=this.decryptionHandler.decrypt(e.value,n,r);return {...e,value:o}}if(e.type==="array")return {...e,items:e.items.map(o=>this.decryptObjectRecursive(o,n,r))};if(e.type==="dict"){let o=new Map;for(let[a,c]of e.entries)o.set(a,this.decryptObjectRecursive(c,n,r));return {...e,entries:o}}if(e.type==="stream"){let o=(s=(i=e.rawBytes)!=null?i:e.data)!=null?s:new Uint8Array(0),a=o.length>0?this.decryptionHandler.decrypt(o,n,r):o,c=this.decryptObjectRecursive(e.dict,n,r);return {type:"stream",dict:c,rawBytes:a,data:a,decode:_.createLazyDecoder(c,a)}}return e}};function tt(t){if(!t)return [];if(q(t))return [t];if(j(t)){let e=[];for(let n of t.items)e.push(...tt(n));return e}return []}function Qi(t){if(t.length===0)return new Uint8Array(0);let e=Math.max(0,t.length-1),n=t.reduce((s,o)=>s+o.length,0)+e,r=new Uint8Array(n),i=0;for(let s=0;s<t.length;s++)r.set(t[s],i),i+=t[s].length,s<t.length-1&&(r[i]=32,i+=1);return r}async function er(t,e){let n=tt(t);if(n.length===0)return {combinedBytes:new Uint8Array(0),streamCount:0,streamByteLengths:[]};let r=[];for(let i of n){let s=await Promise.resolve(e(i));if(!U(s)){console.warn(`[WARN] Contents ref ${i.objNum} ${i.genNum} R is not a stream, skipping`);continue}try{let o=s.decode?await s.decode():await _.decodeStream(s);r.push(o);}catch(o){throw console.error(`[ContentStreamLoader] Failed to decode stream ${i.objNum} ${i.genNum} R:`,o),o}}return {combinedBytes:Qi(r),streamCount:r.length,streamByteLengths:r.map(i=>i.length)}}function Ue(t){return Ye(t).commands}function Ye(t){let e=new Se(t),n=[],r=[],i=[],s=-1;for(;e.skipWhitespace(),!(e.getPosition()>=t.length);){let o=e.getPosition(),a=t[o];if(rr(a)){let c=e.readWord();if(!c)break;if(c==="BI"){let f=ts(e,t);f?(n.push(f.command),r.push({start:o,end:f.end})):(n.push({op:"unknown",keyword:"BI",operands:[]}),r.push({start:o,end:e.getPosition()})),i.length=0,s=-1;continue}let l=ns(c,i);l&&(n.push(l),r.push({start:s>=0?s:o,end:e.getPosition()})),i.length=0,s=-1;}else {s<0&&(s=o);try{let c=he(e);i.push(c);}catch{e.setPosition(o+1);}}}return {commands:n,ranges:r}}function rr(t){return t>=65&&t<=90||t>=97&&t<=122||t===39||t===34}var Dt=t=>t===32||t===10||t===13||t===9||t===12||t===0,tr=t=>t===47||t===60||t===62||t===91||t===93||t===40||t===41||t===37||t===123||t===125,es=t=>{var r,i;let e=(r=t.entries.get("IM"))!=null?r:t.entries.get("ImageMask");if(e&&"type"in e&&e.type==="boolean"&&e.value)return 1;let n=(i=t.entries.get("CS"))!=null?i:t.entries.get("ColorSpace");if(!n||!("type"in n)||n.type!=="name")return 1;switch(n.value){case "RGB":case "DeviceRGB":case "CalRGB":return 3;case "CMYK":case "DeviceCMYK":return 4;default:return 1}};function ts(t,e){var n,r,i,s,o;try{let a=new Map;for(;;){t.skipWhitespace();let g=t.getPosition();if(g>=e.length)return null;let b=e[g];if(b===47){let P=he(t);if(!P||!("type"in P)||P.type!=="name")return null;t.skipWhitespace(),a.set(P.value,he(t));}else if(rr(b)){if(t.readWord()==="ID")break;return null}else return null}let c={type:"dict",entries:a},l=t.getPosition();Dt(e[l])&&(l+=e[l]===13&&e[l+1]===10?2:1);let f=(n=a.get("L"))!=null?n:a.get("Length"),d=A(f),u=a.has("F")||a.has("Filter"),h=-1;if(d!==null&&d>=0&&l+d<=e.length)h=l+d;else if(!u){let g=A((r=a.get("W"))!=null?r:a.get("Width")),b=A((i=a.get("H"))!=null?i:a.get("Height")),P=(o=A((s=a.get("BPC"))!=null?s:a.get("BitsPerComponent")))!=null?o:8;if(g!==null&&b!==null&&g>0&&b>0){let y=Math.ceil(g*P*es(c)/8)*b;l+y<=e.length&&(h=l+y);}}if(h<0){for(let g=l;g+1<e.length;g++){if(e[g]!==69||e[g+1]!==73||g>l&&!Dt(e[g-1]))continue;let b=e[g+2];if(!(b!==void 0&&!Dt(b)&&!tr(b))){h=Math.max(l,g-1);break}}if(h<0)return null}let m=new Uint8Array(e.subarray(l,h));t.setPosition(h),t.skipWhitespace();let p=t.getPosition();if(e[p]!==69||e[p+1]!==73)return null;let x=e[p+2];return x!==void 0&&!Dt(x)&&!tr(x)?null:(t.setPosition(p+2),{command:{op:"inline_image",params:c,data:m},end:p+2})}catch{return null}}function ns(t,e){switch(t){case "q":return {op:"save_state"};case "Q":return {op:"restore_state"};case "cm":return {op:"set_ctm",matrix:nr(e)};case "w":return {op:"set_line_width",width:k(e,0)};case "J":return {op:"set_line_cap",cap:Math.floor(k(e,0))};case "j":return {op:"set_line_join",join:Math.floor(k(e,0))};case "M":return {op:"set_miter_limit",limit:k(e,0)};case "d":return {op:"set_dash",array:rs(e,0),phase:k(e,1)};case "ri":return {op:"set_rendering_intent",intent:Fe(e,0)};case "gs":return {op:"set_graphics_state",name:Fe(e,0)};case "rg":return {op:"set_fill_color_rgb",r:k(e,0),g:k(e,1),b:k(e,2)};case "RG":return {op:"set_stroke_color_rgb",r:k(e,0),g:k(e,1),b:k(e,2)};case "g":return {op:"set_fill_gray",gray:k(e,0)};case "G":return {op:"set_stroke_gray",gray:k(e,0)};case "k":return {op:"set_fill_cmyk",c:k(e,0),m:k(e,1),y:k(e,2),k:k(e,3)};case "K":return {op:"set_stroke_cmyk",c:k(e,0),m:k(e,1),y:k(e,2),k:k(e,3)};case "cs":return {op:"set_fill_color_space",name:Fe(e,0)};case "CS":return {op:"set_stroke_color_space",name:Fe(e,0)};case "sc":case "scn":{let n=e[e.length-1],r=n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:void 0;return {op:"set_fill_color",values:(r?e.slice(0,-1):e).map(wt),patternName:r}}case "SC":case "SCN":{let n=e[e.length-1],r=n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:void 0;return {op:"set_stroke_color",values:(r?e.slice(0,-1):e).map(wt),patternName:r}}case "m":return {op:"move_to",x:k(e,0),y:k(e,1)};case "l":return {op:"line_to",x:k(e,0),y:k(e,1)};case "c":return {op:"curve_to",x1:k(e,0),y1:k(e,1),x2:k(e,2),y2:k(e,3),x3:k(e,4),y3:k(e,5)};case "v":return {op:"curve_to_v",x2:k(e,0),y2:k(e,1),x3:k(e,2),y3:k(e,3)};case "y":return {op:"curve_to",x1:k(e,0),y1:k(e,1),x2:k(e,2),y2:k(e,3),x3:k(e,2),y3:k(e,3)};case "re":return {op:"rect",x:k(e,0),y:k(e,1),w:k(e,2),h:k(e,3)};case "h":return {op:"close_path"};case "S":return {op:"stroke"};case "s":return {op:"close_stroke"};case "f":case "F":return {op:"fill"};case "f*":return {op:"fill_even_odd"};case "B":return {op:"fill_stroke"};case "B*":return {op:"fill_stroke_even_odd"};case "b":return {op:"close_fill_stroke"};case "b*":return {op:"close_fill_stroke_even_odd"};case "n":return {op:"end_path"};case "W":return {op:"clip"};case "W*":return {op:"clip_even_odd"};case "BT":return {op:"begin_text"};case "ET":return {op:"end_text"};case "Tf":return {op:"set_font",name:Fe(e,0),size:k(e,1)};case "Td":return {op:"move_text",tx:k(e,0),ty:k(e,1)};case "TD":return {op:"move_text_set_leading",tx:k(e,0),ty:k(e,1)};case "Tm":return {op:"set_text_matrix",matrix:nr(e)};case "T*":return {op:"next_line"};case "Tc":return {op:"set_char_spacing",spacing:k(e,0)};case "Tw":return {op:"set_word_spacing",spacing:k(e,0)};case "Tz":return {op:"set_horiz_scale",scale:k(e,0)};case "TL":return {op:"set_leading",leading:k(e,0)};case "Tr":return {op:"set_text_render",mode:k(e,0)};case "Ts":return {op:"set_text_rise",rise:k(e,0)};case "Tj":return {op:"show_string",data:nn(e,0)};case "TJ":return {op:"show_strings",items:is(e,0)};case "'":return {op:"next_line_show_string",data:nn(e,0)};case '"':return {op:"set_spacing_next_line_show_string",wordSpacing:k(e,0),charSpacing:k(e,1),data:nn(e,2)};case "d0":return {op:"type3_glyph_width",wx:k(e,0),wy:k(e,1)};case "d1":return {op:"type3_glyph_width",wx:k(e,0),wy:k(e,1)};case "sh":return {op:"shade",name:Fe(e,0)};case "Do":return {op:"xobject",name:Fe(e,0)};case "BMC":return {op:"begin_marked_content",tag:Fe(e,0)};case "BDC":{let n=e[1];return {op:"begin_marked_content",tag:Fe(e,0),properties:M(n)?n:void 0}}case "EMC":return {op:"end_marked_content"};case "MP":case "DP":case "BX":case "EX":return null;default:return {op:"unknown",keyword:t,operands:[...e]}}}function k(t,e){return wt(t[e])}function wt(t){let e=A(t);return e===null?0:e}function Fe(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="name"?n.value:""}function nn(t,e){let n=t[e];return n&&typeof n=="object"&&"type"in n&&n.type==="string"?n.value:new Uint8Array(0)}function rs(t,e){let n=t[e];return j(n)?n.items.map(wt):[]}function is(t,e){let n=t[e];return j(n)?n.items.map(r=>{let i=A(r);return i!==null?i:r&&typeof r=="object"&&"type"in r&&r.type==="string"?r.value:0}):[]}function nr(t){return [k(t,0),k(t,1),k(t,2),k(t,3),k(t,4),k(t,5)]}var St=()=>({ctm:[1,0,0,1,0,0],font:"",fontSize:12,charSpacing:0,wordSpacing:0,horizScale:100,leading:0,textRise:0,textRenderMode:0,textMatrix:[1,0,0,1,0,0],textLineMatrix:[1,0,0,1,0,0],fillColorSpace:"DeviceGray",strokeColorSpace:"DeviceGray",fillColor:{space:"gray",gray:0},strokeColor:{space:"gray",gray:0},fillPatternName:null,strokePatternName:null,fillPattern:null,strokePattern:null,lineWidth:1,lineCap:0,lineJoin:0,miterLimit:10,dashArray:[],dashPhase:0,fillAlpha:1,strokeAlpha:1,blendMode:"Normal"});var Y=(t,e)=>{let[n,r,i,s,o,a]=t,[c,l,f,d,u,h]=e;return [n*c+i*l,r*c+s*l,n*f+i*d,r*f+s*d,n*u+i*h+o,r*u+s*h+a]};var He=t=>{let e=t[0]*t[3]-t[1]*t[2];if(!Number.isFinite(e)||Math.abs(e)<1e-12)return null;let n=t[3]/e,r=-t[1]/e,i=-t[2]/e,s=t[0]/e;return [n,r,i,s,-(n*t[4]+i*t[5]),-(r*t[4]+s*t[5])]};var ir=t=>t===" "||t===" "||t==="\r"||t===`
2
+ `||t==="\f"||t==="\0";function or(t){let e=[],n=[e],r=0;for(;r<t.length;){let i=t[r];if(ir(i)){r++;continue}if(i==="%"){for(;r<t.length&&t[r]!==`
3
+ `&&t[r]!=="\r";)r++;continue}if(i==="{"){let c=[];n[n.length-1].push(c),n.push(c),r++;continue}if(i==="}"){if(n.length===1)throw new Error("Unbalanced } in PostScript function");n.pop(),r++;continue}let s=r;for(;s<t.length&&!ir(t[s])&&t[s]!=="{"&&t[s]!=="}"&&t[s]!=="%";)s++;let o=t.slice(r,s);r=s;let a=Number(o);Number.isFinite(a)&&/^[-+.0-9eE]+$/.test(o)?n[n.length-1].push(a):n[n.length-1].push(o.toLowerCase());}if(n.length!==1)throw new Error("Unbalanced { in PostScript function");return e.length===1&&Array.isArray(e[0])?e[0]:e}var rn=Math.PI/180;function N(t,e){if(typeof t!="number")throw new Error(`${e}: expected number`);return t}function ie(t,e){if(typeof t!="number")throw new Error(`${e}: expected integer`);return Math.trunc(t)}function sr(t,e){if(typeof t!="boolean")throw new Error(`${e}: expected boolean`);return t}function ar(t,e,n){let r=[...e],i=0,s=d=>{if(r.length>=100)throw new Error("PostScript stack overflow");r.push(d);},o=d=>{let u=r.pop();if(u===void 0)throw new Error(`${d}: stack underflow`);return u},a=d=>{let u=o(d);if(!Array.isArray(u))throw new Error(`${d}: expected procedure`);return u},c=d=>{for(let u of d){if(++i>1e4)throw new Error("PostScript op budget exceeded");if(typeof u=="number"){s(u);continue}if(Array.isArray(u)){s(u);continue}switch(u){case "add":{let h=N(o(u),u),m=N(o(u),u);s(m+h);break}case "sub":{let h=N(o(u),u),m=N(o(u),u);s(m-h);break}case "mul":{let h=N(o(u),u),m=N(o(u),u);s(m*h);break}case "div":{let h=N(o(u),u),m=N(o(u),u);s(h===0?0:m/h);break}case "idiv":{let h=ie(o(u),u),m=ie(o(u),u);s(h===0?0:Math.trunc(m/h));break}case "mod":{let h=ie(o(u),u),m=ie(o(u),u);s(h===0?0:m%h);break}case "neg":s(-N(o(u),u));break;case "abs":s(Math.abs(N(o(u),u)));break;case "ceiling":s(Math.ceil(N(o(u),u)));break;case "floor":s(Math.floor(N(o(u),u)));break;case "round":s(Math.round(N(o(u),u)));break;case "truncate":s(Math.trunc(N(o(u),u)));break;case "sqrt":s(Math.sqrt(Math.max(0,N(o(u),u))));break;case "sin":s(Math.sin(N(o(u),u)*rn));break;case "cos":s(Math.cos(N(o(u),u)*rn));break;case "atan":{let h=N(o(u),u),m=N(o(u),u),p=Math.atan2(m,h)/rn;p<0&&(p+=360),s(p);break}case "exp":{let h=N(o(u),u),m=N(o(u),u);s(Math.pow(m,h));break}case "ln":s(Math.log(Math.max(Number.MIN_VALUE,N(o(u),u))));break;case "log":s(Math.log10(Math.max(Number.MIN_VALUE,N(o(u),u))));break;case "cvi":s(Math.trunc(N(o(u),u)));break;case "cvr":s(N(o(u),u));break;case "eq":{let h=o(u),m=o(u);s(m===h);break}case "ne":{let h=o(u),m=o(u);s(m!==h);break}case "gt":{let h=N(o(u),u),m=N(o(u),u);s(m>h);break}case "ge":{let h=N(o(u),u),m=N(o(u),u);s(m>=h);break}case "lt":{let h=N(o(u),u),m=N(o(u),u);s(m<h);break}case "le":{let h=N(o(u),u),m=N(o(u),u);s(m<=h);break}case "and":{let h=o(u),m=o(u);s(typeof m=="boolean"&&typeof h=="boolean"?m&&h:ie(m,u)&ie(h,u));break}case "or":{let h=o(u),m=o(u);s(typeof m=="boolean"&&typeof h=="boolean"?m||h:ie(m,u)|ie(h,u));break}case "xor":{let h=o(u),m=o(u);s(typeof m=="boolean"&&typeof h=="boolean"?m!==h:ie(m,u)^ie(h,u));break}case "not":{let h=o(u);s(typeof h=="boolean"?!h:~ie(h,u));break}case "bitshift":{let h=ie(o(u),u),m=ie(o(u),u);s(h>=0?m<<h:m>>-h);break}case "true":s(true);break;case "false":s(false);break;case "pop":o(u);break;case "exch":{let h=o(u),m=o(u);s(h),s(m);break}case "dup":{let h=o(u);s(h),s(h);break}case "copy":{let h=ie(o(u),u);if(h<0||h>r.length)throw new Error("copy: bad count");let m=r.length-h;for(let p=0;p<h;p++)s(r[m+p]);break}case "index":{let h=ie(o(u),u);if(h<0||h>=r.length)throw new Error("index: out of range");s(r[r.length-1-h]);break}case "roll":{let h=ie(o(u),u),m=ie(o(u),u);if(m<0||m>r.length)throw new Error("roll: bad count");if(m>0&&h!==0){let p=r.splice(r.length-m,m),x=(h%m+m)%m;r.push(...p.slice(m-x),...p.slice(0,m-x));}break}case "if":{let h=a(u);sr(o(u),u)&&c(h);break}case "ifelse":{let h=a(u),m=a(u),p=sr(o(u),u);c(p?m:h);break}default:throw new Error(`Unknown PostScript operator: ${u}`)}}};c(t);let l=Math.floor(n.length/2);if(r.length<l)throw new Error("PostScript function returned too few values");return r.slice(r.length-l).map((d,u)=>{if(typeof d!="number"&&typeof d!="boolean")throw new Error("PostScript function returned a non-numeric value");let h=typeof d=="number"?d:d?1:0,m=n[u*2],p=n[u*2+1];return Math.max(m,Math.min(p,h))})}var Ft=A,De=t=>!t||!j(t)?null:t.items.map(e=>{var n;return (n=Ft(e))!=null?n:0}),oe=(t,e)=>{if(t){if(!q(t))return t;try{return e(t)}catch{return}}},cr=new WeakMap,ss=(t,e,n)=>{var c;let r=e*n,i=r>>3,s=r&7,o=n,a=0;for(;o>0;){let l=8-s,f=Math.min(l,o),u=((c=t[i])!=null?c:0)>>l-f&(1<<f)-1;a=a*(1<<f)+u,o-=f,s+=f,s===8&&(s=0,i++);}return a},os=(t,e)=>t.map((n,r)=>{let i=e[r*2],s=e[r*2+1];return i===void 0||s===void 0?n:Math.max(i,Math.min(s,n))}),vt=(t,e,n)=>{var l,f,d,u,h,m,p,x,g,b,P,y,D,v,S,F,w,C,O,E,I,L,$,H,Z,ae;let r=oe(t,n);if(!r)return null;let i=U(r)?r.dict:M(r)?r:null;if(!i)return null;let s=Math.floor((l=Ft(oe(i.entries.get("FunctionType"),n)))!=null?l:-1),o=(f=De(oe(i.entries.get("Domain"),n)))!=null?f:[0,1],a=Math.max(1,Math.floor(o.length/2)),c=[];for(let T=0;T<a;T++){let B=(d=e[T])!=null?d:0,W=(u=o[T*2])!=null?u:0,G=(h=o[T*2+1])!=null?h:1;c.push(Math.max(Math.min(W,G),Math.min(Math.max(W,G),B)));}if(s===2){let T=(m=Ft(oe(i.entries.get("N"),n)))!=null?m:1,B=(p=De(oe(i.entries.get("C0"),n)))!=null?p:[0],W=(x=De(oe(i.entries.get("C1"),n)))!=null?x:[1],G=Math.pow(c[0],T);return B.map((fe,ee)=>{var te;return fe+G*(((te=W[ee])!=null?te:1)-fe)})}if(s===0){if(!U(r))return null;let T=((g=De(oe(i.entries.get("Size"),n)))!=null?g:[2]).map(K=>Math.max(1,Math.floor(K)));if(T.length<a||a>8)return null;let B=Math.floor((b=Ft(oe(i.entries.get("BitsPerSample"),n)))!=null?b:8);if(![1,2,4,8,12,16,24,32].includes(B))return null;let W=De(oe(i.entries.get("Range"),n));if(!W||W.length<2)return null;let G=Math.floor(W.length/2),fe=[];for(let K=0;K<a;K++)fe.push(0,T[K]-1);let ee=(P=De(oe(i.entries.get("Encode"),n)))!=null?P:fe,te=(y=De(oe(i.entries.get("Decode"),n)))!=null?y:W,Me=B===32?4294967295:(1<<B)-1,xe;try{xe=_.decodeStreamSync(r);}catch{return null}let pe=[],ke=[];for(let K=0;K<a;K++){let ce=(D=o[K*2])!=null?D:0,be=(v=o[K*2+1])!=null?v:1,Q=(S=ee[K*2])!=null?S:0,Qe=(F=ee[K*2+1])!=null?F:T[K]-1,ht=be!==ce?(c[K]-ce)/(be-ce):0,En=Math.max(0,Math.min(T[K]-1,Q+ht*(Qe-Q))),jn=Math.min(T[K]-1,Math.floor(En));pe.push(jn),ke.push(Math.max(0,Math.min(1,En-jn)));}let ge=[],Ze=1;for(let K=0;K<a;K++)ge.push(Ze),Ze*=T[K];let X=new Array(G).fill(0),de=1<<a;for(let K=0;K<de;K++){let ce=1,be=0;for(let Q=0;Q<a;Q++)if(K>>Q&1){if(ke[Q]===0){ce=0;break}ce*=ke[Q],be+=Math.min(T[Q]-1,pe[Q]+1)*ge[Q];}else ce*=1-ke[Q],be+=pe[Q]*ge[Q];if(ce!==0)for(let Q=0;Q<G;Q++)X[Q]+=ce*ss(xe,be*G+Q,B);}let dt=X.map((K,ce)=>{var Qe,ht;let be=(Qe=te[ce*2])!=null?Qe:0,Q=(ht=te[ce*2+1])!=null?ht:1;return be+K/Me*(Q-be)});return os(dt,W)}if(s===3){let T=(w=De(oe(i.entries.get("Bounds"),n)))!=null?w:[],B=(C=De(oe(i.entries.get("Encode"),n)))!=null?C:[],W=oe(i.entries.get("Functions"),n);if(!W||!j(W))return null;let G=W.items,fe=c[0],ee=0;for(let ge=0;ge<T.length&&fe>=T[ge];ge++)ee=ge+1;let te=ee===0?(O=o[0])!=null?O:0:(I=(E=T[ee-1])!=null?E:o[0])!=null?I:0,Me=ee<T.length?($=(L=T[ee])!=null?L:o[1])!=null?$:1:(H=o[1])!=null?H:1,xe=(Z=B[ee*2])!=null?Z:0,pe=(ae=B[ee*2+1])!=null?ae:1,ke=te===Me?xe:xe+(fe-te)/(Me-te)*(pe-xe);return vt(G[ee],[ke],n)}if(s===4){if(!U(r))return null;let T=De(oe(i.entries.get("Range"),n));if(!T||T.length<2)return null;try{let B=cr.get(r);if(!B){let W=new TextDecoder("latin1").decode(_.decodeStreamSync(r));B=or(W),cr.set(r,B);}return ar(B,c,T)}catch{return null}}return null},Ct=(t,e,n)=>vt(t,[e],n),sn=(t,e,n)=>{let r=oe(t,n);if(!r)return null;if(j(r)){let i=[];for(let s of r.items){let o=vt(s,e,n);if(!o)return null;i.push(...o);}return i}return vt(r,e,n)};var lr=t=>Math.max(1,Math.min(2048,Math.ceil(t)));function ur(t,e,n,r){if(![...t,e,n,...r].every(Number.isFinite)||Math.abs(e)<1e-9||Math.abs(n)<1e-9)return null;let i=Math.hypot(r[0],r[1]),s=Math.hypot(r[2],r[3]);if(i<1e-12||s<1e-12)return null;let o=lr(Math.abs(e)*i),a=lr(Math.abs(n)*s),[c,l]=t,f=[o/e,0,0,-a/n,-c*o/e,(l+n)*a/n],d=He(f);return d?{cellPxW:o,cellPxH:a,contentTransform:f,paintTransform:d}:null}var Ke=5e4,an=class{constructor(e){this.bytes=e;this.bitPos=0;}get hasData(){return this.bitPos<this.bytes.length*8}get remainingBits(){return Math.max(0,this.bytes.length*8-this.bitPos)}read(e){var i;let n=0,r=e;for(;r>0;){let s=this.bitPos>>3,a=8-(this.bitPos&7),c=Math.min(a,r),f=((i=this.bytes[s])!=null?i:0)>>a-c&(1<<c)-1;n=n*(1<<c)+f,this.bitPos+=c,r-=c;}return n}alignToByte(){this.bitPos=this.bitPos+7&-8;}},as=t=>t>=32?4294967295:(1<<t)-1,on=(t,e,n,r)=>n+t/as(e)*(r-n);function fr(t,e,n,r){var y;let i=new an(n),s=[],{bitsPerCoordinate:o,bitsPerComponent:a,bitsPerFlag:c,decode:l,numColorComponents:f}=e;if(l.length<4+f*2)return [];let d=()=>[on(i.read(o),o,l[0],l[1]),on(i.read(o),o,l[2],l[3])],u=()=>{let D=[];for(let v=0;v<f;v++)D.push(on(i.read(a),a,l[4+v*2],l[5+v*2]));return r(D)},h=2*o+f*a;if(t===4){let D=c+h,v=null,S=null,F=null,w=()=>{let C=i.read(c),[O,E]=d(),I=u();return i.alignToByte(),{flag:C,v:{x:O,y:E,color:I}}};for(;i.remainingBits>=D&&s.length<Ke;){let C=w();if(C.flag===0||v===null||S===null||F===null){if(v=C.v,i.remainingBits<D||(S=w().v,i.remainingBits<D))break;F=w().v;}else C.flag===1?(v=S,S=F,F=C.v):(S=F,F=C.v);nt(s,v,S,F);}return s}if(t===5){let D=Math.max(2,Math.floor((y=e.verticesPerRow)!=null?y:2)),v=[];for(;i.remainingBits>=D*h;){let S=[];for(let F=0;F<D;F++){let[w,C]=d();S.push({x:w,y:C,color:u()});}if(v.push(S),v.length*D>Ke)break}for(let S=0;S+1<v.length&&s.length<Ke;S++)for(let F=0;F+1<D&&s.length<Ke;F++)nt(s,v[S][F],v[S][F+1],v[S+1][F]),nt(s,v[S][F+1],v[S+1][F+1],v[S+1][F]);return s}let m=t===6?12:16,p=t===6?8:12,x=null,g=null,b=m*2*o+4*f*a,P=p*2*o+2*f*a;for(;i.remainingBits>=c+P&&s.length<Ke;){let D=i.read(c),v,S;if(D===0||!x||!g){if(i.remainingBits<b)break;v=[];for(let F=0;F<m;F++)v.push(d());S=[u(),u(),u(),u()];}else {let F=[];for(let I=0;I<p;I++)F.push(d());let w=u(),C=u(),O,E;D===1?(O=[x[3],x[4],x[5],x[6]],E=[g[1],g[2]]):D===2?(O=[x[6],x[7],x[8],x[9]],E=[g[2],g[3]]):(O=[x[9],x[10],x[11],x[0]],E=[g[3],g[0]]),v=[...O,...F],S=[E[0],E[1],w,C];}if(!Number.isFinite(v[0][0]))break;ls(s,v,S),x=v,g=S;}return s}var nt=(t,e,n,r)=>{t.push({p:[[e.x,e.y],[n.x,n.y],[r.x,r.y]],c:[e.color,n.color,r.color]});},At=(t,e,n,r,i)=>{let s=1-i,o=s*s*s,a=3*s*s*i,c=3*s*i*i,l=i*i*i;return [o*t[0]+a*e[0]+c*n[0]+l*r[0],o*t[1]+a*e[1]+c*n[1]+l*r[1]]},cs=6,ls=(t,e,n)=>{let[r,i,s,o,a,c,l,f,d,u,h,m]=e,[p,x,g,b]=n,P=(S,F)=>{let w=At(r,i,s,o,F),C=At(u,d,f,l,F),O=At(r,m,h,u,S),E=At(o,a,c,l,S),I=(1-S)*w[0]+S*C[0]+(1-F)*O[0]+F*E[0]-((1-S)*(1-F)*r[0]+S*(1-F)*u[0]+(1-S)*F*o[0]+S*F*l[0]),L=(1-S)*w[1]+S*C[1]+(1-F)*O[1]+F*E[1]-((1-S)*(1-F)*r[1]+S*(1-F)*u[1]+(1-S)*F*o[1]+S*F*l[1]);return [I,L]},y=(S,F)=>[(1-S)*(1-F)*p[0]+(1-S)*F*x[0]+S*F*g[0]+S*(1-F)*b[0],(1-S)*(1-F)*p[1]+(1-S)*F*x[1]+S*F*g[1]+S*(1-F)*b[1],(1-S)*(1-F)*p[2]+(1-S)*F*x[2]+S*F*g[2]+S*(1-F)*b[2]],D=cs,v=[];for(let S=0;S<=D;S++){let F=[];for(let w=0;w<=D;w++){let C=w/D,O=S/D,[E,I]=P(C,O);F.push({x:E,y:I,color:y(C,O)});}v.push(F);}for(let S=0;S<D;S++)for(let F=0;F<D;F++){if(t.length+2>Ke)return;nt(t,v[S][F],v[S][F+1],v[S+1][F]),nt(t,v[S][F+1],v[S+1][F+1],v[S+1][F]);}};function dr(t,e,n,r){let i=new Uint8ClampedArray(n*r*4),s=(o,a)=>[e[0]*o+e[2]*a+e[4],e[1]*o+e[3]*a+e[5]];for(let o of t){let[a,c,l]=o.p.map(([p,x])=>s(p,x)),f=(c[0]-a[0])*(l[1]-a[1])-(c[1]-a[1])*(l[0]-a[0]);if(Math.abs(f)<1e-9)continue;let d=Math.max(0,Math.floor(Math.min(a[0],c[0],l[0]))),u=Math.min(n-1,Math.ceil(Math.max(a[0],c[0],l[0]))),h=Math.max(0,Math.floor(Math.min(a[1],c[1],l[1]))),m=Math.min(r-1,Math.ceil(Math.max(a[1],c[1],l[1])));for(let p=h;p<=m;p++)for(let x=d;x<=u;x++){let g=x+.5,b=p+.5,P=((c[0]-g)*(l[1]-b)-(c[1]-b)*(l[0]-g))/f,y=((l[0]-g)*(a[1]-b)-(l[1]-b)*(a[0]-g))/f,D=1-P-y;if(P<-1e-6||y<-1e-6||D<-1e-6)continue;let v=(p*n+x)*4;i[v]=255*(P*o.c[0][0]+y*o.c[1][0]+D*o.c[2][0]),i[v+1]=255*(P*o.c[0][1]+y*o.c[1][1]+D*o.c[2][1]),i[v+2]=255*(P*o.c[0][2]+y*o.c[1][2]+D*o.c[2][2]),i[v+3]=255;}}return i}var us=12,fs=(t,e,n)=>t.minX-n<=e.maxX&&e.minX-n<=t.maxX&&t.minY-n<=e.maxY&&e.minY-n<=t.maxY,ds=(t,e)=>({minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)});function hr(t,e,n,r){if(!t.length)return [];let i=Math.max(2,.01*Math.hypot(n,r)),s=[...e].sort((f,d)=>f-d),o=(f,d)=>{let u=0,h=s.length-1;for(;u<=h;){let m=u+h>>1,p=s[m];if(p<=f)u=m+1;else if(p>=d)h=m-1;else return true}return false},a=[],c=null;for(let f of t)c!==null&&f.fromXObject===c.fromXObject&&f.pathStartIndex-c.operatorEnd<=us&&!o(c.operatorEnd,f.pathStartIndex)&&fs(c.bbox,f.bbox,i)&&c?(c.bbox=ds(c.bbox,f.bbox),c.operatorEnd=Math.max(c.operatorEnd,f.paintIndex),c.operatorStart=Math.min(c.operatorStart,f.pathStartIndex),c.paintOperatorIndices.push(f.paintIndex)):(c&&a.push(c),c={bbox:{...f.bbox},operatorStart:f.pathStartIndex,operatorEnd:f.paintIndex,paintOperatorIndices:[f.paintIndex],ctmAtStart:[...f.ctmAtStart],fromXObject:f.fromXObject});c&&a.push(c);let l=n*r;return a.filter(f=>{let d=f.bbox.maxX-f.bbox.minX,u=f.bbox.maxY-f.bbox.minY;return d>0&&u>0&&d*u<=.9*l})}function hs(t){return t&&typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):""}function mr(t,e){if(!t)return null;let n=o=>{let a=e(o);if(!a||!U(a))return null;try{return _.decodeStreamSync(a)}catch{return null}},r=n(t.entries.get("FontFile2"));if(r&&r.length>0)return {bytes:r,kind:"truetype"};let i=e(t.entries.get("FontFile3"));if(i&&U(i)){let o=n(i);if(o&&o.length>0){let c=hs(i.dict.entries.get("Subtype"))==="OpenType"?"opentype":"cff";return {bytes:o,kind:c}}}let s=n(t.entries.get("FontFile"));return s&&s.length>0?{bytes:s,kind:"type1"}:null}function ms(t){return t==="truetype"||t==="opentype"}var Mt=(t,e)=>t[e]<<8|t[e+1],ps=(t,e)=>t[e]*16777216+(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];function xs(t){if(t.length<12)return false;let e=Mt(t,4),n=-1;for(let i=0;i<e;i+=1){let s=12+i*16;if(s+16>t.length)return false;if(t[s]===99&&t[s+1]===109&&t[s+2]===97&&t[s+3]===112){n=ps(t,s+8);break}}if(n<0||n+4>t.length)return false;let r=Mt(t,n+2);for(let i=0;i<r;i+=1){let s=n+4+i*8;if(s+8>t.length)break;let o=Mt(t,s),a=Mt(t,s+2);if(o===3&&(a===1||a===10)||o===0)return true}return false}function gs(t){let e=2166136261,n=t.length,r=Math.max(1,Math.floor(n/4096));for(let i=0;i<n;i+=r)e^=t[i],e=Math.imul(e,16777619);return e^=n,e=Math.imul(e,16777619),`npf-${(e>>>0).toString(16)}`}var cn=new Map,ln=new Map,bs=()=>typeof document!="undefined"&&typeof globalThis.FontFace!="undefined"&&!!document.fonts;async function pr(t){if(!bs()||!ms(t.kind)||!xs(t.bytes))return null;let e=gs(t.bytes),n=cn.get(e);if(n==="loaded")return e;if(n==="failed")return null;let r=ln.get(e);if(r)return r;let i=(async()=>{try{let s=t.bytes.slice().buffer,o=new FontFace(e,s);return await o.load(),document.fonts.add(o),cn.set(e,"loaded"),e}catch{return cn.set(e,"failed"),null}finally{ln.delete(e);}})();return ln.set(e,i),i}var un=null,kt=()=>un!=null?un:un=import('./pdf.image_decoders.min-5CGUOWQR.js'),xr=new Set,gr=new Set,br=new Set(["F1","F3","F4"]),yr=new WeakMap,ys=()=>new Promise(t=>setTimeout(t,0)),Ve=class Ve{constructor(e,n,r,i,s){this.canvas=e;this.pageWidth=n;this.pageHeight=r;this.scale=i;this.stateStack=[];this.state=St();this.atomicLogCount=0;this.commandIndex=0;this.xobjectDepth=0;this.pageResources=null;this.objectLoader=null;this.fontCache=new Map;this.embeddedFamilies=new Map;this.glyphWidthCache=new Map;this.separationColorCache=new Map;this.fillColorResolver=null;this.strokeColorResolver=null;this.resolverStack=[];this.capturedTextRuns=[];this.fontDiagnosticsLogged=new Set;this.rawByteDiagnosticsLogged=new Set;this.currentPathX=0;this.currentPathY=0;this.pathStartX=0;this.pathStartY=0;this.initialTransform=null;this.forcedColor=null;this.patternDepth=0;this.patternCache=new Map;this.meshCache=new Map;this.layerStack=[];this.layerPool=[];this.capturedImages=[];this.paintRecords=[];this.breakerIndices=[];this.pendingPath=null;this.captureSuppressed=0;var c,l,f,d,u,h,m;let o=(c=s==null?void 0:s.debugAtomic)!=null?c:false,a=e.getContext("2d",{willReadFrequently:o});if(!a)throw new Error("2D context unavailable");this.ctx=a,this.baseCtx=a,this.disableClip=(l=s==null?void 0:s.disableClip)!=null?l:false,this.debug=(f=s==null?void 0:s.debug)!=null?f:false,this.debugAtomic=o,this.maxAtomicLogs=(d=s==null?void 0:s.maxAtomicLogs)!=null?d:500,this.initialTransform=(u=s==null?void 0:s.initialTransform)!=null?u:null,this.forcedColor=(h=s==null?void 0:s.forcedColor)!=null?h:null,this.patternDepth=(m=s==null?void 0:s.patternDepth)!=null?m:0,e.width=Math.ceil(n*i),e.height=Math.ceil(r*i),s!=null&&s.transparentBackground||(this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.fillStyle="white",this.ctx.fillRect(0,0,e.width,e.height),this.ctx.restore()),this.forcedColor&&(this.state.fillColor=this.forcedColor,this.state.strokeColor=this.forcedColor,this.ctx.fillStyle=ve(this.forcedColor),this.ctx.strokeStyle=ve(this.forcedColor)),this.applyCurrentTransform(),this.logDebug("init",{pageWidth:n,pageHeight:r,scale:i,canvasWidth:e.width,canvasHeight:e.height,disableClip:this.disableClip});}render(e){this.commandIndex=0,this.capturedTextRuns=[],this.applyCurrentTransform(),this.logDebug("render:start",{commandCount:e.length}),this.logDebug("orientation",{flipYApplied:true});for(let n of e){let r=this.commandIndex++;this.debug&&this.logDebug("command",{index:r,op:n.op,payload:this.commandPayload(n)});let s=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;this.execute(n),s&&this.logAtomic(r,n,s,this.captureAtomicState());}this.logDebug("render:end",{renderedCommands:e.length,capturedTextRuns:this.capturedTextRuns.length,finalTextMatrix:this.state.textMatrix,finalLineMatrix:this.state.textLineMatrix,finalCTM:this.state.ctm,stackDepth:this.stateStack.length});}async renderAsync(e){for(this.commandIndex=0,this.xobjectDepth=0,this.capturedTextRuns=[],this.capturedImages=[],this.paintRecords=[],this.breakerIndices=[],this.pendingPath=null,this.patternCache.clear(),this.meshCache.clear(),this.glyphWidthCache.clear(),this.ctx=this.baseCtx,this.layerStack=[],this.applyCurrentTransform(),this.logDebug("render:start",{commandCount:e.length,async:true}),await this.preloadEmbeddedFonts(),await this.runCommandsAsync(e);this.layerStack.length>0;)this.popLayer();this.logDebug("render:end",{renderedCommands:e.length,capturedTextRuns:this.capturedTextRuns.length,finalTextMatrix:this.state.textMatrix,finalLineMatrix:this.state.textLineMatrix,finalCTM:this.state.ctm,stackDepth:this.stateStack.length,async:true});}async renderAnnotations(e){if(!e)return;let n=this.resolveObject(e.entries.get("Annots"));if(!n||!j(n))return;let r=this.state;this.state=St(),this.applyCurrentTransform();try{for(let i of n.items){let s=this.resolveObject(i);if(!(!s||!M(s)))try{await this.renderOneAnnotation(s);}catch(o){this.logDebug("annot:render-failed",{error:o instanceof Error?o.message:String(o)});}}}finally{this.state=r,this.applyCurrentTransform();}}async renderOneAnnotation(e){var l,f;let n=V(e.entries.get("Subtype"));if(n==="Popup"||n==="Link"||n==="Widget")return;let r=Math.floor((l=A(e.entries.get("F")))!=null?l:0);if((r&2)!==0||(r&32)!==0)return;let i=this.resolveAppearanceStream(e);if(!i)return;let s=le(this.resolveObject(e.entries.get("Rect")));if(!s||s.length<4)return;let o=le(i.dict.entries.get("BBox"));if(!o||o.length<4)return;let a=(f=rt(i.dict.entries.get("Matrix")))!=null?f:[1,0,0,1,0,0],c=Ss(s,o,a);if(c){this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:c});try{await this.renderFormStreamInline(i);}finally{this.execute({op:"restore_state"});}}}resolveAppearanceStream(e){let n=this.resolveObject(e.entries.get("AP"));if(!n||!M(n))return null;let r=this.resolveObject(n.entries.get("N"));if(r&&M(r)){let i=V(e.entries.get("AS"));r=i?this.resolveObject(r.entries.get(i)):void 0;}return r&&U(r)?r:null}async runCommandsAsync(e){let n=()=>typeof performance!="undefined"?performance.now():Date.now(),r=n();for(let i of e){let s=this.commandIndex++;this.debug&&this.logDebug("command",{index:s,op:i.op,payload:this.commandPayload(i)}),n()-r>12&&(await ys(),r=n());let a=this.debugAtomic&&this.atomicLogCount<this.maxAtomicLogs?this.captureAtomicState():null;i.op==="xobject"?await this.renderXObject(i.name):i.op==="inline_image"?await this.renderInlineImage(i.params,i.data):(i.op==="set_fill_color"||i.op==="set_stroke_color")&&i.patternName&&!this.forcedColor&&(i.op==="set_fill_color"?this.state.fillColorSpace:this.state.strokeColorSpace)==="Pattern"?await this.applyPatternColor(i.op==="set_fill_color"?"fill":"stroke",i.patternName,i.values):i.op==="set_graphics_state"?(this.execute(i),await this.applySoftMaskFromExtGState(i.name)):this.execute(i),a&&this.logAtomic(s,i,a,this.captureAtomicState());}}getCapturedTextRuns(){return this.capturedTextRuns.map(e=>({...e,glyphs:e.glyphs.map(n=>({...n}))}))}getCapturedImages(){return this.capturedImages.map(e=>({...e,ctm:[...e.ctm]}))}getCapturedGraphics(){return hr(this.paintRecords,this.breakerIndices,this.canvas.width,this.canvas.height).map(e=>({canvasX:e.bbox.minX,canvasY:e.bbox.minY,canvasWidth:e.bbox.maxX-e.bbox.minX,canvasHeight:e.bbox.maxY-e.bbox.minY,operatorStart:e.operatorStart,operatorEnd:e.operatorEnd,paintOperatorIndices:e.paintOperatorIndices,ctmAtStart:e.ctmAtStart,fromXObject:e.fromXObject}))}extendPendingPath(e){if(this.captureSuppressed>0)return;this.pendingPath||(this.pendingPath={bbox:{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},startIndex:Math.max(0,this.commandIndex-1),ctmAtStart:[...this.state.ctm]});let n=Y(this.deviceBase(),this.state.ctm),r=this.pendingPath.bbox;for(let[i,s]of e){let o=J(n,i,s);o.x<r.minX&&(r.minX=o.x),o.x>r.maxX&&(r.maxX=o.x),o.y<r.minY&&(r.minY=o.y),o.y>r.maxY&&(r.maxY=o.y);}}recordPaintForCapture(){let e=this.pendingPath;this.pendingPath=null,!(this.captureSuppressed>0||!e)&&(e.bbox.minX>e.bbox.maxX||this.paintRecords.push({bbox:{...e.bbox},pathStartIndex:e.startIndex,paintIndex:Math.max(0,this.commandIndex-1),ctmAtStart:e.ctmAtStart,fromXObject:this.xobjectDepth>0}));}recordBreaker(){this.captureSuppressed>0||this.breakerIndices.push(Math.max(0,this.commandIndex-1));}captureImageBox(e,n){if(this.recordBreaker(),this.captureSuppressed>0)return;let r=Y(this.deviceBase(),this.state.ctm),i=[J(r,0,0),J(r,1,0),J(r,0,1),J(r,1,1)],s=i.map(l=>l.x),o=i.map(l=>l.y),a=Math.min(...s),c=Math.min(...o);this.capturedImages.push({canvasX:a,canvasY:c,canvasWidth:Math.max(...s)-a,canvasHeight:Math.max(...o)-c,ctm:[...this.state.ctm],kind:e,xobjectName:n,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0});}setFontContext(e,n){this.pageResources=e!=null?e:null,this.objectLoader=n!=null?n:null,this.fontCache.clear(),this.fontDiagnosticsLogged.clear(),this.rawByteDiagnosticsLogged.clear(),this.patternCache.clear();}execute(e){var n,r;switch(e.op){case "save_state":this.stateStack.push(Ns(this.state)),this.resolverStack.push({fill:this.fillColorResolver,stroke:this.strokeColorResolver}),this.ctx.save();break;case "restore_state":for(;this.layerStack.length>0&&this.stateStack.length>0;){let i=this.layerStack[this.layerStack.length-1];if(i.kind==="smask"&&i.stateDepthAtPush>=this.stateStack.length)this.popLayer();else break}if(this.stateStack.length>0&&(this.state=this.stateStack.pop()),this.resolverStack.length>0){let i=this.resolverStack.pop();this.fillColorResolver=i.fill,this.strokeColorResolver=i.stroke;}this.ctx.restore();break;case "set_ctm":this.state.ctm=Y(this.state.ctm,e.matrix),this.applyCurrentTransform(),this.logDebug("ctm:update",{ctm:this.state.ctm,cmd:e.matrix});break;case "set_line_width":this.state.lineWidth=e.width,this.ctx.lineWidth=e.width;break;case "set_line_cap":{let i=["butt","round","square"];this.state.lineCap=e.cap,this.ctx.lineCap=(n=i[e.cap])!=null?n:"butt";break}case "set_line_join":{let i=["miter","round","bevel"];this.state.lineJoin=e.join,this.ctx.lineJoin=(r=i[e.join])!=null?r:"miter";break}case "set_miter_limit":this.state.miterLimit=e.limit,this.ctx.miterLimit=e.limit;break;case "set_dash":this.state.dashArray=e.array,this.state.dashPhase=e.phase,this.ctx.setLineDash(e.array),this.ctx.lineDashOffset=e.phase;break;case "set_rendering_intent":break;case "set_graphics_state":this.applyExtGState(e.name);break;case "set_fill_color_rgb":if(this.forcedColor)break;this.state.fillColorSpace="DeviceRGB",this.state.fillColor={space:"rgb",r:e.r,g:e.g,b:e.b},this.state.fillPatternName=null,this.state.fillPattern=null,this.ctx.fillStyle=ye(e.r,e.g,e.b);break;case "set_stroke_color_rgb":if(this.forcedColor)break;this.state.strokeColorSpace="DeviceRGB",this.state.strokeColor={space:"rgb",r:e.r,g:e.g,b:e.b},this.state.strokePatternName=null,this.state.strokePattern=null,this.ctx.strokeStyle=ye(e.r,e.g,e.b);break;case "set_fill_gray":if(this.forcedColor)break;this.state.fillColorSpace="DeviceGray",this.state.fillColor={space:"gray",gray:e.gray},this.state.fillPatternName=null,this.state.fillPattern=null,this.ctx.fillStyle=ye(e.gray,e.gray,e.gray);break;case "set_stroke_gray":if(this.forcedColor)break;this.state.strokeColorSpace="DeviceGray",this.state.strokeColor={space:"gray",gray:e.gray},this.state.strokePatternName=null,this.state.strokePattern=null,this.ctx.strokeStyle=ye(e.gray,e.gray,e.gray);break;case "set_fill_cmyk":{if(this.forcedColor)break;this.state.fillColorSpace="DeviceCMYK",this.state.fillColor={space:"cmyk",c:e.c,m:e.m,y:e.y,k:e.k},this.state.fillPatternName=null,this.state.fillPattern=null;let i=qe(e.c,e.m,e.y,e.k);this.ctx.fillStyle=ye(i.r,i.g,i.b);break}case "set_stroke_cmyk":{if(this.forcedColor)break;this.state.strokeColorSpace="DeviceCMYK",this.state.strokeColor={space:"cmyk",c:e.c,m:e.m,y:e.y,k:e.k},this.state.strokePatternName=null,this.state.strokePattern=null;let i=qe(e.c,e.m,e.y,e.k);this.ctx.strokeStyle=ye(i.r,i.g,i.b);break}case "move_to":this.ctx.beginPath(),this.ctx.moveTo(e.x,e.y),this.currentPathX=e.x,this.currentPathY=e.y,this.pathStartX=e.x,this.pathStartY=e.y,this.extendPendingPath([[e.x,e.y]]);break;case "line_to":this.ctx.lineTo(e.x,e.y),this.currentPathX=e.x,this.currentPathY=e.y,this.extendPendingPath([[e.x,e.y]]);break;case "curve_to":this.ctx.bezierCurveTo(e.x1,e.y1,e.x2,e.y2,e.x3,e.y3),this.extendPendingPath([[e.x1,e.y1],[e.x2,e.y2],[e.x3,e.y3]]),this.currentPathX=e.x3,this.currentPathY=e.y3;break;case "curve_to_v":this.ctx.bezierCurveTo(this.currentPathX,this.currentPathY,e.x2,e.y2,e.x3,e.y3),this.extendPendingPath([[e.x2,e.y2],[e.x3,e.y3]]),this.currentPathX=e.x3,this.currentPathY=e.y3;break;case "rect":this.ctx.beginPath(),this.ctx.rect(e.x,e.y,e.w,e.h),this.currentPathX=e.x,this.currentPathY=e.y,this.pathStartX=e.x,this.pathStartY=e.y,this.extendPendingPath([[e.x,e.y],[e.x+e.w,e.y+e.h]]);break;case "close_path":this.ctx.closePath(),this.currentPathX=this.pathStartX,this.currentPathY=this.pathStartY;break;case "end_path":this.ctx.beginPath(),this.pendingPath=null;break;case "stroke":this.paintStroke(),this.recordPaintForCapture();break;case "close_stroke":this.ctx.closePath(),this.currentPathX=this.pathStartX,this.currentPathY=this.pathStartY,this.paintStroke(),this.recordPaintForCapture();break;case "fill":this.paintFill(),this.recordPaintForCapture();break;case "fill_stroke":this.paintFill(),this.paintStroke(),this.recordPaintForCapture();break;case "fill_even_odd":this.paintFill("evenodd"),this.recordPaintForCapture();break;case "fill_stroke_even_odd":this.paintFill("evenodd"),this.paintStroke(),this.recordPaintForCapture();break;case "close_fill_stroke":this.ctx.closePath(),this.paintFill(),this.paintStroke(),this.recordPaintForCapture();break;case "close_fill_stroke_even_odd":this.ctx.closePath(),this.paintFill("evenodd"),this.paintStroke(),this.recordPaintForCapture();break;case "clip":this.disableClip?this.logDebug("clip:skipped",{rule:"nonzero"}):this.ctx.clip();break;case "clip_even_odd":this.disableClip?this.logDebug("clip:skipped",{rule:"evenodd"}):this.ctx.clip("evenodd");break;case "begin_text":this.state.textMatrix=[1,0,0,1,0,0],this.state.textLineMatrix=[1,0,0,1,0,0];break;case "end_text":break;case "set_font":this.state.font=e.name,this.state.fontSize=e.size;break;case "set_text_matrix":this.state.textMatrix=[...e.matrix],this.state.textLineMatrix=[...e.matrix];break;case "move_text":this.state.textLineMatrix=Y(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case "move_text_set_leading":this.state.leading=-e.ty,this.state.textLineMatrix=Y(this.state.textLineMatrix,[1,0,0,1,e.tx,e.ty]),this.state.textMatrix=[...this.state.textLineMatrix];break;case "next_line":this.state.textLineMatrix=Y(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix];break;case "set_char_spacing":this.state.charSpacing=e.spacing;break;case "set_word_spacing":this.state.wordSpacing=e.spacing;break;case "set_horiz_scale":this.state.horizScale=e.scale;break;case "set_leading":this.state.leading=e.leading;break;case "set_text_render":this.state.textRenderMode=e.mode;break;case "set_text_rise":this.state.textRise=e.rise;break;case "show_string":this.recordBreaker(),this.renderText(e.data);break;case "show_strings":this.recordBreaker();for(let i of e.items)if(i instanceof Uint8Array)this.renderText(i);else {let s=-(i/1e3)*this.state.fontSize*(this.state.horizScale/100);this.state.textMatrix=Y(this.state.textMatrix,[1,0,0,1,s,0]);}break;case "next_line_show_string":this.recordBreaker(),this.moveToNextTextLine(),this.renderText(e.data);break;case "set_spacing_next_line_show_string":this.recordBreaker(),this.state.wordSpacing=e.wordSpacing,this.state.charSpacing=e.charSpacing,this.moveToNextTextLine(),this.renderText(e.data);break;case "xobject":case "inline_image":break;case "set_fill_color_space":this.state.fillColorSpace=this.resolveColorSpaceName(e.name),this.fillColorResolver=this.buildComplexColorResolver(e.name);break;case "set_stroke_color_space":this.state.strokeColorSpace=this.resolveColorSpaceName(e.name),this.strokeColorResolver=this.buildComplexColorResolver(e.name);break;case "set_fill_color":if(this.forcedColor)break;if(this.state.fillColorSpace==="Pattern"&&e.patternName){this.state.fillPatternName=e.patternName;let i=this.resolvePatternFillStyle(e.patternName,"fill");this.ctx.fillStyle=i;}else this.state.fillPatternName=null,this.state.fillPattern=null,this.state.fillColor=this.fillColorResolver?this.fillColorResolver(e.values):je(this.state.fillColorSpace,e.values),this.ctx.fillStyle=ve(this.state.fillColor);break;case "set_stroke_color":if(this.forcedColor)break;if(this.state.strokeColorSpace==="Pattern"&&e.patternName){this.state.strokePatternName=e.patternName;let i=this.resolvePatternFillStyle(e.patternName,"stroke");this.ctx.strokeStyle=i;}else this.state.strokePatternName=null,this.state.strokePattern=null,this.state.strokeColor=this.strokeColorResolver?this.strokeColorResolver(e.values):je(this.state.strokeColorSpace,e.values),this.ctx.strokeStyle=ve(this.state.strokeColor);break;case "shade":this.renderShadeOperator(e.name);break;}}moveToNextTextLine(){this.state.textLineMatrix=Y(this.state.textLineMatrix,[1,0,0,1,0,-this.state.leading]),this.state.textMatrix=[...this.state.textLineMatrix];}renderText(e){var Ze;if(e.length===0)return;let n=this.getCurrentFontInfo();if(n.isType3){this.renderType3Text(e,n);return}let r=this.decodeTextWithFont(e,n),i=Math.max(1,this.state.fontSize);this.ctx.font=vr(n,i);let s=X=>this.measureGlyphWidthCached(X),o=Rs(e,r,n,i,this.state.charSpacing,this.state.wordSpacing,s),a=o.glyphs,c=a.map(X=>X.text).join("")||r;this.logDebug("text:before",{text:c,textLength:c.length,font:this.state.font,fontSize:i,textMatrix:this.state.textMatrix,fillColor:ve(this.state.fillColor),textRise:this.state.textRise,horizScale:this.state.horizScale}),this.ctx.save();let l=this.state.textMatrix;this.ctx.transform(l[0],l[1],l[2],l[3],l[4],l[5]);let f=this.state.horizScale/100;f!==1&&this.ctx.scale(f,1);let d=this.state.textRise;this.ctx.font=vr(n,i),this.ctx.fillStyle=ve(this.state.fillColor),this.ctx.globalAlpha=this.state.fillAlpha;let u=this.ctx.measureText(c),h=Math.max(1e-4,u.width),m=o.hasPdfMetrics?a.reduce((X,de)=>X+de.advance,0)*f:null,p=m!=null?m:h*f,x=Math.max(1,u.actualBoundingBoxAscent||i*.8),g=Math.max(1,u.actualBoundingBoxDescent||i*.2);this.ctx.scale(1,-1);let b=o.hasPdfMetrics&&a.length>0,P=h*Math.max(1e-4,f),y=m?_s(p/P,.5,1.8):1;!b&&y!==1&&this.ctx.scale(y,1);let D=this.state.textRenderMode,v=D===0||D===2||D===4||D===6,S=D===1||D===2||D===5||D===6;v&&(this.ctx.fillStyle=ve(this.state.fillColor)),S&&(this.ctx.strokeStyle=ve(this.state.strokeColor),this.ctx.lineWidth=Math.max(.01,this.state.lineWidth/i));let F=(X,de)=>{v&&(this.ctx.globalAlpha=this.state.fillAlpha,this.ctx.fillText(X,de,-d)),S&&(this.ctx.globalAlpha=this.state.strokeAlpha,this.ctx.strokeText(X,de,-d));};if(b){let X=0;for(let de of a)de.text&&F(de.text,X),X+=de.advance;}else F(c,0);this.ctx.restore();let w=[1,0,0,-1,0,this.pageHeight],C=Y(Y(w,this.state.ctm),l),O=p,E=J(C,0,d),I=[J(C,0,d+x),J(C,O,d+x),J(C,O,d-g),J(C,0,d-g)],L=Math.min(...I.map(X=>X.x)),$=Math.max(...I.map(X=>X.x)),H=Math.min(...I.map(X=>X.y)),Z=Math.max(...I.map(X=>X.y)),ae=L*this.scale,T=H*this.scale,B=Math.max(1,($-L)*this.scale),W=Math.max(1,(Z-H)*this.scale),G=Ee(this.state.fillColor),fe=(Ze=n.baseFontName)!=null?Ze:this.state.font,ee=Y(this.state.ctm,l),te=Math.hypot(ee[1],ee[3]),Me=Math.max(1,i*(te>.01?te:1)),xe=this.capturedTextRuns.length,pe=0,ke=a.map(X=>{let de=o.hasPdfMetrics?X.advance:h>0?this.measureGlyphWidthCached(X.text)/h*(p/Math.max(1e-4,f)):0,dt=J(C,pe*f,d),K=J(C,(pe+de)*f,d),ce=Math.min(dt.x,K.x)*this.scale,be=Math.max(1,Math.abs(K.x-dt.x)*this.scale);return pe+=de,{canvasX:ce,canvasY:T,canvasWidth:be,canvasHeight:W,canvasBaselineY:E.y*this.scale,char:X.text,charCode:X.code,runIndex:xe}});this.capturedTextRuns.push({index:xe,text:c,fontName:fe,fontSize:Me,canvasX:ae,canvasY:T,canvasWidth:B,canvasHeight:W,canvasBaselineX:E.x*this.scale,canvasBaselineY:E.y*this.scale,fillColor:G,streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:ke,fontFamily:xn(n)});let ge=m!=null?m:p;this.state.textMatrix=Y(this.state.textMatrix,[1,0,0,1,ge,0]),this.logDebug("text:after",{text:c,measuredWidth:h,advance:ge,needsTextFlip:true,bytesHexPreview:Array.from(e.slice(0,12)).map(X=>X.toString(16).padStart(2,"0")).join(" "),printableChars:Array.from(r).filter(X=>X>=" "&&X<="~").length,totalChars:r.length,nextTextMatrix:this.state.textMatrix});}renderType3Text(e,n){var v,S,F,w,C,O,E,I;let r=n.type3CharProcs,i=n.type3Encoding;if(!r)return;let s=Math.max(1,this.state.fontSize),o=this.state.horizScale/100,a=this.state.textRise,c=(v=n.fontMatrix)!=null?v:[.001,0,0,.001,0,0],l=this.capturedTextRuns.length,f="";for(let L=0;L<e.length;L++){let $=e[L],H=(S=n.encodingMap)==null?void 0:S.get($);f+=H!=null?H:i&&(F=i.get($))!=null?F:String.fromCharCode($);}let d=[...this.state.textMatrix],u=[1,0,0,-1,0,this.pageHeight],h=this.pageResources;for(let L=0;L<e.length;L++){let $=e[L],H=(w=i==null?void 0:i.get($))!=null?w:".notdef",ae=((E=(O=(C=n.widths)==null?void 0:C.get($))!=null?O:n.defaultWidth)!=null?E:1e3)/1e3*s+this.state.charSpacing+($===32?this.state.wordSpacing:0),T=r.entries.get(H),B=T?this.resolveObject(T):void 0;if(B&&U(B)){let W=this.state.textMatrix,G=[s*o,0,0,s,0,a],fe=Y(Y(W,G),c),ee=[...this.state.textMatrix],te=[...this.state.textLineMatrix];this.execute({op:"save_state"}),this.execute({op:"set_ctm",matrix:fe}),n.type3Resources&&(this.pageResources=n.type3Resources),this.captureSuppressed+=1;try{let Me=_.decodeStreamSync(B),xe=Ue(Me);for(let pe of xe)pe.op!=="type3_glyph_width"&&this.execute(pe);}catch{}finally{this.captureSuppressed-=1;}this.pageResources=h,this.execute({op:"restore_state"}),this.state.textMatrix=ee,this.state.textLineMatrix=te;}this.state.textMatrix=Y(this.state.textMatrix,[1,0,0,1,ae,0]);}let m=Y(Y(u,this.state.ctm),d),p=J(m,0,a),x=Y(Y(u,this.state.ctm),this.state.textMatrix),g=J(x,0,a),b=Math.min(p.x,g.x)*this.scale,P=(Math.min(p.y,g.y)-s)*this.scale,y=Math.max(1,Math.abs(g.x-p.x)*this.scale),D=Math.max(1,s*this.scale);this.capturedTextRuns.push({index:l,text:f,fontName:(I=n.baseFontName)!=null?I:this.state.font,fontSize:s,canvasX:b,canvasY:P,canvasWidth:y,canvasHeight:D,canvasBaselineX:p.x*this.scale,canvasBaselineY:p.y*this.scale,fillColor:Ee(this.state.fillColor),streamOperatorIndex:Math.max(0,this.commandIndex-1),fromXObject:this.xobjectDepth>0,glyphs:[],fontFamily:xn(n)});}commandPayload(e){return e.op==="show_string"?{text:this.decodeText(e.data),bytes:e.data.length}:e.op==="show_strings"?{items:e.items.map(n=>n instanceof Uint8Array?{type:"text",text:this.decodeText(n),bytes:n.length}:{type:"adjust",value:n})}:e}decodeText(e){return this.decodeTextWithFont(e,this.getCurrentFontInfo())}measureGlyphWidthCached(e){let n=`${this.ctx.font}|${e}`,r=this.glyphWidthCache.get(n);if(r!==void 0)return r;let i=this.ctx.measureText(e).width;return this.glyphWidthCache.set(n,i),i}async preloadEmbeddedFonts(){if(this.embeddedFamilies.clear(),!this.pageResources)return;let e=this.resolveObject(this.pageResources.entries.get("Font"));if(!e||!M(e))return;let n=r=>this.resolveObject(r);for(let[r,i]of e.entries)try{let s=this.resolveObject(i);if(!s||!M(s))continue;let a=V(s.entries.get("Subtype"))==="Type0"?Sr(s,n):void 0,c=Fr(s,a,n),l=mr(c,n);if(!l)continue;let f=await pr(l);f&&this.embeddedFamilies.set(r,f);}catch{}}getCurrentFontInfo(){let e=this.state.font;if(!e)return Ot();let n=this.fontCache.get(e);if(n)return n;let r=this.loadFontInfo(e);return this.fontCache.set(e,r),r}loadFontInfo(e){var C,O,E,I,L,$,H,Z,ae;if(!this.pageResources)return Ot();let n=this.resolveObject(this.pageResources.entries.get("Font"));if(!n||!M(n))return Ot();let r=n.entries.get(e),i=this.resolveObject(r);if(!i||!M(i))return Ot();let s=yr.get(i);if(s)return s;let o=i.entries.get("Subtype"),a=(C=V(o))!=null?C:"Unknown",c=(O=V(i.entries.get("BaseFont")))!=null?O:void 0,l=a==="Type0",f=Math.floor((E=A(i.entries.get("FirstChar")))!=null?E:0),d=l?Sr(i,T=>this.resolveObject(T)):void 0,u=Fr(i,d,T=>this.resolveObject(T)),h=l?As(d):Cs(i,f),m=l?Ms(d):ks(i),p=i.entries.get("ToUnicode"),x=i.entries.get("Encoding"),g=null,b=this.resolveObject(p);if(b&&U(b))try{let T=_.decodeStreamSync(b),B=new TextDecoder("latin1").decode(T),W=po(B);this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!p,rawToUnicodeType:Ce(p),resolvedToUnicodeType:Ce(b),encoding:Ce(x),cmapRaw:W}),this.debug&&br.has(e)&&!gr.has(e)&&(gr.add(e),console.log(`=== Raw CMap text for ${e} (first 500 chars) ===`),console.log(B.slice(0,500)),console.log("===")),g=Ws(B),this.logDebug("font:cmap-parsed",{fontName:e,cmapType:g.cmapType,isUsable:g.isUsable,bfChar:g.bfChar.size,bfRange:g.bfRange.length,codeSpaceRanges:g.codeSpaceRanges.length}),g&&br.has(e)&&Hs(g,e);}catch(T){this.logDebug("font:toUnicode-failed",{fontName:e,subtype:a,error:T instanceof Error?T.message:String(T)}),this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!p,rawToUnicodeType:Ce(p),resolvedToUnicodeType:Ce(b),encoding:Ce(x),toUnicodeError:T instanceof Error?T.message:String(T)});}else this.logFontDiagnostic(e,{subtype:a,isComposite:l,hasRawToUnicode:!!p,rawToUnicodeType:Ce(p),resolvedToUnicodeType:Ce(b),encoding:Ce(x),note:l?"Composite font without resolved ToUnicode stream":"No ToUnicode stream"});if(!g&&l){let T=i.entries.get("Encoding");T&&T.type==="name"&&(T.value==="Identity-H"||T.value==="Identity-V")&&this.logDebug("font:identity-no-tounicode",{fontName:e,subtype:a,encoding:T.value});}let P;l||(P=Ls(x,T=>this.resolveObject(T)));let y=false,D,v,S,F;if(a==="Type3"){y=true;let T=this.resolveObject(i.entries.get("CharProcs"));T&&M(T)&&(D=T);let B=i.entries.get("FontMatrix");if(B&&j(B)){let G=B.items;S=[(I=A(G[0]))!=null?I:.001,(L=A(G[1]))!=null?L:0,($=A(G[2]))!=null?$:0,(H=A(G[3]))!=null?H:.001,(Z=A(G[4]))!=null?Z:0,(ae=A(G[5]))!=null?ae:0];}let W=this.resolveObject(i.entries.get("Resources"));W&&M(W)&&(F=W),v=$s(x,G=>this.resolveObject(G));}let w={subtype:a,baseFontName:c,fontWeight:Os(c,u),fontStyle:Ts(c,u),isComposite:l,firstChar:f,widths:h,defaultWidth:m,toUnicode:g,encodingMap:P,isType3:y,type3CharProcs:D,type3Encoding:v,fontMatrix:S,type3Resources:F,registeredFamily:this.embeddedFamilies.get(e)};return this.logDebug("font:loaded",{fontName:e,subtype:a,isComposite:l,hasToUnicode:!!g}),yr.set(i,w),w}logFontDiagnostic(e,n){if(!this.debug)return;let r=`${e}|${String(n.subtype)}|${String(n.rawToUnicodeType)}|${String(n.resolvedToUnicodeType)}`;this.fontDiagnosticsLogged.has(r)||(this.fontDiagnosticsLogged.add(r),console.info("[PageRenderer][FontDiag]",{font:e,...n}));}resolveObject(e){if(e){if(!q(e))return e;if(this.objectLoader)try{return this.objectLoader(e)}catch{return}}}resolveColorSpaceName(e){var s;let n=Pe(e);if(n)return n;if(!this.pageResources)return e;let r=this.resolveObject(this.pageResources.entries.get("ColorSpace"));if(!r||!M(r))return e;let i=this.resolveObject(r.entries.get(e));return (s=Dr(i))!=null?s:e}buildComplexColorResolver(e){var h;if(Pe(e))return null;let n=this.separationColorCache.get(e);if(n)return n;if(!this.pageResources||!this.objectLoader)return null;let r=this.resolveObject(this.pageResources.entries.get("ColorSpace"));if(!r||!M(r))return null;let i=this.resolveObject(r.entries.get(e));if(!i||!j(i)||i.items.length<2)return null;let s=V(i.items[0]);if(s!=="Separation"&&s!=="DeviceN")return null;let o=2,a=3,c=i.items[o]?this.resolveObject(i.items[o]):void 0,l=(h=Dr(c))!=null?h:"DeviceGray",f=i.items[a],d=this.objectLoader,u=m=>{var g;let p=(g=m[0])!=null?g:0,x=Ct(f,p,d);return x&&x.length>0?je(l,x):l==="DeviceCMYK"?{space:"cmyk",c:0,m:0,y:0,k:p}:{space:"gray",gray:1-p}};return this.separationColorCache.set(e,u),u}async renderXObject(e){if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("XObject"));if(!n||!M(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!U(r))return;let i=V(r.dict.entries.get("Subtype"));if(i==="Image"){this.captureImageBox("xobject",e),await this.renderImageXObject(r);return}if(i==="Form")try{let s=r,o=this.resolveObject(s.dict.entries.get("Resources")),c=await(s.decode?s.decode():Promise.resolve(_.decodeStreamSync(s))),l=Ue(c instanceof Uint8Array?c:new Uint8Array(await c)),f=this.pageResources,d=this.objectLoader,u=this.patternCache;this.patternCache=new Map,this.pageResources=o&&M(o)?o:this.pageResources;let h=this.resolveObject(s.dict.entries.get("Group")),x=!!h&&M(h)&&V(h.entries.get("S"))==="Transparency"&&(this.state.fillAlpha<1||this.state.strokeAlpha<1||this.state.blendMode!=="Normal")&&this.pushLayer("group",this.state.fillAlpha,this.state.blendMode,null);this.execute({op:"save_state"}),x&&(this.state.fillAlpha=1,this.state.strokeAlpha=1,this.state.blendMode="Normal",this.ctx.globalAlpha=1,this.ctx.globalCompositeOperation="source-over");let g=s.dict.entries.get("Matrix");if(g&&Array.isArray(g.items))try{let P=g.items.map(y=>{var D;return Number((D=A(y))!=null?D:0)});this.execute({op:"set_ctm",matrix:P});}catch{}let b=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(l);}finally{this.xobjectDepth-=1,this.commandIndex=b;}this.execute({op:"restore_state"}),x&&this.popLayer(),this.pageResources=f,this.objectLoader=d,this.patternCache=u;return}catch(s){this.logDebug("xobject:form-failed",{name:e,error:s instanceof Error?s.message:String(s)});return}}resolveImageColorSpace(e){var r,i,s;if(!e)return "DeviceRGB";let n=V(e);if(n)return (r=Pe(n))!=null?r:n;if(j(e)&&e.items.length>0){let o=V(e.items[0]);if(o==="ICCBased"){let a=this.resolveObject(e.items[1]);if(a&&U(a)){let c=Math.floor((i=A(a.dict.entries.get("N")))!=null?i:3);return c===1?"DeviceGray":c===4?"DeviceCMYK":"DeviceRGB"}return "DeviceRGB"}if(o==="Indexed")return "Indexed";if(o==="CalRGB")return "DeviceRGB";if(o==="CalGray")return "DeviceGray";if(o)return (s=Pe(o))!=null?s:o}return "DeviceRGB"}resolveDecodeParms(e){var r;let n=this.resolveObject((r=e.entries.get("DecodeParms"))!=null?r:e.entries.get("DP"));if(!n)return null;if(M(n))return n;if(j(n))for(let i of n.items){let s=this.resolveObject(i);if(s&&M(s))return s}return null}async decodeJbig2(e){var r;let n=(r=e.rawBytes)!=null?r:e.data;if(!n||n.length===0)return null;try{let{Jbig2Image:i}=await kt(),s,o=this.resolveDecodeParms(e.dict);if(o){let l=this.resolveObject(o.entries.get("JBIG2Globals"));if(l&&U(l))try{s=_.decodeStreamSync(l);}catch{}}let a=[];s&&s.length>0&&a.push({data:s,start:0,end:s.length}),a.push({data:n,start:0,end:n.length});let c=new i().parseChunks(a);for(let l=0;l<c.length;l++)c[l]^=255;return c}catch(i){return this.logDebug("xobject:jbig2-failed",{error:i instanceof Error?i.message:String(i)}),null}}async decodeCcitt(e,n,r){var s;let i=(s=e.rawBytes)!=null?s:e.data;if(!i||i.length===0)return null;try{let{CCITTFaxDecoder:o}=await kt(),a=this.resolveDecodeParms(e.dict),c=(y,D)=>{var v;return a?Math.floor((v=A(a.entries.get(y)))!=null?v:D):D},l=(y,D)=>{let v=a==null?void 0:a.entries.get(y);return v&&typeof v=="object"&&"type"in v&&v.type==="boolean"?v.value:D},f=c("Columns",1728),d=c("Rows",r),u=0,h={next:()=>u<i.length?i[u++]:-1},m=new o(h,{K:c("K",0),EndOfLine:l("EndOfLine",!1),EncodedByteAlign:l("EncodedByteAlign",!1),Columns:f,Rows:d,EndOfBlock:l("EndOfBlock",!0),BlackIs1:l("BlackIs1",!1)}),x=(f+7>>3)*(d>0?d:r),g=new Uint8Array(x),b=0,P;for(;b<x&&(P=m.readNextChar())!==-1;)g[b++]=P;return b>0?g.subarray(0,b):null}catch(o){return this.logDebug("xobject:ccitt-failed",{error:o instanceof Error?o.message:String(o)}),null}}drawRgbaImageData(e,n,r){let i=document.createElement("canvas");i.width=n,i.height=r;let s=i.getContext("2d");s&&(s.putImageData(e,0,0),this.drawImageBitmapLike(i));}async renderImageXObject(e){var u,h,m,p;let n=e.dict,r=Math.floor((u=A(n.entries.get("Width")))!=null?u:0),i=Math.floor((h=A(n.entries.get("Height")))!=null?h:0);if(r<=0||i<=0)return;let s=wr(n.entries.get("Filter")),o=Math.floor((m=A(n.entries.get("BitsPerComponent")))!=null?m:8),a=n.entries.get("ImageMask"),c=a!=null&&typeof a=="object"&&"type"in a&&a.type==="boolean"&&a.value===true||V(a)==="true",l=this.resolveImageColorSpace(n.entries.get("ColorSpace")),f=s.includes("JBIG2Decode"),d=s.includes("CCITTFaxDecode")||s.includes("CCF");try{let x=null;if(f?x=await this.decodeJbig2(e):d&&(x=await this.decodeCcitt(e,r,i)),(f||d)&&!x)return;if(c){await this.renderStencilMask(e,r,i,x);return}if(!f&&!d&&(s.includes("DCTDecode")||s.includes("DCT"))){let g=(p=e.rawBytes)!=null?p:e.data;if(!g)return;if(l==="DeviceCMYK"){await this.renderJpegViaPdfjs(e,g,r,i);return}let b=this.resolveObject(n.entries.get("SMask"));if(b&&U(b))await this.renderImageWithSMask(g,"image/jpeg",b,r,i);else {let P=await fn(g,"image/jpeg");this.drawImageBitmapLike(P),dn(P);}return}if(!f&&!d&&s.includes("JPXDecode")){await this.renderJpxViaPdfjs(e,r,i);return}if(!x&&s.some(g=>!Ds.has(g)))return;if(o===1||o===2||o===4||o===8||o===16){let g=x!=null?x:_.decodeStreamSync(e),b=null;if(l==="Indexed"){let y=n.entries.get("ColorSpace"),D=S=>this.resolveObject(S),v=hn(g,r,i,1,o,!1);b=Bs(v,r,i,y&&j(y)?y.items:[],D);}else {let y=js(l),D=hn(g,r,i,y,o,!0);b=Is(D,r,i,l);}if(!b)return;ws(b,le(n.entries.get("Decode")),l);let P=this.resolveObject(n.entries.get("SMask"));if(P&&U(P))try{let y=await this.decodeSMaskAlpha(P,r,i);Rt(b,y,r,i);}catch{}this.drawRgbaImageData(b,r,i);}}catch(x){this.logDebug("xobject:image-failed",{width:r,height:i,colorSpace:l,bitsPerComponent:o,filters:s,error:x instanceof Error?x.message:String(x)});}}async renderJpegViaPdfjs(e,n,r,i){let{JpegImage:s}=await kt(),o=new s;o.parse(n);let a=o.getData({width:r,height:i,forceRGBA:true,isSourcePDF:true});if(a.length<r*i*4)return;let c=new ImageData(new Uint8ClampedArray(a.subarray(0,r*i*4)),r,i),l=this.resolveObject(e.dict.entries.get("SMask"));if(l&&U(l))try{let f=await this.decodeSMaskAlpha(l,r,i);Rt(c,f,r,i);}catch{}this.drawRgbaImageData(c,r,i);}async renderJpxViaPdfjs(e,n,r){var p,x,g;let i=(p=e.rawBytes)!=null?p:e.data;if(!i)return;let{JpxImage:s}=await kt(),o=new s;o.parse(i);let a=o.width||n,c=o.height||r,l=o.componentsCount||1,f=(g=(x=o.tiles)==null?void 0:x[0])==null?void 0:g.items;if(!f)return;let d=a*c,u=new Uint8ClampedArray(d*4);for(let b=0,P=0;b<d;b++,P+=4){let y=b*l;if(l>=4){let D=f[y],v=f[y+1],S=f[y+2],F=f[y+3];u[P]=255-Math.min(255,D+F),u[P+1]=255-Math.min(255,v+F),u[P+2]=255-Math.min(255,S+F);}else l===3?(u[P]=f[y],u[P+1]=f[y+1],u[P+2]=f[y+2]):u[P]=u[P+1]=u[P+2]=f[y];u[P+3]=255;}let h=new ImageData(u,a,c),m=this.resolveObject(e.dict.entries.get("SMask"));if(m&&U(m))try{let b=await this.decodeSMaskAlpha(m,a,c);Rt(h,b,a,c);}catch{}this.drawRgbaImageData(h,a,c);}async renderInlineImage(e,n){var l;this.captureImageBox("inline",null);let r={W:"Width",H:"Height",BPC:"BitsPerComponent",CS:"ColorSpace",F:"Filter",IM:"ImageMask",D:"Decode",DP:"DecodeParms",I:"Interpolate"},i={AHx:"ASCIIHexDecode",A85:"ASCII85Decode",LZW:"LZWDecode",Fl:"FlateDecode",RL:"RunLengthDecode",CCF:"CCITTFaxDecode",DCT:"DCTDecode"},s={G:"DeviceGray",RGB:"DeviceRGB",CMYK:"DeviceCMYK",I:"Indexed"},o=(f,d)=>f&&"type"in f&&f.type==="name"&&d[f.value]?{type:"name",value:d[f.value]}:f,a=new Map;for(let[f,d]of e.entries){let u=(l=r[f])!=null?l:f,h=d;if(u==="Filter")h=j(d)?{type:"array",items:d.items.map(m=>o(m,i))}:o(d,i);else if(u==="ColorSpace")if(d&&"type"in d&&d.type==="name"&&!s[d.value]&&!["DeviceGray","DeviceRGB","DeviceCMYK","Indexed"].includes(d.value)){let m=this.lookupResource("ColorSpace",d.value);h=m!=null?m:d;}else h=o(d,s);a.set(u,h);}let c={type:"stream",dict:{type:"dict",entries:a},data:n,rawBytes:n};await this.renderImageXObject(c);}lookupResource(e,n){if(!this.pageResources)return;let r=this.resolveObject(this.pageResources.entries.get(e));if(!(!r||!M(r)))return this.resolveObject(r.entries.get(n))}async decodeSMaskAlpha(e,n,r){var d,u,h,m;let i=wr(e.dict.entries.get("Filter")),s=i.includes("JPXDecode");if(i.includes("DCTDecode")||i.includes("DCT")||s){let p=(d=e.rawBytes)!=null?d:e.data;if(p&&p.length>0){let x=await fn(p,s?"image/jp2":"image/jpeg");try{let g=document.createElement("canvas");g.width=n,g.height=r;let b=g.getContext("2d");if(b){b.drawImage(x,0,0,n,r);let{data:P}=b.getImageData(0,0,n,r),y=new Uint8Array(n*r);for(let D=0;D<y.length;D++)y[D]=P[D*4];return y}}finally{dn(x);}}}let a=_.decodeStreamSync(e),c=Math.floor((u=A(e.dict.entries.get("BitsPerComponent")))!=null?u:8);if(c===8)return a;let l=Math.floor((h=A(e.dict.entries.get("Width")))!=null?h:n),f=Math.floor((m=A(e.dict.entries.get("Height")))!=null?m:r);return hn(a,l,f,1,c,true)}async renderImageWithSMask(e,n,r,i,s){let o=await fn(e,n);try{let a=document.createElement("canvas");a.width=i,a.height=s;let c=a.getContext("2d");if(!c){this.drawImageBitmapLike(o);return}c.drawImage(o,0,0,i,s);let l=c.getImageData(0,0,i,s);try{let f=await this.decodeSMaskAlpha(r,i,s);Rt(l,f,i,s);}catch{}c.putImageData(l,0,0),this.drawImageBitmapLike(a);}finally{dn(o);}}async renderStencilMask(e,n,r,i){try{let s=i!=null?i:_.decodeStreamSync(e),o=Ee(this.state.fillColor),a=Math.round(o.r*255),c=Math.round(o.g*255),l=Math.round(o.b*255),f=n*r,d=new Uint8ClampedArray(f*4),u=le(e.dict.entries.get("Decode")),h=!!u&&u.length>=2&&u[0]===1&&u[1]===0,m=0;for(let g=0;g<s.length&&m<f;g++){let b=s[g];for(let P=7;P>=0&&m<f;P--){let y=b>>P&1,D=m*4;y===1!==h&&(d[D]=a,d[D+1]=c,d[D+2]=l,d[D+3]=255),m++;}}let p=document.createElement("canvas");p.width=n,p.height=r;let x=p.getContext("2d");if(!x)return;x.putImageData(new ImageData(d,n,r),0,0),this.drawImageBitmapLike(p);}catch(s){this.logDebug("xobject:stencil-mask-failed",{error:s instanceof Error?s.message:String(s)});}}drawImageBitmapLike(e){this.ctx.save(),this.ctx.transform(1,0,0,-1,0,1),this.ctx.drawImage(e,0,0,1,1),this.ctx.restore();}decodeTextWithFont(e,n){var r;if(e.length===0)return "";if(this.debug){let i=String(this.state.font||"").toLowerCase();if(i==="f1"||i==="f2"){let s=Array.from(e.subarray(0,24)).map(a=>a.toString(16).padStart(2,"0")).join(" "),o=`${i}|${s}`;this.rawByteDiagnosticsLogged.has(o)||(this.rawByteDiagnosticsLogged.add(o),console.log(`[${i} RAW BYTES] ${s}`));}}if(n.toUnicode)return !n.toUnicode.isUsable&&n.isComposite?Vs(e,n.toUnicode):Ks(e,n.toUnicode,n.isComposite,this.state.font,this.debug);if(n.isComposite)return Er(e);if(n.encodingMap&&n.encodingMap.size>0){let i="";for(let s of e)i+=(r=n.encodingMap.get(s))!=null?r:String.fromCharCode(s);return i}return new TextDecoder("latin1").decode(e)}logDebug(e,n){this.debug&&console.debug(`[PageRenderer] ${e}`,n);}captureAtomicState(){return {transform:this.ctx.getTransform(),lineWidth:this.ctx.lineWidth,fillStyle:String(this.ctx.fillStyle),strokeStyle:String(this.ctx.strokeStyle),stackDepth:this.stateStack.length,samples:this.samplePixels()}}samplePixels(){let e=this.canvas.width,n=this.canvas.height;if(e<=0||n<=0)return [];let r=[[1,1],[Math.max(1,Math.floor(e/2)),Math.max(1,Math.floor(n/2))],[Math.max(1,e-2),Math.max(1,n-2)],[Math.max(1,Math.floor(e*.25)),Math.max(1,Math.floor(n*.25))],[Math.max(1,Math.floor(e*.75)),Math.max(1,Math.floor(n*.75))]],i=[],s=this.ctx.getTransform();this.ctx.setTransform(1,0,0,1,0,0);try{for(let[o,a]of r){let c=this.ctx.getImageData(Math.min(e-1,o),Math.min(n-1,a),1,1).data;i.push([c[0],c[1],c[2],c[3]]);}}finally{this.ctx.setTransform(s.a,s.b,s.c,s.d,s.e,s.f);}return i}logAtomic(e,n,r,i){if(!this.debugAtomic||this.atomicLogCount>=this.maxAtomicLogs)return;let s=JSON.stringify(r.samples),o=JSON.stringify(i.samples),a=s!==o;!(n.op==="stroke"||n.op==="fill"||n.op==="fill_even_odd"||n.op==="fill_stroke"||n.op==="show_string"||n.op==="show_strings")&&!a||(this.atomicLogCount+=1,console.debug("[PageRenderer][atomic]",{index:e,op:n.op,stackDepthBefore:r.stackDepth,stackDepthAfter:i.stackDepth,transformBefore:[r.transform.a,r.transform.b,r.transform.c,r.transform.d,r.transform.e,r.transform.f],transformAfter:[i.transform.a,i.transform.b,i.transform.c,i.transform.d,i.transform.e,i.transform.f],lineWidthBefore:r.lineWidth,lineWidthAfter:i.lineWidth,fillStyleBefore:r.fillStyle,fillStyleAfter:i.fillStyle,strokeStyleBefore:r.strokeStyle,strokeStyleAfter:i.strokeStyle,pixelChanged:a,samplesBefore:r.samples,samplesAfter:i.samples}));}applyExtGState(e){var m,p,x;if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("ExtGState"));if(!n||!M(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!M(r))return;let i=r,s=A(i.entries.get("LW"));s!==null&&(this.state.lineWidth=s,this.ctx.lineWidth=s);let o=A(i.entries.get("LC"));if(o!==null){let g=Math.floor(o),b=["butt","round","square"];this.state.lineCap=g,this.ctx.lineCap=(m=b[g])!=null?m:"butt";}let a=A(i.entries.get("LJ"));if(a!==null){let g=Math.floor(a),b=["miter","round","bevel"];this.state.lineJoin=g,this.ctx.lineJoin=(p=b[g])!=null?p:"miter";}let c=A(i.entries.get("ML"));c!==null&&(this.state.miterLimit=c,this.ctx.miterLimit=c);let l=i.entries.get("D");if(l&&j(l)&&l.items.length>=1){let g=l.items[0],b=(x=A(l.items[1]))!=null?x:0;if(j(g)){let P=g.items.map(y=>{var D;return (D=A(y))!=null?D:0});this.state.dashArray=P,this.state.dashPhase=b,this.ctx.setLineDash(P),this.ctx.lineDashOffset=b;}}let f=A(i.entries.get("CA"));f!==null&&(this.state.strokeAlpha=ne(f));let d=A(i.entries.get("ca"));d!==null&&(this.state.fillAlpha=ne(d));let u=i.entries.get("BM"),h=V(u);h&&(this.state.blendMode=h,this.ctx.globalCompositeOperation=Pr(h));}deviceBase(){if(this.initialTransform)return this.initialTransform;let e=this.scale;return [e,0,0,-e,0,e*this.pageHeight]}applyCurrentTransform(){let e=Y(this.deviceBase(),this.state.ctm);this.ctx.setTransform(e[0],e[1],e[2],e[3],e[4],e[5]);}resolvePatternFillStyle(e,n){var r,i,s;try{if(!this.pageResources||!this.objectLoader)return "transparent";let o=this.resolveObject(this.pageResources.entries.get("Pattern"));if(!o||!M(o))return "transparent";let a=this.resolveObject(o.entries.get(e));if(!a||!M(a)||Math.floor((r=A(a.entries.get("PatternType")))!=null?r:0)!==2)return "transparent";let l=this.resolveObject(a.entries.get("Shading"));if(!l||!M(l))return "transparent";let f=(i=rt(a.entries.get("Matrix")))!=null?i:[1,0,0,1,0,0];return (s=this.createCanvasGradient(l,f))!=null?s:"transparent"}catch{return "transparent"}}async resolvePattern(e,n){var o,a;let r=`${e}|${ve(n)}`,i=this.patternCache.get(r);if(i!==void 0)return i;let s=null;try{if(this.pageResources&&this.objectLoader){let c=this.resolveObject(this.pageResources.entries.get("Pattern")),l=c&&M(c)?this.resolveObject(c.entries.get(e)):void 0,f=l?U(l)?l.dict:M(l)?l:null:null;if(f){let d=Math.floor((o=A(f.entries.get("PatternType")))!=null?o:0),u=(a=rt(f.entries.get("Matrix")))!=null?a:[1,0,0,1,0,0];if(d===2){let h=this.resolveObject(f.entries.get("Shading")),m=h?U(h)?h.dict:M(h)?h:null:null;m&&(s={kind:"shading",shading:m,stream:h&&U(h)?h:null,matrix:u});}else d===1&&l&&U(l)&&(s=await this.renderTilingCell(l,f,u,n));}}}catch{s=null;}return this.patternCache.set(r,s),s}async applyPatternColor(e,n,r){let i=e==="fill"?this.state.fillColor:this.state.strokeColor,s=r.length>=4?{space:"cmyk",c:r[0],m:r[1],y:r[2],k:r[3]}:r.length===3?{space:"rgb",r:r[0],g:r[1],b:r[2]}:r.length===1?{space:"gray",gray:r[0]}:i,o=await this.resolvePattern(n,s);e==="fill"?(this.state.fillPatternName=n,this.state.fillPattern=o,o||(this.ctx.fillStyle="transparent")):(this.state.strokePatternName=n,this.state.strokePattern=o,o||(this.ctx.strokeStyle="transparent"));}async renderTilingCell(e,n,r,i){var v,S,F,w;if(this.patternDepth>=4)return null;let s=le(n.entries.get("BBox"));if(!s||s.length<4)return null;let o=[s[0],s[1],s[2],s[3]],a=o[2]-o[0],c=o[3]-o[1],l=(v=A(n.entries.get("XStep")))!=null?v:a,f=(S=A(n.entries.get("YStep")))!=null?S:c,d=Math.abs(l)<1e-9?a:l,u=Math.abs(f)<1e-9?c:f,h=Math.floor((F=A(n.entries.get("PaintType")))!=null?F:1),m=Y(this.deviceBase(),r),p=ur(o,d,u,m);if(!p)return null;let x=document.createElement("canvas"),g=new Ve(x,p.cellPxW,p.cellPxH,1,{disableClip:this.disableClip,transparentBackground:true,initialTransform:p.contentTransform,forcedColor:h===2?i:void 0,patternDepth:this.patternDepth+1}),b=this.resolveObject(n.entries.get("Resources"));g.setFontContext(b&&M(b)?b:void 0,(w=this.objectLoader)!=null?w:void 0);let P=e.decode?await e.decode():_.decodeStreamSync(e),y=Ue(P),D=a>0&&c>0?[{op:"rect",x:o[0],y:o[1],w:a,h:c},{op:"clip"},{op:"end_path"}]:[];return await g.renderAsync([...D,...y]),{kind:"tiling",cell:x,layout:p,matrix:r}}paintFill(e){let n=this.state.fillPattern;if(!n){this.ctx.globalAlpha=this.state.fillAlpha,e?this.ctx.fill(e):this.ctx.fill();return}this.paintPatternThroughPath(n,this.state.fillAlpha,e!=null?e:"nonzero");}paintStroke(){let e=this.state.strokePattern;if(this.ctx.globalAlpha=this.state.strokeAlpha,e)if(e.kind==="tiling"){let c=this.ctx.createPattern(e.cell,"repeat");c&&(this.ctx.strokeStyle=c);}else {let c=this.createCanvasGradient(e.shading,e.matrix);c&&(this.ctx.strokeStyle=c);}let n=this.deviceBase(),r=Math.sqrt(Math.abs(n[0]*n[3]-n[1]*n[2]))||1,i=this.state.ctm,s=Math.sqrt(Math.abs(i[0]*i[3]-i[1]*i[2]))||1,o=r*s,a=this.state.lineWidth*o;this.ctx.lineWidth=this.state.lineWidth===0||a<1?1/o:this.state.lineWidth,this.ctx.stroke();}paintPatternThroughPath(e,n,r){this.ctx.save();try{this.ctx.globalAlpha=n,this.ctx.clip(r);let i=Y(this.deviceBase(),e.matrix);if(e.kind==="tiling"){let s=this.ctx.createPattern(e.cell,"repeat");if(!s)return;let o=Y(i,e.layout.paintTransform);this.ctx.setTransform(o[0],o[1],o[2],o[3],o[4],o[5]),this.ctx.fillStyle=s,this.floodCanvasExtent(o,Math.max(e.layout.cellPxW,e.layout.cellPxH));}else this.paintShadingBackground(e.shading,i),this.paintShadingWithBase(e.shading,e.stream,i);}finally{this.ctx.restore();}}paintShadingBackground(e,n){var a,c;let r=le(e.entries.get("Background"));if(!r||!r.length)return;let i=(a=V(e.entries.get("ColorSpace")))!=null?a:"DeviceRGB",s=(c=Pe(i))!=null?c:"DeviceRGB",o=Ee(je(s,r));this.ctx.save(),this.ctx.setTransform(n[0],n[1],n[2],n[3],n[4],n[5]),this.ctx.fillStyle=ye(o.r,o.g,o.b),this.floodCanvasExtent(n,0),this.ctx.restore();}paintShadingWithBase(e,n,r){var s;let i=Math.floor((s=A(e.entries.get("ShadingType")))!=null?s:0);if(i===2||i===3){let o=this.createCanvasGradient(e);if(!o)return;this.ctx.save(),this.ctx.setTransform(r[0],r[1],r[2],r[3],r[4],r[5]),this.ctx.fillStyle=o,this.floodCanvasExtent(r,0),this.ctx.restore();return}if(i===1){this.paintFunctionShading(e,r);return}i>=4&&i<=7&&n&&this.paintMeshShading(i,e,n,r);}paintFunctionShading(e,n){var P,y,D,v,S,F,w,C;if(!this.objectLoader)return;let r=e.entries.get("Function");if(!r)return;let i=(P=le(e.entries.get("Domain")))!=null?P:[0,1,0,1],[s,o,a,c]=[(y=i[0])!=null?y:0,(D=i[1])!=null?D:1,(v=i[2])!=null?v:0,(S=i[3])!=null?S:1];if(!(o>s)||!(c>a))return;let l=(F=rt(e.entries.get("Matrix")))!=null?F:[1,0,0,1,0,0],f=(w=V(e.entries.get("ColorSpace")))!=null?w:"DeviceRGB",d=(C=Pe(f))!=null?C:"DeviceRGB",u=128,h=128,m=new ImageData(u,h);for(let O=0;O<h;O++){let E=a+(O+.5)/h*(c-a);for(let I=0;I<u;I++){let L=s+(I+.5)/u*(o-s),$=sn(r,[L,E],this.objectLoader);if(!$)continue;let H=Ee(je(d,$)),Z=(O*u+I)*4;m.data[Z]=Math.round(H.r*255),m.data[Z+1]=Math.round(H.g*255),m.data[Z+2]=Math.round(H.b*255),m.data[Z+3]=255;}}let p=document.createElement("canvas");p.width=u,p.height=h;let x=p.getContext("2d");if(!x)return;x.putImageData(m,0,0);let g=[(o-s)/u,0,0,(c-a)/h,s,a],b=Y(Y(n,l),g);this.ctx.save(),this.ctx.setTransform(b[0],b[1],b[2],b[3],b[4],b[5]),this.ctx.drawImage(p,0,0),this.ctx.restore();}paintMeshShading(e,n,r,i){var g,b,P,y,D,v;if(!this.objectLoader)return;let s=this.objectLoader,o=this.meshCache.get(n);if(!o){try{let S=_.decodeStreamSync(r),F=(g=V(n.entries.get("ColorSpace")))!=null?g:"DeviceRGB",w=(b=Pe(F))!=null?b:"DeviceRGB",C=n.entries.get("Function"),O=C?1:Ps(w),E=le(n.entries.get("Decode"));if(!E)return;let I=L=>{var Z;let $=C&&(Z=sn(C,L,s))!=null?Z:L,H=Ee(je(w,$));return [H.r,H.g,H.b]};o=fr(e,{bitsPerCoordinate:Math.floor((P=A(n.entries.get("BitsPerCoordinate")))!=null?P:16),bitsPerComponent:Math.floor((y=A(n.entries.get("BitsPerComponent")))!=null?y:8),bitsPerFlag:Math.floor((D=A(n.entries.get("BitsPerFlag")))!=null?D:8),decode:E,numColorComponents:O,verticesPerRow:(v=A(n.entries.get("VerticesPerRow")))!=null?v:void 0},S,I);}catch{o=[];}this.meshCache.set(n,o);}if(!o.length)return;let a=1/0,c=1/0,l=-1/0,f=-1/0;for(let S of o)for(let[F,w]of S.p){let C=J(i,F,w);C.x<a&&(a=C.x),C.x>l&&(l=C.x),C.y<c&&(c=C.y),C.y>f&&(f=C.y);}a=Math.max(0,Math.floor(a)),c=Math.max(0,Math.floor(c)),l=Math.min(this.canvas.width,Math.ceil(l)),f=Math.min(this.canvas.height,Math.ceil(f));let d=Math.min(4096,l-a),u=Math.min(4096,f-c);if(d<=0||u<=0)return;let h=Y([1,0,0,1,-a,-c],i),m=dr(o,h,d,u),p=document.createElement("canvas");p.width=d,p.height=u;let x=p.getContext("2d");x&&(x.putImageData(new ImageData(m,d,u),0,0),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(p,a,c),this.ctx.restore());}floodCanvasExtent(e,n){let r=He(e);if(!r)return;let i=this.canvas.width,s=this.canvas.height,o=[J(r,0,0),J(r,i,0),J(r,0,s),J(r,i,s)],a=o.map(h=>h.x),c=o.map(h=>h.y),l=Math.min(...a)-n,f=Math.min(...c)-n,d=Math.max(...a)+n,u=Math.max(...c)+n;this.ctx.fillRect(l,f,d-l,u-f);}createCanvasGradient(e,n){var x,g,b,P;let r=Math.floor((x=A(e.entries.get("ShadingType")))!=null?x:0),i=(g=V(e.entries.get("ColorSpace")))!=null?g:"DeviceRGB",s=(b=Pe(i))!=null?b:"DeviceRGB",o=e.entries.get("Function"),a=(P=le(e.entries.get("Domain")))!=null?P:[0,1],[c,l]=Fs(e.entries.get("Extend")),f=y=>{var S,F;let D=a[0]+y*(((S=a[1])!=null?S:1)-a[0]),v=this.objectLoader?(F=Ct(o,D,this.objectLoader))!=null?F:[0]:[0];return Ee(je(s,v))},d=y=>`rgb(${Math.round(y.r*255)},${Math.round(y.g*255)},${Math.round(y.b*255)})`,u=y=>`rgba(${Math.round(y.r*255)},${Math.round(y.g*255)},${Math.round(y.b*255)},0)`,h=le(e.entries.get("Coords"));if(!h)return null;let m=(y,D)=>n?[n[0]*y+n[2]*D+n[4],n[1]*y+n[3]*D+n[5]]:[y,D],p=y=>{let v=.000244140625,S=c?0:v,F=l?1:1-v;c||y.addColorStop(0,u(f(0)));for(let w=0;w<=64;w++){let C=w/64;y.addColorStop(S+C*(F-S),d(f(C)));}l||y.addColorStop(1,u(f(1)));};try{if(r===2){let[y,D,v,S]=h,[F,w]=m(y,D),[C,O]=m(v,S),E=this.ctx.createLinearGradient(F,w,C,O);return p(E),E}if(r===3){let[y,D,v,S,F,w]=h,[C,O]=m(y,D),[E,I]=m(S,F),L=n?(Math.hypot(n[0],n[1])+Math.hypot(n[2],n[3]))/2:1,$=this.ctx.createRadialGradient(C,O,Math.max(0,v*L),E,I,Math.max(0,w*L));return p($),$}}catch{return null}return null}acquireLayerCanvas(){var n;let e=(n=this.layerPool.pop())!=null?n:document.createElement("canvas");if(e.width!==this.canvas.width||e.height!==this.canvas.height)e.width=this.canvas.width,e.height=this.canvas.height;else {let r=e.getContext("2d");if(!r)return null;r.save(),r.setTransform(1,0,0,1,0,0),r.clearRect(0,0,e.width,e.height),r.restore();}return e}releaseLayerCanvas(e){this.layerPool.length<Ve.MAX_LAYER_DEPTH&&this.layerPool.push(e);}pushLayer(e,n,r,i){if(this.layerStack.length>=Ve.MAX_LAYER_DEPTH)return false;let s=this.acquireLayerCanvas(),o=s==null?void 0:s.getContext("2d");return !s||!o?false:(o.setTransform(this.ctx.getTransform()),o.lineWidth=this.ctx.lineWidth,o.lineCap=this.ctx.lineCap,o.lineJoin=this.ctx.lineJoin,o.miterLimit=this.ctx.miterLimit,o.setLineDash(this.ctx.getLineDash()),o.lineDashOffset=this.ctx.lineDashOffset,o.fillStyle=this.ctx.fillStyle,o.strokeStyle=this.ctx.strokeStyle,o.globalAlpha=1,o.globalCompositeOperation="source-over",this.layerStack.push({savedCtx:this.ctx,canvas:s,alpha:n,blend:r,mask:i,kind:e,stateDepthAtPush:this.stateStack.length}),this.ctx=o,true)}popLayer(){let e=this.layerStack.pop();if(!e)return;let n=e.canvas.getContext("2d");n&&e.mask&&(n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=1,n.globalCompositeOperation="destination-in",n.drawImage(e.mask,0,0),n.restore(),this.releaseLayerCanvas(e.mask)),this.ctx=e.savedCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.globalAlpha=e.alpha,this.ctx.globalCompositeOperation=Pr(e.blend),this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.releaseLayerCanvas(e.canvas);}async applySoftMaskFromExtGState(e){try{if(!this.pageResources)return;let n=this.resolveObject(this.pageResources.entries.get("ExtGState"));if(!n||!M(n))return;let r=this.resolveObject(n.entries.get(e));if(!r||!M(r))return;let i=r.entries.get("SMask");if(!i)return;if(V(i)==="None"){for(;this.layerStack.length>0;){let a=this.layerStack[this.layerStack.length-1];if(a.kind==="smask"&&a.stateDepthAtPush===this.stateStack.length)this.popLayer();else break}return}let s=this.resolveObject(i);if(!s||!M(s))return;let o=await this.renderSMaskCanvas(s);if(!o)return;this.pushLayer("smask",1,"Normal",o);}catch{}}async renderSMaskCanvas(e){var d;let n=this.resolveObject(e.entries.get("G"));if(!n||!U(n))return null;let r=((d=V(e.entries.get("S")))!=null?d:"Alpha")==="Luminosity",i=this.acquireLayerCanvas(),s=i==null?void 0:i.getContext("2d",{willReadFrequently:true});if(!i||!s)return null;if(r){let u=le(e.entries.get("BC"));if(s.save(),s.setTransform(1,0,0,1,0,0),u&&u.length){let h=Ee(je(u.length===1?"DeviceGray":u.length===4?"DeviceCMYK":"DeviceRGB",u));s.fillStyle=ye(h.r,h.g,h.b);}else s.fillStyle="black";s.fillRect(0,0,i.width,i.height),s.restore();}s.setTransform(this.ctx.getTransform());let o=this.ctx,a=this.capturedTextRuns.length;this.ctx=s,this.captureSuppressed+=1;try{await this.renderFormStreamInline(n);}finally{this.captureSuppressed-=1,this.ctx=o,this.capturedTextRuns.length=a;}let c=e.entries.get("TR"),l=this.objectLoader,f=c&&l&&V(c)!=="Identity"?u=>{let h=Ct(c,u,l);return h&&h.length?Math.max(0,Math.min(1,h[0])):u}:null;try{let u=s.getImageData(0,0,i.width,i.height),h=u.data;for(let m=0;m<h.length;m+=4){let p=r?(.3*h[m]+.59*h[m+1]+.11*h[m+2])/255:h[m+3]/255,x=f?f(p):p;h[m+3]=Math.round(x*255);}s.putImageData(u,0,0);}catch{return this.releaseLayerCanvas(i),null}return i}async renderFormStreamInline(e){let n=e.decode?await e.decode():_.decodeStreamSync(e),r=Ue(n),i=this.pageResources,s=this.objectLoader,o=this.patternCache;this.patternCache=new Map;let a=this.resolveObject(e.dict.entries.get("Resources"));this.pageResources=a&&M(a)?a:this.pageResources,this.execute({op:"save_state"});let c=rt(e.dict.entries.get("Matrix"));c&&this.execute({op:"set_ctm",matrix:c});let l=le(e.dict.entries.get("BBox"));l&&l.length>=4&&(this.ctx.beginPath(),this.ctx.rect(l[0],l[1],l[2]-l[0],l[3]-l[1]),this.ctx.clip());let f=this.commandIndex;this.xobjectDepth+=1;try{await this.runCommandsAsync(r);}finally{this.xobjectDepth-=1,this.commandIndex=f,this.execute({op:"restore_state"}),this.pageResources=i,this.objectLoader=s,this.patternCache=o;}}renderShadeOperator(e){try{if(!this.pageResources||!this.objectLoader)return;let n=this.resolveObject(this.pageResources.entries.get("Shading"));if(!n||!M(n))return;let r=this.resolveObject(n.entries.get(e)),i=r?U(r)?r.dict:M(r)?r:null:null;if(!i)return;let s=r&&U(r)?r:null;this.ctx.save();try{this.ctx.globalAlpha=this.state.fillAlpha;let o=le(i.entries.get("BBox"));o&&o.length>=4&&(this.ctx.beginPath(),this.ctx.rect(o[0],o[1],o[2]-o[0],o[3]-o[1]),this.ctx.clip());let a=Y(this.deviceBase(),this.state.ctm);this.paintShadingWithBase(i,s,a);}finally{this.ctx.restore();}}catch{}}};Ve.MAX_LAYER_DEPTH=6;var jt=Ve,Ps=t=>t==="DeviceGray"||t==="CalGray"?1:t==="DeviceCMYK"?4:3,Pr=t=>{switch(t){case "Normal":case "Compatible":return "source-over";case "Multiply":return "multiply";case "Screen":return "screen";case "Overlay":return "overlay";case "Darken":return "darken";case "Lighten":return "lighten";case "ColorDodge":return "color-dodge";case "ColorBurn":return "color-burn";case "HardLight":return "hard-light";case "SoftLight":return "soft-light";case "Difference":return "difference";case "Exclusion":return "exclusion";case "Hue":return "hue";case "Saturation":return "saturation";case "Color":return "color";case "Luminosity":return "luminosity";default:return "source-over"}},le=t=>!t||!j(t)?null:t.items.map(e=>{var n;return (n=A(e))!=null?n:0}),Ds=new Set(["FlateDecode","Fl","LZWDecode","LZW","ASCII85Decode","A85","ASCIIHexDecode","AHx","RunLengthDecode","RL","Crypt"]),ws=(t,e,n)=>{if(!e||e.length<2||n!=="DeviceGray"&&n!=="DeviceRGB"||!(e[0]===1&&e[1]===0))return;let r=t.data;for(let i=0;i<r.length;i+=4)r[i]=255-r[i],r[i+1]=255-r[i+1],r[i+2]=255-r[i+2];},rt=t=>{let e=le(t);return !e||e.length<6?null:[e[0],e[1],e[2],e[3],e[4],e[5]]},Ss=(t,e,n)=>{let r=[J(n,e[0],e[1]),J(n,e[2],e[1]),J(n,e[2],e[3]),J(n,e[0],e[3])],i=r.map(b=>b.x),s=r.map(b=>b.y),o=Math.min(...i),a=Math.max(...i),c=Math.min(...s),l=Math.max(...s),f=Math.min(t[0],t[2]),d=Math.max(t[0],t[2]),u=Math.min(t[1],t[3]),h=Math.max(t[1],t[3]),m=a-o,p=l-c;if(!(m>1e-6)||!(p>1e-6))return null;let x=(d-f)/m,g=(h-u)/p;return [x,0,0,g,f-x*o,u-g*c]},Fs=t=>{if(!t||!j(t))return [false,false];let e=n=>!!n&&typeof n=="object"&&"type"in n&&n.type==="boolean"&&n.value;return [e(t.items[0]),e(t.items[1])]},ye=(t,e,n)=>`rgb(${Math.round(ne(t)*255)},${Math.round(ne(e)*255)},${Math.round(ne(n)*255)})`,ve=t=>{if(t.space==="rgb")return ye(t.r,t.g,t.b);if(t.space==="gray")return ye(t.gray,t.gray,t.gray);let e=qe(t.c,t.m,t.y,t.k);return ye(e.r,e.g,e.b)},Ee=t=>{if(t.space==="rgb")return {r:ne(t.r),g:ne(t.g),b:ne(t.b)};if(t.space==="gray"){let e=ne(t.gray);return {r:e,g:e,b:e}}return qe(t.c,t.m,t.y,t.k)},Pe=t=>{switch(t){case "DeviceRGB":case "RGB":return "DeviceRGB";case "DeviceGray":case "G":case "Gray":return "DeviceGray";case "DeviceCMYK":case "CMYK":return "DeviceCMYK";default:return null}},Dr=t=>{var r;let e=V(t),n=e?Pe(e):null;if(n)return n;if(t&&j(t)&&t.items.length>0){let i=V(t.items[0]),s=i?Pe(i):null;if(s)return s;if(i==="ICCBased"){let o=t.items[1];if(o&&U(o)){let a=Math.floor((r=A(o.dict.entries.get("N")))!=null?r:0);if(a===1)return "DeviceGray";if(a===3)return "DeviceRGB";if(a===4)return "DeviceCMYK"}}if(i==="CalGray")return "DeviceGray";if(i==="CalRGB")return "DeviceRGB";if(i==="Lab")return "Lab";if(i==="Separation")return "Separation";if(i==="DeviceN")return "DeviceN";if(i==="Indexed")return "Indexed";if(i==="Pattern")return "Pattern"}return null},vs=(t,e,n)=>{let r=(t+16)/116,i=e/500+r,s=r-n/200,o=m=>m>.206897?m*m*m:(m-16/116)/7.787,a=.9642*o(i),c=1*o(r),l=.8249*o(s),f=3.1338561*a-1.6168667*c-.4906146*l,d=-0.9787684*a+1.9161415*c+.033454*l,u=.0719453*a-.2289914*c+1.4052427*l,h=m=>m<=.0031308?12.92*m:1.055*Math.pow(Math.max(0,m),1/2.4)-.055;return {r:ne(h(f)),g:ne(h(d)),b:ne(h(u))}},je=(t,e)=>{var r,i,s,o,a,c,l,f,d,u,h,m,p,x,g,b,P;let n=Pe(t);if(n==="DeviceGray")return {space:"gray",gray:(r=e[0])!=null?r:0};if(n==="DeviceCMYK")return {space:"cmyk",c:(i=e[0])!=null?i:0,m:(s=e[1])!=null?s:0,y:(o=e[2])!=null?o:0,k:(a=e[3])!=null?a:0};if(n==="DeviceRGB"||!n&&e.length===3)return {space:"rgb",r:(c=e[0])!=null?c:0,g:(l=e[1])!=null?l:0,b:(f=e[2])!=null?f:0};if(t==="Lab"){let y=vs((d=e[0])!=null?d:0,(u=e[1])!=null?u:0,(h=e[2])!=null?h:0);return {space:"rgb",r:y.r,g:y.g,b:y.b}}return t==="Separation"||t==="DeviceN"?{space:"gray",gray:1-((m=e[0])!=null?m:0)}:e.length>=4?{space:"cmyk",c:(p=e[0])!=null?p:0,m:(x=e[1])!=null?x:0,y:(g=e[2])!=null?g:0,k:(b=e[3])!=null?b:0}:{space:"gray",gray:(P=e[0])!=null?P:0}},wr=t=>{if(!t)return [];let e=V(t);return e?[e]:j(t)?t.items.map(n=>V(n)).filter(n=>n!==null):[]},fn=async(t,e)=>typeof createImageBitmap=="function"?createImageBitmap(new Blob([t.slice().buffer],{type:e})):new Promise((n,r)=>{let i=new Image,s=URL.createObjectURL(new Blob([t.slice().buffer],{type:e}));i.onload=()=>{URL.revokeObjectURL(s),n(i);},i.onerror=()=>{URL.revokeObjectURL(s),r(new Error(`Could not decode image ${e}`));},i.src=s;}),dn=t=>{"close"in t&&typeof t.close=="function"&&t.close();},Cs=(t,e)=>{let n=t.entries.get("Widths");if(!n||!j(n))return;let r=new Map;return n.items.forEach((i,s)=>{let o=A(i);o!==null&&r.set(e+s,o);}),r.size>0?r:void 0},Sr=(t,e)=>{let n=t.entries.get("DescendantFonts");if(!n||!j(n)||n.items.length===0)return;let r=e(n.items[0]);return r&&M(r)?r:void 0},Fr=(t,e,n)=>{let r=n(t.entries.get("FontDescriptor"));if(r&&M(r))return r;let i=n(e==null?void 0:e.entries.get("FontDescriptor"));return i&&M(i)?i:void 0},As=t=>{let e=t==null?void 0:t.entries.get("W");if(!e||!j(e))return;let n=new Map,r=e.items;for(let i=0;i<r.length;i+=1){let s=A(r[i]);if(s===null)continue;let o=r[i+1];if(o&&j(o)){o.items.forEach((l,f)=>{let d=A(l);d!==null&&n.set(s+f,d);}),i+=1;continue}let a=A(o),c=A(r[i+2]);if(!(a===null||c===null)){for(let l=s;l<=a;l+=1)n.set(l,c);i+=2;}}return n.size>0?n:void 0},Ms=t=>{let e=A(t==null?void 0:t.entries.get("DW"));return e!=null?e:void 0},ks=t=>{let e=t.entries.get("FontDescriptor");if(!e||!M(e))return;let n=A(e.entries.get("MissingWidth"));return n!=null?n:void 0},Rs=(t,e,n,r,i,s,o)=>{let a=n.isComposite?Es(t,n.toUnicode):Array.from(t).map((u,h)=>({code:u,bytes:t.slice(h,h+1)})),c=Array.from(e),l=!!n.widths||n.defaultWidth!==void 0,f=0;return {glyphs:a.map(u=>{var b,P,y;let h=n.toUnicode?Ae(u.code,n.toUnicode):null,m=(b=h!=null?h:c[f])!=null?b:"";f+=Math.max(1,Array.from(m).length);let p=(y=(P=n.widths)==null?void 0:P.get(u.code))!=null?y:n.defaultWidth,x;p!==void 0?x=p/1e3*r:o?x=o(m):x=(n.isComposite?1e3:500)/1e3*r,x>0||(x=o?Math.max(.01,o(m||" ")):r*.5);let g=i+(m===" "||u.code===32?s:0);return {text:m,code:u.code,bytes:u.bytes,glyphWidth:x,advance:x+g}}),hasPdfMetrics:l}},xn=t=>{var r;let e=It((r=t.baseFontName)!=null?r:"").toLowerCase(),n=Or(e);return t.registeredFamily?`"${t.registeredFamily}", ${n}`:n},vr=(t,e)=>{var o,a,c;let r=It((o=t.baseFontName)!=null?o:"").toLowerCase(),i=(a=t.fontStyle)!=null?a:r.includes("italic")||r.includes("oblique")?"italic":"normal",s=String((c=t.fontWeight)!=null?c:r.includes("bold")||r.includes("black")?700:400);return t.registeredFamily?`${e}px ${xn(t)}`:`${i} ${s} ${e}px ${Or(r)}`},Os=(t,e)=>{var o;let n=It(t!=null?t:"").toLowerCase(),r=A(e==null?void 0:e.entries.get("FontWeight"));if(r!==null)return Math.max(100,Math.min(900,Math.round(r/100)*100));let i=Math.floor((o=A(e==null?void 0:e.entries.get("Flags")))!=null?o:0),s=A(e==null?void 0:e.entries.get("StemV"));if(n.includes("bold")||n.includes("black")||n.includes("heavy")||(i&262144)!==0||s!==null&&s>=120)return 700},Ts=(t,e)=>{var s;let n=It(t!=null?t:"").toLowerCase(),r=Math.floor((s=A(e==null?void 0:e.entries.get("Flags")))!=null?s:0),i=A(e==null?void 0:e.entries.get("ItalicAngle"));if(n.includes("italic")||n.includes("oblique")||(r&64)!==0||i!==null&&i!==0)return "italic"},It=t=>/^[A-Z]{6}\+/.test(t)?t.slice(7):t,Or=t=>t.includes("courier")?'"Courier New", Courier, monospace':t.includes("times")||t.includes("serif")?'"Times New Roman", Times, serif':t.includes("symbol")?'Symbol, "Times New Roman", serif':t.includes("zapfdingbats")||t.includes("dingbats")?'ZapfDingbats, "Times New Roman", serif':(t.includes("helvetica")||t.includes("arial"),"Helvetica, Arial, sans-serif"),Es=(t,e)=>{var r,i;if(t.length===0)return [];if(e!=null&&e.codeSpaceRanges.length){let s=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,c)=>c-a),o=[];for(let a=0;a<t.length;){let c=0,l=0;for(let f of s){if(a+f>t.length)continue;let d=ze(t,a,f);if(d!==null&&jr(d,f,e.codeSpaceRanges)){c=f,l=d;break}}c===0&&(c=Math.min(2,t.length-a),l=(r=ze(t,a,c))!=null?r:t[a]),o.push({code:l,bytes:t.slice(a,a+c)}),a+=c;}return o}let n=[];for(let s=0;s<t.length;){let o=Math.min(2,t.length-s);n.push({code:(i=ze(t,s,o))!=null?i:t[s],bytes:t.slice(s,s+o)}),s+=o;}return n},js=t=>t==="DeviceCMYK"?4:t==="DeviceGray"||t==="Separation"?1:3,hn=(t,e,n,r,i,s)=>{var f,d,u,h;if(i===8)return t;let o=e*r,a=new Uint8Array(o*n);if(i===16){for(let m=0,p=0;m<a.length;m++,p+=2)a[m]=(f=t[p])!=null?f:0;return a}let c=(1<<i)-1,l=Math.ceil(o*i/8);for(let m=0;m<n;m++){let p=m*l,x=0;for(let g=0;g<o;g++){let b=p+(x>>3),y=8-(x&7),D;if(i<=y)D=((d=t[b])!=null?d:0)>>y-i&c;else {let v=i-y,S=((u=t[b])!=null?u:0)&(1<<y)-1,F=((h=t[b+1])!=null?h:0)>>8-v;D=S<<v|F;}a[m*o+g]=s?Math.round(D*255/c):D,x+=i;}}return a},Is=(t,e,n,r)=>{let i=e*n,s=new Uint8ClampedArray(i*4);if(r==="DeviceRGB"){if(t.length<i*3)return null;for(let a=0,c=0;c<s.length;a+=3,c+=4)s[c]=t[a],s[c+1]=t[a+1],s[c+2]=t[a+2],s[c+3]=255;return new ImageData(s,e,n)}if(r==="DeviceGray"){if(t.length<i)return null;for(let a=0,c=0;c<s.length;a+=1,c+=4){let l=t[a];s[c]=l,s[c+1]=l,s[c+2]=l,s[c+3]=255;}return new ImageData(s,e,n)}if(r==="DeviceCMYK"){if(t.length<i*4)return null;for(let a=0,c=0;c<s.length;a+=4,c+=4){let l=qe(t[a]/255,t[a+1]/255,t[a+2]/255,t[a+3]/255);s[c]=Math.round(l.r*255),s[c+1]=Math.round(l.g*255),s[c+2]=Math.round(l.b*255),s[c+3]=255;}return new ImageData(s,e,n)}let o=Math.floor(t.length/Math.max(1,i));if(o>=3){let a=o;for(let c=0,l=0;c<i;c++,l+=4){let f=c*a;s[l]=t[f],s[l+1]=t[f+1],s[l+2]=t[f+2],s[l+3]=255;}return new ImageData(s,e,n)}if(o>=1){let a=r==="Separation"||r==="DeviceN";for(let c=0,l=0;c<i;c++,l+=4){let f=a?255-t[c]:t[c];s[l]=f,s[l+1]=f,s[l+2]=f,s[l+3]=255;}return new ImageData(s,e,n)}return null},Rt=(t,e,n,r)=>{let i=t.data,s=n*r;for(let o=0;o<s&&o<e.length;o++)i[o*4+3]=e[o];},Bs=(t,e,n,r,i)=>{var u,h,m,p,x,g,b,P,y,D,v;if(r.length<4)return null;let s=(u=V(r[1]))!=null?u:"DeviceRGB",o=Math.floor((h=A(r[2]))!=null?h:255),a=i(r[3]),c=null;if(a&&U(a))try{c=_.decodeStreamSync(a);}catch{}else a&&typeof a=="object"&&"type"in a&&a.type==="string"&&(c=a.value);if(!c)return null;let l=s==="DeviceCMYK"?4:s==="DeviceGray"?1:3,f=e*n,d=new Uint8ClampedArray(f*4);for(let S=0;S<f;S++){let w=Math.min((m=t[S])!=null?m:0,o)*l,C=0,O=0,E=0;if(l===3)C=(p=c[w])!=null?p:0,O=(x=c[w+1])!=null?x:0,E=(g=c[w+2])!=null?g:0;else if(l===1)C=O=E=(b=c[w])!=null?b:0;else if(l===4){let L=qe(((P=c[w])!=null?P:0)/255,((y=c[w+1])!=null?y:0)/255,((D=c[w+2])!=null?D:0)/255,((v=c[w+3])!=null?v:0)/255);C=Math.round(L.r*255),O=Math.round(L.g*255),E=Math.round(L.b*255);}let I=S*4;d[I]=C,d[I+1]=O,d[I+2]=E,d[I+3]=255;}return new ImageData(d,e,n)},Us=t=>{var i;if(!t)return null;let e=t.match(/^uni([0-9A-Fa-f]{4,6})$/);if(e){let s=parseInt(e[1],16);try{return String.fromCodePoint(s)}catch{return null}}let n=t.match(/^u([0-9A-Fa-f]{5,6})$/);if(n){let s=parseInt(n[1],16);try{return String.fromCodePoint(s)}catch{return null}}return t.length===1?t:(i={space:" ",exclam:"!",quotedbl:'"',numbersign:"#",dollar:"$",percent:"%",ampersand:"&",quotesingle:"'",parenleft:"(",parenright:")",asterisk:"*",plus:"+",comma:",",hyphen:"-",period:".",slash:"/",zero:"0",one:"1",two:"2",three:"3",four:"4",five:"5",six:"6",seven:"7",eight:"8",nine:"9",colon:":",semicolon:";",less:"<",equal:"=",greater:">",question:"?",at:"@",A:"A",B:"B",C:"C",D:"D",E:"E",F:"F",G:"G",H:"H",I:"I",J:"J",K:"K",L:"L",M:"M",N:"N",O:"O",P:"P",Q:"Q",R:"R",S:"S",T:"T",U:"U",V:"V",W:"W",X:"X",Y:"Y",Z:"Z",bracketleft:"[",backslash:"\\",bracketright:"]",asciicircum:"^",underscore:"_",grave:"`",a:"a",b:"b",c:"c",d:"d",e:"e",f:"f",g:"g",h:"h",i:"i",j:"j",k:"k",l:"l",m:"m",n:"n",o:"o",p:"p",q:"q",r:"r",s:"s",t:"t",u:"u",v:"v",w:"w",x:"x",y:"y",z:"z",braceleft:"{",bar:"|",braceright:"}",asciitilde:"~",exclamdown:"\xA1",cent:"\xA2",sterling:"\xA3",currency:"\xA4",yen:"\xA5",brokenbar:"\xA6",section:"\xA7",dieresis:"\xA8",copyright:"\xA9",ordfeminine:"\xAA",guillemotleft:"\xAB",logicalnot:"\xAC",minus:"\u2212",registered:"\xAE",macron:"\xAF",degree:"\xB0",plusminus:"\xB1",twosuperior:"\xB2",threesuperior:"\xB3",acute:"\xB4",mu:"\xB5",paragraph:"\xB6",periodcentered:"\xB7",cedilla:"\xB8",onesuperior:"\xB9",ordmasculine:"\xBA",guillemotright:"\xBB",onequarter:"\xBC",onehalf:"\xBD",threequarters:"\xBE",questiondown:"\xBF",Agrave:"\xC0",Aacute:"\xC1",Acircumflex:"\xC2",Atilde:"\xC3",Adieresis:"\xC4",Aring:"\xC5",AE:"\xC6",Ccedilla:"\xC7",Egrave:"\xC8",Eacute:"\xC9",Ecircumflex:"\xCA",Edieresis:"\xCB",Igrave:"\xCC",Iacute:"\xCD",Icircumflex:"\xCE",Idieresis:"\xCF",Eth:"\xD0",Ntilde:"\xD1",Ograve:"\xD2",Oacute:"\xD3",Ocircumflex:"\xD4",Otilde:"\xD5",Odieresis:"\xD6",multiply:"\xD7",Oslash:"\xD8",Ugrave:"\xD9",Uacute:"\xDA",Ucircumflex:"\xDB",Udieresis:"\xDC",Yacute:"\xDD",Thorn:"\xDE",germandbls:"\xDF",agrave:"\xE0",aacute:"\xE1",acircumflex:"\xE2",atilde:"\xE3",adieresis:"\xE4",aring:"\xE5",ae:"\xE6",ccedilla:"\xE7",egrave:"\xE8",eacute:"\xE9",ecircumflex:"\xEA",edieresis:"\xEB",igrave:"\xEC",iacute:"\xED",icircumflex:"\xEE",idieresis:"\xEF",eth:"\xF0",ntilde:"\xF1",ograve:"\xF2",oacute:"\xF3",ocircumflex:"\xF4",otilde:"\xF5",odieresis:"\xF6",divide:"\xF7",oslash:"\xF8",ugrave:"\xF9",uacute:"\xFA",ucircumflex:"\xFB",udieresis:"\xFC",yacute:"\xFD",thorn:"\xFE",ydieresis:"\xFF",OE:"\u0152",oe:"\u0153",Scaron:"\u0160",scaron:"\u0161",Ydieresis:"\u0178",Zcaron:"\u017D",zcaron:"\u017E",florin:"\u0192",circumflex:"\u02C6",tilde:"\u02DC",endash:"\u2013",emdash:"\u2014",quotedblleft:"\u201C",quotedblright:"\u201D",quoteleft:"\u2018",quoteright:"\u2019",quotesinglbase:"\u201A",quotedblbase:"\u201E",dagger:"\u2020",daggerdbl:"\u2021",bullet:"\u2022",ellipsis:"\u2026",perthousand:"\u2030",guilsinglleft:"\u2039",guilsinglright:"\u203A",fraction:"\u2044",Euro:"\u20AC",trademark:"\u2122",fi:"\uFB01",fl:"\uFB02",ff:"\uFB00",ffi:"\uFB03",ffl:"\uFB04",lslash:"\u0142",Lslash:"\u0141",dotaccent:"\u02D9",ring:"\u02DA",caron:"\u02C7",breve:"\u02D8",dotlessi:"\u0131",hungarumlaut:"\u02DD",ogonek:"\u02DB",Delta:"\u2206",Omega:"\u03A9",pi:"\u03C0",infinity:"\u221E",lessequal:"\u2264",greaterequal:"\u2265",notequal:"\u2260",approxequal:"\u2248",radical:"\u221A",summation:"\u2211",product:"\u220F",integral:"\u222B",partialdiff:"\u2202",lozenge:"\u25CA",apple:"\uF8FF"}[t])!=null?i:null},Cr=(()=>{let t=[[128,196],[129,197],[130,199],[131,201],[132,209],[133,214],[134,220],[135,225],[136,224],[137,226],[138,228],[139,227],[140,229],[141,231],[142,233],[143,232],[144,234],[145,235],[146,237],[147,236],[148,238],[149,239],[150,241],[151,243],[152,242],[153,244],[154,246],[155,250],[156,249],[157,251],[158,252],[159,8224],[160,176],[161,162],[162,163],[163,167],[164,8226],[165,182],[166,223],[167,174],[168,169],[169,8482],[170,180],[171,168],[172,8800],[173,198],[174,216],[175,8734],[176,177],[177,8804],[178,8805],[179,165],[180,181],[181,8706],[182,8721],[183,8719],[184,960],[185,8747],[186,170],[187,186],[188,937],[189,230],[190,248],[191,191],[192,161],[193,172],[194,8730],[195,402],[196,8776],[197,8710],[198,171],[199,187],[200,8230],[201,160],[202,192],[203,195],[204,213],[205,338],[206,339],[207,8211],[208,8212],[209,8220],[210,8221],[211,8216],[212,8217],[213,247],[214,9674],[215,255],[216,376],[217,8260],[218,8364],[219,8249],[220,8250],[221,64257],[222,64258],[223,8225],[224,183],[225,8218],[226,8222],[227,8240],[228,194],[229,202],[230,193],[231,203],[232,200],[233,205],[234,206],[235,207],[236,204],[237,211],[238,212],[239,210],[240,218],[241,219],[242,217],[243,305],[244,710],[245,732],[246,175],[247,728],[248,729],[249,730],[250,184],[251,733],[252,731],[253,711],[254,254],[255,255]],e=new Map;for(let[n,r]of t)e.set(n,String.fromCodePoint(r));return e})(),Ar=(()=>{let t=[[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]],e=new Map;for(let[n,r]of t)e.set(n,String.fromCodePoint(r));return e})(),Ls=(t,e)=>{if(!t)return;let n=e(t);if(!n)return;let r=V(n);if(r)return r==="MacRomanEncoding"?new Map(Cr):r==="WinAnsiEncoding"?new Map(Ar):void 0;if(!M(n))return;let i=n,s=V(i.entries.get("BaseEncoding")),o;s==="MacRomanEncoding"?o=new Map(Cr):s==="WinAnsiEncoding"?o=new Map(Ar):o=new Map;let a=i.entries.get("Differences");if(!a||!j(a))return o.size>0?o:void 0;let c=0;for(let l of a.items){let f=A(l);if(f!==null)c=Math.floor(f);else {let d=V(l);if(d){let u=Us(d);u&&o.set(c,u),c++;}}}return o.size>0?o:void 0},$s=(t,e)=>{let n=new Map;if(!t)return n;let r=e(t);if(!r||!M(r))return n;let i=r.entries.get("Differences");if(!i||!j(i))return n;let s=0;for(let o of i.items){let a=A(o);if(a!==null)s=Math.floor(a);else {let c=V(o);c&&(n.set(s,c),s++);}}return n},qe=(t,e,n,r)=>({r:(1-ne(t))*(1-ne(r)),g:(1-ne(e))*(1-ne(r)),b:(1-ne(n))*(1-ne(r))}),ne=t=>!Number.isFinite(t)||t<0?0:t>1?1:t,_s=(t,e,n)=>Number.isFinite(t)?Math.min(n,Math.max(e,t)):e,Ns=t=>({...t,ctm:[...t.ctm],textMatrix:[...t.textMatrix],textLineMatrix:[...t.textLineMatrix],fillColor:{...t.fillColor},strokeColor:{...t.strokeColor},dashArray:[...t.dashArray]}),J=(t,e,n)=>({x:t[0]*e+t[2]*n+t[4],y:t[1]*e+t[3]*n+t[5]}),Ot=()=>({subtype:"Unknown",baseFontName:void 0,isComposite:false,firstChar:void 0,widths:void 0,defaultWidth:void 0,toUnicode:null}),Ws=t=>{let e={bfChar:new Map,bfRange:[],codeSpaceRanges:[],cmapType:0,isUsable:true},n=t.match(/\/CMapType\s+(\d+)\s+def/);n&&(e.cmapType=Number.parseInt(n[1],10),e.isUsable=e.cmapType!==0);let r=t.replace(/\r\n/g,`
4
+ `).replace(/\r/g,`
5
+ `),i=Gs(r);for(let s=0;s<i.length;){let o=i[s];if(o==="usecmap"){let a=s>0?i[s-1]:"(unknown)";console.warn("[PageRenderer][CMap] usecmap reference not resolved",{inheritedName:a}),s+=1;continue}if(o==="begincmap"){for(s+=1;s<i.length&&i[s]!=="endcmap";){let a=i[s];if(Ys(a))break;let c=i[s+1];if(we(a)&&we(c)){e.bfChar.set(Et(a),Tt(Le(c))),s+=2;continue}s+=1;}continue}if(o==="beginbfchar"||o==="begincidchar"){for(s+=1;s<i.length&&i[s]!=="endbfchar"&&i[s]!=="endcidchar";){let a=i[s],c=i[s+1];if(we(a)&&we(c)){e.bfChar.set(Et(a),Tt(Le(c))),s+=2;continue}if(it(a)&&we(c)){e.bfChar.set(Number.parseInt(a,10),Tt(Le(c))),s+=2;continue}if(it(a)&&it(c)){let l=Number.parseInt(a,10),f=Number.parseInt(c,10);if(Number.isFinite(l)&&Number.isFinite(f))try{e.bfChar.set(l,String.fromCodePoint(f));}catch{e.bfChar.set(l,"\uFFFD");}s+=2;continue}s+=1;}s<i.length&&(s+=1);continue}if(o==="begincodespacerange"){for(s+=1;s<i.length&&i[s]!=="endcodespacerange";){let a=i[s],c=i[s+1];if(!we(a)||!we(c)){s+=1;continue}let l=Le(a),f=Le(c),d=Math.max(l.length,f.length)/2;d>0&&e.codeSpaceRanges.push({start:Number.parseInt(l,16),end:Number.parseInt(f,16),byteLength:d}),s+=2;}s<i.length&&(s+=1);continue}if(o==="beginbfrange"||o==="begincidrange"){for(s+=1;s<i.length&&i[s]!=="endbfrange"&&i[s]!=="endcidrange";){let a=i[s],c=i[s+1];if(!a||!c){s+=1;continue}let l=Mr(a),f=Mr(c);if(l===null||f===null){s+=1;continue}let d=i[s+2];if(!d){s+=2;continue}if(d==="["){let u=[],h=s+3;for(;h<i.length&&i[h]!=="]";)we(i[h])&&u.push(Tt(Le(i[h]))),h+=1;e.bfRange.push({start:l,end:f,mapped:u}),s=h<i.length?h+1:h;continue}if(we(d)){e.bfRange.push({start:l,end:f,unicodeStart:Et(d)}),s+=3;continue}if(it(d)){e.bfRange.push({start:l,end:f,unicodeStart:Number.parseInt(d,10)}),s+=3;continue}s+=1;}s<i.length&&(s+=1);continue}s+=1;}return e},Gs=t=>{let e=[],n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n+=1;if(n>=t.length)break;if(t[n]==="%"){for(;n<t.length&&t[n]!==`
6
+ `;)n+=1;continue}if(t[n]==="<"){let i=n;for(n+=1;n<t.length&&t[n]!==">";)n+=1;n<t.length&&(n+=1),e.push(t.slice(i,n));continue}if(t[n]==="["||t[n]==="]"){e.push(t[n]),n+=1;continue}let r=n;for(;n<t.length&&!/[\s<\[\]%]/.test(t[n]);)n+=1;if(r<n){let i=t.slice(r,n),s=Xs(i);s?(s.count&&e.push(s.count),e.push(s.keyword)):e.push(i);}}return e},Xs=t=>{let e=t.match(/^(\d+)?(begin\w+|end\w+|usecmap|begincmap|endcmap)$/i);return e?{count:e[1],keyword:e[2]}:null},Ys=t=>t?t==="beginbfchar"||t==="endbfchar"||t==="beginbfrange"||t==="endbfrange"||t==="begincidchar"||t==="endcidchar"||t==="begincidrange"||t==="endcidrange"||t==="begincodespacerange"||t==="endcodespacerange":false,we=t=>!!t&&t.startsWith("<")&&t.endsWith(">"),it=t=>!!t&&/^\d+$/.test(t),Le=t=>t.slice(1,-1),Et=t=>Number.parseInt(Le(t),16),Mr=t=>we(t)?Et(t):it(t)?Number.parseInt(t,10):null,Tt=t=>{let e=t.length%2===0?t:`0${t}`;if(e.length===0)return "";if(e.length<=4){let r=Number.parseInt(e,16);if(!Number.isFinite(r))return "\uFFFD";try{return String.fromCodePoint(r)}catch{return "\uFFFD"}}let n="";for(let r=0;r<e.length;r+=4){let i=e.slice(r,r+4).padStart(4,"0"),s=Number.parseInt(i,16);if(!Number.isFinite(s)){n+="\uFFFD";continue}try{n+=String.fromCodePoint(s);}catch{n+="\uFFFD";}}return n},Hs=(t,e)=>{var r;console.log(`=== CMap debug for font ${e} ===`),console.log(`cmapType: ${t.cmapType}`),console.log(`isUsable: ${t.isUsable}`),console.log(`bfChar entries: ${t.bfChar.size}`),console.log(`bfRange entries: ${t.bfRange.length}`),console.log(`codespace ranges: ${t.codeSpaceRanges.length}`);let n=0;for(let[i,s]of t.bfChar.entries()){if(n>=10)break;let o=s.codePointAt(0);console.log(` 0x${i.toString(16).padStart(4,"0")} -> "${s}" (U+${(r=o==null?void 0:o.toString(16).toUpperCase())!=null?r:"????"})`),n+=1;}for(let i of t.bfRange.slice(0,5))typeof i.unicodeStart=="number"?console.log(` range 0x${i.start.toString(16).padStart(4,"0")}-0x${i.end.toString(16).padStart(4,"0")} -> U+${i.unicodeStart.toString(16).toUpperCase()}`):i.mapped&&console.log(` range 0x${i.start.toString(16).padStart(4,"0")}-0x${i.end.toString(16).padStart(4,"0")} -> [mapped:${i.mapped.length}]`);for(let i of t.codeSpaceRanges.slice(0,5))console.log(` codespace ${i.byteLength}b 0x${i.start.toString(16).padStart(i.byteLength*2,"0")}-0x${i.end.toString(16).padStart(i.byteLength*2,"0")}`);},Ae=(t,e)=>{let n=e.bfChar.get(t);if(n!==void 0)return n;for(let r of e.bfRange)if(!(t<r.start||t>r.end)){if(r.mapped){let i=t-r.start;return i>=0&&i<r.mapped.length?r.mapped[i]:null}if(typeof r.unicodeStart=="number"){let i=r.unicodeStart+(t-r.start);return String.fromCodePoint(i)}}return null},Ks=(t,e,n,r,i=false)=>{var o,a;if(n){let c=oo(e),l=Js(e),d=(l?[{mode:"raw",bytes:t}]:qs(t)).map(x=>({mode:x.mode,attempt:zs(x.bytes,e,c)})),u=Zs(d),h=u.attempt,m=lo(h)?uo(t):null,p=fo(h,m);if(i&&console.debug("[PageRenderer][CMap] decode strategy",{font:r!=null?r:"?",mapped:h.mapped,unmapped:h.unmapped,utf16Score:(o=m==null?void 0:m.score)!=null?o:null,codespaceRanges:e.codeSpaceRanges.length,inferredCodeLengths:c,payloadMode:u.mode,sparseToUnicode:l,chosen:p===m?"utf16be":"cmap"}),i&&h.unmappedGlyphs.length>0){let x=h.unmappedGlyphs.slice(0,12).map(P=>`0x${P.toString(16).padStart(4,"0")}`),g=ao(h.unmappedGlyphs,c),b=l?`${r!=null?r:"?"}|sparse-tounicode`:`${r!=null?r:"?"}|${u.mode}`;xr.has(b)||(xr.add(b),console.warn("[PageRenderer][CMap] unmapped composite glyphs",{font:r!=null?r:"?",count:h.unmappedGlyphs.length,payloadMode:u.mode,sparseToUnicode:l,rootCause:l?`ToUnicode is too sparse (bfChar=${e.bfChar.size}, bfRange=${e.bfRange.length}); Unicode recovery is fundamentally limited for this font.`:void 0,sample:x,topMissing:g.topMissing,mappingHints:g.mappingHints,note:"Use mappingHints as candidate ToUnicode entries (<src> <dst>) for manual verification."}));}return (a=p==null?void 0:p.text)!=null?a:h.text}let s="";for(let c=0;c<t.length;c++){let l=Ae(t[c],e);s+=l!==null?l:String.fromCharCode(t[c]);}return s},Vs=(t,e)=>{let n="",r=0;for(;r+1<t.length;){let i=t[r],s=t[r+1],o=i<<8|s,a=Ae(o,e);if(a!==null){n+=a,r+=2;continue}if(s>=32&&s<=126){n+=String.fromCharCode(s),r+=2;continue}if(i>=32&&i<=126){n+=String.fromCharCode(i),r+=2;continue}r+=2;}if(r<t.length){let i=t[r];i>=32&&i<=126&&(n+=String.fromCharCode(i));}return n},zs=(t,e,n)=>e.codeSpaceRanges.length>0?io(t,e):so(t,e,n),qs=t=>{var o;let e=[{mode:"raw",bytes:t}],n=new Set([`raw:${t.length}:${(o=t[0])!=null?o:-1}`]),r=(a,c)=>{var f,d;if(!c||c.length===0)return;let l=`${a}:${c.length}:${(f=c[0])!=null?f:-1}:${(d=c[1])!=null?d:-1}`;n.has(l)||(n.add(l),e.push({mode:a,bytes:c}));},i=Qs(t);r("zero-stripped",i);let s=eo(t);return r("pair-swapped",s),r("ascii-hex",mn(t)),i&&r("zero-stripped+ascii-hex",mn(i)),s&&r("pair-swapped+ascii-hex",mn(s)),e},Js=t=>t.bfChar.size+t.bfRange.length<=2,Zs=t=>{let e=t[0],n=kr(e.attempt);for(let r=1;r<t.length;r+=1){let i=t[r],s=kr(i.attempt);s>n+1&&(e=i,n=s);}return e},Qs=t=>{if(t.length<4||t.length%2!==0)return null;let e=0,n=0;for(let a=0;a<t.length;a+=2)t[a]===0&&(e+=1),t[a+1]===0&&(n+=1);let r=t.length/2,i=e>=Math.floor(r*.7),s=n>=Math.floor(r*.7);if(!i&&!s)return null;let o=new Uint8Array(r);for(let a=0;a<r;a+=1)o[a]=i?t[a*2+1]:t[a*2];return o},eo=t=>{if(t.length<2||t.length%2!==0)return null;let e=new Uint8Array(t.length);for(let n=0;n<t.length;n+=2)e[n]=t[n+1],e[n+1]=t[n];return e},kr=t=>t.mapped*2-t.unmapped,mn=t=>{if(t.length<8)return null;let e=0,n=0,r=0,i=[];for(let o of t)if(!to(o)){if(n+=1,!no(o))return null;(o>=65&&o<=70||o>=97&&o<=102)&&(r+=1),e+=1,i.push(String.fromCharCode(o));}if(n<8||e!==n||e%2!==0||r===0)return null;let s=new Uint8Array(e/2);for(let o=0;o<s.length;o+=1){let a=Rr(i[o*2]),c=Rr(i[o*2+1]);if(a<0||c<0)return null;s[o]=a<<4|c;}return s},to=t=>t===32||t===9||t===10||t===13,no=t=>t>=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102,Rr=t=>t>="0"&&t<="9"?t.charCodeAt(0)-48:t>="a"&&t<="f"?t.charCodeAt(0)-97+10:t>="A"&&t<="F"?t.charCodeAt(0)-65+10:-1,ro=(t,e)=>{let n="",r=0,i=0,s=[];for(let o=0;o<t.length;){if(o+1<t.length){let c=t[o]<<8|t[o+1],l=Ae(c,e);if(l!==null){n+=l,r+=1,o+=2;continue}let f=Ae(t[o],e),d=Ae(t[o+1],e);if(f!==null||d!==null){n+="\uFFFD\uFFFD",i+=1,s.push(c),o+=2;continue}n+="\uFFFD",i+=1,s.push(c),o+=2;continue}let a=Ae(t[o],e);a!==null?(n+=a,r+=1):(n+="\uFFFD",i+=1,s.push(t[o])),o+=1;}return {text:n,mapped:r,unmapped:i,unmappedGlyphs:s}},io=(t,e)=>{let n=Array.from(new Set(e.codeSpaceRanges.map(a=>a.byteLength))).sort((a,c)=>c-a);if(n.length===0)return ro(t,e);let r="",i=0,s=0,o=[];for(let a=0;a<t.length;){let c=0,l=null;for(let d of n){if(a+d>t.length)continue;let u=ze(t,a,d);if(u!==null&&jr(u,d,e.codeSpaceRanges)){c=d,l=u;break}}if(c>0&&l!==null){let d=Ae(l,e);d!==null?(r+=d,i+=1):(r+="\uFFFD",s+=1,o.push(l)),a+=c;continue}let f=a+1<t.length?t[a]<<8|t[a+1]:t[a];r+="\uFFFD",s+=1,o.push(f),a+=1;}return {text:r,mapped:i,unmapped:s,unmappedGlyphs:o}},so=(t,e,n)=>{var c,l;let r=n.length>0?[...n].sort((f,d)=>d-f):[2,1],i="",s=0,o=0,a=[];for(let f=0;f<t.length;){let d=0,u=null;for(let p of r){if(f+p>t.length)continue;let x=ze(t,f,p);if(x===null)continue;let g=Ae(x,e);if(g!==null){u=g,d=p;break}}if(u!==null&&d>0){i+=u,s+=1,f+=d;continue}let h=(c=r[r.length-1])!=null?c:1,m=(l=ze(t,f,Math.min(h,t.length-f)))!=null?l:t[f];i+="\uFFFD",o+=1,a.push(m),f+=Math.min(h,t.length-f);}return {text:i,mapped:s,unmapped:o,unmappedGlyphs:a}},oo=t=>{let e=new Set;for(let r of t.codeSpaceRanges)r.byteLength>=1&&r.byteLength<=4&&e.add(r.byteLength);for(let r of t.bfChar.keys())e.add(pn(r));for(let r of t.bfRange)e.add(pn(r.start)),e.add(pn(r.end));let n=Array.from(e).filter(r=>r>=1&&r<=4);return n.length===0?[2,1]:n.sort((r,i)=>i-r)},pn=t=>t<=255?1:t<=65535?2:t<=16777215?3:4,ao=(t,e)=>{var c;let n=new Map;for(let l of t)n.set(l,((c=n.get(l))!=null?c:0)+1);let i=Array.from(n.entries()).sort((l,f)=>f[1]-l[1]).slice(0,8),s=i.map(([l,f])=>({glyph:`0x${l.toString(16).padStart(4,"0")}`,count:f})),o=e.length>0?e[e.length-1]:2,a=i.map(([l])=>co(l,o)).filter(l=>l!==null);return {topMissing:s,mappingHints:a}},co=(t,e)=>{let n=t.toString(16).padStart(Math.max(4,e*2),"0"),r=t&255;if(r>=32&&r<=126){let i=r.toString(16).toUpperCase().padStart(4,"0");return {glyph:`0x${n}`,candidateUnicode:`U+${i} (${String.fromCharCode(r)})`,reason:"Printable ASCII low-byte candidate",cmapLine:`<${n}> <${i}>`}}if(t>=32&&t<=126){let i=t.toString(16).toUpperCase().padStart(4,"0");return {glyph:`0x${n}`,candidateUnicode:`U+${i} (${String.fromCharCode(t)})`,reason:"Direct ASCII glyph code candidate",cmapLine:`<${n}> <${i}>`}}return null},lo=t=>t.text.length===0?false:t.mapped>0?t.unmapped>=t.mapped*3:t.unmapped>0,uo=t=>{var s;let e=Er(t),n=Tr(e),r=((s=e.match(/\uFFFD/g))!=null?s:[]).length,i=n-r*3;return {text:e,mapped:n,unmapped:r,unmappedGlyphs:[],printable:n,score:i}},fo=(t,e)=>{if(!e)return t;let n=ho(t.text);return mo(e.text)&&e.score>=n+8?e:t},ho=t=>{var r;let e=Tr(t),n=((r=t.match(/\uFFFD/g))!=null?r:[]).length;return e-n*3},Tr=t=>{var n;let e=0;for(let r of t){let i=(n=r.codePointAt(0))!=null?n:0;if(i===9||i===10||i===13){e+=1;continue}if(i>=32&&i<=126){e+=2;continue}if(i>=160&&i<=591){e+=1;continue}}return e},mo=t=>{var i,s;if(!t||((i=t.match(/\uFFFD/g))!=null?i:[]).length>Math.floor(t.length*.2))return false;let n=0,r=0;for(let o of t){let a=(s=o.codePointAt(0))!=null?s:0;if(a>=32&&a<=126){n+=1;continue}(a>=12288&&a<=12351||a>=8592&&a<=8703)&&(r+=1);}return n>=8&&n*2>=t.length?true:(r>0&&r*2>=t.length,false)},V=t=>t?typeof t=="string"?t:typeof t=="object"&&"type"in t&&t.type==="name"&&"value"in t?String(t.value):null:null,Er=t=>{if(t.length<2)return new TextDecoder("latin1").decode(t);let e="";for(let n=0;n+1<t.length;n+=2){let r=t[n]<<8|t[n+1];e+=String.fromCharCode(r);}return t.length%2!==0&&(e+="\uFFFD"),e},po=t=>{var e,n,r,i,s,o,a;return {length:t.length,beginbfchar:((e=t.match(/beginbfchar/g))!=null?e:[]).length,beginbfrange:((n=t.match(/beginbfrange/g))!=null?n:[]).length,begincidchar:((r=t.match(/begincidchar/g))!=null?r:[]).length,begincidrange:((i=t.match(/begincidrange/g))!=null?i:[]).length,begincodespacerange:((s=t.match(/begincodespacerange/g))!=null?s:[]).length,usecmap:((o=t.match(/usecmap/g))!=null?o:[]).length,hexTokens:((a=t.match(/<[0-9a-fA-F]+>/g))!=null?a:[]).length,preview:t.slice(0,220)}},Ce=t=>{var e,n,r;if(!t)return "undefined";if(typeof t=="string")return `string:${t}`;if(typeof t=="number")return "number";if(typeof t=="boolean")return "boolean";if(typeof t=="object"&&"type"in t){let i=String((e=t.type)!=null?e:"unknown");return i==="ref"&&"objectNumber"in t?`ref:${String((n=t.objectNumber)!=null?n:"?")}`:i==="name"&&"value"in t?`name:${String((r=t.value)!=null?r:"")}`:i}return typeof t},ze=(t,e,n)=>{if(n<1||n>4||e+n>t.length)return null;let r=0;for(let i=0;i<n;i+=1)r=r<<8|t[e+i];return r>>>0},jr=(t,e,n)=>{for(let r of n)if(r.byteLength===e&&t>=r.start&&t<=r.end)return true;return false};var xo=[[/times|serif|georgia|cambria|garamond|minion/,"Times"],[/courier|mono|consol/,"Courier"]],Ir=(t,e={})=>{let n=(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),r="Helvetica";for(let[s,o]of xo)if(s.test(n)){r=o;break}let i=`${e.bold?"Bold":""}${e.italic?"Italic":""}`;return i?`${r}-${i}`:r};var Br=(t,e)=>{let n=t.y+t.height,r=t.y,i=t.x+t.width;return e.maxY!==void 0&&e.maxY<n&&e.maxY>r&&(n=e.maxY),e.minY!==void 0&&e.minY>r&&e.minY<n&&(r=e.minY),e.maxRight!==void 0&&e.maxRight<i&&e.maxRight>t.x&&(i=e.maxRight),{x:t.x,y:r,width:Math.max(0,i-t.x),height:Math.max(0,n-r)}};var Bt=class{static getAllPages(e,n={}){let r=[],i=[];try{r.push("[TRAVERSE] Starting page tree traversal...");let s=e.rootRef;r.push(`[CATALOG] Root reference: ${s.objNum} ${s.genNum} R`);let o=`${s.objNum}.${s.genNum}`,a=e.objectCache.get(o);if((!a||!M(a))&&n.objectLoader)try{a=n.objectLoader(s),r.push("[CATALOG] Loaded root catalog from file");}catch(m){let p=m instanceof Error?m.message:String(m);r.push(`[WARN] Failed to load root catalog: ${p}`);}if(!a||!M(a))return r.push(`[ERROR] Root catalog not found in object cache at ${o}`),{pages:i,logs:r};let c=a;r.push("[CATALOG] \u2713 Found catalog in cache");let l=c.entries.get("Pages");if(!l)return r.push("[ERROR] /Pages reference not found in catalog"),{pages:i,logs:r};if(!q(l))return r.push("[ERROR] /Pages is not an indirect reference"),{pages:i,logs:r};let f=l;r.push(`[PAGES] Pages tree root: ${f.objNum} ${f.genNum} R`);let d=`${f.objNum}.${f.genNum}`,u=e.objectCache.get(d);if((!u||!M(u))&&n.objectLoader)try{u=n.objectLoader(f),r.push("[PAGES] Loaded pages tree root from file");}catch(m){let p=m instanceof Error?m.message:String(m);r.push(`[WARN] Failed to load pages tree root: ${p}`);}if(!u||!M(u))return r.push(`[ERROR] Pages tree object not in cache at ${d}`),r.push("[NOTE] Page tree object must be loaded before traversal can begin"),r.push("[NEXT STEP] Implement ObjectReader.resolveRef() to load from file"),{pages:i,logs:r};let h=u;return r.push("[PAGES] \u2713 Found pages tree root"),this.walkPageTree(h,f,e,i,r,n,1),r.push(`[TRAVERSE] \u2713 Complete. Found ${i.length} page(s)`),{pages:i,logs:r}}catch(s){let o=s instanceof Error?s.message:String(s);return r.push(`[ERROR] Traversal failed: ${o}`),{pages:i,logs:r}}}static walkPageTree(e,n,r,i,s,o,a){let c=e.entries.get("Type"),l=this.extractName(c);if(l==="Pages"){let f=e.entries.get("Kids");if(!f)return s.push(`[WARN] Pages node has no /Kids at ${n.objNum} ${n.genNum} R`),a;let d=this.extractArray(f);if(!d)return s.push("[WARN] /Kids is not an array"),a;s.push(`[NODE] Pages node with ${d.length} child(ren) at ${n.objNum}`);for(let u of d){if(!q(u)){s.push("[WARN] /Kids contains non-reference");continue}let h=u,m=`${h.objNum}.${h.genNum}`,p=r.objectCache.get(m);if((!p||!M(p))&&o.objectLoader)try{p=o.objectLoader(h),s.push(`[NODE] Loaded child page node ${h.objNum} ${h.genNum} R from file`);}catch(x){let g=x instanceof Error?x.message:String(x);s.push(`[WARN] Failed to load child node: ${g}`);}if(!p||!M(p)){s.push(`[SKIP] Child page node not in cache: ${h.objNum} ${h.genNum} R`),s.push("[NOTE] Would need ObjectReader to load from file");continue}if(a=this.walkPageTree(p,h,r,i,s,o,a),o.maxPages&&i.length>=o.maxPages)return a}return a}else if(l==="Page"){s.push(`[PAGE ${a}] Found at ${n.objNum} ${n.genNum} R`);let f=this.extractContentStreams(e,r,s,o);s.push(`[PAGE ${a}] \u2713 Found ${f.length} stream(s)`);let d=this.extractMediaBox(e),u=this.extractResources(e,r,s,o),h=this.extractNumber(e.entries.get("Rotate"));return i.push({pageNum:a,ref:n,dict:e,contentStreams:f,mediaBox:d||[0,0,612,792],resources:u,rotate:h||0}),a+1}else return s.push(`[WARN] Unknown node type: ${l}`),a}static extractContentStreams(e,n,r,i){let s=[];try{let o=e.entries.get("Contents");if(!o)return r.push("[WARN] Page has no /Contents"),s;if(U(o))s.push(o);else if(q(o)){let a=o,c=`${a.objNum}.${a.genNum}`,l=n.objectCache.get(c);if((!l||!U(l))&&i.objectLoader)try{l=i.objectLoader(a),r.push(`[STREAM] Loaded content stream ${a.objNum} ${a.genNum} R from file`);}catch(f){let d=f instanceof Error?f.message:String(f);r.push(`[WARN] Failed to load content stream ${a.objNum} ${a.genNum} R: ${d}`);}l&&U(l)?s.push(l):r.push(`[STREAM] Content stream reference not cached: ${a.objNum} ${a.genNum} R`);}else if(j(o)){let a=this.extractArray(o);if(a){for(let c of a)if(U(c))s.push(c);else if(q(c)){let l=c,f=`${l.objNum}.${l.genNum}`,d=n.objectCache.get(f);if((!d||!U(d))&&i.objectLoader)try{d=i.objectLoader(l),r.push(`[STREAM] Loaded content stream ${l.objNum} ${l.genNum} R from file`);}catch(u){let h=u instanceof Error?u.message:String(u);r.push(`[WARN] Failed to load content stream ${l.objNum} ${l.genNum} R: ${h}`);}d&&U(d)?s.push(d):r.push(`[STREAM] Content stream reference not cached: ${l.objNum} ${l.genNum} R`);}}}}catch(o){r.push(`[ERROR] Failed to extract content streams: ${o instanceof Error?o.message:String(o)}`);}return s}static extractMediaBox(e){let n=e.entries.get("MediaBox");if(n&&j(n)){let r=this.extractArray(n);if(r&&r.length>=4){let i=r.slice(0,4).map(s=>this.extractNumber(s));if(i.every(s=>s!==null))return i}}return null}static extractResources(e,n,r,i){let s=e.entries.get("Resources");if(s&&M(s))return s;if(s&&q(s)){let o=s,a=`${o.objNum}.${o.genNum}`,c=n.objectCache.get(a);if((!c||!M(c))&&i.objectLoader)try{c=i.objectLoader(o),r.push(`[RESOURCES] Loaded resources ${o.objNum} ${o.genNum} R from file`);}catch(l){let f=l instanceof Error?l.message:String(l);r.push(`[WARN] Failed to load resources ${o.objNum} ${o.genNum} R: ${f}`);}if(c&&M(c))return c;r.push(`[RESOURCES] Reference to resources not in cache: ${o.objNum} ${o.genNum} R`);}}static extractName(e){return !e||typeof e!="object"||!("type"in e)?null:e.type==="name"?e.value:null}static extractArray(e){return !e||typeof e!="object"||!("type"in e)?null:e.type==="array"?e.items||[]:null}static extractNumber(e){return A(e)}};var Ur=new Set(["show_string","show_strings","next_line_show_string"]),Lr=t=>t==="show_string"?"() Tj":t==="show_strings"?"[] TJ":"() '",$r=(t,e)=>{if(t.length!==e.length)return false;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return false;return true};async function gn(t,e){let n=new Te(t),r=n.parse(),s=Bt.getAllPages(r,{objectLoader:u=>n.loadObject(u)}).pages[e];if(!s)throw new Error(`Page ${e+1} not found`);let o=tt(s.dict.entries.get("Contents"));if(o.length===0)throw new Error("Page has no content streams");let a=[];for(let u of o){let h=n.loadObject(u);if(!U(h))continue;let m=h.decode?await h.decode():await _.decodeStream(h);a.push({objNum:u.objNum,genNum:u.genNum,bytes:m});}if(a.length===0)throw new Error("Page content streams could not be decoded");let c=a.reduce((u,h)=>u+h.bytes.length,0)+Math.max(0,a.length-1),l=new Uint8Array(c),f=[],d=0;for(let u=0;u<a.length;u++)l.set(a[u].bytes,d),f.push({start:d,end:d+a[u].bytes.length}),d+=a[u].bytes.length,u<a.length-1&&(l[d]=32,d+=1);return {chunks:a,pristine:l,chunkSpans:f}}var _r=(t,e)=>t.chunks.map((n,r)=>{let i=new Uint8Array(e.subarray(t.chunkSpans[r].start,t.chunkSpans[r].end));return {objNum:n.objNum,genNum:n.genNum,bytes:i,changed:!$r(i,n.bytes)}});async function Nr(t,e,n,r){let i=await gn(t,e);if(r&&r.length!==i.pristine.length)throw new Error("Stale rewrite state for page");let{commands:s,ranges:o}=Ye(i.pristine),a=new Uint8Array(r!=null?r:i.pristine);for(let c of n){let l=s[c],f=o[c];if(!l||!f)throw new Error(`No operator at index ${c}`);if(!Ur.has(l.op))throw new Error(`Operator ${l.op} at index ${c} is not rewritable`);if(!i.chunkSpans.some(h=>f.start>=h.start&&f.end<=h.end))throw new Error(`Operator at index ${c} spans multiple content streams`);let u=Lr(l.op);if(f.end-f.start<u.length)throw new Error(`Operator span too small at index ${c}`);a.fill(32,f.start,f.end);for(let h=0;h<u.length;h++)a[f.start+h]=u.charCodeAt(h);}return {streams:_r(i,a),combined:a}}var go=t=>{let e=t.toFixed(6).replace(/\.?0+$/,"");return e===""||e==="-"?"0":e};async function Wr(t,e,n,r,i){var b;let s=await gn(t,e);if(i&&i.length!==s.pristine.length)throw new Error("Stale rewrite state for page");if(!r.every(Number.isFinite))throw new Error("Non-finite transform matrix");let{commands:o,ranges:a}=Ye(s.pristine);if(n.start<0||n.end<n.start||n.end>=o.length)throw new Error(`Invalid operator span ${n.start}..${n.end}`);let c=0;for(let P=n.start;P<=n.end;P++){let y=(b=o[P])==null?void 0:b.op;if(y==="save_state")c+=1;else if(y==="restore_state"&&(c-=1,c<0))throw new Error("Span restores state it did not save")}if(c!==0)throw new Error("Span has unbalanced q/Q");let l=a[n.start].start,f=a[n.end].end,d=s.chunkSpans.findIndex(P=>l>=P.start&&f<=P.end);if(d<0)throw new Error("Span crosses content-stream chunk boundaries");let u=i!=null?i:s.pristine,h=new TextEncoder().encode(`
7
+ q ${r.map(go).join(" ")} cm
8
+ `),m=new TextEncoder().encode(`
9
+ Q
10
+ `),p=new Uint8Array(u.length+h.length+m.length);p.set(u.subarray(0,l),0),p.set(h,l),p.set(u.subarray(l,f),l+h.length),p.set(m,l+h.length+(f-l)),p.set(u.subarray(f),l+h.length+(f-l)+m.length);let x=h.length+m.length;return {streams:s.chunks.map((P,y)=>{let D=s.chunkSpans[y].start,v=s.chunkSpans[y].end;y===d?v+=x:y>d&&(D+=x,v+=x);let S=new Uint8Array(p.subarray(D,v));return {objNum:P.objNum,genNum:P.genNum,bytes:S,changed:!$r(S,P.bytes)}}),combined:p,lengthChanged:true}}var bo=new Set(["save_state","restore_state","set_ctm","set_graphics_state","set_line_width","set_line_cap","set_line_join","set_miter_limit","set_dash","set_rendering_intent","set_fill_color_rgb","set_stroke_color_rgb","set_fill_gray","set_stroke_gray","set_fill_cmyk","set_stroke_cmyk","set_fill_color","set_stroke_color","set_fill_color_space","set_stroke_color_space","begin_text","end_text","set_font","move_text","move_text_set_leading","set_text_matrix","next_line","set_char_spacing","set_word_spacing","set_horiz_scale","set_leading","set_text_render","set_text_rise","begin_marked_content","end_marked_content","type3_glyph_width"]);async function Gr(t,e,n,r){let i=await gn(t,e);if(r&&r.length!==i.pristine.length)throw new Error("Stale rewrite state for page");let{commands:s,ranges:o}=Ye(i.pristine),a=new Uint8Array(r!=null?r:i.pristine),c=l=>{let f=o[l];if(!i.chunkSpans.some(u=>f.start>=u.start&&f.end<=u.end))throw new Error(`Operator at index ${l} spans multiple content streams`);a.fill(32,f.start,f.end);};for(let l of n){if(l.start<0||l.end<l.start||l.end>=s.length)throw new Error(`Invalid operator span ${l.start}..${l.end}`);let f=0;for(let d=l.start;d<=l.end;d++){let u=s[d],h=o[d];if(!u||!h)throw new Error(`No operator at index ${d}`);if(u.op==="save_state"){f+=1;continue}if(u.op==="restore_state"){f-=1;continue}if(!bo.has(u.op)){if(u.op==="clip"||u.op==="clip_even_odd"){if(f<=0)throw new Error("Span contains a clip that outlives it");c(d);continue}if(u.op==="set_spacing_next_line_show_string")throw new Error('Span contains a " operator (spacing side effects)');if(Ur.has(u.op)){let m=Lr(u.op);if(h.end-h.start<m.length)throw new Error(`Operator span too small at index ${d}`);c(d);for(let p=0;p<m.length;p++)a[h.start+p]=m.charCodeAt(p);continue}c(d);}}}return {streams:_r(i,a),combined:a}}var Xr=["view","annotate"],Yr=["view","annotate","edit-text","sign","redact","forms","export-clean"];var Hr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",st={};for(let t=0;t<Hr.length;t++)st[Hr[t]]=t;function Vr(t){return new TextDecoder().decode(t)}function zr(t){let e=t.trim(),n=new Uint8Array(e.length>>1);for(let r=0;r<n.length;r++)n[r]=parseInt(e.substr(r*2,2),16);return n}function Kr(t){let e=[];for(let n=0;n<t.length;n+=4){let r=st[t[n]],i=st[t[n+1]];if(r===void 0||i===void 0)break;e.push(r<<2|i>>4);let s=st[t[n+2]];if(s===void 0)break;e.push((i&15)<<4|s>>2);let o=st[t[n+3]];if(o===void 0)break;e.push((s&3)<<6|o);}return new Uint8Array(e)}function qr(t,e){let n=t.indexOf(".");if(n<0)return null;try{let r=Kr(t.slice(0,n)),i=Kr(t.slice(n+1));return ed25519.verify(i,r,e)?r:null}catch{return null}}var ot="bde297640169e8f75d2d9bd260e8eab78aa93c39e10c84a8f6abe565a19057e3";function Jr(t,e){if(!t||/^0+$/.test(e))return null;let n=qr(t,zr(e));if(!n)return null;try{return JSON.parse(Vr(n))}catch{return null}}function Ut(t,e=ot){let n=Jr(t,e);return !n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function Lt(t,e=ot){let n=Jr(t,e);return !n||typeof n.lid!="string"||!Array.isArray(n.features)?null:n}function bn(t,e){return t===0||t*1e3>e}function Zr(t,e){if(!e||e==="localhost"||e==="127.0.0.1"||e==="::1")return true;let n=e.toLowerCase();return t.some(r=>{let i=r.trim().toLowerCase();return i==="*"||i===n?true:n.endsWith("."+i)})}var $t="NamahaPDF \xB7 Unlicensed SDK";function Qr(t,e,n,r=$t){t.save(),t.globalAlpha=.16,t.fillStyle="#C20E3A";let i=Math.max(14,Math.round(Math.min(e,n)/22));t.font=`600 ${i}px Inter, system-ui, sans-serif`,t.textAlign="center",t.textBaseline="middle";let s=i*9;t.translate(e/2,n/2),t.rotate(-28*Math.PI/180);for(let o=-n;o<n;o+=s*.5)for(let a=-e;a<e;a+=s)t.fillText(r,a,o);t.restore();}async function ei(t,e=$t){try{let{PDFDocument:n,StandardFonts:r,rgb:i,degrees:s}=await import('pdf-lib'),o=await n.load(t,{ignoreEncryption:!0}),a=await o.embedFont(r.HelveticaBold),c=i(.76,.055,.227);for(let l of o.getPages()){let{width:f,height:d}=l.getSize(),u=Math.max(16,Math.min(f,d)/26),h=u*6,m=a.widthOfTextAtSize(e,u)+u*4;for(let p=-d;p<d*2;p+=h)for(let x=-f;x<f*2;x+=m)l.drawText(e,{x,y:p,size:u,font:a,color:c,opacity:.14,rotate:s(28)});}return await o.save()}catch{return t}}var ni=5,Po=4320*60*1e3,Do=4320*60*1e3,wo="/api/license/activate",z={publicKeyHex:ot,now:()=>Date.now()},me=null,_t=[];function So(){let t=new Map;return {getItem:e=>{var n;return (n=t.get(e))!=null?n:null},setItem:(e,n)=>{t.set(e,n);}}}function Fo(t){if(t.storage)return t.storage;try{if(typeof localStorage!="undefined")return localStorage}catch{}return So()}function ri(t){if(t.host)return t.host;try{if(typeof location!="undefined")return location.hostname}catch{}return ""}function ii(t){return `namaha.lic.${t}`}function si(t){try{let e=me==null?void 0:me.getItem(ii(t));if(e)return JSON.parse(e)}catch{}return {failCount:0,firstSeen:z.now(),lastAttempt:0}}function Pn(t,e){try{me==null||me.setItem(ii(t),JSON.stringify(e));}catch{}}function vo(){if(z.deviceId)return z.deviceId;let t="namaha.lic.device";try{let n=me==null?void 0:me.getItem(t);if(n)return n}catch{}let e="dev_"+Math.random().toString(36).slice(2)+Date.now().toString(36);try{me==null||me.setItem(t,e);}catch{}return e}function $e(){let t=z.now();if(z.owner)return {status:"LICENSED",edition:"enterprise",features:Yr,watermark:false,reason:"owner"};if(!z.licenseKey)return c("UNLICENSED","no key");let e=Ut(z.licenseKey,z.publicKeyHex);if(!e)return c("INVALID","bad signature");if(!bn(e.exp,t))return c("INVALID","key expired");if(!Zr(e.domains,ri(z)))return c("INVALID","domain not allowed");let n=si(e.lid);if(n.revoked)return c("DEGRADED","revoked");let r=n.token?Lt(n.token,z.publicKeyHex):null;if(r&&r.lid===e.lid&&bn(r.exp,t))return l("LICENSED",r.edition,r.features,"active token");let i=r?r.exp*1e3:n.firstSeen,s=r?Do:Po,o=t-i<s,a=n.failCount<ni;if(o||a)return l("GRACE",e.edition,e.features,"grace");return c("DEGRADED","grace exhausted");function c(f,d){return {status:f,edition:null,features:Xr.slice(),watermark:true,reason:d}}function l(f,d,u,h){return {status:f,edition:d,features:u.slice(),watermark:false,reason:h}}}function Dn(){let t=$e();for(let e of _t)try{e(t);}catch{}}async function Co(){var o,a;if(z.owner||!z.licenseKey)return;let t=Ut(z.licenseKey,z.publicKeyHex);if(!t)return;let e=(o=z.activationUrl)!=null?o:wo,n=(a=z.fetchImpl)!=null?a:typeof fetch!="undefined"?fetch:null;if(!n)return;let r=ri(z),i=vo(),s=si(t.lid);try{let c=await n(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({licenseKey:z.licenseKey,origin:r,deviceId:i})}),l=await c.json().catch(()=>({}));if(l.status==="revoked"||l.status==="invalid"){Pn(t.lid,{...s,revoked:!0,lastAttempt:z.now()}),Dn();return}if(c.ok&&l.status==="active"&&l.token&&Lt(l.token,z.publicKeyHex)){Pn(t.lid,{...s,token:l.token,failCount:0,lastAttempt:z.now(),revoked:!1}),Dn();return}ti(t.lid,s);}catch{ti(t.lid,s);}}function ti(t,e){Pn(t,{...e,failCount:Math.min(ni,e.failCount+1),lastAttempt:z.now()}),Dn();}function Ao(t={}){z={publicKeyHex:ot,now:()=>Date.now(),...t},me=Fo(t);let e=$e();return Mo(),e}var yn=false;async function Mo(){var e;if(yn||z.owner||!z.licenseKey)return;yn=true;let t=(e=z.retryDelays)!=null?e:[0,2e3,6e3,2e4];try{for(let n=0;n<t.length;n++){t[n]>0&&await ko(t[n]);let r=$e();if(r.status==="LICENSED"&&r.reason==="active token"||r.status==="DEGRADED"||r.status==="INVALID"||r.status==="UNLICENSED")break;await Co();let i=$e();if(i.status==="LICENSED"||i.status==="DEGRADED")break}}finally{yn=false;}}function ko(t){return new Promise(e=>setTimeout(e,t))}function Ro(){return $e()}function oi(t){return $e().features.includes(t)}function wn(t){if(!oi(t))throw new Error(`NamahaPDF: feature "${t}" requires a license. See namahapdf.com/sdk.`)}function Oo(){return $e().watermark}function To(t){return _t.push(t),()=>{_t=_t.filter(e=>e!==t);}}var Eo=t=>t.kind==="highlight"||t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly";var Sn=t=>{let e=t.map(s=>s.x),n=t.map(s=>s.y),r=Math.min(...e),i=Math.min(...n);return {x:r,y:i,width:Math.max(...e)-r,height:Math.max(...n)-i}},at=t=>{if(Eo(t)){let e=[];for(let n of t.quads)e.push({x:n.x,y:n.y},{x:n.x+n.width,y:n.y+n.height});return e.length?Sn(e):{x:0,y:0,width:0,height:0}}if(t.kind==="ink"){let e=t.strokes.flat();return e.length?Sn(e):{x:0,y:0,width:0,height:0}}return t.kind==="note"||t.kind==="freetext"?{...t.rect}:Sn(t.points)};var ct=1.5,R=t=>{let e=Math.round(t*1e3)/1e3;return Object.is(e,-0)?"0":String(e)},_e=t=>[Math.min(1,Math.max(0,t.r)),Math.min(1,Math.max(0,t.g)),Math.min(1,Math.max(0,t.b))],ci=t=>{let e=new Date(t),n=r=>String(r).padStart(2,"0");return `D:${e.getFullYear()}${n(e.getMonth()+1)}${n(e.getDate())}${n(e.getHours())}${n(e.getMinutes())}${n(e.getSeconds())}`},ui=(t,e)=>({x:t.x-e,y:t.y-e,width:t.width+e*2,height:t.height+e*2}),li=t=>[t.x,t.y,t.x+t.width,t.y+t.height],Je=t=>{var s;let[e,n,r]=_e(t.color),i=(s=t.strokeWidth)!=null?s:ct;return `${R(i)} w 1 J 1 j ${R(e)} ${R(n)} ${R(r)} RG`},Nt=t=>{let[e,n,r]=_e(t);return `${R(e)} ${R(n)} ${R(r)} rg`},Fn=t=>{var r;let e=!!t.fill,n=((r=t.strokeWidth)!=null?r:ct)>0;return e&&n?"B":e?"f":"S"},jo=t=>{let n=t.x+t.width/2,r=t.y+t.height/2,i=t.width/2,s=t.height/2;return [`${R(n+i)} ${R(r)} m`,`${R(n+i)} ${R(r+s*.5523)} ${R(n+i*.5523)} ${R(r+s)} ${R(n)} ${R(r+s)} c`,`${R(n-i*.5523)} ${R(r+s)} ${R(n-i)} ${R(r+s*.5523)} ${R(n-i)} ${R(r)} c`,`${R(n-i)} ${R(r-s*.5523)} ${R(n-i*.5523)} ${R(r-s)} ${R(n)} ${R(r-s)} c`,`${R(n+i*.5523)} ${R(r-s)} ${R(n+i)} ${R(r-s*.5523)} ${R(n+i)} ${R(r)} c`].join(`
11
+ `)},vn=(t,e)=>{let n=t.map((r,i)=>`${R(r.x)} ${R(r.y)} ${i===0?"m":"l"}`);return e&&n.push("h"),n.join(`
12
+ `)},Io=(t,e,n)=>{let r=Math.atan2(e.y-t.y,e.x-t.x),i=Math.PI/7,s={x:e.x-n*Math.cos(r-i),y:e.y-n*Math.sin(r-i)},o={x:e.x-n*Math.cos(r+i),y:e.y-n*Math.sin(r+i)};return `${R(s.x)} ${R(s.y)} m ${R(e.x)} ${R(e.y)} l ${R(o.x)} ${R(o.y)} l S`},Bo=(t,e)=>{let i=[`${R(t.x)} ${R(e)} m`],s=true;for(let o=t.x+4;o<=t.x+t.width;o+=4)i.push(`${R(o)} ${R(s?e+1.5:e-1.5)} l`),s=!s;return `${i.join(`
13
+ `)}
14
+ S`},Uo=t=>{var o,a,c;let e=Math.max((o=t.style.strokeWidth)!=null?o:ct,2)+1,n=ui(at(t),e);if(t.kind==="highlight"){let l=t.quads.map(f=>`${R(f.x)} ${R(f.y)} ${R(f.width)} ${R(f.height)} re`).join(`
15
+ `);return {content:`/GS0 gs
16
+ ${Nt(t.style.color)}
17
+ ${l}
18
+ f`,bbox:n,multiply:true}}if(t.kind==="underline"||t.kind==="strikeout"||t.kind==="squiggly"){let l=Math.max(.75,(a=t.style.strokeWidth)!=null?a:1),f=t.quads.map(m=>{let p=t.kind==="strikeout"?m.y+m.height*.5:m.baselineY-Math.max(1,m.height*.12);return t.kind==="squiggly"?Bo(m,m.y+1):`${R(m.x)} ${R(p)} m ${R(m.x+m.width)} ${R(p)} l S`}).join(`
19
+ `),[d,u,h]=_e(t.style.color);return {content:`${R(l)} w ${R(d)} ${R(u)} ${R(h)} RG
20
+ ${f}`,bbox:n,multiply:false}}if(t.kind==="ink"){let l=t.strokes.map(f=>vn(f,false)+`
21
+ S`).join(`
22
+ `);return {content:`${Je(t.style)}
23
+ ${l}`,bbox:n,multiply:false}}if(t.kind==="rect"){let l=at(t),f=`${R(l.x)} ${R(l.y)} ${R(l.width)} ${R(l.height)} re`;return {content:`${(t.style.fill?Nt(t.style.fill)+`
24
+ `:"")+Je(t.style)}
25
+ ${f}
26
+ ${Fn(t.style)}`,bbox:n,multiply:false}}if(t.kind==="ellipse")return {content:`${(t.style.fill?Nt(t.style.fill)+`
27
+ `:"")+Je(t.style)}
28
+ ${jo(at(t))}
29
+ ${Fn(t.style)}`,bbox:n,multiply:false};if(t.kind==="polygon")return {content:`${(t.style.fill?Nt(t.style.fill)+`
30
+ `:"")+Je(t.style)}
31
+ ${vn(t.points,true)}
32
+ ${Fn(t.style)}`,bbox:n,multiply:false};if(t.kind==="polyline")return {content:`${Je(t.style)}
33
+ ${vn(t.points,false)}
34
+ S`,bbox:n,multiply:false};let[r,i]=t.points,s=`${Je(t.style)}
35
+ ${R(r.x)} ${R(r.y)} m ${R(i.x)} ${R(i.y)} l S`;if(t.kind==="arrow"){let l=Math.max(8,((c=t.style.strokeWidth)!=null?c:ct)*4);s+=`
36
+ ${Io(r,i,l)}`;}return {content:s,bbox:n,multiply:false}},Lo=t=>({highlight:"Highlight",underline:"Underline",strikeout:"StrikeOut",squiggly:"Squiggly",rect:"Square",ellipse:"Circle",line:"Line",arrow:"Line",polygon:"Polygon",polyline:"PolyLine",ink:"Ink",note:"Text",freetext:"FreeText"})[t.kind],$o=t=>{let e=[];for(let n of t){let r=n.y+n.height;e.push(n.x,r,n.x+n.width,r,n.x,n.y,n.x+n.width,n.y);}return e},fi=(t,e)=>{var c,l,f;let n=t.getPageCount();if(e.pageIndex<0||e.pageIndex>=n)return;let r=t.getPage(e.pageIndex),i=t.context,s=at(e),o={Type:"Annot",Subtype:Lo(e),Rect:li(ui(s,Math.max((c=e.style.strokeWidth)!=null?c:ct,2)+1)),C:_e(e.style.color),CA:e.style.opacity,F:4,NM:PDFString.of(e.id),M:PDFString.of(ci(e.createdAt)),CreationDate:PDFString.of(ci(e.createdAt))};if(e.author&&(o.T=PDFString.of(e.author)),e.kind==="highlight"||e.kind==="underline"||e.kind==="strikeout"||e.kind==="squiggly")o.QuadPoints=$o(e.quads),e.text&&(o.Contents=PDFString.of(e.text));else if(e.kind==="line"||e.kind==="arrow"){let[d,u]=e.points;o.L=[d.x,d.y,u.x,u.y],e.kind==="arrow"&&(o.LE=["None","ClosedArrow"]),e.style.strokeWidth&&(o.BS={W:e.style.strokeWidth,S:"S"});}else if(e.kind==="polygon"||e.kind==="polyline")o.Vertices=e.points.flatMap(d=>[d.x,d.y]),e.style.fill&&(o.IC=_e(e.style.fill)),e.style.strokeWidth&&(o.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="rect"||e.kind==="ellipse")e.style.fill&&(o.IC=_e(e.style.fill)),e.style.strokeWidth&&(o.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="ink")o.InkList=e.strokes.map(d=>d.flatMap(u=>[u.x,u.y])),e.style.strokeWidth&&(o.BS={W:e.style.strokeWidth,S:"S"});else if(e.kind==="note")o.Contents=PDFString.of((l=e.text)!=null?l:""),o.Name="Comment",o.Open=false;else if(e.kind==="freetext"){o.Contents=PDFString.of((f=e.text)!=null?f:"");let[d,u,h]=_e(e.style.color);o.DA=PDFString.of(`${R(d)} ${R(u)} ${R(h)} rg /Helv 12 Tf`),o.Q=0;}if(e.kind!=="note"){let{content:d,bbox:u,multiply:h}=Uo(e),m={Type:"XObject",Subtype:"Form",FormType:1,BBox:li(u),Resources:h?{ExtGState:{GS0:{Type:"ExtGState",BM:"Multiply",ca:1,CA:1}}}:{}},p=i.stream(d,m),x=i.register(p);o.AP={N:x};}let a=i.register(i.obj(o));r.node.addAnnot(a),r.node.get(PDFName.of("Annots"))||r.node.set(PDFName.of("Annots"),i.obj([a]));};var No={left:TextAlignment.Left,center:TextAlignment.Center,right:TextAlignment.Right},Wo={"insert-text":"edit-text","replace-text":"edit-text","delete-object":"edit-text","transform-object":"edit-text","insert-image":"edit-text","rotate-page":"edit-text","delete-page":"edit-text","redact-area":"redact","create-form-field":"forms","update-form-field":"forms","set-form-values":"forms","delete-form-field":"forms","flatten-form":"forms","add-annotation":"annotate"},ut=t=>({r:Math.min(1,Math.max(0,t.r)),g:Math.min(1,Math.max(0,t.g)),b:Math.min(1,Math.max(0,t.b))}),Go=t=>{let e=(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),n=e.includes("bold")||e.includes("black")||e.includes("heavy"),r=e.includes("italic")||e.includes("oblique");return e.includes("times")?n&&r?StandardFonts.TimesRomanBoldItalic:n?StandardFonts.TimesRomanBold:r?StandardFonts.TimesRomanItalic:StandardFonts.TimesRoman:e.includes("courier")?n&&r?StandardFonts.CourierBoldOblique:n?StandardFonts.CourierBold:r?StandardFonts.CourierOblique:StandardFonts.Courier:n&&r?StandardFonts.HelveticaBoldOblique:n?StandardFonts.HelveticaBold:r?StandardFonts.HelveticaOblique:StandardFonts.Helvetica},Wt=t=>{let e=[];for(let n=0;n<t.length;){let r=t.codePointAt(n);if(r===void 0)break;e.push(r),n+=r>65535?2:1;}return e},Xo=new Map([["\xAD",""],["\u200B",""],["\u200C",""],["\u200D",""],["\uFEFF",""],["\u2000"," "],["\u2001"," "],["\u2002"," "],["\u2003"," "],["\u2004"," "],["\u2005"," "],["\u2006"," "],["\u2007"," "],["\u2008"," "],["\u2009"," "],["\u200A"," "],["\u3000"," "],["\u2010","-"],["\u2011","-"],["\u2012","-"],["\u2015","-"],["\u2212","-"],["\u2024","."],["\u2032","'"],["\u2033",'"'],["\u02BC","'"],["\u2044","/"],["\u2215","/"],["\u2028",`
37
+ `],["\u2029",`
38
+ `],["\uFB01","fi"],["\uFB02","fl"],["\uFB00","ff"],["\uFB03","ffi"],["\uFB04","ffl"]]),mi=t=>(t!=null?t:"").replace(/^[A-Z]{6}\+/,"").replace(/[#,\s]/g,"").toLowerCase(),Mn=t=>!t||typeof t!="object"||!("type"in t)?null:t.type==="name"?t.value:null,Ne=(t,e)=>{if(t){if(!q(t))return t;try{return e(t)}catch{return}}},Yo=t=>{if(!(!t||!j(t)))return t.items[0]},Ho=(t,e)=>{let n=Ne(t.entries.get("FontDescriptor"),e);if(n&&M(n))return n;let r=Ne(t.entries.get("DescendantFonts"),e),i=Ne(Yo(r),e);if(i&&M(i)){let s=Ne(i.entries.get("FontDescriptor"),e);if(s&&M(s))return s}},Ko=t=>{var a,c,l,f,d,u,h,m;let e=new Te(t),r=e.parse().xrefTables.get(0);if(!r)return [];let i=[],s=new Set,o=p=>e.loadObject(p);for(let[p,x]of r.entries()){if(!x.inUse)continue;let g;try{g=o({type:"ref",objNum:p,genNum:x.genNum});}catch{continue}if(!M(g))continue;let b=Mn(g.entries.get("Subtype"));if(!b||!["Type1","TrueType","Type0","CIDFontType0","CIDFontType2"].includes(b))continue;let P=Ho(g,o);if(!P)continue;let y=(c=(a=Ne(P.entries.get("FontFile2"),o))!=null?a:Ne(P.entries.get("FontFile3"),o))!=null?c:Ne(P.entries.get("FontFile"),o);if(!y||!U(y))continue;let D=(f=(l=Mn(g.entries.get("BaseFont")))!=null?l:Mn(P.entries.get("FontName")))!=null?f:`Font${p}`,v=mi(D),S=`${v}:${(m=(h=(d=y.rawBytes)==null?void 0:d.length)!=null?h:(u=y.data)==null?void 0:u.length)!=null?m:0}`;if(!s.has(S))try{let F=_.decodeStreamSync(y);if(F.length===0)continue;i.push({baseName:D,normalizedName:v,bytes:F}),s.add(S);}catch{continue}}return i},hi=(t,e,n,r)=>{let i=Math.max(0,t.x-e),s=Math.max(0,t.y-e),o=Math.min(n,t.x+t.width+e),a=Math.min(r,t.y+t.height+e);return {x:i,y:s,width:Math.max(0,o-i),height:Math.max(0,a-s)}},ft=class t{constructor(e,n){this.pdfDoc=e;this.pdfBytes=n;this.standardFontCache=new Map;this.embeddedFontCache=new Map;this.embeddedFonts=null;this.fontkitRegistered=false;this.rewrittenPages=new Map;this.indexInvalidPages=new Set;this.embeddedImageCache=new Map;this.currentBytes=n;}static async fromAvniDocument(e){let n=await e.blob.arrayBuffer(),r=new Uint8Array(n),i=await PDFDocument.load(r);return new t(i,r)}static async fromBytes(e){let n=e instanceof Uint8Array?e:new Uint8Array(e),r=await PDFDocument.load(n);return new t(r,n)}getPageCount(){return this.pdfDoc.getPageCount()}async applyOperations(e){var r,i,s,o,a,c,l,f,d,u,h,m,p,x,g,b,P,y,D,v,S,F;if(e.length===0)return;for(let w of e)wn(Wo[w.type]);let n=await this.getStandardFont(StandardFonts.Helvetica);for(let w of e){if(w.type==="create-form-field"||w.type==="set-form-values"||w.type==="delete-form-field"||w.type==="flatten-form")continue;if(w.type==="delete-page"){this.deletePage(w.pageIndex);continue}if(w.type==="delete-object"){if(!await this.tryNeutralizeSpans(w.pageIndex,w.spans))throw new Error("This object cannot be deleted safely.");continue}if(w.type==="transform-object"){if(!await this.tryWrapSpanWithTransform(w))throw new Error("This object cannot be moved safely.");continue}if(w.type==="add-annotation"){fi(this.pdfDoc,w.annotation);continue}let C=this.pdfDoc.getPage(w.pageIndex);if(w.type==="insert-image"){let O=await this.getEmbeddedImage(w.bytes,w.format);C.drawImage(O,{x:w.x,y:w.y,width:w.width,height:w.height});continue}if(w.type==="insert-text"){if((r=w.spans)!=null&&r.length){await this.drawStyledSpans(C,w.spans,w.x,w.y,(i=w.size)!=null?i:14,w.fontName);continue}let O=ut((s=w.color)!=null?s:{r:0,g:0,b:0}),E=this.fitTextToFont(n,w.text);if(E.length===0)continue;C.drawText(E,{x:w.x,y:w.y,size:(o=w.size)!=null?o:14,font:n,color:rgb(O.r,O.g,O.b)});continue}if(w.type==="redact-area"){let O=ut((a=w.color)!=null?a:{r:1,g:1,b:1}),{width:E,height:I}=C.getSize();(l=(c=w.removeOperators)==null?void 0:c.streamOperatorIndices)!=null&&l.length&&await this.tryRemoveTextOperators(w.pageIndex,w.removeOperators.streamOperatorIndices);let L=hi({x:w.x,y:w.y,width:w.width,height:w.height},(f=w.padding)!=null?f:1.75,E,I);C.drawRectangle({x:L.x,y:L.y,width:L.width,height:L.height,color:rgb(O.r,O.g,O.b)});continue}if(w.type==="replace-text"){let O=ut((d=w.backgroundColor)!=null?d:{r:1,g:1,b:1}),E=ut((m=(h=w.color)!=null?h:(u=w.font)==null?void 0:u.color)!=null?m:{r:0,g:0,b:0}),I=(g=(x=w.size)!=null?x:(p=w.font)==null?void 0:p.sizePt)!=null?g:Math.max(8,w.height*.8),L=(b=w.font)!=null&&b.pdfName?await this.getRenderableFont(w.font.pdfName,w.newText):n,$=this.fitTextToFont(L,w.newText),{width:H,height:Z}=C.getSize(),ae=$.trim().length>0?L.widthOfTextAtSize($,I):0;if(!((y=(P=w.removeOperators)==null?void 0:P.streamOperatorIndices)!=null&&y.length?await this.tryRemoveTextOperators(w.pageIndex,w.removeOperators.streamOperatorIndices):false)){let W=Math.min(H-w.x,Math.max(w.width,ae+I*.25)),G=hi({x:w.x,y:w.y,width:W,height:w.height},(D=w.erasePadding)!=null?D:1.75,H,Z);w.eraseClamp&&(G=Br(G,w.eraseClamp)),C.drawRectangle({x:G.x,y:G.y,width:G.width,height:G.height,color:rgb(O.r,O.g,O.b)});}let B=(v=w.baselineY)!=null?v:w.y+Math.max(0,(w.height-I)/2);if((S=w.spans)!=null&&S.length){await this.drawStyledSpans(C,w.spans,w.x,B,I,(F=w.font)==null?void 0:F.pdfName);continue}if($.length===0)continue;C.drawText($,{x:w.x,y:B,size:I,font:L,color:rgb(E.r,E.g,E.b)});continue}if(w.type==="rotate-page"){let O=C.getRotation().angle;C.setRotation(degrees(O+w.degrees));}}await this.applyFormOperations(e,n);}async applyFormOperations(e,n){let r=e.filter(a=>a.type==="create-form-field"||a.type==="update-form-field"||a.type==="set-form-values"||a.type==="delete-form-field"||a.type==="flatten-form");if(r.length===0)return;let i=this.pdfDoc.getForm(),s=false,o=false;for(let a of r)if(a.type==="create-form-field")this.createFormField(a,n),s=true;else if(a.type==="update-form-field"){try{let c=i.getField(a.oldName);c&&i.removeField(c);}catch{}this.createFormField(a,n),s=true;}else if(a.type==="set-form-values"){for(let c of a.values)this.setFieldValue(i,c.name,c.fieldType,c.value);s=true;}else if(a.type==="delete-form-field"){try{let c=i.getField(a.name);c&&i.removeField(c);}catch{}s=true;}else a.type==="flatten-form"&&(o=true);if(s)try{i.updateFieldAppearances(n);}catch{}if(o)try{i.flatten();}catch{}}createFormField(e,n){var f,d;let r=this.pdfDoc.getForm(),i=this.pdfDoc.getPage(e.pageIndex),{x:s,y:o,width:a,height:c}=e.rect,l=e.fontSize&&e.fontSize>0?e.fontSize:void 0;switch(e.fieldType){case "text":case "signature":{let u=r.createTextField(e.name);if(e.value&&u.setText(e.value),l)try{u.setFontSize(l);}catch{}if(e.multiline)try{u.enableMultiline();}catch{}if(e.maxLength&&e.maxLength>0)try{u.setMaxLength(e.maxLength);}catch{}if(e.align)try{u.setAlignment(No[e.align]);}catch{}u.addToPage(i,{x:s,y:o,width:a,height:c,font:n}),(e.fieldType==="signature"||e.readOnly)&&u.enableReadOnly(),e.required&&u.enableRequired();break}case "checkbox":{let u=r.createCheckBox(e.name);u.addToPage(i,{x:s,y:o,width:a,height:c}),e.value&&e.value!=="Off"?u.check():u.uncheck(),e.readOnly&&u.enableReadOnly(),e.required&&u.enableRequired();break}case "dropdown":{let u=r.createDropdown(e.name);if((f=e.options)!=null&&f.length&&u.addOptions(e.options),e.editable)try{u.enableEditing();}catch{}if(e.value)try{u.select(e.value);}catch{}if(l)try{u.setFontSize(l);}catch{}u.addToPage(i,{x:s,y:o,width:a,height:c,font:n}),e.readOnly&&u.enableReadOnly(),e.required&&u.enableRequired();break}case "radio":{let u=r.createRadioGroup(e.name);if(((d=e.options)!=null?d:[]).forEach((m,p)=>{var g,b;let x=(b=(g=e.optionRects)==null?void 0:g[p])!=null?b:{x:s,y:o-p*(c+4),width:a,height:c};u.addOptionToPage(m,i,{x:x.x,y:x.y,width:x.width,height:x.height});}),e.value)try{u.select(e.value);}catch{}e.readOnly&&u.enableReadOnly(),e.required&&u.enableRequired();break}}}setFieldValue(e,n,r,i){try{switch(r){case "text":case "signature":e.getTextField(n).setText(i!=null?i:"");break;case "checkbox":{let s=e.getCheckBox(n);i&&i!=="Off"&&i!=="false"?s.check():s.uncheck();break}case "dropdown":i?e.getDropdown(n).select(i):e.getDropdown(n).clear();break;case "radio":i&&i!=="Off"?e.getRadioGroup(n).select(i):e.getRadioGroup(n).clear();break}}catch{}}async toBlob(){let e=await this.pdfDoc.save({useObjectStreams:false}),n=e instanceof Uint8Array?e:Uint8Array.from(e),r=n.slice().buffer;this.currentBytes=n,this.rewrittenPages.clear(),this.indexInvalidPages.clear();for(let i of this.pdfDoc.getPages()){let s=i;s.contentStream=void 0,s.contentStreamRef=void 0;}return new Blob([r],{type:"application/pdf"})}async tryRemoveTextOperators(e,n){if(this.indexInvalidPages.has(e))return false;try{let{streams:r,combined:i}=await Nr(this.currentBytes,e,n,this.rewrittenPages.get(e)),s=r.filter(l=>l.changed);if(s.length===0)return !1;let o=s.map(l=>PDFRef.of(l.objNum,l.genNum));for(let l of o)if(!this.pdfDoc.context.lookup(l))return !1;s.forEach((l,f)=>{this.pdfDoc.context.assign(o[f],this.pdfDoc.context.flateStream(l.bytes));});let a=this.pdfDoc.getPage(e),c=a.contentStreamRef;return c&&o.some(l=>l.tag===c.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,i),!0}catch{return false}}async tryNeutralizeSpans(e,n){if(!n.length||this.indexInvalidPages.has(e))return false;try{let{streams:r,combined:i}=await Gr(this.currentBytes,e,n,this.rewrittenPages.get(e)),s=r.filter(l=>l.changed);if(s.length===0)return !1;let o=s.map(l=>PDFRef.of(l.objNum,l.genNum));for(let l of o)if(!this.pdfDoc.context.lookup(l))return !1;s.forEach((l,f)=>{this.pdfDoc.context.assign(o[f],this.pdfDoc.context.flateStream(l.bytes));});let a=this.pdfDoc.getPage(e),c=a.contentStreamRef;return c&&o.some(l=>l.tag===c.tag)&&(a.contentStream=void 0),this.rewrittenPages.set(e,i),!0}catch{return false}}async tryWrapSpanWithTransform(e){if(this.indexInvalidPages.has(e.pageIndex))return false;try{let n=He(e.baseCtm);if(!n)return !1;let r=Y(Y(n,e.matrix),e.baseCtm),{streams:i,combined:s}=await Wr(this.currentBytes,e.pageIndex,e.span,r,this.rewrittenPages.get(e.pageIndex)),o=i.filter(f=>f.changed);if(o.length===0)return !1;let a=o.map(f=>PDFRef.of(f.objNum,f.genNum));for(let f of a)if(!this.pdfDoc.context.lookup(f))return !1;o.forEach((f,d)=>{this.pdfDoc.context.assign(a[d],this.pdfDoc.context.flateStream(f.bytes));});let c=this.pdfDoc.getPage(e.pageIndex),l=c.contentStreamRef;return l&&a.some(f=>f.tag===l.tag)&&(c.contentStream=void 0),this.rewrittenPages.set(e.pageIndex,s),this.indexInvalidPages.add(e.pageIndex),!0}catch{return false}}deletePage(e){if(this.pdfDoc.getPageCount()<=1)throw new Error("Cannot delete the last remaining page");this.pdfDoc.removePage(e);}getEmbeddedImage(e,n){let r=0;for(let a=0;a<e.length;a+=Math.max(1,e.length>>5))r=r*31+e[a]>>>0;let i=`${n}:${e.length}:${r}`,s=this.embeddedImageCache.get(i);if(s)return s;let o=n==="png"?this.pdfDoc.embedPng(e):this.pdfDoc.embedJpg(e);return this.embeddedImageCache.set(i,o),o}getStandardFont(e){let n=this.standardFontCache.get(e);if(n)return n;let r=this.pdfDoc.embedFont(e);return this.standardFontCache.set(e,r),r}async drawStyledSpans(e,n,r,i,s,o){var c,l;let a=r;for(let f of n){if(f.text.length===0)continue;let d=(c=f.style.sizePt)!=null?c:s,u=Ir(o,{bold:f.style.bold,italic:f.style.italic}),h=await this.getRenderableFont(u,f.text),m=this.fitTextToFont(h,f.text);if(m.length===0)continue;let p=ut((l=f.style.color)!=null?l:{r:0,g:0,b:0}),x=rgb(p.r,p.g,p.b),g=h.widthOfTextAtSize(m,d);if(e.drawText(m,{x:a,y:i,size:d,font:h,color:x}),f.style.underline||f.style.strikethrough){let b=Math.max(.5,d*.06);f.style.underline&&e.drawRectangle({x:a,y:i-d*.12,width:g,height:b,color:x}),f.style.strikethrough&&e.drawRectangle({x:a,y:i+d*.28,width:g,height:b,color:x});}a+=g;}}async getRenderableFont(e,n){let r=mi(e),i=await this.getStandardFont(Go(e));if(this.fontSupportsText(i,n))return i;let s=await this.getStandardFont(StandardFonts.Helvetica);if(this.fontSupportsText(s,n))return s;let o=await this.getEmbeddedFont(r);if(o&&this.fontSupportsText(o,n))return o;let a=o?[i,s,o]:[i,s],c=a[0],l=1/0;for(let f of a){let d=this.unsupportedCount(f,n);d<l&&(l=d,c=f);}return c}supportedCodePoints(e){try{return new Set(e.getCharacterSet())}catch{return new Set}}unsupportedCount(e,n){let r=this.supportedCodePoints(e);return Wt(n).filter(i=>{let s=String.fromCodePoint(i);return s!=="\r"&&s!==`
39
+ `&&s!==" "&&!r.has(i)}).length}fitTextToFont(e,n){if(this.fontSupportsText(e,n))return n;let r=this.supportedCodePoints(e),i=[],s="";for(let o of Wt(n)){let a=String.fromCodePoint(o);if(a==="\r"||a===`
40
+ `||a===" "||r.has(o)){s+=a;continue}let c=Xo.get(a);if(c!==void 0&&Wt(c).every(f=>String.fromCodePoint(f)===`
41
+ `||r.has(f))){s+=c;continue}i.push(a);}i.length>0&&console.warn(`[PDFEditSession] Dropped ${i.length} character(s) the font cannot encode: ${[...new Set(i)].join(" ")}`);try{return e.encodeText(s),s}catch{return s.replace(/[^\x20-\x7E\r\n\t]/g,"")}}fontSupportsText(e,n){if(n.length===0)return true;try{let r=new Set(e.getCharacterSet());return Wt(n).filter(s=>{let o=String.fromCodePoint(s);return o!=="\r"&&o!==`
42
+ `&&o!==" "}).some(s=>!r.has(s))?!1:(e.encodeText(n),!0)}catch{return false}}async getEmbeddedFont(e){let n=this.embeddedFontCache.get(e);if(n)return n;let r=(async()=>{var o;await this.ensureFontkitRegistered();let i=this.getEmbeddedFontPrograms(),s=(o=i.find(a=>a.normalizedName===e))!=null?o:i.find(a=>a.normalizedName.includes(e)||e.includes(a.normalizedName));if(!s)return null;try{return await this.pdfDoc.embedFont(s.bytes,{subset:!0})}catch{return null}})();return this.embeddedFontCache.set(e,r),r}getEmbeddedFontPrograms(){return this.embeddedFonts||(this.embeddedFonts=Ko(this.pdfBytes)),this.embeddedFonts}async ensureFontkitRegistered(){if(this.fontkitRegistered)return;let e=(await import('./fontkit.es-K7R5OPSY.js')).default;this.pdfDoc.registerFontkit(e),this.fontkitRegistered=true;}};function re(t,e){if(t){if(!q(t))return t;try{return e(t)}catch{return}}}function Vo(t,e){if(!t)return;let n=re(t.entries.get("AcroForm"),e);if(!(!n||!M(n)))return n}function zo(t,e){if(!t)return [];let n=re(t.entries.get("Annots"),e);if(!n)return [];let r=[];if(j(n))for(let i of n.items){let s=re(i,e);s&&M(s)&&r.push(s);}return r}var kn=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,We=t=>{if(!t||typeof t!="object"||!("type"in t)||t.type!=="string")return null;let e=t.value;if(e.length>=2&&e[0]===254&&e[1]===255){let r="";for(let i=2;i+1<e.length;i+=2)r+=String.fromCharCode(e[i]<<8|e[i+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},xi=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,qo=1,Jo=2,Zo=4096,Qo=32768,ea=65536,ta=t=>{if(!t||!j(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(o=>xi(o));if(e.some(o=>o===null))return null;let[n,r,i,s]=e;return {x:Math.min(n,i),y:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}},pi=(t,e)=>{let n=re(t.entries.get("AP"),e);if(!n||!M(n))return [];let r=re(n.entries.get("N"),e);return !r||!M(r)?[]:Array.from(r.entries.keys()).filter(i=>i!=="Off")},na=(t,e)=>{var i,s,o;let n=re(t,e);if(!n||!j(n))return [];let r=[];for(let a of n.items){let c=re(a,e);c&&j(c)&&c.items.length>0?r.push((s=(i=We(c.items[0]))!=null?i:We(c.items[1]))!=null?s:""):r.push((o=We(c))!=null?o:"");}return r.filter(a=>a.length>0)},ra=t=>{if(!t)return;let e=t.match(/([\d.]+)\s+Tf/);if(!e)return;let n=parseFloat(e[1]);return Number.isFinite(n)?n:void 0},ia=(t,e)=>{switch(t){case "Tx":return "text";case "Ch":return "dropdown";case "Sig":return "signature";case "Btn":return e&ea?null:e&Qo?"radio":"checkbox";default:return null}},sa=(t,e)=>{let n=new Map;for(let[r,i]of t)for(let s of zo(i,e))n.has(s)||n.set(s,r);return n};function oa(t,e,n){let r=Vo(t,n);if(!r)return [];let i=re(r.entries.get("Fields"),n);if(!i||!j(i))return [];let s=We(r.entries.get("DA")),o=sa(e,n),a=[],c=(l,f)=>{var $,H,Z,ae,T;let d=We(l.entries.get("T")),u=d?f.namePrefix?`${f.namePrefix}.${d}`:d:f.namePrefix,h=xi(l.entries.get("Ff")),m=h!==null?h:f.flags,p=($=kn(l.entries.get("FT")))!=null?$:f.ft,x=(H=We(l.entries.get("DA")))!=null?H:f.da,g=(ae=(Z=We(l.entries.get("V")))!=null?Z:kn(l.entries.get("V")))!=null?ae:f.value,b={flags:m,namePrefix:u,ft:p,da:x,value:g!=null?g:void 0},P=re(l.entries.get("Kids"),n),y=P&&j(P)?P.items.map(B=>re(B,n)).filter(B=>!!B&&M(B)):[],v=kn(l.entries.get("Subtype"))==="Widget"||y.length===0&&l.entries.has("Rect"),S=y.some(B=>B.entries.has("T"));if(y.length>0&&S){for(let B of y)c(B,b);return}let F=ia(p,m);if(!F){for(let B of y)c(B,b);return}let w=ra(x!=null?x:s),C=(m&qo)!==0,O=(m&Jo)!==0,E=(m&Zo)!==0,I=F==="dropdown"?na(l.entries.get("Opt"),n):void 0,L=y.length>0?y:v?[l]:[];for(let B of L){let W=ta(re(B.entries.get("Rect"),n));if(!W)continue;let G=(T=o.get(B))!=null?T:0,ee=(F==="checkbox"||F==="radio"?pi(B,n):[])[0];a.push({id:`${u}__${a.length}`,name:u,type:F,pageIndex:G,rect:W,value:g!=null?g:void 0,options:F==="radio"?L.map(te=>pi(te,n)[0]).filter(te=>!!te):I,onState:ee,fontSize:w,multiline:E,readOnly:C,required:O});}};for(let l of i.items){let f=re(l,n);f&&M(f)&&c(f,{flags:0,namePrefix:""});}return a}var gi=t=>t&&typeof t=="object"&&"type"in t&&t.type==="name"?t.value:null,aa=t=>t&&typeof t=="object"&&"type"in t&&(t.type==="integer"||t.type==="real")?t.value:null,ca=t=>{if(!t||typeof t!="object"||!("type"in t)||t.type!=="string")return null;let e=t.value;if(e.length>=2&&e[0]===254&&e[1]===255){let r="";for(let i=2;i+1<e.length;i+=2)r+=String.fromCharCode(e[i]<<8|e[i+1]);return r}let n="";for(let r=0;r<e.length;r++)n+=String.fromCharCode(e[r]);return n},la=t=>{if(!t||!j(t)||t.items.length<4)return null;let e=t.items.slice(0,4).map(o=>aa(o));if(e.some(o=>o===null))return null;let[n,r,i,s]=e;return {x:Math.min(n,i),y:Math.min(r,s),width:Math.abs(i-n),height:Math.abs(s-r)}},bi=(t,e,n)=>{let r=q(t)?t:re(t,n);if(!r||!j(r)||r.items.length===0)return;let i=r.items[0];if(q(i))return e.get(`${i.objNum}:${i.genNum}`)};function yi(t,e,n){var s;if(!t)return [];let r=re(t.entries.get("Annots"),n);if(!r||!j(r))return [];let i=[];for(let o of r.items){let a=re(o,n);if(!a||!M(a)||gi(a.entries.get("Subtype"))!=="Link")continue;let c=la(re(a.entries.get("Rect"),n));if(!c||c.width<1||c.height<1)continue;let l,f,d=re(a.entries.get("A"),n);if(d&&M(d)){let u=gi(d.entries.get("S"));u==="URI"?l=(s=ca(d.entries.get("URI")))!=null?s:void 0:u==="GoTo"&&(f=bi(d.entries.get("D"),e,n));}l===void 0&&f===void 0&&(f=bi(a.entries.get("Dest"),e,n)),(l||f!==void 0)&&i.push({rect:c,uri:l,destPageIndex:f});}return i}var Pi=new WeakMap,Rn=class{constructor(){this.name="pdf-editor-core";this.supportedTypes=["pdf"];}async process(e,n){var r,i;try{let s=(r=n.operations)!=null?r:[];if(s.length===0)return {success:!1,document:e,error:"No edit operations were provided."};let o=(i=Pi.get(e.blob))!=null?i:await ft.fromAvniDocument(e);await o.applyOperations(s);let a=await o.toBlob();Pi.set(a,o);let c={taskId:crypto.randomUUID(),processorName:this.name,timestamp:Date.now(),params:n};return {success:!0,document:{...e,blob:a,size:a.size,history:[...e.history,c]},metrics:{duration:0,originalSize:e.size,newSize:a.size}}}catch(s){return {success:false,document:e,error:s instanceof Error?s.message:"Unknown PDF edit failure"}}}};var Tn=class{constructor(){this.name="pdf-compressor";this.supportedTypes=["pdf"];}async process(e,n){try{let i=(n.level||50)/100,s=await e.blob.arrayBuffer(),o=await PDFDocument.load(s);o.setTitle(""),o.setAuthor(""),o.setSubject(""),o.setKeywords([]),o.setCreator(""),o.setProducer("");let a=o.context.enumerateIndirectObjects();for(let[,d]of a){if(!(d instanceof PDFRawStream))continue;let u=d.dict;if(u.get(PDFName.of("Subtype"))===PDFName.of("Image"))try{let m=u.get(PDFName.of("Width")),p=u.get(PDFName.of("Height")),x=m instanceof PDFNumber?m.asNumber():0,g=p instanceof PDFNumber?p.asNumber():0;if(x>500||g>500){let b=d.contents,P=await this.compressImageInBrowser(b,x,g,i);P&&P.length<b.length&&(d.contents=P,u.set(PDFName.of("Length"),PDFNumber.of(P.length)),u.set(PDFName.of("Filter"),PDFName.of("DCTDecode")));}}catch{}}if(i<.7){let d=o.getPages();for(let u of d)u.scale(i,i);}let c=await o.save({useObjectStreams:!0}),l=new Blob([c],{type:"application/pdf"}),f={taskId:crypto.randomUUID(),processorName:this.name,timestamp:Date.now(),params:n};return {success:!0,document:{...e,blob:l,size:l.size,history:[...e.history,f]},metrics:{duration:0,originalSize:e.size,newSize:l.size}}}catch(r){return console.error("Adobe-Level Compression error:",r),{success:false,document:e,error:r instanceof Error?r.message:"Unknown error"}}}async compressImageInBrowser(e,n,r,i){return new Promise(s=>{try{let o=new Blob([e]),a=URL.createObjectURL(o),c=new Image;c.onload=()=>{URL.revokeObjectURL(a);let l=document.createElement("canvas"),f=l.getContext("2d");if(!f)return s(null);l.width=Math.floor(n*i),l.height=Math.floor(r*i),f.drawImage(c,0,0,l.width,l.height),l.toBlob(d=>{if(!d)return s(null);let u=new FileReader;u.onloadend=()=>{s(new Uint8Array(u.result));},u.readAsArrayBuffer(d);},"image/jpeg",Math.max(.1,i));},c.onerror=()=>{URL.revokeObjectURL(a),s(null);},c.src=a;}catch{s(null);}})}};export{mt as AvniOrchestrator,Tn as PDFCompressor,Rn as PDFEditProcessor,ft as PDFEditSession,Te as PDFParser,jt as PageRenderer,$t as WATERMARK_TEXT,wn as assertFeature,Di as avniEngine,Ao as configureLicense,Qr as drawWatermarkOnCanvas,Ro as getLicenseState,oi as isFeatureEnabled,er as loadPageContentStream,To as onLicenseChange,Ue as parseContentStream,oa as parseFormFields,yi as parseLinkAnnotations,Oo as shouldWatermark,ei as stampWatermarkOnPdf};