var __webpack_require__={d:(exports,definition)=>{for(var key in definition)__webpack_require__.o(definition,key)&&!__webpack_require__.o(exports,key)&&Object.defineProperty(exports,key,{enumerable:!0,get:definition[key]})},o:(obj,prop)=>Object.prototype.hasOwnProperty.call(obj,prop)},__webpack_exports__=globalThis.pdfjsWorker={};__webpack_require__.d(__webpack_exports__,{WorkerMessageHandler:()=>WorkerMessageHandler});const isNodeJS=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type),IDENTITY_MATRIX=[1,0,0,1,0,0],FONT_IDENTITY_MATRIX=[.001,0,0,.001,0,0],MAX_IMAGE_SIZE_TO_CACHE=1e7,LINE_FACTOR=1.35,LINE_DESCENT_FACTOR=.35,BASELINE_FACTOR=LINE_DESCENT_FACTOR/LINE_FACTOR,RenderingIntentFlag={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,OPLIST:256},AnnotationMode={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},AnnotationEditorPrefix="pdfjs_internal_editor_",AnnotationEditorType={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},AnnotationEditorParamsType={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},PermissionFlag={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},TextRenderingMode={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},ImageKind={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},AnnotationType={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},AnnotationReplyType={GROUP:"Group",REPLY:"R"},AnnotationFlag={INVISIBLE:1,HIDDEN:2,PRINT:4,NOZOOM:8,NOROTATE:16,NOVIEW:32,READONLY:64,LOCKED:128,TOGGLENOVIEW:256,LOCKEDCONTENTS:512},AnnotationFieldFlag={READONLY:1,REQUIRED:2,NOEXPORT:4,MULTILINE:4096,PASSWORD:8192,NOTOGGLETOOFF:16384,RADIO:32768,PUSHBUTTON:65536,COMBO:131072,EDIT:262144,SORT:524288,FILESELECT:1048576,MULTISELECT:2097152,DONOTSPELLCHECK:4194304,DONOTSCROLL:8388608,COMB:16777216,RICHTEXT:33554432,RADIOSINUNISON:33554432,COMMITONSELCHANGE:67108864},AnnotationBorderStyleType={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},AnnotationActionEventType={E:"Mouse Enter",X:"Mouse Exit",D:"Mouse Down",U:"Mouse Up",Fo:"Focus",Bl:"Blur",PO:"PageOpen",PC:"PageClose",PV:"PageVisible",PI:"PageInvisible",K:"Keystroke",F:"Format",V:"Validate",C:"Calculate"},DocumentActionEventType={WC:"WillClose",WS:"WillSave",DS:"DidSave",WP:"WillPrint",DP:"DidPrint"},PageActionEventType={O:"PageOpen",C:"PageClose"},VerbosityLevel={ERRORS:0,WARNINGS:1,INFOS:5},CMapCompressionType={NONE:0,BINARY:1},OPS={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91},PasswordResponses={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let verbosity=VerbosityLevel.WARNINGS;function setVerbosityLevel(level){Number.isInteger(level)&&(verbosity=level)}function getVerbosityLevel(){return verbosity}function info(msg){verbosity>=VerbosityLevel.INFOS&&console.log("Info: "+msg)}function warn(msg){verbosity>=VerbosityLevel.WARNINGS&&console.log("Warning: "+msg)}function unreachable(msg){throw new Error(msg)}function assert(cond,msg){cond||unreachable(msg)}function _isValidProtocol(url){switch(url?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function createValidAbsoluteUrl(url,baseUrl=null,options=null){if(url)try{if(options&&"string"==typeof url)if(options.addDefaultProtocol&&url.startsWith("www.")&&2<=url.match(/\./g)?.length&&(url="http://"+url),options.tryConvertEncoding)try{url=stringToUTF8String(url)}catch{}var absoluteUrl=baseUrl?new URL(url,baseUrl):new URL(url);if(_isValidProtocol(absoluteUrl))return absoluteUrl}catch{}return null}function shadow(obj,prop,value,nonSerializable=!1){return Object.defineProperty(obj,prop,{value:value,enumerable:!nonSerializable,configurable:!0,writable:!1}),value}const BaseException=function(){function BaseException(message,name){this.constructor===BaseException&&unreachable("Cannot initialize BaseException."),this.message=message,this.name=name}return BaseException.prototype=new Error,BaseException.constructor=BaseException}();class PasswordException extends BaseException{constructor(msg,code){super(msg,"PasswordException"),this.code=code}}class UnknownErrorException extends BaseException{constructor(msg,details){super(msg,"UnknownErrorException"),this.details=details}}class InvalidPDFException extends BaseException{constructor(msg){super(msg,"InvalidPDFException")}}class MissingPDFException extends BaseException{constructor(msg){super(msg,"MissingPDFException")}}class UnexpectedResponseException extends BaseException{constructor(msg,status){super(msg,"UnexpectedResponseException"),this.status=status}}class FormatError extends BaseException{constructor(msg){super(msg,"FormatError")}}class AbortException extends BaseException{constructor(msg){super(msg,"AbortException")}}function bytesToString(bytes){"object"==typeof bytes&&void 0!==bytes?.length||unreachable("Invalid argument for bytesToString");var length=bytes.length;if(length<8192)return String.fromCharCode.apply(null,bytes);var strBuf=[];for(let i=0;i>24&255,value>>16&255,value>>8&255,255&value)}function objectSize(obj){return Object.keys(obj).length}function objectFromMap(map){var key,value,obj=Object.create(null);for([key,value]of map)obj[key]=value;return obj}function isLittleEndian(){var buffer8=new Uint8Array(4),buffer8=(buffer8[0]=1,new Uint32Array(buffer8.buffer,0,1));return 1===buffer8[0]}function isEvalSupported(){try{return new Function(""),!0}catch{return!1}}class FeatureTest{static get isLittleEndian(){return shadow(this,"isLittleEndian",isLittleEndian())}static get isEvalSupported(){return shadow(this,"isEvalSupported",isEvalSupported())}static get isOffscreenCanvasSupported(){return shadow(this,"isOffscreenCanvasSupported","undefined"!=typeof OffscreenCanvas)}static get platform(){return"undefined"!=typeof navigator&&"string"==typeof navigator?.platform?shadow(this,"platform",{isMac:navigator.platform.includes("Mac")}):shadow(this,"platform",{isMac:!1})}static get isCSSRoundSupported(){return shadow(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const hexNumbers=Array.from(Array(256).keys(),n=>n.toString(16).padStart(2,"0"));class Util{static makeHexColor(r,g,b){return"#"+hexNumbers[r]+hexNumbers[g]+hexNumbers[b]}static scaleMinMax(transform,minMax){let temp;transform[0]?(transform[0]<0&&(temp=minMax[0],minMax[0]=minMax[2],minMax[2]=temp),minMax[0]*=transform[0],minMax[2]*=transform[0],transform[3]<0&&(temp=minMax[1],minMax[1]=minMax[3],minMax[3]=temp),minMax[1]*=transform[3],minMax[3]*=transform[3]):(temp=minMax[0],minMax[0]=minMax[1],minMax[1]=temp,temp=minMax[2],minMax[2]=minMax[3],minMax[3]=temp,transform[1]<0&&(temp=minMax[1],minMax[1]=minMax[3],minMax[3]=temp),minMax[1]*=transform[1],minMax[3]*=transform[1],transform[2]<0&&(temp=minMax[0],minMax[0]=minMax[2],minMax[2]=temp),minMax[0]*=transform[2],minMax[2]*=transform[2]),minMax[0]+=transform[4],minMax[1]+=transform[5],minMax[2]+=transform[4],minMax[3]+=transform[5]}static transform(m1,m2){return[m1[0]*m2[0]+m1[2]*m2[1],m1[1]*m2[0]+m1[3]*m2[1],m1[0]*m2[2]+m1[2]*m2[3],m1[1]*m2[2]+m1[3]*m2[3],m1[0]*m2[4]+m1[2]*m2[5]+m1[4],m1[1]*m2[4]+m1[3]*m2[5]+m1[5]]}static applyTransform(p,m){return[p[0]*m[0]+p[1]*m[2]+m[4],p[0]*m[1]+p[1]*m[3]+m[5]]}static applyInverseTransform(p,m){var d=m[0]*m[3]-m[1]*m[2];return[(p[0]*m[3]-p[1]*m[2]+m[2]*m[5]-m[4]*m[3])/d,(-p[0]*m[1]+p[1]*m[0]+m[4]*m[1]-m[5]*m[0])/d]}static getAxialAlignedBoundingBox(r,m){var p1=this.applyTransform(r,m),p2=this.applyTransform(r.slice(2,4),m),p3=this.applyTransform([r[0],r[3]],m),r=this.applyTransform([r[2],r[1]],m);return[Math.min(p1[0],p2[0],p3[0],r[0]),Math.min(p1[1],p2[1],p3[1],r[1]),Math.max(p1[0],p2[0],p3[0],r[0]),Math.max(p1[1],p2[1],p3[1],r[1])]}static inverseTransform(m){var d=m[0]*m[3]-m[1]*m[2];return[m[3]/d,-m[1]/d,-m[2]/d,m[0]/d,(m[2]*m[5]-m[4]*m[3])/d,(m[4]*m[1]-m[5]*m[0])/d]}static singularValueDecompose2dScale(m){var transpose=[m[0],m[2],m[1],m[3]],a=m[0]*transpose[0]+m[1]*transpose[2],b=m[0]*transpose[1]+m[1]*transpose[3],c=m[2]*transpose[0]+m[3]*transpose[2],m=m[2]*transpose[1]+m[3]*transpose[3],transpose=(a+m)/2,a=Math.sqrt((a+m)**2-4*(a*m-c*b))/2,m=transpose-a||1;return[Math.sqrt(transpose+a||1),Math.sqrt(m)]}static normalizeRect(rect){var r=rect.slice(0);return rect[0]>rect[2]&&(r[0]=rect[2],r[2]=rect[0]),rect[1]>rect[3]&&(r[1]=rect[3],r[3]=rect[1]),r}static intersect(rect1,rect2){var yLow,xLow=Math.max(Math.min(rect1[0],rect1[2]),Math.min(rect2[0],rect2[2])),xHigh=Math.min(Math.max(rect1[0],rect1[2]),Math.max(rect2[0],rect2[2]));return xHighp1?p1.normalize("NFKC"):NormalizationMap.get(p2))}function getUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto?.randomUUID)return crypto.randomUUID();var buf=new Uint8Array(32);if("undefined"!=typeof crypto&&"function"==typeof crypto?.getRandomValues)crypto.getRandomValues(buf);else for(let i=0;i<32;i++)buf[i]=Math.floor(255*Math.random());return bytesToString(buf)}const AnnotationPrefix="pdfjs_internal_id_",FontRenderOps={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8},CIRCULAR_REF=Symbol("CIRCULAR_REF"),EOF=Symbol("EOF");let CmdCache=Object.create(null),NameCache=Object.create(null),RefCache=Object.create(null);function clearPrimitiveCaches(){CmdCache=Object.create(null),NameCache=Object.create(null),RefCache=Object.create(null)}class Name{constructor(name){this.name=name}static get(name){return NameCache[name]||=new Name(name)}}class Cmd{constructor(cmd){this.cmd=cmd}static get(cmd){return CmdCache[cmd]||=new Cmd(cmd)}}const nonSerializable=function(){return nonSerializable};class Dict{constructor(xref=null){this._map=Object.create(null),this.xref=xref,this.objId=null,this.suppressEncryption=!1,this.__nonSerializable__=nonSerializable}assignXref(newXref){this.xref=newXref}get size(){return Object.keys(this._map).length}get(key1,key2,key3){let value=this._map[key1];return(value=void 0===value&&void 0!==key2&&void 0===(value=this._map[key2])&&void 0!==key3?this._map[key3]:value)instanceof Ref&&this.xref?this.xref.fetch(value,this.suppressEncryption):value}async getAsync(key1,key2,key3){let value=this._map[key1];return(value=void 0===value&&void 0!==key2&&void 0===(value=this._map[key2])&&void 0!==key3?this._map[key3]:value)instanceof Ref&&this.xref?this.xref.fetchAsync(value,this.suppressEncryption):value}getArray(key1,key2,key3){let value=this._map[key1];if((value=void 0===value&&void 0!==key2&&void 0===(value=this._map[key2])&&void 0!==key3?this._map[key3]:value)instanceof Ref&&this.xref&&(value=this.xref.fetch(value,this.suppressEncryption)),Array.isArray(value))for(let i=0,ii=(value=value.slice()).length;i{unreachable("Should not call `set` on the empty dictionary.")},shadow(this,"empty",emptyDict)}static merge({xref,dictArray,mergeSubDicts=!1}){var name,values,mergedDict=new Dict(xref),properties=new Map;for(const dict of dictArray)if(dict instanceof Dict)for(var[key,value]of Object.entries(dict._map)){let property=properties.get(key);if(void 0===property)property=[],properties.set(key,property);else if(!(mergeSubDicts&&value instanceof Dict))continue;property.push(value)}for([name,values]of properties)if(1!==values.length&&values[0]instanceof Dict){var subDict=new Dict(xref);for(const dict of values)for(const[key,value]of Object.entries(dict._map))void 0===subDict._map[key]&&(subDict._map[key]=value);0>24}function readUint16(data,offset){return data[offset]<<8|data[offset+1]}function readUint32(data,offset){return(data[offset]<<24|data[offset+1]<<16|data[offset+2]<<8|data[offset+3])>>>0}function isWhiteSpace(ch){return 32===ch||9===ch||13===ch||10===ch}function isNumberArray(arr,len){return Array.isArray(arr)&&(null===len||arr.length===len)&&arr.every(x=>"number"==typeof x)}function parseXFAPath(path){const positionPattern=/(.+)\[(\d+)\]$/;return path.split(".").map(component=>{var m=component.match(positionPattern);return m?{name:m[1],pos:parseInt(m[2],10)}:{name:component,pos:0}})}function escapePDFName(str){var buffer=[];let start=0;for(let i=0,ii=str.length;i"\n"===match?"\\n":"\r"===match?"\\r":"\\"+match)}function _collectJS(entry,xref,list,parents){if(entry){let parent=null;if(entry instanceof Ref){if(parents.has(entry))return;parent=entry,parents.put(parent),entry=xref.fetch(entry)}if(Array.isArray(entry))for(const element of entry)_collectJS(element,xref,list,parents);else if(entry instanceof Dict){if(isName(entry.get("S"),"JavaScript")){var js=entry.get("JS");let code;js instanceof BaseStream?code=js.getString():"string"==typeof js&&(code=js),(code&&=stringToPDFString(code).replaceAll("\0",""))&&list.push(code)}_collectJS(entry.getRaw("Next"),xref,list,parents)}parent&&parents.remove(parent)}}function collectActions(xref,dict,eventType){var actions=Object.create(null),additionalActionsDicts=getInheritableProperty({dict:dict,key:"AA",stopWhenFound:!1});if(additionalActionsDicts)for(let i=additionalActionsDicts.length-1;0<=i;i--){var additionalActions=additionalActionsDicts[i];if(additionalActions instanceof Dict)for(const key of additionalActions.getKeys()){var list,action=eventType[key];action&&(list=[],_collectJS(additionalActions.getRaw(key),xref,list,new RefSet),0: ${fontFamily}.`),!1;return!0}function validateCSSFont(cssFontInfo){var CSS_FONT_WEIGHT_VALUES=new Set(["100","200","300","400","500","600","700","800","900","1000","normal","bold","bolder","lighter"]),{fontFamily,fontWeight,italicAngle}=cssFontInfo;return!!validateFontName(fontFamily,!0)&&(fontFamily=fontWeight?fontWeight.toString():"",cssFontInfo.fontWeight=CSS_FONT_WEIGHT_VALUES.has(fontFamily)?fontFamily:"400",fontWeight=parseFloat(italicAngle),cssFontInfo.italicAngle=isNaN(fontWeight)||fontWeight<-90||90>8&255).toString(16).padStart(2,"0"),(255&char).toString(16).padStart(2,"0"))}return buf.join("")}function stringToUTF16String(str,bigEndian=!1){var buf=[];bigEndian&&buf.push("þÿ");for(let i=0,ii=str.length;i>8&255),String.fromCharCode(255&char))}return buf.join("")}function getRotationMatrix(rotation,width,height){switch(rotation){case 90:return[0,1,-1,0,width,0];case 180:return[-1,0,0,-1,width,height];case 270:return[0,-1,1,0,0,height];default:throw new Error("Invalid rotation")}}function getSizeInBytes(x){return Math.ceil(Math.ceil(Math.log2(1+x))/8)}class Stream extends BaseStream{constructor(arrayBuffer,start,length,dict){super(),this.bytes=arrayBuffer instanceof Uint8Array?arrayBuffer:new Uint8Array(arrayBuffer),this.start=start||0,this.pos=this.start,this.end=start+length||this.bytes.length,this.dict=dict}get length(){return this.end-this.start}get isEmpty(){return 0===this.length}getByte(){return this.pos>=this.end?-1:this.bytes[this.pos++]}getBytes(length){var bytes=this.bytes,pos=this.pos,strEnd=this.end;if(!length)return bytes.subarray(pos,strEnd);let end=pos+length;return end>strEnd&&(end=strEnd),this.pos=end,bytes.subarray(pos,end)}getByteRange(begin,end){return end>this.end&&(end=this.end),this.bytes.subarray(begin=begin<0?0:begin,end)}reset(){this.pos=this.start}moveStart(){this.start=this.pos}makeSubStream(start,length,dict=null){return new Stream(this.bytes.buffer,start,length,dict)}}class StringStream extends Stream{constructor(str){super(stringToBytes(str))}}class NullStream extends Stream{constructor(){super(new Uint8Array(0))}}class ChunkedStream extends Stream{constructor(length,chunkSize,manager){super(new Uint8Array(length),0,length,null),this.chunkSize=chunkSize,this._loadedChunks=new Set,this.numChunks=Math.ceil(length/chunkSize),this.manager=manager,this.progressiveDataLength=0,this.lastSuccessfulEnsureByteChunk=-1}getMissingChunks(){var chunks=[];for(let chunk=0,n=this.numChunks;chunk=this.end?this.numChunks:Math.floor(position/this.chunkSize));for(let curChunk=beginChunk;curChunkthis.numChunks)&&chunk!==this.lastSuccessfulEnsureByteChunk){if(!this._loadedChunks.has(chunk))throw new MissingDataException(pos,pos+1);this.lastSuccessfulEnsureByteChunk=chunk}}}ensureRange(begin,end){if(!(end<=begin||end<=this.progressiveDataLength)){var beginChunk=Math.floor(begin/this.chunkSize);if(!(beginChunk>this.numChunks)){var endChunk=Math.min(Math.floor((end-1)/this.chunkSize)+1,this.numChunks);for(let chunk=beginChunk;chunk=this.end?-1:(pos>=this.progressiveDataLength&&this.ensureByte(pos),this.bytes[this.pos++])}getBytes(length){var bytes=this.bytes,pos=this.pos,strEnd=this.end;if(!length)return strEnd>this.progressiveDataLength&&this.ensureRange(pos,strEnd),bytes.subarray(pos,strEnd);let end=pos+length;return(end=end>strEnd?strEnd:end)>this.progressiveDataLength&&this.ensureRange(pos,end),this.pos=end,bytes.subarray(pos,end)}getByteRange(begin,end){return begin<0&&(begin=0),(end=end>this.end?this.end:end)>this.progressiveDataLength&&this.ensureRange(begin,end),this.bytes.subarray(begin,end)}makeSubStream(start,length,dict=null){function ChunkedStreamSubstream(){}length?start+length>this.progressiveDataLength&&this.ensureRange(start,start+length):start>=this.progressiveDataLength&&this.ensureByte(start),(ChunkedStreamSubstream.prototype=Object.create(this)).getMissingChunks=function(){var chunkSize=this.chunkSize,beginChunk=Math.floor(this.start/chunkSize),endChunk=Math.floor((this.end-1)/chunkSize)+1,missingChunks=[];for(let chunk=beginChunk;chunk{const readChunk=({value,done})=>{try{var chunkData;done?(chunkData=arrayBuffersToBytes(chunks),chunks=null,resolve(chunkData)):(loaded+=value.byteLength,rangeReader.isStreamingSupported&&this.onProgress({loaded:loaded}),chunks.push(value),rangeReader.read().then(readChunk,reject))}catch(e){reject(e)}};rangeReader.read().then(readChunk,reject)}).then(data=>{this.aborted||this.onReceiveData({chunk:data,begin:begin})})}requestAllChunks(noFetch=!1){return noFetch||(noFetch=this.stream.getMissingChunks(),this._requestChunks(noFetch)),this._loadedStreamCapability.promise}_requestChunks(chunks){var requestId=this.currRequestId++,chunksNeeded=new Set;this._chunksNeededByRequest.set(requestId,chunksNeeded);for(const chunk of chunks)this.stream.hasChunk(chunk)||chunksNeeded.add(chunk);if(0===chunksNeeded.size)return Promise.resolve();var capability=Promise.withResolvers(),chunksToRequest=(this._promisesByRequest.set(requestId,capability),[]);for(const chunk of chunksNeeded){let requestIds=this._requestsByChunk.get(chunk);requestIds||(requestIds=[],this._requestsByChunk.set(chunk,requestIds),chunksToRequest.push(chunk)),requestIds.push(requestId)}if(0{if(!this.aborted)throw reason})}getStream(){return this.stream}requestRange(begin,end){end=Math.min(end,this.length);var begin=this.getBeginChunk(begin),endChunk=this.getEndChunk(end),chunks=[];for(let chunk=begin;chunkthis.amax||this.bmin>this.bmax)&&(info("Invalid Range, falling back to defaults"),this.amin=-100,this.amax=100,this.bmin=-100,this.bmax=100)}#fn_g(x){return 6/29<=x?x**3:108/841*(x-4/29)}#decode(value,high1,low2,high2){return low2+value*(high2-low2)/high1}#toRgb(src,srcOffset,maxVal,dest,destOffset){let Ls=src[srcOffset],as=src[srcOffset+1],bs=src[srcOffset+2];!1!==maxVal&&(Ls=this.#decode(Ls,maxVal,0,100),as=this.#decode(as,maxVal,this.amin,this.amax),bs=this.#decode(bs,maxVal,this.bmin,this.bmax)),as>this.amax?as=this.amax:asthis.bmax?bs=this.bmax:bs>>0}function hexToStr(a,size){return 1===size?String.fromCharCode(a[0],a[1]):3===size?String.fromCharCode(a[0],a[1],a[2],a[3]):String.fromCharCode(...a.subarray(0,size+1))}function addHex(a,b,size){let c=0;for(let i=size;0<=i;i--)c+=a[i]+b[i],a[i]=255&c,c>>=8}function incHex(a,size){let c=1;for(let i=size;0<=i&&0>=8}const MAX_NUM_SIZE=16,MAX_ENCODED_NUM_SIZE=19;class BinaryCMapStream{constructor(data){this.buffer=data,this.pos=0,this.end=data.length,this.tmpBuf=new Uint8Array(MAX_ENCODED_NUM_SIZE)}readByte(){return this.pos>=this.end?-1:this.buffer[this.pos++]}readNumber(){let n=0;var last;do{var b=this.readByte();if(b<0)throw new FormatError("unexpected EOF in bcmap");last=!(128&b),n=n<<7|127&b}while(!last);return n}readSigned(){var n=this.readNumber();return 1&n?~(n>>>1):n>>>1}readHex(num,size){num.set(this.buffer.subarray(this.pos,this.pos+size+1)),this.pos+=size+1}readHexNumber(num,size){var last,stack=this.tmpBuf;let sp=0;do{var b=this.readByte();if(b<0)throw new FormatError("unexpected EOF in bcmap");last=!(128&b),stack[sp++]=127&b}while(!last);let i=size,buffer=0,bufferSize=0;for(;0<=i;){for(;bufferSize<8&&0>=8,bufferSize-=8}}readHexSigned(num,size){this.readHexNumber(num,size);var sign=1&num[size]?255:0;let c=0;for(let i=0;i<=size;i++)c=(1&c)<<8|num[i],num[i]=c>>1^sign}readString(){var len=this.readNumber(),buf=new Array(len);for(let i=0;i>5;if(7==type)switch(31&b){case 0:stream.readString();break;case 1:useCMap=stream.readString()}else{var sequence=!!(16&b),dataSize=15&b;if(1+dataSize>MAX_NUM_SIZE)throw new Error("BinaryCMapReader.process: Invalid dataSize.");var subitemsCount=stream.readNumber();switch(type){case 0:stream.readHex(start,dataSize),stream.readHexNumber(end,dataSize),addHex(end,start,dataSize),cMap.addCodespaceRange(1+dataSize,hexToInt(start,dataSize),hexToInt(end,dataSize));for(let i=1;ilength&&(end=length)}else{for(;!this.eof;)this.readBlock(ignoreColorSpace);end=this.bufferLength}return this.pos=end,this.buffer.subarray(pos,end)}reset(){this.pos=0}makeSubStream(start,length,dict=null){if(void 0===length)for(;!this.eof;)this.readBlock();else for(var end=start+length;this.bufferLength<=end&&!this.eof;)this.readBlock();return new Stream(this.buffer,start,length,dict)}getBaseStreams(){return this.str?this.str.getBaseStreams():null}}class StreamsSequenceStream extends DecodeStream{constructor(streams,onError=null){let maybeLength=0;for(const stream of streams)maybeLength+=stream instanceof DecodeStream?stream._rawMinBufferLength:stream.length;super(maybeLength),this.streams=streams,this._onError=onError}readBlock(){var streams=this.streams;if(0===streams.length)this.eof=!0;else{streams=streams.shift();let chunk;try{chunk=streams.getBytes()}catch(reason){if(this._onError)return void this._onError(reason,streams.dict?.objId);throw reason}var streams=this.bufferLength,newLength=streams+chunk.length;this.ensureBuffer(newLength).set(chunk,streams),this.bufferLength=newLength}}getBaseStreams(){var baseStreamsBuf=[];for(const stream of this.streams){var baseStreams=stream.getBaseStreams();baseStreams&&baseStreamsBuf.push(...baseStreams)}return 0>=8}}}}class AsciiHexStream extends DecodeStream{constructor(str,maybeLength){maybeLength&&(maybeLength*=.5),super(maybeLength),this.str=str,this.dict=str.dict,this.firstDigit=-1}readBlock(){var bytes=this.str.getBytes(8e3);if(bytes.length){var maxDecodeLength=bytes.length+1>>1,buffer=this.ensureBuffer(this.bufferLength+maxDecodeLength);let bufferLength=this.bufferLength,firstDigit=this.firstDigit;for(const ch of bytes){let digit;if(48<=ch&&ch<=57)digit=15&ch;else{if(!(65<=ch&&ch<=70||97<=ch&&ch<=102)){if(62!==ch)continue;this.eof=!0;break}digit=9+(15&ch)}firstDigit=firstDigit<0?digit:(buffer[bufferLength++]=firstDigit<<4|digit,-1)}0<=firstDigit&&this.eof&&(buffer[bufferLength++]=firstDigit<<4,firstDigit=-1),this.firstDigit=firstDigit,this.bufferLength=bufferLength}else this.eof=!0}}const ccittEOL=-2,ccittEOF=-1,twoDimPass=0,twoDimHoriz=1,twoDimVert0=2,twoDimVertR1=3,twoDimVertL1=4,twoDimVertR2=5,twoDimVertL2=6,twoDimVertR3=7,twoDimVertL3=8,twoDimTable=[[-1,-1],[-1,-1],[7,twoDimVertL3],[7,twoDimVertR3],[6,twoDimVertL2],[6,twoDimVertL2],[6,twoDimVertR2],[6,twoDimVertR2],[4,twoDimPass],[4,twoDimPass],[4,twoDimPass],[4,twoDimPass],[4,twoDimPass],[4,twoDimPass],[4,twoDimPass],[4,twoDimPass],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimHoriz],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertL1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[3,twoDimVertR1],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0],[1,twoDimVert0]],whiteTable1=[[-1,-1],[12,ccittEOL],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[12,1984],[12,2048],[12,2112],[12,2176],[12,2240],[12,2304],[11,1856],[11,1856],[11,1920],[11,1920],[12,2368],[12,2432],[12,2496],[12,2560]],whiteTable2=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[8,29],[8,29],[8,30],[8,30],[8,45],[8,45],[8,46],[8,46],[7,22],[7,22],[7,22],[7,22],[7,23],[7,23],[7,23],[7,23],[8,47],[8,47],[8,48],[8,48],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[6,13],[7,20],[7,20],[7,20],[7,20],[8,33],[8,33],[8,34],[8,34],[8,35],[8,35],[8,36],[8,36],[8,37],[8,37],[8,38],[8,38],[7,19],[7,19],[7,19],[7,19],[8,31],[8,31],[8,32],[8,32],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,1],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[6,12],[8,53],[8,53],[8,54],[8,54],[7,26],[7,26],[7,26],[7,26],[8,39],[8,39],[8,40],[8,40],[8,41],[8,41],[8,42],[8,42],[8,43],[8,43],[8,44],[8,44],[7,21],[7,21],[7,21],[7,21],[7,28],[7,28],[7,28],[7,28],[8,61],[8,61],[8,62],[8,62],[8,63],[8,63],[8,0],[8,0],[8,320],[8,320],[8,384],[8,384],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,10],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[5,11],[7,27],[7,27],[7,27],[7,27],[8,59],[8,59],[8,60],[8,60],[9,1472],[9,1536],[9,1600],[9,1728],[7,18],[7,18],[7,18],[7,18],[7,24],[7,24],[7,24],[7,24],[8,49],[8,49],[8,50],[8,50],[8,51],[8,51],[8,52],[8,52],[7,25],[7,25],[7,25],[7,25],[8,55],[8,55],[8,56],[8,56],[8,57],[8,57],[8,58],[8,58],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,192],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[6,1664],[8,448],[8,448],[8,512],[8,512],[9,704],[9,768],[8,640],[8,640],[8,576],[8,576],[9,832],[9,896],[9,960],[9,1024],[9,1088],[9,1152],[9,1216],[9,1280],[9,1344],[9,1408],[7,256],[7,256],[7,256],[7,256],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,2],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,128],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,8],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[5,9],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,16],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[6,17],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,4],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[4,5],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,14],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[6,15],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[5,64],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,6],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7],[4,7]],blackTable1=[[-1,-1],[-1,-1],[12,ccittEOL],[12,ccittEOL],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[-1,-1],[11,1792],[11,1792],[11,1792],[11,1792],[12,1984],[12,1984],[12,2048],[12,2048],[12,2112],[12,2112],[12,2176],[12,2176],[12,2240],[12,2240],[12,2304],[12,2304],[11,1856],[11,1856],[11,1856],[11,1856],[11,1920],[11,1920],[11,1920],[11,1920],[12,2368],[12,2368],[12,2432],[12,2432],[12,2496],[12,2496],[12,2560],[12,2560],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[10,18],[12,52],[12,52],[13,640],[13,704],[13,768],[13,832],[12,55],[12,55],[12,56],[12,56],[13,1280],[13,1344],[13,1408],[13,1472],[12,59],[12,59],[12,60],[12,60],[13,1536],[13,1600],[11,24],[11,24],[11,24],[11,24],[11,25],[11,25],[11,25],[11,25],[13,1664],[13,1728],[12,320],[12,320],[12,384],[12,384],[12,448],[12,448],[13,512],[13,576],[12,53],[12,53],[12,54],[12,54],[13,896],[13,960],[13,1024],[13,1088],[13,1152],[13,1216],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64],[10,64]],blackTable2=[[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[8,13],[11,23],[11,23],[12,50],[12,51],[12,44],[12,45],[12,46],[12,47],[12,57],[12,58],[12,61],[12,256],[10,16],[10,16],[10,16],[10,16],[10,17],[10,17],[10,17],[10,17],[12,48],[12,49],[12,62],[12,63],[12,30],[12,31],[12,32],[12,33],[12,40],[12,41],[11,22],[11,22],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[8,14],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,10],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[7,11],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[9,15],[12,128],[12,192],[12,26],[12,27],[12,28],[12,29],[11,19],[11,19],[11,20],[11,20],[12,34],[12,35],[12,36],[12,37],[12,38],[12,39],[11,21],[11,21],[12,42],[12,43],[10,0],[10,0],[10,0],[10,0],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12],[7,12]],blackTable3=[[-1,-1],[-1,-1],[-1,-1],[-1,-1],[6,9],[6,8],[5,7],[5,7],[4,6],[4,6],[4,6],[4,6],[4,5],[4,5],[4,5],[4,5],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[3,4],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,3],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2],[2,2]];class CCITTFaxDecoder{constructor(source,options={}){if(!source||"function"!=typeof source.next)throw new Error('CCITTFaxDecoder - invalid "source" parameter.');this.source=source,this.eof=!1,this.encoding=options.K||0,this.eoline=options.EndOfLine||!1,this.byteAlign=options.EncodedByteAlign||!1,this.columns=options.Columns||1728,this.rows=options.Rows||0,this.eoblock=options.EndOfBlock??!0,this.black=options.BlackIs1||!1,this.codingLine=new Uint32Array(this.columns+1),this.refLine=new Uint32Array(this.columns+2),this.codingLine[0]=this.columns,this.codingPos=0,this.row=0,this.nextLine2D=this.encoding<0,this.inputBits=0,this.inputBuf=0,this.outputBits=0,this.rowsDone=!1;let code1;for(;0===(code1=this._lookBits(12));)this._eatBits(1);1===code1&&this._eatBits(12),0>1==1)break;this._eatBits(1)}this._eatBits(12),0bits?(c<<=bits,1&this.codingPos||(c|=255>>8-bits),this.outputBits-=bits,bits=0):(c<<=this.outputBits,1&this.codingPos||(c|=255>>8-this.outputBits),bits-=this.outputBits,this.outputBits=0,codingLine[this.codingPos]codingLine[codingPos]&&(a1>this.columns&&(info("row is wrong length"),this.err=!0,a1=this.columns),1&codingPos^blackPixels&&++codingPos,codingLine[codingPos]=a1),this.codingPos=codingPos}_addPixelsNeg(a1,blackPixels){var codingLine=this.codingLine;let codingPos=this.codingPos;if(a1>codingLine[codingPos])a1>this.columns&&(info("row is wrong length"),this.err=!0,a1=this.columns),1&codingPos^blackPixels&&++codingPos,codingLine[codingPos]=a1;else if(a1=limitValue){var p=table[code-limitValue];if(p[0]===i)return this._eatBits(i),[!0,p[1],!0]}}return[!1,0,!1]}_getTwoDimCode(){if(this.eoblock){if(code=this._lookBits(7),0<(code=twoDimTable[code])?.[0])return this._eatBits(code[0]),code[1]}else{var code=this._findTableCode(1,7,twoDimTable);if(code[0]&&code[2])return code[1]}return info("Bad two dim code"),ccittEOF}_getWhiteCode(){if(this.eoblock){if((code=this._lookBits(12))===ccittEOF)return 1;if(0<(code=code>>5==0?whiteTable1[code]:whiteTable2[code>>3])[0])return this._eatBits(code[0]),code[1]}else{var code=this._findTableCode(1,9,whiteTable2);if(code[0])return code[1];if((code=this._findTableCode(11,12,whiteTable1))[0])return code[1]}return info("bad white code"),this._eatBits(1),1}_getBlackCode(){let code,p;if(this.eoblock){if((code=this._lookBits(13))===ccittEOF)return 1;if(0<(p=code>>7==0?blackTable1[code]:code>>9==0&&code>>7!=0?blackTable2[(code>>1)-64]:blackTable3[code>>7])[0])return this._eatBits(p[0]),p[1]}else{var result=this._findTableCode(2,6,blackTable3);if(result[0])return result[1];if((result=this._findTableCode(7,12,blackTable2,64))[0])return result[1];if((result=this._findTableCode(10,13,blackTable1))[0])return result[1]}return info("bad black code"),this._eatBits(1),1}_lookBits(n){for(var c;this.inputBits>16-n;this.inputBuf=this.inputBuf<<8|c,this.inputBits+=8}return this.inputBuf>>this.inputBits-n&65535>>16-n}_eatBits(n){(this.inputBits-=n)<0&&(this.inputBits=0)}}class CCITTFaxStream extends DecodeStream{constructor(str,maybeLength,params){super(maybeLength),this.str=str,this.dict=str.dict,params instanceof Dict||(params=Dict.empty);maybeLength={next(){return str.getByte()}};this.ccittFaxDecoder=new CCITTFaxDecoder(maybeLength,{K:params.get("K"),EndOfLine:params.get("EndOfLine"),EncodedByteAlign:params.get("EncodedByteAlign"),Columns:params.get("Columns"),Rows:params.get("Rows"),EndOfBlock:params.get("EndOfBlock"),BlackIs1:params.get("BlackIs1")})}readBlock(){for(;!this.eof;){var c=this.ccittFaxDecoder.readNextChar();if(-1===c)return void(this.eof=!0);this.ensureBuffer(this.bufferLength+1),this.buffer[this.bufferLength++]=c}}}const codeLenCodeMap=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),lengthDecode=new Int32Array([3,4,5,6,7,8,9,10,65547,65549,65551,65553,131091,131095,131099,131103,196643,196651,196659,196667,262211,262227,262243,262259,327811,327843,327875,327907,258,258,258]),distDecode=new Int32Array([1,2,3,4,65541,65543,131081,131085,196625,196633,262177,262193,327745,327777,393345,393409,459009,459137,524801,525057,590849,591361,657409,658433,724993,727041,794625,798721,868353,876545]),fixedLitCodeTab=[new Int32Array([459008,524368,524304,524568,459024,524400,524336,590016,459016,524384,524320,589984,524288,524416,524352,590048,459012,524376,524312,589968,459028,524408,524344,590032,459020,524392,524328,59e4,524296,524424,524360,590064,459010,524372,524308,524572,459026,524404,524340,590024,459018,524388,524324,589992,524292,524420,524356,590056,459014,524380,524316,589976,459030,524412,524348,590040,459022,524396,524332,590008,524300,524428,524364,590072,459009,524370,524306,524570,459025,524402,524338,590020,459017,524386,524322,589988,524290,524418,524354,590052,459013,524378,524314,589972,459029,524410,524346,590036,459021,524394,524330,590004,524298,524426,524362,590068,459011,524374,524310,524574,459027,524406,524342,590028,459019,524390,524326,589996,524294,524422,524358,590060,459015,524382,524318,589980,459031,524414,524350,590044,459023,524398,524334,590012,524302,524430,524366,590076,459008,524369,524305,524569,459024,524401,524337,590018,459016,524385,524321,589986,524289,524417,524353,590050,459012,524377,524313,589970,459028,524409,524345,590034,459020,524393,524329,590002,524297,524425,524361,590066,459010,524373,524309,524573,459026,524405,524341,590026,459018,524389,524325,589994,524293,524421,524357,590058,459014,524381,524317,589978,459030,524413,524349,590042,459022,524397,524333,590010,524301,524429,524365,590074,459009,524371,524307,524571,459025,524403,524339,590022,459017,524387,524323,589990,524291,524419,524355,590054,459013,524379,524315,589974,459029,524411,524347,590038,459021,524395,524331,590006,524299,524427,524363,590070,459011,524375,524311,524575,459027,524407,524343,590030,459019,524391,524327,589998,524295,524423,524359,590062,459015,524383,524319,589982,459031,524415,524351,590046,459023,524399,524335,590014,524303,524431,524367,590078,459008,524368,524304,524568,459024,524400,524336,590017,459016,524384,524320,589985,524288,524416,524352,590049,459012,524376,524312,589969,459028,524408,524344,590033,459020,524392,524328,590001,524296,524424,524360,590065,459010,524372,524308,524572,459026,524404,524340,590025,459018,524388,524324,589993,524292,524420,524356,590057,459014,524380,524316,589977,459030,524412,524348,590041,459022,524396,524332,590009,524300,524428,524364,590073,459009,524370,524306,524570,459025,524402,524338,590021,459017,524386,524322,589989,524290,524418,524354,590053,459013,524378,524314,589973,459029,524410,524346,590037,459021,524394,524330,590005,524298,524426,524362,590069,459011,524374,524310,524574,459027,524406,524342,590029,459019,524390,524326,589997,524294,524422,524358,590061,459015,524382,524318,589981,459031,524414,524350,590045,459023,524398,524334,590013,524302,524430,524366,590077,459008,524369,524305,524569,459024,524401,524337,590019,459016,524385,524321,589987,524289,524417,524353,590051,459012,524377,524313,589971,459028,524409,524345,590035,459020,524393,524329,590003,524297,524425,524361,590067,459010,524373,524309,524573,459026,524405,524341,590027,459018,524389,524325,589995,524293,524421,524357,590059,459014,524381,524317,589979,459030,524413,524349,590043,459022,524397,524333,590011,524301,524429,524365,590075,459009,524371,524307,524571,459025,524403,524339,590023,459017,524387,524323,589991,524291,524419,524355,590055,459013,524379,524315,589975,459029,524411,524347,590039,459021,524395,524331,590007,524299,524427,524363,590071,459011,524375,524311,524575,459027,524407,524343,590031,459019,524391,524327,589999,524295,524423,524359,590063,459015,524383,524319,589983,459031,524415,524351,590047,459023,524399,524335,590015,524303,524431,524367,590079]),9],fixedDistCodeTab=[new Int32Array([327680,327696,327688,327704,327684,327700,327692,327708,327682,327698,327690,327706,327686,327702,327694,0,327681,327697,327689,327705,327685,327701,327693,327709,327683,327699,327691,327707,327687,327703,327695,0]),5];class FlateStream extends DecodeStream{constructor(str,maybeLength){super(maybeLength),this.str=str,this.dict=str.dict;maybeLength=str.getByte(),str=str.getByte();if(-1===maybeLength||-1===str)throw new FormatError(`Invalid header in flate stream: ${maybeLength}, `+str);if(8!=(15&maybeLength))throw new FormatError(`Unknown compression method in flate stream: ${maybeLength}, `+str);if(((maybeLength<<8)+str)%31!=0)throw new FormatError(`Bad FCHECK in flate stream: ${maybeLength}, `+str);if(32&str)throw new FormatError(`FDICT bit set in flate stream: ${maybeLength}, `+str);this.codeSize=0,this.codeBuf=0}getBits(bits){var str=this.str;let codeSize=this.codeSize,codeBuf=this.codeBuf,b;for(;codeSize>bits,this.codeSize=codeSize-=bits,b}getCode(table){var b,str=this.str,codes=table[0],maxLen=table[1];let codeSize=this.codeSize,codeBuf=this.codeBuf;for(;codeSize>16,table&=65535;if(codes<1||codeSize>codes,this.codeSize=codeSize-codes,table}generateHuffmanTable(lengths){var n=lengths.length;let maxLen=0,i;for(i=0;imaxLen&&(maxLen=lengths[i]);var size=1<>=1;for(i=code2;i>=1))if(-1===(b=str.getByte()))this.#endsStreamOnError("Bad block header in flate stream");else{var blockLen=b;if(-1===(b=str.getByte()))this.#endsStreamOnError("Bad block header in flate stream");else if(blockLen|=b<<8,-1===(b=str.getByte()))this.#endsStreamOnError("Bad block header in flate stream");else{var check=b;if(-1===(b=str.getByte()))this.#endsStreamOnError("Bad block header in flate stream");else{if((check|=b<<8)!=(65535&~blockLen)&&(0!=blockLen||0!=check))throw new FormatError("Bad uncompressed block length in flate stream");this.codeBuf=0,this.codeSize=0;var b=this.bufferLength,check=b+blockLen;buffer=this.ensureBuffer(check),this.bufferLength=check,0==blockLen?-1===str.peekByte()&&(this.eof=!0):(check=str.getBytes(blockLen),buffer.set(check,b),check.length=limit&&(buffer=this.ensureBuffer(pos+1),limit=buffer.length),buffer[pos++]=code1;else{if(256===code1)return void(this.bufferLength=pos);code1-=257;let code2=(code1=lengthDecode[code1])>>16;0>16)?this.getBits(code2):code2);pos+len>=limit&&(buffer=this.ensureBuffer(pos+len),limit=buffer.length);for(let k=0;k>9&127,this.clow=this.clow<<7&65535,this.ct-=7,this.a=32768}byteIn(){var data=this.data;let bp=this.bp;255===data[bp]?143>16,this.clow&=65535)}readBit(contexts,pos){let cx_index=contexts[pos]>>1,cx_mps=1&contexts[pos];var qeTableIcx=QeTable[cx_index],qeIcx=qeTableIcx.qe;let d,a=this.a-qeIcx;if(this.chigh>15&1,this.clow=this.clow<<1&65535,this.ct--,0==(32768&a););return this.a=a,contexts[pos]=cx_index<<1|cx_mps,d}}class Jbig2Error extends BaseException{constructor(msg){super(msg,"Jbig2Error")}}class ContextCache{getContexts(id){return id in this?this[id]:this[id]=new Int8Array(65536)}}class DecodingContext{constructor(data,start,end){this.data=data,this.start=start,this.end=end}get decoder(){return shadow(this,"decoder",new ArithmeticDecoder(this.data,this.start,this.end))}get contextCache(){return shadow(this,"contextCache",new ContextCache)}}const MAX_INT_32=2**31-1,MIN_INT_32=-(2**31);function decodeInteger(contextCache,procedure,decoder){const contexts=contextCache.getContexts(procedure);let prev=1;function readBits(length){let v=0;for(let i=0;i>>0}contextCache=readBits(1),procedure=readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(1)?readBits(32)+4436:readBits(12)+340:readBits(8)+84:readBits(6)+20:readBits(4)+4:readBits(2);let signedValue;return 0===contextCache?signedValue=procedure:0=MIN_INT_32&&signedValue<=MAX_INT_32?signedValue:null}function decodeIAID(contextCache,decoder,codeLength){var contexts=contextCache.getContexts("IAID");let prev=1;for(let i=0;i=sbb_left&&j=sbb_top)for(contextLabel=contextLabel<<1&reuseMask,k=0;k=width?contextLabel<<=1:contextLabel=contextLabel<<1|bitmap[i0][j0];for(k=0;k=referenceHeight||j0<0||j0>=referenceWidth?contextLabel<<=1:contextLabel=contextLabel<<1|referenceBitmap[i0][j0];var pixel=decoder.readBit(contexts,contextLabel);row[j]=pixel}}return bitmap}function decodeSymbolDictionary(huffman,refinement,symbols,numberOfNewSymbols,numberOfExportedSymbols,huffmanTables,templateIndex,at,refinementTemplateIndex,refinementAt,decodingContext,huffmanInput){if(huffman&&refinement)throw new Jbig2Error("symbol refinement with Huffman is not supported");var newSymbols=[];let currentHeight=0,symbolCodeLength=log2(symbols.length+numberOfNewSymbols);var decoder=decodingContext.decoder,contextCache=decodingContext.contextCache;let tableB1,symbolWidths;for(huffman&&(tableB1=getStandardTable(1),symbolWidths=[],symbolCodeLength=Math.max(symbolCodeLength,1));newSymbols.length>1)+rdx,(applyRefinement>>1)+rdy,!1,refinementAt,decodingContext)),0);transposed?1&referenceCorner?increment=symbolHeight-1:currentS+=symbolHeight-1:1>8,y=gridOffsetY+mg*gridVectorX-ng*gridVectorY>>8,0<=x&&x+patternWidth<=regionWidth&&0<=y&&y+patternHeight<=regionHeight)for(i=0;i>5&7;var retainBits=[31&referredFlags];let position=start+6;if(7===referredFlags){referredToCount=536870911&readUint32(data,position-1),position+=3;let bytes=referredToCount+7>>3;for(retainBits[0]=data[position++];0<--bytes;)retainBits.push(data[position++])}else if(5===referredFlags||6===referredFlags)throw new Jbig2Error("invalid referred-to flags");segmentHeader.retainBits=retainBits;let referredToSegmentNumberSize=4;segmentHeader.number<=256?referredToSegmentNumberSize=1:segmentHeader.number<=65536&&(referredToSegmentNumberSize=2);var referredTo=[];let i,ii;for(i=0;i>>24&255,searchPattern[3]=start.height>>16&255,searchPattern[4]=start.height>>8&255,searchPattern[5]=255&start.height,i=position,ii=data.length;i>2&3,dictionary.huffmanDWSelector=dictionaryFlags>>4&3,dictionary.bitmapSizeSelector=dictionaryFlags>>6&1,dictionary.aggregationInstancesSelector=dictionaryFlags>>7&1,dictionary.bitmapCodingContextUsed=!!(256&dictionaryFlags),dictionary.bitmapCodingContextRetained=!!(512&dictionaryFlags),dictionary.template=dictionaryFlags>>10&3,dictionary.refinementTemplate=dictionaryFlags>>12&1,position+=2,!dictionary.huffman){for(atLength=0===dictionary.template?4:1,at=[],i=0;i>2&3,dictionaryFlags.stripSize=1<>4&3,dictionaryFlags.transposed=!!(64&dictionary),dictionaryFlags.combinationOperator=dictionary>>7&3,dictionaryFlags.defaultPixelValue=dictionary>>9&1,dictionaryFlags.dsOffset=dictionary<<17>>27,dictionaryFlags.refinementTemplate=dictionary>>15&1,dictionaryFlags.huffman&&(dictionary=readUint16(data,position),position+=2,dictionaryFlags.huffmanFS=3&dictionary,dictionaryFlags.huffmanDS=dictionary>>2&3,dictionaryFlags.huffmanDT=dictionary>>4&3,dictionaryFlags.huffmanRefinementDW=dictionary>>6&3,dictionaryFlags.huffmanRefinementDH=dictionary>>8&3,dictionaryFlags.huffmanRefinementDX=dictionary>>10&3,dictionaryFlags.huffmanRefinementDY=dictionary>>12&3,dictionaryFlags.huffmanRefinementSizeSelector=!!(16384&dictionary)),dictionaryFlags.refinement&&!dictionaryFlags.refinementTemplate){for(at=[],i=0;i<2;i++)at.push({x:readInt8(data,position),y:readInt8(data,position+1)}),position+=2;dictionaryFlags.refinementAt=at}dictionaryFlags.numberOfSymbolInstances=readUint32(data,position),position+=4,args=[dictionaryFlags,header.referredTo,data,position,end];break;case 16:dictionary={},dictionaryFlags=data[position++];dictionary.mmr=!!(1&dictionaryFlags),dictionary.template=dictionaryFlags>>1&3,dictionary.patternWidth=data[position++],dictionary.patternHeight=data[position++],dictionary.maxPatternIndex=readUint32(data,position),position+=4,args=[dictionary,header.number,data,position,end];break;case 22:case 23:dictionaryFlags={},dictionary=(dictionaryFlags.info=readRegionSegmentInformation(data,position),position+=RegionSegmentInformationFieldLength,data[position++]);dictionaryFlags.mmr=!!(1&dictionary),dictionaryFlags.template=dictionary>>1&3,dictionaryFlags.enableSkip=!!(8&dictionary),dictionaryFlags.combinationOperator=dictionary>>4&7,dictionaryFlags.defaultPixelValue=dictionary>>7&1,dictionaryFlags.gridWidth=readUint32(data,position),position+=4,dictionaryFlags.gridHeight=readUint32(data,position),position+=4,dictionaryFlags.gridOffsetX=4294967295&readUint32(data,position),position+=4,dictionaryFlags.gridOffsetY=4294967295&readUint32(data,position),position+=4,dictionaryFlags.gridVectorX=readUint16(data,position),position+=2,dictionaryFlags.gridVectorY=readUint16(data,position),position+=2,args=[dictionaryFlags,header.referredTo,data,position,end];break;case 38:case 39:dictionary={},dictionaryFlags=(dictionary.info=readRegionSegmentInformation(data,position),position+=RegionSegmentInformationFieldLength,data[position++]);if(dictionary.mmr=!!(1&dictionaryFlags),dictionary.template=dictionaryFlags>>1&3,dictionary.prediction=!!(8&dictionaryFlags),!dictionary.mmr){for(atLength=0===dictionary.template?4:1,at=[],i=0;i>2&1,dictionaryFlags.combinationOperator=dictionary>>3&3,dictionaryFlags.requiresBuffer=!!(32&dictionary),dictionaryFlags.combinationOperatorOverride=!!(64&dictionary),args=[dictionaryFlags];break;case 49:case 50:case 51:break;case 53:args=[header.number,data,position,end];break;case 62:break;default:throw new Jbig2Error(`segment type ${header.typeName}(${header.type}) is not implemented`)}segment="on"+header.typeName;segment in visitor&&visitor[segment].apply(visitor,args)}function processSegments(segments,visitor){for(let i=0,ii=segments.length;i>3,rowSize=new Uint8ClampedArray(rowSize*info.height);info.defaultPixelValue&&rowSize.fill(255),this.buffer=rowSize}drawBitmap(regionInfo,bitmap){var pageInfo=this.currentPageInfo,width=regionInfo.width,height=regionInfo.height,rowSize=pageInfo.width+7>>3,combinationOperator=(pageInfo.combinationOperatorOverride?regionInfo:pageInfo).combinationOperator,buffer=this.buffer,mask0=128>>(7®ionInfo.x);let offset0=regionInfo.y*rowSize+(regionInfo.x>>3),i,j,mask,offset;switch(combinationOperator){case 0:for(i=0;i>=1)||(mask=128,offset++);offset0+=rowSize}break;case 2:for(i=0;i>=1)||(mask=128,offset++);offset0+=rowSize}break;default:throw new Jbig2Error(`operator ${combinationOperator} is not supported`)}}onImmediateGenericRegion(region,data,start,end){var regionInfo=region.info,data=new DecodingContext(data,start,end),start=decodeBitmap(region.mmr,regionInfo.width,regionInfo.height,region.template,region.prediction,null,region.at,data);this.drawBitmap(regionInfo,start)}onImmediateLosslessGenericRegion(){this.onImmediateGenericRegion(...arguments)}onSymbolDictionary(dictionary,currentSegment,referredSegments,data,start,end){let huffmanTables,huffmanInput,symbols=(dictionary.huffman&&(huffmanTables=getSymbolDictionaryHuffmanTables(dictionary,referredSegments,this.customTables),huffmanInput=new Reader(data,start,end)),this.symbols);symbols||(this.symbols=symbols={});var inputSymbols=[];for(const referredSegment of referredSegments){var referredSymbols=symbols[referredSegment];referredSymbols&&inputSymbols.push(...referredSymbols)}referredSegments=new DecodingContext(data,start,end);symbols[currentSegment]=decodeSymbolDictionary(dictionary.huffman,dictionary.refinement,inputSymbols,dictionary.numberOfNewSymbols,dictionary.numberOfExportedSymbols,huffmanTables,dictionary.template,dictionary.at,dictionary.refinementTemplate,dictionary.refinementAt,referredSegments,huffmanInput)}onImmediateTextRegion(region,referredSegments,data,start,end){var regionInfo=region.info;let huffmanTables,huffmanInput;var symbols=this.symbols,inputSymbols=[];for(const referredSegment of referredSegments){var referredSymbols=symbols[referredSegment];referredSymbols&&inputSymbols.push(...referredSymbols)}var symbolCodeLength=log2(inputSymbols.length),referredSegments=(region.huffman&&(huffmanInput=new Reader(data,start,end),huffmanTables=getTextRegionHuffmanTables(region,referredSegments,this.customTables,inputSymbols.length,huffmanInput)),new DecodingContext(data,start,end)),data=decodeTextRegion(region.huffman,region.refinement,regionInfo.width,regionInfo.height,region.defaultPixelValue,region.numberOfSymbolInstances,region.stripSize,inputSymbols,symbolCodeLength,region.transposed,region.dsOffset,region.referenceCorner,region.combinationOperator,huffmanTables,region.refinementTemplate,region.refinementAt,referredSegments,region.logStripSize,huffmanInput);this.drawBitmap(regionInfo,data)}onImmediateLosslessTextRegion(){this.onImmediateTextRegion(...arguments)}onPatternDictionary(dictionary,currentSegment,data,start,end){let patterns=this.patterns;patterns||(this.patterns=patterns={});data=new DecodingContext(data,start,end);patterns[currentSegment]=decodePatternDictionary(dictionary.mmr,dictionary.patternWidth,dictionary.patternHeight,dictionary.maxPatternIndex,dictionary.template,data)}onImmediateHalftoneRegion(region,referredSegments,data,start,end){var referredSegments=this.patterns[referredSegments[0]],regionInfo=region.info,data=new DecodingContext(data,start,end),start=decodeHalftoneRegion(region.mmr,referredSegments,region.template,regionInfo.width,regionInfo.height,region.defaultPixelValue,region.enableSkip,region.combinationOperator,region.gridWidth,region.gridHeight,region.gridOffsetX,region.gridOffsetY,region.gridVectorX,region.gridVectorY,data);this.drawBitmap(regionInfo,start)}onImmediateLosslessHalftoneRegion(){this.onImmediateHalftoneRegion(...arguments)}onTables(currentSegment,data,start,end){let customTables=this.customTables;customTables||(this.customTables=customTables={}),customTables[currentSegment]=decodeTablesSegment(data,start,end)}}class HuffmanLine{constructor(lineData){2===lineData.length?(this.isOOB=!0,this.rangeLow=0,this.prefixLength=lineData[0],this.rangeLength=0,this.prefixCode=lineData[1],this.isLowerRange=!1):(this.isOOB=!1,this.rangeLow=lineData[0],this.prefixLength=lineData[1],this.rangeLength=lineData[2],this.prefixCode=lineData[3],this.isLowerRange="lower"===lineData[4])}}class HuffmanTreeNode{constructor(line){this.children=[],line?(this.isLeaf=!0,this.rangeLength=line.rangeLength,this.rangeLow=line.rangeLow,this.isLowerRange=line.isLowerRange,this.isOOB=line.isOOB):this.isLeaf=!1}buildTree(line,shift){var bit=line.prefixCode>>shift&1;if(shift<=0)this.children[bit]=new HuffmanTreeNode(line);else{let node=this.children[bit];node||(this.children[bit]=node=new HuffmanTreeNode(null)),node.buildTree(line,shift-1)}}decodeNode(reader){if(this.isLeaf)return this.isOOB?null:(htOffset=reader.readBits(this.rangeLength),this.rangeLow+(this.isLowerRange?-htOffset:htOffset));var htOffset=this.children[reader.readBit()];if(htOffset)return htOffset.decodeNode(reader);throw new Jbig2Error("invalid Huffman data")}}class HuffmanTable{constructor(lines,prefixCodesDone){prefixCodesDone||this.assignPrefixCodes(lines),this.rootNode=new HuffmanTreeNode(null);for(let i=0,ii=lines.length;i>1&7),rangeSizeBits=1+(flags>>4&7),lines=[];let prefixLength,rangeLength,currentRangeLow=lowestValue;for(;prefixLength=reader.readBits(prefixSizeBits),rangeLength=reader.readBits(rangeSizeBits),lines.push(new HuffmanLine([currentRangeLow,prefixLength,rangeLength,0])),(currentRangeLow+=1<=this.end)throw new Jbig2Error("end of data while reading bit");this.currentByte=this.data[this.position++],this.shift=7}var bit=this.currentByte>>this.shift&1;return this.shift--,bit}readBits(numBits){let result=0,i;for(i=numBits-1;0<=i;i--)result|=this.readBit()<=this.end?-1:this.data[this.position++]}}function getCustomHuffmanTable(index,referredTo,customTables){let currentIndex=0;for(let i=0,ii=referredTo.length;i>shift&1,shift--}if(endOfBlock&&!eof)for(let i=0;i<5&&-1!==decoder.readNextChar();i++);return bitmap}class Jbig2Image{parseChunks(chunks){return parseJbig2Chunks(chunks)}parse(data){throw new Error("Not implemented: Jbig2Image.parse")}}class Jbig2Stream extends DecodeStream{constructor(stream,maybeLength,params){super(maybeLength),this.stream=stream,this.dict=stream.dict,this.maybeLength=maybeLength,this.params=params}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(requested){}readBlock(){if(!this.eof){var globalsStream,jbig2Image=new Jbig2Image,chunks=[],data=(this.params instanceof Dict&&(globalsStream=this.params.get("JBIG2Globals"))instanceof BaseStream&&(globalsStream=globalsStream.getBytes(),chunks.push({data:globalsStream,start:0,end:globalsStream.length})),chunks.push({data:this.bytes,start:0,end:this.bytes.length}),jbig2Image.parseChunks(chunks)),dataLength=data.length;for(let i=0;i>3,widthRemainder=7&width,srcLength=src.length;dest=new Uint32Array(dest.buffer);let destPos=0;for(let i=0;i>2,src32=new Uint32Array(src.buffer,srcPos,len32);if(FeatureTest.isLittleEndian){for(;i>>24|s2<<8|4278190080,dest[destPos+2]=s2>>>16|s3<<16|4278190080,dest[destPos+3]=s3>>>8|4278190080}for(let j=4*i,jj=src.length;j>>8|255,dest[destPos+2]=s2<<16|s3>>>16|255,dest[destPos+3]=s3<<8|255}for(let j=4*i,jj=src.length;j>bitsCount&1;if(255===(bitsData=data[offset++])){var nextByte=data[offset++];if(nextByte){if(220===nextByte&&parseDNLMarker){var scanLines=readUint16(data,offset+=2);if(offset+=2,0>>7}function decodeHuffman(tree){let node=tree;for(;;){switch(typeof(node=node[readBit()])){case"number":return node;case"object":continue}throw new JpegError("invalid huffman sequence")}}function receive(length){let n=0;for(;0>4;if(0==s){if(rs<15){eobrun=receive(rs)+(1<>4,0==s)successiveACState=r<15?(eobrun=receive(r)+(1<>4;if(0==s){if(rs<15)break;k+=16}else{k+=rs;rs=dctZigZag[k];component.blockData[blockOffset+rs]=receiveAndExtend(s),k++}}},0),fileMarker;for(var h,v,mcuExpected=1===componentsLength?components[0].blocksPerLine*components[0].blocksPerColumn:mcusPerLine*frame.mcusPerColumn;mcu<=mcuExpected;){var mcuToRead=resetInterval?Math.min(mcuExpected-mcu,resetInterval):mcuExpected;if(0>10,p[row]=t,p[row+1]=t,p[row+2]=t,p[row+3]=t,p[row+4]=t,p[row+5]=t,p[row+6]=t,p[row+7]=t):(p1*=qt[row+1],p2*=qt[row+2],p3*=qt[row+3],p4*=qt[row+4],p5*=qt[row+5],p6*=qt[row+6],p7*=qt[row+7],v0=dctSqrt2*p0+128>>8,v1=dctSqrt2*p4+128>>8,v2=p2,v3=p6,v4=dctSqrt1d2*(p1-p7)+128>>8,v7=dctSqrt1d2*(p1+p7)+128>>8,v5=p3<<4,v6=p5<<4,v0=v0+v1+1>>1,v1=v0-v1,t=v2*dctSin6+v3*dctCos6+128>>8,v2=v2*dctCos6-v3*dctSin6+128>>8,v3=t,v4=v4+v6+1>>1,v6=v4-v6,v7=v7+v5+1>>1,v5=v7-v5,v0=v0+v3+1>>1,v3=v0-v3,v1=v1+v2+1>>1,v2=v1-v2,t=v4*dctSin3+v7*dctCos3+2048>>12,v4=v4*dctCos3-v7*dctSin3+2048>>12,v7=t,t=v5*dctSin1+v6*dctCos1+2048>>12,v5=v5*dctCos1-v6*dctSin1+2048>>12,v6=t,p[row]=v0+v7,p[row+7]=v0-v7,p[row+1]=v1+v6,p[row+6]=v1-v6,p[row+2]=v2+v5,p[row+5]=v2-v5,p[row+3]=v3+v4,p[row+4]=v3-v4);for(let col=0;col<8;++col)p0=p[col],p1=p[col+8],p2=p[col+16],p3=p[col+24],p4=p[col+32],p5=p[col+40],p6=p[col+48],p7=p[col+56],0==(p1|p2|p3|p4|p5|p6|p7)?(t=(t=dctSqrt2*p0+8192>>14)<-2040?0:2024<=t?255:t+2056>>4,blockData[blockBufferOffset+col]=t,blockData[blockBufferOffset+col+8]=t,blockData[blockBufferOffset+col+16]=t,blockData[blockBufferOffset+col+24]=t,blockData[blockBufferOffset+col+32]=t,blockData[blockBufferOffset+col+40]=t,blockData[blockBufferOffset+col+48]=t,blockData[blockBufferOffset+col+56]=t):(v0=dctSqrt2*p0+2048>>12,v1=dctSqrt2*p4+2048>>12,v2=p2,v3=p6,v4=dctSqrt1d2*(p1-p7)+2048>>12,v7=dctSqrt1d2*(p1+p7)+2048>>12,v5=p3,v6=p5,v0=4112+(v0+v1+1>>1),v1=v0-v1,t=v2*dctSin6+v3*dctCos6+2048>>12,v2=v2*dctCos6-v3*dctSin6+2048>>12,v3=t,v4=v4+v6+1>>1,v6=v4-v6,v7=v7+v5+1>>1,v5=v7-v5,v0=v0+v3+1>>1,v3=v0-v3,v1=v1+v2+1>>1,v2=v1-v2,t=v4*dctSin3+v7*dctCos3+2048>>12,v4=v4*dctCos3-v7*dctSin3+2048>>12,v7=t,t=v5*dctSin1+v6*dctCos1+2048>>12,v5=v5*dctCos1-v6*dctSin1+2048>>12,v6=t,p0=v0+v7,p7=v0-v7,p1=v1+v6,p6=v1-v6,p2=v2+v5,p5=v2-v5,p3=v3+v4,p4=v3-v4,p0<16?p0=0:4080<=p0?p0=255:p0>>=4,p1<16?p1=0:4080<=p1?p1=255:p1>>=4,p2<16?p2=0:4080<=p2?p2=255:p2>>=4,p3<16?p3=0:4080<=p3?p3=255:p3>>=4,p4<16?p4=0:4080<=p4?p4=255:p4>>=4,p5<16?p5=0:4080<=p5?p5=255:p5>>=4,p6<16?p6=0:4080<=p6?p6=255:p6>>=4,p7<16?p7=0:4080<=p7?p7=255:p7>>=4,blockData[blockBufferOffset+col]=p0,blockData[blockBufferOffset+col+8]=p1,blockData[blockBufferOffset+col+16]=p2,blockData[blockBufferOffset+col+24]=p3,blockData[blockBufferOffset+col+32]=p4,blockData[blockBufferOffset+col+40]=p5,blockData[blockBufferOffset+col+48]=p6,blockData[blockBufferOffset+col+56]=p7)}function buildComponentData(frame,component){var blocksPerLine=component.blocksPerLine,blocksPerColumn=component.blocksPerColumn,computationBuffer=new Int16Array(64);for(let blockRow=0;blockRow=maxPos)return null;newMarker=readUint16(data,newPos)}return{invalid:startPos.toString(16),marker:newMarker,offset:newPos}}class JpegImage{constructor({decodeTransform=null,colorTransform=-1}={}){this._decodeTransform=decodeTransform,this._colorTransform=colorTransform}parse(data,{dnlScanLines=null}={}){let offset=0,jfif=null,adobe=null,frame,resetInterval,numSOSMarkers=0;var quantizationTables=[],huffmanTablesAC=[],huffmanTablesDC=[];let fileMarker=readUint16(data,offset);if(offset+=2,65496!==fileMarker)throw new JpegError("SOI not found");fileMarker=readUint16(data,offset),offset+=2;markerLoop:for(;65497!==fileMarker;){let i,j,l;switch(fileMarker){case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var appData=function(){var length=readUint16(data,offset);let endOffset=(offset+=2)+length-2;return(length=findNextFileMarker(data,endOffset,offset))?.invalid&&(warn("readDataBlock - incorrect length, current marker is: "+length.invalid),endOffset=length.offset),length=data.subarray(offset,endOffset),offset+=length.length,length}();65504===fileMarker&&74===appData[0]&&70===appData[1]&&73===appData[2]&&70===appData[3]&&0===appData[4]&&(jfif={version:{major:appData[5],minor:appData[6]},densityUnits:appData[7],xDensity:appData[8]<<8|appData[9],yDensity:appData[10]<<8|appData[11],thumbWidth:appData[12],thumbHeight:appData[13],thumbData:appData.subarray(14,14+3*appData[12]*appData[13])}),65518===fileMarker&&65===appData[0]&&100===appData[1]&&111===appData[2]&&98===appData[3]&&101===appData[4]&&(adobe={version:appData[5]<<8|appData[6],flags0:appData[7]<<8|appData[8],flags1:appData[9]<<8|appData[10],transformCode:appData[11]});break;case 65499:var quantizationTablesEnd=readUint16(data,offset)+(offset+=2)-2;let z;for(;offset>4==0)for(j=0;j<64;j++)tableData[z=dctZigZag[j]]=data[offset++];else{if(quantizationTableSpec>>4!=1)throw new JpegError("DQT - invalid table spec");for(j=0;j<64;j++)tableData[z=dctZigZag[j]]=readUint16(data,offset),offset+=2}quantizationTables[15&quantizationTableSpec]=tableData}break;case 65472:case 65473:case 65474:if(frame)throw new JpegError("Only single frame JPEGs supported");offset+=2,(frame={}).extended=65473===fileMarker,frame.progressive=65474===fileMarker,frame.precision=data[offset++];var appData=readUint16(data,offset),componentsCount=(offset+=2,frame.scanLines=dnlScanLines||appData,frame.samplesPerLine=readUint16(data,offset),offset+=2,frame.components=[],frame.componentIds={},data[offset++]);let maxH=0,maxV=0;for(i=0;i>4,v=15&data[offset+1],qId=(maxH>4==0?huffmanTablesDC:huffmanTablesAC)[15&huffmanTableSpec]=buildHuffmanTable(codeLengths,huffmanValues)}break;case 65501:offset+=2,resetInterval=readUint16(data,offset),offset+=2;break;case 65498:var parseDNLMarker=1==++numSOSMarkers&&!dnlScanLines,selectorsCount=(offset+=2,data[offset++]),components=[];for(i=0;i>4],componentIndex.huffmanTableAC=huffmanTablesAC[15&index],components.push(componentIndex)}var spectralStart=data[offset++],spectralEnd=data[offset++],successiveApproximation=data[offset++];try{var processed=decodeScan(data,offset,frame,components,resetInterval,spectralStart,spectralEnd,successiveApproximation>>4,15&successiveApproximation,parseDNLMarker);offset+=processed}catch(ex){if(ex instanceof DNLMarkerError)return warn(ex.message+" -- attempting to re-parse the JPEG image."),this.parse(data,{dnlScanLines:ex.scanLines});if(ex instanceof EOIMarkerError){warn(ex.message+" -- ignoring the rest of the image data.");break markerLoop}throw ex}break;case 65500:offset+=4;break;case 65535:255!==data[offset]&&offset--;break;default:spectralStart=findNextFileMarker(data,offset-2,offset-3);if(spectralStart?.invalid){warn("JpegImage.parse - unexpected data, current marker is: "+spectralStart.invalid),offset=spectralStart.offset;break}if(!spectralStart||offset>=data.length-1){warn("JpegImage.parse - reached the end of the image data without finding an EOI marker (0xFFD9).");break markerLoop}throw new JpegError("JpegImage.parse - unknown marker: "+fileMarker.toString(16))}fileMarker=readUint16(data,offset),offset+=2}if(!frame)throw new JpegError("JpegImage.parse - no frame data found.");this.width=frame.samplesPerLine,this.height=frame.scanLines,this.jfif=jfif,this.adobe=adobe,this.components=[];for(const component of frame.components){var quantizationTable=quantizationTables[component.quantizationId];quantizationTable&&(component.quantizationTable=quantizationTable),this.components.push({index:component.index,output:buildComponentData(frame,component),scaleX:component.h/frame.maxH,scaleY:component.v/frame.maxV,blocksPerLine:component.blocksPerLine,blocksPerColumn:component.blocksPerColumn})}this.numComponents=this.components.length}_getLinearizedBlockData(width,height,isSourcePDF=!1){var component,componentScaleX,componentScaleY,blocksPerScanline,index,output,scaleX=this.width/width,scaleY=this.height/height;let x,y,i,j,k,offset=0;var numComponents=this.components.length,dataLength=width*height*numComponents,data=new Uint8ClampedArray(dataLength),xScaleBlockOffset=new Uint32Array(width);let lastComponentScaleX;for(i=0;i>8)+transform[k+1];return data}get _isColorConversionNeeded(){return this.adobe?!!this.adobe.transformCode:3===this.numComponents?0!==this._colorTransform&&(82!==this.components[0].index||71!==this.components[1].index||66!==this.components[2].index):1===this._colorTransform}_convertYccToRgb(data){var Y,Cb,Cr;for(let i=0,length=data.length;i{var _scriptDir="file:///home/timvandermeij/Documenten/Ontwikkeling/pdf.js/Code/external/openjpeg/openjpeg.js";return function(moduleArg={}){var readyPromiseResolve,readyPromiseReject,readBinary,wasmBinary,wasmMemory,Module=moduleArg,moduleOverrides=(new Promise((resolve,reject)=>{readyPromiseResolve=resolve,readyPromiseReject=reject}),Module.decode=function(bytes,ignoreColorSpace){var size=bytes.length,ptr=Module._malloc(size),bytes=(Module.HEAPU8.set(bytes,ptr),Module._jp2_decode(ptr,size,ignoreColorSpace?1:0));return Module._free(ptr),bytes?(size=Module["errorMessages"],size?(delete Module.errorMessages,size):"Unknown error"):(ignoreColorSpace=Module["imageData"],Module.imageData=null,ignoreColorSpace)},Object.assign({},Module)),thisProgram="./this.program",scriptDirectory="",out=("undefined"!=typeof document&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory=(scriptDirectory=_scriptDir).startsWith("blob:")?"":scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),Module.print||console.log.bind(console)),err=Module.printErr||console.error.bind(console);function tryParseAsDataURI(filename){if((filename=>filename.startsWith(dataURIPrefix))(filename)){for(var filename=filename.slice(dataURIPrefix.length),decoded=atob(filename),bytes=new Uint8Array(decoded.length),i=0;i{for(;0thisProgram||"./this.program",getEnvStrings=()=>{if(!getEnvStrings.strings){var env={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:("object"==typeof navigator&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",_:getExecutableName()};for(x in ENV)void 0===ENV[x]?delete env[x]:env[x]=ENV[x];var x,strings=[];for(x in env)strings.push(x+"="+env[x]);getEnvStrings.strings=strings}return getEnvStrings.strings},printCharBuffers=[null,[],[]],UTF8Decoder="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0,UTF8ArrayToString=(heapOrArray,idx,maxBytesToRead)=>{for(var endIdx=idx+maxBytesToRead,endPtr=idx;heapOrArray[endPtr]&&!(endIdx<=endPtr);)++endPtr;if(16>10,56320|1023&u1)))):str+=String.fromCharCode(u0)}return str},UTF8ToString=(ptr,maxBytesToRead)=>ptr?UTF8ArrayToString(HEAPU8,ptr,maxBytesToRead):"";var calledRun,wasmImports={f:(dest,src,num)=>HEAPU8.copyWithin(dest,src,src+num),b:requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;if(!(2147483648{size=(size-wasmMemory.buffer.byteLength+65535)/65536;try{return wasmMemory.grow(size),updateMemoryViews(),1}catch(e){}})(Math.min(2147483648,(overGrownHeapSize=Math.max(requestedSize,overGrownHeapSize))+((multiple=65536)-overGrownHeapSize%multiple)%multiple)))return!0}return!1},c:(__environ,environ_buf)=>{var bufSize=0;return getEnvStrings().forEach((string,i)=>{var ptr=environ_buf+bufSize;((str,buffer)=>{for(var i=0;i>2]=ptr),bufSize+=string.length+1}),0},d:(penviron_count,penviron_buf_size)=>{var strings=getEnvStrings(),bufSize=(HEAPU32[penviron_count>>2]=strings.length,0);return strings.forEach(string=>bufSize+=string.length+1),HEAPU32[penviron_buf_size>>2]=bufSize,0},e:(fd,iov,iovcnt,pnum)=>{for(var stream,curr,buffer,num=0,i=0;i>2],len=HEAPU32[iov+4>>2];iov+=8;for(var j=0;j>2]=num,0},g:function(message_ptr){message_ptr=UTF8ToString(message_ptr),(Module.warn||console.warn)("OpenJPEG: "+message_ptr)},h:function(array_ptr,array_size){Module.imageData=new Uint8ClampedArray(Module.HEAPU8.subarray(array_ptr,array_ptr+array_size))},a:function(message_ptr){message_ptr=UTF8ToString(message_ptr),Module.errorMessages?Module.errorMessages+="\n"+message_ptr:Module.errorMessages=message_ptr}},wasmExports=function(){var info={a:wasmImports};function receiveInstance(instance,module){return wasmExports=instance.exports,wasmMemory=wasmExports.i,updateMemoryViews(),instance=wasmExports.j,__ATINIT__.unshift(instance),runDependencies--,Module.monitorRunDependencies?.(runDependencies),0==runDependencies&&(null!==runDependencyWatcher&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)&&(instance=dependenciesFulfilled,dependenciesFulfilled=null,instance()),wasmExports}if(runDependencies++,Module.monitorRunDependencies?.(runDependencies),Module.instantiateWasm)try{return Module.instantiateWasm(info,receiveInstance)}catch(e){err("Module.instantiateWasm callback failed with error: "+e),readyPromiseReject(e)}return receiveInstance(instantiateSync(wasmBinaryFile,info)[0])}();wasmExports.j,Module._malloc=wasmExports.k,Module._free=wasmExports.l,Module._jp2_decode=wasmExports.n,wasmExports._emscripten_stack_restore,wasmExports._emscripten_stack_alloc,wasmExports.emscripten_stack_get_current;function run(){function doRun(){calledRun||(calledRun=!0,Module.calledRun=!0,ABORT)||(callRuntimeCallbacks(__ATINIT__),readyPromiseResolve(Module),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),postRun())}0>>0,Ysiz=stream.getInt32()>>>0,XOsiz=stream.getInt32()>>>0,YOsiz=stream.getInt32()>>>0,stream.skip(16),{width:Xsiz-XOsiz,height:Ysiz-YOsiz,bitsPerComponent:8,componentsCount:stream.getUint16()}}throw new JpxError("No size marker found in JPX stream")}}class JpxStream extends DecodeStream{constructor(stream,maybeLength,params){super(maybeLength),this.stream=stream,this.dict=stream.dict,this.maybeLength=maybeLength,this.params=params}get bytes(){return shadow(this,"bytes",this.stream.getBytes(this.maybeLength))}ensureBuffer(requested){}readBlock(ignoreColorSpace){this.eof||(this.buffer=JpxImage.decode(this.bytes,ignoreColorSpace),this.bufferLength=this.buffer.length,this.eof=!0)}}class LZWStream extends DecodeStream{constructor(str,maybeLength,earlyChange){super(maybeLength),this.str=str,this.dict=str.dict,this.cachedData=0,this.bitsCached=0;var lzwState={earlyChange:earlyChange,codeLength:9,nextCode:258,dictionaryValues:new Uint8Array(4096),dictionaryLengths:new Uint16Array(4096),dictionaryPrevCodes:new Uint16Array(4096),currentSequence:new Uint8Array(4096),currentSequenceLength:0};for(let i=0;i<256;++i)lzwState.dictionaryValues[i]=i,lzwState.dictionaryLengths[i]=1;this.lzwState=lzwState}readBits(n){let bitsCached=this.bitsCached,cachedData=this.cachedData;for(;bitsCached>>bitsCached&(1<>3,this.rowBytes=params*maybeLength*str+7>>3,this}readBlockTiff(){var rowBytes=this.rowBytes,bufferLength=this.bufferLength,buffer=this.ensureBuffer(bufferLength+rowBytes),bits=this.bits,colors=this.colors,rawBytes=this.str.getBytes(rowBytes);if(this.eof=!rawBytes.length,!this.eof){let inbuf=0,outbuf=0,inbits=0,outbits=0,pos=bufferLength,i;if(1===bits&&1===colors)for(i=0;i>1)^c>>2)^c>>4;inbuf=(1&c)<<7,buffer[pos++]=c}else if(8===bits){for(i=0;i>8&255,buffer[pos++]=255&sum}}else{var compArray=new Uint8Array(colors+1),bitMask=(1<>inbits-bits)&bitMask,inbits-=bits,outbuf=outbuf<>outbits-8&255,outbits-=8);0>1)+rawBytes[i];for(;i>1)+rawBytes[i]&255,j++;break;case 4:for(i=0;i>")&&this.buf1!==EOF;)if(this.buf1 instanceof Name){var key=this.buf1.name;if(this.shift(),this.buf1===EOF)break;dict.set(key,this.getObj(cipherTransform))}else info("Malformed dictionary: key must be a name object"),this.shift();if(this.buf1!==EOF)return isCmd(this.buf2,"stream")?this.allowStreams?this.makeStream(dict,cipherTransform):dict:(this.shift(),dict);if(this.recoveryMode)return dict;throw new ParserEOFException("End of file inside dictionary.");default:return buf1}return Number.isInteger(buf1)?Number.isInteger(this.buf1)&&isCmd(this.buf2,"R")?(ref=Ref.get(buf1,this.buf1),this.shift(),this.shift(),ref):buf1:"string"==typeof buf1&&cipherTransform?cipherTransform.decryptString(buf1):buf1}findDefaultInlineStreamEnd(stream){var knownCommands=this.lexer["knownCommands"],startPos=stream.pos;let state=0,ch,maybeEIPos;for(;-1!==(ch=stream.getByte());)if(0===state)state=69===ch?1:0;else if(1===state)state=73===ch?2:0;else if(32===ch||10===ch||13===ch){maybeEIPos=stream.pos;var followingBytes=stream.peekBytes(15),ii=followingBytes.length;if(0===ii)break;for(let i=0;i{};let numArgs=0;for(;;){var nextObj=tmpLexer.getObj();if(nextObj===EOF){state=0;break}if(nextObj instanceof Cmd){nextObj=knownCommands[nextObj.cmd];if(!nextObj){state=0;break}if(nextObj.variableArgs?numArgs<=nextObj.numArgs:numArgs===nextObj.numArgs)break;numArgs=0}else numArgs++}if(2===state)break}else warn("findDefaultInlineStreamEnd - `lexer.knownCommands` is undefined.")}else state=0;-1===ch&&(warn("findDefaultInlineStreamEnd: Reached the end of the stream without finding a valid EI marker"),maybeEIPos)&&(warn('... trying to recover by using the last "EI" occurrence.'),stream.skip(-(stream.pos-maybeEIPos)));let endOffset=4;return stream.skip(-endOffset),ch=stream.peekByte(),stream.skip(endOffset),isWhiteSpace(ch)||endOffset--,stream.pos-endOffset-startPos}findDCTDecodeInlineStreamEnd(stream){var startPos=stream.pos;let foundEOI=!1,b,markerLength;for(;-1!==(b=stream.getByte());)if(255===b){switch(stream.getByte()){case 0:break;case 255:stream.skip(-1);break;case 217:foundEOI=!0;break;case 192:case 193:case 194:case 195:case 197:case 198:case 199:case 201:case 202:case 203:case 205:case 206:case 207:case 196:case 204:case 218:case 219:case 220:case 221:case 222:case 223:case 224:case 225:case 226:case 227:case 228:case 229:case 230:case 231:case 232:case 233:case 234:case 235:case 236:case 237:case 238:case 239:case 254:2<(markerLength=stream.getUint16())?stream.skip(markerLength-2):stream.skip(-2)}if(foundEOI)break}startPos=stream.pos-startPos;return-1===b?(warn("Inline DCTDecode image stream: EOI marker not found, searching for /EI/ instead."),stream.skip(-startPos),this.findDefaultInlineStreamEnd(stream)):(this.inlineStreamSkipEI(stream),startPos)}findASCII85DecodeInlineStreamEnd(stream){var startPos=stream.pos;let ch;for(;-1!==(ch=stream.getByte());)if(126===ch){var tildePos=stream.pos;for(ch=stream.peekByte();isWhiteSpace(ch);)stream.skip(),ch=stream.peekByte();if(62===ch){stream.skip();break}if(stream.pos>tildePos){tildePos=stream.peekBytes(2);if(69===tildePos[0]&&73===tildePos[1])break}}startPos=stream.pos-startPos;return-1===ch?(warn("Inline ASCII85Decode image stream: EOD marker not found, searching for /EI/ instead."),stream.skip(-startPos),this.findDefaultInlineStreamEnd(stream)):(this.inlineStreamSkipEI(stream),startPos)}findASCIIHexDecodeInlineStreamEnd(stream){var startPos=stream.pos;let ch;for(;-1!==(ch=stream.getByte())&&62!==ch;);startPos=stream.pos-startPos;return-1===ch?(warn("Inline ASCIIHexDecode image stream: EOD marker not found, searching for /EI/ instead."),stream.skip(-startPos),this.findDefaultInlineStreamEnd(stream)):(this.inlineStreamSkipEI(stream),startPos)}inlineStreamSkipEI(stream){let state=0,ch;for(;-1!==(ch=stream.getByte());)if(0===state)state=69===ch?1:0;else if(1===state)state=73===ch?2:0;else if(2===state)break}makeInlineImage(cipherTransform){var lexer=this.lexer,stream=lexer.stream,dictMap=Object.create(null);let dictLength;for(;!isCmd(this.buf1,"ID")&&this.buf1!==EOF;){if(!(this.buf1 instanceof Name))throw new FormatError("Dictionary key must be a name object");var key=this.buf1.name;if(this.shift(),this.buf1===EOF)break;dictMap[key]=this.getObj(cipherTransform)}-1!==lexer.beginInlineImagePos&&(dictLength=stream.pos-lexer.beginInlineImagePos);var filter=this.xref.fetchIfRef(dictMap.F||dictMap.Filter);let filterName;filter instanceof Name?filterName=filter.name:Array.isArray(filter)&&(filter=this.xref.fetchIfRef(filter[0]))instanceof Name&&(filterName=filter.name);filter=stream.pos;let length;switch(filterName){case"DCT":case"DCTDecode":length=this.findDCTDecodeInlineStreamEnd(stream);break;case"A85":case"ASCII85Decode":length=this.findASCII85DecodeInlineStreamEnd(stream);break;case"AHx":case"ASCIIHexDecode":length=this.findASCIIHexDecodeInlineStreamEnd(stream);break;default:length=this.findDefaultInlineStreamEnd(stream)}let cacheKey;if(length=signatureLength)return stream.pos+=pos,stream.pos-startPos;pos++}stream.pos+=scanLength}return-1}makeStream(dict,cipherTransform){var lexer=this.lexer;let stream=lexer.stream;lexer.skipToNextLine();var startPos=stream.pos-1;let length=dict.get("Length");if(Number.isInteger(length)||(info(`Bad length "${length&&length.toString()}" in stream.`),length=0),stream.pos=startPos+length,lexer.nextChar(),!this.tryShift()||!isCmd(this.buf2,"endstream")){var ENDSTREAM_SIGNATURE=new Uint8Array([101,110,100,115,116,114,101,97,109]);let actualLength=this._findStreamLength(startPos,ENDSTREAM_SIGNATURE);if(actualLength<0){for(let i=1;i<=1;i++){var end=ENDSTREAM_SIGNATURE.length-i,TRUNCATED_SIGNATURE=ENDSTREAM_SIGNATURE.slice(0,end),maybeLength=this._findStreamLength(startPos,TRUNCATED_SIGNATURE);if(0<=maybeLength){if(!isWhiteSpace(stream.peekBytes(1+end)[end]))break;info(`Found "${bytesToString(TRUNCATED_SIGNATURE)}" when `+"searching for endstream command."),actualLength=maybeLength;break}}if(actualLength<0)throw new FormatError("Missing endstream command.")}length=actualLength,lexer.nextChar(),this.shift()}return this.shift(),this.shift(),stream=stream.makeSubStream(startPos,length,dict),cipherTransform&&(stream=cipherTransform.createStream(stream,length)),(stream=this.filter(stream,dict,length)).dict=dict,stream}filter(stream,dict,length){let filter=dict.get("F","Filter"),params=dict.get("DP","DecodeParms");if(filter instanceof Name)return Array.isArray(params)&&warn("/DecodeParms should not be an Array, when /Filter is a Name."),this.makeFilter(stream,filter.name,length,params);let maybeLength=length;if(Array.isArray(filter)){var filterArray=filter,paramsArray=params;for(let i=0,ii=filterArray.length;i>")):Cmd.get(">");case 123:return this.nextChar(),Cmd.get("{");case 125:return this.nextChar(),Cmd.get("}");case 41:throw this.nextChar(),new FormatError("Illegal character: "+ch)}let str=String.fromCharCode(ch);if(ch<32||127MAX_MAP_RANGE)throw new Error("mapCidRange - ignoring data above MAX_MAP_RANGE.");for(;low<=high;)this._map[low++]=dstLow++}mapBfRange(low,high,dstLow){if(high-low>MAX_MAP_RANGE)throw new Error("mapBfRange - ignoring data above MAX_MAP_RANGE.");for(var lastByte=dstLow.length-1;low<=high;){var nextCharCode=(this._map[low++]=dstLow).charCodeAt(lastByte)+1;255MAX_MAP_RANGE)throw new Error("mapBfRangeToArray - ignoring data above MAX_MAP_RANGE.");var ii=array.length;let i=0;for(;low<=high&&i>>0;var codespaceRange=codespaceRanges[n];for(let k=0,kk=codespaceRange.length;k=low&&c<=high)return out.charcode=c,void(out.length=n+1)}}out.charcode=0,out.length=1}getCharCodeLength(charCode){var codespaceRanges=this.codespaceRanges;for(let n=0,nn=codespaceRanges.length;n>>0}function expectString(obj){if("string"!=typeof obj)throw new FormatError("Malformed CMap: expected string.")}function expectInt(obj){if(!Number.isInteger(obj))throw new FormatError("Malformed CMap: expected int.")}function parseBfChar(cMap,lexer){for(;;){var obj=lexer.getObj();if(obj===EOF)break;if(isCmd(obj,"endbfchar"))return;expectString(obj);var src=strToInt(obj);expectString(obj=lexer.getObj()),cMap.mapOne(src,obj)}}function parseBfRange(cMap,lexer){for(;;){let obj=lexer.getObj();if(obj===EOF)break;if(isCmd(obj,"endbfrange"))return;expectString(obj);var low=strToInt(obj),high=(expectString(obj=lexer.getObj()),strToInt(obj));if(obj=lexer.getObj(),Number.isInteger(obj)||"string"==typeof obj){var dstLow=Number.isInteger(obj)?String.fromCharCode(obj):obj;cMap.mapBfRange(low,high,dstLow)}else{if(!isCmd(obj,"["))break;obj=lexer.getObj();for(var array=[];!isCmd(obj,"]")&&obj!==EOF;)array.push(obj),obj=lexer.getObj();cMap.mapBfRangeToArray(low,high,array)}}throw new FormatError("Invalid bf range.")}function parseCidChar(cMap,lexer){for(;;){var obj=lexer.getObj();if(obj===EOF)break;if(isCmd(obj,"endcidchar"))return;expectString(obj);var src=strToInt(obj);expectInt(obj=lexer.getObj()),cMap.mapOne(src,obj)}}function parseCidRange(cMap,lexer){for(;;){var obj=lexer.getObj();if(obj===EOF)break;if(isCmd(obj,"endcidrange"))return;expectString(obj);var low=strToInt(obj),high=(expectString(obj=lexer.getObj()),strToInt(obj));expectInt(obj=lexer.getObj());cMap.mapCidRange(low,high,obj)}}function parseCodespaceRange(cMap,lexer){for(;;){var obj=lexer.getObj();if(obj===EOF)break;if(isCmd(obj,"endcodespacerange"))return;if("string"!=typeof obj)break;var low=strToInt(obj);if("string"!=typeof(obj=lexer.getObj()))break;var high=strToInt(obj);cMap.addCodespaceRange(obj.length,low,high)}throw new FormatError("Invalid codespace range.")}function parseWMode(cMap,lexer){lexer=lexer.getObj();Number.isInteger(lexer)&&(cMap.vertical=!!lexer)}function parseCMapName(cMap,lexer){lexer=lexer.getObj();lexer instanceof Name&&(cMap.name=lexer.name)}async function parseCMap(cMap,lexer,fetchBuiltInCMap,useCMap){let previous,embeddedUseCMap;objLoop:for(;;)try{var obj=lexer.getObj();if(obj===EOF)break;if(obj instanceof Name)"WMode"===obj.name?parseWMode(cMap,lexer):"CMapName"===obj.name&&parseCMapName(cMap,lexer),previous=obj;else if(obj instanceof Cmd)switch(obj.cmd){case"endcmap":break objLoop;case"usecmap":previous instanceof Name&&(embeddedUseCMap=previous.name);break;case"begincodespacerange":parseCodespaceRange(cMap,lexer);break;case"beginbfchar":parseBfChar(cMap,lexer);break;case"begincidchar":parseCidChar(cMap,lexer);break;case"beginbfrange":parseBfRange(cMap,lexer);break;case"begincidrange":parseCidRange(cMap,lexer)}}catch(ex){if(ex instanceof MissingDataException)throw ex;warn("Invalid cMap data: "+ex);continue}return(useCMap=!useCMap&&embeddedUseCMap?embeddedUseCMap:useCMap)?extendCMap(cMap,fetchBuiltInCMap,useCMap):cMap}async function extendCMap(cMap,fetchBuiltInCMap,useCMap){if(cMap.useCMap=await createBuiltInCMap(useCMap,fetchBuiltInCMap),0===cMap.numCodespaceRanges){var useCodespaceRanges=cMap.useCMap.codespaceRanges;for(let i=0;iextendCMap(cMap,fetchBuiltInCMap,useCMap));if(compressionType===CMapCompressionType.NONE)return name=new Lexer(new Stream(name)),parseCMap(cMap,name,fetchBuiltInCMap,null);throw new Error('Invalid CMap "compressionType" value: '+compressionType)}class CMapFactory{static async create({encoding,fetchBuiltInCMap,useCMap}){if(encoding instanceof Name)return createBuiltInCMap(encoding.name,fetchBuiltInCMap);if(encoding instanceof BaseStream)return(encoding=await parseCMap(new CMap,new Lexer(encoding),fetchBuiltInCMap,useCMap)).isIdentityCMap?createBuiltInCMap(encoding.name,fetchBuiltInCMap):encoding;throw new Error("Encoding required.")}}const ISOAdobeCharset=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron"],ExpertCharset=[".notdef","space","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],ExpertSubsetCharset=[".notdef","space","dollaroldstyle","dollarsuperior","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","fi","fl","ffi","ffl","parenleftinferior","parenrightinferior","hyphensuperior","colonmonetary","onefitted","rupiah","centoldstyle","figuredash","hypheninferior","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior"],ExpertEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","commasuperior","threequartersemdash","periodsuperior","questionsmall","","asuperior","bsuperior","centsuperior","dsuperior","esuperior","","","","isuperior","","","lsuperior","msuperior","nsuperior","osuperior","","","rsuperior","ssuperior","tsuperior","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdownsmall","centoldstyle","Lslashsmall","","","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","","Dotaccentsmall","","","Macronsmall","","","figuredash","hypheninferior","","","Ogoneksmall","Ringsmall","Cedillasmall","","","","onequarter","onehalf","threequarters","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","zerosuperior","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall"],MacExpertEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclamsmall","Hungarumlautsmall","centoldstyle","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","comma","hyphen","period","fraction","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","colon","semicolon","","threequartersemdash","","questionsmall","","","","","Ethsmall","","","onequarter","onehalf","threequarters","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","","","","","","","ff","fi","fl","ffi","ffl","parenleftinferior","","parenrightinferior","Circumflexsmall","hypheninferior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","","","asuperior","centsuperior","","","","","Aacutesmall","Agravesmall","Acircumflexsmall","Adieresissmall","Atildesmall","Aringsmall","Ccedillasmall","Eacutesmall","Egravesmall","Ecircumflexsmall","Edieresissmall","Iacutesmall","Igravesmall","Icircumflexsmall","Idieresissmall","Ntildesmall","Oacutesmall","Ogravesmall","Ocircumflexsmall","Odieresissmall","Otildesmall","Uacutesmall","Ugravesmall","Ucircumflexsmall","Udieresissmall","","eightsuperior","fourinferior","threeinferior","sixinferior","eightinferior","seveninferior","Scaronsmall","","centinferior","twoinferior","","Dieresissmall","","Caronsmall","osuperior","fiveinferior","","commainferior","periodinferior","Yacutesmall","","dollarinferior","","","Thornsmall","","nineinferior","zeroinferior","Zcaronsmall","AEsmall","Oslashsmall","questiondownsmall","oneinferior","Lslashsmall","","","","","","","Cedillasmall","","","","","","OEsmall","figuredash","hyphensuperior","","","","","exclamdownsmall","","Ydieresissmall","","onesuperior","twosuperior","threesuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","ninesuperior","zerosuperior","","esuperior","rsuperior","tsuperior","","","isuperior","ssuperior","dsuperior","","","","","","lsuperior","Ogoneksmall","Brevesmall","Macronsmall","bsuperior","nsuperior","msuperior","commasuperior","periodsuperior","Dotaccentsmall","Ringsmall","","","",""],MacRomanEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","space","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron"],StandardEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","","endash","dagger","daggerdbl","periodcentered","","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","","questiondown","","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","","ring","cedilla","","hungarumlaut","ogonek","caron","emdash","","","","","","","","","","","","","","","","","AE","","ordfeminine","","","","","Lslash","Oslash","OE","ordmasculine","","","","","","ae","","","","dotlessi","","","lslash","oslash","oe","germandbls","","","",""],WinAnsiEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","bullet","Euro","bullet","quotesinglbase","florin","quotedblbase","ellipsis","dagger","daggerdbl","circumflex","perthousand","Scaron","guilsinglleft","OE","bullet","Zcaron","bullet","bullet","quoteleft","quoteright","quotedblleft","quotedblright","bullet","endash","emdash","tilde","trademark","scaron","guilsinglright","oe","bullet","zcaron","Ydieresis","space","exclamdown","cent","sterling","currency","yen","brokenbar","section","dieresis","copyright","ordfeminine","guillemotleft","logicalnot","hyphen","registered","macron","degree","plusminus","twosuperior","threesuperior","acute","mu","paragraph","periodcentered","cedilla","onesuperior","ordmasculine","guillemotright","onequarter","onehalf","threequarters","questiondown","Agrave","Aacute","Acircumflex","Atilde","Adieresis","Aring","AE","Ccedilla","Egrave","Eacute","Ecircumflex","Edieresis","Igrave","Iacute","Icircumflex","Idieresis","Eth","Ntilde","Ograve","Oacute","Ocircumflex","Otilde","Odieresis","multiply","Oslash","Ugrave","Uacute","Ucircumflex","Udieresis","Yacute","Thorn","germandbls","agrave","aacute","acircumflex","atilde","adieresis","aring","ae","ccedilla","egrave","eacute","ecircumflex","edieresis","igrave","iacute","icircumflex","idieresis","eth","ntilde","ograve","oacute","ocircumflex","otilde","odieresis","divide","oslash","ugrave","uacute","ucircumflex","udieresis","yacute","thorn","ydieresis"],SymbolSetEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","exclam","universal","numbersign","existential","percent","ampersand","suchthat","parenleft","parenright","asteriskmath","plus","comma","minus","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","congruent","Alpha","Beta","Chi","Delta","Epsilon","Phi","Gamma","Eta","Iota","theta1","Kappa","Lambda","Mu","Nu","Omicron","Pi","Theta","Rho","Sigma","Tau","Upsilon","sigma1","Omega","Xi","Psi","Zeta","bracketleft","therefore","bracketright","perpendicular","underscore","radicalex","alpha","beta","chi","delta","epsilon","phi","gamma","eta","iota","phi1","kappa","lambda","mu","nu","omicron","pi","theta","rho","sigma","tau","upsilon","omega1","omega","xi","psi","zeta","braceleft","bar","braceright","similar","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","Euro","Upsilon1","minute","lessequal","fraction","infinity","florin","club","diamond","heart","spade","arrowboth","arrowleft","arrowup","arrowright","arrowdown","degree","plusminus","second","greaterequal","multiply","proportional","partialdiff","bullet","divide","notequal","equivalence","approxequal","ellipsis","arrowvertex","arrowhorizex","carriagereturn","aleph","Ifraktur","Rfraktur","weierstrass","circlemultiply","circleplus","emptyset","intersection","union","propersuperset","reflexsuperset","notsubset","propersubset","reflexsubset","element","notelement","angle","gradient","registerserif","copyrightserif","trademarkserif","product","radical","dotmath","logicalnot","logicaland","logicalor","arrowdblboth","arrowdblleft","arrowdblup","arrowdblright","arrowdbldown","lozenge","angleleft","registersans","copyrightsans","trademarksans","summation","parenlefttp","parenleftex","parenleftbt","bracketlefttp","bracketleftex","bracketleftbt","bracelefttp","braceleftmid","braceleftbt","braceex","","angleright","integral","integraltp","integralex","integralbt","parenrighttp","parenrightex","parenrightbt","bracketrighttp","bracketrightex","bracketrightbt","bracerighttp","bracerightmid","bracerightbt",""],ZapfDingbatsEncoding=["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","space","a1","a2","a202","a3","a4","a5","a119","a118","a117","a11","a12","a13","a14","a15","a16","a105","a17","a18","a19","a20","a21","a22","a23","a24","a25","a26","a27","a28","a6","a7","a8","a9","a10","a29","a30","a31","a32","a33","a34","a35","a36","a37","a38","a39","a40","a41","a42","a43","a44","a45","a46","a47","a48","a49","a50","a51","a52","a53","a54","a55","a56","a57","a58","a59","a60","a61","a62","a63","a64","a65","a66","a67","a68","a69","a70","a71","a72","a73","a74","a203","a75","a204","a76","a77","a78","a79","a81","a82","a83","a84","a97","a98","a99","a100","","a89","a90","a93","a94","a91","a92","a205","a85","a206","a86","a87","a88","a95","a96","","","","","","","","","","","","","","","","","","","","a101","a102","a103","a104","a106","a107","a108","a112","a111","a110","a109","a120","a121","a122","a123","a124","a125","a126","a127","a128","a129","a130","a131","a132","a133","a134","a135","a136","a137","a138","a139","a140","a141","a142","a143","a144","a145","a146","a147","a148","a149","a150","a151","a152","a153","a154","a155","a156","a157","a158","a159","a160","a161","a163","a164","a196","a165","a192","a166","a167","a168","a169","a170","a171","a172","a173","a162","a174","a175","a176","a177","a178","a179","a193","a180","a199","a181","a200","a182","","a201","a183","a184","a197","a185","a194","a198","a186","a195","a187","a188","a189","a190","a191",""];function getEncoding(encodingName){switch(encodingName){case"WinAnsiEncoding":return WinAnsiEncoding;case"StandardEncoding":return StandardEncoding;case"MacRomanEncoding":return MacRomanEncoding;case"SymbolSetEncoding":return SymbolSetEncoding;case"ZapfDingbatsEncoding":return ZapfDingbatsEncoding;case"ExpertEncoding":return ExpertEncoding;case"MacExpertEncoding":return MacExpertEncoding;default:return null}}const MAX_SUBR_NESTING=10,CFFStandardStrings=[".notdef","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quoteright","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","quoteleft","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","exclamdown","cent","sterling","fraction","yen","florin","section","currency","quotesingle","quotedblleft","guillemotleft","guilsinglleft","guilsinglright","fi","fl","endash","dagger","daggerdbl","periodcentered","paragraph","bullet","quotesinglbase","quotedblbase","quotedblright","guillemotright","ellipsis","perthousand","questiondown","grave","acute","circumflex","tilde","macron","breve","dotaccent","dieresis","ring","cedilla","hungarumlaut","ogonek","caron","emdash","AE","ordfeminine","Lslash","Oslash","OE","ordmasculine","ae","dotlessi","lslash","oslash","oe","germandbls","onesuperior","logicalnot","mu","trademark","Eth","onehalf","plusminus","Thorn","onequarter","divide","brokenbar","degree","thorn","threequarters","twosuperior","registered","minus","eth","multiply","threesuperior","copyright","Aacute","Acircumflex","Adieresis","Agrave","Aring","Atilde","Ccedilla","Eacute","Ecircumflex","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Ntilde","Oacute","Ocircumflex","Odieresis","Ograve","Otilde","Scaron","Uacute","Ucircumflex","Udieresis","Ugrave","Yacute","Ydieresis","Zcaron","aacute","acircumflex","adieresis","agrave","aring","atilde","ccedilla","eacute","ecircumflex","edieresis","egrave","iacute","icircumflex","idieresis","igrave","ntilde","oacute","ocircumflex","odieresis","ograve","otilde","scaron","uacute","ucircumflex","udieresis","ugrave","yacute","ydieresis","zcaron","exclamsmall","Hungarumlautsmall","dollaroldstyle","dollarsuperior","ampersandsmall","Acutesmall","parenleftsuperior","parenrightsuperior","twodotenleader","onedotenleader","zerooldstyle","oneoldstyle","twooldstyle","threeoldstyle","fouroldstyle","fiveoldstyle","sixoldstyle","sevenoldstyle","eightoldstyle","nineoldstyle","commasuperior","threequartersemdash","periodsuperior","questionsmall","asuperior","bsuperior","centsuperior","dsuperior","esuperior","isuperior","lsuperior","msuperior","nsuperior","osuperior","rsuperior","ssuperior","tsuperior","ff","ffi","ffl","parenleftinferior","parenrightinferior","Circumflexsmall","hyphensuperior","Gravesmall","Asmall","Bsmall","Csmall","Dsmall","Esmall","Fsmall","Gsmall","Hsmall","Ismall","Jsmall","Ksmall","Lsmall","Msmall","Nsmall","Osmall","Psmall","Qsmall","Rsmall","Ssmall","Tsmall","Usmall","Vsmall","Wsmall","Xsmall","Ysmall","Zsmall","colonmonetary","onefitted","rupiah","Tildesmall","exclamdownsmall","centoldstyle","Lslashsmall","Scaronsmall","Zcaronsmall","Dieresissmall","Brevesmall","Caronsmall","Dotaccentsmall","Macronsmall","figuredash","hypheninferior","Ogoneksmall","Ringsmall","Cedillasmall","questiondownsmall","oneeighth","threeeighths","fiveeighths","seveneighths","onethird","twothirds","zerosuperior","foursuperior","fivesuperior","sixsuperior","sevensuperior","eightsuperior","ninesuperior","zeroinferior","oneinferior","twoinferior","threeinferior","fourinferior","fiveinferior","sixinferior","seveninferior","eightinferior","nineinferior","centinferior","dollarinferior","periodinferior","commainferior","Agravesmall","Aacutesmall","Acircumflexsmall","Atildesmall","Adieresissmall","Aringsmall","AEsmall","Ccedillasmall","Egravesmall","Eacutesmall","Ecircumflexsmall","Edieresissmall","Igravesmall","Iacutesmall","Icircumflexsmall","Idieresissmall","Ethsmall","Ntildesmall","Ogravesmall","Oacutesmall","Ocircumflexsmall","Otildesmall","Odieresissmall","OEsmall","Oslashsmall","Ugravesmall","Uacutesmall","Ucircumflexsmall","Udieresissmall","Yacutesmall","Thornsmall","Ydieresissmall","001.000","001.001","001.002","001.003","Black","Bold","Book","Light","Medium","Regular","Roman","Semibold"],NUM_STANDARD_CFF_STRINGS=391,CharstringValidationData=[null,{id:"hstem",min:2,stackClearing:!0,stem:!0},null,{id:"vstem",min:2,stackClearing:!0,stem:!0},{id:"vmoveto",min:1,stackClearing:!0},{id:"rlineto",min:2,resetStack:!0},{id:"hlineto",min:1,resetStack:!0},{id:"vlineto",min:1,resetStack:!0},{id:"rrcurveto",min:6,resetStack:!0},null,{id:"callsubr",min:1,undefStack:!0},{id:"return",min:0,undefStack:!0},null,null,{id:"endchar",min:0,stackClearing:!0},null,null,null,{id:"hstemhm",min:2,stackClearing:!0,stem:!0},{id:"hintmask",min:0,stackClearing:!0},{id:"cntrmask",min:0,stackClearing:!0},{id:"rmoveto",min:2,stackClearing:!0},{id:"hmoveto",min:1,stackClearing:!0},{id:"vstemhm",min:2,stackClearing:!0,stem:!0},{id:"rcurveline",min:8,resetStack:!0},{id:"rlinecurve",min:8,resetStack:!0},{id:"vvcurveto",min:4,resetStack:!0},{id:"hhcurveto",min:4,resetStack:!0},null,{id:"callgsubr",min:1,undefStack:!0},{id:"vhcurveto",min:4,resetStack:!0},{id:"hvcurveto",min:4,resetStack:!0}],CharstringValidationData12=[null,null,null,{id:"and",min:2,stackDelta:-1},{id:"or",min:2,stackDelta:-1},{id:"not",min:1,stackDelta:0},null,null,null,{id:"abs",min:1,stackDelta:0},{id:"add",min:2,stackDelta:-1,stackFn(stack,index){stack[index-2]=stack[index-2]+stack[index-1]}},{id:"sub",min:2,stackDelta:-1,stackFn(stack,index){stack[index-2]=stack[index-2]-stack[index-1]}},{id:"div",min:2,stackDelta:-1,stackFn(stack,index){stack[index-2]=stack[index-2]/stack[index-1]}},null,{id:"neg",min:1,stackDelta:0,stackFn(stack,index){stack[index-1]=-stack[index-1]}},{id:"eq",min:2,stackDelta:-1},null,null,{id:"drop",min:1,stackDelta:-1},null,{id:"put",min:2,stackDelta:-2},{id:"get",min:1,stackDelta:0},{id:"ifelse",min:4,stackDelta:-3},{id:"random",min:0,stackDelta:1},{id:"mul",min:2,stackDelta:-1,stackFn(stack,index){stack[index-2]=stack[index-2]*stack[index-1]}},null,{id:"sqrt",min:1,stackDelta:0},{id:"dup",min:1,stackDelta:1},{id:"exch",min:2,stackDelta:0},{id:"index",min:2,stackDelta:0},{id:"roll",min:3,stackDelta:-2},null,null,null,{id:"hflex",min:7,resetStack:!0},{id:"flex",min:13,resetStack:!0},{id:"hflex1",min:9,resetStack:!0},{id:"flex1",min:11,resetStack:!0}];class CFFParser{constructor(file,properties,seacAnalysisEnabled){this.bytes=file.getBytes(),this.properties=properties,this.seacAnalysisEnabled=!!seacAnalysisEnabled}parse(){var properties=this.properties,cff=new CFF,header=(this.cff=cff,this.parseHeader()),nameIndex=this.parseIndex(header.endPos),topDictIndex=this.parseIndex(nameIndex.endPos),stringIndex=this.parseIndex(topDictIndex.endPos),globalSubrIndex=this.parseIndex(stringIndex.endPos),topDictIndex=this.parseDict(topDictIndex.obj.get(0)),topDictIndex=this.createDict(CFFTopDict,topDictIndex,cff.strings),header=(cff.header=header.obj,cff.names=this.parseNameIndex(nameIndex.obj),cff.strings=this.parseStringIndex(stringIndex.obj),cff.topDict=topDictIndex,cff.globalSubrIndex=globalSubrIndex.obj,this.parsePrivateDict(cff.topDict),cff.isCIDFont=topDictIndex.hasName("ROS"),topDictIndex.getByName("CharStrings")),nameIndex=this.parseIndex(header).obj,stringIndex=topDictIndex.getByName("FontMatrix"),header=(stringIndex&&(properties.fontMatrix=stringIndex),topDictIndex.getByName("FontBBox"));header&&(properties.ascent=Math.max(header[3],header[1]),properties.descent=Math.min(header[1],header[3]),properties.ascentScaled=!0);let charset,encoding;if(cff.isCIDFont){var fdArrayIndex=this.parseIndex(topDictIndex.getByName("FDArray")).obj;for(let i=0,ii=fdArrayIndex.count;i=bytesLength)throw new FormatError("Invalid CFF header");0!==offset&&(info("cff data is shifted"),bytes=bytes.subarray(offset),this.bytes=bytes);var major=bytes[0],minor=bytes[1],hdrSize=bytes[2],offSize=bytes[3];return{obj:new CFFHeader(major,minor,hdrSize,offSize),endPos:hdrSize}}parseDict(dict){let pos=0;function parseOperand(){let value=dict[pos++];if(30!==value)return 28===value?value=((value=dict[pos++])<<24|dict[pos++]<<16)>>16:29===value?value=(value=(value=(value=dict[pos++])<<8|dict[pos++])<<8|dict[pos++])<<8|dict[pos++]:32<=value&&value<=246?value-139:247<=value&&value<=250?256*(value-247)+dict[pos++]+108:251<=value&&value<=254?-256*(value-251)-dict[pos++]-108:(warn('CFFParser_parseDict: "'+value+'" is a reserved command.'),NaN);{let str="";var lookup=["0","1","2","3","4","5","6","7","8","9",".","E","E-",null,"-"],length=dict.length;for(;pos>4,b=15&b;if(15==b1)break;if(str+=lookup[b1],15==b)break;str+=lookup[b]}return parseFloat(str)}}let operands=[];for(var entries=[],end=(pos=0,dict.length);posMAX_SUBR_NESTING)return!1;let stackSize=state.stackSize;var stack=state.stack;let length=data.length;for(let j=0;j>16,j+=2,stackSize++;else if(14===value){if(4<=stackSize&&(stackSize-=4,this.seacAnalysisEnabled))return state.seac=stack.slice(stackSize,stackSize+4),!1;validationCommand=CharstringValidationData[value]}else if(32<=value&&value<=246)stack[stackSize]=value-139,stackSize++;else if(247<=value&&value<=254)stack[stackSize]=value<251?(value-247<<8)+data[j]+108:-(value-251<<8)-data[j]-108,j++,stackSize++;else if(255===value)stack[stackSize]=(data[j]<<24|data[j+1]<<16|data[j+2]<<8|data[j+3])/65536,j+=4,stackSize++;else if(19===value||20===value){if(state.hints+=stackSize>>1,0===state.hints){data.copyWithin(j-1,j,-1),--j,--length;continue}j+=state.hints+7>>3,stackSize%=2,validationCommand=CharstringValidationData[value]}else{if(10===value||29===value){q=10===value?localSubrIndex:globalSubrIndex;if(!q)return warn("Missing subrsIndex for "+(validationCommand=CharstringValidationData[value]).id),!1;let bias=32768;q.count<1240?bias=107:q.count<33900&&(bias=1131);var subrNumber=stack[--stackSize]+bias;if(subrNumber<0||subrNumber>=q.count||isNaN(subrNumber))return warn("Out of bounds subrIndex for "+(validationCommand=CharstringValidationData[value]).id),!1;if(state.stackSize=stackSize,state.callDepth++,!this.parseCharString(state,q.get(subrNumber),localSubrIndex,globalSubrIndex))return!1;state.callDepth--,stackSize=state.stackSize;continue}if(11===value)return state.stackSize=stackSize,!0;if(0===value&&j===data.length)data[j-1]=14,validationCommand=CharstringValidationData[14];else{if(9===value){data.copyWithin(j-1,j,-1),--j,--length;continue}validationCommand=CharstringValidationData[value]}}if(validationCommand){if(validationCommand.stem&&(state.hints+=stackSize>>1,3===value||23===value?state.hasVStems=!0:!state.hasVStems||1!==value&&18!==value||(warn("CFF stem hints are in wrong order"),data[j-1]=1===value?3:23)),"min"in validationCommand&&!state.undefStack&&stackSize=fdArray.length&&(warn("Invalid fd index for glyph index."),valid=!1),valid&&(privateDictToUse=fdArray[fdIndex].privateDict,localSubrToUse=privateDictToUse.subrsIndex)):localSubrIndex&&(localSubrToUse=localSubrIndex),valid=valid&&this.parseCharString(state,charstring,localSubrToUse,globalSubrIndex),null!==state.width?(fdIndex=privateDictToUse.getByName("nominalWidthX"),widths[i]=fdIndex+state.width):(charstring=privateDictToUse.getByName("defaultWidthX"),widths[i]=charstring),null!==state.seac&&(seacs[i]=state.seac),valid||charStrings.set(i,new Uint8Array([14]))}return{charStrings:charStrings,seacs:seacs,widths:widths}}emptyPrivateDictionary(parentDict){var privateDict=this.createDict(CFFPrivateDict,[],parentDict.strings);parentDict.setByKey(18,[0,0]),parentDict.privateDict=privateDict}parsePrivateDict(parentDict){var size,relativeOffset,privateOffset;parentDict.hasName("Private")?(privateOffset=parentDict.getByName("Private"),Array.isArray(privateOffset)&&2===privateOffset.length?(size=privateOffset[0],privateOffset=privateOffset[1],0===size||privateOffset>=this.bytes.length?this.emptyPrivateDictionary(parentDict):(size=this.bytes.subarray(privateOffset,privateOffset+size),size=this.parseDict(size),size=this.createDict(CFFPrivateDict,size,parentDict.strings),0===(parentDict.privateDict=size).getByName("ExpansionFactor")&&size.setByName("ExpansionFactor",.06),size.getByName("Subrs")&&(relativeOffset=privateOffset+(privateOffset=size.getByName("Subrs")),0===privateOffset||relativeOffset>=this.bytes.length?this.emptyPrivateDictionary(parentDict):(privateOffset=this.parseIndex(relativeOffset),size.subrsIndex=privateOffset.obj)))):parentDict.removeByName("Private")):this.emptyPrivateDictionary(parentDict)}parseCharsets(pos,length,strings,cid){if(0===pos)return new CFFCharset(!0,CFFCharsetPredefinedTypes.ISO_ADOBE,ISOAdobeCharset);if(1===pos)return new CFFCharset(!0,CFFCharsetPredefinedTypes.EXPERT,ExpertCharset);if(2===pos)return new CFFCharset(!0,CFFCharsetPredefinedTypes.EXPERT_SUBSET,ExpertSubsetCharset);var bytes=this.bytes,start=pos,format=bytes[pos++],charset=[cid?0:".notdef"];let id,count,i;switch(--length,format){case 0:for(i=0;i=this.charStrings.count)&&0=this.fdSelect.length?-1:this.fdSelect[glyphIndex]}}class CFFOffsetTracker{constructor(){this.offsets=Object.create(null)}isTracking(key){return key in this.offsets}track(key,location){if(key in this.offsets)throw new FormatError("Already tracking location of "+key);this.offsets[key]=location}offset(value){for(const key in this.offsets)this.offsets[key]+=value}setEntryLocation(key,values,output){if(!(key in this.offsets))throw new FormatError("Not tracking location of "+key);var data=output.data,dataOffset=this.offsets[key];for(let i=0,ii=values.length;i>24&255,data[offset2]=value>>16&255,data[offset3]=value>>8&255,data[offset4]=255&value}}}class CFFCompiler{constructor(cff){this.cff=cff}compile(){var cff=this.cff,output={data:[],length:0,add(data){try{this.data.push(...data)}catch{this.data=this.data.concat(data)}this.length=this.data.length}},header=this.compileHeader(cff.header),header=(output.add(header),this.compileNameIndex(cff.names));if(output.add(header),cff.isCIDFont&&cff.topDict.hasName("FontMatrix")){var base=cff.topDict.getByName("FontMatrix");cff.topDict.removeByName("FontMatrix");for(const subDict of cff.fdArray){let matrix=base.slice(0);subDict.hasName("FontMatrix")&&(matrix=Util.transform(matrix,subDict.getByName("FontMatrix"))),subDict.setByName("FontMatrix",matrix)}}16>8),255&value]:-1131<=value&&value<=-108?[251+((value=-value-108)>>8),255&value]:-32768<=value&&value<=32767?[28,value>>8&255,255&value]:[29,value>>24&255,value>>16&255,value>>8&255,255&value]}compileHeader(header){return[header.major,header.minor,4,header.offSize]}compileNameIndex(names){var nameIndex=new CFFIndex;for(const name of names){var length=Math.min(name.length,127);let sanitizedName=new Array(length);for(let j=0;j"===char||"/"===char||"%"===char)&&(char="_"),sanitizedName[j]=char}""===(sanitizedName=sanitizedName.join(""))&&(sanitizedName="Bad_Font_Name"),nameIndex.add(stringToBytes(sanitizedName))}return this.compileIndex(nameIndex)}compileTopDicts(dicts,length,removeCidKeys){var fontDictTrackers=[];let fdArrayIndex=new CFFIndex;for(const fontDict of dicts){removeCidKeys&&(fontDict.removeByName("CIDFontVersion"),fontDict.removeByName("CIDFontRevision"),fontDict.removeByName("CIDFontType"),fontDict.removeByName("CIDCount"),fontDict.removeByName("UIDBase"));var fontDictTracker=new CFFOffsetTracker,fontDictData=this.compileDict(fontDict,fontDictTracker);fontDictTrackers.push(fontDictTracker),fdArrayIndex.add(fontDictData),fontDictTracker.offset(length)}return{trackers:fontDictTrackers,output:fdArrayIndex=this.compileIndex(fdArrayIndex,fontDictTrackers)}}compilePrivateDicts(dicts,trackers,output){for(let i=0,ii=dicts.length;i>8&255,255&numGlyphs]);else{let charsetIndex=(out=new Uint8Array(1+2*numGlyphs))[0]=0;var name,numCharsets=charset.charset.length;let warned=!1;for(let i=1;i>8&255,out[i+1]=255&sid}}return this.compileTypedArray(out)}compileEncoding(encoding){return this.compileTypedArray(encoding.raw)}compileFDSelect(fdSelect){var format=fdSelect.format;let out,i;switch(format){case 0:for((out=new Uint8Array(1+fdSelect.fdSelect.length))[0]=format,i=0;i>8&255,255&i,currentFD),lastFD=currentFD)}var numRanges=(ranges.length-3)/3;ranges[1]=numRanges>>8&255,ranges[2]=255&numRanges,ranges.push(i>>8&255,255&i),out=new Uint8Array(ranges)}return this.compileTypedArray(out)}compileTypedArray(data){return Array.from(data)}compileIndex(index,trackers=[]){var objects=index.objects,count=objects.length;if(0===count)return[0,0];var data=[count>>8&255,255&count];let lastOffset=1,i;for(i=0;i>8&255,255&relativeOffset):3===offsetSize?data.push(relativeOffset>>16&255,relativeOffset>>8&255,255&relativeOffset):data.push(relativeOffset>>>24&255,relativeOffset>>16&255,relativeOffset>>8&255,255&relativeOffset),objects[i]&&(relativeOffset+=objects[i].length);for(i=0;i=range[i]&&value<=range[i+1])return lastPosition}for(let i=0,ii=UnicodeRanges.length;i=range[j]&&value<=range[j+1])return i}return-1}const SpecialCharRegExp=new RegExp("^(\\s)|(\\p{Mn})|(\\p{Cf})$","u"),CategoryCache=new Map;function getCharUnicodeCategory(char){var cachedCategory=CategoryCache.get(char);return cachedCategory||(cachedCategory={isWhitespace:!!(cachedCategory=char.match(SpecialCharRegExp))?.[1],isZeroWidthDiacritic:!!cachedCategory?.[2],isInvisibleFormatMark:!!cachedCategory?.[3]},CategoryCache.set(char,cachedCategory),cachedCategory)}function clearUnicodeCaches(){CategoryCache.clear()}const SEAC_ANALYSIS_ENABLED=!0,FontFlags={FixedPitch:1,Serif:2,Symbolic:4,Script:8,Nonsymbolic:32,Italic:64,AllCap:65536,SmallCap:131072,ForceBold:262144},MacStandardGlyphOrdering=[".notdef",".null","nonmarkingreturn","space","exclam","quotedbl","numbersign","dollar","percent","ampersand","quotesingle","parenleft","parenright","asterisk","plus","comma","hyphen","period","slash","zero","one","two","three","four","five","six","seven","eight","nine","colon","semicolon","less","equal","greater","question","at","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","bracketleft","backslash","bracketright","asciicircum","underscore","grave","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","braceleft","bar","braceright","asciitilde","Adieresis","Aring","Ccedilla","Eacute","Ntilde","Odieresis","Udieresis","aacute","agrave","acircumflex","adieresis","atilde","aring","ccedilla","eacute","egrave","ecircumflex","edieresis","iacute","igrave","icircumflex","idieresis","ntilde","oacute","ograve","ocircumflex","odieresis","otilde","uacute","ugrave","ucircumflex","udieresis","dagger","degree","cent","sterling","section","bullet","paragraph","germandbls","registered","copyright","trademark","acute","dieresis","notequal","AE","Oslash","infinity","plusminus","lessequal","greaterequal","yen","mu","partialdiff","summation","product","pi","integral","ordfeminine","ordmasculine","Omega","ae","oslash","questiondown","exclamdown","logicalnot","radical","florin","approxequal","Delta","guillemotleft","guillemotright","ellipsis","nonbreakingspace","Agrave","Atilde","Otilde","OE","oe","endash","emdash","quotedblleft","quotedblright","quoteleft","quoteright","divide","lozenge","ydieresis","Ydieresis","fraction","currency","guilsinglleft","guilsinglright","fi","fl","daggerdbl","periodcentered","quotesinglbase","quotedblbase","perthousand","Acircumflex","Ecircumflex","Aacute","Edieresis","Egrave","Iacute","Icircumflex","Idieresis","Igrave","Oacute","Ocircumflex","apple","Ograve","Uacute","Ucircumflex","Ugrave","dotlessi","circumflex","tilde","macron","breve","dotaccent","ring","cedilla","hungarumlaut","ogonek","caron","Lslash","lslash","Scaron","scaron","Zcaron","zcaron","brokenbar","Eth","eth","Yacute","yacute","Thorn","thorn","minus","multiply","onesuperior","twosuperior","threesuperior","onehalf","onequarter","threequarters","franc","Gbreve","gbreve","Idotaccent","Scedilla","scedilla","Cacute","cacute","Ccaron","ccaron","dcroat"];function recoverGlyphName(name,glyphsUnicodeMap){if(void 0===glyphsUnicodeMap[name]){var unicode=getUnicodeForGlyph(name,glyphsUnicodeMap);if(-1!==unicode)for(const key in glyphsUnicodeMap)if(glyphsUnicodeMap[key]===unicode)return key;info("Unable to recover a standard glyph name for: "+name)}return name}function type1FontGlyphMapping(properties,builtInEncoding,glyphNames){var charCodeToGlyphId=Object.create(null);let glyphId,charCode,baseEncoding;var isSymbolicFont=!!(properties.flags&FontFlags.Symbolic);if(properties.isInternalFont)for(baseEncoding=builtInEncoding,charCode=0;charCode=this.firstChar&&v<=this.lastChar?v:-1}amend(map){unreachable("Should not call amend()")}}class CFFFont{constructor(file,properties){this.properties=properties;var parser=new CFFParser(file,properties,SEAC_ANALYSIS_ENABLED),parser=(this.cff=parser.parse(),this.cff.duplicateFirstGlyph(),new CFFCompiler(this.cff));this.seacs=this.cff.seacs;try{this.data=parser.compile()}catch{warn("Failed to compile font "+properties.loadedName),this.data=file}this._createBuiltInEncoding()}get numGlyphs(){return this.cff.charStrings.count}getCharset(){return this.cff.charset.charset}getGlyphMapping(){var cff=this.cff,properties=this.properties,{cidToGidMap,cMap}=properties,charsets=cff.charset.charset;let charCodeToGlyphId,glyphId;if(properties.composite){let invCidToGidMap;if(0>>0}function getUint16(data,offset){return data[offset]<<8|data[offset+1]}function getInt16(data,offset){return(data[offset]<<24|data[offset+1]<<16)>>16}function getInt8(data,offset){return data[offset]<<24>>24}function getFloat214(data,offset){return getInt16(data,offset)/16384}function getSubroutineBias(subrs){subrs=subrs.length;let bias=32768;return subrs<1240?bias=107:subrs<33900&&(bias=1131),bias}function parseCmap(data,start,end){var offset=1===getUint16(data,start+2)?getUint32(data,start+8):getUint32(data,start+16),format=getUint16(data,start+offset);let ranges,p,i;if(4===format){getUint16(data,start+offset+2);var segCount=getUint16(data,start+offset+6)>>1;for(p=start+offset+14,ranges=[],i=0;i2*getUint16(data,offset)))(loca,0);for(let j=itemSize;j>1;code>1,stackClean=!0;break;case 4:y+=stack.pop(),moveTo(x,y),stackClean=!0;break;case 5:for(;0Math.abs(y-y0)?x+=stack.shift():y+=stack.shift(),bezierCurveTo(xa,ya,xb,yb,x,y);break;default:throw new FormatError("unknown operator: 12 "+v)}break;case 14:var bchar,cmap;return void(4<=stack.length&&(fdIndex=stack.pop(),bchar=stack.pop(),y=stack.pop(),x=stack.pop(),cmds.add(FontRenderOps.SAVE),cmds.add(FontRenderOps.TRANSLATE,[x,y]),cmap=lookupCmap(font.cmap,String.fromCharCode(font.glyphNameMap[StandardEncoding[fdIndex]])),compileCharString(font.glyphs[cmap.glyphId],cmds,font,cmap.glyphId),cmds.add(FontRenderOps.RESTORE),cmap=lookupCmap(font.cmap,String.fromCharCode(font.glyphNameMap[StandardEncoding[bchar]])),compileCharString(font.glyphs[cmap.glyphId],cmds,font,cmap.glyphId)));case 18:stems+=stack.length>>1,stackClean=!0;break;case 19:case 20:stems+=stack.length>>1,i+=stems+7>>3,stackClean=!0;break;case 21:y+=stack.pop(),moveTo(x+=stack.pop(),y),stackClean=!0;break;case 22:moveTo(x+=stack.pop(),y),stackClean=!0;break;case 23:stems+=stack.length>>1,stackClean=!0;break;case 24:for(;2>16),i+=2;break;case 29:n=stack.pop()+font.gsubrsBias,(subrCode=font.gsubrs[n])&&parse(subrCode);break;case 30:for(;0"number"==typeof arg?arg:0),this.cmds.push(cmd,...args)):this.cmds.push(cmd)}}class CompiledFont{constructor(fontMatrix){this.constructor===CompiledFont&&unreachable("Cannot initialize CompiledFont."),this.fontMatrix=fontMatrix,this.compiledGlyphs=Object.create(null),this.compiledCharCodeToGlyphId=Object.create(null)}getPathJs(unicode){var{charCode:unicode,glyphId}=lookupCmap(this.cmap,unicode);let fn=this.compiledGlyphs[glyphId],compileEx;if(!fn){try{fn=this.compileGlyph(this.glyphs[glyphId],glyphId)}catch(ex){fn=NOOP,compileEx=ex}this.compiledGlyphs[glyphId]=fn}if(this.compiledCharCodeToGlyphId[unicode]??=glyphId,compileEx)throw compileEx;return fn}compileGlyph(code,glyphId){if(!code||0===code.length||14===code[0])return NOOP;let fontMatrix=this.fontMatrix;this.isCFFCIDFont&&(0<=(fdIndex=this.fdSelect.getFDIndex(glyphId))&&fdIndex{return a+(g.getSize()+3&-4)},0)}write(){var totalSize=this.getSize(),glyfTable=new DataView(new ArrayBuffer(totalSize)),isLocationLong=131070>1);return{isLocationLong:isLocationLong,loca:new Uint8Array(locaTable.buffer),glyf:new Uint8Array(glyfTable.buffer)}}scale(factors){for(let i=0,ii=this.glyphs.length;ia+c.getSize(),0),this.header.getSize()+size):0}write(pos,buf){if(!this.header)return 0;var spos=pos;if(pos+=this.header.write(pos,buf),this.simple)pos+=this.simple.write(pos,buf);else for(const composite of this.composites)pos+=composite.write(pos,buf);return pos-spos}scale(factor){if(this.header){var xMiddle=(this.header.xMin+this.header.xMax)/2;if(this.header.scale(xMiddle,factor),this.simple)this.simple.scale(xMiddle,factor);else for(const composite of this.composites)composite.scale(xMiddle,factor)}}}class GlyphHeader{constructor({numberOfContours,xMin,yMin,xMax,yMax}){this.numberOfContours=numberOfContours,this.xMin=xMin,this.yMin=yMin,this.xMax=xMax,this.yMax=yMax}static parse(pos,glyf){return[10,new GlyphHeader({numberOfContours:glyf.getInt16(pos),xMin:glyf.getInt16(pos+2),yMin:glyf.getInt16(pos+4),xMax:glyf.getInt16(pos+6),yMax:glyf.getInt16(pos+8)})]}getSize(){return 10}write(pos,buf){return buf.setInt16(pos,this.numberOfContours),buf.setInt16(pos+2,this.xMin),buf.setInt16(pos+4,this.yMin),buf.setInt16(pos+6,this.xMax),buf.setInt16(pos+8,this.yMax),10}scale(x,factor){this.xMin=Math.round(x+(this.xMin-x)*factor),this.xMax=Math.round(x+(this.xMax-x)*factor)}}class Contour{constructor({flags,xCoordinates,yCoordinates}){this.xCoordinates=xCoordinates,this.yCoordinates=yCoordinates,this.flags=flags}}class SimpleGlyph{constructor({contours,instructions}){this.contours=contours,this.instructions=instructions}static parse(pos,glyf,numberOfContours){var endPtsOfContours=[];for(let i=0;i>8&255,dest[offset+1]=255&num}function writeInt32(dest,offset,num){dest[offset]=num>>24&255,dest[offset+1]=num>>16&255,dest[offset+2]=num>>8&255,dest[offset+3]=255&num}function writeData(dest,offset,data){if(data instanceof Uint8Array)dest.set(data,offset);else if("string"==typeof data)for(let i=0,ii=data.length;imaxPower2;)maxPower2<<=1,log2++;var searchRange=maxPower2*entrySize;return{range:searchRange,entry:log2,rangeShift:entrySize*entriesCount-searchRange}}toArray(){let sfnt=this.sfnt;var tables=this.tables,tablesNames=Object.keys(tables),numTables=(tablesNames.sort(),tablesNames.length);let i,j,jj,table,tableName,offset=OTF_HEADER_SIZE+numTables*OTF_TABLE_ENTRY_SIZE;var tableOffsets=[offset];for(i=0;i>>0;offset+=paddedLength,tableOffsets.push(offset)}var file=new Uint8Array(offset);for(i=0;i>>0}writeInt32(file,offset+4,checksum),writeInt32(file,offset+8,tableOffsets[i]),writeInt32(file,offset+12,tables[tableName].length),offset+=OTF_TABLE_ENTRY_SIZE}return file}addTable(tag,data){if(tag in this.tables)throw new Error("Table "+tag+" already exists");this.tables[tag]=data}}const HINTING_ENABLED=!1,COMMAND_MAP={hstem:[1],vstem:[3],vmoveto:[4],rlineto:[5],hlineto:[6],vlineto:[7],rrcurveto:[8],callsubr:[10],flex:[12,35],drop:[12,18],endchar:[14],rmoveto:[21],hmoveto:[22],vhcurveto:[30],hvcurveto:[31]};class Type1CharString{constructor(){this.width=0,this.lsb=0,this.flexing=!1,this.output=[],this.stack=[]}convert(encoded,subrs,seacAnalysisEnabled){var sby,num1,flexArgs,count=encoded.length;let error=!1,wx,sbx,subrNumber;for(let i=0;i>8&255,255&value):this.output.push(255,(value=65536*value|0)>>24&255,value>>16&255,value>>8&255,255&value)}return this.output.push(...command),keepStack?this.stack.splice(start,howManyArgs):this.stack.length=0,!1}}const EEXEC_ENCRYPT_KEY=55665,CHAR_STRS_ENCRYPT_KEY=4330;function isHexDigit(code){return 48<=code&&code<=57||65<=code&&code<=70||97<=code&&code<=102}function decrypt(data,key,discardNumber){if(discardNumber>=data.length)return new Uint8Array(0);let r=0|key,i,j;for(i=0;i>8,r=52845*(value+r)+22719&65535}return decrypted}function decryptAscii(data,key,discardNumber){let r=0|key;var count=data.length,decrypted=new Uint8Array(count>>>1);let i,j;for(i=0,j=0;i>8,r=52845*(digit1+r)+22719&65535)}}return decrypted.slice(discardNumber,j)}function isSpecial(c){return 47===c||91===c||93===c||123===c||125===c||40===c||41===c}class Type1Parser{constructor(stream,encrypted,seacAnalysisEnabled){var isBinary;encrypted&&(isBinary=!((isHexDigit((encrypted=stream.getBytes())[0])||isWhiteSpace(encrypted[0]))&&isHexDigit(encrypted[1])&&isHexDigit(encrypted[2])&&isHexDigit(encrypted[3])&&isHexDigit(encrypted[4])&&isHexDigit(encrypted[5])&&isHexDigit(encrypted[6])&&isHexDigit(encrypted[7])),stream=new Stream((isBinary?decrypt:decryptAscii)(encrypted,EEXEC_ENCRYPT_KEY,4))),this.seacAnalysisEnabled=!!seacAnalysisEnabled,this.stream=stream,this.nextChar()}readNumberArray(){this.getToken();for(var array=[];;){var token=this.getToken();if(null===token||"]"===token||"}"===token)break;array.push(parseFloat(token||0))}return array}readNumber(){var token=this.getToken();return parseFloat(token||0)}readInt(){var token=this.getToken();return 0|parseInt(token||0,10)}readBoolean(){return"true"===this.getToken()?1:0}nextChar(){return this.currentChar=this.stream.getByte()}prevChar(){return this.stream.skip(-2),this.currentChar=this.stream.getByte()}getToken(){let comment=!1,ch=this.currentChar;for(;;){if(-1===ch)return null;if(comment)10!==ch&&13!==ch||(comment=!1);else if(37===ch)comment=!0;else if(!isWhiteSpace(ch))break;ch=this.nextChar()}if(isSpecial(ch))return this.nextChar(),String.fromCharCode(ch);let token="";for(;token+=String.fromCharCode(ch),0<=(ch=this.nextChar())&&!isWhiteSpace(ch)&&!isSpecial(ch););return token}readCharStrings(bytes,lenIV){return-1===lenIV?bytes:decrypt(bytes,CHAR_STRS_ENCRYPT_KEY,lenIV)}extractFontProgram(properties){var glyph,encoded,stream=this.stream,subrs=[],charstrings=[],privateData=Object.create(null),program=(privateData.lenIV=4,{subrs:[],charstrings:[],properties:{privateData:privateData}});let token,length,data,lenIV;for(;null!==(token=this.getToken());)if("/"===token)switch(token=this.getToken()){case"CharStrings":for(this.getToken(),this.getToken(),this.getToken(),this.getToken();;){if(null===(token=this.getToken())||"end"===token)break;"/"===token&&(glyph=this.getToken(),length=this.readInt(),this.getToken(),data=0=properties.firstChar&&index<=properties.lastChar&&(properties.widths[index]=charString.width)}}return program}extractFontHeader(properties){let token;for(;null!==(token=this.getToken());)if("/"===token)switch(token=this.getToken()){case"FontMatrix":var matrix=this.readNumberArray();properties.fontMatrix=matrix;break;case"Encoding":matrix=this.getToken();let encoding;if(/^\d+$/.test(matrix)){encoding=[];var size=0|parseInt(matrix,10);this.getToken();for(let j=0;j=signatureLength){for(i+=j;i=this.numGlyphs)&&(0===id||0>>8}function signedInt16(b0,b1){b0=(b0<<8)+b1;return 32768&b0?b0-65536:b0}function writeUint32(bytes,index,value){bytes[index+3]=255&value,bytes[index+2]=value>>>8,bytes[index+1]=value>>>16,bytes[index]=value>>>24}function int32(b0,b1,b2,b3){return(b0<<24)+(b1<<16)+(b2<<8)+b3}function string16(value){return String.fromCharCode(value>>8&255,255&value)}function safeString16(value){return 32767>8&255,255&value)}function isTrueTypeFile(file){file=file.peekBytes(4);return 65536===readUint32(file,0)||"true"===bytesToString(file)}function isTrueTypeCollectionFile(file){return"ttcf"===bytesToString(file.peekBytes(4))}function isOpenTypeFile(file){return"OTTO"===bytesToString(file.peekBytes(4))}function isType1File(file){file=file.peekBytes(2);return 37===file[0]&&33===file[1]||128===file[0]&&1===file[1]}function isCFFFile(file){file=file.peekBytes(4);return 1<=file[0]&&1<=file[3]&&file[3]<=4}function getFontFileType(file,{type,subtype,composite}){let fileType,fileSubtype;return isTrueTypeFile(file)||isTrueTypeCollectionFile(file)?fileType=composite?"CIDFontType2":"TrueType":isOpenTypeFile(file)?fileType=composite?"CIDFontType2":"OpenType":isType1File(file)?fileType=composite?"CIDFontType0":"MMType1"===type?"MMType1":"Type1":fileSubtype=isCFFFile(file)?composite?(fileType="CIDFontType0","CIDFontType0C"):(fileType="MMType1"===type?"MMType1":"Type1","Type1C"):(warn("getFontFileType: Unable to detect correct font file Type/Subtype."),fileType=type,subtype),[fileType,fileSubtype]}function applyStandardFontGlyphMap(map,glyphMap){for(const charCode in glyphMap)map[+charCode]=glyphMap[charCode]}function buildToFontChar(encoding,glyphsUnicodeMap,differences){var toFontChar=[];let unicode;for(let i=0,ii=encoding.length;iprivateUseOffetEnd){if(++privateUseAreaIndex>=PRIVATE_USE_AREAS.length){warn("Ran out of space in font private use area.");break}nextAvailableFontCharCode=PRIVATE_USE_AREAS[privateUseAreaIndex][0],privateUseOffetEnd=PRIVATE_USE_AREAS[privateUseAreaIndex][1]}var fontCharCode=nextAvailableFontCharCode++;0===glyphId&&(glyphId=newGlyphZeroId);let unicode=toUnicode.get(originalCharCode);!(unicode="string"==typeof unicode?unicode.codePointAt(0):unicode)||(code=unicode,PRIVATE_USE_AREAS[0][0]<=code&&code<=PRIVATE_USE_AREAS[0][1])||PRIVATE_USE_AREAS[1][0]<=code&&code<=PRIVATE_USE_AREAS[1][1]||usedGlyphIds.has(glyphId)||(toUnicodeExtraMap.set(unicode,glyphId),usedGlyphIds.add(glyphId)),newMap[fontCharCode]=glyphId,toFontChar[originalCharCode]=fontCharCode}}return{toFontChar:toFontChar,charCodeToGlyphId:newMap,toUnicodeExtraMap:toUnicodeExtraMap,nextAvailableFontCharCode:nextAvailableFontCharCode}}function getRanges(glyphs,toUnicodeExtraMap,numGlyphs){var codes=[];for(const charCode in glyphs)glyphs[charCode]>=numGlyphs||codes.push({fontCharCode:0|charCode,glyphId:glyphs[charCode]});if(toUnicodeExtraMap)for(var[unicode,glyphId]of toUnicodeExtraMap)glyphId>=numGlyphs||codes.push({fontCharCode:unicode,glyphId:glyphId});0===codes.length&&codes.push({fontCharCode:0,glyphId:0}),codes.sort(function(a,b){return a.fontCharCode-b.fontCharCode});var ranges=[],length=codes.length;for(let n=0;ncode||!firstCharIndex)&&(firstCharIndex=code),lastCharIndex 123 are reserved for internal usage");ulUnicodeRange4|=1</%]/g,"").slice(0,63)}function createNameTable(name,proto){var strings=[(proto=proto||[[],[]])[0][0]||"Original licence",proto[0][1]||name,proto[0][2]||"Unknown",proto[0][3]||"uniqueID",proto[0][4]||name,proto[0][5]||"Version 0.11",proto[0][6]||createPostscriptName(name),proto[0][7]||"Unknown",proto[0][8]||"Unknown",proto[0][9]||"Unknown"],stringsUnicode=[];let i,ii,j,jj,str;for(i=0,ii=strings.length;i{var unicode;this.composite||-1!==(unicode=getUnicodeForGlyph(this.differences[charCode]||this.defaultEncoding[charCode],glyphsUnicodeMap))&&(unicodeCharCode=unicode),map[+charCode]=unicodeCharCode}),this.composite&&this.toUnicode instanceof IdentityToUnicodeMap&&/Tahoma|Verdana/i.test(name)&&applyStandardFontGlyphMap(map,getGlyphMapForStandardFonts()),this.toFontChar=map}amendFallbackToUnicode(properties),this.loadedName=fontName.split("-",1)[0]}checkAndRepair(name,font,properties){const VALID_TABLES=["OS/2","cmap","head","hhea","hmtx","maxp","name","post","loca","glyf","fpgm","prep","cvt ","CFF "];function readTables(file,numTables){var tables=Object.create(null);tables["OS/2"]=null,tables.cmap=null,tables.head=null,tables.hhea=null,tables.hmtx=null,tables.maxp=null,tables.name=null,tables.post=null;for(let i=0;i>>0,offset=file.getInt32()>>>0,length=file.getInt32()>>>0,previousPosition=file.pos,data=(file.pos=file.start||0,file.skip(offset),file.getBytes(length));file.pos=previousPosition,"head"===tag&&(data[8]=data[9]=data[10]=data[11]=0,data[17]|=32);return{tag:tag,checksum:checksum,length:length,offset:offset,data:data}}(file);VALID_TABLES.includes(table.tag)&&0!==table.length&&(tables[table.tag]=table)}return tables}function readOpenTypeHeader(ttf){return{version:ttf.getString(4),numTables:ttf.getUint16(),searchRange:ttf.getUint16(),entrySelector:ttf.getUint16(),rangeShift:ttf.getUint16()}}function readTrueTypeCollectionData(ttc,fontName){var{numFonts,offsetTable}=function(ttc){var ttcTag=ttc.getString(4),majorVersion=(assert("ttcf"===ttcTag,"Must be a TrueType Collection font."),ttc.getUint16()),minorVersion=ttc.getUint16(),numFonts=ttc.getInt32()>>>0,offsetTable=[];for(let i=0;i>>0);var header={ttcTag:ttcTag,majorVersion:majorVersion,minorVersion:minorVersion,numFonts:numFonts,offsetTable:offsetTable};switch(majorVersion){case 1:return header;case 2:return header.dsigTag=ttc.getInt32()>>>0,header.dsigLength=ttc.getInt32()>>>0,header.dsigOffset=ttc.getInt32()>>>0,header}throw new FormatError(`Invalid TrueType Collection majorVersion: ${majorVersion}.`)}(ttc),fontNameParts=fontName.split("+");let fallbackData;for(let i=0;i>>24&255,data[offset+1]=value>>16&255,data[offset+2]=value>>8&255,data[offset+3]=255&value}):(itemSize=2,itemDecode=function(data,offset){return data[offset]<<9|data[offset+1]<<1},function(data,offset,value){data[offset]=value>>9&255,data[offset+1]=value>>1&255});var numGlyphsOut=dupFirstEntry?numGlyphs+1:numGlyphs,isGlyphLocationsLong=itemSize*(1+numGlyphsOut),locaData=new Uint8Array(isGlyphLocationsLong),oldGlyfData=(locaData.set(loca.data.subarray(0,isGlyphLocationsLong)),loca.data=locaData,glyf.data),oldGlyfDataLength=oldGlyfData.length,newGlyfData=new Uint8Array(oldGlyfDataLength);let i,j;var locaEntries=[];for(i=0,j=0;ioldGlyfDataLength&&(offset=oldGlyfDataLength),locaEntries.push({index:i,offset:offset,endOffset:0})}for(locaEntries.sort((a,b)=>a.offset-b.offset),i=0;ia.index-b.index),i=0;i=source.length||sourceEnd>source.length||sourceEnd-sourceStart<=12)){var glyf=source.subarray(sourceStart,sourceEnd),source=signedInt16(glyf[2],glyf[3]),sourceStart=signedInt16(glyf[4],glyf[5]),sourceEnd=signedInt16(glyf[6],glyf[7]),yMax=signedInt16(glyf[8],glyf[9]),contoursCount=(sourceEndglyf.length||(!hintsValid&&0maxSizeOfInstructions&&(maxSizeOfInstructions=glyphProfile.sizeOfInstructions),writeOffset+=newLength,itemEncode(locaData,j,writeOffset)}if(0===writeOffset){var simpleGlyph=new Uint8Array([0,1,0,0,0,0,0,0,0,0,0,0,0,0,49,0]);for(i=0,j=itemSize;iisGlyphLocationsLong+writeOffset?glyf.data=newGlyfData.subarray(0,isGlyphLocationsLong+writeOffset):(glyf.data=new Uint8Array(isGlyphLocationsLong+writeOffset),glyf.data.set(newGlyfData.subarray(0,writeOffset))),glyf.data.set(newGlyfData.subarray(0,isGlyphLocationsLong),writeOffset),itemEncode(loca.data,locaData.length-itemSize,writeOffset+isGlyphLocationsLong)):glyf.data=newGlyfData.subarray(0,writeOffset);return{missingGlyphs:missingGlyphs,maxSizeOfInstructions:maxSizeOfInstructions}}function readNameTable(nameTable){var start=(font.start||0)+nameTable.offset,names=(font.pos=start,[[],[]]),records=[],nameTable=nameTable.length,end=start+nameTable,format=font.getUint16();if(!(0!==format||nameTable<6)){var numRecords=font.getUint16(),stringsStart=font.getUint16();let i,ii;for(i=0;iend)){font.pos=pos;pos=record.name;if(record.encoding){let str="";for(let j=0,jj=record.length;jdata.length&&content.push(new Uint8Array(i-data.length)),lastDeff>lastEndf&&(warn("TT: complementing a missing function tail"),content.push(new Uint8Array([34,45]))),function(table,content){if(1>8&255,metrics[1+j]=255&advanceWidth,Math.round(scaleFactors[i]*signedInt16(metrics[2+j],metrics[3+j])));writeSignedInt16(metrics,2+j,advanceWidth)}}let numGlyphsOut=numGlyphs+1,dupFirstEntry=!0,maxFunctionDefs=(65535>8,tables.maxp.data[5]=255&numGlyphsOut;glyphs=function(fpgm,prep,cvt,maxFunctionDefs){var ttContext={functionsDefined:[],functionsUsed:[],functionsStackDeltas:[],tooComplexToFollowFunctions:!1,hintsValid:!0};return fpgm&&sanitizeTTProgram(fpgm,ttContext),prep&&sanitizeTTProgram(prep,ttContext),fpgm&&function(ttContext,maxFunctionDefs){if(!ttContext.tooComplexToFollowFunctions)if(ttContext.functionsDefined.length>maxFunctionDefs)warn("TT: more functions defined than expected"),ttContext.hintsValid=!1;else for(let j=0,jj=ttContext.functionsUsed.length;jmaxFunctionDefs)return warn("TT: invalid function id: "+j),ttContext.hintsValid=!1;if(ttContext.functionsUsed[j]&&!ttContext.functionsDefined[j])return warn("TT: undefined function: "+j),ttContext.hintsValid=!1}}(ttContext,maxFunctionDefs),cvt&&1&cvt.length&&((prep=new Uint8Array(cvt.length+1)).set(cvt.data),cvt.data=prep),ttContext.hintsValid}(tables.fpgm,tables.prep,tables["cvt "],maxFunctionDefs);if(glyphs||(delete tables.fpgm,delete tables.prep,delete tables["cvt "]),!function(file,header,metrics,headTable,numGlyphs,dupFirstEntry){if(header){file.pos=(file.start||0)+header.offset,file.pos+=4,file.pos+=2,file.pos+=2,file.pos+=2,file.pos+=2,file.pos+=2,file.pos+=2,file.pos+=2,file.pos+=2,file.pos+=2;var caretOffset=file.getUint16();file.pos+=8,file.pos+=2;let numOfMetrics=file.getUint16();0===caretOffset||2&int16(headTable.data[44],headTable.data[45])||(header.data[22]=0,header.data[23]=0),numOfMetrics>numGlyphs&&(info(`The numOfMetrics (${numOfMetrics}) should not be `+`greater than the numGlyphs (${numGlyphs}).`),numOfMetrics=numGlyphs,header.data[34]=(65280&numOfMetrics)>>8,header.data[35]=255&numOfMetrics);file=numGlyphs-numOfMetrics-(metrics.length-4*numOfMetrics>>1);0>16!=1&&(info("Attempting to fix invalid version in head table: "+version),head[0]=0,head[1]=1,head[2]=0,head[3]=0),(version=int16(head[50],head[51]))<0||1>8,tables.maxp.data[27]=255&loca.maxSizeOfInstructions)}if(!tables.hhea)throw new FormatError('Required "hhea" table is not found');0===tables.hhea.data[10]&&0===tables.hhea.data[11]&&(tables.hhea.data[10]=255,tables.hhea.data[11]=255);isComposite={unitsPerEm:int16(tables.head.data[18],tables.head.data[19]),yMax:signedInt16(tables.head.data[42],tables.head.data[43]),yMin:signedInt16(tables.head.data[38],tables.head.data[39]),ascent:signedInt16(tables.hhea.data[4],tables.hhea.data[5]),descent:signedInt16(tables.hhea.data[6],tables.hhea.data[7]),lineGap:signedInt16(tables.hhea.data[8],tables.hhea.data[9])};this.ascent=isComposite.ascent/isComposite.unitsPerEm,this.descent=isComposite.descent/isComposite.unitsPerEm,this.lineGap=isComposite.lineGap/isComposite.unitsPerEm,this.cssFontInfo?.lineHeight?(this.lineHeight=this.cssFontInfo.metrics.lineHeight,this.lineGap=this.cssFontInfo.metrics.lineGap):this.lineHeight=this.ascent-this.descent+this.lineGap,tables.post&&function(post,propertiesObj,maxpNumGlyphs){var start=(font.start||0)+post.offset,post=(font.pos=start,post.length),end=start+post,version=font.getInt32();font.skip(28);let glyphNames,valid=!0,i;switch(version){case 65536:glyphNames=MacStandardGlyphOrdering;break;case 131072:var numGlyphs=font.getUint16();if(numGlyphs!==maxpNumGlyphs)valid=!1;else{var glyphNameIndexes=[];for(i=0;i>>0;let useTable=!1;if(potentialTable?.platformId!==platformId||potentialTable?.encodingId!==encodingId){if(0!==platformId||0!==encodingId&&1!==encodingId&&3!==encodingId)if(1===platformId&&0===encodingId)useTable=!0;else if(3!==platformId||1!==encodingId||!hasEncoding&&potentialTable){if(isSymbolicFont&&3===platformId&&0===encodingId){let correctlySorted=useTable=!0;(correctlySorted=i>3;subHeaderKeys.push(subHeaderKey),maxSubHeaderKey=Math.max(subHeaderKey,maxSubHeaderKey)}var subHeaders=[];for(let i=0;i<=maxSubHeaderKey;i++)subHeaders.push({firstCode:file.getUint16(),entryCount:file.getUint16(),idDelta:signedInt16(file.getByte(),file.getByte()),idRangePos:file.pos+file.getUint16()});for(let i=0;i<256;i++)if(0===subHeaderKeys[i])file.pos=subHeaders[0].idRangePos+2*i,glyphId=file.getUint16(),mappings.push({charCode:i,glyphId:glyphId});else{var s=subHeaders[subHeaderKeys[i]];for(j=0;j>1,segments=(file.skip(6),[]);let segIndex;for(segIndex=0;segIndex>1)-(segCount-segIndex),segment.offsetIndex=offsetIndex,offsetsCount=Math.max(offsetsCount,offsetIndex+segment.end-segment.start+1)):segment.offsetIndex=-1}var offsets=[];for(j=0;j>>0;for(j=0;j>>0,endCharCode=file.getInt32()>>>0;let glyphCode=file.getInt32()>>>0;for(let charCode=startCharCode;charCode<=endCharCode;charCode++)mappings.push({charCode:charCode,glyphId:glyphCode++})}}mappings.sort(function(a,b){return a.charCode-b.charCode});for(let i=1;ithis.toUnicode.charCodeOf(unicode):unicode=>this.toUnicode.charCodeOf(String.fromCodePoint(unicode));for(let i=0,ii=str.length;i>8*j&255));continue}}buffers.length%2!=1&&(buffers.push(currentBuf.join("")),currentBuf.length=0),currentBuf.push(String.fromCodePoint(unicode))}return buffers.push(currentBuf.join("")),buffers}}class ErrorFont{constructor(error){this.error=error,this.loadedName="g_font_error",this.missingFile=!0}charsToGlyphs(){return[]}encodeString(chars){return[chars]}exportData(extraProperties=0){return{error:this.error}}}const ShadingType={FUNCTION_BASED:1,AXIAL:2,RADIAL:3,FREE_FORM_MESH:4,LATTICE_FORM_MESH:5,COONS_PATCH_MESH:6,TENSOR_PATCH_MESH:7};class Pattern{constructor(){unreachable("Cannot initialize Pattern.")}static parseShading(shading,xref,res,pdfFunctionFactory,localColorSpaceCache){var dict=shading instanceof BaseStream?shading.dict:shading,type=dict.get("ShadingType");try{switch(type){case ShadingType.AXIAL:case ShadingType.RADIAL:return new RadialAxialShading(dict,xref,res,pdfFunctionFactory,localColorSpaceCache);case ShadingType.FREE_FORM_MESH:case ShadingType.LATTICE_FORM_MESH:case ShadingType.COONS_PATCH_MESH:case ShadingType.TENSOR_PATCH_MESH:return new MeshShading(shading,xref,res,pdfFunctionFactory,localColorSpaceCache);default:throw new FormatError("Unsupported ShadingType: "+type)}}catch(ex){if(ex instanceof MissingDataException)throw ex;return warn(ex),new DummyShading}}}class BaseShading{static SMALL_NUMBER=1e-6;constructor(){this.constructor===BaseShading&&unreachable("Cannot initialize BaseShading.")}getIR(){unreachable("Abstract method `getIR` called.")}}class RadialAxialShading extends BaseShading{constructor(dict,xref,resources,pdfFunctionFactory,localColorSpaceCache){super(),this.coordsArr=dict.getArray("Coords"),this.shadingType=dict.get("ShadingType");var y2,r2,cs=ColorSpace.parse({cs:dict.getRaw("CS")||dict.getRaw("ColorSpace"),xref:xref,resources:resources,pdfFunctionFactory:pdfFunctionFactory,localColorSpaceCache:localColorSpaceCache}),xref=dict.getArray("BBox");this.bbox=Array.isArray(xref)&&4===xref.length?Util.normalizeRect(xref):null;let t0=0,t1=1,extendStart=(dict.has("Domain")&&(resources=dict.getArray("Domain"),t0=resources[0],t1=resources[1]),!1),extendEnd=!1;dict.has("Extend")&&(localColorSpaceCache=dict.getArray("Extend"),extendStart=localColorSpaceCache[0],extendEnd=localColorSpaceCache[1]),this.shadingType!==ShadingType.RADIAL||extendStart&&extendEnd||([xref,resources,localColorSpaceCache,x2,y2,r2]=this.coordsArr,localColorSpaceCache<=r2+(xref=Math.hypot(xref-x2,resources-y2))&&r2<=localColorSpaceCache+xref&&warn("Unsupported radial gradient.")),this.extendStart=extendStart,this.extendEnd=extendEnd;var x2=dict.getRaw("Function"),fn=pdfFunctionFactory.createFromArray(x2),step=(t1-t0)/840,colorStops=this.colorStops=[];if(t0>=t1||step<=0)info("Bad shading domain.");else{var color=new Float32Array(cs.numComps),ratio=new Float32Array(1);let rgbColor,iBase=0,rgbBase=(ratio[0]=t0,fn(ratio,0,color,0),cs.getRgb(color,0));resources=Util.makeHexColor(rgbBase[0],rgbBase[1],rgbBase[2]);colorStops.push([0,resources]);let iPrev=1,rgbPrev=(ratio[0]=t0+step,fn(ratio,0,color,0),cs.getRgb(color,0)),maxSlopeR=rgbPrev[0]-rgbBase[0]+1,maxSlopeG=rgbPrev[1]-rgbBase[1]+1,maxSlopeB=rgbPrev[2]-rgbBase[2]+1,minSlopeR=rgbPrev[0]-rgbBase[0]-1,minSlopeG=rgbPrev[1]-rgbBase[1]-1,minSlopeB=rgbPrev[2]-rgbBase[2]-1;for(let i=2;i<840;i++){ratio[0]=t0+i*step,fn(ratio,0,color,0),rgbColor=cs.getRgb(color,0);var run=i-iBase,run=(maxSlopeR=Math.min(maxSlopeR,(rgbColor[0]-rgbBase[0]+1)/run),maxSlopeG=Math.min(maxSlopeG,(rgbColor[1]-rgbBase[1]+1)/run),maxSlopeB=Math.min(maxSlopeB,(rgbColor[2]-rgbBase[2]+1)/run),minSlopeR=Math.max(minSlopeR,(rgbColor[0]-rgbBase[0]-1)/run),minSlopeG=Math.max(minSlopeG,(rgbColor[1]-rgbBase[1]-1)/run),minSlopeB=Math.max(minSlopeB,(rgbColor[2]-rgbBase[2]-1)/run),minSlopeR<=maxSlopeR&&minSlopeG<=maxSlopeG&&minSlopeB<=maxSlopeB);if(!run){const cssColor=Util.makeHexColor(rgbPrev[0],rgbPrev[1],rgbPrev[2]);colorStops.push([iPrev/840,cssColor]),maxSlopeR=rgbColor[0]-rgbPrev[0]+1,maxSlopeG=rgbColor[1]-rgbPrev[1]+1,maxSlopeB=rgbColor[2]-rgbPrev[2]+1,minSlopeR=rgbColor[0]-rgbPrev[0]-1,minSlopeG=rgbColor[1]-rgbPrev[1]-1,minSlopeB=rgbColor[2]-rgbPrev[2]-1,iBase=iPrev,rgbBase=rgbPrev}iPrev=i,rgbPrev=rgbColor}const cssColor=Util.makeHexColor(rgbPrev[0],rgbPrev[1],rgbPrev[2]);colorStops.push([1,cssColor]);let background="transparent";dict.has("Background")&&(rgbColor=cs.getRgb(dict.get("Background"),0),background=Util.makeHexColor(rgbColor[0],rgbColor[1],rgbColor[2])),extendStart||(colorStops.unshift([0,background]),colorStops[1][0]+=BaseShading.SMALL_NUMBER),extendEnd||(colorStops.at(-1)[0]-=BaseShading.SMALL_NUMBER,colorStops.push([1,background])),this.colorStops=colorStops}}getIR(){var coordsArr=this.coordsArr,shadingType=this.shadingType;let type,p0,p1,r0,r1;return shadingType===ShadingType.AXIAL?(p0=[coordsArr[0],coordsArr[1]],p1=[coordsArr[2],coordsArr[3]],r0=null,r1=null,type="axial"):shadingType===ShadingType.RADIAL?(p0=[coordsArr[0],coordsArr[1]],p1=[coordsArr[3],coordsArr[4]],r0=coordsArr[2],r1=coordsArr[5],type="radial"):unreachable("getPattern type unknown: "+shadingType),["RadialAxial",type,this.bbox,this.colorStops,p0,p1,r0,r1]}}class MeshStreamReader{constructor(stream,context){this.stream=stream,this.context=context,this.buffer=0,this.bufferLength=0;stream=context.numComps,this.tmpCompsBuf=new Float32Array(stream),stream=context.colorSpace.numComps;this.tmpCsCompsBuf=context.colorFn?new Float32Array(stream):this.tmpCompsBuf}get hasData(){if(this.stream.end)return this.stream.pos>>0;buffer=buffer<<24|this.stream.getByte()<<16|this.stream.getByte()<<8|this.stream.getByte();var nextByte=this.stream.getByte();return this.buffer=nextByte&(1<>bufferLength)>>>0}if(8===n&&0===bufferLength)return this.stream.getByte();for(;bufferLength>bufferLength}align(){this.buffer=0,this.bufferLength=0}readFlag(){return this.readBits(this.context.bitsPerFlag)}readCoordinate(){var bitsPerCoordinate=this.context.bitsPerCoordinate,xi=this.readBits(bitsPerCoordinate),yi=this.readBits(bitsPerCoordinate),decode=this.context.decode,bitsPerCoordinate=bitsPerCoordinate<32?1/((1<x?x:minX,minY=minY>y?y:minY,maxX=maxXw*factors[i]):baseWidths;let currentCode=-2,currentArray;var unicode,glyphIndex,newWidths=[];for([unicode,glyphIndex]of baseMapping.map((charUnicode,index)=>[charUnicode,index]).sort(([unicode1],[unicode2])=>unicode1-unicode2))-1!==unicode&&(unicode===currentCode+1?(currentArray.push(rescaledBaseWidths[glyphIndex]),currentCode+=1):(currentCode=unicode,currentArray=[rescaledBaseWidths[glyphIndex]],newWidths.push(unicode,currentArray)));return newWidths}function getXfaFontDict(name){var widths=getXfaFontWidths(name),dict=new Dict(null),name=(dict.set("BaseFont",Name.get(name)),dict.set("Type",Name.get("Font")),dict.set("Subtype",Name.get("CIDFontType2")),dict.set("Encoding",Name.get("Identity-H")),dict.set("CIDToGIDMap",Name.get("Identity")),dict.set("W",widths),dict.set("FirstChar",widths[0]),dict.set("LastChar",widths.at(-2)+widths.at(-1).length-1),new Dict(null)),widths=(dict.set("FontDescriptor",name),new Dict(null));return widths.set("Ordering","Identity"),widths.set("Registry","Adobe"),widths.set("Supplement",0),dict.set("CIDSystemInfo",widths),dict}class PostScriptParser{constructor(lexer){this.lexer=lexer,this.operators=[],this.token=null,this.prev=null}nextToken(){this.prev=this.token,this.token=this.lexer.getToken()}accept(type){return this.token.type===type&&(this.nextToken(),!0)}expect(type){if(this.accept(type))return!0;throw new FormatError(`Unexpected symbol: found ${this.token.type} expected ${type}.`)}parse(){return this.nextToken(),this.expect(PostScriptTokenTypes.LBRACE),this.parseBlock(),this.expect(PostScriptTokenTypes.RBRACE),this.operators}parseBlock(){for(;;)if(this.accept(PostScriptTokenTypes.NUMBER))this.operators.push(this.prev.value);else if(this.accept(PostScriptTokenTypes.OPERATOR))this.operators.push(this.prev.value);else{if(!this.accept(PostScriptTokenTypes.LBRACE))return;this.parseCondition()}}parseCondition(){var conditionLocation=this.operators.length;if(this.operators.push(null,null),this.parseBlock(),this.expect(PostScriptTokenTypes.RBRACE),this.accept(PostScriptTokenTypes.IF))this.operators[conditionLocation]=this.operators.length;else{if(!this.accept(PostScriptTokenTypes.LBRACE))throw new FormatError("PS Function: error parsing conditional.");var jumpLocation=this.operators.length,endOfTrue=(this.operators.push(null,null),this.operators.length);this.parseBlock(),this.expect(PostScriptTokenTypes.RBRACE),this.expect(PostScriptTokenTypes.IFELSE),this.operators[jumpLocation]=this.operators.length,this.operators[jumpLocation+1]="j",this.operators[conditionLocation]=endOfTrue}this.operators[conditionLocation+1]="jz"}}const PostScriptTokenTypes={LBRACE:0,RBRACE:1,NUMBER:2,OPERATOR:3,IF:4,IFELSE:5};class PostScriptToken{static get opCache(){return shadow(this,"opCache",Object.create(null))}constructor(type,value){this.type=type,this.value=value}static getOperator(op){return PostScriptToken.opCache[op]||=new PostScriptToken(PostScriptTokenTypes.OPERATOR,op)}static get LBRACE(){return shadow(this,"LBRACE",new PostScriptToken(PostScriptTokenTypes.LBRACE,"{"))}static get RBRACE(){return shadow(this,"RBRACE",new PostScriptToken(PostScriptTokenTypes.RBRACE,"}"))}static get IF(){return shadow(this,"IF",new PostScriptToken(PostScriptTokenTypes.IF,"IF"))}static get IFELSE(){return shadow(this,"IFELSE",new PostScriptToken(PostScriptTokenTypes.IFELSE,"IFELSE"))}}class PostScriptLexer{constructor(stream){this.stream=stream,this.nextChar(),this.strBuf=[]}nextChar(){return this.currentChar=this.stream.getByte()}getToken(){let comment=!1,ch=this.currentChar;for(;;){if(ch<0)return EOF;if(comment)10!==ch&&13!==ch||(comment=!1);else if(37===ch)comment=!0;else if(!isWhiteSpace(ch))break;ch=this.nextChar()}switch(0|ch){case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:case 43:case 45:case 46:return new PostScriptToken(PostScriptTokenTypes.NUMBER,this.getNumber());case 123:return this.nextChar(),PostScriptToken.LBRACE;case 125:return this.nextChar(),PostScriptToken.RBRACE}var strBuf=this.strBuf;for(strBuf.length=0,strBuf[0]=String.fromCharCode(ch);0<=(ch=this.nextChar())&&(65<=ch&&ch<=90||97<=ch&&ch<=122);)strBuf.push(String.fromCharCode(ch));var str=strBuf.join("");switch(str.toLowerCase()){case"if":return PostScriptToken.IF;case"ifelse":return PostScriptToken.IFELSE;default:return PostScriptToken.getOperator(str)}}getNumber(){var ch=this.currentChar,strBuf=this.strBuf;for(strBuf.length=0,strBuf[0]=String.fromCharCode(ch);0<=(ch=this.nextChar())&&(48<=ch&&ch<=57||45===ch||46===ch);)strBuf.push(String.fromCharCode(ch));var value=parseFloat(strBuf.join(""));if(isNaN(value))throw new FormatError("Invalid floating point number: "+value);return value}}class BaseLocalCache{constructor(options){this.constructor===BaseLocalCache&&unreachable("Cannot initialize BaseLocalCache."),this._onlyRefs=!0===options?.onlyRefs,this._onlyRefs||(this._nameRefMap=new Map,this._imageMap=new Map),this._imageCache=new RefSetCache}getByName(name){this._onlyRefs&&unreachable("Should not call `getByName` method.");var ref=this._nameRefMap.get(name);return ref?this.getByRef(ref):this._imageMap.get(name)||null}getByRef(ref){return this._imageCache.get(ref)||null}set(name,ref,data){unreachable("Abstract method `set` called.")}}class LocalImageCache extends BaseLocalCache{set(name,ref=null,data){if("string"!=typeof name)throw new Error('LocalImageCache.set - expected "name" argument.');if(ref)return this._imageCache.has(ref)?void 0:(this._nameRefMap.set(name,ref),void this._imageCache.put(ref,data));this._imageMap.has(name)||this._imageMap.set(name,data)}}class LocalColorSpaceCache extends BaseLocalCache{set(name=null,ref=null,data){if("string"!=typeof name&&!ref)throw new Error('LocalColorSpaceCache.set - expected "name" and/or "ref" argument.');if(ref)return this._imageCache.has(ref)?void 0:(null!==name&&this._nameRefMap.set(name,ref),void this._imageCache.put(ref,data));this._imageMap.has(name)||this._imageMap.set(name,data)}}class LocalFunctionCache extends BaseLocalCache{constructor(options){super({onlyRefs:!0})}set(name=0,ref,data){if(!ref)throw new Error('LocalFunctionCache.set - expected "ref" argument.');this._imageCache.has(ref)||this._imageCache.put(ref,data)}}class LocalGStateCache extends BaseLocalCache{set(name,ref=null,data){if("string"!=typeof name)throw new Error('LocalGStateCache.set - expected "name" argument.');if(ref)return this._imageCache.has(ref)?void 0:(this._nameRefMap.set(name,ref),void this._imageCache.put(ref,data));this._imageMap.has(name)||this._imageMap.set(name,data)}}class LocalTilingPatternCache extends BaseLocalCache{constructor(options){super({onlyRefs:!0})}set(name=0,ref,data){if(!ref)throw new Error('LocalTilingPatternCache.set - expected "ref" argument.');this._imageCache.has(ref)||this._imageCache.put(ref,data)}}class RegionalImageCache extends BaseLocalCache{constructor(options){super({onlyRefs:!0})}set(name=0,ref,data){if(!ref)throw new Error('RegionalImageCache.set - expected "ref" argument.');this._imageCache.has(ref)||this._imageCache.put(ref,data)}}class GlobalImageCache{static NUM_PAGES_THRESHOLD=2;static MIN_IMAGES_TO_CACHE=10;static MAX_BYTE_SIZE=5*MAX_IMAGE_SIZE_TO_CACHE;constructor(){this._refCache=new RefSetCache,this._imageCache=new RefSetCache}get _byteSize(){let byteSize=0;for(const imageData of this._imageCache)byteSize+=imageData.byteSize;return byteSize}get _cacheLimitReached(){return!(this._imageCache.size+x):null}class PDFFunction{static getSampleArray(size,outputSize,bps,stream){let i,ii,length=1;for(i=0,ii=size.length;i>codeSize)*sampleMul,codeBuf&=(1<>1,numInputs=domain.length>>1,evaluator=new PostScriptEvaluator(fn),cache=Object.create(null);let cache_available=8192;const tmpBuf=new Float32Array(numInputs);return function(src,srcOffset,dest,destOffset){let i,value,key="";var input=tmpBuf;for(i=0;ibound))&&(value=bound),output[i]=value}0=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");this.stack.push(value)}pop(){if(this.stack.length<=0)throw new Error("PostScript function stack underflow.");return this.stack.pop()}copy(n){if(this.stack.length+n>=PostScriptStack.MAX_STACK_SIZE)throw new Error("PostScript function stack overflow.");var stack=this.stack;for(let i=stack.length-n,j=n-1;0<=j;j--,i++)stack.push(stack[i])}index(n){this.push(this.stack[this.stack.length-n-1])}roll(n,p){var stack=this.stack,l=stack.length-n,r=stack.length-1,p=l+(p-Math.floor(p/n)*n);for(let i=l,j=r;i>b);break;case"ceiling":a=stack.pop(),stack.push(Math.ceil(a));break;case"copy":a=stack.pop(),stack.copy(a);break;case"cos":a=stack.pop(),stack.push(Math.cos(a%360/180*Math.PI));break;case"cvi":a=0|stack.pop(),stack.push(a);break;case"cvr":break;case"div":b=stack.pop(),a=stack.pop(),stack.push(a/b);break;case"dup":stack.copy(1);break;case"eq":b=stack.pop(),a=stack.pop(),stack.push(a===b);break;case"exch":stack.roll(2,1);break;case"exp":b=stack.pop(),a=stack.pop(),stack.push(a**b);break;case"false":stack.push(!1);break;case"floor":a=stack.pop(),stack.push(Math.floor(a));break;case"ge":b=stack.pop(),a=stack.pop(),stack.push(a>=b);break;case"gt":b=stack.pop(),a=stack.pop(),stack.push(a>b);break;case"idiv":b=stack.pop(),a=stack.pop(),stack.push(a/b|0);break;case"index":a=stack.pop(),stack.index(a);break;case"le":b=stack.pop(),a=stack.pop(),stack.push(a<=b);break;case"ln":a=stack.pop(),stack.push(Math.log(a));break;case"log":a=stack.pop(),stack.push(Math.log10(a));break;case"lt":b=stack.pop(),a=stack.pop(),stack.push(a=max?new AstLiteral(max):num1.max<=max?num1:new AstMin(num1,max)}class PostScriptCompiler{compile(code,domain,range){var stack=[],instructions=[],inputSize=domain.length>>1,outputSize=range.length>>1;let lastRegister=0,n,j,num1,num2,ast1,ast2,tmpVar,item;for(let i=0;iexpr.min&&(out.unshift("Math.max(",min,", "),out.push(")")),maxlevel&&isOdd(level)&&(lowestOddLevel=level);for(level=highestLevel;level>=lowestOddLevel;--level){let start=-1;for(i=0,ii=levels.length;i"!==ch||(chars[i]="")}return createBidiText(chars.join(""),isLTR)}const NORMAL={style:"normal",weight:"normal"},BOLD={style:"normal",weight:"bold"},ITALIC={style:"italic",weight:"normal"},BOLDITALIC={style:"italic",weight:"bold"},substitutionMap=new Map([["Times-Roman",{local:["Times New Roman","Times-Roman","Times","Liberation Serif","Nimbus Roman","Nimbus Roman L","Tinos","Thorndale","TeX Gyre Termes","FreeSerif","Linux Libertine O","Libertinus Serif","DejaVu Serif","Bitstream Vera Serif","Ubuntu"],style:NORMAL,ultimate:"serif"}],["Times-Bold",{alias:"Times-Roman",style:BOLD,ultimate:"serif"}],["Times-Italic",{alias:"Times-Roman",style:ITALIC,ultimate:"serif"}],["Times-BoldItalic",{alias:"Times-Roman",style:BOLDITALIC,ultimate:"serif"}],["Helvetica",{local:["Helvetica","Helvetica Neue","Arial","Arial Nova","Liberation Sans","Arimo","Nimbus Sans","Nimbus Sans L","A030","TeX Gyre Heros","FreeSans","DejaVu Sans","Albany","Bitstream Vera Sans","Arial Unicode MS","Microsoft Sans Serif","Apple Symbols","Cantarell"],path:"LiberationSans-Regular.ttf",style:NORMAL,ultimate:"sans-serif"}],["Helvetica-Bold",{alias:"Helvetica",path:"LiberationSans-Bold.ttf",style:BOLD,ultimate:"sans-serif"}],["Helvetica-Oblique",{alias:"Helvetica",path:"LiberationSans-Italic.ttf",style:ITALIC,ultimate:"sans-serif"}],["Helvetica-BoldOblique",{alias:"Helvetica",path:"LiberationSans-BoldItalic.ttf",style:BOLDITALIC,ultimate:"sans-serif"}],["Courier",{local:["Courier","Courier New","Liberation Mono","Nimbus Mono","Nimbus Mono L","Cousine","Cumberland","TeX Gyre Cursor","FreeMono","Linux Libertine Mono O","Libertinus Mono"],style:NORMAL,ultimate:"monospace"}],["Courier-Bold",{alias:"Courier",style:BOLD,ultimate:"monospace"}],["Courier-Oblique",{alias:"Courier",style:ITALIC,ultimate:"monospace"}],["Courier-BoldOblique",{alias:"Courier",style:BOLDITALIC,ultimate:"monospace"}],["ArialBlack",{local:["Arial Black"],style:{style:"normal",weight:"900"},fallback:"Helvetica-Bold"}],["ArialBlack-Bold",{alias:"ArialBlack"}],["ArialBlack-Italic",{alias:"ArialBlack",style:{style:"italic",weight:"900"},fallback:"Helvetica-BoldOblique"}],["ArialBlack-BoldItalic",{alias:"ArialBlack-Italic"}],["ArialNarrow",{local:["Arial Narrow","Liberation Sans Narrow","Helvetica Condensed","Nimbus Sans Narrow","TeX Gyre Heros Cn"],style:NORMAL,fallback:"Helvetica"}],["ArialNarrow-Bold",{alias:"ArialNarrow",style:BOLD,fallback:"Helvetica-Bold"}],["ArialNarrow-Italic",{alias:"ArialNarrow",style:ITALIC,fallback:"Helvetica-Oblique"}],["ArialNarrow-BoldItalic",{alias:"ArialNarrow",style:BOLDITALIC,fallback:"Helvetica-BoldOblique"}],["Calibri",{local:["Calibri","Carlito"],style:NORMAL,fallback:"Helvetica"}],["Calibri-Bold",{alias:"Calibri",style:BOLD,fallback:"Helvetica-Bold"}],["Calibri-Italic",{alias:"Calibri",style:ITALIC,fallback:"Helvetica-Oblique"}],["Calibri-BoldItalic",{alias:"Calibri",style:BOLDITALIC,fallback:"Helvetica-BoldOblique"}],["Wingdings",{local:["Wingdings","URW Dingbats"],style:NORMAL}],["Wingdings-Regular",{alias:"Wingdings"}],["Wingdings-Bold",{alias:"Wingdings"}]]),fontAliases=new Map([["Arial-Black","ArialBlack"]]);function getStyleToAppend(style){switch(style){case BOLD:return"Bold";case ITALIC:return"Italic";case BOLDITALIC:return"Bold Italic";default:if("bold"===style?.weight)return"Bold";if("italic"===style?.style)return"Italic"}return""}function getFamilyName(str){const keywords=new Set(["thin","extralight","ultralight","demilight","semilight","light","book","regular","normal","medium","demibold","semibold","bold","extrabold","ultrabold","black","heavy","extrablack","ultrablack","roman","italic","oblique","ultracondensed","extracondensed","condensed","semicondensed","normal","semiexpanded","expanded","extraexpanded","ultraexpanded","bolditalic"]);return str.split(/[- ,+]+/g).filter(tok=>!keywords.has(tok.toLowerCase())).join(" ")}function generateFont({alias,local,path,fallback,style,ultimate},src,localFontPath,useFallback=!0,usePath=!0,append=""){var result={style:null,ultimate:null};if(local){var extra=append?" "+append:"";for(const name of local)src.push(`local(${name}${extra})`)}return alias&&(local=substitutionMap.get(alias),alias=append||getStyleToAppend(style),Object.assign(result,generateFont(local,src,localFontPath,useFallback&&!fallback,usePath&&!path,alias))),style&&(result.style=style),ultimate&&(result.ultimate=ultimate),useFallback&&fallback&&(local=generateFont(substitutionMap.get(fallback),src,localFontPath,useFallback,usePath&&!path,append)["ultimate"],result.ultimate||=local),usePath&&path&&localFontPath&&src.push(`url(${localFontPath}${path})`),result}function getFontSubstitution(systemFontCache,idFactory,localFontPath,baseFontName,standardFontName,type){if(baseFontName.startsWith("InvalidPDFjsFont_"))return null;type=baseFontName=normalizeFontName(baseFontName="TrueType"!==type&&"Type1"!==type||!/^[A-Z]{6}\+/.test(baseFontName)?baseFontName:baseFontName.slice(7));let substitutionInfo=systemFontCache.get(type);if(!substitutionInfo){let substitution=substitutionMap.get(baseFontName);if(!substitution)for(var[alias,subst]of fontAliases)if(baseFontName.startsWith(alias)){baseFontName=""+subst+baseFontName.substring(alias.length),substitution=substitutionMap.get(baseFontName);break}let mustAddBaseFont=!1;substitution||(substitution=substitutionMap.get(standardFontName),mustAddBaseFont=!0);standardFontName=idFactory.getDocId()+"_s"+idFactory.createFontId();if(substitution){idFactory=[];mustAddBaseFont&&validateFontName(baseFontName)&&idFactory.push(`local(${baseFontName})`);const{style,ultimate}=generateFont(substitution,idFactory,localFontPath);var localFontPath=null===ultimate,fallback=localFontPath?"":","+ultimate;substitutionInfo={css:`"${getFamilyName(baseFontName)}",`+standardFontName+fallback,guessFallback:localFontPath,loadedName:standardFontName,baseFontName:baseFontName,src:idFactory.join(","),style:style}}else{if(!validateFontName(baseFontName))return warn("Cannot substitute the font because of its name: "+baseFontName),systemFontCache.set(type,null),null;fallback=/bold/gi.test(baseFontName),localFontPath=/oblique|italic/gi.test(baseFontName);const style=fallback&&localFontPath&&BOLDITALIC||fallback&&BOLD||localFontPath&&ITALIC||NORMAL;substitutionInfo={css:`"${getFamilyName(baseFontName)}",`+standardFontName,guessFallback:!0,loadedName:standardFontName,baseFontName:baseFontName,src:`local(${baseFontName})`,style:style}}systemFontCache.set(type,substitutionInfo)}return substitutionInfo}const MIN_IMAGE_DIM=2048,MAX_IMAGE_DIM=65537,MAX_ERROR=128;class ImageResizer{constructor(imgData,isMask){this._imgData=imgData,this._isMask=isMask}static needsToBeResized(width,height){var MAX_DIM,area;return!(width<=this._goodSquareLength&&height<=this._goodSquareLength)&&(MAX_DIM=this["MAX_DIM"],MAX_DIMthis.MAX_AREA:!(area>2)}static _areGoodDims(width,height){try{var canvas=new OffscreenCanvas(width,height),ctx=canvas.getContext("2d"),opacity=(ctx.fillRect(0,0,1,1),ctx.getImageData(0,0,1,1).data[3]);return canvas.width=canvas.height=1,0!==opacity}catch{return!1}}static _guessMax(start,end,tolerance,defaultHeight){for(;start+tolerance+1>3,rowSize=3+rowLen&-4;if(rowLen!=rowSize){var newData=new Uint8Array(rowSize*height);let k=0;for(let i=0,ii=height*rowLen;i>>8,data[length++]=255&code)}}else{if(!ArrayBuffer.isView(input))throw new Error("Invalid data format, must be a string or TypedArray.");data=input.slice(),length=data.byteLength}var blockCounts=length>>2,tailLength=length-4*blockCounts,dataUint32=new Uint32Array(data.buffer,0,blockCounts);let k1=0,k2,h1=this.h1,h2=this.h2;var C1=3432918353,C2=461845907,C1_LOW=C1&MASK_LOW,C2_LOW=C2&MASK_LOW;for(let i=0;i>>17)*C2&MASK_HIGH|k1*C2_LOW&MASK_LOW,h1=5*(h1=(h1^=k1)<<13|h1>>>19)+3864292196):(k2=(k2=(k2=(k2=dataUint32[i])*C1&MASK_HIGH|k2*C1_LOW&MASK_LOW)<<15|k2>>>17)*C2&MASK_HIGH|k2*C2_LOW&MASK_LOW,h2=5*(h2=(h2^=k2)<<13|h2>>>19)+3864292196);switch(k1=0,tailLength){case 3:k1^=data[4*blockCounts+2]<<16;case 2:k1^=data[4*blockCounts+1]<<8;case 1:k1=(k1=(k1=(k1^=data[4*blockCounts])*C1&MASK_HIGH|k1*C1_LOW&MASK_LOW)<<15|k1>>>17)*C2&MASK_HIGH|k1*C2_LOW&MASK_LOW,1&blockCounts?h1^=k1:h2^=k1}this.h1=h1,this.h2=h2}hexdigest(){var h1=this.h1,h2=this.h2,h1=3981806797*(h1^=h2>>>1)&MASK_HIGH|36045*h1&MASK_LOW;return h1=444984403*(h1^=(h2=4283543511*h2&MASK_HIGH|(2950163797*(h2<<16|h1>>>16)&MASK_HIGH)>>>16)>>>1)&MASK_HIGH|60499*h1&MASK_LOW,((h1^=(h2=3301882366*h2&MASK_HIGH|(3120437893*(h2<<16|h1>>>16)&MASK_HIGH)>>>16)>>>1)>>>0).toString(16).padStart(8,"0")+(h2>>>0).toString(16).padStart(8,"0")}}function addState(parentState,pattern,checkFn,iterateFn,processFn){let state=parentState;for(let i=0,ii=pattern.length-1;i=ii)break}!(state=(state||InitialState)[fnArray[i]])||Array.isArray(state)?i++:(context.iCurr=i,i++,state=(state.checkFn&&!(0,state.checkFn)(context)||(match=state),null))}this.state=state,this.match=match,this.lastProcessed=i}else this.lastProcessed=ii}flush(){for(;this.match;){var length=this.queue.fnArray.length;this.lastProcessed=(0,this.match.processFn)(this.context,length),this.match=null,this.state=null,this._optimize()}}reset(){this.state=null,this.match=null,this.lastProcessed=0}}class OperatorList{static CHUNK_SIZE=1e3;static CHUNK_SIZE_ABOUT=this.CHUNK_SIZE-5;constructor(intent=0,streamSink){this._streamSink=streamSink,this.fnArray=[],this.argsArray=[],this.optimizer=new(!streamSink||intent&RenderingIntentFlag.OPLIST?NullOptimizer:QueueOptimizer)(this),this.dependencies=new Set,this._totalLength=0,this.weight=0,this._resolved=streamSink?null:Promise.resolve()}set isOffscreenCanvasSupported(value){this.optimizer.isOffscreenCanvasSupported=value}get length(){return this.argsArray.length}get ready(){return this._resolved||this._streamSink.ready}get totalLength(){return this._totalLength+this.length}addOp(fn,args){this.optimizer.push(fn,args),this.weight++,this._streamSink&&(this.weight>=OperatorList.CHUNK_SIZE||this.weight>=OperatorList.CHUNK_SIZE_ABOUT&&(fn===OPS.restore||fn===OPS.endText))&&this.flush()}addImageOps(fn,args,optionalContent){void 0!==optionalContent&&this.addOp(OPS.beginMarkedContentProps,["OC",optionalContent]),this.addOp(fn,args),void 0!==optionalContent&&this.addOp(OPS.endMarkedContent,[])}addDependency(dependency){this.dependencies.has(dependency)||(this.dependencies.add(dependency),this.addOp(OPS.dependency,[dependency]))}addDependencies(dependencies){for(const dependency of dependencies)this.addDependency(dependency)}addOpList(opList){if(opList instanceof OperatorList){for(const dependency of opList.dependencies)this.dependencies.add(dependency);for(let i=0,ii=opList.length;i>3)*height,actualLength=imgArray.byteLength;let data,i;if(!imageIsFromDecodeStream||inverseDecode&&!(computedLength===actualLength)?inverseDecode?((data=new Uint8Array(computedLength)).set(imgArray),data.fill(255,actualLength)):data=new Uint8Array(imgArray):data=imgArray,inverseDecode)for(i=0;i>7&1,output[i+1]=buf>>6&1,output[i+2]=buf>>5&1,output[i+3]=buf>>4&1,output[i+4]=buf>>3&1,output[i+5]=buf>>2&1,output[i+6]=buf>>1&1,output[i+7]=1&buf,i+=8;if(i>=1}}else{let bits=0;for(buf=0,i=0,ii=length;i>remainingBits;value<0?value=0:value>max&&(value=max),output[i]=value,buf&=(1<mask[1+maskOffset]){opacity=255;break}}alphaBuf[i]=opacity}}if(alphaBuf)for(i=0,j=3,ii=width*actualHeight;i>3,mustBeResized=isOffscreenCanvasSupported&&ImageResizer.needsToBeResized(drawWidth,drawHeight);if(!forceRGBA){let kind;if("DeviceGray"===this.colorSpace.name&&1===bpc?kind=ImageKind.GRAYSCALE_1BPP:"DeviceRGB"!==this.colorSpace.name||8!==bpc||this.needsDecode||(kind=ImageKind.RGB_24BPP),kind&&!this.smask&&!this.mask&&drawWidth===originalWidth&&drawHeight===originalHeight){const data=this.getImageBytes(originalHeight*numComps,{});if(isOffscreenCanvasSupported)return mustBeResized?ImageResizer.createImage({data:data,kind:kind,width:drawWidth,height:drawHeight,interpolate:this.interpolate},this.needsDecode):this.createBitmap(kind,originalWidth,originalHeight,data);if(imgData.kind=kind,imgData.data=data,this.needsDecode){assert(kind===ImageKind.GRAYSCALE_1BPP,"PDFImage.createImageData: The image must be grayscale.");var buffer=imgData.data;for(let i=0,ii=buffer.length;i>3),{internal:!0}),comps=this.getComponents(numComps);let i,length;if(1===bpc)if(length=width*height,this.needsDecode)for(i=0;i>3)*h),decode=dict.getArray("D","Decode");if(this.parsingType3Font)return(imgData=PDFImage.createRawMask({imgArray:imgArray,width:w,height:h,imageIsFromDecodeStream:image instanceof DecodeStream,inverseDecode:0((imgData=await imageObj.createImageData(!1,this.options.isOffscreenCanvasSupported)).dataLen=imgData.bitmap?imgData.width*imgData.height*4:imgData.data.length,imgData.ref=imageRef,cacheGlobally&&this.globalImageCache.addByteSize(imageRef,imgData.dataLen),this._sendImgData(objId,imgData,cacheGlobally))).catch(reason=>(warn(`Unable to decode image "${objId}": "${reason}".`),this._sendImgData(objId,null,cacheGlobally))),cacheKey){const cacheData={fn:OPS.paintImageXObject,args:args,optionalContent:optionalContent};localImageCache.set(cacheKey,imageRef,cacheData),imageRef&&(this._regionalImageCache.set(null,imageRef,cacheData),cacheGlobally)&&this.globalImageCache.setData(imageRef,{objId:objId,fn:OPS.paintImageXObject,args:args,optionalContent:optionalContent,byteSize:0})}}}else warn("Image dimensions are missing, or not numbers.")}handleSMask(smask,resources,operatorList,task,stateManager,localColorSpaceCache){var smaskContent=smask.get("G"),smaskOptions={subtype:smask.get("S").name,backdrop:smask.get("BC")},smask=smask.get("TR");if(isPDFFunction(smask)){var transferFn=this._pdfFunctionFactory.create(smask),transferMap=new Uint8Array(256),tmp=new Float32Array(1);for(let i=0;i<256;i++)tmp[0]=i/255,transferFn(tmp,0,tmp,0),transferMap[i]=255*tmp[0]|0;smaskOptions.transferMap=transferMap}return this.buildFormXObject(resources,smaskContent,smaskOptions,operatorList,task,stateManager.state.clone(),localColorSpaceCache)}handleTransferFunction(tr){let transferArray;if(Array.isArray(tr))transferArray=tr;else{if(!isPDFFunction(tr))return null;transferArray=[tr]}var transferMaps=[];let numFns=0,numEffectfulFns=0;for(const entry of transferArray){var transferObj=this.xref.fetchIfRef(entry);if(numFns++,isName(transferObj,"Identity"))transferMaps.push(null);else{if(!isPDFFunction(transferObj))return null;var transferFn=this._pdfFunctionFactory.create(transferObj),transferMap=new Uint8Array(256),tmp=new Float32Array(1);for(let j=0;j<256;j++)tmp[0]=j/255,transferFn(tmp,0,tmp,0),transferMap[j]=255*tmp[0]|0;transferMaps.push(transferMap),numEffectfulFns++}}return 1!==numFns&&4!==numFns||0===numEffectfulFns?null:transferMaps}handleTilingType(fn,color,resources,pattern,patternDict,operatorList,task,localTilingPatternCache){const tilingOpList=new OperatorList;resources=Dict.merge({xref:this.xref,dictArray:[patternDict.get("Resources"),resources]});return this.getOperatorList({stream:pattern,task:task,resources:resources,operatorList:tilingOpList}).then(function(){var operatorListIR=tilingOpList.getIR(),tilingPatternIR=getTilingPatternIR(operatorListIR,patternDict,color);operatorList.addDependencies(tilingOpList.dependencies),operatorList.addOp(fn,tilingPatternIR),patternDict.objId&&localTilingPatternCache.set(null,patternDict.objId,{operatorListIR:operatorListIR,dict:patternDict})}).catch(reason=>{if(!(reason instanceof AbortException)){if(!this.options.ignoreErrors)throw reason;warn(`handleTilingType - ignoring pattern: "${reason}".`)}})}async handleSetFont(resources,fontArgs,fontRef,operatorList,task,state,fallbackFontDict=null,cssFontInfo=null){fontArgs=fontArgs?.[0]instanceof Name?fontArgs[0].name:null;let translated=await this.loadFont(fontArgs,fontRef,resources,fallbackFontDict,cssFontInfo);if(translated.font.isType3Font)try{await translated.loadType3Data(this,resources,task),operatorList.addDependencies(translated.type3Dependencies)}catch(reason){translated=new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont("Type3 font load error: "+reason),dict:translated.font,evaluatorOptions:this.options})}return state.font=translated.font,translated.send(this.handler),translated.loadedName}handleText(chars,state){var font=state.font,chars=font.charsToGlyphs(chars);return font.data&&(!!(state.textRenderingMode&TextRenderingMode.ADD_TO_PATH_FLAG)||"Pattern"===state.fillColorSpace.name||font.disableFontFace||this.options.disableFontFace)&&PartialEvaluator.buildFontPaths(font,chars,this.handler,this.options),chars}ensureStateFont(state){if(!state.font){state=new FormatError("Missing setFont (Tf) operator before text rendering operator.");if(!this.options.ignoreErrors)throw state;warn(`ensureStateFont: "${state}".`)}}async setGState({resources,gState,operatorList,cacheKey,task,stateManager,localGStateCache,localColorSpaceCache}){var gStateRef=gState.objId;let isSimpleGState=!0;const gStateObj=[];let promise=Promise.resolve();for(const key of gState.getKeys()){const value=gState.get(key);switch(key){case"Type":break;case"LW":case"LC":case"LJ":case"ML":case"D":case"RI":case"FL":case"CA":case"ca":gStateObj.push([key,value]);break;case"Font":isSimpleGState=!1,promise=promise.then(()=>this.handleSetFont(resources,null,value[0],operatorList,task,stateManager.state).then(function(loadedName){operatorList.addDependency(loadedName),gStateObj.push([key,[loadedName,value[1]]])}));break;case"BM":gStateObj.push([key,normalizeBlendMode(value)]);break;case"SMask":isName(value,"None")?gStateObj.push([key,!1]):value instanceof Dict?(isSimpleGState=!1,promise=promise.then(()=>this.handleSMask(value,resources,operatorList,task,stateManager,localColorSpaceCache)),gStateObj.push([key,!0])):warn("Unsupported SMask type");break;case"TR":var transferMaps=this.handleTransferFunction(value);gStateObj.push([key,transferMaps]);break;case"OP":case"op":case"OPM":case"BG":case"BG2":case"UCR":case"UCR2":case"TR2":case"HT":case"SM":case"SA":case"AIS":case"TK":info("graphic state operator "+key);break;default:info("Unknown graphic state operator "+key)}}await promise,0new TranslatedFont({loadedName:"g_font_error",font:new ErrorFont(`Font "${fontName}" is not available.`),dict:font,evaluatorOptions:this.options});let fontRef;if(font?font instanceof Ref&&(fontRef=font):(resources=resources.get("Font"))&&(fontRef=resources.getRaw(fontName)),fontRef){if(this.parsingType3Font&&this.type3FontRefs.has(fontRef))return errorFont();if(this.fontCache.has(fontRef))return this.fontCache.get(fontRef);font=this.xref.fetchIfRef(fontRef)}if(!(font instanceof Dict)){if(!this.options.ignoreErrors&&!this.parsingType3Font)return warn(`Font "${fontName}" is not available.`),errorFont();warn(`Font "${fontName}" is not available -- attempting to fallback to a default font.`),font=fallbackFontDict||PartialEvaluator.fallbackFontDict}if(font.cacheKey&&this.fontCache.has(font.cacheKey))return this.fontCache.get(font.cacheKey);const{promise,resolve}=Promise.withResolvers();let preEvaluatedFont;try{(preEvaluatedFont=this.preEvaluateFont(font)).cssFontInfo=cssFontInfo}catch(reason){return warn(`loadFont - preEvaluateFont failed: "${reason}".`),errorFont()}var{descriptor:resources,hash:fallbackFontDict}=preEvaluatedFont,cssFontInfo=fontRef instanceof Ref;let fontID;if(fallbackFontDict&&resources instanceof Dict){errorFont=resources.fontAliases||=Object.create(null);if(errorFont[fallbackFontDict]){resources=errorFont[fallbackFontDict].aliasRef;if(cssFontInfo&&resources&&this.fontCache.has(resources))return this.fontCache.putAlias(fontRef,resources),this.fontCache.get(fontRef)}else errorFont[fallbackFontDict]={fontID:this.idFactory.createFontId()};cssFontInfo&&(errorFont[fallbackFontDict].aliasRef=fontRef),fontID=errorFont[fallbackFontDict].fontID}else fontID=this.idFactory.createFontId();return assert(fontID?.startsWith("f"),'The "fontID" must be (correctly) defined.'),cssFontInfo?this.fontCache.put(fontRef,promise):(font.cacheKey="cacheKey_"+fontID,this.fontCache.put(font.cacheKey,promise)),font.loadedName=this.idFactory.getDocId()+"_"+fontID,this.translateFont(preEvaluatedFont).then(translatedFont=>{resolve(new TranslatedFont({loadedName:font.loadedName,font:translatedFont,dict:font,evaluatorOptions:this.options}))}).catch(reason=>{warn(`loadFont - translateFont failed: "${reason}".`),resolve(new TranslatedFont({loadedName:font.loadedName,font:new ErrorFont(reason instanceof Error?reason.message:reason),dict:font,evaluatorOptions:this.options}))}),promise}buildPath(operatorList,fn,args,parsingText=!1){var lastIndex=operatorList.length-1;if(args=args||[],lastIndex<0||operatorList.fnArray[lastIndex]!==OPS.constructPath){parsingText&&(warn(`Encountered path operator "${fn}" inside of a text object.`),operatorList.addOp(OPS.save,null));let minMax;switch(fn){case OPS.rectangle:var x=args[0]+args[2],y=args[1]+args[3];minMax=[Math.min(args[0],x),Math.min(args[1],y),Math.max(args[0],x),Math.max(args[1],y)];break;case OPS.moveTo:case OPS.lineTo:minMax=[args[0],args[1],args[0],args[1]];break;default:minMax=[1/0,1/0,-1/0,-1/0]}operatorList.addOp(OPS.constructPath,[[fn],args,minMax]),parsingText&&operatorList.addOp(OPS.restore,null)}else{var parsingText=operatorList.argsArray[lastIndex],minMax=(parsingText[0].push(fn),parsingText[1].push(...args),parsingText[2]);switch(fn){case OPS.rectangle:const x=args[0]+args[2],y=args[1]+args[3];minMax[0]=Math.min(minMax[0],args[0],x),minMax[1]=Math.min(minMax[1],args[1],y),minMax[2]=Math.max(minMax[2],args[0],x),minMax[3]=Math.max(minMax[3],args[1],y);break;case OPS.moveTo:case OPS.lineTo:minMax[0]=Math.min(minMax[0],args[0]),minMax[1]=Math.min(minMax[1],args[1]),minMax[2]=Math.max(minMax[2],args[0]),minMax[3]=Math.max(minMax[3],args[1])}}}parseColorSpace({cs,resources,localColorSpaceCache}){return ColorSpace.parseAsync({cs:cs,xref:this.xref,resources:resources,pdfFunctionFactory:this._pdfFunctionFactory,localColorSpaceCache:localColorSpaceCache}).catch(reason=>{if(reason instanceof AbortException)return null;if(this.options.ignoreErrors)return warn(`parseColorSpace - ignoring ColorSpace: "${reason}".`),null;throw reason})}parseShading({shading,resources,localColorSpaceCache,localShadingPatternCache}){let id=localShadingPatternCache.get(shading);if(!id){let patternIR;try{var shadingFill=Pattern.parseShading(shading,this.xref,resources,this._pdfFunctionFactory,localColorSpaceCache);patternIR=shadingFill.getIR()}catch(reason){if(reason instanceof AbortException)return null;if(this.options.ignoreErrors)return warn(`parseShading - ignoring shading: "${reason}".`),localShadingPatternCache.set(shading,null),null;throw reason}id="pattern_"+this.idFactory.createObjId(),this.parsingType3Font&&(id=this.idFactory.getDocId()+"_type3_"+id),localShadingPatternCache.set(shading,id),this.parsingType3Font?this.handler.send("commonobj",[id,"Pattern",patternIR]):this.handler.send("obj",[id,this.pageIndex,"Pattern",patternIR])}return id}handleColorN(operatorList,fn,args,cs,patterns,resources,task,localColorSpaceCache,localTilingPatternCache,localShadingPatternCache){var patternName=args.pop();if(patternName instanceof Name){var patterns=patterns.getRaw(patternName.name),localTilingPattern=patterns instanceof Ref&&localTilingPatternCache.getByRef(patterns);if(localTilingPattern)try{var color=cs.base?cs.base.getRgb(args,0):null,tilingPatternIR=getTilingPatternIR(localTilingPattern.operatorListIR,localTilingPattern.dict,color);return void operatorList.addOp(fn,tilingPatternIR)}catch{}localTilingPattern=this.xref.fetchIfRef(patterns);if(localTilingPattern){tilingPatternIR=localTilingPattern instanceof BaseStream?localTilingPattern.dict:localTilingPattern,color=tilingPatternIR.get("PatternType");if(color===PatternType.TILING){const color=cs.base?cs.base.getRgb(args,0):null;return this.handleTilingType(fn,color,resources,localTilingPattern,tilingPatternIR,operatorList,task,localTilingPatternCache)}if(color===PatternType.SHADING)return patterns=tilingPatternIR.get("Shading"),void((cs=this.parseShading({shading:patterns,resources:resources,localColorSpaceCache:localColorSpaceCache,localShadingPatternCache:localShadingPatternCache}))&&(args=tilingPatternIR.getArray("Matrix"),operatorList.addOp(fn,["Shading",cs,args])));throw new FormatError("Unknown PatternType: "+color)}}throw new FormatError("Unknown PatternName: "+patternName)}_parseVisibilityExpression(array,nestingCounter,currentResult){if(10<++nestingCounter)warn("Visibility expression is too deeply nested");else{var length=array.length,operator=this.xref.fetchIfRef(array[0]);if(length<2||!(operator instanceof Name))warn("Invalid visibility expression");else{switch(operator.name){case"And":case"Or":case"Not":currentResult.push(operator.name);break;default:return void warn(`Invalid operator ${operator.name} in visibility expression`)}for(let i=1;i{operatorList.addOp(OPS.beginMarkedContentProps,["OC",data])}).catch(reason=>{if(!(reason instanceof AbortException)){if(!self.options.ignoreErrors)throw reason;warn(`getOperatorList - ignoring beginMarkedContentProps: "${reason}".`),operatorList.addOp(OPS.beginMarkedContentProps,["OC",null])}}));args=[args[0].name,args[1]instanceof Dict?args[1].get("MCID"):null];break;case OPS.beginMarkedContent:case OPS.endMarkedContent:default:if(null!==args){for(i=0,ii=args.length;i{if(!(reason instanceof AbortException)){if(!this.options.ignoreErrors)throw reason;warn(`getOperatorList - ignoring errors during "${task.name}" `+`task: "${reason}".`),closePendingRestoreOPS()}})}getTextContent({stream,task,resources,stateManager=null,includeMarkedContent=!1,sink,seenStyles=new Set,viewBox,markedContentData=null,disableNormalization=!1,keepWhiteSpace=!1}){resources||=Dict.empty,stateManager||=new StateManager(new TextState),includeMarkedContent&&(markedContentData||={level:0});const textContent={items:[],styles:Object.create(null)},textContentItem={initialized:!1,str:[],totalWidth:0,totalHeight:0,width:0,height:0,vertical:!1,prevTransform:null,textAdvanceScale:0,spaceInFlowMin:0,spaceInFlowMax:0,trackingSpaceMin:1/0,negativeSpaceMax:-1/0,notASpace:-1/0,transform:null,fontName:null,hasEOL:!1},twoLastChars=[" "," "];let twoLastCharsPos=0;function saveLastChar(char){var nextPos=(twoLastCharsPos+1)%2,ret=" "!==twoLastChars[twoLastCharsPos]&&" "===twoLastChars[nextPos];return twoLastChars[twoLastCharsPos]=char,twoLastCharsPos=nextPos,!keepWhiteSpace&&ret}function shouldAddWhitepsace(){return!keepWhiteSpace&&" "!==twoLastChars[twoLastCharsPos]&&" "===twoLastChars[(twoLastCharsPos+1)%2]}function resetLastChars(){twoLastChars[0]=twoLastChars[1]=" ",twoLastCharsPos=0}const TRACKING_SPACE_FACTOR=.102,NOT_A_SPACE_FACTOR=.03,NEGATIVE_SPACE_FACTOR=-.2,SPACE_IN_FLOW_MIN_FACTOR=.102,SPACE_IN_FLOW_MAX_FACTOR=.6,VERTICAL_SHIFT_RATIO=.25,self=this,xref=this.xref,showSpacedTextBuffer=[];let xobjs=null;const emptyXObjectCache=new LocalImageCache,emptyGStateCache=new LocalGStateCache,preprocessor=new EvaluatorPreprocessor(stream,xref,stateManager);let textState;function pushWhitespace({width=0,height=0,transform=textContentItem.prevTransform,fontName=textContentItem.fontName}){textContent.items.push({str:" ",dir:"ltr",width:width,height:height,transform:transform,fontName:fontName,hasEOL:!1})}function getCurrentTextTransform(){var font=textState.font,tsm=[textState.fontSize*textState.textHScale,0,0,textState.fontSize,0,textState.textRise];return font.isType3Font&&(textState.fontSize<=1||font.isCharBBox)&&!isArrayEqual(textState.fontMatrix,FONT_IDENTITY_MATRIX)&&0<(font=font.bbox[3]-font.bbox[1])&&(tsm[3]*=font*textState.fontMatrix[3]),Util.transform(textState.ctm,Util.transform(textState.textMatrix,tsm))}async function handleSetFont(fontName,fontRef){fontName=await self.loadFont(fontName,fontRef,resources);if(fontName.font.isType3Font)try{await fontName.loadType3Data(self,resources,task)}catch{}textState.loadedName=fontName.loadedName,textState.font=fontName.font,textState.fontMatrix=fontName.font.fontMatrix||FONT_IDENTITY_MATRIX}function applyInverseRotation(x,y,matrix){var scale=Math.hypot(matrix[0],matrix[1]);return[(matrix[0]*x+matrix[1]*y)/scale,(matrix[2]*x+matrix[3]*y)/scale]}function compareWithLastPosition(glyphWidth){var currentTransform=getCurrentTextTransform();let posX=currentTransform[4],posY=currentTransform[5];if(textState.font?.vertical){if(posXviewBox[2]||posY+glyphWidthviewBox[3])return}else if(posX+glyphWidthviewBox[2]||posYviewBox[3])return;if(textState.font&&textContentItem.prevTransform){let lastPosX=textContentItem.prevTransform[4],lastPosY=textContentItem.prevTransform[5];if(lastPosX!==posX||lastPosY!==posY){let rotate=-1;switch(currentTransform[0]&&0===currentTransform[1]&&0===currentTransform[2]?rotate=0.5*textContentItem.width?appendEOL:(resetLastChars(),flushTextContentItem))():Math.abs(advanceX)>textContentItem.width?appendEOL():(advanceY<=textOrientation*textContentItem.notASpace&&resetLastChars(),advanceY<=textOrientation*textContentItem.trackingSpaceMin?shouldAddWhitepsace()?(resetLastChars(),flushTextContentItem(),pushWhitespace({height:Math.abs(advanceY)})):textContentItem.height+=advanceY:addFakeSpaces(advanceY,textContentItem.prevTransform,textOrientation)||(0===textContentItem.str.length?(resetLastChars(),pushWhitespace({height:Math.abs(advanceY)})):textContentItem.height+=advanceY),Math.abs(advanceX)>textContentItem.width*VERTICAL_SHIFT_RATIO&&flushTextContentItem())}else{const advanceX=(posX-lastPosX)/textContentItem.textAdvanceScale,advanceY=posY-lastPosY,textOrientation=Math.sign(textContentItem.width);advanceX.5*textContentItem.height?appendEOL:(resetLastChars(),flushTextContentItem))():Math.abs(advanceY)>textContentItem.height?appendEOL():(advanceX<=textOrientation*textContentItem.notASpace&&resetLastChars(),advanceX<=textOrientation*textContentItem.trackingSpaceMin?shouldAddWhitepsace()?(resetLastChars(),flushTextContentItem(),pushWhitespace({width:Math.abs(advanceX)})):textContentItem.width+=advanceX:addFakeSpaces(advanceX,textContentItem.prevTransform,textOrientation)||(0===textContentItem.str.length?(resetLastChars(),pushWhitespace({width:Math.abs(advanceX)})):textContentItem.width+=advanceX),Math.abs(advanceY)>textContentItem.height*VERTICAL_SHIFT_RATIO&&flushTextContentItem())}}}return 1}function buildTextContentItem({chars,extraSpacing}){var font=textState.font;if(chars){var glyphs=font.charsToGlyphs(chars),scale=textState.fontMatrix[0]*textState.fontSize;for(let i=0,ii=glyphs.length;i=sink.desiredSize){stop=!0;break}}stop?next(deferred):(flushTextContentItem(),enqueueChunk(),resolve())}).catch(reason=>{if(!(reason instanceof AbortException)){if(!this.options.ignoreErrors)throw reason;warn(`getTextContent - ignoring errors during "${task.name}" `+`task: "${reason}".`),flushTextContentItem(),enqueueChunk()}})}async extractDataStructures(dict,properties){var xref=this.xref;let cidToGidBytes;var toUnicodePromise=this.readToUnicode(properties.toUnicode);if(properties.composite){var cidSystemInfo=dict.get("CIDSystemInfo");cidSystemInfo instanceof Dict&&(properties.cidSystemInfo={registry:stringToPDFString(cidSystemInfo.get("Registry")),ordering:stringToPDFString(cidSystemInfo.get("Ordering")),supplement:cidSystemInfo.get("Supplement")});try{var cidToGidMap=dict.get("CIDToGIDMap");cidToGidMap instanceof BaseStream&&(cidToGidBytes=cidToGidMap.getBytes())}catch(ex){if(!this.options.ignoreErrors)throw ex;warn(`extractDataStructures - ignoring CIDToGIDMap data: "${ex}".`)}}var differences=[];let baseEncodingName=null,encoding;if(dict.has("Encoding")){if((encoding=dict.get("Encoding"))instanceof Dict){if(baseEncodingName=(baseEncodingName=encoding.get("BaseEncoding"))instanceof Name?baseEncodingName.name:null,encoding.has("Differences")){let index=0;for(const entry of encoding.get("Differences")){var data=xref.fetchIfRef(entry);if("number"==typeof data)index=data;else{if(!(data instanceof Name))throw new FormatError("Invalid entry in 'Differences' array: "+data);differences[index++]=data.name}}}}else if(encoding instanceof Name)baseEncodingName=encoding.name;else{cidSystemInfo="Encoding is not a Name nor a Dict";if(!this.options.ignoreErrors)throw new FormatError(cidSystemInfo);warn(cidSystemInfo)}"MacRomanEncoding"!==baseEncodingName&&"MacExpertEncoding"!==baseEncodingName&&"WinAnsiEncoding"!==baseEncodingName&&(baseEncodingName=null)}var isSymbolicFont,cidToGidMap=!properties.file||properties.isInternalFont,cidSystemInfo=getSymbolsFonts()[properties.name],isNonsymbolicFont=((baseEncodingName=baseEncodingName&&cidToGidMap&&cidSystemInfo?null:baseEncodingName)?properties.defaultEncoding=getEncoding(baseEncodingName):(isSymbolicFont=!!(properties.flags&FontFlags.Symbolic),isNonsymbolicFont=!!(properties.flags&FontFlags.Nonsymbolic),encoding=StandardEncoding,"TrueType"!==properties.type||isNonsymbolicFont||(encoding=WinAnsiEncoding),(isSymbolicFont||cidSystemInfo)&&(encoding=MacRomanEncoding,cidToGidMap)&&(/Symbol/i.test(properties.name)?encoding=SymbolSetEncoding:/Dingbats/i.test(properties.name)?encoding=ZapfDingbatsEncoding:/Wingdings/i.test(properties.name)&&(encoding=WinAnsiEncoding)),properties.defaultEncoding=encoding),properties.differences=differences,properties.baseEncodingName=baseEncodingName,properties.hasEncoding=!!baseEncodingName||0>1;0==glyphID&&!toUnicode.has(code)||(result[code]=glyphID)}return result}extractWidths(dict,descriptor,properties){var xref=this.xref;let glyphsWidths=[],defaultWidth=0;var glyphsVMetrics=[];let defaultVMetrics;if(properties.composite){var dw=dict.get("DW"),widths=(defaultWidth=Number.isInteger(dw)?dw:1e3,dict.get("W"));if(Array.isArray(widths))for(let i=0,ii=widths.length;i{var glyphStream=charProcs.get(key);const operatorList=new OperatorList;return type3Evaluator.getOperatorList({stream:glyphStream,task:task,resources:fontResources,operatorList:operatorList}).then(()=>{operatorList.fnArray[0]===OPS.setCharWidthAndBounds&&this._removeType3ColorOperators(operatorList,fontBBoxSize),charProcOperatorList[key]=operatorList.getIR();for(const dependency of operatorList.dependencies)type3Dependencies.add(dependency)}).catch(function(reason){warn(`Type3 font resource "${key}" is not available.`);var dummyOperatorList=new OperatorList;charProcOperatorList[key]=dummyOperatorList.getIR()})});this.type3Loaded=loadCharProcsPromise.then(()=>{translatedFont.charProcOperatorList=charProcOperatorList,this._bbox&&(translatedFont.isCharBBox=!0,translatedFont.bbox=this._bbox)})}return this.type3Loaded}_removeType3ColorOperators(operatorList,fontBBoxSize=NaN){var charBBox=Util.normalizeRect(operatorList.argsArray[0].slice(2)),width=charBBox[2]-charBBox[0],height=charBBox[3]-charBBox[1],charBBoxSize=Math.hypot(width,height);0==width||0==height?(operatorList.fnArray.splice(0,1),operatorList.argsArray.splice(0,1)):(0===fontBBoxSize||10<=Math.round(charBBoxSize/fontBBoxSize))&&(this._bbox||(this._bbox=[1/0,1/0,-1/0,-1/0]),this._bbox[0]=Math.min(this._bbox[0],charBBox[0]),this._bbox[1]=Math.min(this._bbox[1],charBBox[1]),this._bbox[2]=Math.max(this._bbox[2],charBBox[2]),this._bbox[3]=Math.max(this._bbox[3],charBBox[3]));let i=0,ii=operatorList.length;for(;i=OPS.moveTo&&fn<=OPS.endPath,opSpec.variableArgs)argsLength>numArgs&&info(`Command ${cmd}: expected [0, ${numArgs}] args, `+`but received ${argsLength} args.`);else{if(argsLength!==numArgs){for(var nonProcessedArgs=this.nonProcessedArgs;argsLength>numArgs;)nonProcessedArgs.push(args.shift()),argsLength--;for(;argsLengthEvaluatorPreprocessor.MAX_INVALID_PATH_OPS)throw new FormatError("Invalid "+opSpec);warn("Skipping "+opSpec),null!==args&&(args.length=0);continue}}return this.preprocessCommand(fn,args),operation.fn=fn,operation.args=args,!0}if(obj===EOF)return!1;if(null!==obj&&((args=null===args?[]:args).push(obj),33numberToString(c/255)).join(" ")+" "+(isFill?"rg":"RG")}function createDefaultAppearance({fontSize,fontName,fontColor}){return`/${escapePDFName(fontName)} ${fontSize} Tf `+getPdfColor(fontColor,!0)}class FakeUnicodeFont{constructor(xref,fontFamily){this.xref=xref,this.widths=null,this.firstChar=1/0,this.lastChar=-1/0,this.fontFamily=fontFamily;xref=new OffscreenCanvas(1,1);this.ctxMeasure=xref.getContext("2d"),FakeUnicodeFont._fontNameId||(FakeUnicodeFont._fontNameId=1),this.fontName=Name.get(`InvalidPDFjsFont_${fontFamily}_`+FakeUnicodeFont._fontNameId++)}get fontDescriptorRef(){var fontDescriptor;return FakeUnicodeFont._fontDescriptorRef||((fontDescriptor=new Dict(this.xref)).set("Type",Name.get("FontDescriptor")),fontDescriptor.set("FontName",this.fontName),fontDescriptor.set("FontFamily","MyriadPro Regular"),fontDescriptor.set("FontBBox",[0,0,0,0]),fontDescriptor.set("FontStretch",Name.get("Normal")),fontDescriptor.set("FontWeight",400),fontDescriptor.set("ItalicAngle",0),FakeUnicodeFont._fontDescriptorRef=this.xref.getNewPersistentRef(fontDescriptor)),FakeUnicodeFont._fontDescriptorRef}get descendantFontRef(){var char,width,descendantFont=new Dict(this.xref),widths=(descendantFont.set("BaseFont",this.fontName),descendantFont.set("Type",Name.get("Font")),descendantFont.set("Subtype",Name.get("CIDFontType0")),descendantFont.set("CIDToGIDMap",Name.get("Identity")),descendantFont.set("FirstChar",this.firstChar),descendantFont.set("LastChar",this.lastChar),descendantFont.set("FontDescriptor",this.fontDescriptorRef),descendantFont.set("DW",1e3),[]);let currentChar=null,currentWidths=null;for([char,width]of[...this.widths.entries()].sort())currentChar?char===currentChar+currentWidths.length?currentWidths.push(width):(widths.push(currentChar,currentWidths),currentChar=char,currentWidths=[width]):(currentChar=char,currentWidths=[width]);currentChar&&widths.push(currentChar,currentWidths),descendantFont.set("W",widths);var cidSystemInfo=new Dict(this.xref);return cidSystemInfo.set("Ordering","Identity"),cidSystemInfo.set("Registry","Adobe"),cidSystemInfo.set("Supplement",0),descendantFont.set("CIDSystemInfo",cidSystemInfo),this.xref.getNewPersistentRef(descendantFont)}get baseFontRef(){var baseFont=new Dict(this.xref);return baseFont.set("BaseFont",this.fontName),baseFont.set("Type",Name.get("Font")),baseFont.set("Subtype",Name.get("Type0")),baseFont.set("Encoding",Name.get("Identity-H")),baseFont.set("DescendantFonts",[this.descendantFontRef]),baseFont.set("ToUnicode",Name.get("Identity-H")),this.xref.getNewPersistentRef(baseFont)}get resources(){var resources=new Dict(this.xref),font=new Dict(this.xref);return font.set(this.fontName.name,this.baseFontRef),resources.set("Font",font),resources}_createContext(){return this.widths=new Map,this.ctxMeasure.font="1000px "+this.fontFamily,this.ctxMeasure}createFontResources(text){var ctx=this._createContext();for(const line of text.split(/\r\n?|\n/))for(const char of line.split("")){var metrics,code=char.charCodeAt(0);this.widths.has(code)||(metrics=ctx.measureText(char),metrics=Math.ceil(metrics.width),this.widths.set(code,metrics),this.firstChar=Math.min(code,this.firstChar),this.lastChar=Math.max(code,this.lastChar))}return this.resources}static getFirstPositionInfo(rect,rotation,fontSize){var[rect,y1,x2,y2]=rect;let w=x2-rect,h=y2-y1;rotation%180!=0&&([w,h]=[h,w]);x2=LINE_FACTOR*fontSize,rect=LINE_DESCENT_FACTOR*fontSize;return{coords:[0,h+rect-x2],bbox:[0,0,w,h],matrix:0!==rotation?getRotationMatrix(rotation,h,x2):void 0}}createAppearance(text,rect,rotation,fontSize,bgColor,strokeAlpha){var ctx=this._createContext(),lines=[];let maxWidth=-1/0;for(const line of text.split(/\r\n?|\n/)){lines.push(line);var lineWidth=ctx.measureText(line).width;maxWidth=Math.max(maxWidth,lineWidth);for(const code of codePointIter(line)){var char=String.fromCodePoint(code),width=this.widths.get(code);void 0===width&&(char=ctx.measureText(char),width=Math.ceil(char.width),this.widths.set(code,width),this.firstChar=Math.min(code,this.firstChar),this.lastChar=Math.max(code,this.lastChar))}}maxWidth*=fontSize/1e3;var[text,rect,x2,y2]=rect;let w=x2-text,h=y2-rect,hscale=(rotation%180!=0&&([w,h]=[h,w]),1),vscale=(maxWidth>w&&(hscale=w/maxWidth),1);var x2=LINE_FACTOR*fontSize,text=LINE_DESCENT_FACTOR*fontSize,y2=x2*lines.length,rect=(y2>h&&(vscale=h/y2),Math.min(hscale,vscale)),y2=fontSize*rect,buffer=["q",`0 0 ${numberToString(w)} ${numberToString(h)} re W n`,"BT",`1 0 0 1 0 ${numberToString(h+text)} Tm 0 Tc `+getPdfColor(bgColor,!0),`/${this.fontName.name} ${numberToString(y2)} Tf`],fontSize=this["resources"],vShift=(1!==(strokeAlpha="number"==typeof strokeAlpha&&0<=strokeAlpha&&strokeAlpha<=1?strokeAlpha:1)&&(buffer.push("/R0 gs"),rect=new Dict(this.xref),(text=new Dict(this.xref)).set("ca",strokeAlpha),text.set("CA",strokeAlpha),text.set("Type",Name.get("ExtGState")),rect.set("R0",text),fontSize.set("ExtGState",rect)),numberToString(x2));for(const line of lines)buffer.push(`0 -${vShift} Td <${stringToUTF16HexString(line)}> Tj`);buffer.push("ET","Q");bgColor=buffer.join("\n"),y2=new Dict(this.xref),y2.set("Subtype",Name.get("Form")),y2.set("Type",Name.get("XObject")),y2.set("BBox",[0,0,w,h]),y2.set("Length",bgColor.length),y2.set("Resources",fontSize),rotation&&(strokeAlpha=getRotationMatrix(rotation,w,h),y2.set("Matrix",strokeAlpha)),text=new StringStream(bgColor);return text.dict=y2,text}}class NameOrNumberTree{constructor(root,xref,type){this.constructor===NameOrNumberTree&&unreachable("Cannot initialize NameOrNumberTree."),this.root=root,this.xref=xref,this._type=type}getAll(){var map=new Map;if(this.root)for(var xref=this.xref,processed=new RefSet,queue=(processed.put(this.root),[this.root]);0>1,kid=xref.fetchIfRef(kids[m]),limits=kid.get("Limits");if(keyxref.fetchIfRef(limits[1]))){kidsOrEntries=kid;break}l=1+m}}if(l>r)return null}var entries=kidsOrEntries.get(this._type);if(Array.isArray(entries)){let l=0,r=entries.length-2;for(;l<=r;){const tmp=l+r>>1,m=tmp+(1&tmp);var currentKey=xref.fetchIfRef(entries[m]);if(key{if("#x"===entity.substring(0,2))return String.fromCodePoint(parseInt(entity.substring(2),16));if("#"===entity.substring(0,1))return String.fromCodePoint(parseInt(entity.substring(1),10));switch(entity){case"lt":return"<";case"gt":return">";case"amp":return"&";case"quot":return'"';case"apos":return"'"}return this.onResolveEntity(entity)})}_parseContent(s,start){var attributes=[];let pos=start;function skipWs(){for(;pos"!==s[pos]&&"/"!==s[pos];)++pos;var name=s.substring(start,pos);for(skipWs();pos"!==s[pos]&&"/"!==s[pos]&&"?"!==s[pos];){skipWs();let attrName="",attrValue;for(;pos"!==s[pos]&&"?"!==s[pos]&&"/"!==s[pos];)++pos;for(var name=s.substring(start,pos);pos"!==s[pos+1]);)++pos;return{name:name,value:s.substring(attrStart,pos),parsed:pos-start}}parseXml(s){let i=0;for(;i",j))<0)return void this.onError(XMLParserErrorCode.UnterminatedElement);this.onEndElement(s.substring(j,q)),j=q+1;break;case"?":++j;var pi=this._parseProcessingInstruction(s,j);if("?>"!==s.substring(j+pi.parsed,j+pi.parsed+2))return void this.onError(XMLParserErrorCode.UnterminatedXmlDeclaration);this.onPi(pi.name,pi.value),j+=pi.parsed+2;break;case"!":if("--"===s.substring(j+1,j+3)){if((q=s.indexOf("--\x3e",j+3))<0)return void this.onError(XMLParserErrorCode.UnterminatedComment);this.onComment(s.substring(j+3,q)),j=q+3}else if("[CDATA["===s.substring(j+1,j+8)){if((q=s.indexOf("]]>",j+8))<0)return void this.onError(XMLParserErrorCode.UnterminatedCdat);this.onCdata(s.substring(j+8,q)),j=q+3}else{if("DOCTYPE"!==s.substring(j+1,j+8))return void this.onError(XMLParserErrorCode.MalformedElement);{pi=s.indexOf("[",j+8);let complexDoctype=!1;if((q=s.indexOf(">",j+8))<0)return void this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);if(0pi){if((q=s.indexOf("]>",j+8))<0)return void this.onError(XMLParserErrorCode.UnterminatedDoctypeDeclaration);complexDoctype=!0}var doctypeContent=s.substring(j+8,q+(complexDoctype?1:0));this.onDoctype(doctypeContent),j=q+(complexDoctype?2:1)}}break;default:doctypeContent=this._parseContent(s,j);if(null===doctypeContent)return void this.onError(XMLParserErrorCode.MalformedElement);let isClosed=!1;if("/>"===s.substring(j+doctypeContent.parsed,j+doctypeContent.parsed+2))isClosed=!0;else if(">"!==s.substring(j+doctypeContent.parsed,j+doctypeContent.parsed+1))return void this.onError(XMLParserErrorCode.UnterminatedElement);this.onBeginElement(doctypeContent.name,doctypeContent.attributes,isClosed),j+=doctypeContent.parsed+(isClosed?2:1)}}else{for(;j=paths.length)return this;var component=paths[pos];if(component.name.startsWith("#")&&pos");for(const child of this.childNodes)child.dump(buffer);buffer.push(``)}else this.nodeValue?buffer.push(`>${encodeToXmlString(this.nodeValue)}`):buffer.push("/>")}}}class SimpleXMLParser extends XMLParserBase{constructor({hasAttributes=!1,lowerCaseName=!1}){super(),this._currentFragment=null,this._stack=null,this._errorCode=XMLParserErrorCode.NoError,this._hasAttributes=hasAttributes,this._lowerCaseName=lowerCaseName}parseFromString(data){if(this._currentFragment=[],this._stack=[],this._errorCode=XMLParserErrorCode.NoError,this.parseXml(data),this._errorCode===XMLParserErrorCode.NoError){var[data]=this._currentFragment;if(data)return{documentElement:data}}}onText(text){isWhitespaceString(text)||(text=new SimpleDOMNode("#text",text),this._currentFragment.push(text))}onCdata(text){text=new SimpleDOMNode("#text",text);this._currentFragment.push(text)}onBeginElement(name,attributes,isEmpty){this._lowerCaseName&&(name=name.toLowerCase());name=new SimpleDOMNode(name);name.childNodes=[],this._hasAttributes&&(name.attributes=attributes),this._currentFragment.push(name),isEmpty||(this._stack.push(this._currentFragment),this._currentFragment=name.childNodes)}onEndElement(name){this._currentFragment=this._stack.pop()||[];var lastElement=this._currentFragment.at(-1);if(!lastElement)return null;for(const childNode of lastElement.childNodes)childNode.parentNode=lastElement;return lastElement}onError(code){this._errorCode=code}}class MetadataParser{constructor(data){data=this._repair(data);var xmlDocument=new SimpleXMLParser({lowerCaseName:!0}).parseFromString(data);this._metadataMap=new Map,this._data=data,xmlDocument&&this._parse(xmlDocument)}_repair(data){return data.replace(/^[^<]+/,"").replaceAll(/>\\376\\377([^<]+)/g,function(all,codes){var bytes=codes.replaceAll(/\\([0-3])([0-7])([0-7])/g,function(code,d1,d2,d3){return String.fromCharCode(64*d1+8*d2+ +d3)}).replaceAll(/&(amp|apos|gt|lt|quot);/g,function(str,name){switch(name){case"amp":return"&";case"apos":return"'";case"gt":return">";case"lt":return"<";case"quot":return'"'}throw new Error(`_repair: ${name} isn't defined.`)}),charBuf=[">"];for(let i=0,ii=bytes.length;i"rdf:li"===node.nodeName)}_parseArray(entry){var seqNode;entry.hasChildNodes()&&([seqNode]=entry.childNodes,seqNode=this._getSequence(seqNode)||[],this._metadataMap.set(entry.nodeName,seqNode.map(node=>node.textContent.trim())))}_parse(xmlDocument){let rdf=xmlDocument.documentElement;if("rdf:rdf"!==rdf.nodeName)for(rdf=rdf.firstChild;rdf&&"rdf:rdf"!==rdf.nodeName;)rdf=rdf.nextSibling;if(rdf&&"rdf:rdf"===rdf.nodeName&&rdf.hasChildNodes())for(const desc of rdf.childNodes)if("rdf:description"===desc.nodeName)for(const entry of desc.childNodes){var name=entry.nodeName;switch(name){case"#text":continue;case"dc:creator":case"dc:subject":this._parseArray(entry);continue}this._metadataMap.set(name,entry.textContent.trim())}}get serializable(){return{parsedData:this._metadataMap,rawData:this._data}}}const chunkSize=512;class DecryptStream extends DecodeStream{constructor(str,maybeLength,decrypt){super(maybeLength),this.str=str,this.dict=str.dict,this.decrypt=decrypt,this.nextChunk=null,this.initialized=!1}readBlock(){let chunk;var decrypt,hasMoreData;this.initialized?chunk=this.nextChunk:(chunk=this.str.getBytes(chunkSize),this.initialized=!0),chunk&&0!==chunk.length?(this.nextChunk=this.str.getBytes(chunkSize),hasMoreData=0>5&255,padded[i++]=length>>13&255,padded[i++]=length>>21&255,padded[i++]=length>>>29&255,padded[i++]=0,padded[i++]=0,padded[i++]=0;var w=new Int32Array(16);for(i=0;i>>32-rotate)|0,a=tmp}h0=h0+a|0,h1=h1+b|0,h2=h2+c|0,h3=h3+d|0}return new Uint8Array([255&h0,h0>>8&255,h0>>16&255,h0>>>24&255,255&h1,h1>>8&255,h1>>16&255,h1>>>24&255,255&h2,h2>>8&255,h2>>16&255,h2>>>24&255,255&h3,h3>>8&255,h3>>16&255,h3>>>24&255])}}();class Word64{constructor(highInteger,lowInteger){this.high=0|highInteger,this.low=0|lowInteger}and(word){this.high&=word.high,this.low&=word.low}xor(word){this.high^=word.high,this.low^=word.low}or(word){this.high|=word.high,this.low|=word.low}shiftRight(places){32<=places?(this.low=this.high>>>places-32|0,this.high=0):(this.low=this.low>>>places|this.high<<32-places,this.high=this.high>>>places|0)}shiftLeft(places){32<=places?(this.high=this.low<>>32-places,this.low<<=places)}rotateRight(places){let low,high;32&places?(high=this.low,low=this.high):(low=this.low,high=this.high),places&=31,this.low=low>>>places|high<<32-places,this.high=high>>>places|low<<32-places}not(){this.high=~this.high,this.low=~this.low}add(word){var lowAdd=(this.low>>>0)+(word.low>>>0);let highAdd=(this.high>>>0)+(word.high>>>0);4294967295>>24&255,bytes[offset+1]=this.high>>16&255,bytes[offset+2]=this.high>>8&255,bytes[offset+3]=255&this.high,bytes[offset+4]=this.low>>>24&255,bytes[offset+5]=this.low>>16&255,bytes[offset+6]=this.low>>8&255,bytes[offset+7]=255&this.low}assign(word){this.high=word.high,this.low=word.low}}const calculateSHA256=function(){function rotr(x,n){return x>>>n|x<<32-n}const k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];return function(data,offset,length){let h0=1779033703,h1=3144134277,h2=1013904242,h3=2773480762,h4=1359893119,h5=2600822924,h6=528734635,h7=1541459225;var paddedLength=64*Math.ceil((length+9)/64),padded=new Uint8Array(paddedLength);let i,j;for(i=0;i>>29&255,padded[i++]=length>>21&255,padded[i++]=length>>13&255,padded[i++]=length>>5&255,padded[i++]=length<<3&255;var x,w=new Uint32Array(64);for(i=0;i>>10)+w[j-7]+function(x){return rotr(x,7)^rotr(x,18)^x>>>3}(w[j-15])+w[j-16];let a=h0,b=h1,c=h2,d=h3,e=h4,f=h5,g=h6,h=h7,t1,t2;for(j=0;j<64;++j)t1=h+function(x){return rotr(x,6)^rotr(x,11)^rotr(x,25)}(e)+function(x,y,z){return x&y^~x&z}(e,f,g)+k[j]+w[j],t2=function(x){return rotr(x,2)^rotr(x,13)^rotr(x,22)}(a)+function(x,y,z){return x&y^x&z^y&z}(a,b,c),h=g,g=f,f=e,e=d+t1|0,d=c,c=b,b=a,a=t1+t2|0;h0=h0+a|0,h1=h1+b|0,h2=h2+c|0,h3=h3+d|0,h4=h4+e|0,h5=h5+f|0,h6=h6+g|0,h7=h7+h|0}return new Uint8Array([h0>>24&255,h0>>16&255,h0>>8&255,255&h0,h1>>24&255,h1>>16&255,h1>>8&255,255&h1,h2>>24&255,h2>>16&255,h2>>8&255,255&h2,h3>>24&255,h3>>16&255,h3>>8&255,255&h3,h4>>24&255,h4>>16&255,h4>>8&255,255&h4,h5>>24&255,h5>>16&255,h5>>8&255,255&h5,h6>>24&255,h6>>16&255,h6>>8&255,255&h6,h7>>24&255,h7>>16&255,h7>>8&255,255&h7])}}(),calculateSHA512=function(){const k=[new Word64(1116352408,3609767458),new Word64(1899447441,602891725),new Word64(3049323471,3964484399),new Word64(3921009573,2173295548),new Word64(961987163,4081628472),new Word64(1508970993,3053834265),new Word64(2453635748,2937671579),new Word64(2870763221,3664609560),new Word64(3624381080,2734883394),new Word64(310598401,1164996542),new Word64(607225278,1323610764),new Word64(1426881987,3590304994),new Word64(1925078388,4068182383),new Word64(2162078206,991336113),new Word64(2614888103,633803317),new Word64(3248222580,3479774868),new Word64(3835390401,2666613458),new Word64(4022224774,944711139),new Word64(264347078,2341262773),new Word64(604807628,2007800933),new Word64(770255983,1495990901),new Word64(1249150122,1856431235),new Word64(1555081692,3175218132),new Word64(1996064986,2198950837),new Word64(2554220882,3999719339),new Word64(2821834349,766784016),new Word64(2952996808,2566594879),new Word64(3210313671,3203337956),new Word64(3336571891,1034457026),new Word64(3584528711,2466948901),new Word64(113926993,3758326383),new Word64(338241895,168717936),new Word64(666307205,1188179964),new Word64(773529912,1546045734),new Word64(1294757372,1522805485),new Word64(1396182291,2643833823),new Word64(1695183700,2343527390),new Word64(1986661051,1014477480),new Word64(2177026350,1206759142),new Word64(2456956037,344077627),new Word64(2730485921,1290863460),new Word64(2820302411,3158454273),new Word64(3259730800,3505952657),new Word64(3345764771,106217008),new Word64(3516065817,3606008344),new Word64(3600352804,1432725776),new Word64(4094571909,1467031594),new Word64(275423344,851169720),new Word64(430227734,3100823752),new Word64(506948616,1363258195),new Word64(659060556,3750685593),new Word64(883997877,3785050280),new Word64(958139571,3318307427),new Word64(1322822218,3812723403),new Word64(1537002063,2003034995),new Word64(1747873779,3602036899),new Word64(1955562222,1575990012),new Word64(2024104815,1125592928),new Word64(2227730452,2716904306),new Word64(2361852424,442776044),new Word64(2428436474,593698344),new Word64(2756734187,3733110249),new Word64(3204031479,2999351573),new Word64(3329325298,3815920427),new Word64(3391569614,3928383900),new Word64(3515267271,566280711),new Word64(3940187606,3454069534),new Word64(4118630271,4000239992),new Word64(116418474,1914138554),new Word64(174292421,2731055270),new Word64(289380356,3203993006),new Word64(460393269,320620315),new Word64(685471733,587496836),new Word64(852142971,1086792851),new Word64(1017036298,365543100),new Word64(1126000580,2618297676),new Word64(1288033470,3409855158),new Word64(1501505948,4234509866),new Word64(1607167915,987167468),new Word64(1816402316,1246189591)];return function(data,offset,length,mode384=!1){let h0,h1,h2,h3,h4,h5,h6,h7;h7=mode384?(h0=new Word64(3418070365,3238371032),h1=new Word64(1654270250,914150663),h2=new Word64(2438529370,812702999),h3=new Word64(355462360,4144912697),h4=new Word64(1731405415,4290775857),h5=new Word64(2394180231,1750603025),h6=new Word64(3675008525,1694076839),new Word64(1203062813,3204075428)):(h0=new Word64(1779033703,4089235720),h1=new Word64(3144134277,2227873595),h2=new Word64(1013904242,4271175723),h3=new Word64(2773480762,1595750129),h4=new Word64(1359893119,2917565137),h5=new Word64(2600822924,725511199),h6=new Word64(528734635,4215389547),new Word64(1541459225,327033209));var paddedLength=128*Math.ceil((length+17)/128),padded=new Uint8Array(paddedLength);let i,j;for(i=0;i>>29&255,padded[i++]=length>>21&255,padded[i++]=length>>13&255,padded[i++]=length>>5&255,padded[i++]=length<<3&255;var w=new Array(80);for(i=0;i<80;i++)w[i]=new Word64(0,0);let a=new Word64(0,0),b=new Word64(0,0),c=new Word64(0,0),d=new Word64(0,0),e=new Word64(0,0),f=new Word64(0,0),g=new Word64(0,0),h=new Word64(0,0);var t1=new Word64(0,0),t2=new Word64(0,0),tmp1=new Word64(0,0),tmp2=new Word64(0,0);let tmp3;for(i=0;i>>8^s1<<24^s2>>>16^s2<<16^s3>>>24^s3<<8,state[j]=t>>>24&255,state[j+1]=t>>16&255,state[j+2]=t>>8&255,state[j+3]=255&t}}t=state[13],state[13]=state[9],state[9]=state[5],state[5]=state[1],state[1]=t,t=state[14],u=state[10],state[14]=state[6],state[10]=state[2],state[6]=t,state[2]=u,t=state[15],u=state[11],v=state[7],state[15]=state[3],state[11]=t,state[7]=u,state[3]=v;for(let j=0;j<16;++j)state[j]=this._inv_s[state[j]],state[j]^=key[j];return state}_encrypt(input,key){var s=this._s;let t,u,v;var state=new Uint8Array(16);state.set(input);for(let j=0;j<16;++j)state[j]^=key[j];for(let i=1;i=ii;--i)if(lastBlock[i]!==psLen){psLen=0;break}outputLength-=psLen,result[result.length-1]=lastBlock.subarray(0,16-psLen)}}var output=new Uint8Array(outputLength);for(let i=0,j=0,ii=result.length;ii-32;){var combinedLength=password.length+k.length+userBytes.length,combinedArray=new Uint8Array(combinedLength),writeOffset=0,k1=(combinedArray.set(password,0),writeOffset+=password.length,combinedArray.set(k,writeOffset),writeOffset+=k.length,combinedArray.set(userBytes,writeOffset),new Uint8Array(64*combinedLength));for(let j=0,pos=0;j<64;j++,pos+=combinedLength)k1.set(combinedArray,pos);writeOffset=new AES128Cipher(k.subarray(0,16)),writeOffset=(e=writeOffset.encrypt(k1,k.subarray(16,32))).slice(0,16).reduce((a,b)=>a+b,0)%3;0==writeOffset?k=calculateSHA256(e,0,e.length):1==writeOffset?k=calculateSHA384(e,0,e.length):2==writeOffset&&(k=calculateSHA512(e,0,e.length)),i++}return k.subarray(0,32)}checkOwnerPassword(password,ownerValidationSalt,userBytes,ownerPassword){var hashData=new Uint8Array(password.length+56),ownerValidationSalt=(hashData.set(password,0),hashData.set(ownerValidationSalt,password.length),hashData.set(userBytes,password.length+ownerValidationSalt.length),this._hash(password,hashData,userBytes));return isArrayEqual(ownerValidationSalt,ownerPassword)}checkUserPassword(password,userValidationSalt,userPassword){var hashData=new Uint8Array(password.length+8),userValidationSalt=(hashData.set(password,0),hashData.set(userValidationSalt,password.length),this._hash(password,hashData,[]));return isArrayEqual(userValidationSalt,userPassword)}getOwnerKey(password,ownerKeySalt,userBytes,ownerEncryption){var hashData=new Uint8Array(password.length+56),ownerKeySalt=(hashData.set(password,0),hashData.set(ownerKeySalt,password.length),hashData.set(userBytes,password.length+ownerKeySalt.length),this._hash(password,hashData,userBytes));return new AES256Cipher(ownerKeySalt).decryptBlock(ownerEncryption,!1,new Uint8Array(16))}getUserKey(password,userKeySalt,userEncryption){var hashData=new Uint8Array(password.length+8),userKeySalt=(hashData.set(password,0),hashData.set(userKeySalt,password.length),this._hash(password,hashData,[]));return new AES256Cipher(userKeySalt).decryptBlock(userEncryption,!1,new Uint8Array(16))}}class CipherTransform{constructor(stringCipherConstructor,streamCipherConstructor){this.StringCipherConstructor=stringCipherConstructor,this.StreamCipherConstructor=streamCipherConstructor}createStream(stream,length){const cipher=new this.StreamCipherConstructor;return new DecryptStream(stream,length,function(data,finalize){return cipher.decryptBlock(data,finalize)})}decryptString(s){var cipher=new this.StringCipherConstructor,s=stringToBytes(s);return bytesToString(cipher.decryptBlock(s,!0))}encryptString(s){var cipher=new this.StringCipherConstructor;if(cipher instanceof AESBaseCipher){var pad=16-s.length%16,iv=(s+=String.fromCharCode(pad).repeat(pad),new Uint8Array(16));if("undefined"!=typeof crypto)crypto.getRandomValues(iv);else for(let i=0;i<16;i++)iv[i]=Math.floor(256*Math.random());let data=stringToBytes(s);data=cipher.encrypt(data,iv);pad=new Uint8Array(16+data.length);return pad.set(iv),pad.set(data,16),bytesToString(pad)}pad=stringToBytes(s);return bytesToString(cipher.encrypt(pad))}}class CipherTransformFactory{static#defaultPasswordBytes=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]);#createEncryptionKey20(revision,password,ownerPassword,ownerValidationSalt,ownerKeySalt,uBytes,userPassword,userValidationSalt,userKeySalt,ownerEncryption,userEncryption,perms){password=password?(passwordLength=Math.min(127,password.length),password.subarray(0,passwordLength)):[];var passwordLength=new(6===revision?PDF20:PDF17);return passwordLength.checkUserPassword(password,userValidationSalt,userPassword)?passwordLength.getUserKey(password,userKeySalt,userEncryption):password.length&&passwordLength.checkOwnerPassword(password,ownerValidationSalt,uBytes,ownerPassword)?passwordLength.getOwnerKey(password,ownerKeySalt,uBytes,ownerEncryption):null}#prepareKeyData(fileId,password,ownerPassword,userPassword,flags,revision,keyLength,encryptMetadata){var hashDataSize=40+ownerPassword.length+fileId.length,hashData=new Uint8Array(hashDataSize);let i=0,j,n;if(password)for(n=Math.min(32,password.length);i>8&255,hashData[i++]=flags>>16&255,hashData[i++]=flags>>>24&255,j=0,n=fileId.length;j>3;if(3<=revision)for(j=0;j<50;++j)hash=calculateMD5(hash,0,keyLengthInBytes);var encryptionKey=hash.subarray(0,keyLengthInBytes);let cipher,checkData;if(3<=revision){for(i=0;i<32;++i)hashData[i]=CipherTransformFactory.#defaultPasswordBytes[i];for(j=0,n=fileId.length;j>3;if(3<=revision)for(j=0;j<50;++j)hash=calculateMD5(hash,0,hash.length);let cipher,userPassword;if(3<=revision){userPassword=ownerPassword;var derivedKey=new Uint8Array(keyLengthInBytes);for(j=19;0<=j;j--){for(let k=0;k>8&255,key[i++]=num>>16&255,key[i++]=255&gen,key[i++]=gen>>8&255,isAes&&(key[i++]=115,key[i++]=65,key[i++]=108,key[i++]=84),calculateMD5(key,0,i).subarray(0,Math.min(encryptionKey.length+5,16))}#buildCipherConstructor(cf,name,num,gen,key){if(!(name instanceof Name))throw new FormatError("Invalid crypt filter name.");const self=this;cf=cf.get(name.name)?.get("CFM");if(!cf||"None"===cf.name)return function(){return new NullCipher};if("V2"===cf.name)return function(){return new ARCFourCipher(self.#buildObjectKey(num,gen,key,!1))};if("AESV2"===cf.name)return function(){return new AES128Cipher(self.#buildObjectKey(num,gen,key,!0))};if("AESV3"===cf.name)return function(){return new AES256Cipher(key)};throw new FormatError("Unknown crypto method")}constructor(dict,fileId,password){var filter=dict.get("Filter");if(!isName(filter,"Standard"))throw new FormatError("unknown encryption method");this.filterName=filter.name;filter=(this.dict=dict).get("V");if(!Number.isInteger(filter)||1!==filter&&2!==filter&&4!==filter&&5!==filter)throw new FormatError("unsupported encryption algorithm");this.algorithm=filter;let keyLength=dict.get("Length");if(keyLength||(filter<=3?keyLength=40:(cfDict=dict.get("CF"),streamCryptoName=dict.get("StmF"),cfDict instanceof Dict&&streamCryptoName instanceof Name&&(cfDict.suppressEncryption=!0,cfDict=cfDict.get(streamCryptoName.name),(keyLength=cfDict?.get("Length")||128)<40)&&(keyLength<<=3))),!Number.isInteger(keyLength)||keyLength<40||keyLength%8!=0)throw new FormatError("invalid key length");var uBytes,userValidationSalt,ownerEncryption,userEncryption,perms,ownerValidationSalt,streamCryptoName=stringToBytes(dict.get("O")),cfDict=stringToBytes(dict.get("U")),ownerPassword=streamCryptoName.subarray(0,32),userPassword=cfDict.subarray(0,32),flags=dict.get("P"),revision=dict.get("R"),encryptMetadata=(4===filter||5===filter)&&!1!==dict.get("EncryptMetadata"),fileId=(this.encryptMetadata=encryptMetadata,stringToBytes(fileId));let passwordBytes;if(password){if(6===revision)try{password=utf8StringToString(password)}catch{warn("CipherTransformFactory: Unable to convert UTF8 encoded password.")}passwordBytes=stringToBytes(password)}let encryptionKey;if(!(encryptionKey=5!==filter?this.#prepareKeyData(fileId,passwordBytes,ownerPassword,userPassword,flags,revision,keyLength,encryptMetadata):(ownerValidationSalt=streamCryptoName.subarray(32,40),streamCryptoName=streamCryptoName.subarray(40,48),uBytes=cfDict.subarray(0,48),userValidationSalt=cfDict.subarray(32,40),cfDict=cfDict.subarray(40,48),ownerEncryption=stringToBytes(dict.get("OE")),userEncryption=stringToBytes(dict.get("UE")),perms=stringToBytes(dict.get("Perms")),this.#createEncryptionKey20(revision,passwordBytes,ownerPassword,ownerValidationSalt,streamCryptoName,uBytes,userPassword,userValidationSalt,cfDict,ownerEncryption,userEncryption,perms)))&&!password)throw new PasswordException("No password given",PasswordResponses.NEED_PASSWORD);if(!encryptionKey&&password&&(ownerValidationSalt=this.#decodeUserPassword(passwordBytes,ownerPassword,revision,keyLength),encryptionKey=this.#prepareKeyData(fileId,ownerValidationSalt,ownerPassword,userPassword,flags,revision,keyLength,encryptMetadata)),!encryptionKey)throw new PasswordException("Incorrect Password",PasswordResponses.INCORRECT_PASSWORD);this.encryptionKey=encryptionKey,4<=filter&&((streamCryptoName=dict.get("CF"))instanceof Dict&&(streamCryptoName.suppressEncryption=!0),this.cf=streamCryptoName,this.stmf=dict.get("StmF")||Name.get("Identity"),this.strf=dict.get("StrF")||Name.get("Identity"),this.eff=dict.get("EFF")||this.stmf)}createCipherTransform(num,gen){if(4===this.algorithm||5===this.algorithm)return new CipherTransform(this.#buildCipherConstructor(this.cf,this.strf,num,gen,this.encryptionKey),this.#buildCipherConstructor(this.cf,this.stmf,num,gen,this.encryptionKey));const key=this.#buildObjectKey(num,gen,this.encryptionKey,!1);function cipherConstructor(){return new ARCFourCipher(key)}return new CipherTransform(cipherConstructor,cipherConstructor)}}async function writeObject(ref,obj,buffer,{encrypt=null}){encrypt=encrypt?.createCipherTransform(ref.num,ref.gen);buffer.push(`${ref.num} ${ref.gen} obj\n`),obj instanceof Dict?await writeDict(obj,buffer,encrypt):obj instanceof BaseStream?await writeStream(obj,buffer,encrypt):(Array.isArray(obj)||ArrayBuffer.isView(obj))&&await writeArray(obj,buffer,encrypt),buffer.push("\nendobj\n")}async function writeDict(dict,buffer,transform){buffer.push("<<");for(const key of dict.getKeys())buffer.push(` /${escapePDFName(key)} `),await writeValue(dict.getRaw(key),buffer,transform);buffer.push(">>")}async function writeStream(stream,buffer,transform){let bytes=stream.getBytes();var stream=stream["dict"],[filter,params]=await Promise.all([stream.getAsync("Filter"),stream.getAsync("DecodeParms")]),isFilterZeroFlateDecode=isName(Array.isArray(filter)?await stream.xref.fetchIfRefAsync(filter[0]):filter,"FlateDecode");if(256<=bytes.length||isFilterZeroFlateDecode)try{var cs=new CompressionStream("deflate"),writer=cs.writable.getWriter(),buf=(writer.write(bytes),writer.close(),await new Response(cs.readable).arrayBuffer());bytes=new Uint8Array(buf);let newFilter,newParams;filter?isFilterZeroFlateDecode||(newFilter=Array.isArray(filter)?[Name.get("FlateDecode"),...filter]:[Name.get("FlateDecode"),filter],params&&(newParams=Array.isArray(params)?[null,...params]:[null,params])):newFilter=Name.get("FlateDecode"),newFilter&&stream.set("Filter",newFilter),newParams&&stream.set("DecodeParms",newParams)}catch(ex){info(`writeStream - cannot compress data: "${ex}".`)}let string=bytesToString(bytes);transform&&(string=transform.encryptString(string)),stream.set("Length",string.length),await writeDict(stream,buffer,transform),buffer.push(" stream\n",string,"\nendstream")}async function writeArray(array,buffer,transform){buffer.push("[");let first=!0;for(const val of array)first?first=!1:buffer.push(" "),await writeValue(val,buffer,transform);buffer.push("]")}async function writeValue(value,buffer,transform){value instanceof Name?buffer.push("/"+escapePDFName(value.name)):value instanceof Ref?buffer.push(`${value.num} ${value.gen} R`):Array.isArray(value)||ArrayBuffer.isView(value)?await writeArray(value,buffer,transform):"string"==typeof value?(transform&&(value=transform.encryptString(value)),buffer.push(`(${escapeString(value)})`)):"number"==typeof value?buffer.push(numberToString(value)):"boolean"==typeof value?buffer.push(value.toString()):value instanceof Dict?await writeDict(value,buffer,transform):value instanceof BaseStream?await writeStream(value,buffer,transform):null===value?buffer.push("null"):warn(`Unhandled value in writer: ${typeof value}, please file a bug.`)}function writeInt(number,size,offset,buffer){for(let i=size+offset-1;i>offset-1;i--)buffer[i]=255&number,number>>=8;return offset+size}function writeString(string,offset,buffer){for(let i=0,len=string.length;ia+str.length,0);for(const value of Object.values(xrefInfo.info))md5Buffer.push(value),md5BufferLen+=value.length;var array=new Uint8Array(md5BufferLen);let offset=0;for(const str of md5Buffer)writeString(str,offset,array),offset+=str.length;return bytesToString(calculateMD5(array))}function writeXFADataForAcroform(str,newRefs){var xfa,xml=new SimpleXMLParser({hasAttributes:!0}).parseFromString(str);for({xfa}of newRefs)if(xfa){var{path,value}=xfa;if(path){var nodePath=parseXFAPath(path);let node=xml.documentElement.searchNode(nodePath,0);(node=!node&&1new SimpleDOMNode("value",val)):[new SimpleDOMNode("#text",value)]:warn("Node not found for path: "+path)}}str=[];return xml.documentElement.dump(str),str.join("")}async function updateAcroform({xref,acroForm,acroFormRef,hasXfa,hasXfaDatasetsEntry,xfaDatasetsRef,needAppearances,newRefs}){var dict;!hasXfa||hasXfaDatasetsEntry||xfaDatasetsRef||warn("XFA - Cannot save it"),(needAppearances||hasXfa&&xfaDatasetsRef&&!hasXfaDatasetsEntry)&&(dict=acroForm.clone(),hasXfa&&!hasXfaDatasetsEntry&&((hasXfa=acroForm.get("XFA").slice()).splice(2,0,"datasets"),hasXfa.splice(3,0,xfaDatasetsRef),dict.set("XFA",hasXfa)),needAppearances&&dict.set("NeedAppearances",!0),await writeObject(acroFormRef,dict,hasXfaDatasetsEntry=[],xref),newRefs.push({ref:acroFormRef,data:hasXfaDatasetsEntry.join("")}))}function updateXFA({xfaData,xfaDatasetsRef,newRefs,xref}){null===xfaData&&(xfaData=writeXFADataForAcroform(xref.fetchIfRef(xfaDatasetsRef).getString(),newRefs));xref=xref.encrypt,xref&&(xfaData=xref.createCipherTransform(xfaDatasetsRef.num,xfaDatasetsRef.gen).encryptString(xfaData)),xref=`${xfaDatasetsRef.num} ${xfaDatasetsRef.gen} obj\n`+`<< /Type /EmbeddedFile /Length ${xfaData.length}>> stream `+xfaData+"\nendstream\nendobj\n";newRefs.push({ref:xfaDatasetsRef,data:xref})}async function getXRefTable(xrefInfo,baseOffset,newRefs,newXref,buffer){buffer.push("xref\n");var ref,data,indexes=getIndexes(newRefs);let indexesPosition=0;for({ref,data}of newRefs)ref.num===indexes[indexesPosition]&&(buffer.push(`${indexes[indexesPosition]} ${indexes[indexesPosition+1]}\n`),indexesPosition+=2),null!==data?(buffer.push(`${baseOffset.toString().padStart(10,"0")} ${Math.min(ref.gen,65535).toString().padStart(5,"0")} n\r\n`),baseOffset+=data.length):buffer.push(`0000000000 ${Math.min(ref.gen+1,65535).toString().padStart(5,"0")} f\r `);computeIDs(baseOffset,xrefInfo,newXref),buffer.push("trailer\n"),await writeDict(newXref,buffer),buffer.push("\nstartxref\n",baseOffset.toString(),"\n%%EOF\n")}function getIndexes(newRefs){var ref,indexes=[];for({ref}of newRefs)ref.num===indexes.at(-2)+indexes.at(-1)?indexes[indexes.length-1]+=1:indexes.push(ref.num,1);return indexes}async function getXRefStreamTable(xrefInfo,baseOffset,newRefs,newXref,buffer){var xrefTableData=[];let maxOffset=0,maxGen=0;for(const{ref,data}of newRefs){let gen;maxOffset=Math.max(maxOffset,baseOffset),null!==data?(gen=Math.min(ref.gen,65535),xrefTableData.push([1,baseOffset,gen]),baseOffset+=data.length):(gen=Math.min(ref.gen+1,65535),xrefTableData.push([0,0,gen])),maxGen=Math.max(maxGen,gen)}newXref.set("Index",getIndexes(newRefs));var sizes=[1,getSizeInBytes(maxOffset),getSizeInBytes(maxGen)],newRefs=(newXref.set("W",sizes),computeIDs(baseOffset,xrefInfo,newXref),sizes.reduce((a,x)=>a+x,0));const data=new Uint8Array(newRefs*xrefTableData.length);var type,objOffset,gen,newRefs=new Stream(data);newRefs.dict=newXref;let offset=0;for([type,objOffset,gen]of xrefTableData)offset=writeInt(type,sizes[0],offset,data),offset=writeInt(objOffset,sizes[1],offset,data),offset=writeInt(gen,sizes[2],offset,data);await writeObject(xrefInfo.newRef,newRefs,buffer,{}),buffer.push("startxref\n",baseOffset.toString(),"\n%%EOF\n")}function computeIDs(baseOffset,xrefInfo,newXref){Array.isArray(xrefInfo.fileIds)&&0a.ref.num-b.ref.num))null!==data&&buffer.push(data);await(useXrefStream?getXRefStreamTable:getXRefTable)(xrefInfo,baseOffset,newRefs,acroFormRef,buffer);var hasXfaDatasetsEntry=buffer.reduce((a,str)=>a+str.length,originalData.length),array=new Uint8Array(hasXfaDatasetsEntry);array.set(originalData);let offset=originalData.length;for(const str of buffer)writeString(str,offset,array),offset+=str.length;return array}const MAX_DEPTH=40,StructElementType={PAGE_CONTENT:1,STREAM_CONTENT:2,OBJECT:3,ANNOTATION:4,ELEMENT:5};class StructTreeRoot{constructor(rootDict,rootRef){this.dict=rootDict,this.ref=rootRef instanceof Ref?rootRef:null,this.roleMap=new Map,this.structParentIds=null}init(){this.readRoleMap()}#addIdToPage(pageRef,id,type){if(pageRef instanceof Ref&&!(id<0)){this.structParentIds||=new RefSetCache;let ids=this.structParentIds.get(pageRef);ids||(ids=[],this.structParentIds.put(pageRef,ids)),ids.push([id,type])}}addAnnotationIdToPage(pageRef,id){this.#addIdToPage(pageRef,id,StructElementType.ANNOTATION)}readRoleMap(){var roleMapDict=this.dict.get("RoleMap");roleMapDict instanceof Dict&&roleMapDict.forEach((key,value)=>{value instanceof Name&&this.roleMap.set(key,value.name)})}static async canCreateStructureTree({catalogRef,pdfManager,newAnnotationsByPage}){if(!(catalogRef instanceof Ref))return warn("Cannot save the struct tree: no catalog reference."),!1;let nextKey=0,hasNothingToUpdate=!0;for(var[pageIndex,elements]of newAnnotationsByPage){var pageRef=(await pdfManager.getPage(pageIndex))["ref"];if(!(pageRef instanceof Ref)){warn(`Cannot save the struct tree: page ${pageIndex} has no ref.`),hasNothingToUpdate=!0;break}for(const element of elements)element.accessibilityData?.type&&(element.parentTreeId=nextKey++,hasNothingToUpdate=!1)}if(hasNothingToUpdate){for(const elements of newAnnotationsByPage.values())for(const element of elements)delete element.parentTreeId;return!1}return!0}static async createStructureTree({newAnnotationsByPage,xref,catalogRef,pdfManager,newRefs}){var ref,obj,root=pdfManager.catalog.cloneDict(),cache=new RefSetCache,catalogRef=(cache.put(catalogRef,root),xref.getNewTemporaryRef()),root=(root.set("StructTreeRoot",catalogRef),new Dict(xref)),parentTreeRef=(root.set("Type",Name.get("StructTreeRoot")),xref.getNewTemporaryRef()),kids=(root.set("ParentTree",parentTreeRef),[]),parentTree=(root.set("K",kids),cache.put(catalogRef,root),new Dict(xref)),nums=[],newAnnotationsByPage=(parentTree.set("Nums",nums),await this.#writeKids({newAnnotationsByPage:newAnnotationsByPage,structTreeRootRef:catalogRef,kids:kids,nums:nums,xref:xref,pdfManager:pdfManager,cache:cache})),buffer=(root.set("ParentTreeNextKey",newAnnotationsByPage),cache.put(parentTreeRef,parentTree),[]);for([ref,obj]of cache.items())buffer.length=0,await writeObject(ref,obj,buffer,xref),newRefs.push({ref:ref,data:buffer.join("")})}async canUpdateStructTree({pdfManager,xref,newAnnotationsByPage}){if(!this.ref)return warn("Cannot update the struct tree: no root reference."),!1;let nextKey=this.dict.get("ParentTreeNextKey");if(!Number.isInteger(nextKey)||nextKey<0)return warn("Cannot update the struct tree: invalid next key."),!1;var parentTree=this.dict.get("ParentTree");if(!(parentTree instanceof Dict))return warn("Cannot update the struct tree: ParentTree isn't a dict."),!1;var nums=parentTree.get("Nums");if(!Array.isArray(nums))return warn("Cannot update the struct tree: nums isn't an array."),!1;var pageIndex,elements,numberTree=new NumberTree(parentTree,xref);for(const pageIndex of newAnnotationsByPage.keys()){var pageDict=(await pdfManager.getPage(pageIndex))["pageDict"];if(pageDict.has("StructParents")){pageDict=pageDict.get("StructParents");if(!Number.isInteger(pageDict)||!Array.isArray(numberTree.get(pageDict)))return warn(`Cannot save the struct tree: page ${pageIndex} has a wrong id.`),!1}}let hasNothingToUpdate=!0;for([pageIndex,elements]of newAnnotationsByPage){const pageDict=(await pdfManager.getPage(pageIndex))["pageDict"];StructTreeRoot.#collectParents({elements:elements,xref:this.dict.xref,pageDict:pageDict,numberTree:numberTree});for(const element of elements)element.accessibilityData?.type&&(element.parentTreeId=nextKey++,hasNothingToUpdate=!1)}if(hasNothingToUpdate){for(const elements of newAnnotationsByPage.values())for(const element of elements)delete element.parentTreeId,delete element.structTreeParent;return!1}return!0}async updateStructureTree({newAnnotationsByPage,pdfManager,newRefs}){var xref=this.dict.xref,structTreeRoot=this.dict.clone(),structTreeRootRef=this.ref,cache=new RefSetCache;cache.put(structTreeRootRef,structTreeRoot);let parentTreeRef=structTreeRoot.getRaw("ParentTree"),parentTree,nums=(parentTreeRef instanceof Ref?parentTree=xref.fetch(parentTreeRef):(parentTree=parentTreeRef,parentTreeRef=xref.getNewTemporaryRef(),structTreeRoot.set("ParentTree",parentTreeRef)),parentTree=parentTree.clone(),cache.put(parentTreeRef,parentTree),parentTree.getRaw("Nums")),numsRef=null;nums instanceof Ref&&(numsRef=nums,nums=xref.fetch(numsRef)),nums=nums.slice(),numsRef||parentTree.set("Nums",nums);var ref,obj,newAnnotationsByPage=await StructTreeRoot.#writeKids({newAnnotationsByPage:newAnnotationsByPage,structTreeRootRef:structTreeRootRef,kids:null,nums:nums,xref:xref,pdfManager:pdfManager,cache:cache}),buffer=(structTreeRoot.set("ParentTreeNextKey",newAnnotationsByPage),numsRef&&cache.put(numsRef,nums),[]);for([ref,obj]of cache.items())buffer.length=0,await writeObject(ref,obj,buffer,xref),newRefs.push({ref:ref,data:buffer.join("")})}static async#writeKids({newAnnotationsByPage,structTreeRootRef,kids,nums,xref,pdfManager,cache}){var pageIndex,elements,objr=Name.get("OBJR");let nextKey=-1/0;for([pageIndex,elements]of newAnnotationsByPage){var accessibilityData,ref,parentTreeId,structTreeParent,title,lang,alt,expanded,actualText,tagRef,tagDict,type,pageRef=(await pdfManager.getPage(pageIndex))["ref"],isPageRef=pageRef instanceof Ref;for({accessibilityData,ref,parentTreeId,structTreeParent}of elements)accessibilityData?.type&&({type,title,lang,alt,expanded,actualText}=accessibilityData,nextKey=Math.max(nextKey,parentTreeId),tagRef=xref.getNewTemporaryRef(),(tagDict=new Dict(xref)).set("S",Name.get(type)),title&&tagDict.set("T",title),lang&&tagDict.set("Lang",lang),alt&&tagDict.set("Alt",alt),expanded&&tagDict.set("E",expanded),actualText&&tagDict.set("ActualText",actualText),await this.#updateParentTag({structTreeParent:structTreeParent,tagDict:tagDict,newTagRef:tagRef,structTreeRootRef:structTreeRootRef,fallbackKids:kids,xref:xref,cache:cache}),type=new Dict(xref),tagDict.set("K",type),type.set("Type",objr),isPageRef&&type.set("Pg",pageRef),type.set("Obj",ref),cache.put(tagRef,tagDict),nums.push(parentTreeId,tagRef))}return nextKey+1}static#collectParents({elements,xref,pageDict,numberTree}){const idToElements=new Map;for(const element of elements)if(element.structTreeParentId){const id=parseInt(element.structTreeParentId.split("_mc")[1],10);let elems=idToElements.get(id);elems||(elems=[],idToElements.set(id,elems)),elems.push(element)}const id=pageDict.get("StructParents");if(Number.isInteger(id)){var updateElement=(kid,pageKid,kidRef)=>{kid=idToElements.get(kid);if(kid){var parentRef=pageKid.getRaw("P"),parentDict=xref.fetchIfRef(parentRef);if(parentRef instanceof Ref&&parentDict instanceof Dict){var params={ref:kidRef,dict:pageKid};for(const element of kid)element.structTreeParent=params}return!0}return!1};for(const kidRef of numberTree.get(id))if(kidRef instanceof Ref){var pageKid=xref.fetch(kidRef),k=pageKid.get("K");if(Number.isInteger(k))updateElement(k,pageKid,kidRef);else if(Array.isArray(k))for(var kid of k){if(kid=xref.fetchIfRef(kid),Number.isInteger(kid)&&updateElement(kid,pageKid,kidRef))break;if(kid instanceof Dict){if(!isName(kid.get("Type"),"MCR"))break;kid=kid.get("MCID");if(Number.isInteger(kid)&&updateElement(kid,pageKid,kidRef))break}}}}}static async#updateParentTag({structTreeParent,tagDict,newTagRef,structTreeRootRef,fallbackKids,xref,cache}){let ref=null,parentRef;parentRef=structTreeParent&&({ref}=structTreeParent,structTreeParent.dict.getRaw("P"))||structTreeRootRef,tagDict.set("P",parentRef);structTreeParent=xref.fetchIfRef(parentRef);if(structTreeParent){let cachedParentDict=cache.get(parentRef);cachedParentDict||(cachedParentDict=structTreeParent.clone(),cache.put(parentRef,cachedParentDict));structTreeRootRef=cachedParentDict.getRaw("K");let cachedParentKids=structTreeRootRef instanceof Ref?cache.get(structTreeRootRef):null;cachedParentKids||(cachedParentKids=xref.fetchIfRef(structTreeRootRef),cachedParentKids=Array.isArray(cachedParentKids)?cachedParentKids.slice():[structTreeRootRef],tagDict=xref.getNewTemporaryRef(),cachedParentDict.set("K",tagDict),cache.put(tagDict,cachedParentKids));structTreeParent=cachedParentKids.indexOf(ref);cachedParentKids.splice(0<=structTreeParent?structTreeParent+1:cachedParentKids.length,0,newTagRef)}else fallbackKids.push(newTagRef)}}class StructElementNode{constructor(tree,dict){this.tree=tree,this.dict=dict,this.kids=[],this.parseKids()}get role(){var nameObj=this.dict.get("S"),nameObj=nameObj instanceof Name?nameObj.name:"",root=this.tree["root"];return root.roleMap.has(nameObj)?root.roleMap.get(nameObj):nameObj}parseKids(){let pageObjId=null;var objRef=this.dict.getRaw("Pg"),objRef=(objRef instanceof Ref&&(pageObjId=objRef.toString()),this.dict.get("K"));if(Array.isArray(objRef))for(const kid of objRef){var element=this.parseKid(pageObjId,kid);element&&this.kids.push(element)}else{const element=this.parseKid(pageObjId,objRef);element&&this.kids.push(element)}}parseKid(pageObjId,kid){if(Number.isInteger(kid))return this.tree.pageDict.objId!==pageObjId?null:new StructElement({type:StructElementType.PAGE_CONTENT,mcid:kid,pageObjId:pageObjId});let kidDict=null;if(kid instanceof Ref?kidDict=this.dict.xref.fetch(kid):kid instanceof Dict&&(kidDict=kid),!kidDict)return null;var kidRef,kid=kidDict.getRaw("Pg"),kid=(kid instanceof Ref&&(pageObjId=kid.toString()),kidDict.get("Type")instanceof Name?kidDict.get("Type").name:null);if("MCR"===kid)return this.tree.pageDict.objId!==pageObjId?null:(kidRef=kidDict.getRaw("Stm"),new StructElement({type:StructElementType.STREAM_CONTENT,refObjId:kidRef instanceof Ref?kidRef.toString():null,pageObjId:pageObjId,mcid:kidDict.get("MCID")}));if("OBJR"!==kid)return new StructElement({type:StructElementType.ELEMENT,dict:kidDict});{if(this.tree.pageDict.objId!==pageObjId)return null;const kidRef=kidDict.getRaw("Obj");return new StructElement({type:StructElementType.OBJECT,refObjId:kidRef instanceof Ref?kidRef.toString():null,pageObjId:pageObjId})}}}class StructElement{constructor({type,dict=null,mcid=null,pageObjId=null,refObjId=null}){this.type=type,this.dict=dict,this.mcid=mcid,this.pageObjId=pageObjId,this.refObjId=refObjId,this.parentNode=null}}class StructTreePage{constructor(structTreeRoot,pageDict){this.root=structTreeRoot,this.rootDict=structTreeRoot?structTreeRoot.dict:null,this.pageDict=pageDict,this.nodes=[]}parse(pageRef){if(this.root&&this.rootDict){var parentTree=this.rootDict.get("ParentTree");if(parentTree){var id=this.pageDict.get("StructParents"),pageRef=pageRef instanceof Ref&&this.root.structParentIds?.get(pageRef);if(Number.isInteger(id)||pageRef){var map=new Map,numberTree=new NumberTree(parentTree,this.rootDict.xref);if(Number.isInteger(id)){parentTree=numberTree.get(id);if(Array.isArray(parentTree))for(const ref of parentTree)ref instanceof Ref&&this.addNode(this.rootDict.xref.fetch(ref),map)}if(pageRef)for(var[elemId,type]of pageRef){var elemId=numberTree.get(elemId);elemId&&1===(elemId=this.addNode(this.rootDict.xref.fetchIfRef(elemId),map))?.kids?.length&&elemId.kids[0].type===StructElementType.OBJECT&&(elemId.kids[0].type=type)}}}}}addNode(dict,map,level=0){if(level>MAX_DEPTH)return warn("StructTree MAX_DEPTH reached."),null;if(map.has(dict))return map.get(dict);var element=new StructElementNode(this,dict),parent=(map.set(dict,element),dict.get("P"));if(!parent||isName(parent.get("Type"),"StructTreeRoot"))this.addTopLevelNode(dict,element)||map.delete(dict);else{parent=this.addNode(parent,map,level+1);if(parent){let save=!1;for(const kid of parent.kids)kid.type===StructElementType.ELEMENT&&kid.dict===dict&&(kid.parentNode=element,save=!0);save||map.delete(dict)}}return element}addTopLevelNode(dict,element){var obj=this.rootDict.get("K");if(!obj)return!1;if(obj instanceof Dict)return obj.objId===dict.objId&&(this.nodes[0]=element,!0);if(!Array.isArray(obj))return!0;let save=!1;for(let i=0;iMAX_DEPTH)warn("StructTree too deep to be fully serialized.");else{var obj=Object.create(null);obj.role=node.role,obj.children=[],parent.children.push(obj),"string"==typeof(parent=node.dict.get("Alt"))&&(obj.alt=stringToPDFString(parent)),"string"==typeof(parent=node.dict.get("Lang"))&&(obj.lang=stringToPDFString(parent));for(const kid of node.kids){var kidElement=kid.type===StructElementType.ELEMENT?kid.parentNode:null;kidElement?nodeToSerializable(kidElement,obj,level+1):kid.type===StructElementType.PAGE_CONTENT||kid.type===StructElementType.STREAM_CONTENT?obj.children.push({type:"content",id:`p${kid.pageObjId}_mc`+kid.mcid}):kid.type===StructElementType.OBJECT?obj.children.push({type:"object",id:kid.refObjId}):kid.type===StructElementType.ANNOTATION&&obj.children.push({type:"annotation",id:""+AnnotationPrefix+kid.refObjId})}}}(child,root);return root}}function isValidExplicitDest(dest){if(!Array.isArray(dest)||dest.length<2)return!1;var[dest,zoom,...args]=dest;if(!(dest instanceof Ref||Number.isInteger(dest)))return!1;if(!(zoom instanceof Name))return!1;let allowNull=!0;switch(zoom.name){case"XYZ":if(3!==args.length)return!1;break;case"Fit":case"FitB":return 0===args.length;case"FitH":case"FitBH":case"FitV":case"FitBV":if(1!==args.length)return!1;break;case"FitR":if(4!==args.length)return!1;allowNull=!1;break;default:return!1}for(const arg of args)if(!("number"==typeof arg||allowNull&&null===arg))return!1;return!0}function fetchDest(dest){return isValidExplicitDest(dest=dest instanceof Dict?dest.get("D"):dest)?dest:null}function fetchRemoteDest(action){let dest=action.get("D");if(dest){if("string"==typeof(dest=dest instanceof Name?dest.name:dest))return stringToPDFString(dest);if(isValidExplicitDest(dest))return JSON.stringify(dest)}return null}class Catalog{constructor(pdfManager,xref){if(this.pdfManager=pdfManager,this.xref=xref,this._catDict=xref.getCatalogObj(),!(this._catDict instanceof Dict))throw new FormatError("Catalog object is not a dictionary.");this.toplevelPagesDict,this._actualNumPages=null,this.fontCache=new RefSetCache,this.builtInCMapCache=new Map,this.standardFontDataCache=new Map,this.globalImageCache=new GlobalImageCache,this.pageKidsCountCache=new RefSetCache,this.pageIndexCache=new RefSetCache,this.nonBlendModesSet=new RefSet,this.systemFontCache=new Map}cloneDict(){return this._catDict.clone()}get version(){var version=this._catDict.get("Version");if(version instanceof Name){if(PDF_VERSION_REGEXP.test(version.name))return shadow(this,"version",version.name);warn("Invalid PDF catalog version: "+version.name)}return shadow(this,"version",null)}get lang(){var lang=this._catDict.get("Lang");return shadow(this,"lang","string"==typeof lang?stringToPDFString(lang):null)}get needsRendering(){var needsRendering=this._catDict.get("NeedsRendering");return shadow(this,"needsRendering","boolean"==typeof needsRendering&&needsRendering)}get collection(){let collection=null;try{var obj=this._catDict.get("Collection");obj instanceof Dict&&0i instanceof Name)&&(groupRef.intent=intent.map(i=>i.name));name=group.get("Usage");if(name instanceof Dict){var usageObj=groupRef.usage,group=name.get("Print");if(group instanceof Dict){var printState=group.get("PrintState");if(printState instanceof Name)switch(printState.name){case"ON":case"OFF":usageObj.print={printState:printState.name}}}group=name.get("View");if(group instanceof Dict){var viewState=group.get("ViewState");if(viewState instanceof Name)switch(viewState.name){case"ON":case"OFF":usageObj.view={viewState:viewState.name}}}}return groupRef}#readOptionalContentConfig(config,contentGroupRefs){function parseOnOff(refs){var onParsed=[];if(Array.isArray(refs))for(const value of refs)value instanceof Ref&&contentGroupRefs.has(value)&&onParsed.push(value.toString());return onParsed}function parseOrder(refs,nestedLevels=0){if(!Array.isArray(refs))return null;var nestedOrder,order=[];for(const value of refs)value instanceof Ref&&contentGroupRefs.has(value)?(parsedOrderRefs.put(value),order.push(value.toString())):(nestedOrder=function(ref,nestedLevels){if(++nestedLevels>MAX_NESTED_LEVELS)return warn("parseNestedOrder - reached MAX_NESTED_LEVELS."),null;ref=xref.fetchIfRef(ref);if(!Array.isArray(ref))return null;var nestedName=xref.fetchIfRef(ref[0]);if("string"!=typeof nestedName)return null;ref=parseOrder(ref.slice(1),nestedLevels);return ref&&ref.length?{name:stringToPDFString(nestedName),order:ref}:null}(value,nestedLevels))&&order.push(nestedOrder);if(!(0Number.isInteger(page)&&0=arr[i-1])&&page<=this.numPages)&&(prefValue=value);break;case"NumCopies":Number.isInteger(value)&&0=kids.length)queue.pop();else{var currentNode=kids[posInKids];let obj;if(currentNode instanceof Ref){if(visitedNodes.has(currentNode)){addPageError(new FormatError("Pages tree contains circular reference."));break}visitedNodes.put(currentNode);try{obj=await xref.fetchAsync(currentNode)}catch(ex){addPageError(ex);break}}else obj=currentNode;if(!(obj instanceof Dict)){addPageError(new FormatError("Page dictionary kid reference points to wrong type of object."));break}let type=obj.getRaw("Type");if(type instanceof Ref)try{type=await xref.fetchAsync(type)}catch(ex){addPageError(ex);break}isName(type,"Page")||!obj.has("Kids")?(posInKids=obj,(currentNode=currentNode instanceof Ref?currentNode:null)&&!pageIndexCache.has(currentNode)&&pageIndexCache.put(currentNode,pageIndex),map.set(pageIndex++,[posInKids,currentNode])):queue.push({currentNode:obj,posInKids:0}),queueItem.posInKids++}}return map}getPageIndex(pageRef){var cachedPageIndex=this.pageIndexCache.get(pageRef);if(void 0!==cachedPageIndex)return Promise.resolve(cachedPageIndex);const xref=this.xref;let total=0;const next=ref=>function(kidRef){let total=0,parentRef;return xref.fetchAsync(kidRef).then(function(node){if(isRefsEqual(kidRef,pageRef)&&!isDict(node,"Page")&&!(node instanceof Dict&&!node.has("Type")&&node.has("Contents")))throw new FormatError("The reference does not point to a /Page dictionary.");if(!node)return null;if(node instanceof Dict)return parentRef=node.getRaw("Parent"),node.getAsync("Parent");throw new FormatError("Node must be a dictionary.")}).then(function(parent){if(!parent)return null;if(parent instanceof Dict)return parent.getAsync("Kids");throw new FormatError("Parent must be a dictionary.")}).then(function(kids){if(!kids)return null;var kidPromises=[];let found=!1;for(const kid of kids){if(!(kid instanceof Ref))throw new FormatError("Kid must be a reference.");if(isRefsEqual(kid,kidRef)){found=!0;break}kidPromises.push(xref.fetchAsync(kid).then(function(obj){if(!(obj instanceof Dict))throw new FormatError("Kid node must be a dictionary.");obj.has("Count")?total+=obj.get("Count"):total++}))}if(found)return Promise.all(kidPromises).then(function(){return[total,parentRef]});throw new FormatError("Kid reference not found in parent's kids.")})}(ref).then(args=>{var parentRef;return args?([args,parentRef]=args,total+=args,next(parentRef)):(this.pageIndexCache.put(pageRef,total),total)});return next(pageRef)}get baseUrl(){var uri=this._catDict.get("URI");if(uri instanceof Dict){uri=uri.get("Base");if("string"==typeof uri){uri=createValidAbsoluteUrl(uri,null,{tryConvertEncoding:!0});if(uri)return shadow(this,"baseUrl",uri.href)}}return shadow(this,"baseUrl",this.pdfManager.docBaseUrl)}static parseDestDictionary({destDict,resultObj,docBaseUrl=null,docAttachments=null}){if(destDict instanceof Dict){let action=destDict.get("A"),url,dest;if(action instanceof Dict||(destDict.has("Dest")?action=destDict.get("Dest"):(action=destDict.get("AA"))instanceof Dict&&(action.has("D")?action=action.get("D"):action.has("U")&&(action=action.get("U")))),action instanceof Dict){var actionType=action.get("S");if(!(actionType instanceof Name))return void warn("parseDestDictionary: Invalid type in Action dictionary.");var actionName=actionType.name;switch(actionName){case"ResetForm":var flags=action.get("Flags"),flags=0==(1&("number"==typeof flags?flags:0)),fields=[],refs=[];for(const obj of action.get("Fields")||[])obj instanceof Ref?refs.push(obj.toString()):"string"==typeof obj&&fields.push(stringToPDFString(obj));resultObj.resetForm={fields:fields,refs:refs,include:flags};break;case"URI":(url=action.get("URI"))instanceof Name&&(url="/"+url.name);break;case"GoTo":dest=action.get("D");break;case"Launch":case"GoToR":var flags=action.get("F"),filename=(flags instanceof Dict?(filename=new FileSpec(flags,null,!0).serializable["filename"],url=filename):"string"==typeof flags&&(url=flags),fetchRemoteDest(action)),flags=(filename&&"string"==typeof url&&(url=url.split("#",1)[0]+"#"+filename),action.get("NewWindow"));"boolean"==typeof flags&&(resultObj.newWindow=flags);break;case"GoToE":var filename=action.get("T");let attachment;(attachment=docAttachments&&filename instanceof Dict&&(flags=filename.get("R"),filename=filename.get("N"),isName(flags,"C"))&&"string"==typeof filename?docAttachments[stringToPDFString(filename)]:attachment)?(resultObj.attachment=attachment,(flags=fetchRemoteDest(action))&&(resultObj.attachmentDest=flags)):warn('parseDestDictionary - unimplemented "GoToE" action.');break;case"Named":filename=action.get("N");filename instanceof Name&&(resultObj.action=filename.name);break;case"SetOCGState":flags=action.get("State"),filename=action.get("PreserveRB");if(Array.isArray(flags)&&0!==flags.length){var stateArr=[];for(const elem of flags)if(elem instanceof Name)switch(elem.name){case"ON":case"OFF":case"Toggle":stateArr.push(elem.name)}else elem instanceof Ref&&stateArr.push(elem.toString());stateArr.length===flags.length&&(resultObj.setOCGState={state:stateArr,preserveRB:"boolean"!=typeof filename||filename})}break;case"JavaScript":flags=action.get("JS");let js;flags instanceof BaseStream?js=flags.getString():"string"==typeof flags&&(js=flags);filename=js&&recoverJsURL(stringToPDFString(js));if(filename){url=filename.url,resultObj.newWindow=filename.newWindow;break}default:"JavaScript"!==actionName&&"SubmitForm"!==actionName&&warn(`parseDestDictionary - unsupported action: "${actionName}".`)}}else destDict.has("Dest")&&(dest=destDict.get("Dest"));"string"==typeof url&&((actionType=createValidAbsoluteUrl(url,docBaseUrl,{addDefaultProtocol:!0,tryConvertEncoding:!0}))&&(resultObj.url=actionType.href),resultObj.unsafeUrl=url),dest&&("string"==typeof(dest=dest instanceof Name?dest.name:dest)?resultObj.dest=stringToPDFString(dest):isValidExplicitDest(dest)&&(resultObj.dest=dest))}else warn("parseDestDictionary: `destDict` must be a dictionary.")}}function mayHaveChildren(value){return value instanceof Ref||value instanceof Dict||value instanceof BaseStream||Array.isArray(value)}function addChildren(node,nodesToVisit){if(node instanceof Dict)node=node.getRawValues();else if(node instanceof BaseStream)node=node.dict.getRawValues();else if(!Array.isArray(node))return;for(const rawValue of node)mayHaveChildren(rawValue)&&nodesToVisit.push(rawValue)}class ObjectLoader{constructor(dict,keys,xref){this.dict=dict,this.keys=keys,this.xref=xref,this.refSet=null}async load(){if(!this.xref.stream.isDataLoaded){var{keys,dict}=this,nodesToVisit=(this.refSet=new RefSet,[]);for(const key of keys){var rawValue=dict.getRaw(key);void 0!==rawValue&&nodesToVisit.push(rawValue)}return this._walk(nodesToVisit)}}async _walk(nodesToVisit){for(var nodesToRevisit=[],pendingRequests=[];nodesToVisit.length;){let currentNode=nodesToVisit.pop();if(currentNode instanceof Ref){if(this.refSet.has(currentNode))continue;try{this.refSet.put(currentNode),currentNode=this.xref.fetch(currentNode)}catch(ex){if(!(ex instanceof MissingDataException))return warn(`ObjectLoader._walk - requesting all data: "${ex}".`),this.refSet=null,manager=this.xref.stream["manager"],manager.requestAllChunks();nodesToRevisit.push(currentNode),pendingRequests.push({begin:ex.begin,end:ex.end})}}if(currentNode instanceof BaseStream){var manager=currentNode.getBaseStreams();if(manager){let foundMissingData=!1;for(const stream of manager)stream.isDataLoaded||(foundMissingData=!0,pendingRequests.push({begin:stream.start,end:stream.end}));foundMissingData&&nodesToRevisit.push(currentNode)}}addChildren(currentNode,nodesToVisit)}if(pendingRequests.length){await this.xref.stream.manager.requestRanges(pendingRequests);for(const node of nodesToRevisit)node instanceof Ref&&this.refSet.remove(node);return this._walk(nodesToRevisit)}this.refSet=null}}const $acceptWhitespace=Symbol(),$addHTML=Symbol(),$appendChild=Symbol(),$childrenToHTML=Symbol(),$clean=Symbol(),$cleanPage=Symbol(),$cleanup=Symbol(),$clone=Symbol(),$consumed=Symbol(),$content=Symbol("content"),$data=Symbol("data"),$dump=Symbol(),$extra=Symbol("extra"),$finalize=Symbol(),$flushHTML=Symbol(),$getAttributeIt=Symbol(),$getAttributes=Symbol(),$getAvailableSpace=Symbol(),$getChildrenByClass=Symbol(),$getChildrenByName=Symbol(),$getChildrenByNameIt=Symbol(),$getDataValue=Symbol(),$getExtra=Symbol(),$getRealChildrenByNameIt=Symbol(),$getChildren=Symbol(),$getContainedChildren=Symbol(),$getNextPage=Symbol(),$getSubformParent=Symbol(),$getParent=Symbol(),$getTemplateRoot=Symbol(),$globalData=Symbol(),$hasSettableValue=Symbol(),$ids=Symbol(),$indexOf=Symbol(),$insertAt=Symbol(),$isCDATAXml=Symbol(),$isBindable=Symbol(),$isDataValue=Symbol(),$isDescendent=Symbol(),$isNsAgnostic=Symbol(),$isSplittable=Symbol(),$isThereMoreWidth=Symbol(),$isTransparent=Symbol(),$isUsable=Symbol(),$lastAttribute=Symbol(),$namespaceId=Symbol("namespaceId"),$nodeName=Symbol("nodeName"),$nsAttributes=Symbol(),$onChild=Symbol(),$onChildCheck=Symbol(),$onText=Symbol(),$pushGlyphs=Symbol(),$popPara=Symbol(),$pushPara=Symbol(),$removeChild=Symbol(),$root=Symbol("root"),$resolvePrototypes=Symbol(),$searchNode=Symbol(),$setId=Symbol(),$setSetAttributes=Symbol(),$setValue=Symbol(),$tabIndex=Symbol(),$text=Symbol(),$toPages=Symbol(),$toHTML=Symbol(),$toString=Symbol(),$toStyle=Symbol(),$uid=Symbol("uid"),$buildXFAObject=Symbol(),NamespaceIds={config:{id:0,check:ns=>ns.startsWith("http://www.xfa.org/schema/xci/")},connectionSet:{id:1,check:ns=>ns.startsWith("http://www.xfa.org/schema/xfa-connection-set/")},datasets:{id:2,check:ns=>ns.startsWith("http://www.xfa.org/schema/xfa-data/")},form:{id:3,check:ns=>ns.startsWith("http://www.xfa.org/schema/xfa-form/")},localeSet:{id:4,check:ns=>ns.startsWith("http://www.xfa.org/schema/xfa-locale-set/")},pdf:{id:5,check:ns=>"http://ns.adobe.com/xdp/pdf/"===ns},signature:{id:6,check:ns=>"http://www.w3.org/2000/09/xmldsig#"===ns},sourceSet:{id:7,check:ns=>ns.startsWith("http://www.xfa.org/schema/xfa-source-set/")},stylesheet:{id:8,check:ns=>"http://www.w3.org/1999/XSL/Transform"===ns},template:{id:9,check:ns=>ns.startsWith("http://www.xfa.org/schema/xfa-template/")},xdc:{id:10,check:ns=>ns.startsWith("http://www.xfa.org/schema/xdc/")},xdp:{id:11,check:ns=>"http://ns.adobe.com/xdp/"===ns},xfdf:{id:12,check:ns=>"http://ns.adobe.com/xfdf/"===ns},xhtml:{id:13,check:ns=>"http://www.w3.org/1999/xhtml"===ns},xmpmeta:{id:14,check:ns=>"http://ns.adobe.com/xmpmeta/"===ns}},dimConverters={pt:x=>x,cm:x=>x/2.54*72,mm:x=>x/25.4*72,in:x=>72*x,px:x=>x},measurementPattern=/([+-]?\d+\.?\d*)(.*)/;function stripQuotes(str){return str.startsWith("'")||str.startsWith('"')?str.slice(1,-1):str}function getInteger({data,defaultValue,validate}){if(!data)return defaultValue;data=data.trim();data=parseInt(data,10);return!isNaN(data)&&validate(data)?data:defaultValue}function getFloat({data,defaultValue,validate}){if(!data)return defaultValue;data=data.trim();data=parseFloat(data);return!isNaN(data)&&validate(data)?data:defaultValue}function getKeyword({data,defaultValue,validate}){return data&&validate(data=data.trim())?data:defaultValue}function getStringOption(data,options){return getKeyword({data:data,defaultValue:options[0],validate:k=>options.includes(k)})}function getMeasurement(str,def="0"){var unit;return def||="0",!str||!(str=str.trim().match(measurementPattern))||([,str,unit]=str,str=parseFloat(str),isNaN(str))?getMeasurement(def):0===str?0:(unit=dimConverters[unit])?unit(str):str}function getRatio(data){var den;return!data||(1===(data=data.trim().split(/\s*:\s*/).map(x=>parseFloat(x)).filter(x=>!isNaN(x))).length&&data.push(1),0===data.length)?{num:1,den:1}:([data,den]=data,{num:data,den:den})}function getRelevant(data){return data?data.trim().split(/\s+/).map(e=>({excluded:"-"===e[0],viewname:e.substring(1)})):[]}function getColor(data,def=[0,0,0]){var[def,g,b]=def;return!data||(data=data.trim().split(/\s*,\s*/).map(c=>Math.min(Math.max(0,parseInt(c.trim(),10)),255)).map(c=>isNaN(c)?0:c)).length<3||([def,g,b]=data),{r:def,g:g,b:b}}function getBBox(data){var y,width,height;return!data||(data=data.trim().split(/\s*,\s*/).map(m=>getMeasurement(m,"-1"))).length<4||data[2]<0||data[3]<0?{x:-1,y:-1,width:-1,height:-1}:([data,y,width,height]=data,{x:data,y:y,width:width,height:height})}class HTMLResult{static get FAILURE(){return shadow(this,"FAILURE",new HTMLResult(!1,null,null,null))}static get EMPTY(){return shadow(this,"EMPTY",new HTMLResult(!0,null,null,null))}constructor(success,html,bbox,breakNode){this.success=success,this.html=html,this.bbox=bbox,this.breakNode=breakNode}isBreak(){return!!this.breakNode}static breakNode(node){return new HTMLResult(!1,null,null,node)}static success(html,bbox=null){return new HTMLResult(!0,html,bbox,null)}}class FontFinder{constructor(pdfFonts){this.fonts=new Map,this.cache=new Map,this.warned=new Set,this.defaultFont=null,this.add(pdfFonts)}add(pdfFonts,reallyMissingFonts=null){for(const pdfFont of pdfFonts)this.addPdfFont(pdfFont);for(const pdfFont of this.fonts.values())pdfFont.regular||(pdfFont.regular=pdfFont.italic||pdfFont.bold||pdfFont.bolditalic);if(reallyMissingFonts&&0!==reallyMissingFonts.size){var myriad=this.fonts.get("PdfJS-Fallback-PdfJS-XFA");for(const missing of reallyMissingFonts)this.fonts.set(missing,myriad)}}addPdfFont(pdfFont){var cssFontInfo=pdfFont.cssFontInfo,name=cssFontInfo.fontFamily;let font=this.fonts.get(name),property=(font||(font=Object.create(null),this.fonts.set(name,font),this.defaultFont)||(this.defaultFont=font),"");name=parseFloat(cssFontInfo.fontWeight);0!==parseFloat(cssFontInfo.italicAngle)?property=700<=name?"bolditalic":"italic":700<=name&&(property="bold"),!property&&((pdfFont.name.includes("Bold")||pdfFont.psName?.includes("Bold"))&&(property="bold"),pdfFont.name.includes("Italic")||pdfFont.name.endsWith("It")||pdfFont.psName?.includes("Italic")||pdfFont.psName?.endsWith("It"))&&(property+="italic"),property=property||"regular",font[property]=pdfFont}getDefault(){return this.defaultFont}find(fontName,mustWarn=!0){var font=this.fonts.get(fontName)||this.cache.get(fontName);if(font)return font;var pattern=/,|-|_| |bolditalic|bold|italic|regular|it/gi;let name=fontName.replaceAll(pattern,"");if(font=this.fonts.get(name))return this.cache.set(fontName,font),font;name=name.toLowerCase();var family,pdfFont,maybe=[];for([family,pdfFont]of this.fonts.entries())family.replaceAll(pattern,"").toLowerCase().startsWith(name)&&maybe.push(pdfFont);if(0===maybe.length)for(const[,pdfFont]of this.fonts.entries())pdfFont.regular.name?.replaceAll(pattern,"").toLowerCase().startsWith(name)&&maybe.push(pdfFont);if(0===maybe.length){name=name.replaceAll(/psmt|mt/gi,"");for(const[family,pdfFont]of this.fonts.entries())family.replaceAll(pattern,"").toLowerCase().startsWith(name)&&maybe.push(pdfFont)}if(0===maybe.length)for(const pdfFont of this.fonts.values())pdfFont.regular.name?.replaceAll(pattern,"").toLowerCase().startsWith(name)&&maybe.push(pdfFont);return 1<=maybe.length?(1!==maybe.length&&mustWarn&&warn("XFA - Too many choices to guess the correct font: "+fontName),this.cache.set(fontName,maybe[0]),maybe[0]):(mustWarn&&!this.warned.has(fontName)&&(this.warned.add(fontName),warn("XFA - Cannot find the font: "+fontName)),null)}}function selectFont(xfaFont,typeface){return"italic"===xfaFont.posture?"bold"===xfaFont.weight?typeface.bolditalic:typeface.italic:"bold"===xfaFont.weight?typeface.bold:typeface.regular}function fonts_getMetrics(xfaFont,real=!1){let pdfFont=null;var name;return xfaFont&&(name=stripQuotes(xfaFont.typeface),name=xfaFont[$globalData].fontFinder.find(name),pdfFont=selectFont(xfaFont,name)),pdfFont?(name=xfaFont.size||10,{lineHeight:(xfaFont=pdfFont.lineHeight?Math.max(real?0:1.2,pdfFont.lineHeight):1.2)*name,lineGap:(real=void 0===pdfFont.lineGap?.2:pdfFont.lineGap)*name,lineNoGap:Math.max(1,xfaFont-real)*name}):{lineHeight:12,lineGap:2,lineNoGap:10}}const WIDTH_FACTOR=1.02;class FontInfo{constructor(xfaFont,margin,lineHeight,fontFinder){this.lineHeight=lineHeight,this.paraMargin=margin||{top:0,bottom:0,left:0,right:0},xfaFont&&(this.xfaFont={typeface:xfaFont.typeface,posture:xfaFont.posture,weight:xfaFont.weight,size:xfaFont.size,letterSpacing:xfaFont.letterSpacing},lineHeight=fontFinder.find(xfaFont.typeface))&&(this.pdfFont=selectFont(xfaFont,lineHeight),this.pdfFont)||([this.pdfFont,this.xfaFont]=this.defaultFont(fontFinder))}defaultFont(fontFinder){fontFinder=fontFinder.find("Helvetica",!1)||fontFinder.find("Myriad Pro",!1)||fontFinder.find("Arial",!1)||fontFinder.getDefault();if(fontFinder?.regular){fontFinder=fontFinder.regular;const xfaFont={typeface:fontFinder.cssFontInfo.fontFamily,posture:"normal",weight:"normal",size:10,letterSpacing:0};return[fontFinder,xfaFont]}const xfaFont={typeface:"Courier",posture:"normal",weight:"normal",size:10,letterSpacing:0};return[null,xfaFont]}}class FontSelector{constructor(defaultXfaFont,defaultParaMargin,defaultLineHeight,fontFinder){this.fontFinder=fontFinder,this.stack=[new FontInfo(defaultXfaFont,defaultParaMargin,defaultLineHeight,fontFinder)]}pushData(xfaFont,margin,lineHeight){var lastFont=this.stack.at(-1);for(const name of["typeface","posture","weight","size","letterSpacing"])xfaFont[name]||(xfaFont[name]=lastFont.xfaFont[name]);for(const name of["top","bottom","left","right"])isNaN(margin[name])&&(margin[name]=lastFont.paraMargin[name]);lineHeight=new FontInfo(xfaFont,margin,lineHeight||lastFont.lineHeight,this.fontFinder);lineHeight.pdfFont||(lineHeight.pdfFont=lastFont.pdfFont),this.stack.push(lineHeight)}popFont(){this.stack.pop()}topFont(){return this.stack.at(-1)}}class TextMeasure{constructor(defaultXfaFont,defaultParaMargin,defaultLineHeight,fonts){this.glyphs=[],this.fontSelector=new FontSelector(defaultXfaFont,defaultParaMargin,defaultLineHeight,fonts),this.extraHeight=0}pushData(xfaFont,margin,lineHeight){this.fontSelector.pushData(xfaFont,margin,lineHeight)}popFont(xfaFont){return this.fontSelector.popFont()}addPara(){var lastFont=this.fontSelector.topFont();this.extraHeight+=lastFont.paraMargin.top+lastFont.paraMargin.bottom}addString(str){if(str){var lastFont=this.fontSelector.topFont(),fontSize=lastFont.xfaFont.size;if(lastFont.pdfFont){var letterSpacing=lastFont.xfaFont.letterSpacing,pdfFont=lastFont.pdfFont,fontLineHeight=pdfFont.lineHeight||1.2,lineHeight=lastFont.lineHeight||Math.max(1.2,fontLineHeight)*fontSize,lastFont=void 0===pdfFont.lineGap?.2:pdfFont.lineGap,firstLineHeight=Math.max(1,fontLineHeight-lastFont)*fontSize,scale=fontSize/1e3,fallbackWidth=pdfFont.defaultWidth||pdfFont.charsToGlyphs(" ")[0].width;for(const line of str.split(/[\u2029\n]/)){var encodedLine=pdfFont.encodeString(line).join("");for(const glyph of pdfFont.charsToGlyphs(encodedLine)){var width=glyph.width||fallbackWidth;this.glyphs.push([width*scale+letterSpacing,lineHeight,firstLineHeight,glyph.unicode,!1])}this.glyphs.push([0,0,0,"\n",!0])}}else for(const line of str.split(/[\u2029\n]/)){for(const char of line.split(""))this.glyphs.push([fontSize,1.2*fontSize,fontSize,char,!1]);this.glyphs.push([0,0,0,"\n",!0])}this.glyphs.pop()}}compute(maxWidth){let lastSpacePos=-1,lastSpaceWidth=0,width=0,height=0,currentLineWidth=0,currentLineHeight=0,isBroken=!1,isFirstLine=!0;for(let i=0,ii=this.glyphs.length;imaxWidth?(width=Math.max(width,currentLineWidth),currentLineWidth=0,height+=currentLineHeight,currentLineHeight=firstLineHeight,lastSpacePos=-1,lastSpaceWidth=0,isBroken=!0,isFirstLine=!1):(currentLineHeight=Math.max(firstLineHeight,currentLineHeight),lastSpaceWidth=currentLineWidth,currentLineWidth+=glyphWidth,lastSpacePos=i):currentLineWidth+glyphWidth>maxWidth?(height+=currentLineHeight,currentLineHeight=firstLineHeight,-1!==lastSpacePos?(i=lastSpacePos,width=Math.max(width,lastSpaceWidth),currentLineWidth=0,lastSpacePos=-1,lastSpaceWidth=0):(width=Math.max(width,currentLineWidth),currentLineWidth=glyphWidth),isBroken=!0,isFirstLine=!1):(currentLineWidth+=glyphWidth,currentLineHeight=Math.max(firstLineHeight,currentLineHeight))}return width=Math.max(width,currentLineWidth),height+=currentLineHeight+this.extraHeight,{width:WIDTH_FACTOR*width,height:height,isBroken:isBroken}}}const namePattern=/^[^.[]+/,indexPattern=/^[^\]]+/,operators={dot:0,dotDot:1,dotHash:2,dotBracket:3,dotParen:4},shortcuts=new Map([["$data",(root,current)=>root.datasets?root.datasets.data:root],["$record",(root,current)=>(root.datasets?root.datasets.data:root)[$getChildren]()[0]],["$template",(root,current)=>root.template],["$connectionSet",(root,current)=>root.connectionSet],["$form",(root,current)=>root.form],["$layout",(root,current)=>root.layout],["$host",(root,current)=>root.host],["$dataWindow",(root,current)=>root.dataWindow],["$event",(root,current)=>root.event],["!",(root,current)=>root.datasets],["$xfa",(root,current)=>root],["xfa",(root,current)=>root],["$",(root,current)=>current]]),somCache=new WeakMap;function parseIndex(index){return"*"===(index=index.trim())?1/0:parseInt(index,10)||0}function parseExpression(expr,dotDotAllowed,noExpr=!0){let match=expr.match(namePattern);if(!match)return null;var[name]=match,parsed=[{name:name,cacheName:"."+name,index:0,js:null,formCalc:null,operator:operators.dot}];let pos=name.length;for(;posindexnode[index]):nodes.flat();else{if(!(container=container[$getParent]()))return null;i=-1,root=[container]}}return 0===root.length?null:root}function createDataNode(root,container,expr){var parsed=parseExpression(expr);if(parsed&&!parsed.some(x=>x.operator===operators.dotDot)){expr=shortcuts.get(parsed[0].name);let i=0;expr?(root=expr(root,container),i=1):root=container||root;for(var ii=parsed.length;ic[$text]()).join("")}get[_attributeNames](){var proto=Object.getPrototypeOf(this);if(!proto._attributes){var attributes=proto._attributes=new Set;for(const name of Object.getOwnPropertyNames(this)){if(null===this[name]||this[name]instanceof XFAObject||this[name]instanceof XFAObjectArray)break;attributes.add(name)}}return shadow(this,_attributeNames,proto._attributes)}[$isDescendent](parent){let node=this;for(;node;){if(node===parent)return!0;node=node[$getParent]()}return!1}[$getParent](){return this[_parent]}[$getSubformParent](){return this[$getParent]()}[$getChildren](name=null){return name?this[name]:this[_children]}[$dump](){var dumped=Object.create(null);this[$content]&&(dumped.$content=this[$content]);for(const name of Object.getOwnPropertyNames(this)){var value=this[name];null!==value&&(value instanceof XFAObject?dumped[name]=value[$dump]():value instanceof XFAObjectArray?value.isEmpty()||(dumped[name]=value.dump()):dumped[name]=value)}return dumped}[$toStyle](){return null}[$toHTML](){return HTMLResult.EMPTY}*[$getContainedChildren](){for(const node of this[$getChildren]())yield node}*[_filteredChildrenGenerator](filter,include){for(const node of this[$getContainedChildren]()){var availableSpace;filter&&include!==filter.has(node[$nodeName])||(availableSpace=this[$getAvailableSpace](),(availableSpace=node[$toHTML](availableSpace)).success||(this[$extra].failingNode=node),yield availableSpace)}}[$flushHTML](){return null}[$addHTML](html,bbox){this[$extra].children.push(html)}[$getAvailableSpace](){}[$childrenToHTML]({filter=null,include=!0}){if(this[$extra].generator){var availableSpace=this[$getAvailableSpace](),availableSpace=this[$extra].failingNode[$toHTML](availableSpace);if(!availableSpace.success)return availableSpace;availableSpace.html&&this[$addHTML](availableSpace.html,availableSpace.bbox),delete this[$extra].failingNode}else this[$extra].generator=this[_filteredChildrenGenerator](filter,include);for(;;){var gen=this[$extra].generator.next();if(gen.done)break;const res=gen.value;if(!res.success)return res;res.html&&this[$addHTML](res.html,res.bbox)}return this[$extra].generator=null,HTMLResult.EMPTY}[$setSetAttributes](attributes){this[_setAttributes]=new Set(Object.keys(attributes))}[_getUnsetAttributes](protoAttributes){const allAttr=this[_attributeNames],setAttr=this[_setAttributes];return[...protoAttributes].filter(x=>allAttr.has(x)&&!setAttr.has(x))}[$resolvePrototypes](ids,ancestors=new Set){for(const child of this[_children])child[_resolvePrototypesHelper](ids,ancestors)}[_resolvePrototypesHelper](ids,ancestors){var proto=this[_getPrototype](ids,ancestors);proto?this[_applyPrototype](proto,ids,ancestors):this[$resolvePrototypes](ids,ancestors)}[_getPrototype](ids,ancestors){var{use,usehref}=this;if(!use&&!usehref)return null;let proto=null,somExpression=null,id=null,ref=use;if(usehref?(ref=usehref).startsWith("#som(")&&usehref.endsWith(")")?somExpression=usehref.slice("#som(".length,-1):usehref.startsWith(".#som(")&&usehref.endsWith(")")?somExpression=usehref.slice(".#som(".length,-1):usehref.startsWith("#")?id=usehref.slice(1):usehref.startsWith(".#")&&(id=usehref.slice(2)):use.startsWith("#")?id=use.slice(1):somExpression=use,this.use=this.usehref="",!(proto=id?ids.get(id):(proto=searchNode(ids.get($root),this,somExpression,!0,!1))&&proto[0]))return warn(`XFA - Invalid prototype reference: ${ref}.`),null;if(proto[$nodeName]!==this[$nodeName])return warn(`XFA - Incompatible prototype: ${proto[$nodeName]} !== ${this[$nodeName]}.`),null;if(ancestors.has(proto))return warn("XFA - Cycle detected in prototypes use."),null;ancestors.add(proto);usehref=proto[_getPrototype](ids,ancestors);return usehref&&proto[_applyPrototype](usehref,ids,ancestors),proto[$resolvePrototypes](ids,ancestors),ancestors.delete(proto),proto}[_applyPrototype](proto,ids,ancestors){if(ancestors.has(proto))warn("XFA - Cycle detected in prototypes use.");else{!this[$content]&&proto[$content]&&(this[$content]=proto[$content]),new Set(ancestors).add(proto);for(const unsetAttrName of this[_getUnsetAttributes](proto[_setAttributes]))this[unsetAttrName]=proto[unsetAttrName],this[_setAttributes]&&this[_setAttributes].add(unsetAttrName);for(const name of Object.getOwnPropertyNames(this))if(!this[_attributeNames].has(name)){var value=this[name],protoValue=proto[name];if(value instanceof XFAObjectArray){for(const child of value[_children])child[_resolvePrototypesHelper](ids,ancestors);for(let i=value[_children].length,ii=protoValue[_children].length;iXFAObject[_cloneAttribute](x)):"object"==typeof obj&&null!==obj?Object.assign({},obj):obj}[$clone](){var value,clone=Object.create(Object.getPrototypeOf(this));for(const $symbol of Object.getOwnPropertySymbols(this))try{clone[$symbol]=this[$symbol]}catch{shadow(clone,$symbol,this[$symbol])}clone[$uid]=""+clone[$nodeName]+uid++,clone[_children]=[];for(const name of Object.getOwnPropertyNames(this))this[_attributeNames].has(name)?clone[name]=XFAObject[_cloneAttribute](this[name]):(value=this[name],clone[name]=value instanceof XFAObjectArray?new XFAObjectArray(value[_max]):null);for(const child of this[_children]){var name=child[$nodeName],clonedChild=child[$clone]();clone[_children].push(clonedChild),null===(clonedChild[_parent]=clone)[name]?clone[name]=clonedChild:clone[name][_children].push(clonedChild)}return clone}[$getChildren](name=null){return name?this[_children].filter(c=>c[$nodeName]===name):this[_children]}[$getChildrenByClass](name){return this[name]}[$getChildrenByName](name,allTransparent,first=!0){return Array.from(this[$getChildrenByNameIt](name,allTransparent,first))}*[$getChildrenByNameIt](name,allTransparent,first=!0){if("parent"===name)yield this[_parent];else{for(const child of this[_children])child[$nodeName]===name&&(yield child),child.name===name&&(yield child),(allTransparent||child[$isTransparent]())&&(yield*child[$getChildrenByNameIt](name,allTransparent,!1));first&&this[_attributeNames].has(name)&&(yield new XFAAttribute(this,name,this[name]))}}}class XFAObjectArray{constructor(max=1/0){this[_max]=max,this[_children]=[]}get isXFAObject(){return!1}get isXFAObjectArray(){return!0}push(child){return this[_children].length<=this[_max]?(this[_children].push(child),!0):(warn(`XFA - node "${child[$nodeName]}" accepts no more than ${this[_max]} children`),!1)}isEmpty(){return 0===this[_children].length}dump(){return 1===this[_children].length?this[_children][0][$dump]():this[_children].map(x=>x[$dump]())}[$clone](){var clone=new XFAObjectArray(this[_max]);return clone[_children]=this[_children].map(c=>c[$clone]()),clone}get children(){return this[_children]}clear(){this[_children].length=0}}class XFAAttribute{constructor(node,name,value){this[_parent]=node,this[$nodeName]=name,this[$content]=value,this[$consumed]=!1,this[$uid]="attribute"+uid++}[$getParent](){return this[_parent]}[$isDataValue](){return!0}[$getDataValue](){return this[$content].trim()}[$setValue](value){value=value.value||"",this[$content]=value.toString()}[$text](){return this[$content]}[$isDescendent](parent){return this[_parent]===parent||this[_parent][$isDescendent](parent)}}class XmlObject extends XFAObject{constructor(nsId,name,attributes={}){if(super(nsId,name),this[$content]="",this[_dataValue]=null,"#text"!==name){var attrName,value,map=new Map;this[_attributes]=map;for([attrName,value]of Object.entries(attributes))map.set(attrName,new XFAAttribute(this,attrName,value));attributes.hasOwnProperty($nsAttributes)&&void 0!==(nsId=attributes[$nsAttributes].xfa.dataNode)&&("dataGroup"===nsId?this[_dataValue]=!1:"dataValue"===nsId&&(this[_dataValue]=!0))}this[$consumed]=!1}[$toString](buf){var tagName=this[$nodeName];if("#text"===tagName)buf.push(encodeToXmlString(this[$content]));else{var name,value,tagName=utf8StringToString(tagName),prefix=this[$namespaceId]===NS_DATASETS?"xfa:":"";buf.push("<"+prefix+tagName);for([name,value]of this[_attributes].entries()){var utf8Name=utf8StringToString(name);buf.push(` ${utf8Name}="${encodeToXmlString(value[$content])}"`)}if(null!==this[_dataValue]&&(this[_dataValue]?buf.push(' xfa:dataNode="dataValue"'):buf.push(' xfa:dataNode="dataGroup"')),this[$content]||0!==this[_children].length){if(buf.push(">"),this[$content])"string"==typeof this[$content]?buf.push(encodeToXmlString(this[$content])):this[$content][$toString](buf);else for(const child of this[_children])child[$toString](buf);buf.push(``)}else buf.push("/>")}}[$onChild](child){var node;return this[$content]&&(node=new XmlObject(this[$namespaceId],"#text"),this[$appendChild](node),node[$content]=this[$content],this[$content]=""),this[$appendChild](child),!0}[$onText](str){this[$content]+=str}[$finalize](){var node;this[$content]&&0c[$nodeName]===name):this[_children]}[$getAttributes](){return this[_attributes]}[$getChildrenByClass](name){var value=this[_attributes].get(name);return void 0!==value?value:this[$getChildren](name)}*[$getChildrenByNameIt](name,allTransparent){var value=this[_attributes].get(name);value&&(yield value);for(const child of this[_children])child[$nodeName]===name&&(yield child),allTransparent&&(yield*child[$getChildrenByNameIt](name,allTransparent))}*[$getAttributeIt](name,skipConsumed){var value=this[_attributes].get(name);!value||skipConsumed&&value[$consumed]||(yield value);for(const child of this[_children])yield*child[$getAttributeIt](name,skipConsumed)}*[$getRealChildrenByNameIt](name,allTransparent,skipConsumed){for(const child of this[_children])child[$nodeName]!==name||skipConsumed&&child[$consumed]||(yield child),allTransparent&&(yield*child[$getRealChildrenByNameIt](name,allTransparent,skipConsumed))}[$isDataValue](){return null===this[_dataValue]?0===this[_children].length||this[_children][0][$namespaceId]===NamespaceIds.xhtml.id:this[_dataValue]}[$getDataValue](){return null!==this[_dataValue]||0===this[_children].length?this[$content].trim():this[_children][0][$namespaceId]===NamespaceIds.xhtml.id?this[_children][0][$text]().trim():null}[$setValue](value){value=value.value||"",this[$content]=value.toString()}[$dump](hasNS=!1){var name,value,dumped=Object.create(null);hasNS&&(dumped.$ns=this[$namespaceId]),this[$content]&&(dumped.$content=this[$content]),dumped.$name=this[$nodeName],dumped.children=[];for(const child of this[_children])dumped.children.push(child[$dump](hasNS));dumped.attributes=Object.create(null);for([name,value]of this[_attributes])dumped.attributes[name]=value[$content];return dumped}}class ContentObject extends XFAObject{constructor(nsId,name){super(nsId,name),this[$content]=""}[$onText](text){this[$content]+=text}[$finalize](){}}class OptionObject extends ContentObject{constructor(nsId,name,options){super(nsId,name),this[_options]=options}[$finalize](){this[$content]=getKeyword({data:this[$content],defaultValue:this[_options][0],validate:k=>this[_options].includes(k)})}[$clean](builder){super[$clean](builder),delete this[_options]}}class StringObject extends ContentObject{[$finalize](){this[$content]=this[$content].trim()}}class IntegerObject extends ContentObject{constructor(nsId,name,defaultValue,validator){super(nsId,name),this[_defaultValue]=defaultValue,this[_validator]=validator}[$finalize](){this[$content]=getInteger({data:this[$content],defaultValue:this[_defaultValue],validate:this[_validator]})}[$clean](builder){super[$clean](builder),delete this[_defaultValue],delete this[_validator]}}class Option01 extends IntegerObject{constructor(nsId,name){super(nsId,name,0,n=>1===n)}}class Option10 extends IntegerObject{constructor(nsId,name){super(nsId,name,1,n=>0===n)}}function measureToString(m){return"string"==typeof m?"0px":Number.isInteger(m)?m+"px":m.toFixed(2)+"px"}const converters={anchorType(node,style){var parent=node[$getSubformParent]();if(parent&&(!parent.layout||"position"===parent.layout))switch("transform"in style||(style.transform=""),node.anchorType){case"bottomCenter":style.transform+="translate(-50%, -100%)";break;case"bottomLeft":style.transform+="translate(0,-100%)";break;case"bottomRight":style.transform+="translate(-100%,-100%)";break;case"middleCenter":style.transform+="translate(-50%,-50%)";break;case"middleLeft":style.transform+="translate(0,-50%)";break;case"middleRight":style.transform+="translate(-100%,-50%)";break;case"topCenter":style.transform+="translate(-50%,0)";break;case"topRight":style.transform+="translate(-100%,0)"}},dimensions(node,style){var parent=node[$getSubformParent]();let width=node.w;var height=node.h;if(parent.layout?.includes("row")){var parent=parent[$extra],colSpan=node.colSpan;let w;-1===colSpan?(w=parent.columnWidths.slice(parent.currentColumn).reduce((a,x)=>a+x,0),parent.currentColumn=0):(w=parent.columnWidths.slice(parent.currentColumn,parent.currentColumn+colSpan).reduce((a,x)=>a+x,0),parent.currentColumn=(parent.currentColumn+node.colSpan)%parent.columnWidths.length),isNaN(w)||(width=node.w=w)}style.width=""!==width?measureToString(width):"auto",style.height=""!==height?measureToString(height):"auto"},position(node,style){var parent=node[$getSubformParent]();parent?.layout&&"position"!==parent.layout||(style.position="absolute",style.left=measureToString(node.x),style.top=measureToString(node.y))},rotate(node,style){node.rotate&&("transform"in style||(style.transform=""),style.transform+=`rotate(-${node.rotate}deg)`,style.transformOrigin="top left")},presence(node,style){switch(node.presence){case"invisible":style.visibility="hidden";break;case"hidden":case"inactive":style.display="none"}},hAlign(node,style){if("para"===node[$nodeName])switch(node.hAlign){case"justifyAll":style.textAlign="justify-all";break;case"radix":style.textAlign="left";break;default:style.textAlign=node.hAlign}else switch(node.hAlign){case"left":style.alignSelf="start";break;case"center":style.alignSelf="center";break;case"right":style.alignSelf="end"}},margin(node,style){node.margin&&(style.margin=node.margin[$toStyle]().margin)}};function setMinMaxDimensions(node,style){"position"===node[$getSubformParent]().layout&&(0a+w,0):extra.columnWidths.slice(extra.currentColumn,extra.currentColumn+colSpan).reduce((a,w)=>a+w,0),isNaN(width)||(node.w=width)}parent.layout&&"position"!==parent.layout&&(node.x=node.y=0),"table"===node.layout&&""===node.w&&Array.isArray(node.columnWidths)&&(node.w=node.columnWidths.reduce((a,x)=>a+x,0))}function layoutClass(node){switch(node.layout){case"position":return"xfaPosition";case"lr-tb":return"xfaLrTb";case"rl-row":return"xfaRlRow";case"rl-tb":return"xfaRlTb";case"row":return"xfaRow";case"table":return"xfaTable";case"tb":return"xfaTb";default:return"xfaPosition"}}function toStyle(node,...names){var style=Object.create(null);for(const name of names){var value=node[name];null!==value&&(converters.hasOwnProperty(name)?converters[name](node,style):value instanceof XFAObject&&((value=value[$toStyle]())?Object.assign(style,value):warn(`(DEBUG) - XFA - style for ${name} not implemented yet`)))}return style}function createWrapper(node,html){var attributes=html["attributes"],style=attributes["style"],wrapper={name:"div",attributes:{class:["xfaWrapper"],style:Object.create(null)},children:[]};if(attributes.class.push("xfaWrapped"),node.border){var{widths,insets:attributes}=node.border[$extra];let width,height,top=attributes[0],left=attributes[3];var insetsH=attributes[0]+attributes[2],insetsW=attributes[1]+attributes[3];switch(node.border.hand){case"even":top-=widths[0]/2,left-=widths[3]/2,width=`calc(100% + ${(widths[1]+widths[3])/2-insetsW}px)`,height=`calc(100% + ${(widths[0]+widths[2])/2-insetsH}px)`;break;case"left":top-=widths[0],left-=widths[3],width=`calc(100% + ${widths[1]+widths[3]-insetsW}px)`,height=`calc(100% + ${widths[0]+widths[2]-insetsH}px)`;break;case"right":width=insetsW?`calc(100% - ${insetsW}px)`:"100%",height=insetsH?`calc(100% - ${insetsH}px)`:"100%"}var attributes=["xfaBorder"],border=(isPrintOnly(node.border)&&attributes.push("xfaPrintOnly"),{name:"div",attributes:{class:attributes,style:{top:top+"px",left:left+"px",width:width,height:height}},children:[]});for(const key of["border","borderWidth","borderColor","borderRadius","borderStyle"])void 0!==style[key]&&(border.attributes.style[key]=style[key],delete style[key]);wrapper.children.push(border,html)}else wrapper.children.push(html);for(const key of["background","backgroundClip","top","left","width","height","minWidth","minHeight","maxWidth","maxHeight","transform","transformOrigin","visibility"])void 0!==style[key]&&(wrapper.attributes.style[key]=style[key],delete style[key]);return wrapper.attributes.style.position="absolute"===style.position?"absolute":"relative",delete style.position,style.alignSelf&&(wrapper.attributes.style.alignSelf=style.alignSelf,delete style.alignSelf),wrapper}function fixTextIndent(styles){var name,padding,indent=getMeasurement(styles.textIndent,"0px");0<=indent||(padding=getMeasurement(styles[name="padding"+("left"==("right"===styles.textAlign?"right":"left")?"Left":"Right")],"0px"),styles[name]=padding-indent+"px")}function setAccess(node,classNames){switch(node.access){case"nonInteractive":classNames.push("xfaNonInteractive");break;case"readOnly":classNames.push("xfaReadOnly");break;case"protected":classNames.push("xfaDisabled")}}function isPrintOnly(node){return 0a+x),height:availableSpace.height-marginH};case"table":case"tb":return{width:availableSpace.width-marginH,height:availableSpace.height-marginV-node[$extra].height};default:return availableSpace}}function getTransformedBBox(node){let w=""===node.w?NaN:node.w,h=""===node.h?NaN:node.h,[centerX,centerY]=[0,0];switch(node.anchorType||""){case"bottomCenter":[centerX,centerY]=[w/2,h];break;case"bottomLeft":[centerX,centerY]=[0,h];break;case"bottomRight":[centerX,centerY]=[w,h];break;case"middleCenter":[centerX,centerY]=[w/2,h/2];break;case"middleLeft":[centerX,centerY]=[0,h/2];break;case"middleRight":[centerX,centerY]=[w,h/2];break;case"topCenter":[centerX,centerY]=[w/2,0];break;case"topRight":[centerX,centerY]=[w,0]}let x,y;switch(node.rotate||0){case 0:[x,y]=[-centerX,-centerY];break;case 90:[x,y]=[-centerY,centerX],[w,h]=[h,-w];break;case 180:[x,y]=[centerX,centerY],[w,h]=[-w,-h];break;case 270:[x,y]=[centerY,-centerX],[w,h]=[-h,w]}return[node.x+x+Math.min(0,w),node.y+y+Math.min(0,h),Math.abs(w),Math.abs(h)]}function checkDimensions(node,space){if(null===node[$getTemplateRoot]()[$extra].firstUnsplittable)return!0;if(0===node.w||0===node.h)return!0;var parent=node[$getSubformParent](),attempt=parent[$extra]?.attempt||0,[,y,w,h]=getTransformedBBox(node);switch(parent.layout){case"lr-tb":case"rl-tb":return 0===attempt?node[$getTemplateRoot]()[$extra].noLayoutFailure?""!==node.w?Math.round(w-space.width)<=2:2node[$getTemplateRoot]()[$extra].currentContentArea.h;case"rl-row":case"row":return node[$getTemplateRoot]()[$extra].noLayoutFailure?!0:""===node.h||Math.round(h-space.height)<=2;default:return!0}}const TEMPLATE_NS_ID=NamespaceIds.template.id,SVG_NS="http://www.w3.org/2000/svg",MAX_ATTEMPTS_FOR_LRTB_LAYOUT=2,MAX_EMPTY_PAGES=3,DEFAULT_TAB_INDEX=5e3,HEADING_PATTERN=/^H(\d+)$/,MIMES=new Set(["image/gif","image/jpeg","image/jpg","image/pjpeg","image/png","image/apng","image/x-png","image/bmp","image/x-ms-bmp","image/tiff","image/tif","application/octet-stream"]),IMAGES_HEADERS=[[[66,77],"image/bmp"],[[255,216,255],"image/jpeg"],[[73,73,42,0],"image/tiff"],[[77,77,0,42],"image/tiff"],[[71,73,70,56,57,97],"image/gif"],[[137,80,78,71,13,10,26,10],"image/png"]];function getBorderDims(node){return node&&node.border&&(node=node.border[$getExtra]())?{w:node.widths[0]+node.widths[2]+node.insets[0]+node.insets[2],h:node.widths[1]+node.widths[3]+node.insets[1]+node.insets[3]}:{w:0,h:0}}function hasMargin(node){return node.margin&&(node.margin.topInset||node.margin.rightInset||node.margin.bottomInset||node.margin.leftInset)}function _setValue(templateNode,value){var nodeValue;templateNode.value||(nodeValue=new Value({}),templateNode[$appendChild](nodeValue),templateNode.value=nodeValue),templateNode.value[$setValue](value)}function*getContainedChildren(node){for(const child of node[$getChildren]())child instanceof SubformSet?yield*child[$getContainedChildren]():yield child}function isRequired(node){return"error"===node.validate?.nullTest}function setTabIndex(node){for(;node;){if(!node.traversal)return void(node[$tabIndex]=node[$getParent]()[$tabIndex]);if(node[$tabIndex])return;let next=null;for(const child of node.traversal[$getChildren]())if("next"===child.operation){next=child;break}if(!next||!next.ref)return void(node[$tabIndex]=node[$getParent]()[$tabIndex]);var root=node[$getTemplateRoot](),root=(node[$tabIndex]=++root[$tabIndex],root[$searchNode](next.ref,node));if(!root)return;node=root[0]}}function applyAssist(obj,attributes){var assistTitle,assist=obj.assist;assist&&((assistTitle=assist[$toHTML]())&&(attributes.title=assistTitle),assistTitle=assist.role.match(HEADING_PATTERN))&&(assist=assistTitle[1],attributes.role="heading",attributes["aria-level"]=assist),"table"===obj.layout?attributes.role="table":"row"===obj.layout?attributes.role="row":"row"===(assistTitle=obj[$getParent]()).layout&&(attributes.role="TH"===assistTitle.assist?.role?"columnheader":"cell")}function ariaLabel(obj){return obj.assist?(obj=obj.assist).speak&&""!==obj.speak[$content]?obj.speak[$content]:obj.toolTip?obj.toolTip[$content]:null:null}function valueToHtml(value){return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:Object.create(null)},children:[{name:"span",attributes:{style:Object.create(null)},value:value}]})}function setFirstUnsplittable(node){var root=node[$getTemplateRoot]();null===root[$extra].firstUnsplittable&&(root[$extra].firstUnsplittable=node,root[$extra].noLayoutFailure=!0)}function unsetFirstUnsplittable(node){var root=node[$getTemplateRoot]();root[$extra].firstUnsplittable===node&&(root[$extra].noLayoutFailure=!1)}function handleBreak(node){if(node[$extra])return!1;if(node[$extra]=Object.create(null),"auto"===node.targetType)return!1;var root=node[$getTemplateRoot]();let target=null;if(node.target){if(!(target=root[$searchNode](node.target,node[$getParent]())))return!1;target=target[0]}var{currentPageArea:root,currentContentArea}=root[$extra];if("pageArea"===node.targetType)return target instanceof PageArea||(target=null),node.startNew?(node[$extra].target=target||root,!0):!(!target||target===root||(node[$extra].target=target,0));var indexForCurrent,contentAreas,pageArea=(target=target instanceof ContentArea?target:null)&&target[$getParent]();let index,nextPageArea=pageArea;if(node.startNew)index=target?(indexForCurrent=(contentAreas=pageArea.contentArea.children).indexOf(currentContentArea),contentAreas=contentAreas.indexOf(target),-1!==indexForCurrent&&indexForCurrentnode,root[$extra].noLayoutFailure=!0,extraNode[$toHTML](space));node[$addHTML](space.html,space.bbox),root[$extra].noLayoutFailure=saved,extraNode[$getSubformParent]=savedMethod}class AppearanceFilter extends StringObject{constructor(attributes){super(TEMPLATE_NS_ID,"appearanceFilter"),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Arc extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"arc",!0),this.circular=getInteger({data:attributes.circular,defaultValue:0,validate:x=>1===x}),this.hand=getStringOption(attributes.hand,["even","left","right"]),this.id=attributes.id||"",this.startAngle=getFloat({data:attributes.startAngle,defaultValue:0,validate:x=>!0}),this.sweepAngle=getFloat({data:attributes.sweepAngle,defaultValue:360,validate:x=>!0}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.edge=null,this.fill=null}[$toHTML](){var edge=this.edge||new Edge({}),edgeStyle=edge[$toStyle](),style=Object.create(null);"visible"===this.fill?.presence?Object.assign(style,this.fill[$toStyle]()):style.fill="transparent",style.strokeWidth=measureToString("visible"===edge.presence?edge.thickness:0),style.stroke=edgeStyle.color;let arc;var largeArc,sweepAngle,x2,y2,edge={xmlns:SVG_NS,style:{width:"100%",height:"100%",overflow:"visible"}},edgeStyle=(360===this.sweepAngle?arc={name:"ellipse",attributes:{xmlns:SVG_NS,cx:"50%",cy:"50%",rx:"50%",ry:"50%",style:style}}:(edgeStyle=this.startAngle*Math.PI/180,sweepAngle=this.sweepAngle*Math.PI/180,largeArc=1801<=n||-1===n}),this.id=attributes.id||"",this.name=attributes.name||"",this.relevant=getRelevant(attributes.relevant),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.x=getMeasurement(attributes.x,"0pt"),this.y=getMeasurement(attributes.y,"0pt"),this.desc=null,this.extras=null,this.area=new XFAObjectArray,this.draw=new XFAObjectArray,this.exObject=new XFAObjectArray,this.exclGroup=new XFAObjectArray,this.field=new XFAObjectArray,this.subform=new XFAObjectArray,this.subformSet=new XFAObjectArray}*[$getContainedChildren](){yield*getContainedChildren(this)}[$isTransparent](){return!0}[$isBindable](){return!0}[$addHTML](html,bbox){var[bbox,y,w,h]=bbox;this[$extra].width=Math.max(this[$extra].width,bbox+w),this[$extra].height=Math.max(this[$extra].height,y+h),this[$extra].children.push(html)}[$getAvailableSpace](){return this[$extra].availableSpace}[$toHTML](availableSpace){var style=toStyle(this,"position"),attributes={style:style,id:this[$uid],class:["xfaArea"]},children=(isPrintOnly(this)&&attributes.class.push("xfaPrintOnly"),this.name&&(attributes.xfaName=this.name),[]),availableSpace=(this[$extra]={children:children,width:0,height:0,availableSpace:availableSpace},this[$childrenToHTML]({filter:new Set(["area","draw","field","exclGroup","subform","subformSet"]),include:!0}));if(!availableSpace.success)return availableSpace.isBreak()?availableSpace:(delete this[$extra],HTMLResult.FAILURE);style.width=measureToString(this[$extra].width),style.height=measureToString(this[$extra].height);availableSpace={name:"div",attributes:attributes,children:children},style=[this.x,this.y,this[$extra].width,this[$extra].height];return delete this[$extra],HTMLResult.success(availableSpace,style)}}class Assist extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"assist",!0),this.id=attributes.id||"",this.role=attributes.role||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.speak=null,this.toolTip=null}[$toHTML](){return this.toolTip?.[$content]||null}}class Barcode extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"barcode",!0),this.charEncoding=getKeyword({data:attributes.charEncoding?attributes.charEncoding.toLowerCase():"",defaultValue:"",validate:k=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(k)||k.match(/iso-8859-\d{2}/)}),this.checksum=getStringOption(attributes.checksum,["none","1mod10","1mod10_1mod11","2mod10","auto"]),this.dataColumnCount=getInteger({data:attributes.dataColumnCount,defaultValue:-1,validate:x=>0<=x}),this.dataLength=getInteger({data:attributes.dataLength,defaultValue:-1,validate:x=>0<=x}),this.dataPrep=getStringOption(attributes.dataPrep,["none","flateCompress"]),this.dataRowCount=getInteger({data:attributes.dataRowCount,defaultValue:-1,validate:x=>0<=x}),this.endChar=attributes.endChar||"",this.errorCorrectionLevel=getInteger({data:attributes.errorCorrectionLevel,defaultValue:-1,validate:x=>0<=x&&x<=8}),this.id=attributes.id||"",this.moduleHeight=getMeasurement(attributes.moduleHeight,"5mm"),this.moduleWidth=getMeasurement(attributes.moduleWidth,"0.25mm"),this.printCheckDigit=getInteger({data:attributes.printCheckDigit,defaultValue:0,validate:x=>1===x}),this.rowColumnRatio=getRatio(attributes.rowColumnRatio),this.startChar=attributes.startChar||"",this.textLocation=getStringOption(attributes.textLocation,["below","above","aboveEmbedded","belowEmbedded","none"]),this.truncate=getInteger({data:attributes.truncate,defaultValue:0,validate:x=>1===x}),this.type=getStringOption(attributes.type?attributes.type.toLowerCase():"",["aztec","codabar","code2of5industrial","code2of5interleaved","code2of5matrix","code2of5standard","code3of9","code3of9extended","code11","code49","code93","code128","code128a","code128b","code128c","code128sscc","datamatrix","ean8","ean8add2","ean8add5","ean13","ean13add2","ean13add5","ean13pwcd","fim","logmars","maxicode","msi","pdf417","pdf417macro","plessey","postauscust2","postauscust3","postausreplypaid","postausstandard","postukrm4scc","postusdpbc","postusimb","postusstandard","postus5zip","qrcode","rfid","rss14","rss14expanded","rss14limited","rss14stacked","rss14stackedomni","rss14truncated","telepen","ucc128","ucc128random","ucc128sscc","upca","upcaadd2","upcaadd5","upcapwcd","upce","upceadd2","upceadd5","upcean2","upcean5","upsmaxicode"]),this.upsMode=getStringOption(attributes.upsMode,["usCarrier","internationalCarrier","secureSymbol","standardSymbol"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.wideNarrowRatio=getRatio(attributes.wideNarrowRatio),this.encrypt=null,this.extras=null}}class Bind extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"bind",!0),this.match=getStringOption(attributes.match,["once","dataRef","global","none"]),this.ref=attributes.ref||"",this.picture=null}}class BindItems extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"bindItems"),this.connection=attributes.connection||"",this.labelRef=attributes.labelRef||"",this.ref=attributes.ref||"",this.valueRef=attributes.valueRef||""}}class Bookend extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"bookend"),this.id=attributes.id||"",this.leader=attributes.leader||"",this.trailer=attributes.trailer||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class BooleanElement extends Option01{constructor(attributes){super(TEMPLATE_NS_ID,"boolean"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$toHTML](availableSpace){return valueToHtml(1===this[$content]?"1":"0")}}class Border extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"border",!0),this.break=getStringOption(attributes.break,["close","open"]),this.hand=getStringOption(attributes.hand,["even","left","right"]),this.id=attributes.id||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.relevant=getRelevant(attributes.relevant),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.corner=new XFAObjectArray(4),this.edge=new XFAObjectArray(4),this.extras=null,this.fill=null,this.margin=null}[$getExtra](){if(!this[$extra]){var edges=this.edge.children.slice();if(edges.length<4){var defaultEdge=edges.at(-1)||new Edge({});for(let i=edges.length;i<4;i++)edges.push(defaultEdge)}var widths=edges.map(edge=>edge.thickness),insets=[0,0,0,0];this.margin&&(insets[0]=this.margin.topInset,insets[1]=this.margin.rightInset,insets[2]=this.margin.bottomInset,insets[3]=this.margin.leftInset),this[$extra]={widths:widths,insets:insets,edges:edges}}return this[$extra]}[$toStyle](){var edges=this[$getExtra]()["edges"],edgeStyles=edges.map(node=>{node=node[$toStyle]();return node.color||="#000000",node}),style=Object.create(null);if(this.margin&&Object.assign(style,this.margin[$toStyle]()),"visible"===this.fill?.presence&&Object.assign(style,this.fill[$toStyle]()),this.corner.children.some(node=>0!==node.radius)){var cornerStyles=this.corner.children.map(node=>node[$toStyle]());if(2===cornerStyles.length||3===cornerStyles.length){var last=cornerStyles.at(-1);for(let i=cornerStyles.length;i<4;i++)cornerStyles.push(last)}style.borderRadius=cornerStyles.map(s=>s.radius).join(" ")}switch(this.presence){case"invisible":case"hidden":style.borderStyle="";break;case"inactive":style.borderStyle="none";break;default:style.borderStyle=edgeStyles.map(s=>s.style).join(" ")}return style.borderWidth=edgeStyles.map(s=>s.width).join(" "),style.borderColor=edgeStyles.map(s=>s.color).join(" "),style}}class Break extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"break",!0),this.after=getStringOption(attributes.after,["auto","contentArea","pageArea","pageEven","pageOdd"]),this.afterTarget=attributes.afterTarget||"",this.before=getStringOption(attributes.before,["auto","contentArea","pageArea","pageEven","pageOdd"]),this.beforeTarget=attributes.beforeTarget||"",this.bookendLeader=attributes.bookendLeader||"",this.bookendTrailer=attributes.bookendTrailer||"",this.id=attributes.id||"",this.overflowLeader=attributes.overflowLeader||"",this.overflowTarget=attributes.overflowTarget||"",this.overflowTrailer=attributes.overflowTrailer||"",this.startNew=getInteger({data:attributes.startNew,defaultValue:0,validate:x=>1===x}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null}}class BreakAfter extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"breakAfter",!0),this.id=attributes.id||"",this.leader=attributes.leader||"",this.startNew=getInteger({data:attributes.startNew,defaultValue:0,validate:x=>1===x}),this.target=attributes.target||"",this.targetType=getStringOption(attributes.targetType,["auto","contentArea","pageArea"]),this.trailer=attributes.trailer||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.script=null}}class BreakBefore extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"breakBefore",!0),this.id=attributes.id||"",this.leader=attributes.leader||"",this.startNew=getInteger({data:attributes.startNew,defaultValue:0,validate:x=>1===x}),this.target=attributes.target||"",this.targetType=getStringOption(attributes.targetType,["auto","contentArea","pageArea"]),this.trailer=attributes.trailer||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.script=null}[$toHTML](availableSpace){return this[$extra]={},HTMLResult.FAILURE}}class Button extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"button",!0),this.highlight=getStringOption(attributes.highlight,["inverted","none","outline","push"]),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null}[$toHTML](availableSpace){var jsURL,href,grandpa=this[$getParent]()[$getParent](),htmlButton={name:"button",attributes:{id:this[$uid],class:["xfaButton"],style:{}},children:[]};for(const event of grandpa.event.children)"click"===event.activity&&event.script&&(jsURL=recoverJsURL(event.script[$content]))&&(href=fixURL(jsURL.url))&&htmlButton.children.push({name:"a",attributes:{id:"link"+this[$uid],href:href,newWindow:jsURL.newWindow,class:["xfaLink"],style:{}},children:[]});return HTMLResult.success(htmlButton)}}class Calculate extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"calculate",!0),this.id=attributes.id||"",this.override=getStringOption(attributes.override,["disabled","error","ignore","warning"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.message=null,this.script=null}}class Caption extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"caption",!0),this.id=attributes.id||"",this.placement=getStringOption(attributes.placement,["left","bottom","inline","right","top"]),this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.reserve=Math.ceil(getMeasurement(attributes.reserve)),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.font=null,this.margin=null,this.para=null,this.value=null}[$setValue](value){_setValue(this,value)}[$getExtra](availableSpace){if(!this[$extra]){let{width,height}=availableSpace;switch(this.placement){case"left":case"right":case"inline":width=this.reserve<=0?width:this.reserve;break;case"top":case"bottom":height=this.reserve<=0?height:this.reserve}this[$extra]=layoutNode(this,{width:width,height:height})}return this[$extra]}[$toHTML](availableSpace){if(!this.value)return HTMLResult.EMPTY;this[$pushPara]();var value=this.value[$toHTML](availableSpace).html;if(!value)return this[$popPara](),HTMLResult.EMPTY;var savedReserve=this.reserve;if(this.reserve<=0){var{w,h}=this[$getExtra](availableSpace);switch(this.placement){case"left":case"right":case"inline":this.reserve=w;break;case"top":case"bottom":this.reserve=h}}var availableSpace=[],style=(availableSpace.push("string"==typeof value?{name:"#text",value:value}:value),toStyle(this,"font","margin","visibility"));switch(this.placement){case"left":case"right":01===x}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.border=null,this.extras=null,this.margin=null}[$toHTML](availableSpace){var style=toStyle(this,"border","margin"),field=this[$getParent]()[$getParent](),optionStyle={fontSize:`calc(${field.font?.size||10}px * var(--scale-factor))`},children=[];if(00<=x}),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Connect extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"connect",!0),this.connection=attributes.connection||"",this.id=attributes.id||"",this.ref=attributes.ref||"",this.usage=getStringOption(attributes.usage,["exportAndImport","exportOnly","importOnly"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.picture=null}}class ContentArea extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"contentArea",!0),this.h=getMeasurement(attributes.h),this.id=attributes.id||"",this.name=attributes.name||"",this.relevant=getRelevant(attributes.relevant),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.w=getMeasurement(attributes.w),this.x=getMeasurement(attributes.x,"0pt"),this.y=getMeasurement(attributes.y,"0pt"),this.desc=null,this.extras=null}[$toHTML](availableSpace){var style={left:measureToString(this.x),top:measureToString(this.y),width:measureToString(this.w),height:measureToString(this.h)},classNames=["xfaContentarea"];return isPrintOnly(this)&&classNames.push("xfaPrintOnly"),HTMLResult.success({name:"div",children:[],attributes:{style:style,class:classNames,id:this[$uid]}})}}class Corner extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"corner",!0),this.id=attributes.id||"",this.inverted=getInteger({data:attributes.inverted,defaultValue:0,validate:x=>1===x}),this.join=getStringOption(attributes.join,["square","round"]),this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.radius=getMeasurement(attributes.radius),this.stroke=getStringOption(attributes.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]),this.thickness=getMeasurement(attributes.thickness,"0.5pt"),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.color=null,this.extras=null}[$toStyle](){var style=toStyle(this,"visibility");return style.radius=measureToString("square"===this.join?0:this.radius),style}}class DateElement extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"date"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){var date=this[$content].trim();this[$content]=date?new Date(date):null}[$toHTML](availableSpace){return valueToHtml(this[$content]?this[$content].toString():"")}}class DateTime extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"dateTime"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){var date=this[$content].trim();this[$content]=date?new Date(date):null}[$toHTML](availableSpace){return valueToHtml(this[$content]?this[$content].toString():"")}}class DateTimeEdit extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"dateTimeEdit",!0),this.hScrollPolicy=getStringOption(attributes.hScrollPolicy,["auto","off","on"]),this.id=attributes.id||"",this.picker=getStringOption(attributes.picker,["host","none"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.border=null,this.comb=null,this.extras=null,this.margin=null}[$toHTML](availableSpace){var style=toStyle(this,"border","font","margin"),field=this[$getParent]()[$getParent](),style={name:"input",attributes:{type:"text",fieldId:field[$uid],dataId:field[$data]?.[$uid]||field[$uid],class:["xfaTextfield"],style:style,"aria-label":ariaLabel(field),"aria-required":!1}};return isRequired(field)&&(style.attributes["aria-required"]=!0,style.attributes.required=!0),HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[style]})}}class Decimal extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"decimal"),this.fracDigits=getInteger({data:attributes.fracDigits,defaultValue:2,validate:x=>!0}),this.id=attributes.id||"",this.leadDigits=getInteger({data:attributes.leadDigits,defaultValue:-1,validate:x=>!0}),this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){var number=parseFloat(this[$content].trim());this[$content]=isNaN(number)?null:number}[$toHTML](availableSpace){return valueToHtml(null!==this[$content]?this[$content].toString():"")}}class DefaultUi extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"defaultUi",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null}}class Desc extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"desc",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.boolean=new XFAObjectArray,this.date=new XFAObjectArray,this.dateTime=new XFAObjectArray,this.decimal=new XFAObjectArray,this.exData=new XFAObjectArray,this.float=new XFAObjectArray,this.image=new XFAObjectArray,this.integer=new XFAObjectArray,this.text=new XFAObjectArray,this.time=new XFAObjectArray}}class DigestMethod extends OptionObject{constructor(attributes){super(TEMPLATE_NS_ID,"digestMethod",["","SHA1","SHA256","SHA512","RIPEMD160"]),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class DigestMethods extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"digestMethods",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.digestMethod=new XFAObjectArray}}class Draw extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"draw",!0),this.anchorType=getStringOption(attributes.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=getInteger({data:attributes.colSpan,defaultValue:1,validate:n=>1<=n||-1===n}),this.h=attributes.h?getMeasurement(attributes.h):"",this.hAlign=getStringOption(attributes.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=attributes.id||"",this.locale=attributes.locale||"",this.maxH=getMeasurement(attributes.maxH,"0pt"),this.maxW=getMeasurement(attributes.maxW,"0pt"),this.minH=getMeasurement(attributes.minH,"0pt"),this.minW=getMeasurement(attributes.minW,"0pt"),this.name=attributes.name||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.relevant=getRelevant(attributes.relevant),this.rotate=getInteger({data:attributes.rotate,defaultValue:0,validate:x=>x%90==0}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.w=attributes.w?getMeasurement(attributes.w):"",this.x=getMeasurement(attributes.x,"0pt"),this.y=getMeasurement(attributes.y,"0pt"),this.assist=null,this.border=null,this.caption=null,this.desc=null,this.extras=null,this.font=null,this.keep=null,this.margin=null,this.para=null,this.traversal=null,this.ui=null,this.value=null,this.setProperty=new XFAObjectArray}[$setValue](value){_setValue(this,value)}[$toHTML](availableSpace){if(setTabIndex(this),"hidden"===this.presence||"inactive"===this.presence)return HTMLResult.EMPTY;fixDimensions(this),this[$pushPara]();var savedW=this.w,savedH=this.h,{w,h,isBroken}=layoutNode(this,availableSpace);if(w&&""===this.w){if(isBroken&&this[$getSubformParent]()[$isThereMoreWidth]())return this[$popPara](),HTMLResult.FAILURE;this.w=w}if(h&&""===this.h&&(this.h=h),setFirstUnsplittable(this),!checkDimensions(this,availableSpace))return this.w=savedW,this.h=savedH,this[$popPara](),HTMLResult.FAILURE;unsetFirstUnsplittable(this);isBroken=toStyle(this,"font","hAlign","dimensions","position","presence","rotate","anchorType","border","margin"),setMinMaxDimensions(this,isBroken),isBroken.margin&&(isBroken.padding=isBroken.margin,delete isBroken.margin),w=["xfaDraw"],this.font&&w.push("xfaFont"),isPrintOnly(this)&&w.push("xfaPrintOnly"),h={style:isBroken,id:this[$uid],class:w},this.name&&(h.xfaName=this.name),w={name:"div",attributes:h,children:[]},applyAssist(this,h),h=computeBbox(this,w,availableSpace),availableSpace=this.value?this.value[$toHTML](availableSpace).html:null;return null===availableSpace?(this.w=savedW,this.h=savedH,this[$popPara]()):(w.children.push(availableSpace),setPara(this,isBroken,availableSpace),this.w=savedW,this.h=savedH,this[$popPara]()),HTMLResult.success(createWrapper(this,w),h)}}class Edge extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"edge",!0),this.cap=getStringOption(attributes.cap,["square","butt","round"]),this.id=attributes.id||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.stroke=getStringOption(attributes.stroke,["solid","dashDot","dashDotDot","dashed","dotted","embossed","etched","lowered","raised"]),this.thickness=getMeasurement(attributes.thickness,"0.5pt"),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.color=null,this.extras=null}[$toStyle](){var style=toStyle(this,"visibility");if(Object.assign(style,{linecap:this.cap,width:measureToString(this.thickness),color:this.color?this.color[$toStyle]():"#000000",style:""}),"visible"!==this.presence)style.style="none";else switch(this.stroke){case"solid":style.style="solid";break;case"dashDot":case"dashDotDot":case"dashed":style.style="dashed";break;case"dotted":style.style="dotted";break;case"embossed":style.style="ridge";break;case"etched":style.style="groove";break;case"lowered":style.style="inset";break;case"raised":style.style="outset"}return style}}class Encoding extends OptionObject{constructor(attributes){super(TEMPLATE_NS_ID,"encoding",["adbe.x509.rsa_sha1","adbe.pkcs7.detached","adbe.pkcs7.sha1"]),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Encodings extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"encodings",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.encoding=new XFAObjectArray}}class Encrypt extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"encrypt",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.certificate=null}}class EncryptData extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"encryptData",!0),this.id=attributes.id||"",this.operation=getStringOption(attributes.operation,["encrypt","decrypt"]),this.target=attributes.target||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.filter=null,this.manifest=null}}class Encryption extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"encryption",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.certificate=new XFAObjectArray}}class EncryptionMethod extends OptionObject{constructor(attributes){super(TEMPLATE_NS_ID,"encryptionMethod",["","AES256-CBC","TRIPLEDES-CBC","AES128-CBC","AES192-CBC"]),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class EncryptionMethods extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"encryptionMethods",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.encryptionMethod=new XFAObjectArray}}class Event extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"event",!0),this.activity=getStringOption(attributes.activity,["click","change","docClose","docReady","enter","exit","full","indexChange","initialize","mouseDown","mouseEnter","mouseExit","mouseUp","postExecute","postOpen","postPrint","postSave","postSign","postSubmit","preExecute","preOpen","prePrint","preSave","preSign","preSubmit","ready","validationState"]),this.id=attributes.id||"",this.listen=getStringOption(attributes.listen,["refOnly","refAndDescendents"]),this.name=attributes.name||"",this.ref=attributes.ref||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.encryptData=null,this.execute=null,this.script=null,this.signData=null,this.submit=null}}class ExData extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"exData"),this.contentType=attributes.contentType||"",this.href=attributes.href||"",this.id=attributes.id||"",this.maxLength=getInteger({data:attributes.maxLength,defaultValue:-1,validate:x=>-1<=x}),this.name=attributes.name||"",this.rid=attributes.rid||"",this.transferEncoding=getStringOption(attributes.transferEncoding,["none","base64","package"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$isCDATAXml](){return"text/html"===this.contentType}[$onChild](child){return("text/html"===this.contentType&&child[$namespaceId]===NamespaceIds.xhtml.id||"text/xml"===this.contentType)&&(this[$content]=child,!0)}[$toHTML](availableSpace){return"text/html"===this.contentType&&this[$content]?this[$content][$toHTML](availableSpace):HTMLResult.EMPTY}}class ExObject extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"exObject",!0),this.archive=attributes.archive||"",this.classId=attributes.classId||"",this.codeBase=attributes.codeBase||"",this.codeType=attributes.codeType||"",this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.boolean=new XFAObjectArray,this.date=new XFAObjectArray,this.dateTime=new XFAObjectArray,this.decimal=new XFAObjectArray,this.exData=new XFAObjectArray,this.exObject=new XFAObjectArray,this.float=new XFAObjectArray,this.image=new XFAObjectArray,this.integer=new XFAObjectArray,this.text=new XFAObjectArray,this.time=new XFAObjectArray}}class ExclGroup extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"exclGroup",!0),this.access=getStringOption(attributes.access,["open","nonInteractive","protected","readOnly"]),this.accessKey=attributes.accessKey||"",this.anchorType=getStringOption(attributes.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=getInteger({data:attributes.colSpan,defaultValue:1,validate:n=>1<=n||-1===n}),this.h=attributes.h?getMeasurement(attributes.h):"",this.hAlign=getStringOption(attributes.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=attributes.id||"",this.layout=getStringOption(attributes.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]),this.maxH=getMeasurement(attributes.maxH,"0pt"),this.maxW=getMeasurement(attributes.maxW,"0pt"),this.minH=getMeasurement(attributes.minH,"0pt"),this.minW=getMeasurement(attributes.minW,"0pt"),this.name=attributes.name||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.relevant=getRelevant(attributes.relevant),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.w=attributes.w?getMeasurement(attributes.w):"",this.x=getMeasurement(attributes.x,"0pt"),this.y=getMeasurement(attributes.y,"0pt"),this.assist=null,this.bind=null,this.border=null,this.calculate=null,this.caption=null,this.desc=null,this.extras=null,this.margin=null,this.para=null,this.traversal=null,this.validate=null,this.connect=new XFAObjectArray,this.event=new XFAObjectArray,this.field=new XFAObjectArray,this.setProperty=new XFAObjectArray}[$isBindable](){return!0}[$hasSettableValue](){return!0}[$setValue](value){for(const field of this.field.children){var nodeValue;field.value||(nodeValue=new Value({}),field[$appendChild](nodeValue),field.value=nodeValue),field.value[$setValue](value)}}[$isThereMoreWidth](){return this.layout.endsWith("-tb")&&0===this[$extra].attempt&&01<=n||-1===n}),this.h=attributes.h?getMeasurement(attributes.h):"",this.hAlign=getStringOption(attributes.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=attributes.id||"",this.locale=attributes.locale||"",this.maxH=getMeasurement(attributes.maxH,"0pt"),this.maxW=getMeasurement(attributes.maxW,"0pt"),this.minH=getMeasurement(attributes.minH,"0pt"),this.minW=getMeasurement(attributes.minW,"0pt"),this.name=attributes.name||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.relevant=getRelevant(attributes.relevant),this.rotate=getInteger({data:attributes.rotate,defaultValue:0,validate:x=>x%90==0}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.w=attributes.w?getMeasurement(attributes.w):"",this.x=getMeasurement(attributes.x,"0pt"),this.y=getMeasurement(attributes.y,"0pt"),this.assist=null,this.bind=null,this.border=null,this.calculate=null,this.caption=null,this.desc=null,this.extras=null,this.font=null,this.format=null,this.items=new XFAObjectArray(2),this.keep=null,this.margin=null,this.para=null,this.traversal=null,this.ui=null,this.validate=null,this.value=null,this.bindItems=new XFAObjectArray,this.connect=new XFAObjectArray,this.event=new XFAObjectArray,this.setProperty=new XFAObjectArray}[$isBindable](){return!0}[$setValue](value){_setValue(this,value)}[$toHTML](availableSpace){if(setTabIndex(this),!this.ui){this.ui=new Ui({}),this.ui[$globalData]=this[$globalData],this[$appendChild](this.ui);let node;switch(this.items.children.length){case 0:node=new TextEdit({}),this.ui.textEdit=node;break;case 1:node=new CheckButton({}),this.ui.checkButton=node;break;case 2:node=new ChoiceList({}),this.ui.choiceList=node}this.ui[$appendChild](node)}if(!this.ui||"hidden"===this.presence||"inactive"===this.presence||0===this.h||0===this.w)return HTMLResult.EMPTY;this.caption&&delete this.caption[$extra],this[$pushPara]();var caption=this.caption?this.caption[$toHTML](availableSpace).html:null,savedW=this.w,savedH=this.h;let marginH=0,marginV=0,borderDims=(this.margin&&(marginH=this.margin.leftInset+this.margin.rightInset,marginV=this.margin.topInset+this.margin.bottomInset),null);if(""===this.w||""===this.h){let width=null,height=null,uiW=0,uiH=0;if(this.ui.checkButton?uiW=uiH=this.ui.checkButton.size:({w,h}=layoutNode(this,availableSpace),uiH=null!==w?(uiW=w,h):fonts_getMetrics(this.font,!0).lineNoGap),borderDims=getBorderDims(this.ui[$getExtra]()),uiW+=borderDims.w,uiH+=borderDims.h,this.caption){const{w,h,isBroken}=this.caption[$getExtra](availableSpace);if(isBroken&&this[$getSubformParent]()[$isThereMoreWidth]())return this[$popPara](),HTMLResult.FAILURE;switch(width=w,height=h,this.caption.placement){case"left":case"right":case"inline":width+=uiW;break;case"top":case"bottom":height+=uiH}}else width=uiW,height=uiH;width&&""===this.w&&(width+=marginH,this.w=Math.min(this.maxW<=0?1/0:this.maxW,this.minW+11<=x&&x<=5}),this.appearanceFilter=null,this.certificates=null,this.digestMethods=null,this.encodings=null,this.encryptionMethods=null,this.handler=null,this.lockDocument=null,this.mdp=null,this.reasons=null,this.timeStamp=null}}class Float extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"float"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){var number=parseFloat(this[$content].trim());this[$content]=isNaN(number)?null:number}[$toHTML](availableSpace){return valueToHtml(null!==this[$content]?this[$content].toString():"")}}class template_Font extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"font",!0),this.baselineShift=getMeasurement(attributes.baselineShift),this.fontHorizontalScale=getFloat({data:attributes.fontHorizontalScale,defaultValue:100,validate:x=>0<=x}),this.fontVerticalScale=getFloat({data:attributes.fontVerticalScale,defaultValue:100,validate:x=>0<=x}),this.id=attributes.id||"",this.kerningMode=getStringOption(attributes.kerningMode,["none","pair"]),this.letterSpacing=getMeasurement(attributes.letterSpacing,"0"),this.lineThrough=getInteger({data:attributes.lineThrough,defaultValue:0,validate:x=>1===x||2===x}),this.lineThroughPeriod=getStringOption(attributes.lineThroughPeriod,["all","word"]),this.overline=getInteger({data:attributes.overline,defaultValue:0,validate:x=>1===x||2===x}),this.overlinePeriod=getStringOption(attributes.overlinePeriod,["all","word"]),this.posture=getStringOption(attributes.posture,["normal","italic"]),this.size=getMeasurement(attributes.size,"10pt"),this.typeface=attributes.typeface||"Courier",this.underline=getInteger({data:attributes.underline,defaultValue:0,validate:x=>1===x||2===x}),this.underlinePeriod=getStringOption(attributes.underlinePeriod,["all","word"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.weight=getStringOption(attributes.weight,["normal","bold"]),this.extras=null,this.fill=null}[$clean](builder){super[$clean](builder),this[$globalData].usedTypefaces.add(this.typeface)}[$toStyle](){var style=toStyle(this,"fill"),color=style.color;return color&&("#000000"===color?delete style.color:color.startsWith("#")||(style.background=color,style.backgroundClip="text",style.color="transparent")),this.baselineShift&&(style.verticalAlign=measureToString(this.baselineShift)),style.fontKerning="none"===this.kerningMode?"none":"normal",style.letterSpacing=measureToString(this.letterSpacing),0!==this.lineThrough&&(style.textDecoration="line-through",2===this.lineThrough)&&(style.textDecorationStyle="double"),0!==this.overline&&(style.textDecoration="overline",2===this.overline)&&(style.textDecorationStyle="double"),style.fontStyle=this.posture,style.fontSize=measureToString(.99*this.size),setFontFamily(this,this,this[$globalData].fontFinder,style),0!==this.underline&&(style.textDecoration="underline",2===this.underline)&&(style.textDecorationStyle="double"),style.fontWeight=this.weight,style}}class Format extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"format",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.picture=null}}class Handler extends StringObject{constructor(attributes){super(TEMPLATE_NS_ID,"handler"),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Hyphenation extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"hyphenation"),this.excludeAllCaps=getInteger({data:attributes.excludeAllCaps,defaultValue:0,validate:x=>1===x}),this.excludeInitialCap=getInteger({data:attributes.excludeInitialCap,defaultValue:0,validate:x=>1===x}),this.hyphenate=getInteger({data:attributes.hyphenate,defaultValue:0,validate:x=>1===x}),this.id=attributes.id||"",this.pushCharacterCount=getInteger({data:attributes.pushCharacterCount,defaultValue:3,validate:x=>0<=x}),this.remainCharacterCount=getInteger({data:attributes.remainCharacterCount,defaultValue:3,validate:x=>0<=x}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.wordCharacterCount=getInteger({data:attributes.wordCharacterCount,defaultValue:7,validate:x=>0<=x})}}class Image extends StringObject{constructor(attributes){super(TEMPLATE_NS_ID,"image"),this.aspect=getStringOption(attributes.aspect,["fit","actual","height","none","width"]),this.contentType=attributes.contentType||"",this.href=attributes.href||"",this.id=attributes.id||"",this.name=attributes.name||"",this.transferEncoding=getStringOption(attributes.transferEncoding,["base64","none","package"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$toHTML](){if(this.contentType&&!MIMES.has(this.contentType.toLowerCase()))return HTMLResult.EMPTY;let buffer=this[$globalData].images&&this[$globalData].images.get(this.href);if(!buffer&&(this.href||!this[$content]))return HTMLResult.EMPTY;if(!(buffer=buffer||"base64"!==this.transferEncoding?buffer:stringToBytes(atob(this[$content]))))return HTMLResult.EMPTY;if(!this.contentType){for(var[header,type]of IMAGES_HEADERS)if(buffer.length>header.length&&header.every((x,i)=>x===buffer[i])){this.contentType=type;break}if(!this.contentType)return HTMLResult.EMPTY}var blob=new Blob([buffer],{type:this.contentType});let style;switch(this.aspect){case"fit":case"actual":break;case"height":style={height:"100%",objectFit:"fill"};break;case"none":style={width:"100%",height:"100%",objectFit:"fill"};break;case"width":style={width:"100%",objectFit:"fill"}}var parent=this[$getParent]();return HTMLResult.success({name:"img",attributes:{class:["xfaImage"],style:style,src:URL.createObjectURL(blob),alt:parent?ariaLabel(parent[$getParent]()):null}})}}class ImageEdit extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"imageEdit",!0),this.data=getStringOption(attributes.data,["link","embed"]),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.border=null,this.extras=null,this.margin=null}[$toHTML](availableSpace){return"embed"===this.data?HTMLResult.success({name:"div",children:[],attributes:{}}):HTMLResult.EMPTY}}class Integer extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"integer"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){var number=parseInt(this[$content].trim(),10);this[$content]=isNaN(number)?null:number}[$toHTML](availableSpace){return valueToHtml(null!==this[$content]?this[$content].toString():"")}}class Issuers extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"issuers",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.certificate=new XFAObjectArray}}class Items extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"items",!0),this.id=attributes.id||"",this.name=attributes.name||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.ref=attributes.ref||"",this.save=getInteger({data:attributes.save,defaultValue:0,validate:x=>1===x}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.boolean=new XFAObjectArray,this.date=new XFAObjectArray,this.dateTime=new XFAObjectArray,this.decimal=new XFAObjectArray,this.exData=new XFAObjectArray,this.float=new XFAObjectArray,this.image=new XFAObjectArray,this.integer=new XFAObjectArray,this.text=new XFAObjectArray,this.time=new XFAObjectArray}[$toHTML](){var output=[];for(const child of this[$getChildren]())output.push(child[$text]());return HTMLResult.success(output)}}class Keep extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"keep",!0),this.id=attributes.id||"";var options=["none","contentArea","pageArea"];this.intact=getStringOption(attributes.intact,options),this.next=getStringOption(attributes.next,options),this.previous=getStringOption(attributes.previous,options),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null}}class KeyUsage extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"keyUsage");var options=["","yes","no"];this.crlSign=getStringOption(attributes.crlSign,options),this.dataEncipherment=getStringOption(attributes.dataEncipherment,options),this.decipherOnly=getStringOption(attributes.decipherOnly,options),this.digitalSignature=getStringOption(attributes.digitalSignature,options),this.encipherOnly=getStringOption(attributes.encipherOnly,options),this.id=attributes.id||"",this.keyAgreement=getStringOption(attributes.keyAgreement,options),this.keyCertSign=getStringOption(attributes.keyCertSign,options),this.keyEncipherment=getStringOption(attributes.keyEncipherment,options),this.nonRepudiation=getStringOption(attributes.nonRepudiation,options),this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Line extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"line",!0),this.hand=getStringOption(attributes.hand,["even","left","right"]),this.id=attributes.id||"",this.slope=getStringOption(attributes.slope,["\\","/"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.edge=null}[$toHTML](){var parent=this[$getParent]()[$getParent](),edge=this.edge||new Edge({}),edgeStyle=edge[$toStyle](),style=Object.create(null),edge="visible"===edge.presence?edge.thickness:0;style.strokeWidth=measureToString(edge),style.stroke=edgeStyle.color;let x1,y1,x2,y2,width="100%",height="100%";parent.w<=edge?([x1,y1,x2,y2]=["50%",0,"50%","100%"],width=style.strokeWidth):parent.h<=edge?([x1,y1,x2,y2]=[0,"50%","100%","50%"],height=style.strokeWidth):"\\"===this.slope?[x1,y1,x2,y2]=[0,0,"100%","100%"]:[x1,y1,x2,y2]=[0,"100%","100%",0];edgeStyle={name:"svg",children:[{name:"line",attributes:{xmlns:SVG_NS,x1:x1,y1:y1,x2:x2,y2:y2,style:style}}],attributes:{xmlns:SVG_NS,width:width,height:height,style:{overflow:"visible"}}};return hasMargin(parent)?HTMLResult.success({name:"div",attributes:{style:{display:"inline",width:"100%",height:"100%"}},children:[edgeStyle]}):(edgeStyle.attributes.style.position="absolute",HTMLResult.success(edgeStyle))}}class Linear extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"linear",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["toRight","toBottom","toLeft","toTop"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.color=null,this.extras=null}[$toStyle](startColor){return startColor=startColor?startColor[$toStyle]():"#FFFFFF",`linear-gradient(${this.type.replace(/([RBLT])/," $1").toLowerCase()}, ${startColor}, ${this.color?this.color[$toStyle]():"#000000"})`}}class LockDocument extends ContentObject{constructor(attributes){super(TEMPLATE_NS_ID,"lockDocument"),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){this[$content]=getStringOption(this[$content],["auto","0","1"])}}class Manifest extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"manifest",!0),this.action=getStringOption(attributes.action,["include","all","exclude"]),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.ref=new XFAObjectArray}}class Margin extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"margin",!0),this.bottomInset=getMeasurement(attributes.bottomInset,"0"),this.id=attributes.id||"",this.leftInset=getMeasurement(attributes.leftInset,"0"),this.rightInset=getMeasurement(attributes.rightInset,"0"),this.topInset=getMeasurement(attributes.topInset,"0"),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null}[$toStyle](){return{margin:measureToString(this.topInset)+" "+measureToString(this.rightInset)+" "+measureToString(this.bottomInset)+" "+measureToString(this.leftInset)}}}class Mdp extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"mdp"),this.id=attributes.id||"",this.permissions=getInteger({data:attributes.permissions,defaultValue:2,validate:x=>1===x||3===x}),this.signatureType=getStringOption(attributes.signatureType,["filler","author"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Medium extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"medium"),this.id=attributes.id||"",this.imagingBBox=getBBox(attributes.imagingBBox),this.long=getMeasurement(attributes.long),this.orientation=getStringOption(attributes.orientation,["portrait","landscape"]),this.short=getMeasurement(attributes.short),this.stock=attributes.stock||"",this.trayIn=getStringOption(attributes.trayIn,["auto","delegate","pageFront"]),this.trayOut=getStringOption(attributes.trayOut,["auto","delegate"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Message extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"message",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.text=new XFAObjectArray}}class NumericEdit extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"numericEdit",!0),this.hScrollPolicy=getStringOption(attributes.hScrollPolicy,["auto","off","on"]),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.border=null,this.comb=null,this.extras=null,this.margin=null}[$toHTML](availableSpace){var style=toStyle(this,"border","font","margin"),field=this[$getParent]()[$getParent](),style={name:"input",attributes:{type:"text",fieldId:field[$uid],dataId:field[$data]?.[$uid]||field[$uid],class:["xfaTextfield"],style:style,"aria-label":ariaLabel(field),"aria-required":!1}};return isRequired(field)&&(style.attributes["aria-required"]=!0,style.attributes.required=!0),HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[style]})}}class Occur extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"occur",!0),this.id=attributes.id||"",this.initial=""!==attributes.initial?getInteger({data:attributes.initial,defaultValue:"",validate:x=>!0}):"",this.max=""!==attributes.max?getInteger({data:attributes.max,defaultValue:1,validate:x=>!0}):"",this.min=""!==attributes.min?getInteger({data:attributes.min,defaultValue:1,validate:x=>!0}):"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null}[$clean](){var parent=this[$getParent](),originalMin=this.min;""===this.min&&(this.min=parent instanceof PageArea||parent instanceof PageSet?0:1),""===this.max&&(this.max=""===originalMin?parent instanceof PageArea||parent instanceof PageSet?-1:1:this.min),-1!==this.max&&this.max!0}),this.name=attributes.name||"",this.numbered=getInteger({data:attributes.numbered,defaultValue:1,validate:x=>!0}),this.oddOrEven=getStringOption(attributes.oddOrEven,["any","even","odd"]),this.pagePosition=getStringOption(attributes.pagePosition,["any","first","last","only","rest"]),this.relevant=getRelevant(attributes.relevant),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.desc=null,this.extras=null,this.medium=null,this.occur=null,this.area=new XFAObjectArray,this.contentArea=new XFAObjectArray,this.draw=new XFAObjectArray,this.exclGroup=new XFAObjectArray,this.field=new XFAObjectArray,this.subform=new XFAObjectArray}[$isUsable](){return this[$extra]?!this.occur||-1===this.occur.max||this[$extra].numberOfUsep.oddOrEven===parity&&p.pagePosition===position);return parent||this.pageArea.children.find(p=>"any"===p.oddOrEven&&p.pagePosition===position)||this.pageArea.children.find(p=>"any"===p.oddOrEven&&"any"===p.pagePosition)||this.pageArea.children[0]}}class Para extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"para",!0),this.hAlign=getStringOption(attributes.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=attributes.id||"",this.lineHeight=attributes.lineHeight?getMeasurement(attributes.lineHeight,"0pt"):"",this.marginLeft=attributes.marginLeft?getMeasurement(attributes.marginLeft,"0pt"):"",this.marginRight=attributes.marginRight?getMeasurement(attributes.marginRight,"0pt"):"",this.orphans=getInteger({data:attributes.orphans,defaultValue:0,validate:x=>0<=x}),this.preserve=attributes.preserve||"",this.radixOffset=attributes.radixOffset?getMeasurement(attributes.radixOffset,"0pt"):"",this.spaceAbove=attributes.spaceAbove?getMeasurement(attributes.spaceAbove,"0pt"):"",this.spaceBelow=attributes.spaceBelow?getMeasurement(attributes.spaceBelow,"0pt"):"",this.tabDefault=attributes.tabDefault?getMeasurement(this.tabDefault):"",this.tabStops=(attributes.tabStops||"").trim().split(/\s+/).map((x,i)=>i%2==1?getMeasurement(x):x),this.textIndent=attributes.textIndent?getMeasurement(attributes.textIndent,"0pt"):"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.vAlign=getStringOption(attributes.vAlign,["top","bottom","middle"]),this.widows=getInteger({data:attributes.widows,defaultValue:0,validate:x=>0<=x}),this.hyphenation=null}[$toStyle](){var style=toStyle(this,"hAlign");return""!==this.marginLeft&&(style.paddingLeft=measureToString(this.marginLeft)),""!==this.marginRight&&(style.paddingight=measureToString(this.marginRight)),""!==this.spaceAbove&&(style.paddingTop=measureToString(this.spaceAbove)),""!==this.spaceBelow&&(style.paddingBottom=measureToString(this.spaceBelow)),""!==this.textIndent&&(style.textIndent=measureToString(this.textIndent),fixTextIndent(style)),01===x}),this.id=attributes.id||"",this.priority=getStringOption(attributes.priority,["custom","caption","name","toolTip"]),this.rid=attributes.rid||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Stipple extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"stipple",!0),this.id=attributes.id||"",this.rate=getInteger({data:attributes.rate,defaultValue:50,validate:x=>0<=x&&x<=100}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.color=null,this.extras=null}[$toStyle](bgColor){var alpha=this.rate/100;return Util.makeHexColor(Math.round(bgColor.value.r*(1-alpha)+this.value.r*alpha),Math.round(bgColor.value.g*(1-alpha)+this.value.g*alpha),Math.round(bgColor.value.b*(1-alpha)+this.value.b*alpha))}}class Subform extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"subform",!0),this.access=getStringOption(attributes.access,["open","nonInteractive","protected","readOnly"]),this.allowMacro=getInteger({data:attributes.allowMacro,defaultValue:0,validate:x=>1===x}),this.anchorType=getStringOption(attributes.anchorType,["topLeft","bottomCenter","bottomLeft","bottomRight","middleCenter","middleLeft","middleRight","topCenter","topRight"]),this.colSpan=getInteger({data:attributes.colSpan,defaultValue:1,validate:n=>1<=n||-1===n}),this.columnWidths=(attributes.columnWidths||"").trim().split(/\s+/).map(x=>"-1"===x?-1:getMeasurement(x)),this.h=attributes.h?getMeasurement(attributes.h):"",this.hAlign=getStringOption(attributes.hAlign,["left","center","justify","justifyAll","radix","right"]),this.id=attributes.id||"",this.layout=getStringOption(attributes.layout,["position","lr-tb","rl-row","rl-tb","row","table","tb"]),this.locale=attributes.locale||"",this.maxH=getMeasurement(attributes.maxH,"0pt"),this.maxW=getMeasurement(attributes.maxW,"0pt"),this.mergeMode=getStringOption(attributes.mergeMode,["consumeData","matchTemplate"]),this.minH=getMeasurement(attributes.minH,"0pt"),this.minW=getMeasurement(attributes.minW,"0pt"),this.name=attributes.name||"",this.presence=getStringOption(attributes.presence,["visible","hidden","inactive","invisible"]),this.relevant=getRelevant(attributes.relevant),this.restoreState=getStringOption(attributes.restoreState,["manual","auto"]),this.scope=getStringOption(attributes.scope,["name","none"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.w=attributes.w?getMeasurement(attributes.w):"",this.x=getMeasurement(attributes.x,"0pt"),this.y=getMeasurement(attributes.y,"0pt"),this.assist=null,this.bind=null,this.bookend=null,this.border=null,this.break=null,this.calculate=null,this.desc=null,this.extras=null,this.keep=null,this.margin=null,this.occur=null,this.overflow=null,this.pageSet=null,this.para=null,this.traversal=null,this.validate=null,this.variables=null,this.area=new XFAObjectArray,this.breakAfter=new XFAObjectArray,this.breakBefore=new XFAObjectArray,this.connect=new XFAObjectArray,this.draw=new XFAObjectArray,this.event=new XFAObjectArray,this.exObject=new XFAObjectArray,this.exclGroup=new XFAObjectArray,this.field=new XFAObjectArray,this.proto=new XFAObjectArray,this.setProperty=new XFAObjectArray,this.subform=new XFAObjectArray,this.subformSet=new XFAObjectArray}[$getSubformParent](){var parent=this[$getParent]();return parent instanceof SubformSet?parent[$getSubformParent]():parent}[$isBindable](){return!0}[$isThereMoreWidth](){return this.layout.endsWith("-tb")&&0===this[$extra].attempt&&0((kv=kv.split("=",2))[0]=kv[0].trim(),kv)))}}class SubjectDNs extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"subjectDNs",!0),this.id=attributes.id||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.subjectDN=new XFAObjectArray}}class Submit extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"submit",!0),this.embedPDF=getInteger({data:attributes.embedPDF,defaultValue:0,validate:x=>1===x}),this.format=getStringOption(attributes.format,["xdp","formdata","pdf","urlencoded","xfd","xml"]),this.id=attributes.id||"",this.target=attributes.target||"",this.textEncoding=getKeyword({data:attributes.textEncoding?attributes.textEncoding.toLowerCase():"",defaultValue:"",validate:k=>["utf-8","big-five","fontspecific","gbk","gb-18030","gb-2312","ksc-5601","none","shift-jis","ucs-2","utf-16"].includes(k)||k.match(/iso-8859-\d{2}/)}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.xdpContent=attributes.xdpContent||"",this.encrypt=null,this.encryptData=new XFAObjectArray,this.signData=new XFAObjectArray}}class Template extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"template",!0),this.baseProfile=getStringOption(attributes.baseProfile,["full","interactiveForms"]),this.extras=null,this.subform=new XFAObjectArray}[$finalize](){0===this.subform.children.length&&warn("XFA - No subforms in template node."),2<=this.subform.children.length&&warn("XFA - Several subforms in template node: please file a bug."),this[$tabIndex]=DEFAULT_TAB_INDEX}[$isSplittable](){return!0}[$searchNode](expr,container){return expr.startsWith("#")?[this[$ids].get(expr.slice(1))]:searchNode(this,container,expr,!0,!0)}*[$toPages](){if(!this.subform.children.length)return HTMLResult.success({name:"div",children:[]});this[$extra]={overflowNode:null,firstUnsplittable:null,currentContentArea:null,currentPageArea:null,noLayoutFailure:!1,pageNumber:1,pagePosition:"first",oddOrEven:"odd",blankOrNotBlank:"nonBlank",paraStack:[]};const root=this.subform.children[0];root.pageSet[$cleanPage]();var pageAreas=root.pageSet.pageArea.children,mainHtml={name:"div",children:[]};let pageArea=null,breakBefore=null,breakBeforeTarget=null;1<=root.breakBefore.children.length?(breakBefore=root.breakBefore.children[0],breakBeforeTarget=breakBefore.target):1<=root.subform.children.length&&1<=root.subform.children[0].breakBefore.children.length?(breakBefore=root.subform.children[0].breakBefore.children[0],breakBeforeTarget=breakBefore.target):root.break?.beforeTarget?(breakBefore=root.break,breakBeforeTarget=breakBefore.beforeTarget):1<=root.subform.children.length&&root.subform.children[0].break?.beforeTarget&&(breakBefore=root.subform.children[0].break,breakBeforeTarget=breakBefore.beforeTarget),breakBefore&&(target=this[$searchNode](breakBeforeTarget,breakBefore[$getParent]()))instanceof PageArea&&(pageArea=target,breakBefore[$extra]={}),(pageArea=pageArea||pageAreas[0])[$extra]={numberOfUse:1};var target=pageArea[$getParent]();target[$extra]={numberOfUse:1,pageIndex:target.pageArea.children.indexOf(pageArea),pageSetIndex:0};let targetPageArea,leader=null,trailer=null,hasSomething=!0,hasSomethingCounter=0,startIndex=0;for(;;){if(hasSomething)hasSomethingCounter=0;else if(mainHtml.children.pop(),++hasSomethingCounter===MAX_EMPTY_PAGES)return warn("XFA - Something goes wrong: please file a bug."),mainHtml;targetPageArea=null;var page=(this[$extra].currentPageArea=pageArea)[$toHTML]().html,contentAreas=(mainHtml.children.push(page),leader&&(this[$extra].noLayoutFailure=!0,page.children.push(leader[$toHTML](pageArea[$extra].space).html),leader=null),trailer&&(this[$extra].noLayoutFailure=!0,page.children.push(trailer[$toHTML](pageArea[$extra].space).html),trailer=null),pageArea.contentArea.children);const htmlContentAreas=page.children.filter(node=>node.attributes.class.includes("xfaContentarea"));hasSomething=!1,this[$extra].firstUnsplittable=null,this[$extra].noLayoutFailure=!1;var flush=index=>{var html=root[$flushHTML]();html&&(hasSomething||=00<=x}),this.name=attributes.name||"",this.rid=attributes.rid||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$acceptWhitespace](){return!0}[$onChild](child){return child[$namespaceId]===NamespaceIds.xhtml.id?(this[$content]=child,!0):(warn(`XFA - Invalid content in Text: ${child[$nodeName]}.`),!1)}[$onText](str){this[$content]instanceof XFAObject||super[$onText](str)}[$finalize](){"string"==typeof this[$content]&&(this[$content]=this[$content].replaceAll("\r\n","\n"))}[$getExtra](){return"string"==typeof this[$content]?this[$content].split(/[\u2029\u2028\n]/).reduce((acc,line)=>(line&&acc.push(line),acc),[]).join("\n"):this[$content][$text]()}[$toHTML](availableSpace){if("string"!=typeof this[$content])return this[$content][$toHTML](availableSpace);{const html=valueToHtml(this[$content]).html;return this[$content].includes("\u2029")?(html.name="div",html.children=[],this[$content].split("\u2029").map(para=>para.split(/[\u2028\n]/).reduce((acc,line)=>(acc.push({name:"span",value:line},{name:"br"}),acc),[])).forEach(lines=>{html.children.push({name:"p",children:lines})})):/[\u2028\n]/.test(this[$content])&&(html.name="div",html.children=[],this[$content].split(/[\u2028\n]/).forEach(line=>{html.children.push({name:"span",value:line},{name:"br"})})),HTMLResult.success(html)}}}class TextEdit extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"textEdit",!0),this.allowRichText=getInteger({data:attributes.allowRichText,defaultValue:0,validate:x=>1===x}),this.hScrollPolicy=getStringOption(attributes.hScrollPolicy,["auto","off","on"]),this.id=attributes.id||"",this.multiLine=getInteger({data:attributes.multiLine,defaultValue:"",validate:x=>0===x||1===x}),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.vScrollPolicy=getStringOption(attributes.vScrollPolicy,["auto","off","on"]),this.border=null,this.comb=null,this.extras=null,this.margin=null}[$toHTML](availableSpace){var style=toStyle(this,"border","font","margin");let html;var field=this[$getParent]()[$getParent]();return""===this.multiLine&&(this.multiLine=field instanceof Draw?1:0),html=1===this.multiLine?{name:"textarea",attributes:{dataId:field[$data]?.[$uid]||field[$uid],fieldId:field[$uid],class:["xfaTextfield"],style:style,"aria-label":ariaLabel(field),"aria-required":!1}}:{name:"input",attributes:{type:"text",dataId:field[$data]?.[$uid]||field[$uid],fieldId:field[$uid],class:["xfaTextfield"],style:style,"aria-label":ariaLabel(field),"aria-required":!1}},isRequired(field)&&(html.attributes["aria-required"]=!0,html.attributes.required=!0),HTMLResult.success({name:"label",attributes:{class:["xfaLabel"]},children:[html]})}}class Time extends StringObject{constructor(attributes){super(TEMPLATE_NS_ID,"time"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}[$finalize](){var date=this[$content].trim();this[$content]=date?new Date(date):null}[$toHTML](availableSpace){return valueToHtml(this[$content]?this[$content].toString():"")}}class TimeStamp extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"timeStamp"),this.id=attributes.id||"",this.server=attributes.server||"",this.type=getStringOption(attributes.type,["optional","required"]),this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class ToolTip extends StringObject{constructor(attributes){super(TEMPLATE_NS_ID,"toolTip"),this.id=attributes.id||"",this.rid=attributes.rid||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Traversal extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"traversal",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.traverse=new XFAObjectArray}}class Traverse extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"traverse",!0),this.id=attributes.id||"",this.operation=getStringOption(attributes.operation,["next","back","down","first","left","right","up"]),this.ref=attributes.ref||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.script=null}get name(){return this.operation}[$isTransparent](){return!1}}class Ui extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"ui",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.picture=null,this.barcode=null,this.button=null,this.checkButton=null,this.choiceList=null,this.dateTimeEdit=null,this.defaultUi=null,this.imageEdit=null,this.numericEdit=null,this.passwordEdit=null,this.signature=null,this.textEdit=null}[$getExtra](){if(void 0===this[$extra]){for(const name of Object.getOwnPropertyNames(this))if("extras"!==name&&"picture"!==name){var obj=this[name];if(obj instanceof XFAObject)return this[$extra]=obj}this[$extra]=null}return this[$extra]}[$toHTML](availableSpace){var obj=this[$getExtra]();return obj?obj[$toHTML](availableSpace):HTMLResult.EMPTY}}class Validate extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"validate",!0),this.formatTest=getStringOption(attributes.formatTest,["warning","disabled","error"]),this.id=attributes.id||"",this.nullTest=getStringOption(attributes.nullTest,["disabled","error","warning"]),this.scriptTest=getStringOption(attributes.scriptTest,["error","disabled","warning"]),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.extras=null,this.message=null,this.picture=null,this.script=null}}class Value extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"value",!0),this.id=attributes.id||"",this.override=getInteger({data:attributes.override,defaultValue:0,validate:x=>1===x}),this.relevant=getRelevant(attributes.relevant),this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.arc=null,this.boolean=null,this.date=null,this.dateTime=null,this.decimal=null,this.exData=null,this.float=null,this.image=null,this.integer=null,this.line=null,this.rectangle=null,this.text=null,this.time=null}[$setValue](value){var parent=this[$getParent]();if(parent instanceof Field&&parent.ui?.imageEdit)this.image||(this.image=new Image({}),this[$appendChild](this.image)),this.image[$content]=value[$content];else{parent=value[$nodeName];if(null!==this[parent])this[parent][$content]=value[$content];else{for(const name of Object.getOwnPropertyNames(this)){var obj=this[name];obj instanceof XFAObject&&(this[name]=null,this[$removeChild](obj))}this[value[$nodeName]]=value,this[$appendChild](value)}}}[$text](){if(this.exData)return("string"==typeof this.exData[$content]?this.exData[$content]:this.exData[$content][$text]()).trim();for(const name of Object.getOwnPropertyNames(this))if("image"!==name){var obj=this[name];if(obj instanceof XFAObject)return(obj[$content]||"").toString().trim()}return null}[$toHTML](availableSpace){for(const name of Object.getOwnPropertyNames(this)){var obj=this[name];if(obj instanceof XFAObject)return obj[$toHTML](availableSpace)}return HTMLResult.EMPTY}}class Variables extends XFAObject{constructor(attributes){super(TEMPLATE_NS_ID,"variables",!0),this.id=attributes.id||"",this.use=attributes.use||"",this.usehref=attributes.usehref||"",this.boolean=new XFAObjectArray,this.date=new XFAObjectArray,this.dateTime=new XFAObjectArray,this.decimal=new XFAObjectArray,this.exData=new XFAObjectArray,this.float=new XFAObjectArray,this.image=new XFAObjectArray,this.integer=new XFAObjectArray,this.manifest=new XFAObjectArray,this.script=new XFAObjectArray,this.text=new XFAObjectArray,this.time=new XFAObjectArray}[$isTransparent](){return!0}}class TemplateNamespace{static[$buildXFAObject](name,attributes){if(TemplateNamespace.hasOwnProperty(name))return(name=TemplateNamespace[name](attributes))[$setSetAttributes](attributes),name}static appearanceFilter(attrs){return new AppearanceFilter(attrs)}static arc(attrs){return new Arc(attrs)}static area(attrs){return new Area(attrs)}static assist(attrs){return new Assist(attrs)}static barcode(attrs){return new Barcode(attrs)}static bind(attrs){return new Bind(attrs)}static bindItems(attrs){return new BindItems(attrs)}static bookend(attrs){return new Bookend(attrs)}static boolean(attrs){return new BooleanElement(attrs)}static border(attrs){return new Border(attrs)}static break(attrs){return new Break(attrs)}static breakAfter(attrs){return new BreakAfter(attrs)}static breakBefore(attrs){return new BreakBefore(attrs)}static button(attrs){return new Button(attrs)}static calculate(attrs){return new Calculate(attrs)}static caption(attrs){return new Caption(attrs)}static certificate(attrs){return new Certificate(attrs)}static certificates(attrs){return new Certificates(attrs)}static checkButton(attrs){return new CheckButton(attrs)}static choiceList(attrs){return new ChoiceList(attrs)}static color(attrs){return new Color(attrs)}static comb(attrs){return new Comb(attrs)}static connect(attrs){return new Connect(attrs)}static contentArea(attrs){return new ContentArea(attrs)}static corner(attrs){return new Corner(attrs)}static date(attrs){return new DateElement(attrs)}static dateTime(attrs){return new DateTime(attrs)}static dateTimeEdit(attrs){return new DateTimeEdit(attrs)}static decimal(attrs){return new Decimal(attrs)}static defaultUi(attrs){return new DefaultUi(attrs)}static desc(attrs){return new Desc(attrs)}static digestMethod(attrs){return new DigestMethod(attrs)}static digestMethods(attrs){return new DigestMethods(attrs)}static draw(attrs){return new Draw(attrs)}static edge(attrs){return new Edge(attrs)}static encoding(attrs){return new Encoding(attrs)}static encodings(attrs){return new Encodings(attrs)}static encrypt(attrs){return new Encrypt(attrs)}static encryptData(attrs){return new EncryptData(attrs)}static encryption(attrs){return new Encryption(attrs)}static encryptionMethod(attrs){return new EncryptionMethod(attrs)}static encryptionMethods(attrs){return new EncryptionMethods(attrs)}static event(attrs){return new Event(attrs)}static exData(attrs){return new ExData(attrs)}static exObject(attrs){return new ExObject(attrs)}static exclGroup(attrs){return new ExclGroup(attrs)}static execute(attrs){return new Execute(attrs)}static extras(attrs){return new Extras(attrs)}static field(attrs){return new Field(attrs)}static fill(attrs){return new Fill(attrs)}static filter(attrs){return new Filter(attrs)}static float(attrs){return new Float(attrs)}static font(attrs){return new template_Font(attrs)}static format(attrs){return new Format(attrs)}static handler(attrs){return new Handler(attrs)}static hyphenation(attrs){return new Hyphenation(attrs)}static image(attrs){return new Image(attrs)}static imageEdit(attrs){return new ImageEdit(attrs)}static integer(attrs){return new Integer(attrs)}static issuers(attrs){return new Issuers(attrs)}static items(attrs){return new Items(attrs)}static keep(attrs){return new Keep(attrs)}static keyUsage(attrs){return new KeyUsage(attrs)}static line(attrs){return new Line(attrs)}static linear(attrs){return new Linear(attrs)}static lockDocument(attrs){return new LockDocument(attrs)}static manifest(attrs){return new Manifest(attrs)}static margin(attrs){return new Margin(attrs)}static mdp(attrs){return new Mdp(attrs)}static medium(attrs){return new Medium(attrs)}static message(attrs){return new Message(attrs)}static numericEdit(attrs){return new NumericEdit(attrs)}static occur(attrs){return new Occur(attrs)}static oid(attrs){return new Oid(attrs)}static oids(attrs){return new Oids(attrs)}static overflow(attrs){return new Overflow(attrs)}static pageArea(attrs){return new PageArea(attrs)}static pageSet(attrs){return new PageSet(attrs)}static para(attrs){return new Para(attrs)}static passwordEdit(attrs){return new PasswordEdit(attrs)}static pattern(attrs){return new template_Pattern(attrs)}static picture(attrs){return new Picture(attrs)}static proto(attrs){return new Proto(attrs)}static radial(attrs){return new Radial(attrs)}static reason(attrs){return new Reason(attrs)}static reasons(attrs){return new Reasons(attrs)}static rectangle(attrs){return new Rectangle(attrs)}static ref(attrs){return new RefElement(attrs)}static script(attrs){return new Script(attrs)}static setProperty(attrs){return new SetProperty(attrs)}static signData(attrs){return new SignData(attrs)}static signature(attrs){return new Signature(attrs)}static signing(attrs){return new Signing(attrs)}static solid(attrs){return new Solid(attrs)}static speak(attrs){return new Speak(attrs)}static stipple(attrs){return new Stipple(attrs)}static subform(attrs){return new Subform(attrs)}static subformSet(attrs){return new SubformSet(attrs)}static subjectDN(attrs){return new SubjectDN(attrs)}static subjectDNs(attrs){return new SubjectDNs(attrs)}static submit(attrs){return new Submit(attrs)}static template(attrs){return new Template(attrs)}static text(attrs){return new Text(attrs)}static textEdit(attrs){return new TextEdit(attrs)}static time(attrs){return new Time(attrs)}static timeStamp(attrs){return new TimeStamp(attrs)}static toolTip(attrs){return new ToolTip(attrs)}static traversal(attrs){return new Traversal(attrs)}static traverse(attrs){return new Traverse(attrs)}static ui(attrs){return new Ui(attrs)}static validate(attrs){return new Validate(attrs)}static value(attrs){return new Value(attrs)}static variables(attrs){return new Variables(attrs)}}const bind_NS_DATASETS=NamespaceIds.datasets.id;function createText(content){var node=new Text({});return node[$content]=content,node}class Binder{constructor(root){this.root=root,this.datasets=root.datasets,this.data=root.datasets?.data||new XmlObject(NamespaceIds.datasets.id,"data"),this.emptyMerge=0===this.data[$getChildren]().length,this.root.form=this.form=root.template[$clone]()}_isConsumeData(){return!this.emptyMerge&&this._mergeMode}_isMatchTemplate(){return!this._isConsumeData()}bind(){return this._bindElement(this.form,this.data),this.form}getData(){return this.data}_bindValue(formNode,data,picture){if(formNode[$data]=data,formNode[$hasSettableValue]())if(data[$isDataValue]()){var value=data[$getDataValue]();formNode[$setValue](createText(value))}else if(formNode instanceof Field&&"multiSelect"===formNode.ui?.choiceList?.open){const value=data[$getChildren]().map(child=>child[$content].trim()).join("\n");formNode[$setValue](createText(value))}else this._isConsumeData()&&warn("XFA - Nodes haven't the same type.");else!data[$isDataValue]()||this._isMatchTemplate()?this._bindElement(formNode,data):warn("XFA - Nodes haven't the same type.")}_findDataByNameToConsume(name,isValue,dataNode,global){if(!name)return null;let generator,match;for(let i=0;i<3;i++){for(generator=dataNode[$getRealChildrenByNameIt](name,!1,!0);;){if(!(match=generator.next().value))break;if(isValue===match[$isDataValue]())return match}if(dataNode[$namespaceId]===NamespaceIds.datasets.id&&"data"===dataNode[$nodeName])break;dataNode=dataNode[$getParent]()}return global?(generator=this.data[$getRealChildrenByNameIt](name,!0,!1),(match=generator.next().value)||(generator=this.data[$getAttributeIt](name,!0),(match=generator.next().value)?.[$isDataValue]()?match:null)):null}_setProperties(formNode,dataNode){if(formNode.hasOwnProperty("setProperty"))for(var{ref,target,connection}of formNode.setProperty.children){var targetNodes,targetParent,content,name,attrs;connection||ref&&((connection=searchNode(this.root,dataNode,ref,!1,!1))?([connection]=connection,connection[$isDescendent](this.data)?(targetNodes=searchNode(this.root,formNode,target,!1,!1))?([targetNodes]=targetNodes,targetNodes[$isDescendent](formNode)?(targetParent=targetNodes[$getParent](),targetNodes instanceof SetProperty||targetParent instanceof SetProperty?warn("XFA - Invalid target: cannot be a setProperty or one of its properties."):targetNodes instanceof BindItems||targetParent instanceof BindItems?warn("XFA - Invalid target: cannot be a bindItems or one of its properties."):(content=connection[$text](),name=targetNodes[$nodeName],targetNodes instanceof XFAAttribute?((attrs=Object.create(null))[name]=content,attrs=Reflect.construct(Object.getPrototypeOf(targetParent).constructor,[attrs]),targetParent[name]=attrs[name]):targetNodes.hasOwnProperty($content)?(targetNodes[$data]=connection,targetNodes[$content]=content,targetNodes[$finalize]()):warn("XFA - Invalid node to use in setProperty"))):warn("XFA - Invalid target: must be a property or subproperty.")):warn(`XFA - Invalid target: ${target}.`):warn("XFA - Invalid node: must be a data node.")):warn(`XFA - Invalid reference: ${ref}.`))}}_bindItems(formNode,dataNode){if(formNode.hasOwnProperty("items")&&formNode.hasOwnProperty("bindItems")&&!formNode.bindItems.isEmpty()){for(const item of formNode.items.children)formNode[$removeChild](item);formNode.items.clear();var ref,labelRef,valueRef,connection,labels=new Items({}),values=new Items({});formNode[$appendChild](labels),formNode.items.push(labels),formNode[$appendChild](values),formNode.items.push(values);for({ref,labelRef,valueRef,connection}of formNode.bindItems.children)if(!connection&&ref){var labelNodes,valueNodes,nodes=searchNode(this.root,dataNode,ref,!1,!1);if(nodes)for(const node of nodes)node[$isDescendent](this.datasets)?(labelNodes=searchNode(this.root,node,labelRef,!0,!1))?([labelNodes]=labelNodes,labelNodes[$isDescendent](this.datasets)?(valueNodes=searchNode(this.root,node,valueRef,!0,!1))?([valueNodes]=valueNodes,valueNodes[$isDescendent](this.datasets)?(labelNodes=createText(labelNodes[$text]()),valueNodes=createText(valueNodes[$text]()),labels[$appendChild](labelNodes),labels.text.push(labelNodes),values[$appendChild](valueNodes),values.text.push(valueNodes)):warn("XFA - Invalid value: must be a datasets child.")):warn(`XFA - Invalid value: ${valueRef}.`):warn("XFA - Invalid label: must be a datasets child.")):warn(`XFA - Invalid label: ${labelRef}.`):warn(`XFA - Invalid ref (${ref}): must be a datasets child.`);else warn(`XFA - Invalid reference: ${ref}.`)}}}_bindOccurrences(formNode,matches,picture){let baseClone;if(1e.name===formNode.name):parent[name].children).length;var pos=parent[$indexOf](formNode)+1,ii=occur.initial-currentNumber;if(ii){var nodeClone=formNode[$clone]();nodeClone[$removeChild](nodeClone.occur),nodeClone.occur=null,parent[name].push(nodeClone),parent[$insertAt](pos,nodeClone);for(let i=1;i!node[$consumed]):match).length>max?match=match.slice(0,max):0===match.length&&(match=null),match&&this._isConsumeData()&&match.forEach(node=>{node[$consumed]=!0})}else{if(!child.name){this._setAndBind(child,dataNode);continue}if(this._isConsumeData()){for(var matches=[];matches.lengthnode[$getParent]()[$removeChild](node))}}class DataHandler{constructor(root,data){this.data=data,this.dataset=root.datasets||null}serialize(storage){for(var stack=[[-1,this.data[$getChildren]()]];0'];if(this.dataset)for(const child of this.dataset[$getChildren]())"data"!==child[$nodeName]&&child[$toString](buf);return this.data[$toString](buf),buf.push(""),buf.join("")}}const CONFIG_NS_ID=NamespaceIds.config.id;class Acrobat extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"acrobat",!0),this.acrobat7=null,this.autoSave=null,this.common=null,this.validate=null,this.validateApprovalSignatures=null,this.submitUrl=new XFAObjectArray}}class Acrobat7 extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"acrobat7",!0),this.dynamicRender=null}}class ADBE_JSConsole extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"ADBE_JSConsole",["delegate","Enable","Disable"])}}class ADBE_JSDebugger extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"ADBE_JSDebugger",["delegate","Enable","Disable"])}}class AddSilentPrint extends Option01{constructor(attributes){super(CONFIG_NS_ID,"addSilentPrint")}}class AddViewerPreferences extends Option01{constructor(attributes){super(CONFIG_NS_ID,"addViewerPreferences")}}class AdjustData extends Option10{constructor(attributes){super(CONFIG_NS_ID,"adjustData")}}class AdobeExtensionLevel extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"adobeExtensionLevel",0,n=>1<=n&&n<=8)}}class Agent extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"agent",!0),this.name=attributes.name?attributes.name.trim():"",this.common=new XFAObjectArray}}class AlwaysEmbed extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"alwaysEmbed")}}class Amd extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"amd")}}class config_Area extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"area"),this.level=getInteger({data:attributes.level,defaultValue:0,validate:n=>1<=n&&n<=3}),this.name=getStringOption(attributes.name,["","barcode","coreinit","deviceDriver","font","general","layout","merge","script","signature","sourceSet","templateCache"])}}class Attributes extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"attributes",["preserve","delegate","ignore"])}}class AutoSave extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"autoSave",["disabled","enabled"])}}class Base extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"base")}}class BatchOutput extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"batchOutput"),this.format=getStringOption(attributes.format,["none","concat","zip","zipCompress"])}}class BehaviorOverride extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"behaviorOverride")}[$finalize](){this[$content]=new Map(this[$content].trim().split(/\s+/).filter(x=>x.includes(":")).map(x=>x.split(":",2)))}}class Cache extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"cache",!0),this.templateCache=null}}class Change extends Option01{constructor(attributes){super(CONFIG_NS_ID,"change")}}class Common extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"common",!0),this.data=null,this.locale=null,this.localeSet=null,this.messaging=null,this.suppressBanner=null,this.template=null,this.validationMessaging=null,this.versionControl=null,this.log=new XFAObjectArray}}class Compress extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"compress"),this.scope=getStringOption(attributes.scope,["imageOnly","document"])}}class CompressLogicalStructure extends Option01{constructor(attributes){super(CONFIG_NS_ID,"compressLogicalStructure")}}class CompressObjectStream extends Option10{constructor(attributes){super(CONFIG_NS_ID,"compressObjectStream")}}class Compression extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"compression",!0),this.compressLogicalStructure=null,this.compressObjectStream=null,this.level=null,this.type=null}}class Config extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"config",!0),this.acrobat=null,this.present=null,this.trace=null,this.agent=new XFAObjectArray}}class Conformance extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"conformance",["A","B"])}}class ContentCopy extends Option01{constructor(attributes){super(CONFIG_NS_ID,"contentCopy")}}class Copies extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"copies",1,n=>1<=n)}}class Creator extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"creator")}}class CurrentPage extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"currentPage",0,n=>0<=n)}}class Data extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"data",!0),this.adjustData=null,this.attributes=null,this.incrementalLoad=null,this.outputXSL=null,this.range=null,this.record=null,this.startNode=null,this.uri=null,this.window=null,this.xsl=null,this.excludeNS=new XFAObjectArray,this.transform=new XFAObjectArray}}class Debug extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"debug",!0),this.uri=null}}class DefaultTypeface extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"defaultTypeface"),this.writingScript=getStringOption(attributes.writingScript,["*","Arabic","Cyrillic","EastEuropeanRoman","Greek","Hebrew","Japanese","Korean","Roman","SimplifiedChinese","Thai","TraditionalChinese","Vietnamese"])}}class Destination extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"destination",["pdf","pcl","ps","webClient","zpl"])}}class DocumentAssembly extends Option01{constructor(attributes){super(CONFIG_NS_ID,"documentAssembly")}}class Driver extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"driver",!0),this.name=attributes.name?attributes.name.trim():"",this.fontInfo=null,this.xdc=null}}class DuplexOption extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"duplexOption",["simplex","duplexFlipLongEdge","duplexFlipShortEdge"])}}class DynamicRender extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"dynamicRender",["forbidden","required"])}}class Embed extends Option01{constructor(attributes){super(CONFIG_NS_ID,"embed")}}class config_Encrypt extends Option01{constructor(attributes){super(CONFIG_NS_ID,"encrypt")}}class config_Encryption extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"encryption",!0),this.encrypt=null,this.encryptionLevel=null,this.permissions=null}}class EncryptionLevel extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"encryptionLevel",["40bit","128bit"])}}class Enforce extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"enforce")}}class Equate extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"equate"),this.force=getInteger({data:attributes.force,defaultValue:1,validate:n=>0===n}),this.from=attributes.from||"",this.to=attributes.to||""}}class EquateRange extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"equateRange"),this.from=attributes.from||"",this.to=attributes.to||"",this._unicodeRange=attributes.unicodeRange||""}get unicodeRange(){var range,ranges=[];const unicodeRegex=/U\+([0-9a-fA-F]+)/;for(range of this._unicodeRange.split(",").map(x=>x.trim()).filter(x=>!!x))1===(range=range.split("-",2).map(x=>{x=x.match(unicodeRegex);return x?parseInt(x[1],16):0})).length&&range.push(range[0]),ranges.push(range);return shadow(this,"unicodeRange",ranges)}}class Exclude extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"exclude")}[$finalize](){this[$content]=this[$content].trim().split(/\s+/).filter(x=>x&&["calculate","close","enter","exit","initialize","ready","validate"].includes(x))}}class ExcludeNS extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"excludeNS")}}class FlipLabel extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"flipLabel",["usePrinterSetting","on","off"])}}class config_FontInfo extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"fontInfo",!0),this.embed=null,this.map=null,this.subsetBelow=null,this.alwaysEmbed=new XFAObjectArray,this.defaultTypeface=new XFAObjectArray,this.neverEmbed=new XFAObjectArray}}class FormFieldFilling extends Option01{constructor(attributes){super(CONFIG_NS_ID,"formFieldFilling")}}class GroupParent extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"groupParent")}}class IfEmpty extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"ifEmpty",["dataValue","dataGroup","ignore","remove"])}}class IncludeXDPContent extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"includeXDPContent")}}class IncrementalLoad extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"incrementalLoad",["none","forwardOnly"])}}class IncrementalMerge extends Option01{constructor(attributes){super(CONFIG_NS_ID,"incrementalMerge")}}class Interactive extends Option01{constructor(attributes){super(CONFIG_NS_ID,"interactive")}}class Jog extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"jog",["usePrinterSetting","none","pageSet"])}}class LabelPrinter extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"labelPrinter",!0),this.name=getStringOption(attributes.name,["zpl","dpl","ipl","tcpl"]),this.batchOutput=null,this.flipLabel=null,this.fontInfo=null,this.xdc=null}}class Layout extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"layout",["paginate","panel"])}}class Level extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"level",0,n=>01<=n)}}class NameAttr extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"nameAttr")}}class NeverEmbed extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"neverEmbed")}}class NumberOfCopies extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"numberOfCopies",null,n=>2<=n&&n<=5)}}class OpenAction extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"openAction",!0),this.destination=null}}class Output extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"output",!0),this.to=null,this.type=null,this.uri=null}}class OutputBin extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"outputBin")}}class OutputXSL extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"outputXSL",!0),this.uri=null}}class Overprint extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"overprint",["none","both","draw","field"])}}class Packets extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"packets")}[$finalize](){"*"!==this[$content]&&(this[$content]=this[$content].trim().split(/\s+/).filter(x=>["config","datasets","template","xfdf","xslt"].includes(x)))}}class PageOffset extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"pageOffset"),this.x=getInteger({data:attributes.x,defaultValue:"useXDCSetting",validate:n=>!0}),this.y=getInteger({data:attributes.y,defaultValue:"useXDCSetting",validate:n=>!0})}}class PageRange extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"pageRange")}[$finalize](){var numbers=this[$content].trim().split(/\s+/).map(x=>parseInt(x,10)),ranges=[];for(let i=0,ii=numbers.length;i!1)}}class Pcl extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"pcl",!0),this.name=attributes.name||"",this.batchOutput=null,this.fontInfo=null,this.jog=null,this.mediumInfo=null,this.outputBin=null,this.pageOffset=null,this.staple=null,this.xdc=null}}class Pdf extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"pdf",!0),this.name=attributes.name||"",this.adobeExtensionLevel=null,this.batchOutput=null,this.compression=null,this.creator=null,this.encryption=null,this.fontInfo=null,this.interactive=null,this.linearized=null,this.openAction=null,this.pdfa=null,this.producer=null,this.renderPolicy=null,this.scriptModel=null,this.silentPrint=null,this.submitFormat=null,this.tagged=null,this.version=null,this.viewerPreferences=null,this.xdc=null}}class Pdfa extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"pdfa",!0),this.amd=null,this.conformance=null,this.includeXDPContent=null,this.part=null}}class Permissions extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"permissions",!0),this.accessibleContent=null,this.change=null,this.contentCopy=null,this.documentAssembly=null,this.formFieldFilling=null,this.modifyAnnots=null,this.plaintextMetadata=null,this.print=null,this.printHighQuality=null}}class PickTrayByPDFSize extends Option01{constructor(attributes){super(CONFIG_NS_ID,"pickTrayByPDFSize")}}class config_Picture extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"picture")}}class PlaintextMetadata extends Option01{constructor(attributes){super(CONFIG_NS_ID,"plaintextMetadata")}}class Presence extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"presence",["preserve","dissolve","dissolveStructure","ignore","remove"])}}class Present extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"present",!0),this.behaviorOverride=null,this.cache=null,this.common=null,this.copies=null,this.destination=null,this.incrementalMerge=null,this.layout=null,this.output=null,this.overprint=null,this.pagination=null,this.paginationOverride=null,this.script=null,this.validate=null,this.xdp=null,this.driver=new XFAObjectArray,this.labelPrinter=new XFAObjectArray,this.pcl=new XFAObjectArray,this.pdf=new XFAObjectArray,this.ps=new XFAObjectArray,this.submitUrl=new XFAObjectArray,this.webClient=new XFAObjectArray,this.zpl=new XFAObjectArray}}class Print extends Option01{constructor(attributes){super(CONFIG_NS_ID,"print")}}class PrintHighQuality extends Option01{constructor(attributes){super(CONFIG_NS_ID,"printHighQuality")}}class PrintScaling extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"printScaling",["appdefault","noScaling"])}}class PrinterName extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"printerName")}}class Producer extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"producer")}}class Ps extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"ps",!0),this.name=attributes.name||"",this.batchOutput=null,this.fontInfo=null,this.jog=null,this.mediumInfo=null,this.outputBin=null,this.staple=null,this.xdc=null}}class Range extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"range")}[$finalize](){this[$content]=this[$content].trim().split(/\s*,\s*/,2).map(range=>range.split("-").map(x=>parseInt(x.trim(),10))).filter(range=>range.every(x=>!isNaN(x))).map(range=>(1===range.length&&range.push(range[0]),range))}}class Record extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"record")}[$finalize](){this[$content]=this[$content].trim();var n=parseInt(this[$content],10);!isNaN(n)&&0<=n&&(this[$content]=n)}}class Relevant extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"relevant")}[$finalize](){this[$content]=this[$content].trim().split(/\s+/)}}class Rename extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"rename")}[$finalize](){this[$content]=this[$content].trim(),(this[$content].toLowerCase().startsWith("xml")||new RegExp("[\\p{L}_][\\p{L}\\d._\\p{M}-]*","u").test(this[$content]))&&warn("XFA - Rename: invalid XFA name")}}class RenderPolicy extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"renderPolicy",["server","client"])}}class RunScripts extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"runScripts",["both","client","none","server"])}}class config_Script extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"script",!0),this.currentPage=null,this.exclude=null,this.runScripts=null}}class ScriptModel extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"scriptModel",["XFA","none"])}}class Severity extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"severity",["ignore","error","information","trace","warning"])}}class SilentPrint extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"silentPrint",!0),this.addSilentPrint=null,this.printerName=null}}class Staple extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"staple"),this.mode=getStringOption(attributes.mode,["usePrinterSetting","on","off"])}}class StartNode extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"startNode")}}class StartPage extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"startPage",0,n=>!0)}}class SubmitFormat extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"submitFormat",["html","delegate","fdf","xml","pdf"])}}class SubmitUrl extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"submitUrl")}}class SubsetBelow extends IntegerObject{constructor(attributes){super(CONFIG_NS_ID,"subsetBelow",100,n=>0<=n&&n<=100)}}class SuppressBanner extends Option01{constructor(attributes){super(CONFIG_NS_ID,"suppressBanner")}}class Tagged extends Option01{constructor(attributes){super(CONFIG_NS_ID,"tagged")}}class config_Template extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"template",!0),this.base=null,this.relevant=null,this.startPage=null,this.uri=null,this.xsl=null}}class Threshold extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"threshold",["trace","error","information","warning"])}}class To extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"to",["null","memory","stderr","stdout","system","uri"])}}class TemplateCache extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"templateCache"),this.maxEntries=getInteger({data:attributes.maxEntries,defaultValue:5,validate:n=>0<=n})}}class Trace extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"trace",!0),this.area=new XFAObjectArray}}class Transform extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"transform",!0),this.groupParent=null,this.ifEmpty=null,this.nameAttr=null,this.picture=null,this.presence=null,this.rename=null,this.whitespace=null}}class Type extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"type",["none","ascii85","asciiHex","ccittfax","flate","lzw","runLength","native","xdp","mergedXDP"])}}class Uri extends StringObject{constructor(attributes){super(CONFIG_NS_ID,"uri")}}class config_Validate extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"validate",["preSubmit","prePrint","preExecute","preSave"])}}class ValidateApprovalSignatures extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"validateApprovalSignatures")}[$finalize](){this[$content]=this[$content].trim().split(/\s+/).filter(x=>["docReady","postSign"].includes(x))}}class ValidationMessaging extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"validationMessaging",["allMessagesIndividually","allMessagesTogether","firstMessageOnly","noMessages"])}}class Version extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"version",["1.7","1.6","1.5","1.4","1.3","1.2"])}}class VersionControl extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"VersionControl"),this.outputBelow=getStringOption(attributes.outputBelow,["warn","error","update"]),this.sourceAbove=getStringOption(attributes.sourceAbove,["warn","error"]),this.sourceBelow=getStringOption(attributes.sourceBelow,["update","maintain"])}}class ViewerPreferences extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"viewerPreferences",!0),this.ADBE_JSConsole=null,this.ADBE_JSDebugger=null,this.addViewerPreferences=null,this.duplexOption=null,this.enforce=null,this.numberOfCopies=null,this.pageRange=null,this.pickTrayByPDFSize=null,this.printScaling=null}}class WebClient extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"webClient",!0),this.name=attributes.name?attributes.name.trim():"",this.fontInfo=null,this.xdc=null}}class Whitespace extends OptionObject{constructor(attributes){super(CONFIG_NS_ID,"whitespace",["preserve","ltrim","normalize","rtrim","trim"])}}class Window extends ContentObject{constructor(attributes){super(CONFIG_NS_ID,"window")}[$finalize](){var pair=this[$content].trim().split(/\s*,\s*/,2).map(x=>parseInt(x,10));pair.some(x=>isNaN(x))?this[$content]=[0,0]:(1===pair.length&&pair.push(pair[0]),this[$content]=pair)}}class Xdc extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"xdc",!0),this.uri=new XFAObjectArray,this.xsl=new XFAObjectArray}}class Xdp extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"xdp",!0),this.packets=null}}class Xsl extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"xsl",!0),this.debug=null,this.uri=null}}class Zpl extends XFAObject{constructor(attributes){super(CONFIG_NS_ID,"zpl",!0),this.name=attributes.name?attributes.name.trim():"",this.batchOutput=null,this.flipLabel=null,this.fontInfo=null,this.xdc=null}}class ConfigNamespace{static[$buildXFAObject](name,attributes){if(ConfigNamespace.hasOwnProperty(name))return ConfigNamespace[name](attributes)}static acrobat(attrs){return new Acrobat(attrs)}static acrobat7(attrs){return new Acrobat7(attrs)}static ADBE_JSConsole(attrs){return new ADBE_JSConsole(attrs)}static ADBE_JSDebugger(attrs){return new ADBE_JSDebugger(attrs)}static addSilentPrint(attrs){return new AddSilentPrint(attrs)}static addViewerPreferences(attrs){return new AddViewerPreferences(attrs)}static adjustData(attrs){return new AdjustData(attrs)}static adobeExtensionLevel(attrs){return new AdobeExtensionLevel(attrs)}static agent(attrs){return new Agent(attrs)}static alwaysEmbed(attrs){return new AlwaysEmbed(attrs)}static amd(attrs){return new Amd(attrs)}static area(attrs){return new config_Area(attrs)}static attributes(attrs){return new Attributes(attrs)}static autoSave(attrs){return new AutoSave(attrs)}static base(attrs){return new Base(attrs)}static batchOutput(attrs){return new BatchOutput(attrs)}static behaviorOverride(attrs){return new BehaviorOverride(attrs)}static cache(attrs){return new Cache(attrs)}static change(attrs){return new Change(attrs)}static common(attrs){return new Common(attrs)}static compress(attrs){return new Compress(attrs)}static compressLogicalStructure(attrs){return new CompressLogicalStructure(attrs)}static compressObjectStream(attrs){return new CompressObjectStream(attrs)}static compression(attrs){return new Compression(attrs)}static config(attrs){return new Config(attrs)}static conformance(attrs){return new Conformance(attrs)}static contentCopy(attrs){return new ContentCopy(attrs)}static copies(attrs){return new Copies(attrs)}static creator(attrs){return new Creator(attrs)}static currentPage(attrs){return new CurrentPage(attrs)}static data(attrs){return new Data(attrs)}static debug(attrs){return new Debug(attrs)}static defaultTypeface(attrs){return new DefaultTypeface(attrs)}static destination(attrs){return new Destination(attrs)}static documentAssembly(attrs){return new DocumentAssembly(attrs)}static driver(attrs){return new Driver(attrs)}static duplexOption(attrs){return new DuplexOption(attrs)}static dynamicRender(attrs){return new DynamicRender(attrs)}static embed(attrs){return new Embed(attrs)}static encrypt(attrs){return new config_Encrypt(attrs)}static encryption(attrs){return new config_Encryption(attrs)}static encryptionLevel(attrs){return new EncryptionLevel(attrs)}static enforce(attrs){return new Enforce(attrs)}static equate(attrs){return new Equate(attrs)}static equateRange(attrs){return new EquateRange(attrs)}static exclude(attrs){return new Exclude(attrs)}static excludeNS(attrs){return new ExcludeNS(attrs)}static flipLabel(attrs){return new FlipLabel(attrs)}static fontInfo(attrs){return new config_FontInfo(attrs)}static formFieldFilling(attrs){return new FormFieldFilling(attrs)}static groupParent(attrs){return new GroupParent(attrs)}static ifEmpty(attrs){return new IfEmpty(attrs)}static includeXDPContent(attrs){return new IncludeXDPContent(attrs)}static incrementalLoad(attrs){return new IncrementalLoad(attrs)}static incrementalMerge(attrs){return new IncrementalMerge(attrs)}static interactive(attrs){return new Interactive(attrs)}static jog(attrs){return new Jog(attrs)}static labelPrinter(attrs){return new LabelPrinter(attrs)}static layout(attrs){return new Layout(attrs)}static level(attrs){return new Level(attrs)}static linearized(attrs){return new Linearized(attrs)}static locale(attrs){return new Locale(attrs)}static localeSet(attrs){return new LocaleSet(attrs)}static log(attrs){return new Log(attrs)}static map(attrs){return new MapElement(attrs)}static mediumInfo(attrs){return new MediumInfo(attrs)}static message(attrs){return new config_Message(attrs)}static messaging(attrs){return new Messaging(attrs)}static mode(attrs){return new Mode(attrs)}static modifyAnnots(attrs){return new ModifyAnnots(attrs)}static msgId(attrs){return new MsgId(attrs)}static nameAttr(attrs){return new NameAttr(attrs)}static neverEmbed(attrs){return new NeverEmbed(attrs)}static numberOfCopies(attrs){return new NumberOfCopies(attrs)}static openAction(attrs){return new OpenAction(attrs)}static output(attrs){return new Output(attrs)}static outputBin(attrs){return new OutputBin(attrs)}static outputXSL(attrs){return new OutputXSL(attrs)}static overprint(attrs){return new Overprint(attrs)}static packets(attrs){return new Packets(attrs)}static pageOffset(attrs){return new PageOffset(attrs)}static pageRange(attrs){return new PageRange(attrs)}static pagination(attrs){return new Pagination(attrs)}static paginationOverride(attrs){return new PaginationOverride(attrs)}static part(attrs){return new Part(attrs)}static pcl(attrs){return new Pcl(attrs)}static pdf(attrs){return new Pdf(attrs)}static pdfa(attrs){return new Pdfa(attrs)}static permissions(attrs){return new Permissions(attrs)}static pickTrayByPDFSize(attrs){return new PickTrayByPDFSize(attrs)}static picture(attrs){return new config_Picture(attrs)}static plaintextMetadata(attrs){return new PlaintextMetadata(attrs)}static presence(attrs){return new Presence(attrs)}static present(attrs){return new Present(attrs)}static print(attrs){return new Print(attrs)}static printHighQuality(attrs){return new PrintHighQuality(attrs)}static printScaling(attrs){return new PrintScaling(attrs)}static printerName(attrs){return new PrinterName(attrs)}static producer(attrs){return new Producer(attrs)}static ps(attrs){return new Ps(attrs)}static range(attrs){return new Range(attrs)}static record(attrs){return new Record(attrs)}static relevant(attrs){return new Relevant(attrs)}static rename(attrs){return new Rename(attrs)}static renderPolicy(attrs){return new RenderPolicy(attrs)}static runScripts(attrs){return new RunScripts(attrs)}static script(attrs){return new config_Script(attrs)}static scriptModel(attrs){return new ScriptModel(attrs)}static severity(attrs){return new Severity(attrs)}static silentPrint(attrs){return new SilentPrint(attrs)}static staple(attrs){return new Staple(attrs)}static startNode(attrs){return new StartNode(attrs)}static startPage(attrs){return new StartPage(attrs)}static submitFormat(attrs){return new SubmitFormat(attrs)}static submitUrl(attrs){return new SubmitUrl(attrs)}static subsetBelow(attrs){return new SubsetBelow(attrs)}static suppressBanner(attrs){return new SuppressBanner(attrs)}static tagged(attrs){return new Tagged(attrs)}static template(attrs){return new config_Template(attrs)}static templateCache(attrs){return new TemplateCache(attrs)}static threshold(attrs){return new Threshold(attrs)}static to(attrs){return new To(attrs)}static trace(attrs){return new Trace(attrs)}static transform(attrs){return new Transform(attrs)}static type(attrs){return new Type(attrs)}static uri(attrs){return new Uri(attrs)}static validate(attrs){return new config_Validate(attrs)}static validateApprovalSignatures(attrs){return new ValidateApprovalSignatures(attrs)}static validationMessaging(attrs){return new ValidationMessaging(attrs)}static version(attrs){return new Version(attrs)}static versionControl(attrs){return new VersionControl(attrs)}static viewerPreferences(attrs){return new ViewerPreferences(attrs)}static webClient(attrs){return new WebClient(attrs)}static whitespace(attrs){return new Whitespace(attrs)}static window(attrs){return new Window(attrs)}static xdc(attrs){return new Xdc(attrs)}static xdp(attrs){return new Xdp(attrs)}static xsl(attrs){return new Xsl(attrs)}static zpl(attrs){return new Zpl(attrs)}}const CONNECTION_SET_NS_ID=NamespaceIds.connectionSet.id;class ConnectionSet extends XFAObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"connectionSet",!0),this.wsdlConnection=new XFAObjectArray,this.xmlConnection=new XFAObjectArray,this.xsdConnection=new XFAObjectArray}}class EffectiveInputPolicy extends XFAObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"effectiveInputPolicy"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class EffectiveOutputPolicy extends XFAObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"effectiveOutputPolicy"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class Operation extends StringObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"operation"),this.id=attributes.id||"",this.input=attributes.input||"",this.name=attributes.name||"",this.output=attributes.output||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class RootElement extends StringObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"rootElement"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class SoapAction extends StringObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"soapAction"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class SoapAddress extends StringObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"soapAddress"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class connection_set_Uri extends StringObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"uri"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class WsdlAddress extends StringObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"wsdlAddress"),this.id=attributes.id||"",this.name=attributes.name||"",this.use=attributes.use||"",this.usehref=attributes.usehref||""}}class WsdlConnection extends XFAObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"wsdlConnection",!0),this.dataDescription=attributes.dataDescription||"",this.name=attributes.name||"",this.effectiveInputPolicy=null,this.effectiveOutputPolicy=null,this.operation=null,this.soapAction=null,this.soapAddress=null,this.wsdlAddress=null}}class XmlConnection extends XFAObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"xmlConnection",!0),this.dataDescription=attributes.dataDescription||"",this.name=attributes.name||"",this.uri=null}}class XsdConnection extends XFAObject{constructor(attributes){super(CONNECTION_SET_NS_ID,"xsdConnection",!0),this.dataDescription=attributes.dataDescription||"",this.name=attributes.name||"",this.rootElement=null,this.uri=null}}class ConnectionSetNamespace{static[$buildXFAObject](name,attributes){if(ConnectionSetNamespace.hasOwnProperty(name))return ConnectionSetNamespace[name](attributes)}static connectionSet(attrs){return new ConnectionSet(attrs)}static effectiveInputPolicy(attrs){return new EffectiveInputPolicy(attrs)}static effectiveOutputPolicy(attrs){return new EffectiveOutputPolicy(attrs)}static operation(attrs){return new Operation(attrs)}static rootElement(attrs){return new RootElement(attrs)}static soapAction(attrs){return new SoapAction(attrs)}static soapAddress(attrs){return new SoapAddress(attrs)}static uri(attrs){return new connection_set_Uri(attrs)}static wsdlAddress(attrs){return new WsdlAddress(attrs)}static wsdlConnection(attrs){return new WsdlConnection(attrs)}static xmlConnection(attrs){return new XmlConnection(attrs)}static xsdConnection(attrs){return new XsdConnection(attrs)}}const DATASETS_NS_ID=NamespaceIds.datasets.id;class datasets_Data extends XmlObject{constructor(attributes){super(DATASETS_NS_ID,"data",attributes)}[$isNsAgnostic](){return!0}}class Datasets extends XFAObject{constructor(attributes){super(DATASETS_NS_ID,"datasets",!0),this.data=null,this.Signature=null}[$onChild](child){var name=child[$nodeName];("data"===name&&child[$namespaceId]===DATASETS_NS_ID||"Signature"===name&&child[$namespaceId]===NamespaceIds.signature.id)&&(this[name]=child),this[$appendChild](child)}}class DatasetsNamespace{static[$buildXFAObject](name,attributes){if(DatasetsNamespace.hasOwnProperty(name))return DatasetsNamespace[name](attributes)}static datasets(attributes){return new Datasets(attributes)}static data(attributes){return new datasets_Data(attributes)}}const LOCALE_SET_NS_ID=NamespaceIds.localeSet.id;class CalendarSymbols extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"calendarSymbols",!0),this.name="gregorian",this.dayNames=new XFAObjectArray(2),this.eraNames=null,this.meridiemNames=null,this.monthNames=new XFAObjectArray(2)}}class CurrencySymbol extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"currencySymbol"),this.name=getStringOption(attributes.name,["symbol","isoname","decimal"])}}class CurrencySymbols extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"currencySymbols",!0),this.currencySymbol=new XFAObjectArray(3)}}class DatePattern extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"datePattern"),this.name=getStringOption(attributes.name,["full","long","med","short"])}}class DatePatterns extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"datePatterns",!0),this.datePattern=new XFAObjectArray(4)}}class DateTimeSymbols extends ContentObject{constructor(attributes){super(LOCALE_SET_NS_ID,"dateTimeSymbols")}}class Day extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"day")}}class DayNames extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"dayNames",!0),this.abbr=getInteger({data:attributes.abbr,defaultValue:0,validate:x=>1===x}),this.day=new XFAObjectArray(7)}}class Era extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"era")}}class EraNames extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"eraNames",!0),this.era=new XFAObjectArray(2)}}class locale_set_Locale extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"locale",!0),this.desc=attributes.desc||"",this.name="isoname",this.calendarSymbols=null,this.currencySymbols=null,this.datePatterns=null,this.dateTimeSymbols=null,this.numberPatterns=null,this.numberSymbols=null,this.timePatterns=null,this.typeFaces=null}}class locale_set_LocaleSet extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"localeSet",!0),this.locale=new XFAObjectArray}}class Meridiem extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"meridiem")}}class MeridiemNames extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"meridiemNames",!0),this.meridiem=new XFAObjectArray(2)}}class Month extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"month")}}class MonthNames extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"monthNames",!0),this.abbr=getInteger({data:attributes.abbr,defaultValue:0,validate:x=>1===x}),this.month=new XFAObjectArray(12)}}class NumberPattern extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"numberPattern"),this.name=getStringOption(attributes.name,["full","long","med","short"])}}class NumberPatterns extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"numberPatterns",!0),this.numberPattern=new XFAObjectArray(4)}}class NumberSymbol extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"numberSymbol"),this.name=getStringOption(attributes.name,["decimal","grouping","percent","minus","zero"])}}class NumberSymbols extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"numberSymbols",!0),this.numberSymbol=new XFAObjectArray(5)}}class TimePattern extends StringObject{constructor(attributes){super(LOCALE_SET_NS_ID,"timePattern"),this.name=getStringOption(attributes.name,["full","long","med","short"])}}class TimePatterns extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"timePatterns",!0),this.timePattern=new XFAObjectArray(4)}}class TypeFace extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"typeFace",!0),this.name=""|attributes.name}}class TypeFaces extends XFAObject{constructor(attributes){super(LOCALE_SET_NS_ID,"typeFaces",!0),this.typeFace=new XFAObjectArray}}class LocaleSetNamespace{static[$buildXFAObject](name,attributes){if(LocaleSetNamespace.hasOwnProperty(name))return LocaleSetNamespace[name](attributes)}static calendarSymbols(attrs){return new CalendarSymbols(attrs)}static currencySymbol(attrs){return new CurrencySymbol(attrs)}static currencySymbols(attrs){return new CurrencySymbols(attrs)}static datePattern(attrs){return new DatePattern(attrs)}static datePatterns(attrs){return new DatePatterns(attrs)}static dateTimeSymbols(attrs){return new DateTimeSymbols(attrs)}static day(attrs){return new Day(attrs)}static dayNames(attrs){return new DayNames(attrs)}static era(attrs){return new Era(attrs)}static eraNames(attrs){return new EraNames(attrs)}static locale(attrs){return new locale_set_Locale(attrs)}static localeSet(attrs){return new locale_set_LocaleSet(attrs)}static meridiem(attrs){return new Meridiem(attrs)}static meridiemNames(attrs){return new MeridiemNames(attrs)}static month(attrs){return new Month(attrs)}static monthNames(attrs){return new MonthNames(attrs)}static numberPattern(attrs){return new NumberPattern(attrs)}static numberPatterns(attrs){return new NumberPatterns(attrs)}static numberSymbol(attrs){return new NumberSymbol(attrs)}static numberSymbols(attrs){return new NumberSymbols(attrs)}static timePattern(attrs){return new TimePattern(attrs)}static timePatterns(attrs){return new TimePatterns(attrs)}static typeFace(attrs){return new TypeFace(attrs)}static typeFaces(attrs){return new TypeFaces(attrs)}}const SIGNATURE_NS_ID=NamespaceIds.signature.id;class signature_Signature extends XFAObject{constructor(attributes){super(SIGNATURE_NS_ID,"signature",!0)}}class SignatureNamespace{static[$buildXFAObject](name,attributes){if(SignatureNamespace.hasOwnProperty(name))return SignatureNamespace[name](attributes)}static signature(attributes){return new signature_Signature(attributes)}}const STYLESHEET_NS_ID=NamespaceIds.stylesheet.id;class Stylesheet extends XFAObject{constructor(attributes){super(STYLESHEET_NS_ID,"stylesheet",!0)}}class StylesheetNamespace{static[$buildXFAObject](name,attributes){if(StylesheetNamespace.hasOwnProperty(name))return StylesheetNamespace[name](attributes)}static stylesheet(attributes){return new Stylesheet(attributes)}}const XDP_NS_ID=NamespaceIds.xdp.id;class xdp_Xdp extends XFAObject{constructor(attributes){super(XDP_NS_ID,"xdp",!0),this.uuid=attributes.uuid||"",this.timeStamp=attributes.timeStamp||"",this.config=null,this.connectionSet=null,this.datasets=null,this.localeSet=null,this.stylesheet=new XFAObjectArray,this.template=null}[$onChildCheck](child){var ns=NamespaceIds[child[$nodeName]];return ns&&child[$namespaceId]===ns.id}}class XdpNamespace{static[$buildXFAObject](name,attributes){if(XdpNamespace.hasOwnProperty(name))return XdpNamespace[name](attributes)}static xdp(attributes){return new xdp_Xdp(attributes)}}const XHTML_NS_ID=NamespaceIds.xhtml.id,$richText=Symbol(),VALID_STYLES=new Set(["color","font","font-family","font-size","font-stretch","font-style","font-weight","margin","margin-bottom","margin-left","margin-right","margin-top","letter-spacing","line-height","orphans","page-break-after","page-break-before","page-break-inside","tab-interval","tab-stop","text-align","text-decoration","text-indent","vertical-align","widows","kerning-mode","xfa-font-horizontal-scale","xfa-font-vertical-scale","xfa-spacerun","xfa-tab-stops"]),StyleMapping=new Map([["page-break-after","breakAfter"],["page-break-before","breakBefore"],["page-break-inside","breakInside"],["kerning-mode",value=>"none"===value?"none":"normal"],["xfa-font-horizontal-scale",value=>`scaleX(${Math.max(0,Math.min(parseInt(value)/100)).toFixed(2)})`],["xfa-font-vertical-scale",value=>`scaleY(${Math.max(0,Math.min(parseInt(value)/100)).toFixed(2)})`],["xfa-spacerun",""],["xfa-tab-stops",""],["font-size",(value,original)=>measureToString(.99*(value=original.fontSize=getMeasurement(value)))],["letter-spacing",value=>measureToString(getMeasurement(value))],["line-height",value=>measureToString(getMeasurement(value))],["margin",value=>measureToString(getMeasurement(value))],["margin-bottom",value=>measureToString(getMeasurement(value))],["margin-left",value=>measureToString(getMeasurement(value))],["margin-right",value=>measureToString(getMeasurement(value))],["margin-top",value=>measureToString(getMeasurement(value))],["text-indent",value=>measureToString(getMeasurement(value))],["font-family",value=>value],["vertical-align",value=>measureToString(getMeasurement(value))]]),spacesRegExp=/\s+/g,crlfRegExp=/[\r\n]+/g,crlfForRichTextRegExp=/\r\n?/g;function mapStyle(styleStr,node,richText){var style=Object.create(null);if(styleStr){var key,value,original=Object.create(null);for([key,value]of styleStr.split(";").map(s=>s.split(":",2))){var mapping=StyleMapping.get(key);if(""!==mapping){let newValue=value;mapping&&(newValue="string"==typeof mapping?mapping:mapping(value,original)),key.endsWith("scale")?style.transform=style.transform?style[key]+" "+newValue:newValue:style[key.replaceAll(/-([a-zA-Z])/g,(_,x)=>x.toUpperCase())]=newValue}}style.fontFamily&&setFontFamily({typeface:style.fontFamily,weight:style.fontWeight||"normal",posture:style.fontStyle||"normal",size:original.fontSize||0},node,node[$globalData].fontFinder,style),richText&&style.verticalAlign&&"0px"!==style.verticalAlign&&style.fontSize&&(styleStr=getMeasurement(style.fontSize),style.fontSize=measureToString(.583*styleStr),style.verticalAlign=measureToString(Math.sign(getMeasurement(style.verticalAlign))*styleStr*.333)),richText&&style.fontSize&&(style.fontSize=`calc(${style.fontSize} * var(--scale-factor))`),fixTextIndent(style)}return style}function checkStyle(node){return node.style?node.style.trim().split(/\s*;\s*/).filter(s=>!!s).map(s=>s.split(/\s*:\s*/,2)).filter(([key,value])=>("font-family"===key&&node[$globalData].usedTypefaces.add(value),VALID_STYLES.has(key))).map(kv=>kv.join(":")).join(";"):""}const NoWhites=new Set(["body","html"]);class XhtmlObject extends XmlObject{constructor(attributes,name){super(XHTML_NS_ID,name),this[$richText]=!1,this.style=attributes.style||""}[$clean](builder){super[$clean](builder),this.style=checkStyle(this)}[$acceptWhitespace](){return!NoWhites.has(this[$nodeName])}[$onText](str,richText=!1){richText?this[$richText]=!0:(str=str.replaceAll(crlfRegExp,""),this.style.includes("xfa-spacerun:yes")||(str=str.replaceAll(spacesRegExp," "))),str&&(this[$content]+=str)}[$pushGlyphs](measure,mustPop=!0){var key,value,xfaFont=Object.create(null),margin={top:NaN,bottom:NaN,left:NaN,right:NaN};let lineHeight=null;for([key,value]of this.style.split(";").map(s=>s.split(":",2)))switch(key){case"font-family":xfaFont.typeface=stripQuotes(value);break;case"font-size":xfaFont.size=getMeasurement(value);break;case"font-weight":xfaFont.weight=value;break;case"font-style":xfaFont.posture=value;break;case"letter-spacing":xfaFont.letterSpacing=getMeasurement(value);break;case"margin":var values=value.split(/ \t/).map(x=>getMeasurement(x));switch(values.length){case 1:margin.top=margin.bottom=margin.left=margin.right=values[0];break;case 2:margin.top=margin.bottom=values[0],margin.left=margin.right=values[1];break;case 3:margin.top=values[0],margin.bottom=values[2],margin.left=margin.right=values[1];break;case 4:margin.top=values[0],margin.left=values[1],margin.bottom=values[2],margin.right=values[3]}break;case"margin-top":margin.top=getMeasurement(value);break;case"margin-bottom":margin.bottom=getMeasurement(value);break;case"margin-left":margin.left=getMeasurement(value);break;case"margin-right":margin.right=getMeasurement(value);break;case"line-height":lineHeight=getMeasurement(value)}if(measure.pushData(xfaFont,margin,lineHeight),this[$content])measure.addString(this[$content]);else for(const child of this[$getChildren]())"#text"===child[$nodeName]?measure.addString(child[$content]):child[$pushGlyphs](measure);mustPop&&measure.popFont()}[$toHTML](availableSpace){var children=[];if(this[$extra]={children:children},this[$childrenToHTML]({}),0===children.length&&!this[$content])return HTMLResult.EMPTY;let value;return value=this[$richText]?this[$content]?this[$content].replaceAll(crlfForRichTextRegExp,"\n"):void 0:this[$content]||void 0,HTMLResult.success({name:this[$nodeName],attributes:{href:this.href,style:mapStyle(this.style,this,this[$richText])},children:children,value:value})}}class A extends XhtmlObject{constructor(attributes){super(attributes,"a"),this.href=fixURL(attributes.href)||""}}class B extends XhtmlObject{constructor(attributes){super(attributes,"b")}[$pushGlyphs](measure){measure.pushFont({weight:"bold"}),super[$pushGlyphs](measure),measure.popFont()}}class Body extends XhtmlObject{constructor(attributes){super(attributes,"body")}[$toHTML](availableSpace){var availableSpace=super[$toHTML](availableSpace),html=availableSpace["html"];return html?(html.name="div",html.attributes.class=["xfaRich"],availableSpace):HTMLResult.EMPTY}}class Br extends XhtmlObject{constructor(attributes){super(attributes,"br")}[$text](){return"\n"}[$pushGlyphs](measure){measure.addString("\n")}[$toHTML](availableSpace){return HTMLResult.success({name:"br"})}}class Html extends XhtmlObject{constructor(attributes){super(attributes,"html")}[$toHTML](availableSpace){var children=[];if(this[$extra]={children:children},this[$childrenToHTML]({}),0===children.length)return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},value:this[$content]||""});if(1===children.length){var child=children[0];if(child.attributes?.class.includes("xfaRich"))return HTMLResult.success(child)}return HTMLResult.success({name:"div",attributes:{class:["xfaRich"],style:{}},children:children})}}class I extends XhtmlObject{constructor(attributes){super(attributes,"i")}[$pushGlyphs](measure){measure.pushFont({posture:"italic"}),super[$pushGlyphs](measure),measure.popFont()}}class Li extends XhtmlObject{constructor(attributes){super(attributes,"li")}}class Ol extends XhtmlObject{constructor(attributes){super(attributes,"ol")}}class P extends XhtmlObject{constructor(attributes){super(attributes,"p")}[$pushGlyphs](measure){super[$pushGlyphs](measure,!1),measure.addString("\n"),measure.addPara(),measure.popFont()}[$text](){return this[$getParent]()[$getChildren]().at(-1)===this?super[$text]():super[$text]()+"\n"}}class Span extends XhtmlObject{constructor(attributes){super(attributes,"span")}}class Sub extends XhtmlObject{constructor(attributes){super(attributes,"sub")}}class Sup extends XhtmlObject{constructor(attributes){super(attributes,"sup")}}class Ul extends XhtmlObject{constructor(attributes){super(attributes,"ul")}}class XhtmlNamespace{static[$buildXFAObject](name,attributes){if(XhtmlNamespace.hasOwnProperty(name))return XhtmlNamespace[name](attributes)}static a(attributes){return new A(attributes)}static b(attributes){return new B(attributes)}static body(attributes){return new Body(attributes)}static br(attributes){return new Br(attributes)}static html(attributes){return new Html(attributes)}static i(attributes){return new I(attributes)}static li(attributes){return new Li(attributes)}static ol(attributes){return new Ol(attributes)}static p(attributes){return new P(attributes)}static span(attributes){return new Span(attributes)}static sub(attributes){return new Sub(attributes)}static sup(attributes){return new Sup(attributes)}static ul(attributes){return new Ul(attributes)}}const NamespaceSetUp={config:ConfigNamespace,connection:ConnectionSetNamespace,datasets:DatasetsNamespace,localeSet:LocaleSetNamespace,signature:SignatureNamespace,stylesheet:StylesheetNamespace,template:TemplateNamespace,xdp:XdpNamespace,xhtml:XhtmlNamespace};class UnknownNamespace{constructor(nsId){this.namespaceId=nsId}[$buildXFAObject](name,attributes){return new XmlObject(this.namespaceId,name,attributes)}}class Root extends XFAObject{constructor(ids){super(-1,"root",Object.create(null)),this.element=null,this[$ids]=ids}[$onChild](child){return this.element=child,!0}[$finalize](){super[$finalize](),this.element.template instanceof Template&&(this[$ids].set($root,this.element),this.element.template[$resolvePrototypes](this[$ids]),this.element.template[$ids]=this[$ids])}}class Empty extends XFAObject{constructor(){super(-1,"",Object.create(null))}[$onChild](_){return!1}}class Builder{constructor(rootNameSpace=null){this._namespaceStack=[],this._nsAgnosticLevel=0,this._namespacePrefixes=new Map,this._namespaces=new Map,this._nextNsId=Math.max(...Object.values(NamespaceIds).map(({id})=>id)),this._currentNamespace=rootNameSpace||new UnknownNamespace(++this._nextNsId)}buildRoot(ids){return new Root(ids)}build({nsPrefix,name,attributes,namespace,prefixes}){var hasNamespaceDef=null!==namespace;if(hasNamespaceDef&&(this._namespaceStack.push(this._currentNamespace),this._currentNamespace=this._searchNamespace(namespace)),prefixes&&this._addNamespacePrefix(prefixes),attributes.hasOwnProperty($nsAttributes)){var ns,attrs,dataTemplate=NamespaceSetUp.datasets,namespace=attributes[$nsAttributes];let xfaAttrs=null;for([ns,attrs]of Object.entries(namespace))if(this._getNamespaceToUse(ns)===dataTemplate){xfaAttrs={xfa:attrs};break}xfaAttrs?attributes[$nsAttributes]=xfaAttrs:delete attributes[$nsAttributes]}namespace=this._getNamespaceToUse(nsPrefix)?.[$buildXFAObject](name,attributes)||new Empty;return namespace[$isNsAgnostic]()&&this._nsAgnosticLevel++,(hasNamespaceDef||prefixes||namespace[$isNsAgnostic]())&&(namespace[$cleanup]={hasNamespace:hasNamespaceDef,prefixes:prefixes,nsAgnostic:namespace[$isNsAgnostic]()}),namespace}isNsAgnostic(){return 0{this._namespacePrefixes.get(prefix).pop()}),nsAgnostic&&this._nsAgnosticLevel--}}class XFAParser extends XMLParserBase{constructor(rootNameSpace=null,richText=!1){super(),this._builder=new Builder(rootNameSpace),this._stack=[],this._globalData={usedTypefaces:new Set},this._ids=new Map,this._current=this._builder.buildRoot(this._ids),this._errorCode=XMLParserErrorCode.NoError,this._whiteRegex=/^\s+$/,this._nbsps=/\xa0+/g,this._richText=richText}parse(data){if(this.parseXml(data),this._errorCode===XMLParserErrorCode.NoError)return this._current[$finalize](),this._current.element}onText(text){text=text.replace(this._nbsps,match=>match.slice(1)+" "),this._richText||this._current[$acceptWhitespace]()?this._current[$onText](text,this._richText):this._whiteRegex.test(text)||this._current[$onText](text.trim())}onCdata(text){this._current[$onText](text)}_mkAttributes(attributes,tagName){let namespace=null,prefixes=null;var name,value,attributeObj=Object.create({});for({name,value}of attributes)if("xmlns"===name)namespace?warn(`XFA - multiple namespace definition in <${tagName}>`):namespace=value;else if(name.startsWith("xmlns:")){var prefix=name.substring("xmlns:".length);(prefixes=prefixes||[]).push({prefix:prefix,value:value})}else{prefix=name.indexOf(":");if(-1===prefix)attributeObj[name]=value;else{let nsAttrs=attributeObj[$nsAttributes];nsAttrs=nsAttrs||(attributeObj[$nsAttributes]=Object.create(null));var[ns,attrName]=[name.slice(0,prefix),name.slice(prefix+1)];(nsAttrs[ns]||=Object.create(null))[attrName]=value}}return[namespace,prefixes,attributeObj]}_getNameAndPrefix(name,nsAgnostic){var i=name.indexOf(":");return-1===i?[name,null]:[name.substring(i+1),nsAgnostic?"":name.substring(0,i)]}onBeginElement(tagName,attributes,isEmpty){var[attributes,prefixes,attributesObj]=this._mkAttributes(attributes,tagName),[tagName,nsPrefix]=this._getNameAndPrefix(tagName,this._builder.isNsAgnostic()),nsPrefix=this._builder.build({nsPrefix:nsPrefix,name:tagName,attributes:attributesObj,namespace:attributes,prefixes:prefixes});nsPrefix[$globalData]=this._globalData,isEmpty?(nsPrefix[$finalize](),this._current[$onChild](nsPrefix)&&nsPrefix[$setId](this._ids),nsPrefix[$clean](this._builder)):(this._stack.push(this._current),this._current=nsPrefix)}onEndElement(name){var parser,node=this._current;node[$isCDATAXml]()&&"string"==typeof node[$content]&&((parser=new XFAParser)._globalData=this._globalData,parser=parser.parse(node[$content]),node[$content]=null,node[$onChild](parser)),node[$finalize](),this._current=this._stack.pop(),this._current[$onChild](node)&&node[$setId](this._ids),node[$clean](this._builder)}onError(code){this._errorCode=code}}class XFAFactory{constructor(data){try{this.root=(new XFAParser).parse(XFAFactory._createDocument(data));var binder=new Binder(this.root);this.form=binder.bind(),this.dataHandler=new DataHandler(this.root,binder.getData()),this.form[$globalData].template=this.form}catch(e){warn("XFA - an error occurred during parsing and binding: "+e)}}isValid(){return this.root&&this.form}_createPagesHelper(){const iterator=this.form[$toPages]();return new Promise((resolve,reject)=>{const nextIteration=()=>{try{var value=iterator.next();value.done?resolve(value.value):setTimeout(nextIteration,0)}catch(e){reject(e)}};setTimeout(nextIteration,0)})}async _createPages(){try{this.pages=await this._createPagesHelper(),this.dims=this.pages.children.map(c=>{var{width:c,height}=c.attributes.style;return[0,0,parseInt(c),parseInt(height)]})}catch(e){warn("XFA - an error occurred during layout: "+e)}}getBoundingBox(pageIndex){return this.dims[pageIndex]}async getNumPages(){return this.pages||await this._createPages(),this.dims.length}setImages(images){this.form[$globalData].images=images}setFonts(fonts){this.form[$globalData].fontFinder=new FontFinder(fonts);var typeface,missingFonts=[];for(typeface of this.form[$globalData].usedTypefaces)typeface=stripQuotes(typeface),this.form[$globalData].fontFinder.find(typeface)||missingFonts.push(typeface);return 0!attr.startsWith("xfa"))),attributes.dir="auto"),{html:html,str:root[$text]()}):null}catch(e){warn("XFA - an error occurred during parsing of rich text: "+e)}return null}}class AnnotationFactory{static createGlobals(pdfManager){return Promise.all([pdfManager.ensureCatalog("acroForm"),pdfManager.ensureDoc("xfaDatasets"),pdfManager.ensureCatalog("structTreeRoot"),pdfManager.ensureCatalog("baseUrl"),pdfManager.ensureCatalog("attachments")]).then(([acroForm,xfaDatasets,structTreeRoot,baseUrl,attachments])=>({pdfManager:pdfManager,acroForm:acroForm instanceof Dict?acroForm:Dict.empty,xfaDatasets:xfaDatasets,structTreeRoot:structTreeRoot,baseUrl:baseUrl,attachments:attachments}),reason=>(warn(`createGlobals: "${reason}".`),null))}static async create(xref,ref,annotationGlobals,idFactory,collectFields,pageRef){var pageIndex=collectFields?await this._getPageIndex(xref,ref,annotationGlobals.pdfManager):null;return annotationGlobals.pdfManager.ensure(this,"_create",[xref,ref,annotationGlobals,idFactory,collectFields,pageIndex,pageRef])}static _create(xref,ref,annotationGlobals,idFactory,collectFields=!1,pageIndex=null,pageRef=null){var dict=xref.fetchIfRef(ref);if(dict instanceof Dict){var{acroForm,pdfManager}=annotationGlobals,idFactory=ref instanceof Ref?ref.toString():"annot_"+idFactory.createObjId(),subtype=dict.get("Subtype"),parameters={xref:xref,ref:ref,dict:dict,subtype:subtype=subtype instanceof Name?subtype.name:null,id:idFactory,annotationGlobals:annotationGlobals,collectFields:collectFields,needAppearances:!collectFields&&!0===acroForm.get("NeedAppearances"),pageIndex:pageIndex,evaluatorOptions:pdfManager.evaluatorOptions,pageRef:pageRef};switch(subtype){case"Link":return new LinkAnnotation(parameters);case"Text":return new TextAnnotation(parameters);case"Widget":var fieldType=getInheritableProperty({dict:dict,key:"FT"});switch(fieldType=fieldType instanceof Name?fieldType.name:null){case"Tx":return new TextWidgetAnnotation(parameters);case"Btn":return new ButtonWidgetAnnotation(parameters);case"Ch":return new ChoiceWidgetAnnotation(parameters);case"Sig":return new SignatureWidgetAnnotation(parameters)}return warn(`Unimplemented widget field type "${fieldType}", `+"falling back to base field type."),new WidgetAnnotation(parameters);case"Popup":return new PopupAnnotation(parameters);case"FreeText":return new FreeTextAnnotation(parameters);case"Line":return new LineAnnotation(parameters);case"Square":return new SquareAnnotation(parameters);case"Circle":return new CircleAnnotation(parameters);case"PolyLine":return new PolylineAnnotation(parameters);case"Polygon":return new PolygonAnnotation(parameters);case"Caret":return new CaretAnnotation(parameters);case"Ink":return new InkAnnotation(parameters);case"Highlight":return new HighlightAnnotation(parameters);case"Underline":return new UnderlineAnnotation(parameters);case"Squiggly":return new SquigglyAnnotation(parameters);case"StrikeOut":return new StrikeOutAnnotation(parameters);case"Stamp":return new StampAnnotation(parameters);case"FileAttachment":return new FileAttachmentAnnotation(parameters);default:return collectFields||warn(subtype?`Unimplemented annotation type "${subtype}", `+"falling back to base annotation.":"Annotation is missing the required /Subtype."),new Annotation(parameters)}}}static async _getPageIndex(xref,ref,pdfManager){try{var annotDict=await xref.fetchIfRefAsync(ref);if(!(annotDict instanceof Dict))return-1;var pageRef=annotDict.getRaw("P");if(pageRef instanceof Ref)try{return await pdfManager.ensureCatalog("getPageIndex",[pageRef])}catch(ex){info(`_getPageIndex -- not a valid page reference: "${ex}".`)}if(annotDict.has("Kids"))return-1;var numPages=await pdfManager.ensureDoc("numPages");for(let pageIndex=0;pageIndexc/255)}function getQuadPoints(dict,rect){var quadPoints=dict.getArray("QuadPoints");if(!Array.isArray(quadPoints)||0===quadPoints.length||0rect[2]||minYrect[3]))return null;quadPointsLists.push([{x:minX,y:maxY},{x:maxX,y:maxY},{x:minX,y:minY},{x:maxX,y:minY}])}return quadPointsLists}function getTransformMatrix(rect,bbox,matrix){var[bbox,matrix,maxX,maxY]=Util.getAxialAlignedBoundingBox(bbox,matrix);return bbox===maxX||matrix===maxY?[1,0,0,1,rect[0],rect[1]]:[maxX=(rect[2]-rect[0])/(maxX-bbox),0,0,maxY=(rect[3]-rect[1])/(maxY-matrix),rect[0]-bbox*maxX,rect[1]-matrix*maxY]}class Annotation{constructor(params){var structParent,{dict,xref,annotationGlobals}=params,MK=(this.setTitle(dict.get("T")),this.setContents(dict.get("Contents")),this.setModificationDate(dict.get("M")),this.setFlags(dict.get("F")),this.setRectangle(dict.getArray("Rect")),this.setColor(dict.getArray("C")),this.setBorderStyle(dict),this.setAppearance(dict),this.setOptionalContent(dict),dict.get("MK")),MK=(this.setBorderAndBackgroundColors(MK),this.setRotation(MK,dict),this.ref=params.ref instanceof Ref?params.ref:null,this._streams=[],this.appearance&&this._streams.push(this.appearance),!!(this.flags&AnnotationFlag.LOCKED)),isContentLocked=!!(this.flags&AnnotationFlag.LOCKEDCONTENTS);if(annotationGlobals.structTreeRoot&&(structParent=dict.get("StructParent"),structParent=Number.isInteger(structParent)&&0<=structParent?structParent:-1,annotationGlobals.structTreeRoot.addAnnotationIdToPage(params.pageRef,structParent)),this.data={annotationFlags:this.flags,borderStyle:this.borderStyle,color:this.color,backgroundColor:this.backgroundColor,borderColor:this.borderColor,rotation:this.rotation,contentsObj:this._contents,hasAppearance:!!this.appearance,id:params.id,modificationDate:this.modificationDate,rect:this.rectangle,subtype:params.subtype,hasOwnCanvas:!1,noRotate:!!(this.flags&AnnotationFlag.NOROTATE),noHTML:MK&&isContentLocked},params.collectFields){annotationGlobals=dict.get("Kids");if(Array.isArray(annotationGlobals)){var kidIds=[];for(const kid of annotationGlobals)kid instanceof Ref&&kidIds.push(kid.toString());0!==kidIds.length&&(this.data.kidIds=kidIds)}this.data.actions=collectActions(xref,dict,AnnotationActionEventType),this.data.fieldName=this._constructFieldName(dict),this.data.pageIndex=params.pageIndex}this._isOffscreenCanvasSupported=params.evaluatorOptions.isOffscreenCanvasSupported,this._fallbackFontDict=null,this._needAppearances=!1}_hasFlag(flags,flag){return!!(flags&flag)}_isViewable(flags){return!this._hasFlag(flags,AnnotationFlag.INVISIBLE)&&!this._hasFlag(flags,AnnotationFlag.NOVIEW)}_isPrintable(flags){return this._hasFlag(flags,AnnotationFlag.PRINT)&&!this._hasFlag(flags,AnnotationFlag.HIDDEN)&&!this._hasFlag(flags,AnnotationFlag.INVISIBLE)}mustBeViewed(annotationStorage,_renderForms){annotationStorage=annotationStorage?.get(this.data.id)?.noView;return void 0!==annotationStorage?!annotationStorage:this.viewable&&!this._hasFlag(this.flags,AnnotationFlag.HIDDEN)}mustBePrinted(annotationStorage){annotationStorage=annotationStorage?.get(this.data.id)?.noPrint;return void 0!==annotationStorage?!annotationStorage:this.printable}get viewable(){return null!==this.data.quadPoints&&(0===this.flags||this._isViewable(this.flags))}get printable(){return null!==this.data.quadPoints&&0!==this.flags&&this._isPrintable(this.flags)}_parseStringHelper(data){data="string"==typeof data?stringToPDFString(data):"";return{str:data,dir:data&&"rtl"===bidi(data).dir?"rtl":"ltr"}}setDefaultAppearance(params){var{dict:params,annotationGlobals}=params,params=getInheritableProperty({dict:params,key:"DA"})||annotationGlobals.acroForm.get("DA");this._defaultAppearance="string"==typeof params?params:"",this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance)}setTitle(title){this._title=this._parseStringHelper(title)}setContents(contents){this._contents=this._parseStringHelper(contents)}setModificationDate(modificationDate){this.modificationDate="string"==typeof modificationDate?modificationDate:null}setFlags(flags){this.flags=Number.isInteger(flags)&&0{if(resources)return new ObjectLoader(resources,keys,resources.xref).load().then(function(){return resources})})}async getOperatorList(evaluator,task,intent,renderForms,annotationStorage){var{hasOwnCanvas,id,rect}=this.data;let appearance=this.appearance;hasOwnCanvas=!!(hasOwnCanvas&&intent&RenderingIntentFlag.DISPLAY);if(hasOwnCanvas&&(rect[0]===rect[2]||rect[1]===rect[3]))return this.data.hasOwnCanvas=!1,{opList:new OperatorList,separateForm:!1,separateCanvas:!1};if(!appearance){if(!hasOwnCanvas)return{opList:new OperatorList,separateForm:!1,separateCanvas:!1};(appearance=new StringStream("")).dict=new Dict}var intent=appearance.dict,resources=await this.loadResources(["ExtGState","ColorSpace","Pattern","Shading","XObject","Font"],appearance),bbox=intent.getArray("BBox")||[0,0,1,1],intent=intent.getArray("Matrix")||[1,0,0,1,0,0],bbox=getTransformMatrix(rect,bbox,intent),opList=new OperatorList;let optionalContent;return void 0!==(optionalContent=this.oc?await evaluator.parseMarkedContentProps(this.oc,null):optionalContent)&&opList.addOp(OPS.beginMarkedContentProps,["OC",optionalContent]),opList.addOp(OPS.beginAnnotation,[id,rect,bbox,intent,hasOwnCanvas]),await evaluator.getOperatorList({stream:appearance,task:task,resources:resources,operatorList:opList,fallbackFontDict:this._fallbackFontDict}),opList.addOp(OPS.endAnnotation,[]),void 0!==optionalContent&&opList.addOp(OPS.endMarkedContent,[]),this.reset(),{opList:opList,separateForm:!1,separateCanvas:hasOwnCanvas}}async save(evaluator,task,annotationStorage){return null}get hasTextContent(){return!1}async extractTextContent(evaluator,task,viewBox){if(this.appearance){var resources=await this.loadResources(["ExtGState","Font","Properties","XObject"],this.appearance);const text=[],buffer=[];let firstPosition=null;var sink={desiredSize:Math.Infinity,ready:!0,enqueue(chunk,size){for(const item of chunk.items)void 0!==item.str&&(firstPosition||=item.transform.slice(-2),buffer.push(item.str),item.hasEOL)&&(text.push(buffer.join("").trimEnd()),buffer.length=0)}};await evaluator.getTextContent({stream:this.appearance,task:task,resources:resources,includeMarkedContent:!0,keepWhiteSpace:!0,sink:sink,viewBox:viewBox}),this.reset(),buffer.length&&text.push(buffer.join("").trimEnd()),(1"string"==typeof item).map(item=>stringToPDFString(item)):formValue instanceof Name?stringToPDFString(formValue.name):"string"==typeof formValue?stringToPDFString(formValue):null}hasFieldFlag(flag){return!!(this.data.fieldFlags&flag)}_isViewable(flags){return!0}mustBeViewed(annotationStorage,renderForms){return renderForms?this.viewable:super.mustBeViewed(annotationStorage,renderForms)&&!this._hasFlag(this.flags,AnnotationFlag.NOVIEW)}getRotationMatrix(annotationStorage){let rotation=annotationStorage?.get(this.data.id)?.rotation;var height;return 0===(rotation=void 0===rotation?this.rotation:rotation)?IDENTITY_MATRIX:(annotationStorage=this.data.rect[2]-this.data.rect[0],height=this.data.rect[3]-this.data.rect[1],getRotationMatrix(rotation,annotationStorage,height))}getBorderAndBackgroundAppearances(annotationStorage){let rotation=annotationStorage?.get(this.data.id)?.rotation;if(void 0===rotation&&(rotation=this.rotation),!this.backgroundColor&&!this.borderColor)return"";var annotationStorage=this.data.rect[2]-this.data.rect[0],height=this.data.rect[3]-this.data.rect[1],height=0===rotation||180===rotation?`0 0 ${annotationStorage} ${height} re`:`0 0 ${height} ${annotationStorage} re`;let str="";return this.backgroundColor&&(str=getPdfColor(this.backgroundColor,!0)+` ${height} f `),this.borderColor&&(annotationStorage=this.borderStyle.width||1,str+=`${annotationStorage} w ${getPdfColor(this.borderColor,!1)} ${height} S `),str}async getOperatorList(evaluator,task,intent,renderForms,annotationStorage){if(renderForms&&!(this instanceof SignatureWidgetAnnotation)&&!this.data.noHTML&&!this.data.hasOwnCanvas)return{opList:new OperatorList,separateForm:!0,separateCanvas:!1};if(!this._hasText)return super.getOperatorList(evaluator,task,intent,renderForms,annotationStorage);var content=await this._getAppearance(evaluator,task,intent,annotationStorage);if(this.appearance&&null===content)return super.getOperatorList(evaluator,task,intent,renderForms,annotationStorage);renderForms=new OperatorList;if(!this._defaultAppearance||null===content)return{opList:renderForms,separateForm:!1,separateCanvas:!1};var intent=!!(this.data.hasOwnCanvas&&intent&RenderingIntentFlag.DISPLAY),bbox=[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]],bbox=getTransformMatrix(this.data.rect,bbox,[1,0,0,1,0,0]);let optionalContent;void 0!==(optionalContent=this.oc?await evaluator.parseMarkedContentProps(this.oc,null):optionalContent)&&renderForms.addOp(OPS.beginMarkedContentProps,["OC",optionalContent]),renderForms.addOp(OPS.beginAnnotation,[this.data.id,this.data.rect,bbox,this.getRotationMatrix(annotationStorage),intent]);bbox=new StringStream(content);return await evaluator.getOperatorList({stream:bbox,task:task,resources:this._fieldResources.mergedResources,operatorList:renderForms}),renderForms.addOp(OPS.endAnnotation,[]),void 0!==optionalContent&&renderForms.addOp(OPS.endMarkedContent,[]),{opList:renderForms,separateForm:!1,separateCanvas:intent}}_getMKDict(rotation){var mk=new Dict(null);return rotation&&mk.set("R",rotation),this.borderColor&&mk.set("BC",getPdfColorArray(this.borderColor)),this.backgroundColor&&mk.set("BG",getPdfColorArray(this.backgroundColor)),0x===this.data.fieldValue[i]))return null;void 0===rotation&&(rotation=this.rotation);let appearance=null;if(!this._needAppearances&&null===(appearance=await this._getAppearance(evaluator,task,RenderingIntentFlag.SAVE,annotationStorage)))return null;let needAppearances=!1;appearance?.needAppearances&&(needAppearances=!0,appearance=null);var storageEntry=evaluator["xref"],originalDict=storageEntry.fetchIfRef(this.ref);if(!(originalDict instanceof Dict))return null;var dict=new Dict(storageEntry);for(const key of originalDict.getKeys())"AP"!==key&&dict.set(key,originalDict.getRaw(key));var newRef,appearanceStream,appearanceDict,AP,task={path:this.data.fieldName,value:value},evaluator=val=>isAscii(val)?val:stringToUTF16String(val,!0),evaluator=(dict.set("V",Array.isArray(value)?value.map(evaluator):evaluator(value)),this.amendSavedDict(annotationStorage,dict),this._getMKDict(rotation)),evaluator=(evaluator&&dict.set("MK",evaluator),[]),task=[{ref:this.ref,data:"",xfa:task,needAppearances:needAppearances}];return null!==appearance&&(newRef=storageEntry.getNewTemporaryRef(),AP=new Dict(storageEntry),dict.set("AP",AP),AP.set("N",newRef),AP=this._getSaveFieldResources(storageEntry),(appearanceDict=(appearanceStream=new StringStream(appearance)).dict=new Dict(storageEntry)).set("Subtype",Name.get("Form")),appearanceDict.set("Resources",AP),appearanceDict.set("BBox",[0,0,this.data.rect[2]-this.data.rect[0],this.data.rect[3]-this.data.rect[1]]),(AP=this.getRotationMatrix(annotationStorage))!==IDENTITY_MATRIX&&appearanceDict.set("Matrix",AP),await writeObject(newRef,appearanceStream,evaluator,storageEntry),task.push({ref:newRef,data:evaluator.join(""),xfa:null,needAppearances:!1}),evaluator.length=0),dict.set("M","D:"+getModificationDate()),await writeObject(this.ref,dict,evaluator,storageEntry),task[0].data=evaluator.join(""),task}async _getAppearance(evaluator,task,intent,annotationStorage){if(this.hasFieldFlag(AnnotationFieldFlag.PASSWORD))return null;var storageEntry=annotationStorage?.get(this.data.id);let value,rotation;if(storageEntry&&(value=storageEntry.formattedValue||storageEntry.value,rotation=storageEntry.rotation),void 0===rotation&&void 0===value&&!this._needAppearances&&(!this._hasValueFromXFA||this.appearance))return null;storageEntry=this.getBorderAndBackgroundAppearances(annotationStorage);if(void 0===value&&!(value=this.data.fieldValue))return`/Tx BMC q ${storageEntry}Q EMC`;if(assert("string"==typeof(value=Array.isArray(value)&&1===value.length?value[0]:value),"Expected `value` to be a string."),value=value.trim(),this.data.combo&&(option=this.data.options.find(({exportValue})=>value===exportValue),value=option?.displayValue||value),""===value)return`/Tx BMC q ${storageEntry}Q EMC`;void 0===rotation&&(rotation=this.rotation);let lineCount=-1,lines;this.data.multiLine?(lines=value.split(/\r\n?|\n/).map(line=>line.normalize("NFC")),lineCount=lines.length):lines=[value.replace(/\r\n?|\n/,"").normalize("NFC")];let totalHeight=this.data.rect[3]-this.data.rect[1],totalWidth=this.data.rect[2]-this.data.rect[0],font=(90!==rotation&&270!==rotation||([totalWidth,totalHeight]=[totalHeight,totalWidth]),this._defaultAppearance||(this.data.defaultAppearanceData=parseDefaultAppearance(this._defaultAppearance="/Helvetica 0 Tf 0 g")),await WidgetAnnotation._getFontData(evaluator,task,this.data.defaultAppearanceData,this._fieldResources.mergedResources)),defaultAppearance,fontSize,lineHeight;var encodedLines=[];let encodingError=!1;for(const line of lines){var encodedString=font.encodeString(line);1width+glyph.width,0)/1e3}_computeFontSize(height,width,text,font,lineCount){let fontSize=this.data.defaultAppearanceData["fontSize"],lineHeight=(fontSize||12)*LINE_FACTOR,numberOfLines=Math.round(height/lineHeight);if(!fontSize){var roundWithTwoDigits=x=>Math.floor(100*x)/100;if(-1===lineCount){var textWidth=this._getTextWidth(text,font);fontSize=roundWithTwoDigits(Math.min(height/LINE_FACTOR,width{let totalHeight=0;for(const cache of cachedLines){var chunks=this._splitLine(null,font,fsize,width,cache);if((totalHeight+=chunks.length*fsize)>height)return!0}return!1};for(numberOfLines=Math.max(numberOfLines,lineCount);;){if(lineHeight=height/numberOfLines,!isTooBig(fontSize=roundWithTwoDigits(lineHeight/LINE_FACTOR)))break;numberOfLines++}}var{fontName:text,fontColor:textWidth}=this.data.defaultAppearanceData;this._defaultAppearance=createDefaultAppearance({fontSize:fontSize,fontName:text,fontColor:textWidth})}return[this._defaultAppearance,fontSize,height/numberOfLines]}_renderText(text,font,fontSize,totalWidth,alignment,prevInfo,hPadding,vPadding){let shift;if(1===alignment){var width=this._getTextWidth(text,font)*fontSize;shift=(totalWidth-width)/2}else if(2===alignment){const width=this._getTextWidth(text,font)*fontSize;shift=totalWidth-width-hPadding}else shift=hPadding;width=numberToString(shift-prevInfo.shift);return prevInfo.shift=shift,`${width} ${vPadding=numberToString(vPadding)} Td (${escapeString(text)}) Tj`}_getSaveFieldResources(xref){var{localResources,appearanceResources,acroFormResources}=this._fieldResources,fontName=this.data.defaultAppearanceData?.fontName;if(fontName){for(const resources of[localResources,appearanceResources])if(resources instanceof Dict){var localFont=resources.get("Font");if(localFont instanceof Dict&&localFont.has(fontName))return resources}if(acroFormResources instanceof Dict){var appearanceResources=acroFormResources.get("Font");if(appearanceResources instanceof Dict&&appearanceResources.has(fontName))return(acroFormResources=new Dict(xref)).set(fontName,appearanceResources.getRaw(fontName)),(appearanceResources=new Dict(xref)).set("Font",acroFormResources),Dict.merge({xref:xref,dictArray:[appearanceResources,localResources],mergeSubDicts:!0})}}return localResources||Dict.empty}getFieldObject(){return null}}class TextWidgetAnnotation extends WidgetAnnotation{constructor(params){super(params),this.data.hasOwnCanvas=this.data.readOnly&&!this.data.noHTML,this._hasText=!0;params=params.dict;"string"!=typeof this.data.fieldValue&&(this.data.fieldValue="");let alignment=getInheritableProperty({dict:params,key:"Q"}),maximumLength=((!Number.isInteger(alignment)||alignment<0||2width?(chunks.push(line.substring(startChunk,start)),startChunk=start,currentWidth=glyphWidth,lastSpacePosInStringStart=-1):(currentWidth+=glyphWidth,lastSpacePosInStringStart=start,lastSpacePosInStringEnd=end,i):currentWidth+glyphWidth>width?currentWidth=-1!==lastSpacePosInStringStart?(chunks.push(line.substring(startChunk,lastSpacePosInStringEnd)),startChunk=lastSpacePosInStringEnd,i=lastSpacePos+1,lastSpacePosInStringStart=-1,0):(chunks.push(line.substring(startChunk,start)),startChunk=start,glyphWidth):currentWidth+=glyphWidth}return startChunk"Off"!==v),exportValues.length=0,exportValues.push("Off",asValue)),exportValues.includes(this.data.fieldValue)||(this.data.fieldValue="Off"),this.data.exportValue=exportValues[1],asValue=customAppearance.get(this.data.exportValue),this.checkedAppearance=asValue instanceof BaseStream?asValue:null,exportValues=customAppearance.get("Off"),this.uncheckedAppearance=exportValues instanceof BaseStream?exportValues:null,this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(params,"check"),this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance),this._fallbackFontDict=this.fallbackFontDict,null===this.data.defaultFieldValue)&&(this.data.defaultFieldValue="Off")}_processRadioButton(params){this.data.buttonValue=null;var fieldParent=params.dict.get("Parent"),fieldParent=(fieldParent instanceof Dict&&(this.parent=params.dict.getRaw("Parent"),(fieldParent=fieldParent.get("V"))instanceof Name)&&(this.data.fieldValue=this._decodeFormValue(fieldParent)),params.dict.get("AP"));if(fieldParent instanceof Dict){fieldParent=fieldParent.get("N");if(fieldParent instanceof Dict){for(const key of fieldParent.getKeys())if("Off"!==key){this.data.buttonValue=this._decodeFormValue(key);break}var checkedAppearance=fieldParent.get(this.data.buttonValue),checkedAppearance=(this.checkedAppearance=checkedAppearance instanceof BaseStream?checkedAppearance:null,fieldParent.get("Off"));this.uncheckedAppearance=checkedAppearance instanceof BaseStream?checkedAppearance:null,this.checkedAppearance?this._streams.push(this.checkedAppearance):this._getDefaultCheckedAppearance(params,"disc"),this.uncheckedAppearance&&this._streams.push(this.uncheckedAppearance),this._fallbackFontDict=this.fallbackFontDict,null===this.data.defaultFieldValue&&(this.data.defaultFieldValue="Off")}}}_processPushButton(params){var{dict:params,annotationGlobals}=params;params.has("A")||params.has("AA")||this.data.alternativeText?(this.data.isTooltipOnly=!params.has("A")&&!params.has("AA"),Catalog.parseDestDictionary({destDict:params,resultObj:this.data,docBaseUrl:annotationGlobals.baseUrl,docAttachments:annotationGlobals.attachments})):warn("Push buttons without action dictionaries are not supported")}getFieldObject(){let type="button",exportValues;return this.data.checkBox?(type="checkbox",exportValues=this.data.exportValue):this.data.radioButton&&(type="radiobutton",exportValues=this.data.buttonValue),{id:this.data.id,value:this.data.fieldValue||"Off",defaultValue:this.data.defaultFieldValue,exportValues:exportValues,editable:!this.data.readOnly,name:this.data.fieldName,rect:this.data.rect,hidden:this.data.hidden,actions:this.data.actions,page:this.data.pageIndex,strokeColor:this.data.borderColor,fillColor:this.data.backgroundColor,rotation:this.rotation,type:type}}get fallbackFontDict(){var dict=new Dict;return dict.set("BaseFont",Name.get("ZapfDingbats")),dict.set("Type",Name.get("FallbackType")),dict.set("Subtype",Name.get("FallbackType")),dict.set("Encoding",Name.get("ZapfDingbatsEncoding")),shadow(this,"fallbackFontDict",dict)}}class ChoiceWidgetAnnotation extends WidgetAnnotation{constructor(params){super(params);var{dict:params,xref}=params,options=(this.indices=params.getArray("I"),this.hasIndices=Array.isArray(this.indices)&&0lineWidth&&(lineWidth=width,value=displayValue)}[defaultAppearance,fontSize]=this._computeFontSize(lineHeight,totalWidth-4,value,font,-1)}const lineHeight=fontSize*LINE_FACTOR;var vPadding=(lineHeight-fontSize)/2,annotationStorage=Math.floor(totalHeight/lineHeight);let firstIndex=0;0intent)&&(firstIndex=intent);var end=Math.min(firstIndex+annotationStorage+1,lineCount),buf=["/Tx BMC q",`1 1 ${totalWidth} ${totalHeight} re W n`];if(valueIndices.length){buf.push("0.600006 0.756866 0.854904 rg");for(const index of valueIndices)firstIndex<=index&&indexline.trimEnd()),{coords:evaluatorOptions,bbox,matrix}=FakeUnicodeFont.getFirstPositionInfo(this.rectangle,this.rotation,fontSize),this.data.textPosition=this._transformPoint(evaluatorOptions,bbox,matrix)),this._isOffscreenCanvasSupported?(evaluatorOptions=params.dict.get("CA"),bbox=new FakeUnicodeFont(xref,"sans-serif"),this.appearance=bbox.createAppearance(this._contents.str,this.rectangle,this.rotation,fontSize,fontColor,evaluatorOptions),this._streams.push(this.appearance)):warn("FreeTextAnnotation: OffscreenCanvas is not supported, annotation may not render correctly.")}}get hasTextContent(){return this._hasAppearance}static createNewDict(annotation,xref,{apRef,ap}){var{color:annotation,fontSize,rect,rotation,user,value}=annotation,freetext=new Dict(xref),rect=(freetext.set("Type",Name.get("Annot")),freetext.set("Subtype",Name.get("FreeText")),freetext.set("CreationDate","D:"+getModificationDate()),freetext.set("Rect",rect),`/Helv ${fontSize} Tf `+getPdfColor(annotation,!0));return freetext.set("DA",rect),freetext.set("Contents",isAscii(value)?value:stringToUTF16String(value,!0)),freetext.set("F",4),freetext.set("Border",[0,0,0]),freetext.set("Rotate",rotation),user&&freetext.set("T",isAscii(user)?user:stringToUTF16String(user,!0)),(apRef||ap)&&(fontSize=new Dict(xref),freetext.set("AP",fontSize),apRef?fontSize.set("N",apRef):fontSize.set("N",ap)),freetext}static async createNewAppearanceStream(annotation,xref,params){var{baseFontRef:params,evaluator,task}=params,{color:annotation,fontSize,rect,rotation,value}=annotation,resources=new Dict(xref),font=new Dict(xref),helv=(params?font.set("Helv",params):((params=new Dict(xref)).set("BaseFont",Name.get("Helvetica")),params.set("Type",Name.get("Font")),params.set("Subtype",Name.get("Type1")),params.set("Encoding",Name.get("WinAnsiEncoding")),font.set("Helv",params)),resources.set("Font",font),await WidgetAnnotation._getFontData(evaluator,task,{fontName:"Helv",fontSize:fontSize},resources)),[params,font,evaluator,task]=rect;let w=evaluator-params,h=task-font;rotation%180!=0&&([w,h]=[h,w]);var evaluator=value.split("\n"),scale=fontSize/1e3;let totalWidth=-1/0;var line,encodedLines=[];for(line of evaluator){var encoded=helv.encodeString(line);if(1w&&(hscale=w/totalWidth),1);var params=LINE_FACTOR*fontSize,lineAscent=(LINE_FACTOR-LINE_DESCENT_FACTOR)*fontSize,task=params*evaluator.length,font=(task>h&&(vscale=h/task),Math.min(hscale,vscale)),value=fontSize*font;let firstPoint,clipBox,matrix;switch(rotation){case 0:matrix=[1,0,0,1],clipBox=[rect[0],rect[1],w,h],firstPoint=[rect[0],rect[3]-lineAscent];break;case 90:matrix=[0,1,-1,0],clipBox=[rect[1],-rect[2],w,h],firstPoint=[rect[1],-rect[0]-lineAscent];break;case 180:matrix=[-1,0,0,-1],clipBox=[-rect[2],-rect[3],w,h],firstPoint=[-rect[2],-rect[1]-lineAscent];break;case 270:matrix=[0,-1,1,0],clipBox=[-rect[3],rect[0],w,h],firstPoint=[-rect[3],rect[2]-lineAscent]}var buffer=["q",matrix.join(" ")+" 0 0 cm",clipBox.join(" ")+" re W n","BT",""+getPdfColor(annotation,!0),`0 Tc /Helv ${numberToString(value)} Tf`],vShift=(buffer.push(`${firstPoint.join(" ")} Td (${escapeString(encodedLines[0])}) Tj`),numberToString(params));for(let i=1,ii=encodedLines.length;i(buffer.push(`${lineCoordinates[0]} ${lineCoordinates[1]} m`,`${lineCoordinates[2]} ${lineCoordinates[3]} l`,"S"),[points[0].x-borderWidth,points[1].x+borderWidth,points[3].y-borderWidth,points[1].y+borderWidth])})}}}class SquareAnnotation extends MarkupAnnotation{constructor(params){super(params);var{dict:params,xref}=params;if(this.data.annotationType=AnnotationType.SQUARE,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1,!this.appearance){var strokeColor=this.color?getPdfColorArray(this.color):[0,0,0],strokeAlpha=params.get("CA"),params=getRgbColor(params.getArray("IC"),null);const fillColor=params?getPdfColorArray(params):null;params=fillColor?strokeAlpha:null;0===this.borderStyle.width&&!fillColor||this._setDefaultAppearance({xref:xref,extra:this.borderStyle.width+" w",strokeColor:strokeColor,fillColor:fillColor,strokeAlpha:strokeAlpha,fillAlpha:params,pointsCallback:(buffer,points)=>{var x=points[2].x+this.borderStyle.width/2,y=points[2].y+this.borderStyle.width/2,width=points[3].x-points[2].x-this.borderStyle.width,height=points[1].y-points[3].y-this.borderStyle.width;return buffer.push(x+` ${y} ${width} ${height} re`),fillColor?buffer.push("B"):buffer.push("S"),[points[0].x,points[1].x,points[3].y,points[1].y]}})}}}class CircleAnnotation extends MarkupAnnotation{constructor(params){super(params);var{dict:params,xref}=params;if(this.data.annotationType=AnnotationType.CIRCLE,!this.appearance){var strokeColor=this.color?getPdfColorArray(this.color):[0,0,0],strokeAlpha=params.get("CA"),params=getRgbColor(params.getArray("IC"),null);const fillColor=params?getPdfColorArray(params):null;params=fillColor?strokeAlpha:null;if(0!==this.borderStyle.width||fillColor){const controlPointsDistance=4/3*Math.tan(Math.PI/8);this._setDefaultAppearance({xref:xref,extra:this.borderStyle.width+" w",strokeColor:strokeColor,fillColor:fillColor,strokeAlpha:strokeAlpha,fillAlpha:params,pointsCallback:(buffer,points)=>{var x0=points[0].x+this.borderStyle.width/2,y0=points[0].y-this.borderStyle.width/2,x1=points[3].x-this.borderStyle.width/2,y1=points[3].y+this.borderStyle.width/2,xMid=x0+(x1-x0)/2,yMid=y0+(y1-y0)/2,xOffset=(x1-x0)/2*controlPointsDistance,yOffset=(y1-y0)/2*controlPointsDistance;return buffer.push(xMid+` ${y1} m`,xMid+xOffset+` ${y1} ${x1} ${yMid+yOffset} ${x1} ${yMid} c`,x1+` ${yMid-yOffset} ${xMid+xOffset} ${y0} ${xMid} ${y0} c`,xMid-xOffset+` ${y0} ${x0} ${yMid-yOffset} ${x0} ${yMid} c`,x0+` ${yMid+yOffset} ${xMid-xOffset} ${y1} ${xMid} ${y1} c`,"h"),fillColor?buffer.push("B"):buffer.push("S"),[points[0].x,points[1].x,points[3].y,points[1].y]}})}}}}class PolylineAnnotation extends MarkupAnnotation{constructor(params){super(params);var{dict:params,xref}=params,rawVertices=(this.data.annotationType=AnnotationType.POLYLINE,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1,this.data.vertices=[],this instanceof PolygonAnnotation||(this.setLineEndings(params.getArray("LE")),this.data.lineEndings=this.lineEndings),params.getArray("Vertices"));if(Array.isArray(rawVertices)){for(let i=0,ii=rawVertices.length;i{var vertices=this.data.vertices;for(let i=0,ii=vertices.length;i{for(const inkList of this.data.inkLists){for(let i=0,ii=inkList.length;ip.points)),ink.set("F",4),ink.set("Rotate",rotation),outlines&&ink.set("IT",Name.get("InkHighlight")),new Dict(xref)),paths=(ink.set("BS",rect),rect.set("W",thickness),ink.set("C",Array.from(annotation,c=>c/255)),ink.set("CA",opacity),new Dict(xref));return ink.set("AP",paths),apRef?paths.set("N",apRef):paths.set("N",ap),ink}static async createNewAppearanceStream(annotation,xref,params){if(annotation.outlines)return this.createNewAppearanceStreamForHighlight(annotation,xref,params);var bezier,{color:params,rect:annotation,paths,thickness,opacity}=annotation,appearanceBuffer=[thickness+" w 1 J 1 j",""+getPdfColor(params,!1)],buffer=(1!==opacity&&appearanceBuffer.push("/R0 gs"),[]);for({bezier}of paths){if(buffer.length=0,buffer.push(`${numberToString(bezier[0])} ${numberToString(bezier[1])} m`),2===bezier.length)buffer.push(`${numberToString(bezier[0])} ${numberToString(bezier[1])} l S`);else{for(let i=2,ii=bezier.length;i(buffer.push(`${points[0].x} ${points[0].y} m`,`${points[1].x} ${points[1].y} l`,`${points[3].x} ${points[3].y} l`,`${points[2].x} ${points[2].y} l`,"f"),[points[0].x,points[1].x,points[3].y,points[1].y])}))):this.data.popupRef=null}static createNewDict(annotation,xref,{apRef,ap}){var{color:annotation,opacity,rect,rotation,user,quadPoints}=annotation,highlight=new Dict(xref);return highlight.set("Type",Name.get("Annot")),highlight.set("Subtype",Name.get("Highlight")),highlight.set("CreationDate","D:"+getModificationDate()),highlight.set("Rect",rect),highlight.set("F",4),highlight.set("Border",[0,0,0]),highlight.set("Rotate",rotation),highlight.set("QuadPoints",quadPoints),highlight.set("C",Array.from(annotation,c=>c/255)),highlight.set("CA",opacity),user&&highlight.set("T",isAscii(user)?user:stringToUTF16String(user,!0)),(apRef||ap)&&(rect=new Dict(xref),highlight.set("AP",rect),rect.set("N",apRef||ap)),highlight}static async createNewAppearanceStream(annotation,xref,params){var{color:annotation,rect,outlines,opacity}=annotation,appearanceBuffer=[""+getPdfColor(annotation,!0),"/R0 gs"],buffer=[];for(const outline of outlines){buffer.length=0,buffer.push(`${numberToString(outline[0])} ${numberToString(outline[1])} m`);for(let i=2,ii=outline.length;i(buffer.push(`${points[2].x} ${points[2].y+1.3} m`,`${points[3].x} ${points[3].y+1.3} l`,"S"),[points[0].x,points[1].x,points[3].y,points[1].y])})):this.data.popupRef=null}}class SquigglyAnnotation extends MarkupAnnotation{constructor(params){super(params);var{dict:params,xref}=params,quadPoints=(this.data.annotationType=AnnotationType.SQUIGGLY,this.data.quadPoints=getQuadPoints(params,null));quadPoints?this.appearance||(quadPoints=this.color?getPdfColorArray(this.color):[0,0,0],params=params.get("CA"),this._setDefaultAppearance({xref:xref,extra:"[] 0 d 1 w",strokeColor:quadPoints,strokeAlpha:params,pointsCallback:(buffer,points)=>{var dy=(points[0].y-points[2].y)/6;let shift=dy,x=points[2].x;var y=points[2].y,xEnd=points[3].x;for(buffer.push(`${x} ${y+shift} m`);x+=2,shift=0===shift?dy:0,buffer.push(`${x} ${y+shift} l`),x(buffer.push((points[0].x+points[2].x)/2+" "+(points[0].y+points[2].y)/2+" m",(points[1].x+points[3].x)/2+" "+(points[1].y+points[3].y)/2+" l","S"),[points[0].x,points[1].x,points[3].y,points[1].y])})):this.data.popupRef=null}}class StampAnnotation extends MarkupAnnotation{constructor(params){super(params),this.data.annotationType=AnnotationType.STAMP,this.data.hasOwnCanvas=this.data.noRotate,this.data.noHTML=!1}static async createImage(bitmap,xref){var{width,height}=bitmap,canvas=new OffscreenCanvas(width,height),ctx=canvas.getContext("2d",{alpha:!0}),data=(ctx.drawImage(bitmap,0,0),ctx.getImageData(0,0,width,height).data),buf32=new Uint32Array(data.buffer),data=buf32.some(FeatureTest.isLittleEndian?x=>x>>>24!=255:x=>255!=(255&x)),ctx=(data&&(ctx.fillStyle="white",ctx.fillRect(0,0,width,height),ctx.drawImage(bitmap,0,0)),canvas.convertToBlob({type:"image/jpeg",quality:1}).then(blob=>blob.arrayBuffer())),bitmap=Name.get("XObject"),canvas=Name.get("Image"),image=new Dict(xref);image.set("Type",bitmap),image.set("Subtype",canvas),image.set("BitsPerComponent",8),image.set("ColorSpace",Name.get("DeviceRGB")),image.set("Filter",Name.get("DCTDecode")),image.set("BBox",[0,0,width,height]),image.set("Width",width),image.set("Height",height);let smaskStream=null;if(data){var alphaBuffer=new Uint8Array(buf32.length);if(FeatureTest.isLittleEndian)for(let i=0,ii=buf32.length;i>>24;else for(let i=0,ii=buf32.length;idecodeString(child.textContent)):decodeString(path.textContent):""}}class XRef{#firstXRefStmPos=null;constructor(stream,pdfManager){this.stream=stream,this.pdfManager=pdfManager,this.entries=[],this._xrefStms=new Set,this._cacheMap=new Map,this._pendingRefs=new RefSet,this._newPersistentRefNum=null,this._newTemporaryRefNum=null,this._persistentRefsCache=null}getNewPersistentRef(obj){null===this._newPersistentRefNum&&(this._newPersistentRefNum=this.entries.length||1);var num=this._newPersistentRefNum++;return this._cacheMap.set(num,obj),Ref.get(num,0)}getNewTemporaryRef(){if(null===this._newTemporaryRefNum&&(this._newTemporaryRefNum=this.entries.length||1,this._newPersistentRefNum)){this._persistentRefsCache=new Map;for(let i=this._newTemporaryRefNum;i=length)break;offset++,skipped++}return skipped}var gEndobjRegExp=/\b(endobj|\d+\s+\d+\s+obj|xref|trailer\s*<<)\b/g,gStartxrefRegExp=/\b(startxref|\d+\s+\d+\s+obj)\b/g,objRegExp=/^(\d+)\s+(\d+)\s+obj\b/,trailerBytes=new Uint8Array([116,114,97,105,108,101,114]),startxrefBytes=new Uint8Array([115,116,97,114,116,120,114,101,102]),xrefBytes=new Uint8Array([47,88,82,101,102]),stream=(this.entries.length=0,this._cacheMap.clear(),this.stream),buffer=(stream.pos=0,stream.getBytes()),bufferStr=bytesToString(buffer),length=buffer.length;let position=stream.start;for(var trailers=[],xrefStms=[];position=length)&&(ch=buffer[position])!==LF&&ch!==CR;);else{var token=function(data,offset){let token="",ch=data[offset];for(;ch!==LF&&ch!==CR&&ch!==LT&&!(++offset>=data.length);)token+=String.fromCharCode(ch),ch=data[offset];return token}(buffer,position);if(token.startsWith("xref")&&(4===token.length||/\s/.test(token[4])))position+=skipUntil(buffer,position,trailerBytes),trailers.push(position),position+=skipUntil(buffer,position,startxrefBytes);else if(m=objRegExp.exec(token)){var num=0|m[1],m=0|m[2],startPos=position+token.length;let contentLength,updateEntries=!1;if(this.entries[num]){if(this.entries[num].gen===m)try{new Parser({lexer:new Lexer(stream.makeSubStream(startPos))}).getObj(),updateEntries=!0}catch(ex){ex instanceof ParserEOFException?warn(`indexObjects -- checking object (${token}): "${ex}".`):updateEntries=!0}}else updateEntries=!0;updateEntries&&(this.entries[num]={offset:position-stream.start,gen:m,uncompressed:!0}),gEndobjRegExp.lastIndex=startPos;num=gEndobjRegExp.exec(bufferStr),startPos=(num?(m=gEndobjRegExp.lastIndex+1,contentLength=m-position,"endobj"!==num[1]&&(warn(`indexObjects: Found "${num[1]}" inside of another "obj", `+'caused by missing "endobj" -- trying to recover.'),contentLength-=num[1].length+1)):contentLength=length-position,buffer.subarray(position,position+contentLength)),m=skipUntil(startPos,0,xrefBytes);mcontent instanceof BaseStream?content:Array.isArray(content)?new StreamsSequenceStream(content,this._onSubStreamError.bind(this)):new NullStream)}get xfaData(){return shadow(this,"xfaData",this.xfaFactory?{bbox:this.xfaFactory.getBoundingBox(this.pageIndex)}:null)}#replaceIdByRef(annotations,deletedAnnotations,existingAnnotations){for(const annotation of annotations){var ref;annotation.id&&((ref=Ref.fromString(annotation.id))?annotation.deleted?deletedAnnotations.put(ref,ref):(existingAnnotations?.put(ref),annotation.ref=ref,delete annotation.id):warn("A non-linked annotation cannot be modified: "+annotation.id))}}async saveNewAnnotations(handler,task,annotations,imagePromises){if(this.xfaFactory)throw new Error("XFA: Cannot save new annotations.");handler=new PartialEvaluator({xref:this.xref,handler:handler,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});const deletedAnnotations=new RefSetCache;var ref,existingAnnotations=new RefSet,pageDict=(this.#replaceIdByRef(annotations,deletedAnnotations,existingAnnotations),this.pageDict),annotationsArray=this.annotations.filter(a=>!(a instanceof Ref&&deletedAnnotations.has(a))),handler=await AnnotationFactory.saveNewAnnotations(handler,task,annotations,imagePromises);for({ref}of handler.annotations)ref instanceof Ref&&!existingAnnotations.has(ref)&&annotationsArray.push(ref);var task=pageDict.get("Annots"),annotations=(pageDict.set("Annots",annotationsArray),[]),objects=(await writeObject(this.ref,pageDict,annotations,this.xref),task&&pageDict.set("Annots",task),handler.dependencies);objects.push({ref:this.ref,data:annotations.join("")},...handler.annotations);for(const deletedRef of deletedAnnotations)objects.push({ref:deletedRef,data:null});return objects}save(handler,task,annotationStorage){const partialEvaluator=new PartialEvaluator({xref:this.xref,handler:handler,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});return this._parsedAnnotations.then(function(annotations){var newRefsPromises=[];for(const annotation of annotations)annotation.mustBePrinted(annotationStorage)&&newRefsPromises.push(annotation.save(partialEvaluator,task,annotationStorage).catch(function(reason){return warn("save - ignoring annotation data during "+`"${task.name}" task: "${reason}".`),null}));return Promise.all(newRefsPromises).then(function(newRefs){return newRefs.filter(newRef=>!!newRef)})})}loadResources(keys){return this.resourcesPromise||(this.resourcesPromise=this.pdfManager.ensure(this,"resources")),this.resourcesPromise.then(()=>{return new ObjectLoader(this.resources,keys,this.xref).load()})}getOperatorList({handler,sink,task,intent,cacheKey,annotationStorage=null}){var contentStreamPromise=this.getContentStream(),resourcesPromise=this.loadResources(["ColorSpace","ExtGState","Font","Pattern","Properties","Shading","XObject"]);const partialEvaluator=new PartialEvaluator({xref:this.xref,handler:handler,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions});var newAnnotationsByPage=this.xfaFactory?null:getNewAnnotationsMap(annotationStorage);let deletedAnnotations=null,newAnnotationsPromise=Promise.resolve(null);if(newAnnotationsByPage){const newAnnotations=newAnnotationsByPage.get(this.pageIndex);if(newAnnotations){newAnnotationsByPage=this.pdfManager.ensureDoc("annotationGlobals");let imagePromises;var bitmapId,bitmap,missingBitmaps=new Set;for({bitmapId,bitmap}of newAnnotations)!bitmapId||bitmap||missingBitmaps.has(bitmapId)||missingBitmaps.add(bitmapId);var isOffscreenCanvasSupported=this.evaluatorOptions["isOffscreenCanvasSupported"];if(0annotationGlobals?AnnotationFactory.printNewAnnotations(annotationGlobals,partialEvaluator,task,newAnnotations,imagePromises):null)}}isOffscreenCanvasSupported=Promise.all([contentStreamPromise,resourcesPromise]).then(([contentStream])=>{const opList=new OperatorList(intent,sink);return handler.send("StartRenderPage",{transparency:partialEvaluator.hasBlendModes(this.resources,this.nonBlendModesSet),pageIndex:this.pageIndex,cacheKey:cacheKey}),partialEvaluator.getOperatorList({stream:contentStream,task:task,resources:this.resources,operatorList:opList}).then(function(){return opList})});return Promise.all([isOffscreenCanvasSupported,this._parsedAnnotations,newAnnotationsPromise]).then(function([pageOpList,annotations,newAnnotations]){if(newAnnotations){annotations=annotations.filter(a=>!(a.ref&&deletedAnnotations.has(a.ref)));for(let i=0,ii=newAnnotations.length;ia.ref&&isRefsEqual(a.ref,newAnnotation.refToReplace)))&&(annotations.splice(j,1,newAnnotation),newAnnotations.splice(i--,1),ii--)}annotations=annotations.concat(newAnnotations)}if(0===annotations.length||intent&RenderingIntentFlag.ANNOTATIONS_DISABLE)return pageOpList.flush(!0),{length:pageOpList.totalLength};var renderForms=!!(intent&RenderingIntentFlag.ANNOTATIONS_FORMS),intentAny=!!(intent&RenderingIntentFlag.ANY),intentDisplay=!!(intent&RenderingIntentFlag.DISPLAY),intentPrint=!!(intent&RenderingIntentFlag.PRINT),opListPromises=[];for(const annotation of annotations)(intentAny||intentDisplay&&annotation.mustBeViewed(annotationStorage,renderForms)||intentPrint&&annotation.mustBePrinted(annotationStorage))&&opListPromises.push(annotation.getOperatorList(partialEvaluator,task,intent,renderForms,annotationStorage).catch(function(reason){return warn("getOperatorList - ignoring annotation data during "+`"${task.name}" task: "${reason}".`),{opList:null,separateForm:!1,separateCanvas:!1}}));return Promise.all(opListPromises).then(function(opLists){let form=!1,canvas=!1;for(var{opList,separateForm,separateCanvas}of opLists)pageOpList.addOpList(opList),form||=separateForm,canvas||=separateCanvas;return pageOpList.flush(!0,{form:form,canvas:canvas}),{length:pageOpList.totalLength}})})}extractTextContent({handler,task,includeMarkedContent,disableNormalization,sink}){var contentStreamPromise=this.getContentStream(),resourcesPromise=this.loadResources(["ExtGState","Font","Properties","XObject"]);return Promise.all([contentStreamPromise,resourcesPromise]).then(([contentStream])=>{return new PartialEvaluator({xref:this.xref,handler:handler,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}).getTextContent({stream:contentStream,task:task,resources:this.resources,includeMarkedContent:includeMarkedContent,disableNormalization:disableNormalization,sink:sink,viewBox:this.view})})}async getStructTree(){var structTreeRoot=await this.pdfManager.ensureCatalog("structTreeRoot");return structTreeRoot?(await this._parsedAnnotations,(await this.pdfManager.ensure(this,"_parseStructTree",[structTreeRoot])).serializable):null}_parseStructTree(structTreeRoot){structTreeRoot=new StructTreePage(structTreeRoot,this.pageDict);return structTreeRoot.parse(this.ref),structTreeRoot}async getAnnotationsData(handler,task,intent){var annotations=await this._parsedAnnotations;if(0===annotations.length)return annotations;var annotationsData=[],textContentPromises=[];let partialEvaluator;var intentAny=!!(intent&RenderingIntentFlag.ANY),intentDisplay=!!(intent&RenderingIntentFlag.DISPLAY),intentPrint=!!(intent&RenderingIntentFlag.PRINT);for(const annotation of annotations){var isVisible=intentAny||intentDisplay&&annotation.viewable;(isVisible||intentPrint&&annotation.printable)&&annotationsData.push(annotation.data),annotation.hasTextContent&&isVisible&&(partialEvaluator||=new PartialEvaluator({xref:this.xref,handler:handler,pageIndex:this.pageIndex,idFactory:this._localIdFactory,fontCache:this.fontCache,builtInCMapCache:this.builtInCMapCache,standardFontDataCache:this.standardFontDataCache,globalImageCache:this.globalImageCache,systemFontCache:this.systemFontCache,options:this.evaluatorOptions}),textContentPromises.push(annotation.extractTextContent(partialEvaluator,task,[-1/0,-1/0,1/0,1/0]).catch(function(reason){warn(`getAnnotationsData - ignoring textContent during "${task.name}" task: "${reason}".`)})))}return await Promise.all(textContentPromises),annotationsData}get annotations(){var annots=this._getInheritableProperty("Annots");return shadow(this,"annotations",Array.isArray(annots)?annots:[])}get _parsedAnnotations(){var promise=this.pdfManager.ensure(this,"annotations").then(async annots=>{if(0===annots.length)return annots;var annotationGlobals=await this.pdfManager.ensureDoc("annotationGlobals");if(!annotationGlobals)return[];var annotationPromises=[];for(const annotationRef of annots)annotationPromises.push(AnnotationFactory.create(this.xref,annotationRef,annotationGlobals,this._localIdFactory,!1,this.ref).catch(function(reason){return warn(`_parsedAnnotations: "${reason}".`),null}));var sortedAnnotations=[];let popupAnnotations,widgetAnnotations;for(const annotation of await Promise.all(annotationPromises))annotation&&(annotation instanceof WidgetAnnotation?widgetAnnotations||=[]:annotation instanceof PopupAnnotation?popupAnnotations||=[]:sortedAnnotations).push(annotation);return widgetAnnotations&&sortedAnnotations.push(...widgetAnnotations),popupAnnotations&&sortedAnnotations.push(...popupAnnotations),sortedAnnotations});return shadow(this,"_parsedAnnotations",promise)}get jsActions(){return shadow(this,"jsActions",collectActions(this.xref,this.pageDict,PageActionEventType))}}const PDF_HEADER_SIGNATURE=new Uint8Array([37,80,68,70,45]),STARTXREF_SIGNATURE=new Uint8Array([115,116,97,114,116,120,114,101,102]),ENDOBJ_SIGNATURE=new Uint8Array([101,110,100,111,98,106]),FINGERPRINT_FIRST_BYTES=1024,EMPTY_FINGERPRINT="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";function find(stream,signature,limit=1024,backwards=!1){var signatureLength=signature.length,scanBytes=stream.peekBytes(limit),scanLength=scanBytes.length-signatureLength;if(!(scanLength<=0))if(backwards){var signatureEnd=signatureLength-1;let pos=scanBytes.length-1;for(;pos>=signatureEnd;){let j=0;for(;j=signatureLength)return stream.pos+=pos-signatureEnd,!0;pos--}}else{let pos=0;for(;pos<=scanLength;){let j=0;for(;j=signatureLength)return stream.pos+=pos,!0;pos++}}return!1}class PDFDocument{constructor(pdfManager,stream){if(stream.length<=0)throw new InvalidPDFException("The PDF file is empty, i.e. its size is zero bytes.");this.pdfManager=pdfManager,this.stream=stream,this.xref=new XRef(stream,pdfManager),this._pagePromises=new Map,this._version=null;const idCounters={font:0};this._globalIdFactory=class{static getDocId(){return"g_"+pdfManager.docId}static createFontId(){return"f"+ ++idCounters.font}static createObjId(){unreachable("Abstract method `createObjId` called.")}static getPageObjId(){unreachable("Abstract method `getPageObjId` called.")}}}parse(recoveryMode){this.xref.parse(recoveryMode),this.catalog=new Catalog(this.pdfManager,this.xref)}get linearization(){let linearization=null;try{linearization=Linearization.create(this.stream)}catch(err){if(err instanceof MissingDataException)throw err;info(err)}return shadow(this,"linearization",linearization)}get startXRef(){var stream=this.stream;let startXRef=0;if(this.linearization){if(stream.reset(),find(stream,ENDOBJ_SIGNATURE)){stream.skip(6);let ch=stream.peekByte();for(;isWhiteSpace(ch);)stream.pos++,ch=stream.peekByte();startXRef=stream.pos-stream.start}}else{var startXRefLength=STARTXREF_SIGNATURE.length;let found=!1,pos=stream.end;for(;!found&&0{var isSignature;return(field=this.xref.fetchIfRef(field))instanceof Dict&&(field.has("Kids")?10<++recursionDepth?(warn("_hasOnlyDocumentSignatures: maximum recursion depth reached"),!1):this._hasOnlyDocumentSignatures(field.get("Kids"),recursionDepth):(isSignature=isName(field.get("FT"),"Sig"),field=field.get("Rect"),field=Array.isArray(field)&&field.every(value=>0===value),isSignature&&field))})}get _xfaStreams(){var acroForm=this.catalog.acroForm;if(!acroForm)return null;var data,xfa=acroForm.get("XFA"),entries={"xdp:xdp":"",template:"",datasets:"",config:"",connectionSet:"",localeSet:"",stylesheet:"","/xdp:xdp":""};if(xfa instanceof BaseStream&&!xfa.isEmpty)entries["xdp:xdp"]=xfa;else{if(!Array.isArray(xfa)||0===xfa.length)return null;for(let i=0,ii=xfa.length;i{fonts.set(fontName,font)});var fontName,font,promises=[];for([fontName,font]of fonts){var descriptor=font.get("FontDescriptor");if(descriptor instanceof Dict){let fontFamily=descriptor.get("FontFamily");fontFamily=fontFamily.replaceAll(/[ ]+(\d)/g,"$1");var fontWeight=descriptor.get("FontWeight"),descriptor=-descriptor.get("ItalicAngle"),fontWeight={fontFamily:fontFamily,fontWeight:fontWeight,italicAngle:descriptor};validateCSSFont(fontWeight)&&promises.push(partialEvaluator.handleSetFont(resources,[Name.get(fontName),1],null,operatorList,task,initialState,null,fontWeight).catch(function(reason){return warn(`loadXfaFonts: "${reason}".`),null}))}}await Promise.all(promises);handler=this.xfaFactory.setFonts(pdfFonts);if(handler){options.ignoreErrors=!0,promises.length=0,pdfFonts.length=0;var reallyMissingFonts=new Set;for(const missing of handler)getXfaFontName(missing+"-Regular")||reallyMissingFonts.add(missing);reallyMissingFonts.size&&handler.push("PdfJS-Fallback");for(const missing of handler)if(!reallyMissingFonts.has(missing))for(const fontInfo of[{name:"Regular",fontWeight:400,italicAngle:0},{name:"Bold",fontWeight:700,italicAngle:0},{name:"Italic",fontWeight:400,italicAngle:12},{name:"BoldItalic",fontWeight:700,italicAngle:12}]){var name=missing+"-"+fontInfo.name,dict=getXfaFontDict(name);promises.push(partialEvaluator.handleSetFont(resources,[Name.get(name),1],null,operatorList,task,initialState,dict,{fontFamily:missing,fontWeight:fontInfo.fontWeight,italicAngle:fontInfo.italicAngle}).catch(function(reason){return warn(`loadXfaFonts: "${reason}".`),null}))}await Promise.all(promises),this.xfaFactory.appendFonts(pdfFonts,reallyMissingFonts)}}}}}async serializeXfaData(annotationStorage){return this.xfaFactory?this.xfaFactory.serializeData(annotationStorage):null}get version(){return this.catalog.version||this._version}get formInfo(){var formInfo={hasFields:!1,hasAcroForm:!1,hasXfa:!1,hasSignatures:!1},acroForm=this.catalog.acroForm;if(acroForm)try{var fields=acroForm.get("Fields"),hasFields=Array.isArray(fields)&&0new Page({pdfManager:this.pdfManager,xref:this.xref,pageIndex:pageIndex,pageDict:pageDict,ref:ref,globalIdFactory:this._globalIdFactory,fontCache:catalog.fontCache,builtInCMapCache:catalog.builtInCMapCache,standardFontDataCache:catalog.standardFontDataCache,globalImageCache:catalog.globalImageCache,systemFontCache:catalog.systemFontCache,nonBlendModesSet:catalog.nonBlendModesSet,xfaFactory:xfaFactory})),this._pagePromises.set(pageIndex,promise),promise}async checkFirstPage(recoveryMode=!1){if(!recoveryMode)try{await this.getPage(0)}catch(reason){if(reason instanceof XRefEntryException)throw this._pagePromises.delete(0),await this.cleanup(),new XRefParseException}}async checkLastPage(recoveryMode=!1){var{catalog,pdfManager}=this;catalog.setActualNumPages();let numPages;try{if(await Promise.all([pdfManager.ensureDoc("xfaFactory"),pdfManager.ensureDoc("linearization"),pdfManager.ensureCatalog("numPages")]),!this.xfaFactory){if(numPages=(this.linearization||catalog).numPages,!Number.isInteger(numPages))throw new FormatError("Page count is not an integer.");numPages<=1||await this.getPage(numPages-1)}}catch(reason){if(this._pagePromises.delete(numPages-1),await this.cleanup(),reason instanceof XRefEntryException&&!recoveryMode)throw new XRefParseException;warn(`checkLastPage - invalid /Pages tree /Count: ${numPages}.`);let pagesTree;try{pagesTree=await catalog.getAllPageDicts(recoveryMode)}catch(reasonAll){if(reasonAll instanceof XRefEntryException&&!recoveryMode)throw new XRefParseException;return void catalog.setActualNumPages(1)}for(var[pageIndex,[pageDict,ref]]of pagesTree){let promise;pageDict instanceof Error?(promise=Promise.reject(pageDict)).catch(()=>{}):promise=Promise.resolve(new Page({pdfManager:pdfManager,xref:this.xref,pageIndex:pageIndex,pageDict:pageDict,ref:ref,globalIdFactory:this._globalIdFactory,fontCache:catalog.fontCache,builtInCMapCache:catalog.builtInCMapCache,standardFontDataCache:catalog.standardFontDataCache,globalImageCache:catalog.globalImageCache,systemFontCache:catalog.systemFontCache,nonBlendModesSet:catalog.nonBlendModesSet,xfaFactory:null})),this._pagePromises.set(pageIndex,promise)}catalog.setActualNumPages(pagesTree.size)}}fontFallback(id,handler){return this.catalog.fontFallback(id,handler)}async cleanup(manuallyTriggered=!1){return this.catalog?this.catalog.cleanup(manuallyTriggered):clearGlobalCaches()}async#collectFieldObjects(name,fieldRef,promises,annotationGlobals,visitedRefs){var xref=this["xref"];if(fieldRef instanceof Ref&&!visitedRefs.has(fieldRef)){visitedRefs.put(fieldRef);var field=await xref.fetchAsync(fieldRef);if(field instanceof Dict){if(field.has("T")){var partName=stringToPDFString(await field.getAsync("T"));name=""===name?partName:name+"."+partName}else{let obj=field;for(;;){if((obj=obj.getRaw("Parent"))instanceof Ref){if(visitedRefs.has(obj))break;obj=await xref.fetchAsync(obj)}if(!(obj instanceof Dict))break;if(obj.has("T")){const partName=stringToPDFString(await obj.getAsync("T"));name=""===name?partName:name+"."+partName;break}}}if(promises.has(name)||promises.set(name,[]),promises.get(name).push(AnnotationFactory.create(xref,fieldRef,annotationGlobals,null,!0,null).then(annotation=>annotation?.getFieldObject()).catch(function(reason){return warn(`#collectFieldObjects: "${reason}".`),null})),field.has("Kids")){partName=await field.getAsync("Kids");if(Array.isArray(partName))for(const kid of partName)await this.#collectFieldObjects(name,kid,promises,annotationGlobals,visitedRefs)}}}}get fieldObjects(){var promise;return this.formInfo.hasFields?(promise=Promise.all([this.pdfManager.ensureDoc("annotationGlobals"),this.pdfManager.ensureCatalog("acroForm")]).then(async([annotationGlobals,acroForm])=>{if(!annotationGlobals)return null;var visitedRefs=new RefSet;const allFields=Object.create(null);var fieldPromises=new Map;for(const fieldRef of await acroForm.getAsync("Fields"))await this.#collectFieldObjects("",fieldRef,fieldPromises,annotationGlobals,visitedRefs);var allPromises=[];for(const[name,promises]of fieldPromises)allPromises.push(Promise.all(promises).then(fields=>{0<(fields=fields.filter(field=>!!field)).length&&(allFields[name]=fields)}));return await Promise.all(allPromises),allFields}),shadow(this,"fieldObjects",promise)):shadow(this,"fieldObjects",Promise.resolve(null))}get hasJSActions(){var promise=this.pdfManager.ensureDoc("_parseHasJSActions");return shadow(this,"hasJSActions",promise)}async _parseHasJSActions(){var[catalogJsActions,fieldObjects]=await Promise.all([this.pdfManager.ensureCatalog("jsActions"),this.pdfManager.ensureDoc("fieldObjects")]);return!!catalogJsActions||!!fieldObjects&&Object.values(fieldObjects).some(fieldObject=>fieldObject.some(object=>null!==object.actions))}get calculationOrderIds(){var acroForm=this.catalog.acroForm;if(!acroForm?.has("CO"))return shadow(this,"calculationOrderIds",null);acroForm=acroForm.get("CO");if(!Array.isArray(acroForm)||0===acroForm.length)return shadow(this,"calculationOrderIds",null);var ids=[];for(const id of acroForm)id instanceof Ref&&ids.push(id.toString());return shadow(this,"calculationOrderIds",0===ids.length?null:ids)}get annotationGlobals(){return shadow(this,"annotationGlobals",AnnotationFactory.createGlobals(this.pdfManager))}}function parseDocBaseUrl(url){if(url){var absoluteUrl=createValidAbsoluteUrl(url);if(absoluteUrl)return absoluteUrl.href;warn(`Invalid absolute docBaseUrl: "${url}".`)}return null}class BasePdfManager{constructor(args){this.constructor===BasePdfManager&&unreachable("Cannot initialize BasePdfManager."),this._docBaseUrl=parseDocBaseUrl(args.docBaseUrl),this._docId=args.docId,this._password=args.password,this.enableXfa=args.enableXfa,args.evaluatorOptions.isOffscreenCanvasSupported&&=FeatureTest.isOffscreenCanvasSupported,this.evaluatorOptions=args.evaluatorOptions}get docId(){return this._docId}get password(){return this._password}get docBaseUrl(){return this._docBaseUrl}get catalog(){return this.pdfDocument.catalog}ensureDoc(prop,args){return this.ensure(this.pdfDocument,prop,args)}ensureXRef(prop,args){return this.ensure(this.pdfDocument.xref,prop,args)}ensureCatalog(prop,args){return this.ensure(this.pdfDocument.catalog,prop,args)}getPage(pageIndex){return this.pdfDocument.getPage(pageIndex)}fontFallback(id,handler){return this.pdfDocument.fontFallback(id,handler)}loadXfaFonts(handler,task){return this.pdfDocument.loadXfaFonts(handler,task)}loadXfaImages(){return this.pdfDocument.loadXfaImages()}serializeXfaData(annotationStorage){return this.pdfDocument.serializeXfaData(annotationStorage)}cleanup(manuallyTriggered=!1){return this.pdfDocument.cleanup(manuallyTriggered)}async ensure(obj,prop,args){unreachable("Abstract method `ensure` called")}requestRange(begin,end){unreachable("Abstract method `requestRange` called")}requestLoadedStream(noFetch=0){unreachable("Abstract method `requestLoadedStream` called")}sendProgressiveData(chunk){unreachable("Abstract method `sendProgressiveData` called")}updatePassword(password){this._password=password}terminate(reason){unreachable("Abstract method `terminate` called")}}class LocalPdfManager extends BasePdfManager{constructor(args){super(args);args=new Stream(args.source);this.pdfDocument=new PDFDocument(this,args),this._loadedStreamPromise=Promise.resolve(args)}async ensure(obj,prop,args){prop=obj[prop];return"function"==typeof prop?prop.apply(obj,args):prop}requestRange(begin,end){return Promise.resolve()}requestLoadedStream(noFetch=0){return this._loadedStreamPromise}terminate(reason){}}class NetworkPdfManager extends BasePdfManager{constructor(args){super(args),this.streamManager=new ChunkedStreamManager(args.source,{msgHandler:args.handler,length:args.length,disableAutoFetch:args.disableAutoFetch,rangeChunkSize:args.rangeChunkSize}),this.pdfDocument=new PDFDocument(this,this.streamManager.getStream())}async ensure(obj,prop,args){try{var value=obj[prop];return"function"==typeof value?value.apply(obj,args):value}catch(ex){if(ex instanceof MissingDataException)return await this.requestRange(ex.begin,ex.end),this.ensure(obj,prop,args);throw ex}}requestRange(begin,end){return this.streamManager.requestRange(begin,end)}requestLoadedStream(noFetch=!1){return this.streamManager.requestAllChunks(noFetch)}sendProgressiveData(chunk){this.streamManager.onReceiveData({chunk:chunk})}terminate(reason){this.streamManager.abort(reason)}}const CallbackKind={UNKNOWN:0,DATA:1,ERROR:2},StreamKind={UNKNOWN:0,CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function wrapReason(reason){switch(reason instanceof Error||"object"==typeof reason&&null!==reason||unreachable('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),reason.name){case"AbortException":return new AbortException(reason.message);case"MissingPDFException":return new MissingPDFException(reason.message);case"PasswordException":return new PasswordException(reason.message,reason.code);case"UnexpectedResponseException":return new UnexpectedResponseException(reason.message,reason.status);case"UnknownErrorException":return new UnknownErrorException(reason.message,reason.details);default:return new UnknownErrorException(reason.message,reason.toString())}}class MessageHandler{constructor(sourceName,targetName,comObj){this.sourceName=sourceName,this.targetName=targetName,this.comObj=comObj,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),this._onComObjOnMessage=event=>{const data=event.data;if(data.targetName===this.sourceName)if(data.stream)this.#processStreamMessage(data);else if(data.callback){var event=data.callbackId,capability=this.callbackCapabilities[event];if(!capability)throw new Error("Cannot resolve callback "+event);if(delete this.callbackCapabilities[event],data.callback===CallbackKind.DATA)capability.resolve(data.data);else{if(data.callback!==CallbackKind.ERROR)throw new Error("Unexpected callback case");capability.reject(wrapReason(data.reason))}}else{const action=this.actionHandler[data.action];if(!action)throw new Error("Unknown action from worker: "+data.action);if(data.callbackId){const cbSourceName=this.sourceName,cbTargetName=data.sourceName;void new Promise(function(resolve){resolve(action(data.data))}).then(function(result){comObj.postMessage({sourceName:cbSourceName,targetName:cbTargetName,callback:CallbackKind.DATA,callbackId:data.callbackId,data:result})},function(reason){comObj.postMessage({sourceName:cbSourceName,targetName:cbTargetName,callback:CallbackKind.ERROR,callbackId:data.callbackId,reason:wrapReason(reason)})})}else data.streamId?this.#createStreamSink(data):action(data.data)}},comObj.addEventListener("message",this._onComObjOnMessage)}on(actionName,handler){var ah=this.actionHandler;if(ah[actionName])throw new Error(`There is already an actionName called "${actionName}"`);ah[actionName]=handler}send(actionName,data,transfers){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:actionName,data:data},transfers)}sendWithPromise(actionName,data,transfers){var callbackId=this.callbackId++,capability=Promise.withResolvers();this.callbackCapabilities[callbackId]=capability;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:actionName,callbackId:callbackId,data:data},transfers)}catch(ex){capability.reject(ex)}return capability.promise}sendWithStream(actionName,data,queueingStrategy,transfers){const streamId=this.streamId++,sourceName=this.sourceName,targetName=this.targetName,comObj=this.comObj;return new ReadableStream({start:controller=>{var startCapability=Promise.withResolvers();return this.streamControllers[streamId]={controller:controller,startCall:startCapability,pullCall:null,cancelCall:null,isClosed:!1},comObj.postMessage({sourceName:sourceName,targetName:targetName,action:actionName,streamId:streamId,data:data,desiredSize:controller.desiredSize},transfers),startCapability.promise},pull:controller=>{var pullCapability=Promise.withResolvers();return this.streamControllers[streamId].pullCall=pullCapability,comObj.postMessage({sourceName:sourceName,targetName:targetName,stream:StreamKind.PULL,streamId:streamId,desiredSize:controller.desiredSize}),pullCapability.promise},cancel:reason=>{assert(reason instanceof Error,"cancel must have a valid reason");var cancelCapability=Promise.withResolvers();return this.streamControllers[streamId].cancelCall=cancelCapability,this.streamControllers[streamId].isClosed=!0,comObj.postMessage({sourceName:sourceName,targetName:targetName,stream:StreamKind.CANCEL,streamId:streamId,reason:wrapReason(reason)}),cancelCapability.promise}},queueingStrategy)}#createStreamSink(data){const streamId=data.streamId,sourceName=this.sourceName,targetName=data.sourceName,comObj=this.comObj,self=this,action=this.actionHandler[data.action],streamSink={enqueue(chunk,size=1,transfers){var lastDesiredSize;this.isCancelled||(lastDesiredSize=this.desiredSize,this.desiredSize-=size,0{this._isStreamingSupported=data.isStreamingSupported,this._isRangeSupported=data.isRangeSupported,this._contentLength=data.contentLength})}get headersReady(){return this._headersReady}get contentLength(){return this._contentLength}get isStreamingSupported(){return this._isStreamingSupported}get isRangeSupported(){return this._isRangeSupported}async read(){var{value,done}=await this._reader.read();return done?{value:void 0,done:!0}:{value:value.buffer,done:!1}}cancel(reason){this._reader.cancel(reason)}}class PDFWorkerStreamRangeReader{constructor(begin,end,msgHandler){this._msgHandler=msgHandler,this.onProgress=null;msgHandler=this._msgHandler.sendWithStream("GetRangeReader",{begin:begin,end:end});this._reader=msgHandler.getReader()}get isStreamingSupported(){return!1}async read(){var{value,done}=await this._reader.read();return done?{value:void 0,done:!0}:{value:value.buffer,done:!1}}cancel(reason){this._reader.cancel(reason)}}class WorkerTask{constructor(name){this.name=name,this.terminated=!1,this._capability=Promise.withResolvers()}get finished(){return this._capability.promise}finish(){this._capability.resolve()}terminate(){this.terminated=!0}ensureNotTerminated(){if(this.terminated)throw new Error("Worker task was terminated")}}class WorkerMessageHandler{static setup(handler,port){let testMessageProcessed=!1;handler.on("test",function(data){testMessageProcessed||(testMessageProcessed=!0,handler.send("test",data instanceof Uint8Array))}),handler.on("configure",function(data){setVerbosityLevel(data.verbosity)}),handler.on("GetDocRequest",function(data){return WorkerMessageHandler.createDocumentHandler(data,port)})}static createDocumentHandler(docParams,port){let pdfManager,terminated=!1,cancelXHRs=null;const WorkerTasks=new Set,verbosity=getVerbosityLevel(),{docId,apiVersion}=docParams;if("4.2.67"!==apiVersion)throw new Error(`The API version "${apiVersion}" does not match `+'the Worker version "4.2.67".');var enumerableProperties=[];for(const property in[])enumerableProperties.push(property);if(enumerableProperties.length)throw new Error("The `Array.prototype` contains unexpected enumerable properties: "+enumerableProperties.join(", ")+"; thus breaking e.g. `for...in` iteration of `Array`s.");var workerHandlerName=docId+"_worker";let handler=new MessageHandler(workerHandlerName,docId,port);function ensureNotTerminated(){if(terminated)throw new Error("Worker was terminated")}function startWorkerTask(task){WorkerTasks.add(task)}function finishWorkerTask(task){task.finish(),WorkerTasks.delete(task)}async function loadDocument(recoveryMode){await pdfManager.ensureDoc("checkHeader"),await pdfManager.ensureDoc("parseStartXRef"),await pdfManager.ensureDoc("parse",[recoveryMode]),await pdfManager.ensureDoc("checkFirstPage",[recoveryMode]),await pdfManager.ensureDoc("checkLastPage",[recoveryMode]);recoveryMode=await pdfManager.ensureDoc("isPureXfa");if(recoveryMode){const task=new WorkerTask("loadXfaFonts");startWorkerTask(task),await Promise.all([pdfManager.loadXfaFonts(handler,task).catch(reason=>{}).then(()=>finishWorkerTask(task)),pdfManager.loadXfaImages()])}var[numPages,fingerprints]=await Promise.all([pdfManager.ensureDoc("numPages"),pdfManager.ensureDoc("fingerprints")]);return{numPages:numPages,fingerprints:fingerprints,htmlForXfa:recoveryMode?await pdfManager.ensureDoc("htmlForXfa"):null}}function getPdfManager({data,password,disableAutoFetch,rangeChunkSize,length,docBaseUrl,enableXfa,evaluatorOptions}){const pdfManagerArgs={source:null,disableAutoFetch:disableAutoFetch,docBaseUrl:docBaseUrl,docId:docId,enableXfa:enableXfa,evaluatorOptions:evaluatorOptions,handler:handler,length:length,password:password,rangeChunkSize:rangeChunkSize},pdfManagerCapability=Promise.withResolvers();let newPdfManager;if(data)try{pdfManagerArgs.source=data,newPdfManager=new LocalPdfManager(pdfManagerArgs),pdfManagerCapability.resolve(newPdfManager)}catch(ex){pdfManagerCapability.reject(ex)}else{let pdfStream,cachedChunks=[];try{pdfStream=new PDFWorkerStream(handler)}catch(ex){return pdfManagerCapability.reject(ex),pdfManagerCapability.promise}const fullRequest=pdfStream.getFullReader();fullRequest.headersReady.then(function(){if(fullRequest.isRangeSupported){pdfManagerArgs.source=pdfStream,pdfManagerArgs.length=fullRequest.contentLength,pdfManagerArgs.disableAutoFetch||=fullRequest.isStreamingSupported,newPdfManager=new NetworkPdfManager(pdfManagerArgs);for(const chunk of cachedChunks)newPdfManager.sendProgressiveData(chunk);cachedChunks=[],pdfManagerCapability.resolve(newPdfManager),cancelXHRs=null}}).catch(function(reason){pdfManagerCapability.reject(reason),cancelXHRs=null});let loaded=0;new Promise(function(resolve,reject){const readChunk=function({value,done}){try{if(ensureNotTerminated(),done){if(!newPdfManager){var pdfFile=arrayBuffersToBytes(cachedChunks);length&&pdfFile.length!==length&&warn("reported HTTP length is different from actual");try{pdfManagerArgs.source=pdfFile,newPdfManager=new LocalPdfManager(pdfManagerArgs),pdfManagerCapability.resolve(newPdfManager)}catch(ex){pdfManagerCapability.reject(ex)}cachedChunks=[]}cancelXHRs=null}else loaded+=value.byteLength,fullRequest.isStreamingSupported||handler.send("DocProgress",{loaded:loaded,total:Math.max(loaded,fullRequest.contentLength||0)}),newPdfManager?newPdfManager.sendProgressiveData(value):cachedChunks.push(value),fullRequest.read().then(readChunk,reject)}catch(e){reject(e)}};fullRequest.read().then(readChunk,reject)}).catch(function(e){pdfManagerCapability.reject(e),cancelXHRs=null}),cancelXHRs=function(reason){pdfStream.cancelAllRequests(reason)}}return pdfManagerCapability.promise}return handler.on("GetPage",function(data){return pdfManager.getPage(data.pageIndex).then(function(page){return Promise.all([pdfManager.ensure(page,"rotate"),pdfManager.ensure(page,"ref"),pdfManager.ensure(page,"userUnit"),pdfManager.ensure(page,"view")]).then(function([rotate,ref,userUnit,view]){return{rotate:rotate,ref:ref,refStr:ref?.toString()??null,userUnit:userUnit,view:view}})})}),handler.on("GetPageIndex",function(data){data=Ref.get(data.num,data.gen);return pdfManager.ensureCatalog("getPageIndex",[data])}),handler.on("GetDestinations",function(data){return pdfManager.ensureCatalog("destinations")}),handler.on("GetDestination",function(data){return pdfManager.ensureCatalog("getDestination",[data.id])}),handler.on("GetPageLabels",function(data){return pdfManager.ensureCatalog("pageLabels")}),handler.on("GetPageLayout",function(data){return pdfManager.ensureCatalog("pageLayout")}),handler.on("GetPageMode",function(data){return pdfManager.ensureCatalog("pageMode")}),handler.on("GetViewerPreferences",function(data){return pdfManager.ensureCatalog("viewerPreferences")}),handler.on("GetOpenAction",function(data){return pdfManager.ensureCatalog("openAction")}),handler.on("GetAttachments",function(data){return pdfManager.ensureCatalog("attachments")}),handler.on("GetDocJSActions",function(data){return pdfManager.ensureCatalog("jsActions")}),handler.on("GetPageJSActions",function({pageIndex}){return pdfManager.getPage(pageIndex).then(function(page){return pdfManager.ensure(page,"jsActions")})}),handler.on("GetOutline",function(data){return pdfManager.ensureCatalog("documentOutline")}),handler.on("GetOptionalContentConfig",function(data){return pdfManager.ensureCatalog("optionalContentConfig")}),handler.on("GetPermissions",function(data){return pdfManager.ensureCatalog("permissions")}),handler.on("GetMetadata",function(data){return Promise.all([pdfManager.ensureDoc("documentInfo"),pdfManager.ensureCatalog("metadata")])}),handler.on("GetMarkInfo",function(data){return pdfManager.ensureCatalog("markInfo")}),handler.on("GetData",function(data){return pdfManager.requestLoadedStream().then(function(stream){return stream.bytes})}),handler.on("GetAnnotations",function({pageIndex,intent}){return pdfManager.getPage(pageIndex).then(function(page){const task=new WorkerTask("GetAnnotations: page "+pageIndex);return startWorkerTask(task),page.getAnnotationsData(handler,task,intent).then(data=>(finishWorkerTask(task),data),reason=>{throw finishWorkerTask(task),reason})})}),handler.on("GetFieldObjects",function(data){return pdfManager.ensureDoc("fieldObjects")}),handler.on("HasJSActions",function(data){return pdfManager.ensureDoc("hasJSActions")}),handler.on("GetCalculationOrderIds",function(data){return pdfManager.ensureDoc("calculationOrderIds")}),handler.on("SaveDocument",async function({isPureXfa,numPages,annotationStorage,filename}){var globalPromises=[pdfManager.requestLoadedStream(),pdfManager.ensureCatalog("acroForm"),pdfManager.ensureCatalog("acroFormRef"),pdfManager.ensureDoc("startXRef"),pdfManager.ensureDoc("xref"),pdfManager.ensureDoc("linearization"),pdfManager.ensureCatalog("structTreeRoot")],promises=[];const newAnnotationsByPage=isPureXfa?null:getNewAnnotationsMap(annotationStorage),[stream,acroForm,acroFormRef,startXRef,xref,linearization,_structTreeRoot]=await Promise.all(globalPromises),catalogRef=xref.trailer.getRaw("Root")||null;let structTreeRoot;if(newAnnotationsByPage){_structTreeRoot?await _structTreeRoot.canUpdateStructTree({pdfManager:pdfManager,xref:xref,newAnnotationsByPage:newAnnotationsByPage})&&(structTreeRoot=_structTreeRoot):await StructTreeRoot.canCreateStructureTree({catalogRef:catalogRef,pdfManager:pdfManager,newAnnotationsByPage:newAnnotationsByPage})&&(structTreeRoot=null);const imagePromises=AnnotationFactory.generateImages(annotationStorage.values(),xref,pdfManager.evaluatorOptions.isOffscreenCanvasSupported);var newAnnotationPromises=void 0===structTreeRoot?promises:[];for(const[pageIndex,annotations]of newAnnotationsByPage)newAnnotationPromises.push(pdfManager.getPage(pageIndex).then(page=>{const task=new WorkerTask("Save (editor): page "+pageIndex);return page.saveNewAnnotations(handler,task,annotations,imagePromises).finally(function(){finishWorkerTask(task)})}));null===structTreeRoot?promises.push(Promise.all(newAnnotationPromises).then(async newRefs=>(await StructTreeRoot.createStructureTree({newAnnotationsByPage:newAnnotationsByPage,xref:xref,catalogRef:catalogRef,pdfManager:pdfManager,newRefs:newRefs}),newRefs))):structTreeRoot&&promises.push(Promise.all(newAnnotationPromises).then(async newRefs=>(await structTreeRoot.updateStructureTree({newAnnotationsByPage:newAnnotationsByPage,pdfManager:pdfManager,newRefs:newRefs}),newRefs)))}if(isPureXfa)promises.push(pdfManager.serializeXfaData(annotationStorage));else for(let pageIndex=0;pageIndexref.needAppearances),xfa=acroForm instanceof Dict&&acroForm.get("XFA")||null;let xfaDatasetsRef=null,hasXfaDatasetsEntry=!1;if(Array.isArray(xfa)){for(let i=0,ii=xfa.length;i{"string"==typeof value&&(infoObj[key]=stringToPDFString(value))}),newXrefInfo={rootRef:catalogRef,encryptRef:xref.trailer.getRaw("Encrypt")||null,newRef:xref.getNewTemporaryRef(),infoRef:xref.trailer.getRaw("Info")||null,info:infoObj,fileIds:xref.trailer.get("ID")||null,startXRef:linearization?startXRef:xref.lastXRefStreamPos??startXRef,filename:filename}}return incrementalUpdate({originalData:stream.bytes,xrefInfo:newXrefInfo,newRefs:newRefs,xref:xref,hasXfa:!!xfa,xfaDatasetsRef:xfaDatasetsRef,hasXfaDatasetsEntry:hasXfaDatasetsEntry,needAppearances:isPureXfa,acroFormRef:acroFormRef,acroForm:acroForm,xfaData:xfaData,useXrefStream:isDict(xref.topDict,"XRef")}).finally(()=>{xref.resetNewTemporaryRef()})}),handler.on("GetOperatorList",function(data,sink){const pageIndex=data.pageIndex;pdfManager.getPage(pageIndex).then(function(page){const task=new WorkerTask("GetOperatorList: page "+pageIndex),start=(startWorkerTask(task),verbosity>=VerbosityLevel.INFOS?Date.now():0);page.getOperatorList({handler:handler,sink:sink,task:task,intent:data.intent,cacheKey:data.cacheKey,annotationStorage:data.annotationStorage}).then(function(operatorListInfo){finishWorkerTask(task),start&&info(`page=${pageIndex+1} - getOperatorList: time=`+(Date.now()-start)+"ms, len="+operatorListInfo.length),sink.close()},function(reason){finishWorkerTask(task),task.terminated||sink.error(reason)})})}),handler.on("GetTextContent",function(data,sink){const{pageIndex,includeMarkedContent,disableNormalization}=data;pdfManager.getPage(pageIndex).then(function(page){const task=new WorkerTask("GetTextContent: page "+pageIndex),start=(startWorkerTask(task),verbosity>=VerbosityLevel.INFOS?Date.now():0);page.extractTextContent({handler:handler,task:task,sink:sink,includeMarkedContent:includeMarkedContent,disableNormalization:disableNormalization}).then(function(){finishWorkerTask(task),start&&info(`page=${pageIndex+1} - getTextContent: time=`+(Date.now()-start)+"ms"),sink.close()},function(reason){finishWorkerTask(task),task.terminated||sink.error(reason)})})}),handler.on("GetStructTree",function(data){return pdfManager.getPage(data.pageIndex).then(function(page){return pdfManager.ensure(page,"getStructTree")})}),handler.on("FontFallback",function(data){return pdfManager.fontFallback(data.id,handler)}),handler.on("Cleanup",function(data){return pdfManager.cleanup(!0)}),handler.on("Terminate",function(data){terminated=!0;var cleanupPromise,waitOn=[];pdfManager?(pdfManager.terminate(new AbortException("Worker was terminated.")),cleanupPromise=pdfManager.cleanup(),waitOn.push(cleanupPromise),pdfManager=null):clearGlobalCaches(),cancelXHRs&&cancelXHRs(new AbortException("Worker was terminated."));for(const task of WorkerTasks)waitOn.push(task.finished),task.terminate();return Promise.all(waitOn).then(function(){handler.destroy(),handler=null})}),handler.on("Ready",function(data){!function(data){function onSuccess(doc){ensureNotTerminated(),handler.send("GetDoc",{pdfInfo:doc})}function onFailure(ex){if(ensureNotTerminated(),ex instanceof PasswordException){const task=new WorkerTask("PasswordException: response "+ex.code);startWorkerTask(task),handler.sendWithPromise("PasswordRequest",ex).then(function({password}){finishWorkerTask(task),pdfManager.updatePassword(password),pdfManagerReady()}).catch(function(){finishWorkerTask(task),handler.send("DocException",ex)})}else ex instanceof InvalidPDFException||ex instanceof MissingPDFException||ex instanceof UnexpectedResponseException||ex instanceof UnknownErrorException?handler.send("DocException",ex):handler.send("DocException",new UnknownErrorException(ex.message,ex.toString()))}function pdfManagerReady(){ensureNotTerminated(),loadDocument(!1).then(onSuccess,function(reason){ensureNotTerminated(),reason instanceof XRefParseException?pdfManager.requestLoadedStream().then(function(){ensureNotTerminated(),loadDocument(!0).then(onSuccess,onFailure)}):onFailure(reason)})}ensureNotTerminated(),getPdfManager(data).then(function(newPdfManager){if(terminated)throw newPdfManager.terminate(new AbortException("Worker was terminated.")),new Error("Worker was terminated");(pdfManager=newPdfManager).requestLoadedStream(!0).then(stream=>{handler.send("DataLoaded",{length:stream.bytes.byteLength})})}).then(pdfManagerReady,onFailure)}(docParams),docParams=null}),workerHandlerName}static initializeFromPort(port){var handler=new MessageHandler("worker","main",port);WorkerMessageHandler.setup(handler,port),handler.send("ready",null)}}function isMessagePort(maybePort){return"function"==typeof maybePort.postMessage&&"onmessage"in maybePort}"undefined"==typeof window&&!isNodeJS&&"undefined"!=typeof self&&isMessagePort(self)&&WorkerMessageHandler.initializeFromPort(self);const pdfjsVersion="4.2.67",pdfjsBuild="49b388101";var __webpack_exports__WorkerMessageHandler=__webpack_exports__.WorkerMessageHandler;export{__webpack_exports__WorkerMessageHandler as WorkerMessageHandler};