diff --git a/assets/i18n/en.json b/assets/i18n/en.json index 8d64c5b..577d6bb 100644 --- a/assets/i18n/en.json +++ b/assets/i18n/en.json @@ -59,7 +59,7 @@ "instructions_details": "This key is the ONLY way to recover your VeilidChat account in the event of a forgotton password or a lost, stolen, or compromised device.", "instructions_options": "Here are some options for your recovery key:", "instructions_print": "Print the recovery key and keep it somewhere safe", - "instructions_view": "View the recovery key and write it down on paper", + "instructions_view": "View the recovery key and take a screenshot", "instructions_share": "Share the recovery key to another app to save it", "print": "Print", "view": "View", diff --git a/assets/js/pdf/3.2.146/pdf.min.js b/assets/js/pdf/3.2.146/pdf.min.js new file mode 100644 index 0000000..4d43020 --- /dev/null +++ b/assets/js/pdf/3.2.146/pdf.min.js @@ -0,0 +1,22 @@ +/** + * @licstart The following is the entire license notice for the + * JavaScript code in this page + * + * Copyright 2022 Mozilla Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @licend The above is the entire license notice for the + * JavaScript code in this page + */ +!function webpackUniversalModuleDefinition(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("pdfjs-dist/build/pdf",[],e):"object"==typeof exports?exports["pdfjs-dist/build/pdf"]=e():t["pdfjs-dist/build/pdf"]=t.pdfjsLib=e()}(globalThis,(()=>(()=>{"use strict";var __webpack_modules__=[,(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});e.VerbosityLevel=e.Util=e.UnknownErrorException=e.UnexpectedResponseException=e.UNSUPPORTED_FEATURES=e.TextRenderingMode=e.StreamType=e.RenderingIntentFlag=e.PermissionFlag=e.PasswordResponses=e.PasswordException=e.PageActionEventType=e.OPS=e.MissingPDFException=e.LINE_FACTOR=e.LINE_DESCENT_FACTOR=e.InvalidPDFException=e.ImageKind=e.IDENTITY_MATRIX=e.FormatError=e.FontType=e.FeatureTest=e.FONT_IDENTITY_MATRIX=e.DocumentActionEventType=e.CMapCompressionType=e.BaseException=e.BASELINE_FACTOR=e.AnnotationType=e.AnnotationStateModelType=e.AnnotationReviewState=e.AnnotationReplyType=e.AnnotationMode=e.AnnotationMarkedState=e.AnnotationFlag=e.AnnotationFieldFlag=e.AnnotationEditorType=e.AnnotationEditorPrefix=e.AnnotationEditorParamsType=e.AnnotationBorderStyleType=e.AnnotationActionEventType=e.AbortException=void 0;e.arrayByteLength=arrayByteLength;e.arraysToBytes=function arraysToBytes(t){const e=t.length;if(1===e&&t[0]instanceof Uint8Array)return t[0];let s=0;for(let n=0;ne});t.promise=new Promise((function(s,n){t.resolve=function(t){e=!0;s(t)};t.reject=function(t){e=!0;n(t)}}));return t};e.createValidAbsoluteUrl=function createValidAbsoluteUrl(t,e=null,s=null){if(!t)return null;try{if(s&&"string"==typeof t){if(s.addDefaultProtocol&&t.startsWith("www.")){const e=t.match(/\./g);e&&e.length>=2&&(t=`http://${t}`)}if(s.tryConvertEncoding)try{t=stringToUTF8String(t)}catch(t){}}const n=e?new URL(t,e):new URL(t);if(function _isValidProtocol(t){if(!t)return!1;switch(t.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}(n))return n}catch(t){}return null};e.getModificationDate=function getModificationDate(t=new Date){return[t.getUTCFullYear().toString(),(t.getUTCMonth()+1).toString().padStart(2,"0"),t.getUTCDate().toString().padStart(2,"0"),t.getUTCHours().toString().padStart(2,"0"),t.getUTCMinutes().toString().padStart(2,"0"),t.getUTCSeconds().toString().padStart(2,"0")].join("")};e.getVerbosityLevel=function getVerbosityLevel(){return n};e.info=function info(t){n>=s.INFOS&&console.log(`Info: ${t}`)};e.isArrayBuffer=function isArrayBuffer(t){return"object"==typeof t&&null!==t&&void 0!==t.byteLength};e.isArrayEqual=function isArrayEqual(t,e){if(t.length!==e.length)return!1;for(let s=0,n=t.length;s>24&255,t>>16&255,t>>8&255,255&t)};e.stringToBytes=stringToBytes;e.stringToPDFString=function stringToPDFString(t){if(t[0]>="ï"){let e;"þ"===t[0]&&"ÿ"===t[1]?e="utf-16be":"ÿ"===t[0]&&"þ"===t[1]?e="utf-16le":"ï"===t[0]&&"»"===t[1]&&"¿"===t[2]&&(e="utf-8");if(e)try{const s=new TextDecoder(e,{fatal:!0}),n=stringToBytes(t);return s.decode(n)}catch(t){warn(`stringToPDFString: "${t}".`)}}const e=[];for(let s=0,n=t.length;s=s.WARNINGS&&console.log(`Warning: ${t}`)}function unreachable(t){throw new Error(t)}function shadow(t,e,s,n=!1){Object.defineProperty(t,e,{value:s,enumerable:!n,configurable:!0,writable:!1});return s}const i=function BaseExceptionClosure(){function BaseException(t,e){this.constructor===BaseException&&unreachable("Cannot initialize BaseException.");this.message=t;this.name=e}BaseException.prototype=new Error;BaseException.constructor=BaseException;return BaseException}();e.BaseException=i;e.PasswordException=class PasswordException extends i{constructor(t,e){super(t,"PasswordException");this.code=e}};e.UnknownErrorException=class UnknownErrorException extends i{constructor(t,e){super(t,"UnknownErrorException");this.details=e}};e.InvalidPDFException=class InvalidPDFException extends i{constructor(t){super(t,"InvalidPDFException")}};e.MissingPDFException=class MissingPDFException extends i{constructor(t){super(t,"MissingPDFException")}};e.UnexpectedResponseException=class UnexpectedResponseException extends i{constructor(t,e){super(t,"UnexpectedResponseException");this.status=e}};e.FormatError=class FormatError extends i{constructor(t){super(t,"FormatError")}};e.AbortException=class AbortException extends i{constructor(t){super(t,"AbortException")}};function stringToBytes(t){"string"!=typeof t&&unreachable("Invalid argument for stringToBytes");const e=t.length,s=new Uint8Array(e);for(let n=0;nt.toString(16).padStart(2,"0")));class Util{static makeHexColor(t,e,s){return`#${a[t]}${a[e]}${a[s]}`}static scaleMinMax(t,e){let s;if(t[0]){if(t[0]<0){s=e[0];e[0]=e[1];e[1]=s}e[0]*=t[0];e[1]*=t[0];if(t[3]<0){s=e[2];e[2]=e[3];e[3]=s}e[2]*=t[3];e[3]*=t[3]}else{s=e[0];e[0]=e[2];e[2]=s;s=e[1];e[1]=e[3];e[3]=s;if(t[1]<0){s=e[2];e[2]=e[3];e[3]=s}e[2]*=t[1];e[3]*=t[1];if(t[2]<0){s=e[0];e[0]=e[1];e[1]=s}e[0]*=t[2];e[1]*=t[2]}e[0]+=t[4];e[1]+=t[4];e[2]+=t[5];e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){return[t[0]*e[0]+t[1]*e[2]+e[4],t[0]*e[1]+t[1]*e[3]+e[5]]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2];return[(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s]}static getAxialAlignedBoundingBox(t,e){const s=Util.applyTransform(t,e),n=Util.applyTransform(t.slice(2,4),e),i=Util.applyTransform([t[0],t[3]],e),a=Util.applyTransform([t[2],t[1]],e);return[Math.min(s[0],n[0],i[0],a[0]),Math.min(s[1],n[1],i[1],a[1]),Math.max(s[0],n[0],i[0],a[0]),Math.max(s[1],n[1],i[1],a[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],n=t[0]*e[1]+t[1]*e[3],i=t[2]*e[0]+t[3]*e[2],a=t[2]*e[1]+t[3]*e[3],r=(s+a)/2,o=Math.sqrt((s+a)**2-4*(s*a-i*n))/2,l=r+o||1,c=r-o||1;return[Math.sqrt(l),Math.sqrt(c)]}static normalizeRect(t){const e=t.slice(0);if(t[0]>t[2]){e[0]=t[2];e[2]=t[0]}if(t[1]>t[3]){e[1]=t[3];e[3]=t[1]}return e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),n=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>n)return null;const i=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),a=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return i>a?null:[s,i,n,a]}static bezierBoundingBox(t,e,s,n,i,a,r,o){const l=[],c=[[],[]];let h,d,u,p,g,m,f,b;for(let c=0;c<2;++c){if(0===c){d=6*t-12*s+6*i;h=-3*t+9*s-9*i+3*r;u=3*s-3*t}else{d=6*e-12*n+6*a;h=-3*e+9*n-9*a+3*o;u=3*n-3*e}if(Math.abs(h)<1e-12){if(Math.abs(d)<1e-12)continue;p=-u/d;0{Object.defineProperty(exports,"__esModule",{value:!0});exports.build=exports.RenderTask=exports.PDFWorkerUtil=exports.PDFWorker=exports.PDFPageProxy=exports.PDFDocumentProxy=exports.PDFDocumentLoadingTask=exports.PDFDataRangeTransport=exports.LoopbackPort=exports.DefaultStandardFontDataFactory=exports.DefaultCanvasFactory=exports.DefaultCMapReaderFactory=void 0;exports.getDocument=getDocument;exports.setPDFNetworkStreamFactory=setPDFNetworkStreamFactory;exports.version=void 0;var _util=__w_pdfjs_require__(1),_annotation_storage=__w_pdfjs_require__(3),_display_utils=__w_pdfjs_require__(6),_font_loader=__w_pdfjs_require__(9),_canvas=__w_pdfjs_require__(11),_worker_options=__w_pdfjs_require__(14),_is_node=__w_pdfjs_require__(10),_message_handler=__w_pdfjs_require__(15),_metadata=__w_pdfjs_require__(16),_optional_content_config=__w_pdfjs_require__(17),_transport_stream=__w_pdfjs_require__(18),_xfa_text=__w_pdfjs_require__(19);const DEFAULT_RANGE_CHUNK_SIZE=65536,RENDERING_CANCELLED_TIMEOUT=100;let DefaultCanvasFactory=_display_utils.DOMCanvasFactory;exports.DefaultCanvasFactory=DefaultCanvasFactory;let DefaultCMapReaderFactory=_display_utils.DOMCMapReaderFactory;exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory;let DefaultStandardFontDataFactory=_display_utils.DOMStandardFontDataFactory,createPDFNetworkStream;exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory;if(_is_node.isNodeJS){const{NodeCanvasFactory:t,NodeCMapReaderFactory:e,NodeStandardFontDataFactory:s}=__w_pdfjs_require__(20);exports.DefaultCanvasFactory=DefaultCanvasFactory=t;exports.DefaultCMapReaderFactory=DefaultCMapReaderFactory=e;exports.DefaultStandardFontDataFactory=DefaultStandardFontDataFactory=s}function setPDFNetworkStreamFactory(t){createPDFNetworkStream=t}function getDocument(t){const e=new PDFDocumentLoadingTask;let s;if("string"==typeof t||t instanceof URL)s={url:t};else if((0,_util.isArrayBuffer)(t))s={data:t};else if(t instanceof PDFDataRangeTransport)s={range:t};else{if("object"!=typeof t)throw new Error("Invalid parameter in getDocument, need either string, URL, TypedArray, or parameter object.");if(!t.url&&!t.data&&!t.range)throw new Error("Invalid parameter object: need either .data, .range or .url");s=t}const n=Object.create(null);let i=null,a=null;for(const t in s){const e=s[t];switch(t){case"url":if("undefined"!=typeof window)try{n[t]=new URL(e,window.location).href;continue}catch(t){(0,_util.warn)(`Cannot create valid URL: "${t}".`)}else if("string"==typeof e||e instanceof URL){n[t]=e.toString();continue}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.");case"range":i=e;continue;case"worker":a=e;continue;case"data":if(_is_node.isNodeJS&&"undefined"!=typeof Buffer&&e instanceof Buffer)n[t]=new Uint8Array(e);else{if(e instanceof Uint8Array)break;if("string"==typeof e)n[t]=(0,_util.stringToBytes)(e);else if("object"!=typeof e||null===e||isNaN(e.length)){if(!(0,_util.isArrayBuffer)(e))throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.");n[t]=new Uint8Array(e)}else n[t]=new Uint8Array(e)}continue}n[t]=e}n.CMapReaderFactory=n.CMapReaderFactory||DefaultCMapReaderFactory;n.StandardFontDataFactory=n.StandardFontDataFactory||DefaultStandardFontDataFactory;n.ignoreErrors=!0!==n.stopAtErrors;n.fontExtraProperties=!0===n.fontExtraProperties;n.pdfBug=!0===n.pdfBug;n.enableXfa=!0===n.enableXfa;(!Number.isInteger(n.rangeChunkSize)||n.rangeChunkSize<1)&&(n.rangeChunkSize=DEFAULT_RANGE_CHUNK_SIZE);("string"!=typeof n.docBaseUrl||(0,_display_utils.isDataScheme)(n.docBaseUrl))&&(n.docBaseUrl=null);(!Number.isInteger(n.maxImageSize)||n.maxImageSize<-1)&&(n.maxImageSize=-1);"string"!=typeof n.cMapUrl&&(n.cMapUrl=null);"string"!=typeof n.standardFontDataUrl&&(n.standardFontDataUrl=null);"boolean"!=typeof n.useWorkerFetch&&(n.useWorkerFetch=n.CMapReaderFactory===_display_utils.DOMCMapReaderFactory&&n.StandardFontDataFactory===_display_utils.DOMStandardFontDataFactory);"boolean"!=typeof n.isEvalSupported&&(n.isEvalSupported=!0);"boolean"!=typeof n.isOffscreenCanvasSupported&&(n.isOffscreenCanvasSupported=!_is_node.isNodeJS);"boolean"!=typeof n.disableFontFace&&(n.disableFontFace=_is_node.isNodeJS);"boolean"!=typeof n.useSystemFonts&&(n.useSystemFonts=!_is_node.isNodeJS&&!n.disableFontFace);"object"==typeof n.ownerDocument&&null!==n.ownerDocument||(n.ownerDocument=globalThis.document);"boolean"!=typeof n.disableRange&&(n.disableRange=!1);"boolean"!=typeof n.disableStream&&(n.disableStream=!1);"boolean"!=typeof n.disableAutoFetch&&(n.disableAutoFetch=!1);(0,_util.setVerbosityLevel)(n.verbosity);if(!a){const t={verbosity:n.verbosity,port:_worker_options.GlobalWorkerOptions.workerPort};a=t.port?PDFWorker.fromPort(t):new PDFWorker(t);e._worker=a}const r=e.docId;a.promise.then((function(){if(e.destroyed)throw new Error("Loading aborted");const t=_fetchDocument(a,n,i,r),s=new Promise((function(t){let e;i?e=new _transport_stream.PDFDataTransportStream({length:n.length,initialData:n.initialData,progressiveDone:n.progressiveDone,contentDispositionFilename:n.contentDispositionFilename,disableRange:n.disableRange,disableStream:n.disableStream},i):n.data||(e=createPDFNetworkStream({url:n.url,length:n.length,httpHeaders:n.httpHeaders,withCredentials:n.withCredentials,rangeChunkSize:n.rangeChunkSize,disableRange:n.disableRange,disableStream:n.disableStream}));t(e)}));return Promise.all([t,s]).then((function([t,s]){if(e.destroyed)throw new Error("Loading aborted");const i=new _message_handler.MessageHandler(r,t,a.port),o=new WorkerTransport(i,e,s,n);e._transport=o;i.send("Ready",null)}))})).catch(e._capability.reject);return e}async function _fetchDocument(t,e,s,n){if(t.destroyed)throw new Error("Worker was destroyed");if(s){e.length=s.length;e.initialData=s.initialData;e.progressiveDone=s.progressiveDone;e.contentDispositionFilename=s.contentDispositionFilename}const i=await t.messageHandler.sendWithPromise("GetDocRequest",{docId:n,apiVersion:"3.2.146",data:e.data,password:e.password,disableAutoFetch:e.disableAutoFetch,rangeChunkSize:e.rangeChunkSize,length:e.length,docBaseUrl:e.docBaseUrl,enableXfa:e.enableXfa,evaluatorOptions:{maxImageSize:e.maxImageSize,disableFontFace:e.disableFontFace,ignoreErrors:e.ignoreErrors,isEvalSupported:e.isEvalSupported,isOffscreenCanvasSupported:e.isOffscreenCanvasSupported,fontExtraProperties:e.fontExtraProperties,useSystemFonts:e.useSystemFonts,cMapUrl:e.useWorkerFetch?e.cMapUrl:null,standardFontDataUrl:e.useWorkerFetch?e.standardFontDataUrl:null}});e.data&&(e.data=null);if(t.destroyed)throw new Error("Worker was destroyed");return i}class PDFDocumentLoadingTask{static#t=0;#e=null;constructor(){this._capability=(0,_util.createPromiseCapability)();this._transport=null;this._worker=null;this.docId="d"+PDFDocumentLoadingTask.#t++;this.destroyed=!1;this.onPassword=null;this.onProgress=null}get onUnsupportedFeature(){return this.#e}set onUnsupportedFeature(t){(0,_display_utils.deprecated)("The PDFDocumentLoadingTask onUnsupportedFeature property will be removed in the future.");this.#e=t}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;await(this._transport?.destroy());this._transport=null;if(this._worker){this._worker.destroy();this._worker=null}}}exports.PDFDocumentLoadingTask=PDFDocumentLoadingTask;class PDFDataRangeTransport{constructor(t,e,s=!1,n=null){this.length=t;this.initialData=e;this.progressiveDone=s;this.contentDispositionFilename=n;this._rangeListeners=[];this._progressListeners=[];this._progressiveReadListeners=[];this._progressiveDoneListeners=[];this._readyCapability=(0,_util.createPromiseCapability)()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then((()=>{for(const s of this._progressListeners)s(t,e)}))}onDataProgressiveRead(t){this._readyCapability.promise.then((()=>{for(const e of this._progressiveReadListeners)e(t)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(const t of this._progressiveDoneListeners)t()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){(0,_util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}exports.PDFDataRangeTransport=PDFDataRangeTransport;class PDFDocumentProxy{constructor(t,e){this._pdfInfo=t;this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get stats(){(0,_display_utils.deprecated)("The PDFDocumentProxy stats property will be removed in the future.");return this._transport.stats}get isPureXfa(){return(0,_util.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJavaScript(){return this._transport.getJavaScript()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig(){return this._transport.getOptionalContentConfig()}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}exports.PDFDocumentProxy=PDFDocumentProxy;class PDFPageProxy{constructor(t,e,s,n,i=!1){this._pageIndex=t;this._pageInfo=e;this._ownerDocument=n;this._transport=s;this._stats=i?new _display_utils.StatTimer:null;this._pdfBug=i;this.commonObjs=s.commonObjs;this.objs=new PDFObjects;this._bitmaps=new Set;this.cleanupAfterRender=!1;this.pendingCleanup=!1;this._intentStates=new Map;this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:n=0,dontFlip:i=!1}={}){return new _display_utils.PageViewport({viewBox:this.view,scale:t,rotation:e,offsetX:s,offsetY:n,dontFlip:i})}getAnnotations({intent:t="display"}={}){const e=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e.renderingIntent)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get isPureXfa(){return(0,_util.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:n=_util.AnnotationMode.ENABLE,transform:i=null,canvasFactory:a=null,background:r=null,optionalContentConfigPromise:o=null,annotationCanvasMap:l=null,pageColors:c=null,printAnnotationStorage:h=null}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,n,h);this.pendingCleanup=!1;o||(o=this._transport.getOptionalContentConfig());let u=this._intentStates.get(d.cacheKey);if(!u){u=Object.create(null);this._intentStates.set(d.cacheKey,u)}if(u.streamReaderCancelTimeout){clearTimeout(u.streamReaderCancelTimeout);u.streamReaderCancelTimeout=null}const p=a||new DefaultCanvasFactory({ownerDocument:this._ownerDocument}),g=!!(d.renderingIntent&_util.RenderingIntentFlag.PRINT);if(!u.displayReadyCapability){u.displayReadyCapability=(0,_util.createPromiseCapability)();u.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(d)}const complete=t=>{u.renderTasks.delete(m);(this.cleanupAfterRender||g)&&(this.pendingCleanup=!0);this._tryCleanup();if(t){m.capability.reject(t);this._abortOperatorList({intentState:u,reason:t instanceof Error?t:new Error(t)})}else m.capability.resolve();this._stats?.timeEnd("Rendering");this._stats?.timeEnd("Overall")},m=new InternalRenderTask({callback:complete,params:{canvasContext:t,viewport:e,transform:i,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:u.operatorList,pageIndex:this._pageIndex,canvasFactory:p,useRequestAnimationFrame:!g,pdfBug:this._pdfBug,pageColors:c});(u.renderTasks||=new Set).add(m);const f=m.task;Promise.all([u.displayReadyCapability.promise,o]).then((([t,e])=>{if(this.pendingCleanup)complete();else{this._stats?.time("Rendering");m.initializeGraphics({transparency:t,optionalContentConfig:e});m.operatorListChanged()}})).catch(complete);return f}getOperatorList({intent:t="display",annotationMode:e=_util.AnnotationMode.ENABLE,printAnnotationStorage:s=null}={}){const n=this._transport.getRenderingIntent(t,e,s,!0);let i,a=this._intentStates.get(n.cacheKey);if(!a){a=Object.create(null);this._intentStates.set(n.cacheKey,a)}if(!a.opListReadCapability){i=Object.create(null);i.operatorListChanged=function operatorListChanged(){if(a.operatorList.lastChunk){a.opListReadCapability.resolve(a.operatorList);a.renderTasks.delete(i)}};a.opListReadCapability=(0,_util.createPromiseCapability)();(a.renderTasks||=new Set).add(i);a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null};this._stats?.time("Page Request");this._pumpOperatorList(n)}return a.opListReadCapability.promise}streamTextContent({disableCombineTextItems:t=!1,includeMarkedContent:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,combineTextItems:!0!==t,includeMarkedContent:!0===e},{highWaterMark:100,size:t=>t.items.length})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then((t=>_xfa_text.XfaText.textContent(t)));const e=this.streamTextContent(t);return new Promise((function(t,s){const n=e.getReader(),i={items:[],styles:Object.create(null)};!function pump(){n.read().then((function({value:e,done:s}){if(s)t(i);else{Object.assign(i.styles,e.styles);i.items.push(...e.items);pump()}}),s)}()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values()){this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0});if(!e.opListReadCapability)for(const s of e.renderTasks){t.push(s.completed);s.cancel()}}this.objs.clear();for(const t of this._bitmaps)t.close();this._bitmaps.clear();this.pendingCleanup=!1;return Promise.all(t)}cleanup(t=!1){this.pendingCleanup=!0;return this._tryCleanup(t)}_tryCleanup(t=!1){if(!this.pendingCleanup)return!1;for(const{renderTasks:t,operatorList:e}of this._intentStates.values())if(t.size>0||!e.lastChunk)return!1;this._intentStates.clear();this.objs.clear();t&&this._stats&&(this._stats=new _display_utils.StatTimer);for(const t of this._bitmaps)t.close();this._bitmaps.clear();this.pendingCleanup=!1;return!0}_startRenderPage(t,e){const s=this._intentStates.get(e);if(s){this._stats?.timeEnd("Page Request");s.displayReadyCapability?.resolve(t)}}_renderPageChunk(t,e){for(let s=0,n=t.length;s{n.read().then((({value:t,done:e})=>{if(e)i.streamReader=null;else if(!this._transport.destroyed){this._renderPageChunk(t,i);pump()}}),(t=>{i.streamReader=null;if(!this._transport.destroyed){if(i.operatorList){i.operatorList.lastChunk=!0;for(const t of i.renderTasks)t.operatorListChanged();this._tryCleanup()}if(i.displayReadyCapability)i.displayReadyCapability.reject(t);else{if(!i.opListReadCapability)throw t;i.opListReadCapability.reject(t)}}}))};pump()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout){clearTimeout(t.streamReaderCancelTimeout);t.streamReaderCancelTimeout=null}if(!s){if(t.renderTasks.size>0)return;if(e instanceof _display_utils.RenderingCancelledException){let s=RENDERING_CANCELLED_TIMEOUT;e.extraDelay>0&&e.extraDelay<1e3&&(s+=e.extraDelay);t.streamReaderCancelTimeout=setTimeout((()=>{t.streamReaderCancelTimeout=null;this._abortOperatorList({intentState:t,reason:e,force:!0})}),s);return}}t.streamReader.cancel(new _util.AbortException(e.message)).catch((()=>{}));t.streamReader=null;if(!this._transport.destroyed){for(const[e,s]of this._intentStates)if(s===t){this._intentStates.delete(e);break}this.cleanup()}}}get stats(){return this._stats}}exports.PDFPageProxy=PDFPageProxy;class LoopbackPort{#s=[];#n=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e)};this.#n.then((()=>{for(const t of this.#s)t.call(this,s)}))}addEventListener(t,e){this.#s.push(e)}removeEventListener(t,e){const s=this.#s.indexOf(e);this.#s.splice(s,1)}terminate(){this.#s.length=0}}exports.LoopbackPort=LoopbackPort;const PDFWorkerUtil={isWorkerDisabled:!1,fallbackWorkerSrc:null,fakeWorkerId:0};exports.PDFWorkerUtil=PDFWorkerUtil;if(_is_node.isNodeJS&&"function"==typeof require){PDFWorkerUtil.isWorkerDisabled=!0;PDFWorkerUtil.fallbackWorkerSrc="./pdf.worker.js"}else if("object"==typeof document){const t=document?.currentScript?.src;t&&(PDFWorkerUtil.fallbackWorkerSrc=t.replace(/(\.(?:min\.)?js)(\?.*)?$/i,".worker$1$2"))}PDFWorkerUtil.isSameOrigin=function(t,e){let s;try{s=new URL(t);if(!s.origin||"null"===s.origin)return!1}catch(t){return!1}const n=new URL(e,s);return s.origin===n.origin};PDFWorkerUtil.createCDNWrapper=function(t){const e=`importScripts("${t}");`;return URL.createObjectURL(new Blob([e]))};class PDFWorker{static#i=new WeakMap;constructor({name:t=null,port:e=null,verbosity:s=(0,_util.getVerbosityLevel)()}={}){if(e&&PDFWorker.#i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");this.name=t;this.destroyed=!1;this.verbosity=s;this._readyCapability=(0,_util.createPromiseCapability)();this._port=null;this._webWorker=null;this._messageHandler=null;if(e){PDFWorker.#i.set(e,this);this._initializeFromPort(e)}else this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t;this._messageHandler=new _message_handler.MessageHandler("main","worker",t);this._messageHandler.on("ready",(function(){}));this._readyCapability.resolve();this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!PDFWorkerUtil.isWorkerDisabled&&!PDFWorker._mainThreadWorkerMessageHandler){let{workerSrc:t}=PDFWorker;try{PDFWorkerUtil.isSameOrigin(window.location.href,t)||(t=PDFWorkerUtil.createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t),s=new _message_handler.MessageHandler("main","worker",e),terminateEarly=()=>{e.removeEventListener("error",onWorkerError);s.destroy();e.terminate();this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},onWorkerError=()=>{this._webWorker||terminateEarly()};e.addEventListener("error",onWorkerError);s.on("test",(t=>{e.removeEventListener("error",onWorkerError);if(this.destroyed)terminateEarly();else if(t){this._messageHandler=s;this._port=e;this._webWorker=e;this._readyCapability.resolve();s.send("configure",{verbosity:this.verbosity})}else{this._setupFakeWorker();s.destroy();e.terminate()}}));s.on("ready",(t=>{e.removeEventListener("error",onWorkerError);if(this.destroyed)terminateEarly();else try{sendTest()}catch(t){this._setupFakeWorker()}}));const sendTest=()=>{const t=new Uint8Array;s.send("test",t,[t.buffer])};sendTest();return}catch(t){(0,_util.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){if(!PDFWorkerUtil.isWorkerDisabled){(0,_util.warn)("Setting up fake worker.");PDFWorkerUtil.isWorkerDisabled=!0}PDFWorker._setupFakeWorkerGlobal.then((t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new LoopbackPort;this._port=e;const s="fake"+PDFWorkerUtil.fakeWorkerId++,n=new _message_handler.MessageHandler(s+"_worker",s,e);t.setup(n,e);const i=new _message_handler.MessageHandler(s,s+"_worker",e);this._messageHandler=i;this._readyCapability.resolve();i.send("configure",{verbosity:this.verbosity})})).catch((t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))}))}destroy(){this.destroyed=!0;if(this._webWorker){this._webWorker.terminate();this._webWorker=null}PDFWorker.#i.delete(this._port);this._port=null;if(this._messageHandler){this._messageHandler.destroy();this._messageHandler=null}}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");return this.#i.has(t.port)?this.#i.get(t.port):new PDFWorker(t)}static get workerSrc(){if(_worker_options.GlobalWorkerOptions.workerSrc)return _worker_options.GlobalWorkerOptions.workerSrc;if(null!==PDFWorkerUtil.fallbackWorkerSrc){_is_node.isNodeJS||(0,_display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');return PDFWorkerUtil.fallbackWorkerSrc}throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _mainThreadWorkerMessageHandler(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch(t){return null}}static get _setupFakeWorkerGlobal(){const loader=async()=>{const mainWorkerMessageHandler=this._mainThreadWorkerMessageHandler;if(mainWorkerMessageHandler)return mainWorkerMessageHandler;if(_is_node.isNodeJS&&"function"==typeof require){const worker=eval("require")(this.workerSrc);return worker.WorkerMessageHandler}await(0,_display_utils.loadScript)(this.workerSrc);return window.pdfjsWorker.WorkerMessageHandler};return(0,_util.shadow)(this,"_setupFakeWorkerGlobal",loader())}}exports.PDFWorker=PDFWorker;class WorkerTransport{#a=null;#r=new Map;#o=new Map;#l=null;constructor(t,e,s,n){this.messageHandler=t;this.loadingTask=e;this.commonObjs=new PDFObjects;this.fontLoader=new _font_loader.FontLoader({onUnsupportedFeature:this._onUnsupportedFeature.bind(this),ownerDocument:n.ownerDocument,styleElement:n.styleElement});this._params=n;if(!n.useWorkerFetch){this.CMapReaderFactory=new n.CMapReaderFactory({baseUrl:n.cMapUrl,isCompressed:n.cMapPacked});this.StandardFontDataFactory=new n.StandardFontDataFactory({baseUrl:n.standardFontDataUrl})}this.destroyed=!1;this.destroyCapability=null;this._passwordCapability=null;this._networkStream=s;this._fullReader=null;this._lastProgress=null;this.downloadInfoCapability=(0,_util.createPromiseCapability)();this.setupMessageHandler()}get annotationStorage(){return(0,_util.shadow)(this,"annotationStorage",new _annotation_storage.AnnotationStorage)}get stats(){return this.#a}getRenderingIntent(t,e=_util.AnnotationMode.ENABLE,s=null,n=!1){let i=_util.RenderingIntentFlag.DISPLAY,a=null;switch(t){case"any":i=_util.RenderingIntentFlag.ANY;break;case"display":break;case"print":i=_util.RenderingIntentFlag.PRINT;break;default:(0,_util.warn)(`getRenderingIntent - invalid intent: ${t}`)}switch(e){case _util.AnnotationMode.DISABLE:i+=_util.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case _util.AnnotationMode.ENABLE:break;case _util.AnnotationMode.ENABLE_FORMS:i+=_util.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case _util.AnnotationMode.ENABLE_STORAGE:i+=_util.RenderingIntentFlag.ANNOTATIONS_STORAGE;a=(i&_util.RenderingIntentFlag.PRINT&&s instanceof _annotation_storage.PrintAnnotationStorage?s:this.annotationStorage).serializable;break;default:(0,_util.warn)(`getRenderingIntent - invalid annotationMode: ${e}`)}n&&(i+=_util.RenderingIntentFlag.OPLIST);return{renderingIntent:i,cacheKey:`${i}_${_annotation_storage.AnnotationStorage.getHash(a)}`,annotationStorageMap:a}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0;this.destroyCapability=(0,_util.createPromiseCapability)();this._passwordCapability&&this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const e of this.#r.values())t.push(e._destroy());this.#r.clear();this.#o.clear();this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);t.push(e);Promise.all(t).then((()=>{this.commonObjs.clear();this.fontLoader.clear();this.#l=null;this._getFieldObjectsPromise=null;this._hasJSActionsPromise=null;this._networkStream&&this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));if(this.messageHandler){this.messageHandler.destroy();this.messageHandler=null}this.destroyCapability.resolve()}),this.destroyCapability.reject);return this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",((t,e)=>{(0,_util.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available.");this._fullReader=this._networkStream.getFullReader();this._fullReader.onProgress=t=>{this._lastProgress={loaded:t.loaded,total:t.total}};e.onPull=()=>{this._fullReader.read().then((function({value:t,done:s}){if(s)e.close();else{(0,_util.assert)((0,_util.isArrayBuffer)(t),"GetReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{this._fullReader.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}));t.on("ReaderHeadersReady",(t=>{const s=(0,_util.createPromiseCapability)(),n=this._fullReader;n.headersReady.then((()=>{if(!n.isStreamingSupported||!n.isRangeSupported){this._lastProgress&&e.onProgress?.(this._lastProgress);n.onProgress=t=>{e.onProgress?.({loaded:t.loaded,total:t.total})}}s.resolve({isStreamingSupported:n.isStreamingSupported,isRangeSupported:n.isRangeSupported,contentLength:n.contentLength})}),s.reject);return s.promise}));t.on("GetRangeReader",((t,e)=>{(0,_util.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const s=this._networkStream.getRangeReader(t.begin,t.end);if(s){e.onPull=()=>{s.read().then((function({value:t,done:s}){if(s)e.close();else{(0,_util.assert)((0,_util.isArrayBuffer)(t),"GetRangeReader - expected an ArrayBuffer.");e.enqueue(new Uint8Array(t),1,[t])}})).catch((t=>{e.error(t)}))};e.onCancel=t=>{s.cancel(t);e.ready.catch((t=>{if(!this.destroyed)throw t}))}}else e.close()}));t.on("GetDoc",(({pdfInfo:t})=>{this._numPages=t.numPages;this._htmlForXfa=t.htmlForXfa;delete t.htmlForXfa;e._capability.resolve(new PDFDocumentProxy(t,this))}));t.on("DocException",(function(t){let s;switch(t.name){case"PasswordException":s=new _util.PasswordException(t.message,t.code);break;case"InvalidPDFException":s=new _util.InvalidPDFException(t.message);break;case"MissingPDFException":s=new _util.MissingPDFException(t.message);break;case"UnexpectedResponseException":s=new _util.UnexpectedResponseException(t.message,t.status);break;case"UnknownErrorException":s=new _util.UnknownErrorException(t.message,t.details);break;default:(0,_util.unreachable)("DocException - expected a valid Error.")}e._capability.reject(s)}));t.on("PasswordRequest",(t=>{this._passwordCapability=(0,_util.createPromiseCapability)();if(e.onPassword){const updatePassword=t=>{t instanceof Error?this._passwordCapability.reject(t):this._passwordCapability.resolve({password:t})};try{e.onPassword(updatePassword,t.code)}catch(t){this._passwordCapability.reject(t)}}else this._passwordCapability.reject(new _util.PasswordException(t.message,t.code));return this._passwordCapability.promise}));t.on("DataLoaded",(t=>{e.onProgress?.({loaded:t.length,total:t.length});this.downloadInfoCapability.resolve(t)}));t.on("StartRenderPage",(t=>{if(this.destroyed)return;this.#r.get(t.pageIndex)._startRenderPage(t.transparency,t.cacheKey)}));t.on("commonobj",(([e,s,n])=>{if(!this.destroyed&&!this.commonObjs.has(e))switch(s){case"Font":const i=this._params;if("error"in n){const t=n.error;(0,_util.warn)(`Error during font loading: ${t}`);this.commonObjs.resolve(e,t);break}let a=null;i.pdfBug&&globalThis.FontInspector?.enabled&&(a={registerFont(t,e){globalThis.FontInspector.fontAdded(t,e)}});const r=new _font_loader.FontFaceObject(n,{isEvalSupported:i.isEvalSupported,disableFontFace:i.disableFontFace,ignoreErrors:i.ignoreErrors,onUnsupportedFeature:this._onUnsupportedFeature.bind(this),fontRegistry:a});this.fontLoader.bind(r).catch((s=>t.sendWithPromise("FontFallback",{id:e}))).finally((()=>{!i.fontExtraProperties&&r.data&&(r.data=null);this.commonObjs.resolve(e,r)}));break;case"FontPath":case"Image":this.commonObjs.resolve(e,n);break;default:throw new Error(`Got unknown common object type ${s}`)}}));t.on("obj",(([t,e,s,n])=>{if(this.destroyed)return;const i=this.#r.get(e);if(!i.objs.has(t))switch(s){case"Image":i.objs.resolve(t,n);const e=8e6;if(n){let t;if(n.bitmap){const{bitmap:e,width:s,height:a}=n;t=s*a*4;i._bitmaps.add(e)}else t=n.data?.length||0;t>e&&(i.cleanupAfterRender=!0)}break;case"Pattern":i.objs.resolve(t,n);break;default:throw new Error(`Got unknown object type ${s}`)}}));t.on("DocProgress",(t=>{this.destroyed||e.onProgress?.({loaded:t.loaded,total:t.total})}));t.on("DocStats",(t=>{this.destroyed||(this.#a=Object.freeze({streamTypes:Object.freeze(t.streamTypes),fontTypes:Object.freeze(t.fontTypes)}))}));t.on("UnsupportedFeature",this._onUnsupportedFeature.bind(this));t.on("FetchBuiltInCMap",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.CMapReaderFactory?this.CMapReaderFactory.fetch(t):Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."))));t.on("FetchStandardFontData",(t=>this.destroyed?Promise.reject(new Error("Worker was destroyed.")):this.StandardFontDataFactory?this.StandardFontDataFactory.fetch(t):Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."))))}_onUnsupportedFeature({featureId:t}){this.destroyed||this.loadingTask.onUnsupportedFeature?.(t)}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&(0,_util.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:this.annotationStorage.serializable,filename:this._fullReader?.filename??null}).finally((()=>{this.annotationStorage.resetModified()}))}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#o.get(e);if(s)return s;const n=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then((t=>{if(this.destroyed)throw new Error("Transport destroyed");const s=new PDFPageProxy(e,t,this,this._params.ownerDocument,this._params.pdfBug);this.#r.set(e,s);return s}));this.#o.set(e,n);return n}getPageIndex(t){return"object"!=typeof t||null===t||!Number.isInteger(t.num)||t.num<0||!Number.isInteger(t.gen)||t.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen})}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this._getFieldObjectsPromise||=this.messageHandler.sendWithPromise("GetFieldObjects",null)}hasJSActions(){return this._hasJSActionsPromise||=this.messageHandler.sendWithPromise("HasJSActions",null)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return"string"!=typeof t?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getJavaScript(){return this.messageHandler.sendWithPromise("GetJavaScript",null)}getDocJSActions(){return this.messageHandler.sendWithPromise("GetDocJSActions",null)}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(){return this.messageHandler.sendWithPromise("GetOptionalContentConfig",null).then((t=>new _optional_content_config.OptionalContentConfig(t)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){return this.#l||=this.messageHandler.sendWithPromise("GetMetadata",null).then((t=>({info:t[0],metadata:t[1]?new _metadata.Metadata(t[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})))}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const t of this.#r.values()){if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`)}this.commonObjs.clear();t||this.fontLoader.clear();this.#l=null;this._getFieldObjectsPromise=null;this._hasJSActionsPromise=null}}get loadingParams(){const t=this._params;return(0,_util.shadow)(this,"loadingParams",{disableAutoFetch:t.disableAutoFetch,enableXfa:t.enableXfa})}}class PDFObjects{#c=Object.create(null);#h(t){const e=this.#c[t];return e||(this.#c[t]={capability:(0,_util.createPromiseCapability)(),data:null})}get(t,e=null){if(e){const s=this.#h(t);s.capability.promise.then((()=>e(s.data)));return null}const s=this.#c[t];if(!s?.capability.settled)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){return this.#c[t]?.capability.settled||!1}resolve(t,e=null){const s=this.#h(t);s.data=e;s.capability.resolve()}clear(){this.#c=Object.create(null)}}class RenderTask{#d=null;constructor(t){this.#d=t;this.onContinue=null}get promise(){return this.#d.capability.promise}cancel(t=0){this.#d.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#d.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#d;return t.form||t.canvas&&e?.size>0}}exports.RenderTask=RenderTask;class InternalRenderTask{static#u=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:n,annotationCanvasMap:i,operatorList:a,pageIndex:r,canvasFactory:o,useRequestAnimationFrame:l=!1,pdfBug:c=!1,pageColors:h=null}){this.callback=t;this.params=e;this.objs=s;this.commonObjs=n;this.annotationCanvasMap=i;this.operatorListIdx=null;this.operatorList=a;this._pageIndex=r;this.canvasFactory=o;this._pdfBug=c;this.pageColors=h;this.running=!1;this.graphicsReadyCallback=null;this.graphicsReady=!1;this._useRequestAnimationFrame=!0===l&&"undefined"!=typeof window;this.cancelled=!1;this.capability=(0,_util.createPromiseCapability)();this.task=new RenderTask(this);this._cancelBound=this.cancel.bind(this);this._continueBound=this._continue.bind(this);this._scheduleNextBound=this._scheduleNext.bind(this);this._nextBound=this._next.bind(this);this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(InternalRenderTask.#u.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");InternalRenderTask.#u.add(this._canvas)}if(this._pdfBug&&globalThis.StepperManager?.enabled){this.stepper=globalThis.StepperManager.create(this._pageIndex);this.stepper.init(this.operatorList);this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint()}const{canvasContext:s,viewport:n,transform:i,background:a}=this.params;this.gfx=new _canvas.CanvasGraphics(s,this.commonObjs,this.objs,this.canvasFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors);this.gfx.beginDrawing({transform:i,viewport:n,transparency:t,background:a});this.operatorListIdx=0;this.graphicsReady=!0;this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1;this.cancelled=!0;this.gfx?.endDrawing();this._canvas&&InternalRenderTask.#u.delete(this._canvas);this.callback(t||new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex+1}`,"canvas",e))}operatorListChanged(){if(this.graphicsReady){this.stepper?.updateOperatorList(this.operatorList);this.running||this._continue()}else this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound)}_continue(){this.running=!0;this.cancelled||(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?window.requestAnimationFrame((()=>{this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){if(!this.cancelled){this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper);if(this.operatorListIdx===this.operatorList.argsArray.length){this.running=!1;if(this.operatorList.lastChunk){this.gfx.endDrawing();this._canvas&&InternalRenderTask.#u.delete(this._canvas);this.callback()}}}}}const version="3.2.146";exports.version=version;const build="3fd2a3548";exports.build=build},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.PrintAnnotationStorage=e.AnnotationStorage=void 0;var n=s(1),i=s(4),a=s(8);class AnnotationStorage{#p=!1;#g=new Map;constructor(){this.onSetModified=null;this.onResetModified=null;this.onAnnotationEditor=null}getValue(t,e){const s=this.#g.get(t);return void 0===s?e:Object.assign(e,s)}getRawValue(t){return this.#g.get(t)}remove(t){this.#g.delete(t);0===this.#g.size&&this.resetModified();if("function"==typeof this.onAnnotationEditor){for(const t of this.#g.values())if(t instanceof i.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#g.get(t);let n=!1;if(void 0!==s){for(const[t,i]of Object.entries(e))if(s[t]!==i){n=!0;s[t]=i}}else{n=!0;this.#g.set(t,e)}n&&this.#m();e instanceof i.AnnotationEditor&&"function"==typeof this.onAnnotationEditor&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#g.has(t)}getAll(){return this.#g.size>0?(0,n.objectFromMap)(this.#g):null}get size(){return this.#g.size}#m(){if(!this.#p){this.#p=!0;"function"==typeof this.onSetModified&&this.onSetModified()}}resetModified(){if(this.#p){this.#p=!1;"function"==typeof this.onResetModified&&this.onResetModified()}}get print(){return new PrintAnnotationStorage(this)}get serializable(){if(0===this.#g.size)return null;const t=new Map;for(const[e,s]of this.#g){const n=s instanceof i.AnnotationEditor?s.serialize():s;n&&t.set(e,n)}return t}static getHash(t){if(!t)return"";const e=new a.MurmurHash3_64;for(const[s,n]of t)e.update(`${s}:${JSON.stringify(n)}`);return e.hexdigest()}}e.AnnotationStorage=AnnotationStorage;class PrintAnnotationStorage extends AnnotationStorage{#f=null;constructor(t){super();this.#f=structuredClone(t.serializable)}get print(){(0,n.unreachable)("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#f}}e.PrintAnnotationStorage=PrintAnnotationStorage},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.AnnotationEditor=void 0;var n=s(5),i=s(1);class AnnotationEditor{#b=this.focusin.bind(this);#A=this.focusout.bind(this);#_=!1;#y=!1;#v=!1;_uiManager=null;#S=AnnotationEditor._zIndex++;static _colorManager=new n.ColorManager;static _zIndex=1;constructor(t){this.constructor===AnnotationEditor&&(0,i.unreachable)("Cannot initialize AnnotationEditor.");this.parent=t.parent;this.id=t.id;this.width=this.height=null;this.pageIndex=t.parent.pageIndex;this.name=t.name;this.div=null;this._uiManager=t.uiManager;const{rotation:e,rawDims:{pageWidth:s,pageHeight:n,pageX:a,pageY:r}}=this.parent.viewport;this.rotation=e;this.pageDimensions=[s,n];this.pageTranslation=[a,r];const[o,l]=this.parentDimensions;this.x=t.x/o;this.y=t.y/l;this.isAttachedToDOM=!1}static get _defaultLineColor(){return(0,i.shadow)(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#S}setParent(t){if(null!==t){this.pageIndex=t.pageIndex;this.pageDimensions=t.pageDimensions}this.parent=t}focusin(t){this.#_?this.#_=!1:this.parent.setSelected(this)}focusout(t){if(!this.isAttachedToDOM)return;if(!t.relatedTarget?.closest(`#${this.id}`)){t.preventDefault();this.parent?.isMultipleSelection||this.commitOrRemove()}}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}dragstart(t){const e=this.parent.div.getBoundingClientRect();this.startX=t.clientX-e.x;this.startY=t.clientY-e.y;t.dataTransfer.setData("text/plain",this.id);t.dataTransfer.effectAllowed="move"}setAt(t,e,s,n){const[i,a]=this.parentDimensions;[s,n]=this.screenToPageTranslation(s,n);this.x=(t+s)/i;this.y=(e+n)/a;this.div.style.left=100*this.x+"%";this.div.style.top=100*this.y+"%"}translate(t,e){const[s,n]=this.parentDimensions;[t,e]=this.screenToPageTranslation(t,e);this.x+=t/s;this.y+=e/n;this.div.style.left=100*this.x+"%";this.div.style.top=100*this.y+"%"}screenToPageTranslation(t,e){switch(this.parentRotation){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return this._uiManager.viewParameters.rotation}get parentDimensions(){const{realScale:t}=this._uiManager.viewParameters,[e,s]=this.pageDimensions;return[e*t,s*t]}setDims(t,e){const[s,n]=this.parentDimensions;this.div.style.width=100*t/s+"%";this.div.style.height=100*e/n+"%"}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,n=s.endsWith("%"),i=e.endsWith("%");if(n&&i)return;const[a,r]=this.parentDimensions;n||(t.width=100*parseFloat(s)/a+"%");i||(t.height=100*parseFloat(e)/r+"%")}getInitialTranslation(){return[0,0]}render(){this.div=document.createElement("div");this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360);this.div.className=this.name;this.div.setAttribute("id",this.id);this.div.setAttribute("tabIndex",0);this.setInForeground();this.div.addEventListener("focusin",this.#b);this.div.addEventListener("focusout",this.#A);const[t,e]=this.getInitialTranslation();this.translate(t,e);(0,n.bindEvents)(this,this.div,["dragstart","pointerdown"]);return this.div}pointerdown(t){const{isMac:e}=i.FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)t.preventDefault();else{t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this);this.#_=!0}}getRect(t,e){const s=this.parentScale,[n,i]=this.pageDimensions,[a,r]=this.pageTranslation,o=t/s,l=e/s,c=this.x*n,h=this.y*i,d=this.width*n,u=this.height*i;switch(this.rotation){case 0:return[c+o+a,i-h-l-u+r,c+o+d+a,i-h-l+r];case 90:return[c+l+a,i-h+o+r,c+l+u+a,i-h+o+d+r];case 180:return[c-o-d+a,i-h+l+r,c-o+a,i-h+l+u+r];case 270:return[c-l-u+a,i-h-o-d+r,c-l+a,i-h-o+r];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,n,i,a]=t,r=i-s,o=a-n;switch(this.rotation){case 0:return[s,e-a,r,o];case 90:return[s,e-n,o,r];case 180:return[i,e-n,r,o];case 270:return[i,e-a,o,r];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){this.#v=!0}disableEditMode(){this.#v=!1}isInEditMode(){return this.#v}shouldGetKeyboardEvents(){return!1}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){this.div?.addEventListener("focusin",this.#b)}serialize(){(0,i.unreachable)("An editor must be serializable")}static deserialize(t,e,s){const n=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});n.rotation=t.rotation;const[i,a]=n.pageDimensions,[r,o,l,c]=n.getRectInCurrentCoords(t.rect,a);n.x=r/i;n.y=o/a;n.width=l/i;n.height=c/a;return n}remove(){this.div.removeEventListener("focusin",this.#b);this.div.removeEventListener("focusout",this.#A);this.isEmpty()||this.commit();this.parent.remove(this)}select(){this.div?.classList.add("selectedEditor")}unselect(){this.div?.classList.remove("selectedEditor")}updateParams(t,e){}disableEditing(){}enableEditing(){}get propertiesToUpdate(){return{}}get contentDiv(){return this.div}get isEditing(){return this.#y}set isEditing(t){this.#y=t;if(t){this.parent.setSelected(this);this.parent.setActiveEditor(this)}else this.parent.setActiveEditor(null)}}e.AnnotationEditor=AnnotationEditor},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.KeyboardManager=e.CommandManager=e.ColorManager=e.AnnotationEditorUIManager=void 0;e.bindEvents=function bindEvents(t,e,s){for(const n of s)e.addEventListener(n,t[n].bind(t))};e.opacityToHex=function opacityToHex(t){return Math.round(Math.min(255,Math.max(1,255*t))).toString(16).padStart(2,"0")};var n=s(1),i=s(6);class IdManager{#x=0;getId(){return`${n.AnnotationEditorPrefix}${this.#x++}`}}class CommandManager{#E=[];#C=!1;#P;#T=-1;constructor(t=128){this.#P=t}add({cmd:t,undo:e,mustExec:s,type:n=NaN,overwriteIfSameType:i=!1,keepUndo:a=!1}){s&&t();if(this.#C)return;const r={cmd:t,undo:e,type:n};if(-1===this.#T){this.#E.length>0&&(this.#E.length=0);this.#T=0;this.#E.push(r);return}if(i&&this.#E[this.#T].type===n){a&&(r.undo=this.#E[this.#T].undo);this.#E[this.#T]=r;return}const o=this.#T+1;if(o===this.#P)this.#E.splice(0,1);else{this.#T=o;ot===e[s])))return ColorManager._colorsMapping.get(t);return e}getHexCode(t){const e=this._colors.get(t);return e?n.Util.makeHexColor(...e):t}}e.ColorManager=ColorManager;class AnnotationEditorUIManager{#k=null;#F=new Map;#R=new Map;#M=null;#D=new CommandManager;#I=0;#O=null;#L=new Set;#N=null;#j=new IdManager;#U=!1;#B=n.AnnotationEditorType.NONE;#q=new Set;#W=this.copy.bind(this);#H=this.cut.bind(this);#G=this.paste.bind(this);#z=this.keydown.bind(this);#V=this.onEditingAction.bind(this);#X=this.onPageChanging.bind(this);#$=this.onScaleChanging.bind(this);#Y=this.onRotationChanging.bind(this);#K={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1};#J=null;static _keyboardManager=new KeyboardManager([[["ctrl+a","mac+meta+a"],AnnotationEditorUIManager.prototype.selectAll],[["ctrl+z","mac+meta+z"],AnnotationEditorUIManager.prototype.undo],[["ctrl+y","ctrl+shift+Z","mac+meta+shift+Z"],AnnotationEditorUIManager.prototype.redo],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete"],AnnotationEditorUIManager.prototype.delete],[["Escape","mac+Escape"],AnnotationEditorUIManager.prototype.unselectAll]]);constructor(t,e,s){this.#J=t;this.#N=e;this.#N._on("editingaction",this.#V);this.#N._on("pagechanging",this.#X);this.#N._on("scalechanging",this.#$);this.#N._on("rotationchanging",this.#Y);this.#M=s;this.viewParameters={realScale:i.PixelsPerInch.PDF_TO_CSS_UNITS,rotation:0}}destroy(){this.#Q();this.#N._off("editingaction",this.#V);this.#N._off("pagechanging",this.#X);this.#N._off("scalechanging",this.#$);this.#N._off("rotationchanging",this.#Y);for(const t of this.#R.values())t.destroy();this.#R.clear();this.#F.clear();this.#L.clear();this.#k=null;this.#q.clear();this.#D.destroy()}onPageChanging({pageNumber:t}){this.#I=t-1}focusMainContainer(){this.#J.focus()}addShouldRescale(t){this.#L.add(t)}removeShouldRescale(t){this.#L.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove();this.viewParameters.realScale=t*i.PixelsPerInch.PDF_TO_CSS_UNITS;for(const t of this.#L)t.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove();this.viewParameters.rotation=t}addToAnnotationStorage(t){t.isEmpty()||!this.#M||this.#M.has(t.id)||this.#M.setValue(t.id,t)}#Z(){this.#J.addEventListener("keydown",this.#z)}#Q(){this.#J.removeEventListener("keydown",this.#z)}#tt(){document.addEventListener("copy",this.#W);document.addEventListener("cut",this.#H);document.addEventListener("paste",this.#G)}#et(){document.removeEventListener("copy",this.#W);document.removeEventListener("cut",this.#H);document.removeEventListener("paste",this.#G)}copy(t){t.preventDefault();this.#k&&this.#k.commitOrRemove();if(!this.hasSelection)return;const e=[];for(const t of this.#q)t.isEmpty()||e.push(t.serialize());0!==e.length&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t);this.delete()}paste(t){t.preventDefault();let e=t.clipboardData.getData("application/pdfjs");if(!e)return;try{e=JSON.parse(e)}catch(t){(0,n.warn)(`paste: "${t.message}".`);return}if(!Array.isArray(e))return;this.unselectAll();const s=this.#R.get(this.#I);try{const t=[];for(const n of e){const e=s.deserialize(n);if(!e)return;t.push(e)}const cmd=()=>{for(const e of t)this.#st(e);this.#nt(t)},undo=()=>{for(const e of t)e.remove()};this.addCommands({cmd:cmd,undo:undo,mustExec:!0})}catch(t){(0,n.warn)(`paste: "${t.message}".`)}}keydown(t){this.getActive()?.shouldGetKeyboardEvents()||AnnotationEditorUIManager._keyboardManager.exec(this,t)}onEditingAction(t){["undo","redo","delete","selectAll"].includes(t.name)&&this[t.name]()}#it(t){Object.entries(t).some((([t,e])=>this.#K[t]!==e))&&this.#N.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#K,t)})}#at(t){this.#N.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){if(t){this.#Z();this.#tt();this.#it({isEditing:this.#B!==n.AnnotationEditorType.NONE,isEmpty:this.#rt(),hasSomethingToUndo:this.#D.hasSomethingToUndo(),hasSomethingToRedo:this.#D.hasSomethingToRedo(),hasSelectedEditor:!1})}else{this.#Q();this.#et();this.#it({isEditing:!1})}}registerEditorTypes(t){if(!this.#O){this.#O=t;for(const t of this.#O)this.#at(t.defaultPropertiesToUpdate)}}getId(){return this.#j.getId()}get currentLayer(){return this.#R.get(this.#I)}get currentPageIndex(){return this.#I}addLayer(t){this.#R.set(t.pageIndex,t);this.#U?t.enable():t.disable()}removeLayer(t){this.#R.delete(t.pageIndex)}updateMode(t){this.#B=t;if(t===n.AnnotationEditorType.NONE){this.setEditingState(!1);this.#ot()}else{this.setEditingState(!0);this.#lt();for(const e of this.#R.values())e.updateMode(t)}}updateToolbar(t){t!==this.#B&&this.#N.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#O){for(const s of this.#q)s.updateParams(t,e);for(const s of this.#O)s.updateDefaultParams(t,e)}}#lt(){if(!this.#U){this.#U=!0;for(const t of this.#R.values())t.enable()}}#ot(){this.unselectAll();if(this.#U){this.#U=!1;for(const t of this.#R.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#F.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#F.get(t)}addEditor(t){this.#F.set(t.id,t)}removeEditor(t){this.#F.delete(t.id);this.unselect(t);this.#M?.remove(t.id)}#st(t){const e=this.#R.get(t.pageIndex);e?e.addOrRebuild(t):this.addEditor(t)}setActiveEditor(t){if(this.#k!==t){this.#k=t;t&&this.#at(t.propertiesToUpdate)}}toggleSelected(t){if(this.#q.has(t)){this.#q.delete(t);t.unselect();this.#it({hasSelectedEditor:this.hasSelection})}else{this.#q.add(t);t.select();this.#at(t.propertiesToUpdate);this.#it({hasSelectedEditor:!0})}}setSelected(t){for(const e of this.#q)e!==t&&e.unselect();this.#q.clear();this.#q.add(t);t.select();this.#at(t.propertiesToUpdate);this.#it({hasSelectedEditor:!0})}isSelected(t){return this.#q.has(t)}unselect(t){t.unselect();this.#q.delete(t);this.#it({hasSelectedEditor:this.hasSelection})}get hasSelection(){return 0!==this.#q.size}undo(){this.#D.undo();this.#it({hasSomethingToUndo:this.#D.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#rt()})}redo(){this.#D.redo();this.#it({hasSomethingToUndo:!0,hasSomethingToRedo:this.#D.hasSomethingToRedo(),isEmpty:this.#rt()})}addCommands(t){this.#D.add(t);this.#it({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#rt()})}#rt(){if(0===this.#F.size)return!0;if(1===this.#F.size)for(const t of this.#F.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();if(!this.hasSelection)return;const t=[...this.#q];this.addCommands({cmd:()=>{for(const e of t)e.remove()},undo:()=>{for(const e of t)this.#st(e)},mustExec:!0})}commitOrRemove(){this.#k?.commitOrRemove()}#nt(t){this.#q.clear();for(const e of t)if(!e.isEmpty()){this.#q.add(e);e.select()}this.#it({hasSelectedEditor:!0})}selectAll(){for(const t of this.#q)t.commit();this.#nt(this.#F.values())}unselectAll(){if(this.#k)this.#k.commitOrRemove();else if(0!==this.#q.size){for(const t of this.#q)t.unselect();this.#q.clear();this.#it({hasSelectedEditor:!1})}}isActive(t){return this.#k===t}getActive(){return this.#k}getMode(){return this.#B}}e.AnnotationEditorUIManager=AnnotationEditorUIManager},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.StatTimer=e.RenderingCancelledException=e.PixelsPerInch=e.PageViewport=e.PDFDateString=e.DOMStandardFontDataFactory=e.DOMSVGFactory=e.DOMCanvasFactory=e.DOMCMapReaderFactory=e.AnnotationPrefix=void 0;e.deprecated=function deprecated(t){console.log("Deprecated API usage: "+t)};e.getColorValues=function getColorValues(t){const e=document.createElement("span");e.style.visibility="hidden";document.body.append(e);for(const s of t.keys()){e.style.color=s;const n=window.getComputedStyle(e).color;t.set(s,getRGB(n))}e.remove()};e.getCurrentTransform=function getCurrentTransform(t){const{a:e,b:s,c:n,d:i,e:a,f:r}=t.getTransform();return[e,s,n,i,a,r]};e.getCurrentTransformInverse=function getCurrentTransformInverse(t){const{a:e,b:s,c:n,d:i,e:a,f:r}=t.getTransform().invertSelf();return[e,s,n,i,a,r]};e.getFilenameFromUrl=function getFilenameFromUrl(t,e=!1){e||([t]=t.split(/[#?]/,1));return t.substring(t.lastIndexOf("/")+1)};e.getPdfFilenameFromUrl=function getPdfFilenameFromUrl(t,e="document.pdf"){if("string"!=typeof t)return e;if(isDataScheme(t)){(0,i.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');return e}const s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,n=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(t);let a=s.exec(n[1])||s.exec(n[2])||s.exec(n[3]);if(a){a=a[0];if(a.includes("%"))try{a=s.exec(decodeURIComponent(a))[0]}catch(t){}}return a||e};e.getRGB=getRGB;e.getXfaPageViewport=function getXfaPageViewport(t,{scale:e=1,rotation:s=0}){const{width:n,height:i}=t.attributes.style,a=[0,0,parseInt(n),parseInt(i)];return new PageViewport({viewBox:a,scale:e,rotation:s})};e.isDataScheme=isDataScheme;e.isPdfFile=function isPdfFile(t){return"string"==typeof t&&/\.pdf$/i.test(t)};e.isValidFetchUrl=isValidFetchUrl;e.loadScript=function loadScript(t,e=!1){return new Promise(((s,n)=>{const i=document.createElement("script");i.src=t;i.onload=function(t){e&&i.remove();s(t)};i.onerror=function(){n(new Error(`Cannot load script at: ${i.src}`))};(document.head||document.documentElement).append(i)}))};e.setLayerDimensions=function setLayerDimensions(t,e,s=!1,n=!0){if(e instanceof PageViewport){const{pageWidth:n,pageHeight:i}=e.rawDims,{style:a}=t,r=`calc(var(--scale-factor) * ${n}px)`,o=`calc(var(--scale-factor) * ${i}px)`;if(s&&e.rotation%180!=0){a.width=o;a.height=r}else{a.width=r;a.height=o}}n&&t.setAttribute("data-main-rotation",e.rotation)};var n=s(7),i=s(1);e.AnnotationPrefix="pdfjs_internal_id_";class PixelsPerInch{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}e.PixelsPerInch=PixelsPerInch;class DOMCanvasFactory extends n.BaseCanvasFactory{constructor({ownerDocument:t=globalThis.document}={}){super();this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");s.width=t;s.height=e;return s}}e.DOMCanvasFactory=DOMCanvasFactory;async function fetchData(t,e=!1){if(isValidFetchUrl(t,document.baseURI)){const s=await fetch(t);if(!s.ok)throw new Error(s.statusText);return e?new Uint8Array(await s.arrayBuffer()):(0,i.stringToBytes)(await s.text())}return new Promise(((s,n)=>{const a=new XMLHttpRequest;a.open("GET",t,!0);e&&(a.responseType="arraybuffer");a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){if(200===a.status||0===a.status){let t;e&&a.response?t=new Uint8Array(a.response):!e&&a.responseText&&(t=(0,i.stringToBytes)(a.responseText));if(t){s(t);return}}n(new Error(a.statusText))}};a.send(null)}))}class DOMCMapReaderFactory extends n.BaseCMapReaderFactory{_fetchData(t,e){return fetchData(t,this.isCompressed).then((t=>({cMapData:t,compressionType:e})))}}e.DOMCMapReaderFactory=DOMCMapReaderFactory;class DOMStandardFontDataFactory extends n.BaseStandardFontDataFactory{_fetchData(t){return fetchData(t,!0)}}e.DOMStandardFontDataFactory=DOMStandardFontDataFactory;class DOMSVGFactory extends n.BaseSVGFactory{_createSVG(t){return document.createElementNS("http://www.w3.org/2000/svg",t)}}e.DOMSVGFactory=DOMSVGFactory;class PageViewport{constructor({viewBox:t,scale:e,rotation:s,offsetX:n=0,offsetY:i=0,dontFlip:a=!1}){this.viewBox=t;this.scale=e;this.rotation=s;this.offsetX=n;this.offsetY=i;const r=(t[2]+t[0])/2,o=(t[3]+t[1])/2;let l,c,h,d,u,p,g,m;(s%=360)<0&&(s+=360);switch(s){case 180:l=-1;c=0;h=0;d=1;break;case 90:l=0;c=1;h=1;d=0;break;case 270:l=0;c=-1;h=-1;d=0;break;case 0:l=1;c=0;h=0;d=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}if(a){h=-h;d=-d}if(0===l){u=Math.abs(o-t[1])*e+n;p=Math.abs(r-t[0])*e+i;g=(t[3]-t[1])*e;m=(t[2]-t[0])*e}else{u=Math.abs(r-t[0])*e+n;p=Math.abs(o-t[1])*e+i;g=(t[2]-t[0])*e;m=(t[3]-t[1])*e}this.transform=[l*e,c*e,h*e,d*e,u-l*e*r-h*e*o,p-c*e*r-d*e*o];this.width=g;this.height=m}get rawDims(){const{viewBox:t}=this;return(0,i.shadow)(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:n=this.offsetY,dontFlip:i=!1}={}){return new PageViewport({viewBox:this.viewBox.slice(),scale:t,rotation:e,offsetX:s,offsetY:n,dontFlip:i})}convertToViewportPoint(t,e){return i.Util.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=i.Util.applyTransform([t[0],t[1]],this.transform),s=i.Util.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return i.Util.applyInverseTransform([t,e],this.transform)}}e.PageViewport=PageViewport;class RenderingCancelledException extends i.BaseException{constructor(t,e,s=0){super(t,"RenderingCancelledException");this.type=e;this.extraDelay=s}}e.RenderingCancelledException=RenderingCancelledException;function isDataScheme(t){const e=t.length;let s=0;for(;s=1&&n<=12?n-1:0;let i=parseInt(e[3],10);i=i>=1&&i<=31?i:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let o=parseInt(e[5],10);o=o>=0&&o<=59?o:0;let l=parseInt(e[6],10);l=l>=0&&l<=59?l:0;const c=e[7]||"Z";let h=parseInt(e[8],10);h=h>=0&&h<=23?h:0;let d=parseInt(e[9],10)||0;d=d>=0&&d<=59?d:0;if("-"===c){r+=h;o+=d}else if("+"===c){r-=h;o-=d}return new Date(Date.UTC(s,n,i,r,o,l))}};function getRGB(t){if(t.startsWith("#")){const e=parseInt(t.slice(1),16);return[(16711680&e)>>16,(65280&e)>>8,255&e]}if(t.startsWith("rgb("))return t.slice(4,-1).split(",").map((t=>parseInt(t)));if(t.startsWith("rgba("))return t.slice(5,-1).split(",").map((t=>parseInt(t))).slice(0,3);(0,i.warn)(`Not a valid color format: "${t}"`);return[0,0,0]}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.BaseStandardFontDataFactory=e.BaseSVGFactory=e.BaseCanvasFactory=e.BaseCMapReaderFactory=void 0;var n=s(1);class BaseCanvasFactory{constructor(){this.constructor===BaseCanvasFactory&&(0,n.unreachable)("Cannot initialize BaseCanvasFactory.")}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d")}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e;t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0;t.canvas.height=0;t.canvas=null;t.context=null}_createCanvas(t,e){(0,n.unreachable)("Abstract method `_createCanvas` called.")}}e.BaseCanvasFactory=BaseCanvasFactory;class BaseCMapReaderFactory{constructor({baseUrl:t=null,isCompressed:e=!1}){this.constructor===BaseCMapReaderFactory&&(0,n.unreachable)("Cannot initialize BaseCMapReaderFactory.");this.baseUrl=t;this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error('The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.');if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":""),s=this.isCompressed?n.CMapCompressionType.BINARY:n.CMapCompressionType.NONE;return this._fetchData(e,s).catch((t=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)}))}_fetchData(t,e){(0,n.unreachable)("Abstract method `_fetchData` called.")}}e.BaseCMapReaderFactory=BaseCMapReaderFactory;class BaseStandardFontDataFactory{constructor({baseUrl:t=null}){this.constructor===BaseStandardFontDataFactory&&(0,n.unreachable)("Cannot initialize BaseStandardFontDataFactory.");this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error('The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.');if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetchData(e).catch((t=>{throw new Error(`Unable to load font data at: ${e}`)}))}_fetchData(t){(0,n.unreachable)("Abstract method `_fetchData` called.")}}e.BaseStandardFontDataFactory=BaseStandardFontDataFactory;class BaseSVGFactory{constructor(){this.constructor===BaseSVGFactory&&(0,n.unreachable)("Cannot initialize BaseSVGFactory.")}create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const n=this._createSVG("svg:svg");n.setAttribute("version","1.1");if(!s){n.setAttribute("width",`${t}px`);n.setAttribute("height",`${e}px`)}n.setAttribute("preserveAspectRatio","none");n.setAttribute("viewBox",`0 0 ${t} ${e}`);return n}createElement(t){if("string"!=typeof t)throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){(0,n.unreachable)("Abstract method `_createSVG` called.")}}e.BaseSVGFactory=BaseSVGFactory},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.MurmurHash3_64=void 0;var n=s(1);const i=3285377520,a=4294901760,r=65535;e.MurmurHash3_64=class MurmurHash3_64{constructor(t){this.h1=t?4294967295&t:i;this.h2=t?4294967295&t:i}update(t){let e,s;if("string"==typeof t){e=new Uint8Array(2*t.length);s=0;for(let n=0,i=t.length;n>>8;e[s++]=255&i}}}else{if(!(0,n.isArrayBuffer)(t))throw new Error("Wrong data format in MurmurHash3_64_update. Input must be a string or array.");e=t.slice();s=e.byteLength}const i=s>>2,o=s-4*i,l=new Uint32Array(e.buffer,0,i);let c=0,h=0,d=this.h1,u=this.h2;const p=3432918353,g=461845907,m=11601,f=13715;for(let t=0;t>>17;c=c*g&a|c*f&r;d^=c;d=d<<13|d>>>19;d=5*d+3864292196}else{h=l[t];h=h*p&a|h*m&r;h=h<<15|h>>>17;h=h*g&a|h*f&r;u^=h;u=u<<13|u>>>19;u=5*u+3864292196}c=0;switch(o){case 3:c^=e[4*i+2]<<16;case 2:c^=e[4*i+1]<<8;case 1:c^=e[4*i];c=c*p&a|c*m&r;c=c<<15|c>>>17;c=c*g&a|c*f&r;1&i?d^=c:u^=c}this.h1=d;this.h2=u}hexdigest(){let t=this.h1,e=this.h2;t^=e>>>1;t=3981806797*t&a|36045*t&r;e=4283543511*e&a|(2950163797*(e<<16|t>>>16)&a)>>>16;t^=e>>>1;t=444984403*t&a|60499*t&r;e=3301882366*e&a|(3120437893*(e<<16|t>>>16)&a)>>>16;t^=e>>>1;return(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.FontLoader=e.FontFaceObject=void 0;var n=s(1),i=s(10);e.FontLoader=class FontLoader{constructor({onUnsupportedFeature:t,ownerDocument:e=globalThis.document,styleElement:s=null}){this._onUnsupportedFeature=t;this._document=e;this.nativeFontFaces=[];this.styleElement=null;this.loadingRequests=[];this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.push(t);this._document.fonts.add(t)}insertRule(t){if(!this.styleElement){this.styleElement=this._document.createElement("style");this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement)}const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.length=0;if(this.styleElement){this.styleElement.remove();this.styleElement=null}}async bind(t){if(t.attached||t.missingFile)return;t.attached=!0;if(this.isFontLoadingAPISupported){const e=t.createNativeFontFace();if(e){this.addNativeFontFace(e);try{await e.loaded}catch(s){this._onUnsupportedFeature({featureId:n.UNSUPPORTED_FEATURES.errorFontLoadNative});(0,n.warn)(`Failed to load font '${e.family}': '${s}'.`);t.disableFontFace=!0;throw s}}return}const e=t.createFontFaceRule();if(e){this.insertRule(e);if(this.isSyncFontLoadingSupported)return;await new Promise((e=>{const s=this._queueLoadingCallback(e);this._prepareFontLoadEvent(t,s)}))}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return(0,n.shadow)(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;(i.isNodeJS||"undefined"!=typeof navigator&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0);return(0,n.shadow)(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){const{loadingRequests:e}=this,s={done:!1,complete:function completeRequest(){(0,n.assert)(!s.done,"completeRequest() cannot be called twice.");s.done=!0;for(;e.length>0&&e[0].done;){const t=e.shift();setTimeout(t.callback,0)}},callback:t};e.push(s);return s}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return(0,n.shadow)(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function int32(t,e){return t.charCodeAt(e)<<24|t.charCodeAt(e+1)<<16|t.charCodeAt(e+2)<<8|255&t.charCodeAt(e+3)}function spliceString(t,e,s,n){return t.substring(0,e)+n+t.substring(e+s)}let s,i;const a=this._document.createElement("canvas");a.width=1;a.height=1;const r=a.getContext("2d");let o=0;const l=`lt${Date.now()}${this.loadTestFontId++}`;let c=this._loadTestFont;c=spliceString(c,976,l.length,l);const h=1482184792;let d=int32(c,16);for(s=0,i=l.length-3;s30){(0,n.warn)("Load test font never loaded.");e();return}r.font="30px "+t;r.fillText(".",0,20);r.getImageData(0,0,1,1).data[3]>0?e():setTimeout(isFontReady.bind(null,t,e))}(l,(()=>{p.remove();e.complete()}))}};e.FontFaceObject=class FontFaceObject{constructor(t,{isEvalSupported:e=!0,disableFontFace:s=!1,ignoreErrors:n=!1,onUnsupportedFeature:i,fontRegistry:a=null}){this.compiledGlyphs=Object.create(null);for(const e in t)this[e]=t[e];this.isEvalSupported=!1!==e;this.disableFontFace=!0===s;this.ignoreErrors=!0===n;this._onUnsupportedFeature=i;this.fontRegistry=a}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(this.cssFontInfo){const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`);t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}else t=new FontFace(this.loadedName,this.data,{});this.fontRegistry?.registerFont(this);return t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=(0,n.bytesToString)(this.data),e=`url(data:${this.mimetype};base64,${btoa(t)});`;let s;if(this.cssFontInfo){let t=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(t+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`);s=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${t}src:${e}}`}else s=`@font-face {font-family:"${this.loadedName}";src:${e}}`;this.fontRegistry?.registerFont(this,e);return s}getPathGenerator(t,e){if(void 0!==this.compiledGlyphs[e])return this.compiledGlyphs[e];let s;try{s=t.get(this.loadedName+"_path_"+e)}catch(t){if(!this.ignoreErrors)throw t;this._onUnsupportedFeature({featureId:n.UNSUPPORTED_FEATURES.errorFontGetPath});(0,n.warn)(`getPathGenerator - ignoring character: "${t}".`);return this.compiledGlyphs[e]=function(t,e){}}if(this.isEvalSupported&&n.FeatureTest.isEvalSupported){const t=[];for(const e of s){const s=void 0!==e.args?e.args.join(","):"";t.push("c.",e.cmd,"(",s,");\n")}return this.compiledGlyphs[e]=new Function("c","size",t.join(""))}return this.compiledGlyphs[e]=function(t,e){for(const n of s){"scale"===n.cmd&&(n.args=[e,-e]);t[n.cmd].apply(t,n.args)}}}}},(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});e.isNodeJS=void 0;const s=!("object"!=typeof process||process+""!="[object process]"||process.versions.nw||process.versions.electron&&process.type&&"browser"!==process.type);e.isNodeJS=s},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.CanvasGraphics=void 0;var n=s(1),i=s(6),a=s(12),r=s(13),o=s(10);const l=4096,c=o.isNodeJS&&"undefined"==typeof Path2D?-1:1e3,h=16;class CachedCanvases{constructor(t){this.canvasFactory=t;this.cache=Object.create(null)}getCanvas(t,e,s){let n;if(void 0!==this.cache[t]){n=this.cache[t];this.canvasFactory.reset(n,e,s)}else{n=this.canvasFactory.create(e,s);this.cache[t]=n}return n}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e);delete this.cache[t]}}}function drawImageAtIntegerCoords(t,e,s,n,a,r,o,l,c,h){const[d,u,p,g,m,f]=(0,i.getCurrentTransform)(t);if(0===u&&0===p){const i=o*d+m,b=Math.round(i),A=l*g+f,_=Math.round(A),y=(o+c)*d+m,v=Math.abs(Math.round(y)-b)||1,S=(l+h)*g+f,x=Math.abs(Math.round(S)-_)||1;t.setTransform(Math.sign(d),0,0,Math.sign(g),b,_);t.drawImage(e,s,n,a,r,0,0,v,x);t.setTransform(d,u,p,g,m,f);return[v,x]}if(0===d&&0===g){const i=l*p+m,b=Math.round(i),A=o*u+f,_=Math.round(A),y=(l+h)*p+m,v=Math.abs(Math.round(y)-b)||1,S=(o+c)*u+f,x=Math.abs(Math.round(S)-_)||1;t.setTransform(0,Math.sign(u),Math.sign(p),0,b,_);t.drawImage(e,s,n,a,r,0,0,x,v);t.setTransform(d,u,p,g,m,f);return[x,v]}t.drawImage(e,s,n,a,r,o,l,c,h);return[Math.hypot(d,u)*c,Math.hypot(p,g)*h]}class CanvasExtraState{constructor(t,e){this.alphaIsShape=!1;this.fontSize=0;this.fontSizeScale=1;this.textMatrix=n.IDENTITY_MATRIX;this.textMatrixScale=1;this.fontMatrix=n.FONT_IDENTITY_MATRIX;this.leading=0;this.x=0;this.y=0;this.lineX=0;this.lineY=0;this.charSpacing=0;this.wordSpacing=0;this.textHScale=1;this.textRenderingMode=n.TextRenderingMode.FILL;this.textRise=0;this.fillColor="#000000";this.strokeColor="#000000";this.patternFill=!1;this.fillAlpha=1;this.strokeAlpha=1;this.lineWidth=1;this.activeSMask=null;this.transferMaps=null;this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);t.clipBox=this.clipBox.slice();return t}setCurrentPoint(t,e){this.x=t;this.y=e}updatePathMinMax(t,e,s){[e,s]=n.Util.applyTransform([e,s],t);this.minX=Math.min(this.minX,e);this.minY=Math.min(this.minY,s);this.maxX=Math.max(this.maxX,e);this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=n.Util.applyTransform(e,t),i=n.Util.applyTransform(e.slice(2),t);this.minX=Math.min(this.minX,s[0],i[0]);this.minY=Math.min(this.minY,s[1],i[1]);this.maxX=Math.max(this.maxX,s[0],i[0]);this.maxY=Math.max(this.maxY,s[1],i[1])}updateScalingPathMinMax(t,e){n.Util.scaleMinMax(t,e);this.minX=Math.min(this.minX,e[0]);this.maxX=Math.max(this.maxX,e[1]);this.minY=Math.min(this.minY,e[2]);this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,a,r,o,l,c,h){const d=n.Util.bezierBoundingBox(e,s,i,a,r,o,l,c);if(h){h[0]=Math.min(h[0],d[0],d[2]);h[1]=Math.max(h[1],d[0],d[2]);h[2]=Math.min(h[2],d[1],d[3]);h[3]=Math.max(h[3],d[1],d[3])}else this.updateRectMinMax(t,d)}getPathBoundingBox(t=a.PathType.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===a.PathType.STROKE){e||(0,n.unreachable)("Stroke bounding box must include transform.");const t=n.Util.singularValueDecompose2dScale(e),i=t[0]*this.lineWidth/2,a=t[1]*this.lineWidth/2;s[0]-=i;s[1]-=a;s[2]+=i;s[3]+=a}return s}updateClipFromPath(){const t=n.Util.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t;this.minX=1/0;this.minY=1/0;this.maxX=0;this.maxY=0}getClippedPathBoundingBox(t=a.PathType.FILL,e=null){return n.Util.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function putBinaryImageData(t,e,s=null){if("undefined"!=typeof ImageData&&e instanceof ImageData){t.putImageData(e,0,0);return}const i=e.height,a=e.width,r=i%h,o=(i-r)/h,l=0===r?o:o+1,c=t.createImageData(a,h);let d,u=0;const p=e.data,g=c.data;let m,f,b,A,_,y,v,S;if(s)switch(s.length){case 1:_=s[0];y=s[0];v=s[0];S=s[0];break;case 4:_=s[0];y=s[1];v=s[2];S=s[3]}if(e.kind===n.ImageKind.GRAYSCALE_1BPP){const e=p.byteLength,s=new Uint32Array(g.buffer,0,g.byteLength>>2),i=s.length,A=a+7>>3;let _=4294967295,y=n.FeatureTest.isLittleEndian?4278190080:255;S&&255===S[0]&&0===S[255]&&([_,y]=[y,_]);for(m=0;mA?a:8*t-7,r=-8&i;let o=0,l=0;for(;n>=1}}for(;d=o){b=r;A=a*b}d=0;for(f=A;f--;){g[d++]=p[u++];g[d++]=p[u++];g[d++]=p[u++];g[d++]=255}if(e)for(let t=0;t>8;t[a-2]=t[a-2]*i+s*r>>8;t[a-1]=t[a-1]*i+n*r>>8}}}function composeSMaskAlpha(t,e,s){const n=t.length;for(let i=3;i>8]>>8:e[i]*n>>16}}function composeSMask(t,e,s,n){const i=n[0],a=n[1],r=n[2]-i,o=n[3]-a;if(0!==r&&0!==o){!function genericComposeSMask(t,e,s,n,i,a,r,o,l,c,h){const d=!!a,u=d?a[0]:0,p=d?a[1]:0,g=d?a[2]:0;let m;m="Luminosity"===i?composeSMaskLuminosity:composeSMaskAlpha;const f=Math.min(n,Math.ceil(1048576/s));for(let i=0;i(t/=255)<=.03928?t/12.92:((t+.055)/1.055)**2.4,o=Math.round(.2126*newComp(s)+.7152*newComp(a)+.0722*newComp(r));this.selectColor=(s,n,i)=>{const a=.2126*newComp(s)+.7152*newComp(n)+.0722*newComp(i);return Math.round(a)===o?e:t}}}this.ctx.fillStyle=this.backgroundColor||o;this.ctx.fillRect(0,0,a,r);this.ctx.restore();if(s){const t=this.cachedCanvases.getCanvas("transparent",a,r);this.compositeCtx=this.ctx;this.transparentCanvas=t.canvas;this.ctx=t.context;this.ctx.save();this.ctx.transform(...(0,i.getCurrentTransform)(this.compositeCtx))}this.ctx.save();resetCtxToDefault(this.ctx,this.foregroundColor);if(t){this.ctx.transform(...t);this.outputScaleX=t[0];this.outputScaleY=t[0]}this.ctx.transform(...e.transform);this.viewportScale=e.scale;this.baseTransform=(0,i.getCurrentTransform)(this.ctx)}executeOperatorList(t,e,s,i){const a=t.argsArray,r=t.fnArray;let o=e||0;const l=a.length;if(l===o)return o;const c=l-o>10&&"function"==typeof s,h=c?Date.now()+15:0;let d=0;const u=this.commonObjs,p=this.objs;let g;for(;;){if(void 0!==i&&o===i.nextBreakPoint){i.breakIt(o,s);return o}g=r[o];if(g!==n.OPS.dependency)this[g].apply(this,a[o]);else for(const t of a[o]){const e=t.startsWith("g_")?u:p;if(!e.has(t)){e.get(t,s);return o}}o++;if(o===l)return o;if(c&&++d>10){if(Date.now()>h){s();return o}d=0}}}#ct(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.ctx.restore();if(this.transparentCanvas){this.ctx=this.compositeCtx;this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.drawImage(this.transparentCanvas,0,0);this.ctx.restore();this.transparentCanvas=null}}endDrawing(){this.#ct();this.cachedCanvases.clear();this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear()}_scaleImage(t,e){const s=t.width,n=t.height;let i,a,r=Math.max(Math.hypot(e[0],e[1]),1),o=Math.max(Math.hypot(e[2],e[3]),1),l=s,c=n,h="prescale1";for(;r>2&&l>1||o>2&&c>1;){let e=l,s=c;if(r>2&&l>1){e=Math.ceil(l/2);r/=l/e}if(o>2&&c>1){s=Math.ceil(c/2);o/=c/s}i=this.cachedCanvases.getCanvas(h,e,s);a=i.context;a.clearRect(0,0,e,s);a.drawImage(t,0,0,l,c,0,0,e,s);t=i.canvas;l=e;c=s;h="prescale1"===h?"prescale2":"prescale1"}return{img:t,paintWidth:l,paintHeight:c}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:r}=t,o=this.current.fillColor,l=this.current.patternFill,c=(0,i.getCurrentTransform)(e);let h,d,u,p;if((t.bitmap||t.data)&&t.count>1){const e=t.bitmap||t.data.buffer;d=JSON.stringify(l?c:[c.slice(0,4),o]);h=this._cachedBitmapsMap.get(e);if(!h){h=new Map;this._cachedBitmapsMap.set(e,h)}const s=h.get(d);if(s&&!l){return{canvas:s,offsetX:Math.round(Math.min(c[0],c[2])+c[4]),offsetY:Math.round(Math.min(c[1],c[3])+c[5])}}u=s}if(!u){p=this.cachedCanvases.getCanvas("maskCanvas",s,r);putBinaryImageMask(p.context,t)}let g=n.Util.transform(c,[1/s,0,0,-1/r,0,0]);g=n.Util.transform(g,[1,0,0,1,0,-r]);const m=n.Util.applyTransform([0,0],g),f=n.Util.applyTransform([s,r],g),b=n.Util.normalizeRect([m[0],m[1],f[0],f[1]]),A=Math.round(b[2]-b[0])||1,_=Math.round(b[3]-b[1])||1,y=this.cachedCanvases.getCanvas("fillCanvas",A,_),v=y.context,S=Math.min(m[0],f[0]),x=Math.min(m[1],f[1]);v.translate(-S,-x);v.transform(...g);if(!u){u=this._scaleImage(p.canvas,(0,i.getCurrentTransformInverse)(v));u=u.img;h&&l&&h.set(d,u)}v.imageSmoothingEnabled=getImageSmoothingEnabled((0,i.getCurrentTransform)(v),t.interpolate);drawImageAtIntegerCoords(v,u,0,0,u.width,u.height,0,0,s,r);v.globalCompositeOperation="source-in";const E=n.Util.transform((0,i.getCurrentTransformInverse)(v),[1,0,0,1,-S,-x]);v.fillStyle=l?o.getPattern(e,this,E,a.PathType.FILL):o;v.fillRect(0,0,s,r);if(h&&!l){this.cachedCanvases.delete("fillCanvas");h.set(d,y.canvas)}return{canvas:y.canvas,offsetX:Math.round(S),offsetY:Math.round(x)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking=null);this.current.lineWidth=t;this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=d[t]}setLineJoin(t){this.ctx.lineJoin=u[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;if(void 0!==s.setLineDash){s.setLineDash(t);s.lineDashOffset=e}}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s;this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null;this.tempSMask=null;this.checkSMaskState();break;case"TR":this.current.transferMaps=s}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,n=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx;this.ctx=n.context;const a=this.ctx;a.setTransform(...(0,i.getCurrentTransform)(this.suspendedCtx));copyCtxState(this.suspendedCtx,a);!function mirrorContextOperations(t,e){if(t._removeMirroring)throw new Error("Context is already forwarding operations.");t.__originalSave=t.save;t.__originalRestore=t.restore;t.__originalRotate=t.rotate;t.__originalScale=t.scale;t.__originalTranslate=t.translate;t.__originalTransform=t.transform;t.__originalSetTransform=t.setTransform;t.__originalResetTransform=t.resetTransform;t.__originalClip=t.clip;t.__originalMoveTo=t.moveTo;t.__originalLineTo=t.lineTo;t.__originalBezierCurveTo=t.bezierCurveTo;t.__originalRect=t.rect;t.__originalClosePath=t.closePath;t.__originalBeginPath=t.beginPath;t._removeMirroring=()=>{t.save=t.__originalSave;t.restore=t.__originalRestore;t.rotate=t.__originalRotate;t.scale=t.__originalScale;t.translate=t.__originalTranslate;t.transform=t.__originalTransform;t.setTransform=t.__originalSetTransform;t.resetTransform=t.__originalResetTransform;t.clip=t.__originalClip;t.moveTo=t.__originalMoveTo;t.lineTo=t.__originalLineTo;t.bezierCurveTo=t.__originalBezierCurveTo;t.rect=t.__originalRect;t.closePath=t.__originalClosePath;t.beginPath=t.__originalBeginPath;delete t._removeMirroring};t.save=function ctxSave(){e.save();this.__originalSave()};t.restore=function ctxRestore(){e.restore();this.__originalRestore()};t.translate=function ctxTranslate(t,s){e.translate(t,s);this.__originalTranslate(t,s)};t.scale=function ctxScale(t,s){e.scale(t,s);this.__originalScale(t,s)};t.transform=function ctxTransform(t,s,n,i,a,r){e.transform(t,s,n,i,a,r);this.__originalTransform(t,s,n,i,a,r)};t.setTransform=function ctxSetTransform(t,s,n,i,a,r){e.setTransform(t,s,n,i,a,r);this.__originalSetTransform(t,s,n,i,a,r)};t.resetTransform=function ctxResetTransform(){e.resetTransform();this.__originalResetTransform()};t.rotate=function ctxRotate(t){e.rotate(t);this.__originalRotate(t)};t.clip=function ctxRotate(t){e.clip(t);this.__originalClip(t)};t.moveTo=function(t,s){e.moveTo(t,s);this.__originalMoveTo(t,s)};t.lineTo=function(t,s){e.lineTo(t,s);this.__originalLineTo(t,s)};t.bezierCurveTo=function(t,s,n,i,a,r){e.bezierCurveTo(t,s,n,i,a,r);this.__originalBezierCurveTo(t,s,n,i,a,r)};t.rect=function(t,s,n,i){e.rect(t,s,n,i);this.__originalRect(t,s,n,i)};t.closePath=function(){e.closePath();this.__originalClosePath()};t.beginPath=function(){e.beginPath();this.__originalBeginPath()}}(a,this.suspendedCtx);this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring();copyCtxState(this.ctx,this.suspendedCtx);this.ctx=this.suspendedCtx;this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;if(t){t[0]=Math.floor(t[0]);t[1]=Math.floor(t[1]);t[2]=Math.ceil(t[2]);t[3]=Math.ceil(t[3])}else t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask;composeSMask(this.suspendedCtx,e,this.ctx,t);this.ctx.save();this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height);this.ctx.restore()}save(){if(this.inSMaskMode){copyCtxState(this.ctx,this.suspendedCtx);this.suspendedCtx.save()}else this.ctx.save();const t=this.current;this.stateStack.push(t);this.current=t.clone()}restore(){0===this.stateStack.length&&this.inSMaskMode&&this.endSMaskMode();if(0!==this.stateStack.length){this.current=this.stateStack.pop();if(this.inSMaskMode){this.suspendedCtx.restore();copyCtxState(this.suspendedCtx,this.ctx)}else this.ctx.restore();this.checkSMaskState();this.pendingClip=null;this._cachedScaleForStroking=null;this._cachedGetSinglePixelWidth=null}}transform(t,e,s,n,i,a){this.ctx.transform(t,e,s,n,i,a);this._cachedScaleForStroking=null;this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const a=this.ctx,r=this.current;let o,l,c=r.x,h=r.y;const d=(0,i.getCurrentTransform)(a),u=0===d[0]&&0===d[3]||0===d[1]&&0===d[2],p=u?s.slice(0):null;for(let s=0,i=0,g=t.length;s100&&(c=100);this.current.fontSizeScale=e/c;this.ctx.font=`${o} ${r} ${c}px ${l}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t;this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e);this.moveText(t,e)}setTextMatrix(t,e,s,n,i,a){this.current.textMatrix=[t,e,s,n,i,a];this.current.textMatrixScale=Math.hypot(t,e);this.current.x=this.current.lineX=0;this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,s,a){const r=this.ctx,o=this.current,l=o.font,c=o.textRenderingMode,h=o.fontSize/o.fontSizeScale,d=c&n.TextRenderingMode.FILL_STROKE_MASK,u=!!(c&n.TextRenderingMode.ADD_TO_PATH_FLAG),p=o.patternFill&&!l.missingFile;let g;(l.disableFontFace||u||p)&&(g=l.getPathGenerator(this.commonObjs,t));if(l.disableFontFace||p){r.save();r.translate(e,s);r.beginPath();g(r,h);a&&r.setTransform(...a);d!==n.TextRenderingMode.FILL&&d!==n.TextRenderingMode.FILL_STROKE||r.fill();d!==n.TextRenderingMode.STROKE&&d!==n.TextRenderingMode.FILL_STROKE||r.stroke();r.restore()}else{d!==n.TextRenderingMode.FILL&&d!==n.TextRenderingMode.FILL_STROKE||r.fillText(t,e,s);d!==n.TextRenderingMode.STROKE&&d!==n.TextRenderingMode.FILL_STROKE||r.strokeText(t,e,s)}if(u){(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:(0,i.getCurrentTransform)(r),x:e,y:s,fontSize:h,addToPath:g})}}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1);t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let t=3;t0&&e[t]<255){s=!0;break}return(0,n.shadow)(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const r=e.fontSize;if(0===r)return;const o=this.ctx,l=e.fontSizeScale,c=e.charSpacing,h=e.wordSpacing,d=e.fontDirection,u=e.textHScale*d,p=t.length,g=s.vertical,m=g?1:-1,f=s.defaultVMetrics,b=r*e.fontMatrix[0],A=e.textRenderingMode===n.TextRenderingMode.FILL&&!s.disableFontFace&&!e.patternFill;o.save();o.transform(...e.textMatrix);o.translate(e.x,e.y+e.textRise);d>0?o.scale(u,-1):o.scale(u,1);let _;if(e.patternFill){o.save();const t=e.fillColor.getPattern(o,this,(0,i.getCurrentTransformInverse)(o),a.PathType.FILL);_=(0,i.getCurrentTransform)(o);o.restore();o.fillStyle=t}let y=e.lineWidth;const v=e.textMatrixScale;if(0===v||0===y){const t=e.textRenderingMode&n.TextRenderingMode.FILL_STROKE_MASK;t!==n.TextRenderingMode.STROKE&&t!==n.TextRenderingMode.FILL_STROKE||(y=this.getSinglePixelWidth())}else y/=v;if(1!==l){o.scale(l,l);y/=l}o.lineWidth=y;if(s.isInvalidPDFjsFont){const s=[];let n=0;for(const e of t){s.push(e.unicode);n+=e.width}o.fillText(s.join(""),0,0);e.x+=n*b*u;o.restore();this.compose();return}let S,x=0;for(S=0;S0){const t=1e3*o.measureText(a).width/r*l;if(Enew CanvasGraphics(t,this.commonObjs,this.objs,this.canvasFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new a.TilingPattern(t,s,this.ctx,r,n)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments);this.current.patternFill=!0}setStrokeRGBColor(t,e,s){const i=this.selectColor?.(t,e,s)||n.Util.makeHexColor(t,e,s);this.ctx.strokeStyle=i;this.current.strokeColor=i}setFillRGBColor(t,e,s){const i=this.selectColor?.(t,e,s)||n.Util.makeHexColor(t,e,s);this.ctx.fillStyle=i;this.current.fillColor=i;this.current.patternFill=!1}_getPattern(t,e=null){let s;if(this.cachedPatterns.has(t))s=this.cachedPatterns.get(t);else{s=(0,a.getShadingPattern)(this.objs.get(t));this.cachedPatterns.set(t,s)}e&&(s.matrix=e);return s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,(0,i.getCurrentTransformInverse)(e),a.PathType.SHADING);const r=(0,i.getCurrentTransformInverse)(e);if(r){const t=e.canvas,s=t.width,i=t.height,a=n.Util.applyTransform([0,0],r),o=n.Util.applyTransform([0,i],r),l=n.Util.applyTransform([s,0],r),c=n.Util.applyTransform([s,i],r),h=Math.min(a[0],o[0],l[0],c[0]),d=Math.min(a[1],o[1],l[1],c[1]),u=Math.max(a[0],o[0],l[0],c[0]),p=Math.max(a[1],o[1],l[1],c[1]);this.ctx.fillRect(h,d,u-h,p-d)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox());this.restore()}beginInlineImage(){(0,n.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,n.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible){this.save();this.baseTransformStack.push(this.baseTransform);Array.isArray(t)&&6===t.length&&this.transform(...t);this.baseTransform=(0,i.getCurrentTransform)(this.ctx);if(e){const t=e[2]-e[0],s=e[3]-e[1];this.ctx.rect(e[0],e[1],t,s);this.current.updateRectMinMax((0,i.getCurrentTransform)(this.ctx),e);this.clip();this.endPath()}}}paintFormXObjectEnd(){if(this.contentVisible){this.restore();this.baseTransform=this.baseTransformStack.pop()}}beginGroup(t){if(!this.contentVisible)return;this.save();if(this.inSMaskMode){this.endSMaskMode();this.current.activeSMask=null}const e=this.ctx;t.isolated||(0,n.info)("TODO: Support non-isolated groups.");t.knockout&&(0,n.warn)("Knockout groups not supported.");const s=(0,i.getCurrentTransform)(e);t.matrix&&e.transform(...t.matrix);if(!t.bbox)throw new Error("Bounding box is required.");let a=n.Util.getAxialAlignedBoundingBox(t.bbox,(0,i.getCurrentTransform)(e));const r=[0,0,e.canvas.width,e.canvas.height];a=n.Util.intersect(a,r)||[0,0,0,0];const o=Math.floor(a[0]),c=Math.floor(a[1]);let h=Math.max(Math.ceil(a[2])-o,1),d=Math.max(Math.ceil(a[3])-c,1),u=1,p=1;if(h>l){u=h/l;h=l}if(d>l){p=d/l;d=l}this.current.startNewPathAndClipBox([0,0,h,d]);let g="groupAt"+this.groupLevel;t.smask&&(g+="_smask_"+this.smaskCounter++%2);const m=this.cachedCanvases.getCanvas(g,h,d),f=m.context;f.scale(1/u,1/p);f.translate(-o,-c);f.transform(...s);if(t.smask)this.smaskStack.push({canvas:m.canvas,context:f,offsetX:o,offsetY:c,scaleX:u,scaleY:p,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null});else{e.setTransform(1,0,0,1,0,0);e.translate(o,c);e.scale(u,p);e.save()}copyCtxState(e,f);this.ctx=f;this.setGState([["BM","source-over"],["ca",1],["CA",1]]);this.groupStack.push(e);this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();this.ctx=s;this.ctx.imageSmoothingEnabled=!1;if(t.smask){this.tempSMask=this.smaskStack.pop();this.restore()}else{this.ctx.restore();const t=(0,i.getCurrentTransform)(this.ctx);this.restore();this.ctx.save();this.ctx.setTransform(...t);const s=n.Util.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],t);this.ctx.drawImage(e.canvas,0,0);this.ctx.restore();this.compose(s)}}beginAnnotation(t,e,s,a,r){this.#ct();resetCtxToDefault(this.ctx,this.foregroundColor);this.ctx.save();this.save();this.baseTransform&&this.ctx.setTransform(...this.baseTransform);if(Array.isArray(e)&&4===e.length){const a=e[2]-e[0],o=e[3]-e[1];if(r&&this.annotationCanvasMap){(s=s.slice())[4]-=e[0];s[5]-=e[1];(e=e.slice())[0]=e[1]=0;e[2]=a;e[3]=o;const[r,l]=n.Util.singularValueDecompose2dScale((0,i.getCurrentTransform)(this.ctx)),{viewportScale:c}=this,h=Math.ceil(a*this.outputScaleX*c),d=Math.ceil(o*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(h,d);const{canvas:u,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,u);this.annotationCanvas.savedCtx=this.ctx;this.ctx=p;this.ctx.setTransform(r,0,0,-l,0,o*l);resetCtxToDefault(this.ctx,this.foregroundColor)}else{resetCtxToDefault(this.ctx,this.foregroundColor);this.ctx.rect(e[0],e[1],a,o);this.ctx.clip();this.endPath()}}this.current=new CanvasExtraState(this.ctx.canvas.width,this.ctx.canvas.height);this.transform(...s);this.transform(...a)}endAnnotation(){if(this.annotationCanvas){this.ctx=this.annotationCanvas.savedCtx;delete this.annotationCanvas.savedCtx;delete this.annotationCanvas}}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;(t=this.getObject(t.data,t)).count=e;const s=this.ctx,n=this.processingType3;if(n){void 0===n.compiled&&(n.compiled=function compileType3Glyph(t){const{width:e,height:s}=t;if(e>c||s>c)return null;const n=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=e+1;let a,r,o,l=new Uint8Array(i*(s+1));const h=e+7&-8;let d=new Uint8Array(h*s),u=0;for(const e of t.data){let t=128;for(;t>0;){d[u++]=e&t?0:255;t>>=1}}let p=0;u=0;if(0!==d[u]){l[0]=1;++p}for(r=1;r>2)+(d[u+1]?4:0)+(d[u-h+1]?8:0);if(n[t]){l[o+r]=n[t];++p}u++}if(d[u-h]!==d[u]){l[o+r]=d[u]?2:4;++p}if(p>1e3)return null}u=h*(s-1);o=a*i;if(0!==d[u]){l[o]=8;++p}for(r=1;r1e3)return null;const g=new Int32Array([0,i,-1,0,-i,0,0,0,1]),m=new Path2D;for(a=0;p&&a<=s;a++){let t=a*i;const s=t+e;for(;t>4;l[t]&=r>>2|r<<2}m.lineTo(t%i,t/i|0);l[t]||--p}while(n!==t);--a}d=null;l=null;return function(t){t.save();t.scale(1/e,-1/s);t.translate(0,-s);t.fill(m);t.beginPath();t.restore()}}(t));if(n.compiled){n.compiled(s);return}}const i=this._createMaskCanvas(t),a=i.canvas;s.save();s.setTransform(1,0,0,1,0,0);s.drawImage(a,i.offsetX,i.offsetY);s.restore();this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,a=0,r,o){if(!this.contentVisible)return;t=this.getObject(t.data,t);const l=this.ctx;l.save();const c=(0,i.getCurrentTransform)(l);l.transform(e,s,a,r,0,0);const h=this._createMaskCanvas(t);l.setTransform(1,0,0,1,h.offsetX-c[4],h.offsetY-c[5]);for(let t=0,i=o.length;te?r/e:1;n=a>e?a/e:1}}this._cachedScaleForStroking=[s,n]}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[n,a]=this.getScaleForStroking();e.lineWidth=s||1;if(1===n&&1===a){e.stroke();return}let r,o,l;if(t){r=(0,i.getCurrentTransform)(e);o=e.getLineDash().slice();l=e.lineDashOffset}e.scale(n,a);const c=Math.max(n,a);e.setLineDash(e.getLineDash().map((t=>t/c)));e.lineDashOffset/=c;e.stroke();if(t){e.setTransform(...r);e.setLineDash(o);e.lineDashOffset=l}}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}e.CanvasGraphics=CanvasGraphics;for(const t in n.OPS)void 0!==CanvasGraphics.prototype[t]&&(CanvasGraphics.prototype[n.OPS[t]]=CanvasGraphics.prototype[t])},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.TilingPattern=e.PathType=void 0;e.getShadingPattern=function getShadingPattern(t){switch(t[0]){case"RadialAxial":return new RadialAxialShadingPattern(t);case"Mesh":return new MeshShadingPattern(t);case"Dummy":return new DummyShadingPattern}throw new Error(`Unknown IR type: ${t[0]}`)};var n=s(1),i=s(6),a=s(10);const r={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};e.PathType=r;function applyBoundingBox(t,e){if(!e||a.isNodeJS)return;const s=e[2]-e[0],n=e[3]-e[1],i=new Path2D;i.rect(e[0],e[1],s,n);t.clip(i)}class BaseShadingPattern{constructor(){this.constructor===BaseShadingPattern&&(0,n.unreachable)("Cannot initialize BaseShadingPattern.")}getPattern(){(0,n.unreachable)("Abstract method `getPattern` called.")}}class RadialAxialShadingPattern extends BaseShadingPattern{constructor(t){super();this._type=t[1];this._bbox=t[2];this._colorStops=t[3];this._p0=t[4];this._p1=t[5];this._r0=t[6];this._r1=t[7];this.matrix=null}_createGradient(t){let e;"axial"===this._type?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):"radial"===this._type&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const t of this._colorStops)e.addColorStop(t[0],t[1]);return e}getPattern(t,e,s,a){let o;if(a===r.STROKE||a===r.FILL){const r=e.current.getClippedPathBoundingBox(a,(0,i.getCurrentTransform)(t))||[0,0,0,0],l=Math.ceil(r[2]-r[0])||1,c=Math.ceil(r[3]-r[1])||1,h=e.cachedCanvases.getCanvas("pattern",l,c,!0),d=h.context;d.clearRect(0,0,d.canvas.width,d.canvas.height);d.beginPath();d.rect(0,0,d.canvas.width,d.canvas.height);d.translate(-r[0],-r[1]);s=n.Util.transform(s,[1,0,0,1,r[0],r[1]]);d.transform(...e.baseTransform);this.matrix&&d.transform(...this.matrix);applyBoundingBox(d,this._bbox);d.fillStyle=this._createGradient(d);d.fill();o=t.createPattern(h.canvas,"no-repeat");const u=new DOMMatrix(s);o.setTransform(u)}else{applyBoundingBox(t,this._bbox);o=this._createGradient(t)}return o}}function drawTriangle(t,e,s,n,i,a,r,o){const l=e.coords,c=e.colors,h=t.data,d=4*t.width;let u;if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=a;a=r;r=u}if(l[n+1]>l[i+1]){u=n;n=i;i=u;u=r;r=o;o=u}if(l[s+1]>l[n+1]){u=s;s=n;n=u;u=a;a=r;r=u}const p=(l[s]+e.offsetX)*e.scaleX,g=(l[s+1]+e.offsetY)*e.scaleY,m=(l[n]+e.offsetX)*e.scaleX,f=(l[n+1]+e.offsetY)*e.scaleY,b=(l[i]+e.offsetX)*e.scaleX,A=(l[i+1]+e.offsetY)*e.scaleY;if(g>=A)return;const _=c[a],y=c[a+1],v=c[a+2],S=c[r],x=c[r+1],E=c[r+2],C=c[o],P=c[o+1],T=c[o+2],w=Math.round(g),k=Math.round(A);let F,R,M,D,I,O,L,N;for(let t=w;t<=k;t++){if(tA?1:f===A?0:(f-t)/(f-A);F=m-(m-b)*e;R=S-(S-C)*e;M=x-(x-P)*e;D=E-(E-T)*e}let e;e=tA?1:(g-t)/(g-A);I=p-(p-b)*e;O=_-(_-C)*e;L=y-(y-P)*e;N=v-(v-T)*e;const s=Math.round(Math.min(F,I)),n=Math.round(Math.max(F,I));let i=d*t+4*s;for(let t=s;t<=n;t++){e=(F-t)/(F-I);e<0?e=0:e>1&&(e=1);h[i++]=R-(R-O)*e|0;h[i++]=M-(M-L)*e|0;h[i++]=D-(D-N)*e|0;h[i++]=255}}}function drawFigure(t,e,s){const n=e.coords,i=e.colors;let a,r;switch(e.type){case"lattice":const o=e.verticesPerRow,l=Math.floor(n.length/o)-1,c=o-1;for(a=0;a=n?i=n:s=i/t;return{scale:s,size:i}}clipBbox(t,e,s,n,a){const r=n-e,o=a-s;t.ctx.rect(e,s,r,o);t.current.updateRectMinMax((0,i.getCurrentTransform)(t.ctx),[e,s,n,a]);t.clip();t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,a=t.current;switch(e){case o:const t=this.ctx;i.fillStyle=t.fillStyle;i.strokeStyle=t.strokeStyle;a.fillColor=t.fillStyle;a.strokeColor=t.strokeStyle;break;case l:const r=n.Util.makeHexColor(s[0],s[1],s[2]);i.fillStyle=r;i.strokeStyle=r;a.fillColor=r;a.strokeColor=r;break;default:throw new n.FormatError(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let a=s;if(i!==r.SHADING){a=n.Util.transform(a,e.baseTransform);this.matrix&&(a=n.Util.transform(a,this.matrix))}const o=this.createPatternCanvas(e);let l=new DOMMatrix(a);l=l.translate(o.offsetX,o.offsetY);l=l.scale(1/o.scaleX,1/o.scaleY);const c=t.createPattern(o.canvas,"repeat");c.setTransform(l);return c}}e.TilingPattern=TilingPattern},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.applyMaskImageData=function applyMaskImageData({src:t,srcPos:e=0,dest:s,destPos:i=0,width:a,height:r,inverseDecode:o=!1}){const l=n.FeatureTest.isLittleEndian?4278190080:255,[c,h]=o?[0,l]:[l,0],d=a>>3,u=7&a,p=t.length;s=new Uint32Array(s.buffer);for(let n=0;n{Object.defineProperty(e,"__esModule",{value:!0});e.GlobalWorkerOptions=void 0;const s=Object.create(null);e.GlobalWorkerOptions=s;s.workerPort=void 0===s.workerPort?null:s.workerPort;s.workerSrc=void 0===s.workerSrc?"":s.workerSrc},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.MessageHandler=void 0;var n=s(1);const i=1,a=2,r=1,o=2,l=3,c=4,h=5,d=6,u=7,p=8;function wrapReason(t){t instanceof Error||"object"==typeof t&&null!==t||(0,n.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');switch(t.name){case"AbortException":return new n.AbortException(t.message);case"MissingPDFException":return new n.MissingPDFException(t.message);case"PasswordException":return new n.PasswordException(t.message,t.code);case"UnexpectedResponseException":return new n.UnexpectedResponseException(t.message,t.status);case"UnknownErrorException":return new n.UnknownErrorException(t.message,t.details);default:return new n.UnknownErrorException(t.message,t.toString())}}e.MessageHandler=class MessageHandler{constructor(t,e,s){this.sourceName=t;this.targetName=e;this.comObj=s;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=t=>{const e=t.data;if(e.targetName!==this.sourceName)return;if(e.stream){this._processStreamMessage(e);return}if(e.callback){const t=e.callbackId,s=this.callbackCapabilities[t];if(!s)throw new Error(`Cannot resolve callback ${t}`);delete this.callbackCapabilities[t];if(e.callback===i)s.resolve(e.data);else{if(e.callback!==a)throw new Error("Unexpected callback case");s.reject(wrapReason(e.reason))}return}const n=this.actionHandler[e.action];if(!n)throw new Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){const t=this.sourceName,r=e.sourceName;new Promise((function(t){t(n(e.data))})).then((function(n){s.postMessage({sourceName:t,targetName:r,callback:i,callbackId:e.callbackId,data:n})}),(function(n){s.postMessage({sourceName:t,targetName:r,callback:a,callbackId:e.callbackId,reason:wrapReason(n)})}))}else e.streamId?this._createStreamSink(e):n(e.data)};s.addEventListener("message",this._onComObjOnMessage)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,a=(0,n.createPromiseCapability)();this.callbackCapabilities[i]=a;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(t){a.reject(t)}return a.promise}sendWithStream(t,e,s,i){const a=this.streamId++,o=this.sourceName,l=this.targetName,c=this.comObj;return new ReadableStream({start:s=>{const r=(0,n.createPromiseCapability)();this.streamControllers[a]={controller:s,startCall:r,pullCall:null,cancelCall:null,isClosed:!1};c.postMessage({sourceName:o,targetName:l,action:t,streamId:a,data:e,desiredSize:s.desiredSize},i);return r.promise},pull:t=>{const e=(0,n.createPromiseCapability)();this.streamControllers[a].pullCall=e;c.postMessage({sourceName:o,targetName:l,stream:d,streamId:a,desiredSize:t.desiredSize});return e.promise},cancel:t=>{(0,n.assert)(t instanceof Error,"cancel must have a valid reason");const e=(0,n.createPromiseCapability)();this.streamControllers[a].cancelCall=e;this.streamControllers[a].isClosed=!0;c.postMessage({sourceName:o,targetName:l,stream:r,streamId:a,reason:wrapReason(t)});return e.promise}},s)}_createStreamSink(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,a=this.comObj,r=this,o=this.actionHandler[t.action],d={enqueue(t,r=1,o){if(this.isCancelled)return;const l=this.desiredSize;this.desiredSize-=r;if(l>0&&this.desiredSize<=0){this.sinkCapability=(0,n.createPromiseCapability)();this.ready=this.sinkCapability.promise}a.postMessage({sourceName:s,targetName:i,stream:c,streamId:e,chunk:t},o)},close(){if(!this.isCancelled){this.isCancelled=!0;a.postMessage({sourceName:s,targetName:i,stream:l,streamId:e});delete r.streamSinks[e]}},error(t){(0,n.assert)(t instanceof Error,"error must have a valid reason");if(!this.isCancelled){this.isCancelled=!0;a.postMessage({sourceName:s,targetName:i,stream:h,streamId:e,reason:wrapReason(t)})}},sinkCapability:(0,n.createPromiseCapability)(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};d.sinkCapability.resolve();d.ready=d.sinkCapability.promise;this.streamSinks[e]=d;new Promise((function(e){e(o(t.data,d))})).then((function(){a.postMessage({sourceName:s,targetName:i,stream:p,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:s,targetName:i,stream:p,streamId:e,reason:wrapReason(t)})}))}_processStreamMessage(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,a=this.comObj,g=this.streamControllers[e],m=this.streamSinks[e];switch(t.stream){case p:t.success?g.startCall.resolve():g.startCall.reject(wrapReason(t.reason));break;case u:t.success?g.pullCall.resolve():g.pullCall.reject(wrapReason(t.reason));break;case d:if(!m){a.postMessage({sourceName:s,targetName:i,stream:u,streamId:e,success:!0});break}m.desiredSize<=0&&t.desiredSize>0&&m.sinkCapability.resolve();m.desiredSize=t.desiredSize;new Promise((function(t){t(m.onPull&&m.onPull())})).then((function(){a.postMessage({sourceName:s,targetName:i,stream:u,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:s,targetName:i,stream:u,streamId:e,reason:wrapReason(t)})}));break;case c:(0,n.assert)(g,"enqueue should have stream controller");if(g.isClosed)break;g.controller.enqueue(t.chunk);break;case l:(0,n.assert)(g,"close should have stream controller");if(g.isClosed)break;g.isClosed=!0;g.controller.close();this._deleteStreamController(g,e);break;case h:(0,n.assert)(g,"error should have stream controller");g.controller.error(wrapReason(t.reason));this._deleteStreamController(g,e);break;case o:t.success?g.cancelCall.resolve():g.cancelCall.reject(wrapReason(t.reason));this._deleteStreamController(g,e);break;case r:if(!m)break;new Promise((function(e){e(m.onCancel&&m.onCancel(wrapReason(t.reason)))})).then((function(){a.postMessage({sourceName:s,targetName:i,stream:o,streamId:e,success:!0})}),(function(t){a.postMessage({sourceName:s,targetName:i,stream:o,streamId:e,reason:wrapReason(t)})}));m.sinkCapability.reject(wrapReason(t.reason));m.isCancelled=!0;delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async _deleteStreamController(t,e){await Promise.allSettled([t.startCall&&t.startCall.promise,t.pullCall&&t.pullCall.promise,t.cancelCall&&t.cancelCall.promise]);delete this.streamControllers[e]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.Metadata=void 0;var n=s(1);e.Metadata=class Metadata{#ht;#dt;constructor({parsedData:t,rawData:e}){this.#ht=t;this.#dt=e}getRaw(){return this.#dt}get(t){return this.#ht.get(t)??null}getAll(){return(0,n.objectFromMap)(this.#ht)}has(t){return this.#ht.has(t)}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.OptionalContentConfig=void 0;var n=s(1),i=s(8);const a=Symbol("INTERNAL");class OptionalContentGroup{#ut=!0;constructor(t,e){this.name=t;this.intent=e}get visible(){return this.#ut}_setVisible(t,e){t!==a&&(0,n.unreachable)("Internal method `_setVisible` called.");this.#ut=e}}e.OptionalContentConfig=class OptionalContentConfig{#pt=null;#gt=new Map;#mt=null;#ft=null;constructor(t){this.name=null;this.creator=null;if(null!==t){this.name=t.name;this.creator=t.creator;this.#ft=t.order;for(const e of t.groups)this.#gt.set(e.id,new OptionalContentGroup(e.name,e.intent));if("OFF"===t.baseState)for(const t of this.#gt.values())t._setVisible(a,!1);for(const e of t.on)this.#gt.get(e)._setVisible(a,!0);for(const e of t.off)this.#gt.get(e)._setVisible(a,!1);this.#mt=this.getHash()}}#bt(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i0?(0,n.objectFromMap)(this.#gt):null}getGroup(t){return this.#gt.get(t)||null}getHash(){if(null!==this.#pt)return this.#pt;const t=new i.MurmurHash3_64;for(const[e,s]of this.#gt)t.update(`${e}:${s.visible}`);return this.#pt=t.hexdigest()}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.PDFDataTransportStream=void 0;var n=s(1),i=s(6);e.PDFDataTransportStream=class PDFDataTransportStream{constructor(t,e){(0,n.assert)(e,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');this._queuedChunks=[];this._progressiveDone=t.progressiveDone||!1;this._contentDispositionFilename=t.contentDispositionFilename||null;const s=t.initialData;if(s?.length>0){const t=new Uint8Array(s).buffer;this._queuedChunks.push(t)}this._pdfDataRangeTransport=e;this._isStreamingSupported=!t.disableStream;this._isRangeSupported=!t.disableRange;this._contentLength=t.length;this._fullRequestReader=null;this._rangeReaders=[];this._pdfDataRangeTransport.addRangeListener(((t,e)=>{this._onReceiveData({begin:t,chunk:e})}));this._pdfDataRangeTransport.addProgressListener(((t,e)=>{this._onProgress({loaded:t,total:e})}));this._pdfDataRangeTransport.addProgressiveReadListener((t=>{this._onReceiveData({chunk:t})}));this._pdfDataRangeTransport.addProgressiveDoneListener((()=>{this._onProgressiveDone()}));this._pdfDataRangeTransport.transportReady()}_onReceiveData(t){const e=new Uint8Array(t.chunk).buffer;if(void 0===t.begin)this._fullRequestReader?this._fullRequestReader._enqueue(e):this._queuedChunks.push(e);else{const s=this._rangeReaders.some((function(s){if(s._begin!==t.begin)return!1;s._enqueue(e);return!0}));(0,n.assert)(s,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){void 0===t.total?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone();this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){(0,n.assert)(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;this._queuedChunks=null;return new PDFDataTransportStreamReader(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new PDFDataTransportStreamRangeReader(this,t,e);this._pdfDataRangeTransport.requestDataRange(t,e);this._rangeReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}};class PDFDataTransportStreamReader{constructor(t,e,s=!1,n=null){this._stream=t;this._done=s||!1;this._filename=(0,i.isPdfFile)(n)?n:null;this._queuedChunks=e||[];this._loaded=0;for(const t of this._queuedChunks)this._loaded+=t.byteLength;this._requests=[];this._headersReady=Promise.resolve();t._fullRequestReader=this;this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length>0){this._requests.shift().resolve({value:t,done:!1})}else this._queuedChunks.push(t);this._loaded+=t.byteLength}}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0){return{value:this._queuedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=(0,n.createPromiseCapability)();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class PDFDataTransportStreamRangeReader{constructor(t,e,s){this._stream=t;this._begin=e;this._end=s;this._queuedChunk=null;this._requests=[];this._done=!1;this.onProgress=null}_enqueue(t){if(!this._done){if(0===this._requests.length)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0;this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=(0,n.createPromiseCapability)();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._stream._removeRangeReader(this)}}},(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0});e.XfaText=void 0;class XfaText{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};!function walk(t){if(!t)return;let s=null;const n=t.name;if("#text"===n)s=t.value;else{if(!XfaText.shouldBuildText(n))return;t?.attributes?.textContent?s=t.attributes.textContent:t.value&&(s=t.value)}null!==s&&e.push({str:s});if(t.children)for(const e of t.children)walk(e)}(t);return s}static shouldBuildText(t){return!("textarea"===t||"input"===t||"option"===t||"select"===t)}}e.XfaText=XfaText},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.NodeStandardFontDataFactory=e.NodeCanvasFactory=e.NodeCMapReaderFactory=void 0;var n=s(7);const fetchData=function(t){return new Promise(((e,s)=>{require("fs").readFile(t,((t,n)=>{!t&&n?e(new Uint8Array(n)):s(new Error(t))}))}))};class NodeCanvasFactory extends n.BaseCanvasFactory{_createCanvas(t,e){return require("canvas").createCanvas(t,e)}}e.NodeCanvasFactory=NodeCanvasFactory;class NodeCMapReaderFactory extends n.BaseCMapReaderFactory{_fetchData(t,e){return fetchData(t).then((t=>({cMapData:t,compressionType:e})))}}e.NodeCMapReaderFactory=NodeCMapReaderFactory;class NodeStandardFontDataFactory extends n.BaseStandardFontDataFactory{_fetchData(t){return fetchData(t)}}e.NodeStandardFontDataFactory=NodeStandardFontDataFactory},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.TextLayerRenderTask=void 0;e.renderTextLayer=function renderTextLayer(t){if(!t.textContentSource&&(t.textContent||t.textContentStream)){(0,i.deprecated)("The TextLayerRender `textContent`/`textContentStream` parameters will be removed in the future, please use `textContentSource` instead.");t.textContentSource=t.textContent||t.textContentStream}const e=new TextLayerRenderTask(t);e._render();return e};e.updateTextLayer=function updateTextLayer({container:t,viewport:e,textDivs:s,textDivProperties:n,isOffscreenCanvasSupported:a,mustRotate:r=!0,mustRescale:o=!0}){r&&(0,i.setLayerDimensions)(t,{rotation:e.rotation});if(o){const t=getCtx(0,a),i={prevFontSize:null,prevFontFamily:null,div:null,scale:e.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:t};for(const t of s){i.properties=n.get(t);i.div=t;layout(i)}}};var n=s(1),i=s(6);const a=30,r=new Map;function getCtx(t,e){let s;if(e&&n.FeatureTest.isOffscreenCanvasSupported)s=new OffscreenCanvas(t,t).getContext("2d",{alpha:!1});else{const e=document.createElement("canvas");e.width=e.height=t;s=e.getContext("2d",{alpha:!1})}return s}function appendText(t,e,s){const i=document.createElement("span"),o={angle:0,canvasWidth:0,hasText:""!==e.str,hasEOL:e.hasEOL,fontSize:0};t._textDivs.push(i);const l=n.Util.transform(t._transform,e.transform);let c=Math.atan2(l[1],l[0]);const h=s[e.fontName];h.vertical&&(c+=Math.PI/2);const d=Math.hypot(l[2],l[3]),u=d*function getAscent(t,e){const s=r.get(t);if(s)return s;const n=getCtx(a,e);n.font=`30px ${t}`;const i=n.measureText("");let o=i.fontBoundingBoxAscent,l=Math.abs(i.fontBoundingBoxDescent);if(o){const e=o/(o+l);r.set(t,e);n.canvas.width=n.canvas.height=0;return e}n.strokeStyle="red";n.clearRect(0,0,a,a);n.strokeText("g",0,0);let c=n.getImageData(0,0,a,a).data;l=0;for(let t=c.length-1-3;t>=0;t-=4)if(c[t]>0){l=Math.ceil(t/4/a);break}n.clearRect(0,0,a,a);n.strokeText("A",0,a);c=n.getImageData(0,0,a,a).data;o=0;for(let t=0,e=c.length;t0){o=a-Math.floor(t/4/a);break}n.canvas.width=n.canvas.height=0;if(o){const e=o/(o+l);r.set(t,e);return e}r.set(t,.8);return.8}(h.fontFamily,t._isOffscreenCanvasSupported);let p,g;if(0===c){p=l[4];g=l[5]-u}else{p=l[4]+u*Math.sin(c);g=l[5]-u*Math.cos(c)}const m="calc(var(--scale-factor)*",f=i.style;if(t._container===t._rootContainer){f.left=`${(100*p/t._pageWidth).toFixed(2)}%`;f.top=`${(100*g/t._pageHeight).toFixed(2)}%`}else{f.left=`${m}${p.toFixed(2)}px)`;f.top=`${m}${g.toFixed(2)}px)`}f.fontSize=`${m}${d.toFixed(2)}px)`;f.fontFamily=h.fontFamily;o.fontSize=d;i.setAttribute("role","presentation");i.textContent=e.str;i.dir=e.dir;t._fontInspectorEnabled&&(i.dataset.fontName=e.fontName);0!==c&&(o.angle=c*(180/Math.PI));let b=!1;if(e.str.length>1)b=!0;else if(" "!==e.str&&e.transform[0]!==e.transform[3]){const t=Math.abs(e.transform[0]),s=Math.abs(e.transform[3]);t!==s&&Math.max(t,s)/Math.min(t,s)>1.5&&(b=!0)}b&&(o.canvasWidth=h.vertical?e.height:e.width);t._textDivProperties.set(i,o);t._isReadableStream&&t._layoutText(i)}function layout(t){const{div:e,scale:s,properties:n,ctx:i,prevFontSize:a,prevFontFamily:r}=t,{style:o}=e;let l="";if(0!==n.canvasWidth&&n.hasText){const{fontFamily:c}=o,{canvasWidth:h,fontSize:d}=n;if(a!==d||r!==c){i.font=`${d*s}px ${c}`;t.prevFontSize=d;t.prevFontFamily=c}const{width:u}=i.measureText(e.textContent);u>0&&(l=`scaleX(${h*s/u})`)}0!==n.angle&&(l=`rotate(${n.angle}deg) ${l}`);l.length>0&&(o.transform=l)}class TextLayerRenderTask{constructor({textContentSource:t,container:e,viewport:s,textDivs:a,textDivProperties:r,textContentItemsStr:o,isOffscreenCanvasSupported:l}){this._textContentSource=t;this._isReadableStream=t instanceof ReadableStream;this._container=this._rootContainer=e;this._textDivs=a||[];this._textContentItemsStr=o||[];this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled;this._reader=null;this._textDivProperties=r||new WeakMap;this._canceled=!1;this._capability=(0,n.createPromiseCapability)();this._layoutTextParams={prevFontSize:null,prevFontFamily:null,div:null,scale:s.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:getCtx(0,l)};const{pageWidth:c,pageHeight:h,pageX:d,pageY:u}=s.rawDims;this._transform=[1,0,0,-1,-d,u+h];this._pageWidth=c;this._pageHeight=h;(0,i.setLayerDimensions)(e,s);this._capability.promise.finally((()=>{this._layoutTextParams=null})).catch((()=>{}))}get promise(){return this._capability.promise}cancel(){this._canceled=!0;if(this._reader){this._reader.cancel(new n.AbortException("TextLayer task cancelled.")).catch((()=>{}));this._reader=null}this._capability.reject(new n.AbortException("TextLayer task cancelled."))}_processItems(t,e){for(const s of t)if(void 0!==s.str){this._textContentItemsStr.push(s.str);appendText(this,s,e)}else if("beginMarkedContentProps"===s.type||"beginMarkedContent"===s.type){const t=this._container;this._container=document.createElement("span");this._container.classList.add("markedContent");null!==s.id&&this._container.setAttribute("id",`${s.id}`);t.append(this._container)}else"endMarkedContent"===s.type&&(this._container=this._container.parentNode)}_layoutText(t){const e=this._layoutTextParams.properties=this._textDivProperties.get(t);this._layoutTextParams.div=t;layout(this._layoutTextParams);e.hasText&&this._container.append(t);if(e.hasEOL){const t=document.createElement("br");t.setAttribute("role","presentation");this._container.append(t)}}_render(){const t=(0,n.createPromiseCapability)();let e=Object.create(null);if(this._isReadableStream){const pump=()=>{this._reader.read().then((({value:s,done:n})=>{if(n)t.resolve();else{Object.assign(e,s.styles);this._processItems(s.items,e);pump()}}),t.reject)};this._reader=this._textContentSource.getReader();pump()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{const{items:e,styles:s}=this._textContentSource;this._processItems(e,s);t.resolve()}}t.promise.then((()=>{e=null;!function render(t){if(t._canceled)return;const e=t._textDivs,s=t._capability;if(e.length>1e5)s.resolve();else{if(!t._isReadableStream)for(const s of e)t._layoutText(s);s.resolve()}}(this)}),this._capability.reject)}}e.TextLayerRenderTask=TextLayerRenderTask},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.AnnotationEditorLayer=void 0;var n=s(1),i=s(5),a=s(23),r=s(24),o=s(6);class AnnotationEditorLayer{#At;#_t=!1;#yt=this.pointerup.bind(this);#vt=this.pointerdown.bind(this);#St=new Map;#xt=!1;#Et=!1;#Ct;static _initialized=!1;constructor(t){if(!AnnotationEditorLayer._initialized){AnnotationEditorLayer._initialized=!0;a.FreeTextEditor.initialize(t.l10n);r.InkEditor.initialize(t.l10n)}t.uiManager.registerEditorTypes([a.FreeTextEditor,r.InkEditor]);this.#Ct=t.uiManager;this.pageIndex=t.pageIndex;this.div=t.div;this.#At=t.accessibilityManager;this.#Ct.addLayer(this)}updateToolbar(t){this.#Ct.updateToolbar(t)}updateMode(t=this.#Ct.getMode()){this.#Pt();if(t===n.AnnotationEditorType.INK){this.addInkEditorIfNeeded(!1);this.disableClick()}else this.enableClick();this.#Ct.unselectAll();this.div.classList.toggle("freeTextEditing",t===n.AnnotationEditorType.FREETEXT);this.div.classList.toggle("inkEditing",t===n.AnnotationEditorType.INK)}addInkEditorIfNeeded(t){if(!t&&this.#Ct.getMode()!==n.AnnotationEditorType.INK)return;if(!t)for(const t of this.#St.values())if(t.isEmpty()){t.setInBackground();return}this.#Tt({offsetX:0,offsetY:0}).setInBackground()}setEditingState(t){this.#Ct.setEditingState(t)}addCommands(t){this.#Ct.addCommands(t)}enable(){this.div.style.pointerEvents="auto";for(const t of this.#St.values())t.enableEditing()}disable(){this.div.style.pointerEvents="none";for(const t of this.#St.values())t.disableEditing()}setActiveEditor(t){this.#Ct.getActive()!==t&&this.#Ct.setActiveEditor(t)}enableClick(){this.div.addEventListener("pointerdown",this.#vt);this.div.addEventListener("pointerup",this.#yt)}disableClick(){this.div.removeEventListener("pointerdown",this.#vt);this.div.removeEventListener("pointerup",this.#yt)}attach(t){this.#St.set(t.id,t)}detach(t){this.#St.delete(t.id);this.#At?.removePointerInTextLayer(t.contentDiv)}remove(t){this.#Ct.removeEditor(t);this.detach(t);t.div.style.display="none";setTimeout((()=>{t.div.style.display="";t.div.remove();t.isAttachedToDOM=!1;document.activeElement===document.body&&this.#Ct.focusMainContainer()}),0);this.#Et||this.addInkEditorIfNeeded(!1)}#wt(t){if(t.parent!==this){this.attach(t);t.parent?.detach(t);t.setParent(this);if(t.div&&t.isAttachedToDOM){t.div.remove();this.div.append(t.div)}}}add(t){this.#wt(t);this.#Ct.addEditor(t);this.attach(t);if(!t.isAttachedToDOM){const e=t.render();this.div.append(e);t.isAttachedToDOM=!0}this.moveEditorInDOM(t);t.onceAdded();this.#Ct.addToAnnotationStorage(t)}moveEditorInDOM(t){this.#At?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?t.rebuild():this.add(t)}addANewEditor(t){this.addCommands({cmd:()=>{this.addOrRebuild(t)},undo:()=>{t.remove()},mustExec:!0})}addUndoableEditor(t){this.addCommands({cmd:()=>{this.addOrRebuild(t)},undo:()=>{t.remove()},mustExec:!1})}getNextId(){return this.#Ct.getId()}#kt(t){switch(this.#Ct.getMode()){case n.AnnotationEditorType.FREETEXT:return new a.FreeTextEditor(t);case n.AnnotationEditorType.INK:return new r.InkEditor(t)}return null}deserialize(t){switch(t.annotationType){case n.AnnotationEditorType.FREETEXT:return a.FreeTextEditor.deserialize(t,this,this.#Ct);case n.AnnotationEditorType.INK:return r.InkEditor.deserialize(t,this,this.#Ct)}return null}#Tt(t){const e=this.getNextId(),s=this.#kt({parent:this,id:e,x:t.offsetX,y:t.offsetY,uiManager:this.#Ct});s&&this.add(s);return s}setSelected(t){this.#Ct.setSelected(t)}toggleSelected(t){this.#Ct.toggleSelected(t)}isSelected(t){return this.#Ct.isSelected(t)}unselect(t){this.#Ct.unselect(t)}pointerup(t){const{isMac:e}=n.FeatureTest.platform;if(!(0!==t.button||t.ctrlKey&&e)&&t.target===this.div&&this.#xt){this.#xt=!1;this.#_t?this.#Tt(t):this.#_t=!0}}pointerdown(t){const{isMac:e}=n.FeatureTest.platform;if(0!==t.button||t.ctrlKey&&e)return;if(t.target!==this.div)return;this.#xt=!0;const s=this.#Ct.getActive();this.#_t=!s||s.isEmpty()}drop(t){const e=t.dataTransfer.getData("text/plain"),s=this.#Ct.getEditor(e);if(!s)return;t.preventDefault();t.dataTransfer.dropEffect="move";this.#wt(s);const n=this.div.getBoundingClientRect(),i=t.clientX-n.x,a=t.clientY-n.y;s.translate(i-s.startX,a-s.startY);this.moveEditorInDOM(s);s.div.focus()}dragover(t){t.preventDefault()}destroy(){this.#Ct.getActive()?.parent===this&&this.#Ct.setActiveEditor(null);for(const t of this.#St.values()){this.#At?.removePointerInTextLayer(t.contentDiv);t.setParent(null);t.isAttachedToDOM=!1;t.div.remove()}this.div=null;this.#St.clear();this.#Ct.removeLayer(this)}#Pt(){this.#Et=!0;for(const t of this.#St.values())t.isEmpty()&&t.remove();this.#Et=!1}render({viewport:t}){this.viewport=t;(0,o.setLayerDimensions)(this.div,t);(0,i.bindEvents)(this,this.div,["dragover","drop"]);for(const t of this.#Ct.getEditors(this.pageIndex))this.add(t);this.updateMode()}update({viewport:t}){this.#Ct.commitOrRemove();this.viewport=t;(0,o.setLayerDimensions)(this.div,{rotation:t.rotation});this.updateMode()}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}}e.AnnotationEditorLayer=AnnotationEditorLayer},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.FreeTextEditor=void 0;var n=s(1),i=s(5),a=s(4);class FreeTextEditor extends a.AnnotationEditor{#Ft=this.editorDivBlur.bind(this);#Rt=this.editorDivFocus.bind(this);#Mt=this.editorDivInput.bind(this);#Dt=this.editorDivKeydown.bind(this);#It;#Ot="";#Lt=`${this.id}-editor`;#Nt=!1;#jt;static _freeTextDefaultContent="";static _l10nPromise;static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static _keyboardManager=new i.KeyboardManager([[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],FreeTextEditor.prototype.commitOrRemove]]);static _type="freetext";constructor(t){super({...t,name:"freeTextEditor"});this.#It=t.color||FreeTextEditor._defaultColor||a.AnnotationEditor._defaultLineColor;this.#jt=t.fontSize||FreeTextEditor._defaultFontSize}static initialize(t){this._l10nPromise=new Map(["free_text2_default_content","editor_free_text2_aria_label"].map((e=>[e,t.get(e)])));const e=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(e.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case n.AnnotationEditorParamsType.FREETEXT_SIZE:FreeTextEditor._defaultFontSize=e;break;case n.AnnotationEditorParamsType.FREETEXT_COLOR:FreeTextEditor._defaultColor=e}}updateParams(t,e){switch(t){case n.AnnotationEditorParamsType.FREETEXT_SIZE:this.#Ut(e);break;case n.AnnotationEditorParamsType.FREETEXT_COLOR:this.#Bt(e)}}static get defaultPropertiesToUpdate(){return[[n.AnnotationEditorParamsType.FREETEXT_SIZE,FreeTextEditor._defaultFontSize],[n.AnnotationEditorParamsType.FREETEXT_COLOR,FreeTextEditor._defaultColor||a.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[n.AnnotationEditorParamsType.FREETEXT_SIZE,this.#jt],[n.AnnotationEditorParamsType.FREETEXT_COLOR,this.#It]]}#Ut(t){const setFontsize=t=>{this.editorDiv.style.fontSize=`calc(${t}px * var(--scale-factor))`;this.translate(0,-(t-this.#jt)*this.parentScale);this.#jt=t;this.#qt()},e=this.#jt;this.addCommands({cmd:()=>{setFontsize(t)},undo:()=>{setFontsize(e)},mustExec:!0,type:n.AnnotationEditorParamsType.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#Bt(t){const e=this.#It;this.addCommands({cmd:()=>{this.#It=this.editorDiv.style.color=t},undo:()=>{this.#It=this.editorDiv.style.color=e},mustExec:!0,type:n.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}getInitialTranslation(){const t=this.parentScale;return[-FreeTextEditor._internalPadding*t,-(FreeTextEditor._internalPadding+this.#jt)*t]}rebuild(){super.rebuild();null!==this.div&&(this.isAttachedToDOM||this.parent.add(this))}enableEditMode(){if(!this.isInEditMode()){this.parent.setEditingState(!1);this.parent.updateToolbar(n.AnnotationEditorType.FREETEXT);super.enableEditMode();this.overlayDiv.classList.remove("enabled");this.editorDiv.contentEditable=!0;this.div.draggable=!1;this.div.removeAttribute("aria-activedescendant");this.editorDiv.addEventListener("keydown",this.#Dt);this.editorDiv.addEventListener("focus",this.#Rt);this.editorDiv.addEventListener("blur",this.#Ft);this.editorDiv.addEventListener("input",this.#Mt)}}disableEditMode(){if(this.isInEditMode()){this.parent.setEditingState(!0);super.disableEditMode();this.overlayDiv.classList.add("enabled");this.editorDiv.contentEditable=!1;this.div.setAttribute("aria-activedescendant",this.#Lt);this.div.draggable=!0;this.editorDiv.removeEventListener("keydown",this.#Dt);this.editorDiv.removeEventListener("focus",this.#Rt);this.editorDiv.removeEventListener("blur",this.#Ft);this.editorDiv.removeEventListener("input",this.#Mt);this.div.focus({preventScroll:!0});this.isEditing=!1;this.parent.div.classList.add("freeTextEditing")}}focusin(t){super.focusin(t);t.target!==this.editorDiv&&this.editorDiv.focus()}onceAdded(){if(!this.width){this.enableEditMode();this.editorDiv.focus()}}isEmpty(){return!this.editorDiv||""===this.editorDiv.innerText.trim()}remove(){this.isEditing=!1;this.parent.setEditingState(!0);this.parent.div.classList.add("freeTextEditing");super.remove()}#Wt(){const t=this.editorDiv.getElementsByTagName("div");if(0===t.length)return this.editorDiv.innerText;const e=[];for(const s of t)e.push(s.innerText.replace(/\r\n?|\n/,""));return e.join("\n")}#qt(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:t,div:e}=this,n=e.style.display;e.style.display="hidden";t.div.append(this.div);s=e.getBoundingClientRect();e.remove();e.style.display=n}this.width=s.width/t;this.height=s.height/e}commit(){if(this.isInEditMode()){super.commit();if(!this.#Nt){this.#Nt=!0;this.parent.addUndoableEditor(this)}this.disableEditMode();this.#Ot=this.#Wt().trimEnd();this.#qt()}}shouldGetKeyboardEvents(){return this.isInEditMode()}dblclick(t){this.enableEditMode();this.editorDiv.focus()}keydown(t){if(t.target===this.div&&"Enter"===t.key){this.enableEditMode();this.editorDiv.focus()}}editorDivKeydown(t){FreeTextEditor._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freeTextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment");this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox");this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();this.editorDiv=document.createElement("div");this.editorDiv.className="internal";this.editorDiv.setAttribute("id",this.#Lt);this.enableEditing();FreeTextEditor._l10nPromise.get("editor_free_text2_aria_label").then((t=>this.editorDiv?.setAttribute("aria-label",t)));FreeTextEditor._l10nPromise.get("free_text2_default_content").then((t=>this.editorDiv?.setAttribute("default-content",t)));this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;s.fontSize=`calc(${this.#jt}px * var(--scale-factor))`;s.color=this.#It;this.div.append(this.editorDiv);this.overlayDiv=document.createElement("div");this.overlayDiv.classList.add("overlay","enabled");this.div.append(this.overlayDiv);(0,i.bindEvents)(this,this.div,["dblclick","keydown"]);if(this.width){const[s,n]=this.parentDimensions;this.setAt(t*s,e*n,this.width*s,this.height*n);for(const t of this.#Ot.split("\n")){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br"));this.editorDiv.append(e)}this.div.draggable=!0;this.editorDiv.contentEditable=!1}else{this.div.draggable=!1;this.editorDiv.contentEditable=!0}return this.div}get contentDiv(){return this.editorDiv}static deserialize(t,e,s){const i=super.deserialize(t,e,s);i.#jt=t.fontSize;i.#It=n.Util.makeHexColor(...t.color);i.#Ot=t.value;return i}serialize(){if(this.isEmpty())return null;const t=FreeTextEditor._internalPadding*this.parentScale,e=this.getRect(t,t),s=a.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#It);return{annotationType:n.AnnotationEditorType.FREETEXT,color:s,fontSize:this.#jt,value:this.#Ot,pageIndex:this.pageIndex,rect:e,rotation:this.rotation}}}e.FreeTextEditor=FreeTextEditor},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.InkEditor=void 0;Object.defineProperty(e,"fitCurve",{enumerable:!0,get:function(){return a.fitCurve}});var n=s(1),i=s(4),a=s(25),r=s(5);const o=16;class InkEditor extends i.AnnotationEditor{#Ht=0;#Gt=0;#zt=0;#Vt=this.canvasPointermove.bind(this);#Xt=this.canvasPointerleave.bind(this);#$t=this.canvasPointerup.bind(this);#Yt=this.canvasPointerdown.bind(this);#Kt=!1;#Jt=!1;#Qt=null;#Zt=null;#te=0;#ee=0;#se=null;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=1;static _l10nPromise;static _type="ink";constructor(t){super({...t,name:"inkEditor"});this.color=t.color||null;this.thickness=t.thickness||null;this.opacity=t.opacity||null;this.paths=[];this.bezierPath2D=[];this.currentPath=[];this.scaleFactor=1;this.translationX=this.translationY=0;this.x=0;this.y=0}static initialize(t){this._l10nPromise=new Map(["editor_ink_canvas_aria_label","editor_ink2_aria_label"].map((e=>[e,t.get(e)])))}static updateDefaultParams(t,e){switch(t){case n.AnnotationEditorParamsType.INK_THICKNESS:InkEditor._defaultThickness=e;break;case n.AnnotationEditorParamsType.INK_COLOR:InkEditor._defaultColor=e;break;case n.AnnotationEditorParamsType.INK_OPACITY:InkEditor._defaultOpacity=e/100}}updateParams(t,e){switch(t){case n.AnnotationEditorParamsType.INK_THICKNESS:this.#ne(e);break;case n.AnnotationEditorParamsType.INK_COLOR:this.#Bt(e);break;case n.AnnotationEditorParamsType.INK_OPACITY:this.#ie(e)}}static get defaultPropertiesToUpdate(){return[[n.AnnotationEditorParamsType.INK_THICKNESS,InkEditor._defaultThickness],[n.AnnotationEditorParamsType.INK_COLOR,InkEditor._defaultColor||i.AnnotationEditor._defaultLineColor],[n.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*InkEditor._defaultOpacity)]]}get propertiesToUpdate(){return[[n.AnnotationEditorParamsType.INK_THICKNESS,this.thickness||InkEditor._defaultThickness],[n.AnnotationEditorParamsType.INK_COLOR,this.color||InkEditor._defaultColor||i.AnnotationEditor._defaultLineColor],[n.AnnotationEditorParamsType.INK_OPACITY,Math.round(100*(this.opacity??InkEditor._defaultOpacity))]]}#ne(t){const e=this.thickness;this.addCommands({cmd:()=>{this.thickness=t;this.#ae()},undo:()=>{this.thickness=e;this.#ae()},mustExec:!0,type:n.AnnotationEditorParamsType.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})}#Bt(t){const e=this.color;this.addCommands({cmd:()=>{this.color=t;this.#re()},undo:()=>{this.color=e;this.#re()},mustExec:!0,type:n.AnnotationEditorParamsType.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})}#ie(t){t/=100;const e=this.opacity;this.addCommands({cmd:()=>{this.opacity=t;this.#re()},undo:()=>{this.opacity=e;this.#re()},mustExec:!0,type:n.AnnotationEditorParamsType.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}rebuild(){super.rebuild();if(null!==this.div){if(!this.canvas){this.#oe();this.#le()}if(!this.isAttachedToDOM){this.parent.add(this);this.#ce()}this.#ae()}}remove(){if(null!==this.canvas){this.isEmpty()||this.commit();this.canvas.width=this.canvas.height=0;this.canvas.remove();this.canvas=null;this.#Zt.disconnect();this.#Zt=null;super.remove()}}setParent(t){!this.parent&&t?this._uiManager.removeShouldRescale(this):this.parent&&null===t&&this._uiManager.addShouldRescale(this);super.setParent(t)}onScaleChanging(){const[t,e]=this.parentDimensions,s=this.width*t,n=this.height*e;this.setDimensions(s,n)}enableEditMode(){if(!this.#Kt&&null!==this.canvas){super.enableEditMode();this.div.draggable=!1;this.canvas.addEventListener("pointerdown",this.#Yt);this.canvas.addEventListener("pointerup",this.#$t)}}disableEditMode(){if(this.isInEditMode()&&null!==this.canvas){super.disableEditMode();this.div.draggable=!this.isEmpty();this.div.classList.remove("editing");this.canvas.removeEventListener("pointerdown",this.#Yt);this.canvas.removeEventListener("pointerup",this.#$t)}}onceAdded(){this.div.draggable=!this.isEmpty()}isEmpty(){return 0===this.paths.length||1===this.paths.length&&0===this.paths[0].length}#he(){const{parentRotation:t,parentDimensions:[e,s]}=this;switch(t){case 90:return[0,s,s,e];case 180:return[e,s,e,s];case 270:return[e,0,s,e];default:return[0,0,e,s]}}#de(){const{ctx:t,color:e,opacity:s,thickness:n,parentScale:i,scaleFactor:a}=this;t.lineWidth=n*i/a;t.lineCap="round";t.lineJoin="round";t.miterLimit=10;t.strokeStyle=`${e}${(0,r.opacityToHex)(s)}`}#ue(t,e){this.isEditing=!0;if(!this.#Jt){this.#Jt=!0;this.#ce();this.thickness||=InkEditor._defaultThickness;this.color||=InkEditor._defaultColor||i.AnnotationEditor._defaultLineColor;this.opacity??=InkEditor._defaultOpacity}this.currentPath.push([t,e]);this.#Qt=null;this.#de();this.ctx.beginPath();this.ctx.moveTo(t,e);this.#se=()=>{if(this.#se){if(this.#Qt){if(this.isEmpty()){this.ctx.setTransform(1,0,0,1,0,0);this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}else this.#re();this.ctx.lineTo(...this.#Qt);this.#Qt=null;this.ctx.stroke()}window.requestAnimationFrame(this.#se)}};window.requestAnimationFrame(this.#se)}#pe(t,e){const[s,n]=this.currentPath.at(-1);if(t!==s||e!==n){this.currentPath.push([t,e]);this.#Qt=[t,e]}}#ge(t,e){this.ctx.closePath();this.#se=null;t=Math.min(Math.max(t,0),this.canvas.width);e=Math.min(Math.max(e,0),this.canvas.height);const[s,n]=this.currentPath.at(-1);t===s&&e===n||this.currentPath.push([t,e]);let i;if(1!==this.currentPath.length)i=(0,a.fitCurve)(this.currentPath,30,null);else{const s=[t,e];i=[[s,s.slice(),s.slice(),s]]}const r=InkEditor.#me(i);this.currentPath.length=0;this.addCommands({cmd:()=>{this.paths.push(i);this.bezierPath2D.push(r);this.rebuild()},undo:()=>{this.paths.pop();this.bezierPath2D.pop();if(0===this.paths.length)this.remove();else{if(!this.canvas){this.#oe();this.#le()}this.#ae()}},mustExec:!0})}#re(){if(this.isEmpty()){this.#fe();return}this.#de();const{canvas:t,ctx:e}=this;e.setTransform(1,0,0,1,0,0);e.clearRect(0,0,t.width,t.height);this.#fe();for(const t of this.bezierPath2D)e.stroke(t)}commit(){if(!this.#Kt){super.commit();this.isEditing=!1;this.disableEditMode();this.setInForeground();this.#Kt=!0;this.div.classList.add("disabled");this.#ae(!0);this.parent.addInkEditorIfNeeded(!0);this.parent.moveEditorInDOM(this);this.div.focus({preventScroll:!0})}}focusin(t){super.focusin(t);this.enableEditMode()}canvasPointerdown(t){if(0===t.button&&this.isInEditMode()&&!this.#Kt){this.setInForeground();"mouse"!==t.type&&this.div.focus();t.stopPropagation();this.canvas.addEventListener("pointerleave",this.#Xt);this.canvas.addEventListener("pointermove",this.#Vt);this.#ue(t.offsetX,t.offsetY)}}canvasPointermove(t){t.stopPropagation();this.#pe(t.offsetX,t.offsetY)}canvasPointerup(t){if(0===t.button&&this.isInEditMode()&&0!==this.currentPath.length){t.stopPropagation();this.#be(t);this.setInBackground()}}canvasPointerleave(t){this.#be(t);this.setInBackground()}#be(t){this.#ge(t.offsetX,t.offsetY);this.canvas.removeEventListener("pointerleave",this.#Xt);this.canvas.removeEventListener("pointermove",this.#Vt);this.addToAnnotationStorage()}#oe(){this.canvas=document.createElement("canvas");this.canvas.width=this.canvas.height=0;this.canvas.className="inkEditorCanvas";InkEditor._l10nPromise.get("editor_ink_canvas_aria_label").then((t=>this.canvas?.setAttribute("aria-label",t)));this.div.append(this.canvas);this.ctx=this.canvas.getContext("2d")}#le(){let t=null;this.#Zt=new ResizeObserver((e=>{const s=e[0].contentRect;if(s.width&&s.height){null!==t&&clearTimeout(t);t=setTimeout((()=>{this.fixDims();t=null}),100);this.setDimensions(s.width,s.height)}}));this.#Zt.observe(this.div)}render(){if(this.div)return this.div;let t,e;if(this.width){t=this.x;e=this.y}super.render();InkEditor._l10nPromise.get("editor_ink2_aria_label").then((t=>this.div?.setAttribute("aria-label",t)));const[s,n,i,a]=this.#he();this.setAt(s,n,0,0);this.setDims(i,a);this.#oe();if(this.width){const[s,n]=this.parentDimensions;this.setAt(t*s,e*n,this.width*s,this.height*n);this.#Jt=!0;this.#ce();this.setDims(this.width*s,this.height*n);this.#re();this.#Ae();this.div.classList.add("disabled")}else{this.div.classList.add("editing");this.enableEditMode()}this.#le();return this.div}#ce(){if(!this.#Jt)return;const[t,e]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*t);this.canvas.height=Math.ceil(this.height*e);this.#fe()}setDimensions(t,e){const s=Math.round(t),n=Math.round(e);if(this.#te===s&&this.#ee===n)return;this.#te=s;this.#ee=n;this.canvas.style.visibility="hidden";if(this.#Ht&&Math.abs(this.#Ht-t/e)>.01){e=Math.ceil(t/this.#Ht);this.setDims(t,e)}const[i,a]=this.parentDimensions;this.width=t/i;this.height=e/a;this.#Kt&&this.#_e(t,e);this.#ce();this.#re();this.canvas.style.visibility="visible"}#_e(t,e){const s=this.#ye(),n=(t-s)/this.#zt,i=(e-s)/this.#Gt;this.scaleFactor=Math.min(n,i)}#fe(){const t=this.#ye()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+t,this.translationY*this.scaleFactor+t)}static#me(t){const e=new Path2D;for(let s=0,n=t.length;s=1){t.minHeight="16px";t.minWidth=`${Math.round(this.#Ht*o)}px`}else{t.minWidth="16px";t.minHeight=`${Math.round(o/this.#Ht)}px`}}static deserialize(t,e,s){const i=super.deserialize(t,e,s);i.thickness=t.thickness;i.color=n.Util.makeHexColor(...t.color);i.opacity=t.opacity;const[a,r]=i.pageDimensions,l=i.width*a,c=i.height*r,h=i.parentScale,d=t.thickness/2;i.#Ht=l/c;i.#Kt=!0;i.#te=Math.round(l);i.#ee=Math.round(c);for(const{bezier:e}of t.paths){const t=[];i.paths.push(t);let s=h*(e[0]-d),n=h*(c-e[1]-d);for(let i=2,a=e.length;i{Object.defineProperty(e,"__esModule",{value:!0});e.fitCurve=void 0;const n=s(26);e.fitCurve=n},t=>{function fitCubic(t,e,s,n,i){var a,r,o,l,c,h,d,u,p,g,m,f,b;if(2===t.length){f=maths.vectorLen(maths.subtract(t[0],t[1]))/3;return[a=[t[0],maths.addArrays(t[0],maths.mulItems(e,f)),maths.addArrays(t[1],maths.mulItems(s,f)),t[1]]]}r=function chordLengthParameterize(t){var e,s,n,i=[];t.forEach(((t,a)=>{e=a?s+maths.vectorLen(maths.subtract(t,n)):0;i.push(e);s=e;n=t}));i=i.map((t=>t/s));return i}(t);[a,l,h]=generateAndReport(t,r,r,e,s,i);if(0===l||l.9999&&t<1.0001)break}c=l;d=h}}m=[];if((u=maths.subtract(t[h-1],t[h+1])).every((t=>0===t))){u=maths.subtract(t[h-1],t[h]);[u[0],u[1]]=[-u[1],u[0]]}p=maths.normalize(u);g=maths.mulItems(p,-1);return m=(m=m.concat(fitCubic(t.slice(0,h+1),e,p,n,i))).concat(fitCubic(t.slice(h),g,s,n,i))}function generateAndReport(t,e,s,n,i,a){var r,o,l;r=function generateBezier(t,e,s,n){var i,a,r,o,l,c,h,d,u,p,g,m,f,b,A,_,y,v=t[0],S=t[t.length-1];i=[v,null,null,S];a=maths.zeros_Xx2x2(e.length);for(f=0,b=e.length;fi){i=n;a=o}}return[i,a]}(t,r,e);a&&a({bez:r,points:t,params:e,maxErr:o,maxPoint:l});return[r,o,l]}function reparameterize(t,e,s){return s.map(((s,n)=>newtonRaphsonRootFind(t,e[n],s)))}function newtonRaphsonRootFind(t,e,s){var n=maths.subtract(bezier.q(t,s),e),i=bezier.qprime(t,s),a=maths.mulMatrix(n,i),r=maths.sum(maths.squareItems(i))+2*maths.mulMatrix(n,bezier.qprimeprime(t,s));return 0===r?s:s-a/r}var mapTtoRelativeDistances=function(t,e){for(var s,n=[0],i=t[0],a=0,r=1;r<=e;r++){s=bezier.q(t,r/e);a+=maths.vectorLen(maths.subtract(s,i));n.push(a);i=s}return n=n.map((t=>t/a))};function find_t(t,e,s,n){if(e<0)return 0;if(e>1)return 1;for(var i,a,r,o,l=1;l<=n;l++)if(e<=s[l]){r=(l-1)/n;a=l/n;o=(e-(i=s[l-1]))/(s[l]-i)*(a-r)+r;break}return o}function createTangent(t,e){return maths.normalize(maths.subtract(t,e))}class maths{static zeros_Xx2x2(t){for(var e=[];t--;)e.push([0,0]);return e}static mulItems(t,e){return t.map((t=>t*e))}static mulMatrix(t,e){return t.reduce(((t,s,n)=>t+s*e[n]),0)}static subtract(t,e){return t.map(((t,s)=>t-e[s]))}static addArrays(t,e){return t.map(((t,s)=>t+e[s]))}static addItems(t,e){return t.map((t=>t+e))}static sum(t){return t.reduce(((t,e)=>t+e))}static dot(t,e){return maths.mulMatrix(t,e)}static vectorLen(t){return Math.hypot(...t)}static divItems(t,e){return t.map((t=>t/e))}static squareItems(t){return t.map((t=>t*t))}static normalize(t){return this.divItems(t,this.vectorLen(t))}}class bezier{static q(t,e){var s=1-e,n=maths.mulItems(t[0],s*s*s),i=maths.mulItems(t[1],3*s*s*e),a=maths.mulItems(t[2],3*s*e*e),r=maths.mulItems(t[3],e*e*e);return maths.addArrays(maths.addArrays(n,i),maths.addArrays(a,r))}static qprime(t,e){var s=1-e,n=maths.mulItems(maths.subtract(t[1],t[0]),3*s*s),i=maths.mulItems(maths.subtract(t[2],t[1]),6*s*e),a=maths.mulItems(maths.subtract(t[3],t[2]),3*e*e);return maths.addArrays(maths.addArrays(n,i),a)}static qprimeprime(t,e){return maths.addArrays(maths.mulItems(maths.addArrays(maths.subtract(t[2],maths.mulItems(t[1],2)),t[0]),6*(1-e)),maths.mulItems(maths.addArrays(maths.subtract(t[3],maths.mulItems(t[2],2)),t[1]),6*e))}}t.exports=function fitCurve(t,e,s){if(!Array.isArray(t))throw new TypeError("First argument should be an array");t.forEach((e=>{if(!Array.isArray(e)||e.some((t=>"number"!=typeof t))||e.length!==t[0].length)throw Error("Each point should be an array of numbers. Each point should have the same amount of numbers.")}));if((t=t.filter(((e,s)=>0===s||!e.every(((e,n)=>e===t[s-1][n]))))).length<2)return[];const n=t.length,i=createTangent(t[1],t[0]),a=createTangent(t[n-2],t[n-1]);return fitCubic(t,i,a,e,s)};t.exports.fitCubic=fitCubic;t.exports.createTangent=createTangent},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.AnnotationLayer=void 0;var n=s(1),i=s(6),a=s(3),r=s(28),o=s(29);const l=1e3,c=new WeakSet;function getRectDims(t){return{width:t[2]-t[0],height:t[3]-t[1]}}class AnnotationElementFactory{static create(t){switch(t.data.annotationType){case n.AnnotationType.LINK:return new LinkAnnotationElement(t);case n.AnnotationType.TEXT:return new TextAnnotationElement(t);case n.AnnotationType.WIDGET:switch(t.data.fieldType){case"Tx":return new TextWidgetAnnotationElement(t);case"Btn":return t.data.radioButton?new RadioButtonWidgetAnnotationElement(t):t.data.checkBox?new CheckboxWidgetAnnotationElement(t):new PushButtonWidgetAnnotationElement(t);case"Ch":return new ChoiceWidgetAnnotationElement(t)}return new WidgetAnnotationElement(t);case n.AnnotationType.POPUP:return new PopupAnnotationElement(t);case n.AnnotationType.FREETEXT:return new FreeTextAnnotationElement(t);case n.AnnotationType.LINE:return new LineAnnotationElement(t);case n.AnnotationType.SQUARE:return new SquareAnnotationElement(t);case n.AnnotationType.CIRCLE:return new CircleAnnotationElement(t);case n.AnnotationType.POLYLINE:return new PolylineAnnotationElement(t);case n.AnnotationType.CARET:return new CaretAnnotationElement(t);case n.AnnotationType.INK:return new InkAnnotationElement(t);case n.AnnotationType.POLYGON:return new PolygonAnnotationElement(t);case n.AnnotationType.HIGHLIGHT:return new HighlightAnnotationElement(t);case n.AnnotationType.UNDERLINE:return new UnderlineAnnotationElement(t);case n.AnnotationType.SQUIGGLY:return new SquigglyAnnotationElement(t);case n.AnnotationType.STRIKEOUT:return new StrikeOutAnnotationElement(t);case n.AnnotationType.STAMP:return new StampAnnotationElement(t);case n.AnnotationType.FILEATTACHMENT:return new FileAttachmentAnnotationElement(t);default:return new AnnotationElement(t)}}}class AnnotationElement{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:n=!1}={}){this.isRenderable=e;this.data=t.data;this.layer=t.layer;this.page=t.page;this.viewport=t.viewport;this.linkService=t.linkService;this.downloadManager=t.downloadManager;this.imageResourcesPath=t.imageResourcesPath;this.renderForms=t.renderForms;this.svgFactory=t.svgFactory;this.annotationStorage=t.annotationStorage;this.enableScripting=t.enableScripting;this.hasJSActions=t.hasJSActions;this._fieldObjects=t.fieldObjects;e&&(this.container=this._createContainer(s));n&&(this.quadrilaterals=this._createQuadrilaterals(s))}_createContainer(t=!1){const{data:e,page:s,viewport:i}=this,a=document.createElement("section");a.setAttribute("data-annotation-id",e.id);const{pageWidth:r,pageHeight:o,pageX:l,pageY:c}=i.rawDims,{width:h,height:d}=getRectDims(e.rect),u=n.Util.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]);if(!t&&e.borderStyle.width>0){a.style.borderWidth=`${e.borderStyle.width}px`;const t=e.borderStyle.horizontalCornerRadius,s=e.borderStyle.verticalCornerRadius;if(t>0||s>0){const e=`calc(${t}px * var(--scale-factor)) / calc(${s}px * var(--scale-factor))`;a.style.borderRadius=e}else if(this instanceof RadioButtonWidgetAnnotationElement){const t=`calc(${h}px * var(--scale-factor)) / calc(${d}px * var(--scale-factor))`;a.style.borderRadius=t}switch(e.borderStyle.style){case n.AnnotationBorderStyleType.SOLID:a.style.borderStyle="solid";break;case n.AnnotationBorderStyleType.DASHED:a.style.borderStyle="dashed";break;case n.AnnotationBorderStyleType.BEVELED:(0,n.warn)("Unimplemented border style: beveled");break;case n.AnnotationBorderStyleType.INSET:(0,n.warn)("Unimplemented border style: inset");break;case n.AnnotationBorderStyleType.UNDERLINE:a.style.borderBottomStyle="solid"}const i=e.borderColor||null;i?a.style.borderColor=n.Util.makeHexColor(0|i[0],0|i[1],0|i[2]):a.style.borderWidth=0}a.style.left=100*(u[0]-l)/r+"%";a.style.top=100*(u[1]-c)/o+"%";const{rotation:p}=e;if(e.hasOwnCanvas||0===p){a.style.width=100*h/r+"%";a.style.height=100*d/o+"%"}else this.setRotation(p,a);return a}setRotation(t,e=this.container){const{pageWidth:s,pageHeight:n}=this.viewport.rawDims,{width:i,height:a}=getRectDims(this.data.rect);let r,o;if(t%180==0){r=100*i/s;o=100*a/n}else{r=100*a/s;o=100*i/n}e.style.width=`${r}%`;e.style.height=`${o}%`;e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const setColor=(t,e,s)=>{const n=s.detail[t];s.target.style[e]=r.ColorConverters[`${n[0]}_HTML`](n.slice(1))};return(0,n.shadow)(this,"_commonActions",{display:t=>{const e=t.detail.display%2==1;this.container.style.visibility=e?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{hidden:e,print:0===t.detail.display||3===t.detail.display})},print:t=>{this.annotationStorage.setValue(this.data.id,{print:t.detail.print})},hidden:t=>{this.container.style.visibility=t.detail.hidden?"hidden":"visible";this.annotationStorage.setValue(this.data.id,{hidden:t.detail.hidden})},focus:t=>{setTimeout((()=>t.target.focus({preventScroll:!1})),0)},userName:t=>{t.target.title=t.detail.userName},readonly:t=>{t.detail.readonly?t.target.setAttribute("readonly",""):t.target.removeAttribute("readonly")},required:t=>{this._setRequired(t.target,t.detail.required)},bgColor:t=>{setColor("bgColor","backgroundColor",t)},fillColor:t=>{setColor("fillColor","backgroundColor",t)},fgColor:t=>{setColor("fgColor","color",t)},textColor:t=>{setColor("textColor","color",t)},borderColor:t=>{setColor("borderColor","borderColor",t)},strokeColor:t=>{setColor("strokeColor","borderColor",t)},rotation:t=>{const e=t.detail.rotation;this.setRotation(e);this.annotationStorage.setValue(this.data.id,{rotation:e})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const n of Object.keys(e.detail)){(t[n]||s[n])?.(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[n,i]of Object.entries(e)){const a=s[n];if(a){a({detail:{[n]:i},target:t});delete e[n]}}}_createQuadrilaterals(t=!1){if(!this.data.quadPoints)return null;const e=[],s=this.data.rect;for(const s of this.data.quadPoints){this.data.rect=[s[2].x,s[2].y,s[1].x,s[1].y];e.push(this._createContainer(t))}this.data.rect=s;return e}_createPopup(t,e){let s=this.container;if(this.quadrilaterals){t=t||this.quadrilaterals;s=this.quadrilaterals[0]}if(!t){(t=document.createElement("div")).className="popupTriggerArea";s.append(t)}const n=new PopupElement({container:s,trigger:t,color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,hideWrapper:!0}).render();n.style.left="100%";s.append(n)}_renderQuadrilaterals(t){for(const e of this.quadrilaterals)e.className=t;return this.quadrilaterals}render(){(0,n.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:t,id:a,exportValues:r}of i){if(-1===t)continue;if(a===e)continue;const i="string"==typeof r?r:null,o=document.querySelector(`[data-element-id="${a}"]`);!o||c.has(o)?s.push({id:a,exportValue:i,domElement:o}):(0,n.warn)(`_getElementsByName - element not allowed: ${a}`)}return s}for(const n of document.getElementsByName(t)){const{exportValue:t}=n,i=n.getAttribute("data-element-id");i!==e&&(c.has(n)&&s.push({id:i,exportValue:t,domElement:n}))}return s}}class LinkAnnotationElement extends AnnotationElement{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0});this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let n=!1;if(t.url){e.addLinkAttributes(s,t.url,t.newWindow);n=!0}else if(t.action){this._bindNamedAction(s,t.action);n=!0}else if(t.attachment){this._bindAttachment(s,t.attachment);n=!0}else if(t.setOCGState){this.#Ce(s,t.setOCGState);n=!0}else if(t.dest){this._bindLink(s,t.dest);n=!0}else{if(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions){this._bindJSAction(s,t);n=!0}if(t.resetForm){this._bindResetFormAction(s,t.resetForm);n=!0}else if(this.isTooltipOnly&&!n){this._bindLink(s,"");n=!0}}if(this.quadrilaterals)return this._renderQuadrilaterals("linkAnnotation").map(((t,e)=>{const n=0===e?s:s.cloneNode();t.append(n);return t}));this.container.className="linkAnnotation";n&&this.container.append(s);return this.container}#Pe(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e);t.onclick=()=>{e&&this.linkService.goToDestination(e);return!1};(e||""===e)&&this.#Pe()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeNamedAction(e);return!1};this.#Pe()}_bindAttachment(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.downloadManager?.openOrDownloadData(this.container,e.content,e.filename);return!1};this.#Pe()}#Ce(t,e){t.href=this.linkService.getAnchorUrl("");t.onclick=()=>{this.linkService.executeSetOCGState(e);return!1};this.#Pe()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(e.actions)){const i=s.get(n);i&&(t[i]=()=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:n}});return!1})}t.onclick||(t.onclick=()=>!1);this.#Pe()}_bindResetFormAction(t,e){const s=t.onclick;s||(t.href=this.linkService.getAnchorUrl(""));this.#Pe();if(this._fieldObjects)t.onclick=()=>{s?.();const{fields:t,refs:i,include:a}=e,r=[];if(0!==t.length||0!==i.length){const e=new Set(i);for(const s of t){const t=this._fieldObjects[s]||[];for(const{id:s}of t)e.add(s)}for(const t of Object.values(this._fieldObjects))for(const s of t)e.has(s.id)===a&&r.push(s)}else for(const t of Object.values(this._fieldObjects))r.push(...t);const o=this.annotationStorage,l=[];for(const t of r){const{id:e}=t;l.push(e);switch(t.type){case"text":{const s=t.defaultValue||"";o.setValue(e,{value:s});break}case"checkbox":case"radiobutton":{const s=t.defaultValue===t.exportValues;o.setValue(e,{value:s});break}case"combobox":case"listbox":{const s=t.defaultValue||"";o.setValue(e,{value:s});break}default:continue}const s=document.querySelector(`[data-element-id="${e}"]`);s&&(c.has(s)?s.dispatchEvent(new Event("resetform")):(0,n.warn)(`_bindResetFormAction - element not allowed: ${e}`))}this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:l,name:"ResetForm"}});return!1};else{(0,n.warn)('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.');s||(t.onclick=()=>!1)}}}class TextAnnotationElement extends AnnotationElement{constructor(t){super(t,{isRenderable:!!(t.data.hasPopup||t.data.titleObj?.str||t.data.contentsObj?.str||t.data.richText?.str)})}render(){this.container.className="textAnnotation";const t=document.createElement("img");t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg";t.alt="[{{type}} Annotation]";t.dataset.l10nId="text_annotation_type";t.dataset.l10nArgs=JSON.stringify({type:this.data.name});this.data.hasPopup||this._createPopup(t,this.data);this.container.append(t);return this.container}}class WidgetAnnotationElement extends AnnotationElement{render(){this.data.alternativeText&&(this.container.title=this.data.alternativeText);return this.container}_getKeyModifier(t){const{isWin:e,isMac:s}=n.FeatureTest.platform;return e&&t.ctrlKey||s&&t.metaKey}_setEventListener(t,e,s,n){e.includes("mouse")?t.addEventListener(e,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t),shift:t.shiftKey,modifier:this._getKeyModifier(t)}})})):t.addEventListener(e,(t=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:s,value:n(t)}})}))}_setEventListeners(t,e,s){for(const[n,i]of e)("Action"===i||this.data.actions?.[i])&&this._setEventListener(t,n,i,s)}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=null===e?"transparent":n.Util.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||9,a=t.style;let r;const roundToOneDecimal=t=>Math.round(10*t)/10;if(this.data.multiLine){const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2),e=t/(Math.round(t/(n.LINE_FACTOR*i))||1);r=Math.min(i,roundToOneDecimal(e/n.LINE_FACTOR))}else{const t=Math.abs(this.data.rect[3]-this.data.rect[1]-2);r=Math.min(i,roundToOneDecimal(t/n.LINE_FACTOR))}a.fontSize=`calc(${r}px * var(--scale-factor))`;a.color=n.Util.makeHexColor(s[0],s[1],s[2]);null!==this.data.textAlignment&&(a.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required");t.setAttribute("aria-required",e)}}class TextWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms||!t.data.hasAppearance&&!!t.data.fieldValue})}setPropertyOnSiblings(t,e,s,n){const i=this.annotationStorage;for(const a of this._getElementsByName(t.name,t.id)){a.domElement&&(a.domElement[e]=s);i.setValue(a.id,{[n]:s})}}render(){const t=this.annotationStorage,e=this.data.id;this.container.className="textWidgetAnnotation";let s=null;if(this.renderForms){const n=t.getValue(e,{value:this.data.fieldValue});let i=n.formattedValue||n.value||"";const a=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;a&&i.length>a&&(i=i.slice(0,a));const r={userValue:i,formattedValue:null,lastCommittedValue:null,commitKey:1};if(this.data.multiLine){s=document.createElement("textarea");s.textContent=i;this.data.doNotScroll&&(s.style.overflowY="hidden")}else{s=document.createElement("input");s.type="text";s.setAttribute("value",i);this.data.doNotScroll&&(s.style.overflowX="hidden")}c.add(s);s.setAttribute("data-element-id",e);s.disabled=this.data.readOnly;s.name=this.data.fieldName;s.tabIndex=l;this._setRequired(s,this.data.required);a&&(s.maxLength=a);s.addEventListener("input",(n=>{t.setValue(e,{value:n.target.value});this.setPropertyOnSiblings(s,"value",n.target.value,"value")}));s.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue??"";s.value=r.userValue=e;r.formattedValue=null}));let blurListener=t=>{const{formattedValue:e}=r;null!=e&&(t.target.value=e);t.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",(t=>{const{target:e}=t;r.userValue&&(e.value=r.userValue);r.lastCommittedValue=e.value;r.commitKey=1}));s.addEventListener("updatefromsandbox",(s=>{const n={value(s){r.userValue=s.detail.value??"";t.setValue(e,{value:r.userValue.toString()});s.target.value=r.userValue},formattedValue(s){const{formattedValue:n}=s.detail;r.formattedValue=n;null!=n&&s.target!==document.activeElement&&(s.target.value=n);t.setValue(e,{formattedValue:n})},selRange(t){t.target.setSelectionRange(...t.detail.selRange)},charLimit:s=>{const{charLimit:n}=s.detail,{target:i}=s;if(0===n){i.removeAttribute("maxLength");return}i.setAttribute("maxLength",n);let a=r.userValue;if(a&&!(a.length<=n)){a=a.slice(0,n);i.value=r.userValue=a;t.setValue(e,{value:a});this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:a,willCommit:!0,commitKey:1,selStart:i.selectionStart,selEnd:i.selectionEnd}})}}};this._dispatchEventFromSandbox(n,s)}));s.addEventListener("keydown",(t=>{r.commitKey=1;let s=-1;"Escape"===t.key?s=0:"Enter"!==t.key||this.data.multiLine?"Tab"===t.key&&(r.commitKey=3):s=2;if(-1===s)return;const{value:n}=t.target;if(r.lastCommittedValue!==n){r.lastCommittedValue=n;r.userValue=n;this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:n,willCommit:!0,commitKey:s,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}})}}));const n=blurListener;blurListener=null;s.addEventListener("blur",(t=>{if(!t.relatedTarget)return;const{value:s}=t.target;r.userValue=s;r.lastCommittedValue!==s&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:s,willCommit:!0,commitKey:r.commitKey,selStart:t.target.selectionStart,selEnd:t.target.selectionEnd}});n(t)}));this.data.actions?.Keystroke&&s.addEventListener("beforeinput",(t=>{r.lastCommittedValue=null;const{data:s,target:n}=t,{value:i,selectionStart:a,selectionEnd:o}=n;let l=a,c=o;switch(t.inputType){case"deleteWordBackward":{const t=i.substring(0,a).match(/\w*[^\w]*$/);t&&(l-=t[0].length);break}case"deleteWordForward":{const t=i.substring(a).match(/^[^\w]*\w*/);t&&(c+=t[0].length);break}case"deleteContentBackward":a===o&&(l-=1);break;case"deleteContentForward":a===o&&(c+=1)}t.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:i,change:s||"",willCommit:!1,selStart:l,selEnd:c}})}));this._setEventListeners(s,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.value))}blurListener&&s.addEventListener("blur",blurListener);if(this.data.comb){const t=(this.data.rect[2]-this.data.rect[0])/a;s.classList.add("comb");s.style.letterSpacing=`calc(${t}px * var(--scale-factor) - 1ch)`}}else{s=document.createElement("div");s.textContent=this.data.fieldValue;s.style.verticalAlign="middle";s.style.display="table-cell"}this._setTextStyle(s);this._setBackgroundColor(s);this._setDefaultPropertiesFromJS(s);this.container.append(s);return this.container}}class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let n=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;if("string"==typeof n){n="Off"!==n;t.setValue(s,{value:n})}this.container.className="buttonWidgetAnnotation checkBox";const i=document.createElement("input");c.add(i);i.setAttribute("data-element-id",s);i.disabled=e.readOnly;this._setRequired(i,this.data.required);i.type="checkbox";i.name=e.fieldName;n&&i.setAttribute("checked",!0);i.setAttribute("exportValue",e.exportValue);i.tabIndex=l;i.addEventListener("change",(n=>{const{name:i,checked:a}=n.target;for(const n of this._getElementsByName(i,s)){const s=a&&n.exportValue===e.exportValue;n.domElement&&(n.domElement.checked=s);t.setValue(n.id,{value:s})}t.setValue(s,{value:a})}));i.addEventListener("resetform",(t=>{const s=e.defaultFieldValue||"Off";t.target.checked=s===e.exportValue}));if(this.enableScripting&&this.hasJSActions){i.addEventListener("updatefromsandbox",(e=>{const n={value(e){e.target.checked="Off"!==e.detail.value;t.setValue(s,{value:e.target.checked})}};this._dispatchEventFromSandbox(n,e)}));this._setEventListeners(i,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.className="buttonWidgetAnnotation radioButton";const t=this.annotationStorage,e=this.data,s=e.id;let n=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if("string"==typeof n){n=n!==e.buttonValue;t.setValue(s,{value:n})}const i=document.createElement("input");c.add(i);i.setAttribute("data-element-id",s);i.disabled=e.readOnly;this._setRequired(i,this.data.required);i.type="radio";i.name=e.fieldName;n&&i.setAttribute("checked",!0);i.tabIndex=l;i.addEventListener("change",(e=>{const{name:n,checked:i}=e.target;for(const e of this._getElementsByName(n,s))t.setValue(e.id,{value:!1});t.setValue(s,{value:i})}));i.addEventListener("resetform",(t=>{const s=e.defaultFieldValue;t.target.checked=null!=s&&s===e.buttonValue}));if(this.enableScripting&&this.hasJSActions){const n=e.buttonValue;i.addEventListener("updatefromsandbox",(e=>{const i={value:e=>{const i=n===e.detail.value;for(const n of this._getElementsByName(e.target.name)){const e=i&&n.id===s;n.domElement&&(n.domElement.checked=e);t.setValue(n.id,{value:e})}}};this._dispatchEventFromSandbox(i,e)}));this._setEventListeners(i,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(t=>t.target.checked))}this._setBackgroundColor(i);this._setDefaultPropertiesFromJS(i);this.container.append(i);return this.container}}class PushButtonWidgetAnnotationElement extends LinkAnnotationElement{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.className="buttonWidgetAnnotation pushButton";this.data.alternativeText&&(t.title=this.data.alternativeText);const e=t.lastChild;if(this.enableScripting&&this.hasJSActions&&e){this._setDefaultPropertiesFromJS(e);e.addEventListener("updatefromsandbox",(t=>{this._dispatchEventFromSandbox({},t)}))}return t}}class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.className="choiceWidgetAnnotation";const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),n=document.createElement("select");c.add(n);n.setAttribute("data-element-id",e);n.disabled=this.data.readOnly;this._setRequired(n,this.data.required);n.name=this.data.fieldName;n.tabIndex=l;let i=this.data.combo&&this.data.options.length>0;if(!this.data.combo){n.size=this.data.options.length;this.data.multiSelect&&(n.multiple=!0)}n.addEventListener("resetform",(t=>{const e=this.data.defaultFieldValue;for(const t of n.options)t.selected=t.value===e}));for(const t of this.data.options){const e=document.createElement("option");e.textContent=t.displayValue;e.value=t.exportValue;if(s.value.includes(t.exportValue)){e.setAttribute("selected",!0);i=!1}n.append(e)}let a=null;if(i){const t=document.createElement("option");t.value=" ";t.setAttribute("hidden",!0);t.setAttribute("selected",!0);n.prepend(t);a=()=>{t.remove();n.removeEventListener("input",a);a=null};n.addEventListener("input",a)}const getValue=t=>{const e=t?"value":"textContent",{options:s,multiple:i}=n;return i?Array.prototype.filter.call(s,(t=>t.selected)).map((t=>t[e])):-1===s.selectedIndex?null:s[s.selectedIndex][e]};let r=getValue(!1);const getItems=t=>{const e=t.target.options;return Array.prototype.map.call(e,(t=>({displayValue:t.textContent,exportValue:t.value})))};if(this.enableScripting&&this.hasJSActions){n.addEventListener("updatefromsandbox",(s=>{const i={value(s){a?.();const i=s.detail.value,o=new Set(Array.isArray(i)?i:[i]);for(const t of n.options)t.selected=o.has(t.value);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},multipleSelection(t){n.multiple=!0},remove(s){const i=n.options,a=s.detail.remove;i[a].selected=!1;n.remove(a);if(i.length>0){-1===Array.prototype.findIndex.call(i,(t=>t.selected))&&(i[0].selected=!0)}t.setValue(e,{value:getValue(!0),items:getItems(s)});r=getValue(!1)},clear(s){for(;0!==n.length;)n.remove(0);t.setValue(e,{value:null,items:[]});r=getValue(!1)},insert(s){const{index:i,displayValue:a,exportValue:o}=s.detail.insert,l=n.children[i],c=document.createElement("option");c.textContent=a;c.value=o;l?l.before(c):n.append(c);t.setValue(e,{value:getValue(!0),items:getItems(s)});r=getValue(!1)},items(s){const{items:i}=s.detail;for(;0!==n.length;)n.remove(0);for(const t of i){const{displayValue:e,exportValue:s}=t,i=document.createElement("option");i.textContent=e;i.value=s;n.append(i)}n.options.length>0&&(n.options[0].selected=!0);t.setValue(e,{value:getValue(!0),items:getItems(s)});r=getValue(!1)},indices(s){const n=new Set(s.detail.indices);for(const t of s.target.options)t.selected=n.has(t.index);t.setValue(e,{value:getValue(!0)});r=getValue(!1)},editable(t){t.target.disabled=!t.detail.editable}};this._dispatchEventFromSandbox(i,s)}));n.addEventListener("input",(s=>{const n=getValue(!0);t.setValue(e,{value:n});s.preventDefault();this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:r,changeEx:n,willCommit:!1,commitKey:1,keyDown:!1}})}));this._setEventListeners(n,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"]],(t=>t.target.checked))}else n.addEventListener("input",(function(s){t.setValue(e,{value:getValue(!0)})}));this.data.combo&&this._setTextStyle(n);this._setBackgroundColor(n);this._setDefaultPropertiesFromJS(n);this.container.append(n);return this.container}}class PopupAnnotationElement extends AnnotationElement{static IGNORE_TYPES=new Set(["Line","Square","Circle","PolyLine","Polygon","Ink"]);constructor(t){const{data:e}=t;super(t,{isRenderable:!PopupAnnotationElement.IGNORE_TYPES.has(e.parentType)&&!!(e.titleObj?.str||e.contentsObj?.str||e.richText?.str)})}render(){this.container.className="popupAnnotation";const t=this.layer.querySelectorAll(`[data-annotation-id="${this.data.parentId}"]`);if(0===t.length)return this.container;const e=new PopupElement({container:this.container,trigger:Array.from(t),color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText}),s=this.page,i=n.Util.normalizeRect([this.data.parentRect[0],s.view[3]-this.data.parentRect[1]+s.view[1],this.data.parentRect[2],s.view[3]-this.data.parentRect[3]+s.view[1]]),a=i[0]+this.data.parentRect[2]-this.data.parentRect[0],r=i[1],{pageWidth:o,pageHeight:l,pageX:c,pageY:h}=this.viewport.rawDims;this.container.style.left=100*(a-c)/o+"%";this.container.style.top=100*(r-h)/l+"%";this.container.append(e.render());return this.container}}class PopupElement{constructor(t){this.container=t.container;this.trigger=t.trigger;this.color=t.color;this.titleObj=t.titleObj;this.modificationDate=t.modificationDate;this.contentsObj=t.contentsObj;this.richText=t.richText;this.hideWrapper=t.hideWrapper||!1;this.pinned=!1}render(){const t=document.createElement("div");t.className="popupWrapper";this.hideElement=this.hideWrapper?t:this.container;this.hideElement.hidden=!0;const e=document.createElement("div");e.className="popup";const s=this.color;if(s){const t=.7*(255-s[0])+s[0],i=.7*(255-s[1])+s[1],a=.7*(255-s[2])+s[2];e.style.backgroundColor=n.Util.makeHexColor(0|t,0|i,0|a)}const a=document.createElement("h1");a.dir=this.titleObj.dir;a.textContent=this.titleObj.str;e.append(a);const r=i.PDFDateString.toDateObject(this.modificationDate);if(r){const t=document.createElement("span");t.className="popupDate";t.textContent="{{date}}, {{time}}";t.dataset.l10nId="annotation_date_string";t.dataset.l10nArgs=JSON.stringify({date:r.toLocaleDateString(),time:r.toLocaleTimeString()});e.append(t)}if(!this.richText?.str||this.contentsObj?.str&&this.contentsObj.str!==this.richText.str){const t=this._formatContents(this.contentsObj);e.append(t)}else{o.XfaLayer.render({xfaHtml:this.richText.html,intent:"richText",div:e});e.lastChild.className="richText popupContent"}Array.isArray(this.trigger)||(this.trigger=[this.trigger]);for(const t of this.trigger){t.addEventListener("click",this._toggle.bind(this));t.addEventListener("mouseover",this._show.bind(this,!1));t.addEventListener("mouseout",this._hide.bind(this,!1))}e.addEventListener("click",this._hide.bind(this,!0));t.append(e);return t}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.className="popupContent";s.dir=e;const n=t.split(/(?:\r\n?|\n)/);for(let t=0,e=n.length;t{Object.defineProperty(e,"__esModule",{value:!0});e.ColorConverters=void 0;function makeColorComp(t){return Math.floor(255*Math.max(0,Math.min(1,t))).toString(16).padStart(2,"0")}e.ColorConverters=class ColorConverters{static CMYK_G([t,e,s,n]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+n)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_HTML([t]){const e=makeColorComp(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_HTML([t,e,s]){return`#${makeColorComp(t)}${makeColorComp(e)}${makeColorComp(s)}`}static T_HTML(){return"#00000000"}static CMYK_RGB([t,e,s,n]){return["RGB",1-Math.min(1,t+n),1-Math.min(1,s+n),1-Math.min(1,e+n)]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const n=1-t,i=1-e,a=1-s;return["CMYK",n,i,a,Math.min(n,i,a)]}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.XfaLayer=void 0;var n=s(19);e.XfaLayer=class XfaLayer{static setupStorage(t,e,s,n,i){const a=n.getValue(e,{value:null});switch(s.name){case"textarea":null!==a.value&&(t.textContent=a.value);if("print"===i)break;t.addEventListener("input",(t=>{n.setValue(e,{value:t.target.value})}));break;case"input":if("radio"===s.attributes.type||"checkbox"===s.attributes.type){a.value===s.attributes.xfaOn?t.setAttribute("checked",!0):a.value===s.attributes.xfaOff&&t.removeAttribute("checked");if("print"===i)break;t.addEventListener("change",(t=>{n.setValue(e,{value:t.target.checked?t.target.getAttribute("xfaOn"):t.target.getAttribute("xfaOff")})}))}else{null!==a.value&&t.setAttribute("value",a.value);if("print"===i)break;t.addEventListener("input",(t=>{n.setValue(e,{value:t.target.value})}))}break;case"select":if(null!==a.value)for(const t of s.children)t.attributes.value===a.value&&(t.attributes.selected=!0);t.addEventListener("input",(t=>{const s=t.target.options,i=-1===s.selectedIndex?"":s[s.selectedIndex].value;n.setValue(e,{value:i})}))}}static setAttributes({html:t,element:e,storage:s=null,intent:n,linkService:i}){const{attributes:a}=e,r=t instanceof HTMLAnchorElement;"radio"===a.type&&(a.name=`${a.name}-${n}`);for(const[e,s]of Object.entries(a))if(null!=s)switch(e){case"class":s.length&&t.setAttribute(e,s.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",s);break;case"style":Object.assign(t.style,s);break;case"textContent":t.textContent=s;break;default:(!r||"href"!==e&&"newWindow"!==e)&&t.setAttribute(e,s)}r&&i.addLinkAttributes(t,a.href,a.newWindow);s&&a.dataId&&this.setupStorage(t,a.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,a=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:a,linkService:s});const o=[[i,-1,r]],l=t.div;l.append(r);if(t.viewport){const e=`matrix(${t.viewport.transform.join(",")})`;l.style.transform=e}"richText"!==a&&l.setAttribute("class","xfaLayer xfaFont");const c=[];for(;o.length>0;){const[t,i,r]=o.at(-1);if(i+1===t.children.length){o.pop();continue}const l=t.children[++o.at(-1)[1]];if(null===l)continue;const{name:h}=l;if("#text"===h){const t=document.createTextNode(l.value);c.push(t);r.append(t);continue}let d;d=l?.attributes?.xmlns?document.createElementNS(l.attributes.xmlns,h):document.createElement(h);r.append(d);l.attributes&&this.setAttributes({html:d,element:l,storage:e,intent:a,linkService:s});if(l.children&&l.children.length>0)o.push([l,-1,d]);else if(l.value){const t=document.createTextNode(l.value);n.XfaText.shouldBuildText(h)&&c.push(t);d.append(t)}}for(const t of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))t.setAttribute("readOnly",!0);return{textDivs:c}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e;t.div.hidden=!1}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.SVGGraphics=void 0;var n=s(6),i=s(1),a=s(10);let r=class{constructor(){(0,i.unreachable)("Not implemented: SVGGraphics")}};e.SVGGraphics=r;{const o={fontStyle:"normal",fontWeight:"normal",fillColor:"#000000"},l="http://www.w3.org/XML/1998/namespace",c="http://www.w3.org/1999/xlink",h=["butt","round","square"],d=["miter","round","bevel"],createObjectURL=function(t,e="",s=!1){if(URL.createObjectURL&&"undefined"!=typeof Blob&&!s)return URL.createObjectURL(new Blob([t],{type:e}));const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let i=`data:${e};base64,`;for(let e=0,s=t.length;e>2]+n[(3&a)<<4|r>>4]+n[e+1>6:64]+n[e+2>1&2147483647:s>>1&2147483647;e[t]=s}function writePngChunk(t,s,n,i){let a=i;const r=s.length;n[a]=r>>24&255;n[a+1]=r>>16&255;n[a+2]=r>>8&255;n[a+3]=255&r;a+=4;n[a]=255&t.charCodeAt(0);n[a+1]=255&t.charCodeAt(1);n[a+2]=255&t.charCodeAt(2);n[a+3]=255&t.charCodeAt(3);a+=4;n.set(s,a);a+=s.length;const o=function crc32(t,s,n){let i=-1;for(let a=s;a>>8^e[s]}return-1^i}(n,i+4,a);n[a]=o>>24&255;n[a+1]=o>>16&255;n[a+2]=o>>8&255;n[a+3]=255&o}function deflateSyncUncompressed(t){let e=t.length;const s=65535,n=Math.ceil(e/s),i=new Uint8Array(2+e+5*n+4);let a=0;i[a++]=120;i[a++]=156;let r=0;for(;e>s;){i[a++]=0;i[a++]=255;i[a++]=255;i[a++]=0;i[a++]=0;i.set(t.subarray(r,r+s),a);a+=s;r+=s;e-=s}i[a++]=1;i[a++]=255&e;i[a++]=e>>8&255;i[a++]=255&~e;i[a++]=(65535&~e)>>8&255;i.set(t.subarray(r),a);a+=t.length-r;const o=function adler32(t,e,s){let n=1,i=0;for(let a=e;a>24&255;i[a++]=o>>16&255;i[a++]=o>>8&255;i[a++]=255&o;return i}function encode(e,s,n,r){const o=e.width,l=e.height;let c,h,d;const u=e.data;switch(s){case i.ImageKind.GRAYSCALE_1BPP:h=0;c=1;d=o+7>>3;break;case i.ImageKind.RGB_24BPP:h=2;c=8;d=3*o;break;case i.ImageKind.RGBA_32BPP:h=6;c=8;d=4*o;break;default:throw new Error("invalid format")}const p=new Uint8Array((1+d)*l);let g=0,m=0;for(let t=0;t>24&255,o>>16&255,o>>8&255,255&o,l>>24&255,l>>16&255,l>>8&255,255&l,c,h,0,0,0]),b=function deflateSync(t){if(!a.isNodeJS)return deflateSyncUncompressed(t);try{let e;e=parseInt(process.versions.node)>=8?t:Buffer.from(t);const s=require("zlib").deflateSync(e,{level:9});return s instanceof Uint8Array?s:new Uint8Array(s)}catch(t){(0,i.warn)("Not compressing PNG because zlib.deflateSync is unavailable: "+t)}return deflateSyncUncompressed(t)}(p),A=t.length+36+f.length+b.length,_=new Uint8Array(A);let y=0;_.set(t,y);y+=t.length;writePngChunk("IHDR",f,_,y);y+=12+f.length;writePngChunk("IDATA",b,_,y);y+=12+b.length;writePngChunk("IEND",new Uint8Array(0),_,y);return createObjectURL(_,"image/png",n)}return function convertImgDataToPng(t,e,s){return encode(t,void 0===t.kind?i.ImageKind.GRAYSCALE_1BPP:t.kind,e,s)}}();class SVGExtraState{constructor(){this.fontSizeScale=1;this.fontWeight=o.fontWeight;this.fontSize=0;this.textMatrix=i.IDENTITY_MATRIX;this.fontMatrix=i.FONT_IDENTITY_MATRIX;this.leading=0;this.textRenderingMode=i.TextRenderingMode.FILL;this.textMatrixScale=1;this.x=0;this.y=0;this.lineX=0;this.lineY=0;this.charSpacing=0;this.wordSpacing=0;this.textHScale=1;this.textRise=0;this.fillColor=o.fillColor;this.strokeColor="#000000";this.fillAlpha=1;this.strokeAlpha=1;this.lineWidth=1;this.lineJoin="";this.lineCap="";this.miterLimit=0;this.dashArray=[];this.dashPhase=0;this.dependencies=[];this.activeClipUrl=null;this.clipGroup=null;this.maskId=""}clone(){return Object.create(this)}setCurrentPoint(t,e){this.x=t;this.y=e}}function opListToTree(t){let e=[];const s=[];for(const n of t)if("save"!==n.fn)"restore"===n.fn?e=s.pop():e.push(n);else{e.push({fnId:92,fn:"group",items:[]});s.push(e);e=e.at(-1).items}return e}function pf(t){if(Number.isInteger(t))return t.toString();const e=t.toFixed(10);let s=e.length-1;if("0"!==e[s])return e;do{s--}while("0"===e[s]);return e.substring(0,"."===e[s]?s:s+1)}function pm(t){if(0===t[4]&&0===t[5]){if(0===t[1]&&0===t[2])return 1===t[0]&&1===t[3]?"":`scale(${pf(t[0])} ${pf(t[3])})`;if(t[0]===t[3]&&t[1]===-t[2]){return`rotate(${pf(180*Math.acos(t[0])/Math.PI)})`}}else if(1===t[0]&&0===t[1]&&0===t[2]&&1===t[3])return`translate(${pf(t[4])} ${pf(t[5])})`;return`matrix(${pf(t[0])} ${pf(t[1])} ${pf(t[2])} ${pf(t[3])} ${pf(t[4])} ${pf(t[5])})`}let p=0,g=0,m=0;e.SVGGraphics=r=class{constructor(t,e,s=!1){(0,n.deprecated)("The SVG back-end is no longer maintained and *may* be removed in the future.");this.svgFactory=new n.DOMSVGFactory;this.current=new SVGExtraState;this.transformMatrix=i.IDENTITY_MATRIX;this.transformStack=[];this.extraStack=[];this.commonObjs=t;this.objs=e;this.pendingClip=null;this.pendingEOFill=!1;this.embedFonts=!1;this.embeddedFonts=Object.create(null);this.cssStyle=null;this.forceDataSchema=!!s;this._operatorIdMapping=[];for(const t in i.OPS)this._operatorIdMapping[i.OPS[t]]=t}getObject(t,e=null){return"string"==typeof t?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}save(){this.transformStack.push(this.transformMatrix);const t=this.current;this.extraStack.push(t);this.current=t.clone()}restore(){this.transformMatrix=this.transformStack.pop();this.current=this.extraStack.pop();this.pendingClip=null;this.tgrp=null}group(t){this.save();this.executeOpTree(t);this.restore()}loadDependencies(t){const e=t.fnArray,s=t.argsArray;for(let t=0,n=e.length;t{t.get(e,s)}));this.current.dependencies.push(s)}return Promise.all(this.current.dependencies)}transform(t,e,s,n,a,r){const o=[t,e,s,n,a,r];this.transformMatrix=i.Util.transform(this.transformMatrix,o);this.tgrp=null}getSVG(t,e){this.viewport=e;const s=this._initialize(e);return this.loadDependencies(t).then((()=>{this.transformMatrix=i.IDENTITY_MATRIX;this.executeOpTree(this.convertOpList(t));return s}))}convertOpList(t){const e=this._operatorIdMapping,s=t.argsArray,n=t.fnArray,i=[];for(let t=0,a=n.length;t0&&(this.current.lineWidth=t)}setLineCap(t){this.current.lineCap=h[t]}setLineJoin(t){this.current.lineJoin=d[t]}setMiterLimit(t){this.current.miterLimit=t}setStrokeAlpha(t){this.current.strokeAlpha=t}setStrokeRGBColor(t,e,s){this.current.strokeColor=i.Util.makeHexColor(t,e,s)}setFillAlpha(t){this.current.fillAlpha=t}setFillRGBColor(t,e,s){this.current.fillColor=i.Util.makeHexColor(t,e,s);this.current.tspan=this.svgFactory.createElement("svg:tspan");this.current.xcoords=[];this.current.ycoords=[]}setStrokeColorN(t){this.current.strokeColor=this._makeColorN_Pattern(t)}setFillColorN(t){this.current.fillColor=this._makeColorN_Pattern(t)}shadingFill(t){const e=this.viewport.width,s=this.viewport.height,n=i.Util.inverseTransform(this.transformMatrix),a=i.Util.applyTransform([0,0],n),r=i.Util.applyTransform([0,s],n),o=i.Util.applyTransform([e,0],n),l=i.Util.applyTransform([e,s],n),c=Math.min(a[0],r[0],o[0],l[0]),h=Math.min(a[1],r[1],o[1],l[1]),d=Math.max(a[0],r[0],o[0],l[0]),u=Math.max(a[1],r[1],o[1],l[1]),p=this.svgFactory.createElement("svg:rect");p.setAttributeNS(null,"x",c);p.setAttributeNS(null,"y",h);p.setAttributeNS(null,"width",d-c);p.setAttributeNS(null,"height",u-h);p.setAttributeNS(null,"fill",this._makeShadingPattern(t));this.current.fillAlpha<1&&p.setAttributeNS(null,"fill-opacity",this.current.fillAlpha);this._ensureTransformGroup().append(p)}_makeColorN_Pattern(t){return"TilingPattern"===t[0]?this._makeTilingPattern(t):this._makeShadingPattern(t)}_makeTilingPattern(t){const e=t[1],s=t[2],n=t[3]||i.IDENTITY_MATRIX,[a,r,o,l]=t[4],c=t[5],h=t[6],d=t[7],u="shading"+m++,[p,g,f,b]=i.Util.normalizeRect([...i.Util.applyTransform([a,r],n),...i.Util.applyTransform([o,l],n)]),[A,_]=i.Util.singularValueDecompose2dScale(n),y=c*A,v=h*_,S=this.svgFactory.createElement("svg:pattern");S.setAttributeNS(null,"id",u);S.setAttributeNS(null,"patternUnits","userSpaceOnUse");S.setAttributeNS(null,"width",y);S.setAttributeNS(null,"height",v);S.setAttributeNS(null,"x",`${p}`);S.setAttributeNS(null,"y",`${g}`);const x=this.svg,E=this.transformMatrix,C=this.current.fillColor,P=this.current.strokeColor,T=this.svgFactory.create(f-p,b-g);this.svg=T;this.transformMatrix=n;if(2===d){const t=i.Util.makeHexColor(...e);this.current.fillColor=t;this.current.strokeColor=t}this.executeOpTree(this.convertOpList(s));this.svg=x;this.transformMatrix=E;this.current.fillColor=C;this.current.strokeColor=P;S.append(T.childNodes[0]);this.defs.append(S);return`url(#${u})`}_makeShadingPattern(t){"string"==typeof t&&(t=this.objs.get(t));switch(t[0]){case"RadialAxial":const e="shading"+m++,s=t[3];let n;switch(t[1]){case"axial":const s=t[4],i=t[5];n=this.svgFactory.createElement("svg:linearGradient");n.setAttributeNS(null,"id",e);n.setAttributeNS(null,"gradientUnits","userSpaceOnUse");n.setAttributeNS(null,"x1",s[0]);n.setAttributeNS(null,"y1",s[1]);n.setAttributeNS(null,"x2",i[0]);n.setAttributeNS(null,"y2",i[1]);break;case"radial":const a=t[4],r=t[5],o=t[6],l=t[7];n=this.svgFactory.createElement("svg:radialGradient");n.setAttributeNS(null,"id",e);n.setAttributeNS(null,"gradientUnits","userSpaceOnUse");n.setAttributeNS(null,"cx",r[0]);n.setAttributeNS(null,"cy",r[1]);n.setAttributeNS(null,"r",l);n.setAttributeNS(null,"fx",a[0]);n.setAttributeNS(null,"fy",a[1]);n.setAttributeNS(null,"fr",o);break;default:throw new Error(`Unknown RadialAxial type: ${t[1]}`)}for(const t of s){const e=this.svgFactory.createElement("svg:stop");e.setAttributeNS(null,"offset",t[0]);e.setAttributeNS(null,"stop-color",t[1]);n.append(e)}this.defs.append(n);return`url(#${e})`;case"Mesh":(0,i.warn)("Unimplemented pattern Mesh");return null;case"Dummy":return"hotpink";default:throw new Error(`Unknown IR type: ${t[0]}`)}}setDash(t,e){this.current.dashArray=t;this.current.dashPhase=e}constructPath(t,e){const s=this.current;let n=s.x,a=s.y,r=[],o=0;for(const s of t)switch(0|s){case i.OPS.rectangle:n=e[o++];a=e[o++];const t=n+e[o++],s=a+e[o++];r.push("M",pf(n),pf(a),"L",pf(t),pf(a),"L",pf(t),pf(s),"L",pf(n),pf(s),"Z");break;case i.OPS.moveTo:n=e[o++];a=e[o++];r.push("M",pf(n),pf(a));break;case i.OPS.lineTo:n=e[o++];a=e[o++];r.push("L",pf(n),pf(a));break;case i.OPS.curveTo:n=e[o+4];a=e[o+5];r.push("C",pf(e[o]),pf(e[o+1]),pf(e[o+2]),pf(e[o+3]),pf(n),pf(a));o+=6;break;case i.OPS.curveTo2:r.push("C",pf(n),pf(a),pf(e[o]),pf(e[o+1]),pf(e[o+2]),pf(e[o+3]));n=e[o+2];a=e[o+3];o+=4;break;case i.OPS.curveTo3:n=e[o+2];a=e[o+3];r.push("C",pf(e[o]),pf(e[o+1]),pf(n),pf(a),pf(n),pf(a));o+=4;break;case i.OPS.closePath:r.push("Z")}r=r.join(" ");if(s.path&&t.length>0&&t[0]!==i.OPS.rectangle&&t[0]!==i.OPS.moveTo)r=s.path.getAttributeNS(null,"d")+r;else{s.path=this.svgFactory.createElement("svg:path");this._ensureTransformGroup().append(s.path)}s.path.setAttributeNS(null,"d",r);s.path.setAttributeNS(null,"fill","none");s.element=s.path;s.setCurrentPoint(n,a)}endPath(){const t=this.current;t.path=null;if(!this.pendingClip)return;if(!t.element){this.pendingClip=null;return}const e="clippath"+p++,s=this.svgFactory.createElement("svg:clipPath");s.setAttributeNS(null,"id",e);s.setAttributeNS(null,"transform",pm(this.transformMatrix));const n=t.element.cloneNode(!0);"evenodd"===this.pendingClip?n.setAttributeNS(null,"clip-rule","evenodd"):n.setAttributeNS(null,"clip-rule","nonzero");this.pendingClip=null;s.append(n);this.defs.append(s);if(t.activeClipUrl){t.clipGroup=null;for(const t of this.extraStack)t.clipGroup=null;s.setAttributeNS(null,"clip-path",t.activeClipUrl)}t.activeClipUrl=`url(#${e})`;this.tgrp=null}clip(t){this.pendingClip=t}closePath(){const t=this.current;if(t.path){const e=`${t.path.getAttributeNS(null,"d")}Z`;t.path.setAttributeNS(null,"d",e)}}setLeading(t){this.current.leading=-t}setTextRise(t){this.current.textRise=t}setTextRenderingMode(t){this.current.textRenderingMode=t}setHScale(t){this.current.textHScale=t/100}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s);break;case"CA":this.setStrokeAlpha(s);break;case"ca":this.setFillAlpha(s);break;default:(0,i.warn)(`Unimplemented graphic state operator ${e}`)}}fill(){const t=this.current;if(t.element){t.element.setAttributeNS(null,"fill",t.fillColor);t.element.setAttributeNS(null,"fill-opacity",t.fillAlpha);this.endPath()}}stroke(){const t=this.current;if(t.element){this._setStrokeAttributes(t.element);t.element.setAttributeNS(null,"fill","none");this.endPath()}}_setStrokeAttributes(t,e=1){const s=this.current;let n=s.dashArray;1!==e&&n.length>0&&(n=n.map((function(t){return e*t})));t.setAttributeNS(null,"stroke",s.strokeColor);t.setAttributeNS(null,"stroke-opacity",s.strokeAlpha);t.setAttributeNS(null,"stroke-miterlimit",pf(s.miterLimit));t.setAttributeNS(null,"stroke-linecap",s.lineCap);t.setAttributeNS(null,"stroke-linejoin",s.lineJoin);t.setAttributeNS(null,"stroke-width",pf(e*s.lineWidth)+"px");t.setAttributeNS(null,"stroke-dasharray",n.map(pf).join(" "));t.setAttributeNS(null,"stroke-dashoffset",pf(e*s.dashPhase)+"px")}eoFill(){this.current.element?.setAttributeNS(null,"fill-rule","evenodd");this.fill()}fillStroke(){this.stroke();this.fill()}eoFillStroke(){this.current.element?.setAttributeNS(null,"fill-rule","evenodd");this.fillStroke()}closeStroke(){this.closePath();this.stroke()}closeFillStroke(){this.closePath();this.fillStroke()}closeEOFillStroke(){this.closePath();this.eoFillStroke()}paintSolidColorImageMask(){const t=this.svgFactory.createElement("svg:rect");t.setAttributeNS(null,"x","0");t.setAttributeNS(null,"y","0");t.setAttributeNS(null,"width","1px");t.setAttributeNS(null,"height","1px");t.setAttributeNS(null,"fill",this.current.fillColor);this._ensureTransformGroup().append(t)}paintImageXObject(t){const e=this.getObject(t);e?this.paintInlineImageXObject(e):(0,i.warn)(`Dependent image with object ID ${t} is not ready yet`)}paintInlineImageXObject(t,e){const s=t.width,n=t.height,i=u(t,this.forceDataSchema,!!e),a=this.svgFactory.createElement("svg:rect");a.setAttributeNS(null,"x","0");a.setAttributeNS(null,"y","0");a.setAttributeNS(null,"width",pf(s));a.setAttributeNS(null,"height",pf(n));this.current.element=a;this.clip("nonzero");const r=this.svgFactory.createElement("svg:image");r.setAttributeNS(c,"xlink:href",i);r.setAttributeNS(null,"x","0");r.setAttributeNS(null,"y",pf(-n));r.setAttributeNS(null,"width",pf(s)+"px");r.setAttributeNS(null,"height",pf(n)+"px");r.setAttributeNS(null,"transform",`scale(${pf(1/s)} ${pf(-1/n)})`);e?e.append(r):this._ensureTransformGroup().append(r)}paintImageMaskXObject(t){const e=this.getObject(t.data,t);if(e.bitmap){(0,i.warn)("paintImageMaskXObject: ImageBitmap support is not implemented, ensure that the `isOffscreenCanvasSupported` API parameter is disabled.");return}const s=this.current,n=e.width,a=e.height,r=s.fillColor;s.maskId="mask"+g++;const o=this.svgFactory.createElement("svg:mask");o.setAttributeNS(null,"id",s.maskId);const l=this.svgFactory.createElement("svg:rect");l.setAttributeNS(null,"x","0");l.setAttributeNS(null,"y","0");l.setAttributeNS(null,"width",pf(n));l.setAttributeNS(null,"height",pf(a));l.setAttributeNS(null,"fill",r);l.setAttributeNS(null,"mask",`url(#${s.maskId})`);this.defs.append(o);this._ensureTransformGroup().append(l);this.paintInlineImageXObject(e,o)}paintFormXObjectBegin(t,e){Array.isArray(t)&&6===t.length&&this.transform(t[0],t[1],t[2],t[3],t[4],t[5]);if(e){const t=e[2]-e[0],s=e[3]-e[1],n=this.svgFactory.createElement("svg:rect");n.setAttributeNS(null,"x",e[0]);n.setAttributeNS(null,"y",e[1]);n.setAttributeNS(null,"width",pf(t));n.setAttributeNS(null,"height",pf(s));this.current.element=n;this.clip("nonzero");this.endPath()}}paintFormXObjectEnd(){}_initialize(t){const e=this.svgFactory.create(t.width,t.height),s=this.svgFactory.createElement("svg:defs");e.append(s);this.defs=s;const n=this.svgFactory.createElement("svg:g");n.setAttributeNS(null,"transform",pm(t.transform));e.append(n);this.svg=n;return e}_ensureClipGroup(){if(!this.current.clipGroup){const t=this.svgFactory.createElement("svg:g");t.setAttributeNS(null,"clip-path",this.current.activeClipUrl);this.svg.append(t);this.current.clipGroup=t}return this.current.clipGroup}_ensureTransformGroup(){if(!this.tgrp){this.tgrp=this.svgFactory.createElement("svg:g");this.tgrp.setAttributeNS(null,"transform",pm(this.transformMatrix));this.current.activeClipUrl?this._ensureClipGroup().append(this.tgrp):this.svg.append(this.tgrp)}return this.tgrp}}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.PDFNodeStream=void 0;var n=s(1),i=s(32);const a=require("fs"),r=require("http"),o=require("https"),l=require("url"),c=/^file:\/\/\/[a-zA-Z]:\//;e.PDFNodeStream=class PDFNodeStream{constructor(t){this.source=t;this.url=function parseUrl(t){const e=l.parse(t);if("file:"===e.protocol||e.host)return e;if(/^[a-z]:[/\\]/i.test(t))return l.parse(`file:///${t}`);e.host||(e.protocol="file:");return e}(t.url);this.isHttp="http:"===this.url.protocol||"https:"===this.url.protocol;this.isFsUrl="file:"===this.url.protocol;this.httpHeaders=this.isHttp&&t.httpHeaders||{};this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){(0,n.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once.");this._fullRequestReader=this.isFsUrl?new PDFNodeStreamFsFullReader(this):new PDFNodeStreamFullReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=this.isFsUrl?new PDFNodeStreamFsRangeReader(this,t,e):new PDFNodeStreamRangeReader(this,t,e);this._rangeRequestReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}};class BaseFullReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;const e=t.source;this._contentLength=e.length;this._loaded=0;this._filename=null;this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._readableStream=null;this._readCapability=(0,n.createPromiseCapability)();this._headersCapability=(0,n.createPromiseCapability)()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=(0,n.createPromiseCapability)();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));!this._isStreamingSupported&&this._isRangeSupported&&this._error(new n.AbortException("streaming is disabled"));this._storedError&&this._readableStream.destroy(this._storedError)}}class BaseRangeReader{constructor(t){this._url=t.url;this._done=!1;this._storedError=null;this.onProgress=null;this._loaded=0;this._readableStream=null;this._readCapability=(0,n.createPromiseCapability)();const e=t.source;this._isStreamingSupported=!e.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;if(this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();if(null===t){this._readCapability=(0,n.createPromiseCapability)();return this.read()}this._loaded+=t.length;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._readableStream?this._readableStream.destroy(t):this._error(t)}_error(t){this._storedError=t;this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t;t.on("readable",(()=>{this._readCapability.resolve()}));t.on("end",(()=>{t.destroy();this._done=!0;this._readCapability.resolve()}));t.on("error",(t=>{this._error(t)}));this._storedError&&this._readableStream.destroy(this._storedError)}}function createRequestOptions(t,e){return{protocol:t.protocol,auth:t.auth,host:t.hostname,port:t.port,path:t.path,method:"GET",headers:e}}class PDFNodeStreamFullReader extends BaseFullReader{constructor(t){super(t);const handleResponse=e=>{if(404===e.statusCode){const t=new n.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=t;this._headersCapability.reject(t);return}this._headersCapability.resolve();this._setReadableStream(e);const getResponseHeader=t=>this._readableStream.headers[t.toLowerCase()],{allowRangeRequests:s,suggestedLength:a}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:getResponseHeader,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=s;this._contentLength=a||this._contentLength;this._filename=(0,i.extractFilenameFromHeader)(getResponseHeader)};this._request=null;"http:"===this._url.protocol?this._request=r.request(createRequestOptions(this._url,t.httpHeaders),handleResponse):this._request=o.request(createRequestOptions(this._url,t.httpHeaders),handleResponse);this._request.on("error",(t=>{this._storedError=t;this._headersCapability.reject(t)}));this._request.end()}}class PDFNodeStreamRangeReader extends BaseRangeReader{constructor(t,e,s){super(t);this._httpHeaders={};for(const e in t.httpHeaders){const s=t.httpHeaders[e];void 0!==s&&(this._httpHeaders[e]=s)}this._httpHeaders.Range=`bytes=${e}-${s-1}`;const handleResponse=t=>{if(404!==t.statusCode)this._setReadableStream(t);else{const t=new n.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=t}};this._request=null;"http:"===this._url.protocol?this._request=r.request(createRequestOptions(this._url,this._httpHeaders),handleResponse):this._request=o.request(createRequestOptions(this._url,this._httpHeaders),handleResponse);this._request.on("error",(t=>{this._storedError=t}));this._request.end()}}class PDFNodeStreamFsFullReader extends BaseFullReader{constructor(t){super(t);let e=decodeURIComponent(this._url.path);c.test(this._url.href)&&(e=e.replace(/^\//,""));a.lstat(e,((t,s)=>{if(t){"ENOENT"===t.code&&(t=new n.MissingPDFException(`Missing PDF "${e}".`));this._storedError=t;this._headersCapability.reject(t)}else{this._contentLength=s.size;this._setReadableStream(a.createReadStream(e));this._headersCapability.resolve()}}))}}class PDFNodeStreamFsRangeReader extends BaseRangeReader{constructor(t,e,s){super(t);let n=decodeURIComponent(this._url.path);c.test(this._url.href)&&(n=n.replace(/^\//,""));this._setReadableStream(a.createReadStream(n,{start:e,end:s-1}))}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.createResponseStatusError=function createResponseStatusError(t,e){if(404===t||0===t&&e.startsWith("file:"))return new n.MissingPDFException('Missing PDF "'+e+'".');return new n.UnexpectedResponseException(`Unexpected server response (${t}) while retrieving PDF "${e}".`,t)};e.extractFilenameFromHeader=function extractFilenameFromHeader(t){const e=t("Content-Disposition");if(e){let t=(0,i.getFilenameFromContentDispositionHeader)(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch(t){}if((0,a.isPdfFile)(t))return t}return null};e.validateRangeRequestCapabilities=function validateRangeRequestCapabilities({getResponseHeader:t,isHttp:e,rangeChunkSize:s,disableRange:n}){const i={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(t("Content-Length"),10);if(!Number.isInteger(a))return i;i.suggestedLength=a;if(a<=2*s)return i;if(n||!e)return i;if("bytes"!==t("Accept-Ranges"))return i;if("identity"!==(t("Content-Encoding")||"identity"))return i;i.allowRangeRequests=!0;return i};e.validateResponseStatus=function validateResponseStatus(t){return 200===t||206===t};var n=s(1),i=s(33),a=s(6)},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.getFilenameFromContentDispositionHeader=function getFilenameFromContentDispositionHeader(t){let e=!0,s=toParamRegExp("filename\\*","i").exec(t);if(s){s=s[1];let t=rfc2616unquote(s);t=unescape(t);t=rfc5987decode(t);t=rfc2047decode(t);return fixupEncoding(t)}s=function rfc2231getparam(t){const e=[];let s;const n=toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;null!==(s=n.exec(t));){let[,t,n,i]=s;t=parseInt(t,10);if(t in e){if(0===t)break}else e[t]=[n,i]}const i=[];for(let t=0;t{Object.defineProperty(e,"__esModule",{value:!0});e.PDFNetworkStream=void 0;var n=s(1),i=s(32);class NetworkManager{constructor(t,e={}){this.url=t;this.isHttp=/^https?:/i.test(t);this.httpHeaders=this.isHttp&&e.httpHeaders||Object.create(null);this.withCredentials=e.withCredentials||!1;this.getXhr=e.getXhr||function NetworkManager_getXhr(){return new XMLHttpRequest};this.currXhrId=0;this.pendingRequests=Object.create(null)}requestRange(t,e,s){const n={begin:t,end:e};for(const t in s)n[t]=s[t];return this.request(n)}requestFull(t){return this.request(t)}request(t){const e=this.getXhr(),s=this.currXhrId++,n=this.pendingRequests[s]={xhr:e};e.open("GET",this.url);e.withCredentials=this.withCredentials;for(const t in this.httpHeaders){const s=this.httpHeaders[t];void 0!==s&&e.setRequestHeader(t,s)}if(this.isHttp&&"begin"in t&&"end"in t){e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`);n.expectedStatus=206}else n.expectedStatus=200;e.responseType="arraybuffer";t.onError&&(e.onerror=function(s){t.onError(e.status)});e.onreadystatechange=this.onStateChange.bind(this,s);e.onprogress=this.onProgress.bind(this,s);n.onHeadersReceived=t.onHeadersReceived;n.onDone=t.onDone;n.onError=t.onError;n.onProgress=t.onProgress;e.send(null);return s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived){s.onHeadersReceived();delete s.onHeadersReceived}if(4!==i.readyState)return;if(!(t in this.pendingRequests))return;delete this.pendingRequests[t];if(0===i.status&&this.isHttp){s.onError?.(i.status);return}const a=i.status||200;if(!(200===a&&206===s.expectedStatus)&&a!==s.expectedStatus){s.onError?.(i.status);return}const r=function getArrayBuffer(t){const e=t.response;return"string"!=typeof e?e:(0,n.stringToBytes)(e).buffer}(i);if(206===a){const t=i.getResponseHeader("Content-Range"),e=/bytes (\d+)-(\d+)\/(\d+)/.exec(t);s.onDone({begin:parseInt(e[1],10),chunk:r})}else r?s.onDone({begin:0,chunk:r}):s.onError?.(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t];e.abort()}}e.PDFNetworkStream=class PDFNetworkStream{constructor(t){this._source=t;this._manager=new NetworkManager(t.url,{httpHeaders:t.httpHeaders,withCredentials:t.withCredentials});this._rangeChunkSize=t.rangeChunkSize;this._fullRequestReader=null;this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){(0,n.assert)(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once.");this._fullRequestReader=new PDFNetworkStreamFullRequestReader(this._manager,this._source);return this._fullRequestReader}getRangeReader(t,e){const s=new PDFNetworkStreamRangeRequestReader(this._manager,t,e);s.onClosed=this._onRangeRequestReaderClosed.bind(this);this._rangeRequestReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}};class PDFNetworkStreamFullRequestReader{constructor(t,e){this._manager=t;const s={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=e.url;this._fullRequestId=t.requestFull(s);this._headersReceivedCapability=(0,n.createPromiseCapability)();this._disableRange=e.disableRange||!1;this._contentLength=e.length;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._isStreamingSupported=!1;this._isRangeSupported=!1;this._cachedChunks=[];this._requests=[];this._done=!1;this._storedError=void 0;this._filename=null;this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t),getResponseHeader=t=>e.getResponseHeader(t),{allowRangeRequests:s,suggestedLength:n}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:getResponseHeader,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});s&&(this._isRangeSupported=!0);this._contentLength=n||this._contentLength;this._filename=(0,i.extractFilenameFromHeader)(getResponseHeader);this._isRangeSupported&&this._manager.abortRequest(t);this._headersReceivedCapability.resolve()}_onDone(t){if(t)if(this._requests.length>0){this._requests.shift().resolve({value:t.chunk,done:!1})}else this._cachedChunks.push(t.chunk);this._done=!0;if(!(this._cachedChunks.length>0)){for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=(0,i.createResponseStatusError)(t,this._url);this._headersReceivedCapability.reject(this._storedError);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersReceivedCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0){return{value:this._cachedChunks.shift(),done:!1}}if(this._done)return{value:void 0,done:!0};const t=(0,n.createPromiseCapability)();this._requests.push(t);return t.promise}cancel(t){this._done=!0;this._headersReceivedCapability.reject(t);for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId);this._fullRequestReader=null}}class PDFNetworkStreamRangeRequestReader{constructor(t,e,s){this._manager=t;const n={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url;this._requestId=t.requestRange(e,s,n);this._requests=[];this._queuedChunk=null;this._done=!1;this._storedError=void 0;this.onProgress=null;this.onClosed=null}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;if(this._requests.length>0){this._requests.shift().resolve({value:e,done:!1})}else this._queuedChunk=e;this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._close()}_onError(t){this._storedError=(0,i.createResponseStatusError)(t,this._url);for(const t of this._requests)t.reject(this._storedError);this._requests.length=0;this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(null!==this._queuedChunk){const t=this._queuedChunk;this._queuedChunk=null;return{value:t,done:!1}}if(this._done)return{value:void 0,done:!0};const t=(0,n.createPromiseCapability)();this._requests.push(t);return t.promise}cancel(t){this._done=!0;for(const t of this._requests)t.resolve({value:void 0,done:!0});this._requests.length=0;this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId);this._close()}}},(t,e,s)=>{Object.defineProperty(e,"__esModule",{value:!0});e.PDFFetchStream=void 0;var n=s(1),i=s(32);function createFetchOptions(t,e,s){return{method:"GET",headers:t,signal:s.signal,mode:"cors",credentials:e?"include":"same-origin",redirect:"follow"}}function createHeaders(t){const e=new Headers;for(const s in t){const n=t[s];void 0!==n&&e.append(s,n)}return e}e.PDFFetchStream=class PDFFetchStream{constructor(t){this.source=t;this.isHttp=/^https?:/i.test(t.url);this.httpHeaders=this.isHttp&&t.httpHeaders||{};this._fullRequestReader=null;this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){(0,n.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once.");this._fullRequestReader=new PDFFetchStreamReader(this);return this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new PDFFetchStreamRangeReader(this,t,e);this._rangeRequestReaders.push(s);return s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}};class PDFFetchStreamReader{constructor(t){this._stream=t;this._reader=null;this._loaded=0;this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1;this._contentLength=e.length;this._headersCapability=(0,n.createPromiseCapability)();this._disableRange=e.disableRange||!1;this._rangeChunkSize=e.rangeChunkSize;this._rangeChunkSize||this._disableRange||(this._disableRange=!0);this._abortController=new AbortController;this._isStreamingSupported=!e.disableStream;this._isRangeSupported=!e.disableRange;this._headers=createHeaders(this._stream.httpHeaders);const s=e.url;fetch(s,createFetchOptions(this._headers,this._withCredentials,this._abortController)).then((t=>{if(!(0,i.validateResponseStatus)(t.status))throw(0,i.createResponseStatusError)(t.status,s);this._reader=t.body.getReader();this._headersCapability.resolve();const getResponseHeader=e=>t.headers.get(e),{allowRangeRequests:e,suggestedLength:a}=(0,i.validateRangeRequestCapabilities)({getResponseHeader:getResponseHeader,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=e;this._contentLength=a||this._contentLength;this._filename=(0,i.extractFilenameFromHeader)(getResponseHeader);!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new n.AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject);this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded,total:this._contentLength});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}class PDFFetchStreamRangeReader{constructor(t,e,s){this._stream=t;this._reader=null;this._loaded=0;const a=t.source;this._withCredentials=a.withCredentials||!1;this._readCapability=(0,n.createPromiseCapability)();this._isStreamingSupported=!a.disableStream;this._abortController=new AbortController;this._headers=createHeaders(this._stream.httpHeaders);this._headers.append("Range",`bytes=${e}-${s-1}`);const r=a.url;fetch(r,createFetchOptions(this._headers,this._withCredentials,this._abortController)).then((t=>{if(!(0,i.validateResponseStatus)(t.status))throw(0,i.createResponseStatusError)(t.status,r);this._readCapability.resolve();this._reader=t.body.getReader()})).catch(this._readCapability.reject);this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();if(e)return{value:t,done:e};this._loaded+=t.byteLength;this.onProgress?.({loaded:this._loaded});return{value:new Uint8Array(t).buffer,done:!1}}cancel(t){this._reader?.cancel(t);this._abortController.abort()}}}],__webpack_module_cache__={};function __w_pdfjs_require__(t){var e=__webpack_module_cache__[t];if(void 0!==e)return e.exports;var s=__webpack_module_cache__[t]={exports:{}};__webpack_modules__[t](s,s.exports,__w_pdfjs_require__);return s.exports}var __webpack_exports__={};(()=>{var t=__webpack_exports__;Object.defineProperty(t,"__esModule",{value:!0});Object.defineProperty(t,"AbortException",{enumerable:!0,get:function(){return e.AbortException}});Object.defineProperty(t,"AnnotationEditorLayer",{enumerable:!0,get:function(){return a.AnnotationEditorLayer}});Object.defineProperty(t,"AnnotationEditorParamsType",{enumerable:!0,get:function(){return e.AnnotationEditorParamsType}});Object.defineProperty(t,"AnnotationEditorType",{enumerable:!0,get:function(){return e.AnnotationEditorType}});Object.defineProperty(t,"AnnotationEditorUIManager",{enumerable:!0,get:function(){return r.AnnotationEditorUIManager}});Object.defineProperty(t,"AnnotationLayer",{enumerable:!0,get:function(){return o.AnnotationLayer}});Object.defineProperty(t,"AnnotationMode",{enumerable:!0,get:function(){return e.AnnotationMode}});Object.defineProperty(t,"CMapCompressionType",{enumerable:!0,get:function(){return e.CMapCompressionType}});Object.defineProperty(t,"GlobalWorkerOptions",{enumerable:!0,get:function(){return l.GlobalWorkerOptions}});Object.defineProperty(t,"InvalidPDFException",{enumerable:!0,get:function(){return e.InvalidPDFException}});Object.defineProperty(t,"MissingPDFException",{enumerable:!0,get:function(){return e.MissingPDFException}});Object.defineProperty(t,"OPS",{enumerable:!0,get:function(){return e.OPS}});Object.defineProperty(t,"PDFDataRangeTransport",{enumerable:!0,get:function(){return s.PDFDataRangeTransport}});Object.defineProperty(t,"PDFDateString",{enumerable:!0,get:function(){return n.PDFDateString}});Object.defineProperty(t,"PDFWorker",{enumerable:!0,get:function(){return s.PDFWorker}});Object.defineProperty(t,"PasswordResponses",{enumerable:!0,get:function(){return e.PasswordResponses}});Object.defineProperty(t,"PermissionFlag",{enumerable:!0,get:function(){return e.PermissionFlag}});Object.defineProperty(t,"PixelsPerInch",{enumerable:!0,get:function(){return n.PixelsPerInch}});Object.defineProperty(t,"RenderingCancelledException",{enumerable:!0,get:function(){return n.RenderingCancelledException}});Object.defineProperty(t,"SVGGraphics",{enumerable:!0,get:function(){return h.SVGGraphics}});Object.defineProperty(t,"UNSUPPORTED_FEATURES",{enumerable:!0,get:function(){return e.UNSUPPORTED_FEATURES}});Object.defineProperty(t,"UnexpectedResponseException",{enumerable:!0,get:function(){return e.UnexpectedResponseException}});Object.defineProperty(t,"Util",{enumerable:!0,get:function(){return e.Util}});Object.defineProperty(t,"VerbosityLevel",{enumerable:!0,get:function(){return e.VerbosityLevel}});Object.defineProperty(t,"XfaLayer",{enumerable:!0,get:function(){return d.XfaLayer}});Object.defineProperty(t,"build",{enumerable:!0,get:function(){return s.build}});Object.defineProperty(t,"createPromiseCapability",{enumerable:!0,get:function(){return e.createPromiseCapability}});Object.defineProperty(t,"createValidAbsoluteUrl",{enumerable:!0,get:function(){return e.createValidAbsoluteUrl}});Object.defineProperty(t,"getDocument",{enumerable:!0,get:function(){return s.getDocument}});Object.defineProperty(t,"getFilenameFromUrl",{enumerable:!0,get:function(){return n.getFilenameFromUrl}});Object.defineProperty(t,"getPdfFilenameFromUrl",{enumerable:!0,get:function(){return n.getPdfFilenameFromUrl}});Object.defineProperty(t,"getXfaPageViewport",{enumerable:!0,get:function(){return n.getXfaPageViewport}});Object.defineProperty(t,"isDataScheme",{enumerable:!0,get:function(){return n.isDataScheme}});Object.defineProperty(t,"isPdfFile",{enumerable:!0,get:function(){return n.isPdfFile}});Object.defineProperty(t,"loadScript",{enumerable:!0,get:function(){return n.loadScript}});Object.defineProperty(t,"renderTextLayer",{enumerable:!0,get:function(){return i.renderTextLayer}});Object.defineProperty(t,"setLayerDimensions",{enumerable:!0,get:function(){return n.setLayerDimensions}});Object.defineProperty(t,"shadow",{enumerable:!0,get:function(){return e.shadow}});Object.defineProperty(t,"updateTextLayer",{enumerable:!0,get:function(){return i.updateTextLayer}});Object.defineProperty(t,"version",{enumerable:!0,get:function(){return s.version}});var e=__w_pdfjs_require__(1),s=__w_pdfjs_require__(2),n=__w_pdfjs_require__(6),i=__w_pdfjs_require__(21),a=__w_pdfjs_require__(22),r=__w_pdfjs_require__(5),o=__w_pdfjs_require__(27),l=__w_pdfjs_require__(14),c=__w_pdfjs_require__(10),h=__w_pdfjs_require__(30),d=__w_pdfjs_require__(29);if(c.isNodeJS){const{PDFNodeStream:t}=__w_pdfjs_require__(31);(0,s.setPDFNetworkStreamFactory)((e=>new t(e)))}else{const{PDFNetworkStream:t}=__w_pdfjs_require__(34),{PDFFetchStream:e}=__w_pdfjs_require__(35);(0,s.setPDFNetworkStreamFactory)((s=>(0,n.isValidFetchUrl)(s.url)?new e(s):new t(s)))}})();return __webpack_exports__})())); \ No newline at end of file diff --git a/ios/Podfile.lock b/ios/Podfile.lock index 166b1aa..f9cadda 100644 --- a/ios/Podfile.lock +++ b/ios/Podfile.lock @@ -1,6 +1,8 @@ PODS: - camera_avfoundation (0.0.1): - Flutter + - file_saver (0.0.1): + - Flutter - Flutter (1.0.0) - flutter_native_splash (0.0.1): - Flutter @@ -63,6 +65,8 @@ PODS: - path_provider_foundation (0.0.1): - Flutter - FlutterMacOS + - printing (1.0.0): + - Flutter - PromisesObjC (2.4.0) - share_plus (0.0.1): - Flutter @@ -83,12 +87,14 @@ PODS: DEPENDENCIES: - camera_avfoundation (from `.symlinks/plugins/camera_avfoundation/ios`) + - file_saver (from `.symlinks/plugins/file_saver/ios`) - Flutter (from `Flutter`) - flutter_native_splash (from `.symlinks/plugins/flutter_native_splash/ios`) - mobile_scanner (from `.symlinks/plugins/mobile_scanner/ios`) - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) - pasteboard (from `.symlinks/plugins/pasteboard/ios`) - path_provider_foundation (from `.symlinks/plugins/path_provider_foundation/darwin`) + - printing (from `.symlinks/plugins/printing/ios`) - share_plus (from `.symlinks/plugins/share_plus/ios`) - shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`) - smart_auth (from `.symlinks/plugins/smart_auth/ios`) @@ -115,6 +121,8 @@ SPEC REPOS: EXTERNAL SOURCES: camera_avfoundation: :path: ".symlinks/plugins/camera_avfoundation/ios" + file_saver: + :path: ".symlinks/plugins/file_saver/ios" Flutter: :path: Flutter flutter_native_splash: @@ -127,6 +135,8 @@ EXTERNAL SOURCES: :path: ".symlinks/plugins/pasteboard/ios" path_provider_foundation: :path: ".symlinks/plugins/path_provider_foundation/darwin" + printing: + :path: ".symlinks/plugins/printing/ios" share_plus: :path: ".symlinks/plugins/share_plus/ios" shared_preferences_foundation: @@ -144,6 +154,7 @@ EXTERNAL SOURCES: SPEC CHECKSUMS: camera_avfoundation: 759172d1a77ae7be0de08fc104cfb79738b8a59e + file_saver: 503e386464dbe118f630e17b4c2e1190fa0cf808 Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 flutter_native_splash: edf599c81f74d093a4daf8e17bd7a018854bc778 GoogleDataTransport: 6c09b596d841063d76d4288cc2d2f42cc36e1e2a @@ -161,6 +172,7 @@ SPEC CHECKSUMS: package_info_plus: 58f0028419748fad15bf008b270aaa8e54380b1c pasteboard: 982969ebaa7c78af3e6cc7761e8f5e77565d9ce0 path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46 + printing: 233e1b73bd1f4a05615548e9b5a324c98588640b PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 share_plus: 8875f4f2500512ea181eef553c3e27dba5135aad shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78 diff --git a/lib/account_manager/repository/account_repository.dart b/lib/account_manager/repository/account_repository.dart index 52351af..9510997 100644 --- a/lib/account_manager/repository/account_repository.dart +++ b/lib/account_manager/repository/account_repository.dart @@ -132,7 +132,8 @@ class AccountRepository { /// Creates a new super identity, an identity instance, an account associated /// with the identity instance, stores the account in the identity key and /// then logs into that account with no password set at this time - Future createWithNewSuperIdentity(proto.Profile newProfile) async { + Future createWithNewSuperIdentity( + proto.Profile newProfile) async { log.debug('Creating super identity'); final wsi = await WritableSuperIdentity.create(); try { @@ -146,7 +147,7 @@ class AccountRepository { localAccount.superIdentity.recordKey, EncryptionKeyType.none, ''); assert(ok, 'login with none should never fail'); - return wsi.superSecret; + return wsi; } on Exception catch (_) { await wsi.delete(); rethrow; diff --git a/lib/account_manager/views/edit_account_page.dart b/lib/account_manager/views/edit_account_page.dart index 0cf0264..47e2ab2 100644 --- a/lib/account_manager/views/edit_account_page.dart +++ b/lib/account_manager/views/edit_account_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:awesome_extensions/awesome_extensions.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; @@ -55,6 +57,13 @@ class _EditAccountPageState extends State { }); } + @override + void dispose() { + unawaited( + changeWindowSetup(TitleBarStyle.normal, OrientationCapability.normal)); + super.dispose(); + } + Widget _editAccountForm(BuildContext context, {required Future Function(GlobalKey) onSubmit}) => @@ -282,30 +291,27 @@ class _EditAccountPageState extends State { await GoRouterHelper(context).push('/settings'); }) ]), - body: Column(children: [ + body: SingleChildScrollView( + child: Column(children: [ _editAccountForm( context, onSubmit: _onSubmit, - ).expanded(), - Text(translate('edit_account_page.remove_account_description')), - ElevatedButton( - onPressed: _onRemoveAccount, - child: Row(mainAxisSize: MainAxisSize.min, children: [ - const Icon(Icons.person_remove_alt_1, size: 16) - .paddingLTRB(0, 0, 4, 0), - Text(translate('edit_account_page.remove_account')) - .paddingLTRB(0, 0, 4, 0) - ])).paddingLTRB(0, 8, 0, 24), - Text(translate('edit_account_page.destroy_account_description')), - ElevatedButton( - onPressed: _onDestroyAccount, - child: Row(mainAxisSize: MainAxisSize.min, children: [ - const Icon(Icons.person_off, size: 16) - .paddingLTRB(0, 0, 4, 0), - Text(translate('edit_account_page.destroy_account')) - .paddingLTRB(0, 0, 4, 0) - ])).paddingLTRB(0, 8, 0, 24) - ]).paddingSymmetric(horizontal: 24, vertical: 8)) + ).paddingLTRB(0, 0, 0, 32), + OptionBox( + instructions: + translate('edit_account_page.remove_account_description'), + buttonIcon: Icons.person_remove_alt_1, + buttonText: translate('edit_account_page.remove_account'), + onClick: _onRemoveAccount, + ), + OptionBox( + instructions: + translate('edit_account_page.destroy_account_description'), + buttonIcon: Icons.person_off, + buttonText: translate('edit_account_page.destroy_account'), + onClick: _onDestroyAccount, + ) + ]).paddingSymmetric(horizontal: 24, vertical: 8))) .withModalHUD(context, displayModalHUD); } } diff --git a/lib/account_manager/views/new_account_page.dart b/lib/account_manager/views/new_account_page.dart index 6b98467..cc2a333 100644 --- a/lib/account_manager/views/new_account_page.dart +++ b/lib/account_manager/views/new_account_page.dart @@ -70,10 +70,10 @@ class _NewAccountPageState extends State { _isInAsyncCall = true; }); try { - final superSecret = await AccountRepository.instance + final writableSuperIdentity = await AccountRepository.instance .createWithNewSuperIdentity(newProfile); - GoRouterHelper(context) - .pushReplacement('/new_account/recovery_key', extra: superSecret); + GoRouterHelper(context).pushReplacement('/new_account/recovery_key', + extra: [writableSuperIdentity, newProfile.name]); } finally { if (mounted) { setState(() { @@ -94,7 +94,6 @@ class _NewAccountPageState extends State { final displayModalHUD = _isInAsyncCall; return StyledScaffold( - // resizeToAvoidBottomInset: false, appBar: DefaultAppBar( title: Text(translate('new_account_page.titlebar')), leading: Navigator.canPop(context) @@ -114,10 +113,11 @@ class _NewAccountPageState extends State { await GoRouterHelper(context).push('/settings'); }) ]), - body: _newAccountForm( + body: SingleChildScrollView( + child: _newAccountForm( context, onSubmit: _onSubmit, - ).paddingSymmetric(horizontal: 24, vertical: 8), + )).paddingSymmetric(horizontal: 24, vertical: 8), ).withModalHUD(context, displayModalHUD); } } diff --git a/lib/account_manager/views/profile_edit_form.dart b/lib/account_manager/views/profile_edit_form.dart index d7b3c7d..cc6e987 100644 --- a/lib/account_manager/views/profile_edit_form.dart +++ b/lib/account_manager/views/profile_edit_form.dart @@ -58,7 +58,7 @@ class _EditProfileFormState extends State { ) => FormBuilder( key: _formKey, - child: ListView( + child: Column( children: [ Text(widget.header) .textStyle(context.headlineSmall) diff --git a/lib/account_manager/views/profile_widget.dart b/lib/account_manager/views/profile_widget.dart index 1f06476..9d06648 100644 --- a/lib/account_manager/views/profile_widget.dart +++ b/lib/account_manager/views/profile_widget.dart @@ -7,12 +7,15 @@ import '../../theme/theme.dart'; class ProfileWidget extends StatelessWidget { const ProfileWidget({ required proto.Profile profile, + required bool showPronouns, super.key, - }) : _profile = profile; + }) : _profile = profile, + _showPronouns = showPronouns; // final proto.Profile _profile; + final bool _showPronouns; // @@ -42,22 +45,25 @@ class ProfileWidget extends StatelessWidget { borderRadius: BorderRadius.all( Radius.circular(16 * scaleConfig.borderRadiusScale))), ), - child: Column(children: [ + child: Row(children: [ + const Spacer(), Text( _profile.name, - style: textTheme.headlineSmall!.copyWith( + style: textTheme.titleMedium!.copyWith( color: scaleConfig.preferBorders ? scale.primaryScale.border : scale.primaryScale.borderText), textAlign: TextAlign.left, - ).paddingAll(4), - if (_profile.pronouns.isNotEmpty) - Text(_profile.pronouns, - style: textTheme.bodyMedium!.copyWith( + ).paddingAll(12), + if (_profile.pronouns.isNotEmpty && _showPronouns) + Text('(${_profile.pronouns})', + textAlign: TextAlign.right, + style: textTheme.bodySmall!.copyWith( color: scaleConfig.preferBorders ? scale.primaryScale.border - : scale.primaryScale.borderText)) - .paddingLTRB(4, 0, 4, 4), + : scale.primaryScale.primary)) + .paddingAll(12), + const Spacer() ]), ); } diff --git a/lib/account_manager/views/show_recovery_key_page.dart b/lib/account_manager/views/show_recovery_key_page.dart index 6230a85..33de475 100644 --- a/lib/account_manager/views/show_recovery_key_page.dart +++ b/lib/account_manager/views/show_recovery_key_page.dart @@ -1,10 +1,18 @@ +import 'dart:io'; import 'dart:math'; +import 'dart:typed_data'; import 'package:async_tools/async_tools.dart'; import 'package:awesome_extensions/awesome_extensions.dart'; +import 'package:file_saver/file_saver.dart'; import 'package:flutter/material.dart'; import 'package:flutter_translate/flutter_translate.dart'; import 'package:go_router/go_router.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:printing/printing.dart'; +import 'package:qr_flutter/qr_flutter.dart'; +import 'package:screenshot/screenshot.dart'; +import 'package:share_plus/share_plus.dart'; import 'package:veilid_support/veilid_support.dart'; import '../../layout/default_app_bar.dart'; @@ -13,13 +21,18 @@ import '../../tools/tools.dart'; import '../../veilid_processor/veilid_processor.dart'; class ShowRecoveryKeyPage extends StatefulWidget { - const ShowRecoveryKeyPage({required SecretKey secretKey, super.key}) - : _secretKey = secretKey; + const ShowRecoveryKeyPage( + {required WritableSuperIdentity writableSuperIdentity, + required String name, + super.key}) + : _writableSuperIdentity = writableSuperIdentity, + _name = name; @override ShowRecoveryKeyPageState createState() => ShowRecoveryKeyPageState(); - final SecretKey _secretKey; + final WritableSuperIdentity _writableSuperIdentity; + final String _name; } class ShowRecoveryKeyPageState extends State { @@ -33,18 +46,99 @@ class ShowRecoveryKeyPageState extends State { }); } - Widget _recoveryKeyWidget(SecretKey _secretKey) { + Future _shareRecoveryKey( + BuildContext context, Uint8List recoveryKey, String name) async { + setState(() { + _isInAsyncCall = true; + }); + + final screenshotController = ScreenshotController(); + final bytes = await screenshotController.captureFromWidget( + Container( + color: Colors.white, + width: 400, + height: 400, + child: _recoveryKeyWidget(context, recoveryKey, name)), + ); + + setState(() { + _isInAsyncCall = false; + }); + + if (Platform.isLinux) { + // Share plus doesn't do Linux yet + await FileSaver.instance.saveFile(name: 'recovery_key.png', bytes: bytes); + } else { + final xfile = XFile.fromData( + bytes, + mimeType: 'image/png', + name: 'recovery_key.png', + ); + await Share.shareXFiles([xfile]); + } + } + + static Future _printRecoveryKey( + BuildContext context, Uint8List recoveryKey, String name) async { + final wrapped = await WidgetWrapper.fromWidget( + context: context, + widget: SizedBox( + width: 400, + height: 400, + child: _recoveryKeyWidget(context, recoveryKey, name)), + constraints: const BoxConstraints(maxWidth: 400, maxHeight: 400), + pixelRatio: 3); + + final doc = pw.Document() + ..addPage(pw.Page( + build: (context) => + pw.Center(child: pw.Image(wrapped, width: 400)) // Center + )); // Page + + await Printing.layoutPdf(onLayout: (format) async => doc.save()); + } + + static Widget _recoveryKeyWidget( + BuildContext context, Uint8List recoveryKey, String name) { final theme = Theme.of(context); final textTheme = theme.textTheme; + //final scaleConfig = theme.extension()!; + + return Column(mainAxisSize: MainAxisSize.min, children: [ + Text( + style: textTheme.headlineSmall!.copyWith( + color: Colors.black, + fontWeight: FontWeight.bold, + ), + translate('show_recovery_key_page.recovery_key')) + .paddingLTRB(16, 16, 16, 0), + FittedBox( + child: QrImageView.withQr( + size: 300, + qr: QrCode.fromUint8List( + data: recoveryKey, + errorCorrectLevel: QrErrorCorrectLevel.L))) + .paddingLTRB(16, 16, 16, 8) + .expanded(), + Text( + style: textTheme.labelMedium!.copyWith( + color: Colors.black, + fontWeight: FontWeight.bold, + ), + name) + .paddingLTRB(16, 8, 16, 24), + ]); + } + + static Widget _recoveryKeyDialog( + BuildContext context, Uint8List recoveryKey, String name) { + final theme = Theme.of(context); + //final textTheme = theme.textTheme; final scaleConfig = theme.extension()!; final cardsize = min(MediaQuery.of(context).size.shortestSide - 48.0, 400); - final phonoString = prettyPhonoString( - encodePhono(_secretKey.decode()), - wordsPerLine: 2, - ); return Dialog( shape: RoundedRectangleBorder( side: const BorderSide(width: 2), @@ -55,65 +149,19 @@ class ShowRecoveryKeyPageState extends State { constraints: BoxConstraints( minWidth: cardsize, maxWidth: cardsize, - minHeight: cardsize, - maxHeight: cardsize), - child: Column(mainAxisSize: MainAxisSize.min, children: [ - Text( - style: textTheme.headlineSmall!.copyWith( - color: Colors.black, - fontWeight: FontWeight.bold, - ), - translate('show_recovery_key_page.recovery_key')) - .paddingAll(32), - Text( - style: textTheme.headlineSmall!.copyWith( - color: Colors.black, fontFamily: 'Source Code Pro'), - phonoString) - ]))); - } - - Widget _optionBox( - {required String instructions, - required Icon buttonIcon, - required String buttonText, - required void Function() onClick}) { - final theme = Theme.of(context); - final scale = theme.extension()!; - final scaleConfig = theme.extension()!; - - return Container( - constraints: const BoxConstraints(maxWidth: 400), - decoration: BoxDecoration( - color: scale.primaryScale.subtleBackground, - borderRadius: - BorderRadius.circular(8 * scaleConfig.borderRadiusScale), - border: Border.all(color: scale.primaryScale.border)), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text( - style: theme.textTheme.labelMedium! - .copyWith(color: scale.primaryScale.appText), - softWrap: true, - textAlign: TextAlign.center, - instructions), - ElevatedButton( - onPressed: onClick, - child: Row(mainAxisSize: MainAxisSize.min, children: [ - buttonIcon.paddingLTRB(0, 8, 12, 8), - Text(textAlign: TextAlign.center, buttonText) - ])).paddingLTRB(0, 12, 0, 0).toCenter() - ]).paddingAll(12)) - .paddingLTRB(24, 0, 24, 12); + minHeight: cardsize + 16, + maxHeight: cardsize + 16), + child: _recoveryKeyWidget(context, recoveryKey, name))); } @override // ignore: prefer_expression_function_bodies Widget build(BuildContext context) { - final secretKey = widget._secretKey; final theme = Theme.of(context); - final scale = theme.extension()!; - final scaleConfig = theme.extension()!; + // final scale = theme.extension()!; + // final scaleConfig = theme.extension()!; + + final displayModalHUD = _isInAsyncCall; return StyledScaffold( // resizeToAvoidBottomInset: false, @@ -146,42 +194,55 @@ class ShowRecoveryKeyPageState extends State { Text( textAlign: TextAlign.center, translate('show_recovery_key_page.instructions_options')) - .paddingLTRB(12, 0, 12, 12), - _optionBox( + .paddingLTRB(12, 0, 12, 24), + OptionBox( instructions: translate('show_recovery_key_page.instructions_print'), - buttonIcon: const Icon(Icons.print), + buttonIcon: Icons.print, buttonText: translate('show_recovery_key_page.print'), - onClick: () { - // - setState(() { - _codeHandled = true; - }); - }), - _optionBox( - instructions: - translate('show_recovery_key_page.instructions_view'), - buttonIcon: const Icon(Icons.edit_document), - buttonText: translate('show_recovery_key_page.view'), onClick: () { // singleFuture(this, () async { - await showDialog( - context: context, - builder: (context) => _recoveryKeyWidget(secretKey)); + await _printRecoveryKey(context, + widget._writableSuperIdentity.recoveryKey, widget._name); }); setState(() { _codeHandled = true; }); }), - _optionBox( + OptionBox( + instructions: + translate('show_recovery_key_page.instructions_view'), + buttonIcon: Icons.edit_document, + buttonText: translate('show_recovery_key_page.view'), + onClick: () { + // + singleFuture(this, () async { + await showDialog( + context: context, + builder: (context) => _recoveryKeyDialog( + context, + widget._writableSuperIdentity.recoveryKey, + widget._name)); + }); + + setState(() { + _codeHandled = true; + }); + }), + OptionBox( instructions: translate('show_recovery_key_page.instructions_share'), - buttonIcon: const Icon(Icons.ios_share), + buttonIcon: Icons.ios_share, buttonText: translate('show_recovery_key_page.share'), onClick: () { // + singleFuture(this, () async { + await _shareRecoveryKey(context, + widget._writableSuperIdentity.recoveryKey, widget._name); + }); + setState(() { _codeHandled = true; }); @@ -198,8 +259,9 @@ class ShowRecoveryKeyPageState extends State { }, child: Text(translate('button.finish')).paddingAll(8)) .paddingAll(12)) - ]))); + ]))).withModalHUD(context, displayModalHUD); } bool _codeHandled = false; + bool _isInAsyncCall = false; } diff --git a/lib/app.dart b/lib/app.dart index 3dd2d57..3480b18 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -149,8 +149,8 @@ class VeilidChatApp extends StatelessWidget { scale.grayScale.subtleBackground, ] : [ - scale.tertiaryScale.hoverElementBackground, - scale.tertiaryScale.subtleBackground, + scale.primaryScale.hoverElementBackground, + scale.primaryScale.subtleBackground, ]); return DecoratedBox( diff --git a/lib/chat/views/no_conversation_widget.dart b/lib/chat/views/no_conversation_widget.dart index c19b535..e05cbf0 100644 --- a/lib/chat/views/no_conversation_widget.dart +++ b/lib/chat/views/no_conversation_widget.dart @@ -14,14 +14,13 @@ class NoConversationWidget extends StatelessWidget { final theme = Theme.of(context); final scale = theme.extension()!; - return Container( - width: double.infinity, - height: double.infinity, + return DecoratedBox( decoration: BoxDecoration( - color: Theme.of(context).scaffoldBackgroundColor, + color: scale.primaryScale.appBackground, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Icon( Icons.diversity_3, @@ -29,6 +28,7 @@ class NoConversationWidget extends StatelessWidget { size: 48, ), Text( + textAlign: TextAlign.center, translate('chat.start_a_conversation'), style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: scale.primaryScale.subtleBorder, diff --git a/lib/contact_invitation/views/contact_invitation_display.dart b/lib/contact_invitation/views/contact_invitation_display.dart index 25ca4e5..9c0f688 100644 --- a/lib/contact_invitation/views/contact_invitation_display.dart +++ b/lib/contact_invitation/views/contact_invitation_display.dart @@ -11,7 +11,6 @@ import 'package:qr_flutter/qr_flutter.dart'; import 'package:veilid_support/veilid_support.dart'; import '../../theme/theme.dart'; -import '../../tools/tools.dart'; import '../contact_invitation.dart'; class ContactInvitationDisplayDialog extends StatelessWidget { diff --git a/lib/contact_invitation/views/contact_invitation_list_widget.dart b/lib/contact_invitation/views/contact_invitation_list_widget.dart index 4ea44a3..ad72027 100644 --- a/lib/contact_invitation/views/contact_invitation_list_widget.dart +++ b/lib/contact_invitation/views/contact_invitation_list_widget.dart @@ -49,7 +49,7 @@ class ContactInvitationListWidgetState shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16 * scaleConfig.borderRadiusScale), )), - constraints: const BoxConstraints(maxHeight: 200), + constraints: const BoxConstraints(maxHeight: 100), child: Container( width: double.infinity, decoration: ShapeDecoration( @@ -59,6 +59,7 @@ class ContactInvitationListWidgetState BorderRadius.circular(16 * scaleConfig.borderRadiusScale), )), child: ListView.builder( + shrinkWrap: true, controller: _scrollController, itemCount: widget.contactInvitationRecordList.length, itemBuilder: (context, index) { diff --git a/lib/contact_invitation/views/create_invitation_dialog.dart b/lib/contact_invitation/views/create_invitation_dialog.dart index 93b5796..06503a8 100644 --- a/lib/contact_invitation/views/create_invitation_dialog.dart +++ b/lib/contact_invitation/views/create_invitation_dialog.dart @@ -11,7 +11,6 @@ import 'package:veilid_support/veilid_support.dart'; import '../../account_manager/account_manager.dart'; import '../../theme/theme.dart'; -import '../../tools/tools.dart'; import '../contact_invitation.dart'; class CreateInvitationDialog extends StatefulWidget { diff --git a/lib/contact_invitation/views/invitation_dialog.dart b/lib/contact_invitation/views/invitation_dialog.dart index cd962ab..a8afd70 100644 --- a/lib/contact_invitation/views/invitation_dialog.dart +++ b/lib/contact_invitation/views/invitation_dialog.dart @@ -270,11 +270,12 @@ class InvitationDialogState extends State { if (_validInvitation != null && !_isValidating) Column(children: [ Container( - constraints: const BoxConstraints(maxHeight: 64), - width: double.infinity, - child: - ProfileWidget(profile: _validInvitation!.remoteProfile)) - .paddingLTRB(0, 0, 0, 16), + constraints: const BoxConstraints(maxHeight: 64), + width: double.infinity, + child: ProfileWidget( + profile: _validInvitation!.remoteProfile, + showPronouns: true, + )).paddingLTRB(0, 0, 0, 16), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ diff --git a/lib/contact_invitation/views/paste_invitation_dialog.dart b/lib/contact_invitation/views/paste_invitation_dialog.dart index 377d13f..9cd9efc 100644 --- a/lib/contact_invitation/views/paste_invitation_dialog.dart +++ b/lib/contact_invitation/views/paste_invitation_dialog.dart @@ -8,7 +8,6 @@ import 'package:provider/provider.dart'; import 'package:veilid_support/veilid_support.dart'; import '../../theme/theme.dart'; -import '../../tools/tools.dart'; import 'invitation_dialog.dart'; class PasteInvitationDialog extends StatefulWidget { diff --git a/lib/contact_invitation/views/scan_invitation_dialog.dart b/lib/contact_invitation/views/scan_invitation_dialog.dart index d3881c2..9f7a878 100644 --- a/lib/contact_invitation/views/scan_invitation_dialog.dart +++ b/lib/contact_invitation/views/scan_invitation_dialog.dart @@ -13,7 +13,6 @@ import 'package:provider/provider.dart'; import 'package:zxing2/qrcode.dart'; import '../../theme/theme.dart'; -import '../../tools/tools.dart'; import 'invitation_dialog.dart'; // class BarcodeOverlay extends CustomPainter { diff --git a/lib/contacts/views/contact_list_widget.dart b/lib/contacts/views/contact_list_widget.dart index eda6776..eb9958d 100644 --- a/lib/contacts/views/contact_list_widget.dart +++ b/lib/contacts/views/contact_list_widget.dart @@ -10,12 +10,15 @@ import '../../theme/theme.dart'; import 'contact_item_widget.dart'; import 'empty_contact_list_widget.dart'; -class ContactListWidget extends StatelessWidget { +class ContactListWidget extends StatefulWidget { const ContactListWidget( {required this.contactList, required this.disabled, super.key}); final IList contactList; final bool disabled; + @override + State createState() => _ContactListWidgetState(); + @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); @@ -23,45 +26,51 @@ class ContactListWidget extends StatelessWidget { ..add(IterableProperty('contactList', contactList)) ..add(DiagnosticsProperty('disabled', disabled)); } +} + +class _ContactListWidgetState extends State { + @override + void initState() { + super.initState(); + } + + @override + void dispose() { + super.dispose(); + } @override Widget build(BuildContext context) { final theme = Theme.of(context); final scale = theme.extension()!; - return SizedBox.expand( - child: styledTitleContainer( - context: context, - title: translate('contact_list.title'), - child: SizedBox.expand( - child: (contactList.isEmpty) - ? const EmptyContactListWidget() - : SearchableList( - initialList: contactList.toList(), - itemBuilder: (c) => - ContactItemWidget(contact: c, disabled: disabled) - .paddingLTRB(0, 4, 0, 0), - filter: (value) { - final lowerValue = value.toLowerCase(); - return contactList - .where((element) => - element.nickname - .toLowerCase() - .contains(lowerValue) || - element.profile.name - .toLowerCase() - .contains(lowerValue) || - element.profile.pronouns - .toLowerCase() - .contains(lowerValue)) - .toList(); - }, - spaceBetweenSearchAndList: 4, - defaultSuffixIconColor: scale.primaryScale.border, - inputDecoration: InputDecoration( - labelText: translate('contact_list.search'), - ), - ).paddingAll(8), - ))).paddingLTRB(8, 0, 8, 8); + return styledTitleContainer( + context: context, + title: translate('contact_list.title'), + child: SearchableList( + shrinkWrap: true, + initialList: widget.contactList.toList(), + itemBuilder: (c) => + ContactItemWidget(contact: c, disabled: widget.disabled) + .paddingLTRB(0, 4, 0, 0), + filter: (value) { + final lowerValue = value.toLowerCase(); + return widget.contactList + .where((element) => + element.nickname.toLowerCase().contains(lowerValue) || + element.profile.name.toLowerCase().contains(lowerValue) || + element.profile.pronouns.toLowerCase().contains(lowerValue)) + .toList(); + }, + searchFieldHeight: 40, + spaceBetweenSearchAndList: 4, + emptyWidget: const EmptyContactListWidget(), + defaultSuffixIconColor: scale.primaryScale.border, + closeKeyboardWhenScrolling: true, + inputDecoration: InputDecoration( + labelText: translate('contact_list.search'), + ), + ).paddingAll(8), + ).paddingLTRB(8, 0, 8, 8); } } diff --git a/lib/contacts/views/empty_contact_list_widget.dart b/lib/contacts/views/empty_contact_list_widget.dart index db07b4a..ae8a852 100644 --- a/lib/contacts/views/empty_contact_list_widget.dart +++ b/lib/contacts/views/empty_contact_list_widget.dart @@ -17,6 +17,7 @@ class EmptyContactListWidget extends StatelessWidget { return Column( mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( @@ -25,6 +26,7 @@ class EmptyContactListWidget extends StatelessWidget { size: 48, ), Text( + textAlign: TextAlign.center, translate('contact_list.invite_people'), style: textTheme.bodyMedium?.copyWith( color: scale.primaryScale.subtleBorder, diff --git a/lib/layout/home/drawer_menu/drawer_menu.dart b/lib/layout/home/drawer_menu/drawer_menu.dart index 855edcc..8f1ec07 100644 --- a/lib/layout/home/drawer_menu/drawer_menu.dart +++ b/lib/layout/home/drawer_menu/drawer_menu.dart @@ -1,7 +1,6 @@ import 'package:async_tools/async_tools.dart'; import 'package:awesome_extensions/awesome_extensions.dart'; import 'package:fast_immutable_collections/fast_immutable_collections.dart'; -import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_svg/flutter_svg.dart'; @@ -20,7 +19,7 @@ class DrawerMenu extends StatefulWidget { const DrawerMenu({super.key}); @override - State createState() => _DrawerMenuState(); + State createState() => _DrawerMenuState(); } class _DrawerMenuState extends State { @@ -105,10 +104,12 @@ class _DrawerMenuState extends State { width: 34, decoration: BoxDecoration( shape: BoxShape.circle, - border: Border.all( - color: border, - width: 2, - strokeAlign: BorderSide.strokeAlignOutside), + border: scaleConfig.preferBorders + ? Border.all( + color: border, + width: 2, + strokeAlign: BorderSide.strokeAlignOutside) + : null, color: Colors.blue, ), child: AvatarImage( @@ -130,9 +131,18 @@ class _DrawerMenuState extends State { backgroundColor: background, backgroundHoverColor: hoverBackground, backgroundFocusColor: activeBackground, - borderColor: border, - borderHoverColor: hoverBorder, - borderFocusColor: activeBorder, + borderColor: + (scaleConfig.preferBorders || scaleConfig.useVisualIndicators) + ? border + : null, + borderHoverColor: + (scaleConfig.preferBorders || scaleConfig.useVisualIndicators) + ? hoverBorder + : null, + borderFocusColor: + (scaleConfig.preferBorders || scaleConfig.useVisualIndicators) + ? activeBorder + : null, borderRadius: 16 * scaleConfig.borderRadiusScale, callback: callback, footerButtonIcon: loggedIn ? Icons.edit_outlined : null, @@ -143,7 +153,7 @@ class _DrawerMenuState extends State { )); } - Widget _getAccountList( + List _getAccountList( {required IList localAccounts, required TypedKey? activeLocalAccount, required PerAccountCollectionBlocMapState @@ -164,7 +174,9 @@ class _DrawerMenuState extends State { final avAccountRecordState = perAccountState?.avAccountRecordState; if (perAccountState != null && avAccountRecordState != null) { // Account is logged in - final scale = theme.extension()!.primaryScale; + final scale = scaleConfig.useVisualIndicators + ? theme.extension()!.primaryScale + : theme.extension()!.tertiaryScale; final loggedInAccount = avAccountRecordState.when( data: (value) => _makeAccountWidget( name: value.profile.name, @@ -209,14 +221,7 @@ class _DrawerMenuState extends State { } // Assemble main menu - final mainMenu = [...loggedInAccounts, ...loggedOutAccounts]; - - // Return main menu widgets - return Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [...mainMenu], - ); + return [...loggedInAccounts, ...loggedOutAccounts]; } Widget _getButton( @@ -262,18 +267,18 @@ class _DrawerMenuState extends State { }), shape: WidgetStateProperty.resolveWith((states) { if (states.contains(WidgetState.hovered)) { return RoundedRectangleBorder( - side: BorderSide(color: hoverBorder), + side: BorderSide(color: hoverBorder, width: 2), borderRadius: BorderRadius.all( Radius.circular(16 * scaleConfig.borderRadiusScale))); } if (states.contains(WidgetState.focused)) { return RoundedRectangleBorder( - side: BorderSide(color: activeBorder), + side: BorderSide(color: activeBorder, width: 2), borderRadius: BorderRadius.all( Radius.circular(16 * scaleConfig.borderRadiusScale))); } return RoundedRectangleBorder( - side: BorderSide(color: border), + side: BorderSide(color: border, width: 2), borderRadius: BorderRadius.all( Radius.circular(16 * scaleConfig.borderRadiusScale))); })), @@ -306,7 +311,7 @@ class _DrawerMenuState extends State { return Row( mainAxisAlignment: MainAxisAlignment.center, - children: [settingsButton, addButton]).paddingLTRB(0, 16, 0, 0); + children: [settingsButton, addButton]).paddingLTRB(0, 16, 0, 16); } @override @@ -323,8 +328,8 @@ class _DrawerMenuState extends State { begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ + scale.tertiaryScale.border, scale.tertiaryScale.subtleBorder, - scale.tertiaryScale.subtleBackground, ]); return DecoratedBox( @@ -391,35 +396,21 @@ class _DrawerMenuState extends State { ? grayColorFilter : null), ]))), - const Spacer(), - DecoratedBox( - decoration: ShapeDecoration( - shape: RoundedRectangleBorder( - side: !scaleConfig.useVisualIndicators - ? BorderSide.none - : scaleConfig.preferBorders - ? BorderSide(color: scale.tertiaryScale.border) - : BorderSide(color: scale.tertiaryScale.primary), - borderRadius: BorderRadius.circular( - 16 * scaleConfig.borderRadiusScale)), - color: scaleConfig.preferBorders - ? Colors.transparent - : scale.tertiaryScale.border.withAlpha(0x5F)), - child: Column(children: [ - Text(translate('menu.accounts'), - style: theme.textTheme.titleMedium!.copyWith( - color: scaleConfig.preferBorders - ? scale.tertiaryScale.border - : scale.tertiaryScale.primary)) - .paddingLTRB(0, 0, 0, 16), - _getAccountList( - localAccounts: localAccounts, - activeLocalAccount: activeLocalAccount, - perAccountCollectionBlocMapState: - perAccountCollectionBlocMapState) - ]).paddingAll(16)), + Text(translate('menu.accounts'), + style: theme.textTheme.titleMedium!.copyWith( + color: scaleConfig.preferBorders + ? scale.tertiaryScale.border + : scale.tertiaryScale.borderText)) + .paddingLTRB(0, 16, 0, 16), + ListView( + shrinkWrap: true, + children: _getAccountList( + localAccounts: localAccounts, + activeLocalAccount: activeLocalAccount, + perAccountCollectionBlocMapState: + perAccountCollectionBlocMapState)) + .expanded(), _getBottomButtons(), - const Spacer(), Row(children: [ Text('${translate('menu.version')} $packageInfoVersion', style: theme.textTheme.labelMedium! diff --git a/lib/layout/home/drawer_menu/menu_item_widget.dart b/lib/layout/home/drawer_menu/menu_item_widget.dart index b94a243..12c5008 100644 --- a/lib/layout/home/drawer_menu/menu_item_widget.dart +++ b/lib/layout/home/drawer_menu/menu_item_widget.dart @@ -72,7 +72,7 @@ class MenuItemWidget extends StatelessWidget { ).paddingAll(8)), ), if (footerButtonIcon != null) - IconButton.outlined( + IconButton( color: footerButtonIconColor, focusColor: footerButtonIconFocusColor, hoverColor: footerButtonIconHoverColor, diff --git a/lib/layout/home/home_account_ready/home_account_ready_chat.dart b/lib/layout/home/home_account_ready/home_account_ready_chat.dart index cd56aa1..625e01f 100644 --- a/lib/layout/home/home_account_ready/home_account_ready_chat.dart +++ b/lib/layout/home/home_account_ready/home_account_ready_chat.dart @@ -34,6 +34,7 @@ class HomeAccountReadyChatState extends State { @override Widget build(BuildContext context) => SafeArea( + bottom: false, child: buildChatComponent(context), ); } diff --git a/lib/layout/home/home_account_ready/home_account_ready_main.dart b/lib/layout/home/home_account_ready/home_account_ready_main.dart index 0c50bbd..4b79771 100644 --- a/lib/layout/home/home_account_ready/home_account_ready_main.dart +++ b/lib/layout/home/home_account_ready/home_account_ready_main.dart @@ -1,5 +1,4 @@ import 'package:awesome_extensions/awesome_extensions.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_translate/flutter_translate.dart'; @@ -9,7 +8,6 @@ import '../../../account_manager/account_manager.dart'; import '../../../chat/chat.dart'; import '../../../proto/proto.dart' as proto; import '../../../theme/theme.dart'; -import '../../../tools/tools.dart'; import 'main_pager/main_pager.dart'; class HomeAccountReadyMain extends StatefulWidget { @@ -44,7 +42,7 @@ class _HomeAccountReadyMainState extends State { ? scale.primaryScale.border : scale.primaryScale.borderText, constraints: - const BoxConstraints.expand(height: 64, width: 64), + const BoxConstraints.expand(height: 48, width: 48), style: ButtonStyle( backgroundColor: WidgetStateProperty.all( scaleConfig.preferBorders @@ -61,7 +59,7 @@ class _HomeAccountReadyMainState extends State { : scale.primaryScale.borderText, width: 2), borderRadius: BorderRadius.all(Radius.circular( - 16 * scaleConfig.borderRadiusScale))), + 12 * scaleConfig.borderRadiusScale))), )), tooltip: translate('menu.settings_tooltip'), onPressed: () async { @@ -69,7 +67,10 @@ class _HomeAccountReadyMainState extends State { await ctrl.toggle?.call(); //await GoRouterHelper(context).push('/settings'); }).paddingLTRB(0, 0, 8, 0), - ProfileWidget(profile: profile).expanded(), + ProfileWidget( + profile: profile, + showPronouns: false, + ).expanded(), ]).paddingAll(8), MainPager(key: _mainPagerKey).expanded() ])); diff --git a/lib/layout/home/home_account_ready/main_pager/account_page.dart b/lib/layout/home/home_account_ready/main_pager/account_page.dart index f80a8fe..1b48e5b 100644 --- a/lib/layout/home/home_account_ready/main_pager/account_page.dart +++ b/lib/layout/home/home_account_ready/main_pager/account_page.dart @@ -55,6 +55,8 @@ class AccountPageState extends State { tilePadding: const EdgeInsets.fromLTRB(8, 0, 8, 0), backgroundColor: scale.primaryScale.border, collapsedBackgroundColor: scale.primaryScale.border, + dense: true, + minTileHeight: 16, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16 * scaleConfig.borderRadiusScale), @@ -66,10 +68,11 @@ class AccountPageState extends State { title: Text( translate('account_page.contact_invitations'), textAlign: TextAlign.center, - style: textTheme.titleMedium! + style: textTheme.titleSmall! .copyWith(color: scale.primaryScale.borderText), ), iconColor: scale.primaryScale.borderText, + collapsedIconColor: scale.primaryScale.borderText, initiallyExpanded: true, children: [ ContactInvitationListWidget( diff --git a/lib/layout/home/home_account_ready/main_pager/bottom_sheet_action_button.dart b/lib/layout/home/home_account_ready/main_pager/bottom_sheet_action_button.dart index c34e478..494cdb4 100644 --- a/lib/layout/home/home_account_ready/main_pager/bottom_sheet_action_button.dart +++ b/lib/layout/home/home_account_ready/main_pager/bottom_sheet_action_button.dart @@ -46,6 +46,7 @@ class BottomSheetActionButtonState extends State { return _showFab ? FloatingActionButton( elevation: 0, + heroTag: this, hoverElevation: 0, shape: widget.shape, foregroundColor: widget.foregroundColor, diff --git a/lib/layout/home/home_account_ready/main_pager/main_pager.dart b/lib/layout/home/home_account_ready/main_pager/main_pager.dart index d043433..75ca6ed 100644 --- a/lib/layout/home/home_account_ready/main_pager/main_pager.dart +++ b/lib/layout/home/home_account_ready/main_pager/main_pager.dart @@ -113,7 +113,7 @@ class MainPagerState extends State with TickerProviderStateMixin { padding: const EdgeInsets.symmetric(horizontal: 4), child: Text( _bottomLabelList[index], - style: theme.textTheme.labelLarge!.copyWith( + style: theme.textTheme.labelMedium!.copyWith( fontWeight: isActive ? FontWeight.bold : FontWeight.normal, color: color), ), diff --git a/lib/layout/home/home_screen.dart b/lib/layout/home/home_screen.dart index 1e10d27..018c3be 100644 --- a/lib/layout/home/home_screen.dart +++ b/lib/layout/home/home_screen.dart @@ -74,7 +74,10 @@ class HomeScreenState extends State tablet: false, tabletLandscape: false, desktop: false)) { + final activeChatCubit = context.watch(); + return BlocConsumer( + bloc: activeChatCubit, listener: (context, activeChat) { final hasActiveChat = activeChat != null; if (hasActiveChat) { @@ -179,6 +182,7 @@ class HomeScreenState extends State final canClose = activeIndex != -1; return SafeArea( + bottom: false, child: DefaultTextStyle( style: theme.textTheme.bodySmall!, child: ZoomDrawer( diff --git a/lib/router/cubit/router_cubit.dart b/lib/router/cubit/router_cubit.dart index 6323da3..9e9bfe6 100644 --- a/lib/router/cubit/router_cubit.dart +++ b/lib/router/cubit/router_cubit.dart @@ -78,10 +78,14 @@ class RouterCubit extends Cubit { builder: (context, state) => const NewAccountPage(), ), GoRoute( - path: '/new_account/recovery_key', - builder: (context, state) => - ShowRecoveryKeyPage(secretKey: state.extra! as SecretKey), - ), + path: '/new_account/recovery_key', + builder: (context, state) { + final extra = state.extra! as List; + + return ShowRecoveryKeyPage( + writableSuperIdentity: extra[0]! as WritableSuperIdentity, + name: extra[1]! as String); + }), GoRoute( path: '/settings', builder: (context, state) => const SettingsPage(), diff --git a/lib/theme/models/chat_theme.dart b/lib/theme/models/chat_theme.dart index 2d52eae..8623427 100644 --- a/lib/theme/models/chat_theme.dart +++ b/lib/theme/models/chat_theme.dart @@ -31,6 +31,7 @@ ChatTheme makeChatTheme( ), inputBackgroundColor: Colors.blue, inputBorderRadius: BorderRadius.zero, + inputTextStyle: textTheme.bodyLarge!, inputTextDecoration: InputDecoration( filled: !scaleConfig.preferBorders, fillColor: scale.primaryScale.subtleBackground, @@ -77,13 +78,10 @@ ChatTheme makeChatTheme( color: Colors.white, fontSize: 64, ), - receivedMessageBodyTextStyle: TextStyle( + receivedMessageBodyTextStyle: textTheme.bodyLarge!.copyWith( color: scaleConfig.preferBorders ? scale.secondaryScale.calloutBackground : scale.secondaryScale.calloutText, - fontSize: 16, - fontWeight: FontWeight.w500, - height: 1.5, ), receivedEmojiMessageTextStyle: const TextStyle( color: Colors.white, diff --git a/lib/theme/models/slider_tile.dart b/lib/theme/models/slider_tile.dart index 11b4199..e6c4711 100644 --- a/lib/theme/models/slider_tile.dart +++ b/lib/theme/models/slider_tile.dart @@ -106,7 +106,7 @@ class SliderTile extends StatelessWidget { ? tileColor.border : tileColor.borderText) : scale.scale(a.actionScale).primaryText, - icon: a.icon, + icon: subtitle.isNotEmpty ? a.icon : null, label: a.label, padding: const EdgeInsets.all(2)), ) @@ -129,7 +129,7 @@ class SliderTile extends StatelessWidget { ? tileColor.border : tileColor.borderText) : scale.scale(a.actionScale).primaryText, - icon: a.icon, + icon: subtitle.isNotEmpty ? a.icon : null, label: a.label, padding: const EdgeInsets.all(2)), ) @@ -140,9 +140,12 @@ class SliderTile extends StatelessWidget { : const EdgeInsets.fromLTRB(0, 2, 0, 2), child: ListTile( onTap: onTap, + dense: true, + visualDensity: const VisualDensity(vertical: -4), title: Text( title, - softWrap: true, + overflow: TextOverflow.fade, + softWrap: false, ), subtitle: subtitle.isNotEmpty ? Text(subtitle) : null, iconColor: textColor, diff --git a/lib/tools/enter_password.dart b/lib/theme/views/enter_password.dart similarity index 99% rename from lib/tools/enter_password.dart rename to lib/theme/views/enter_password.dart index 2240278..fc876da 100644 --- a/lib/tools/enter_password.dart +++ b/lib/theme/views/enter_password.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_translate/flutter_translate.dart'; -import '../theme/theme.dart'; +import '../theme.dart'; class EnterPasswordDialog extends StatefulWidget { const EnterPasswordDialog({ diff --git a/lib/tools/enter_pin.dart b/lib/theme/views/enter_pin.dart similarity index 99% rename from lib/tools/enter_pin.dart rename to lib/theme/views/enter_pin.dart index 5d476fb..f4055c1 100644 --- a/lib/tools/enter_pin.dart +++ b/lib/theme/views/enter_pin.dart @@ -5,7 +5,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_translate/flutter_translate.dart'; import 'package:pinput/pinput.dart'; -import '../theme/theme.dart'; +import '../theme.dart'; class EnterPinDialog extends StatefulWidget { const EnterPinDialog({ diff --git a/lib/theme/views/option_box.dart b/lib/theme/views/option_box.dart new file mode 100644 index 0000000..508c7ba --- /dev/null +++ b/lib/theme/views/option_box.dart @@ -0,0 +1,54 @@ +import 'package:awesome_extensions/awesome_extensions.dart'; +import 'package:flutter/material.dart'; + +import '../theme.dart'; + +class OptionBox extends StatelessWidget { + const OptionBox( + {required String instructions, + required IconData buttonIcon, + required String buttonText, + required void Function() onClick, + super.key}) + : _instructions = instructions, + _buttonIcon = buttonIcon, + _buttonText = buttonText, + _onClick = onClick; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scale = theme.extension()!; + final scaleConfig = theme.extension()!; + + return Container( + constraints: const BoxConstraints(maxWidth: 400), + decoration: BoxDecoration( + color: scale.primaryScale.subtleBackground, + borderRadius: + BorderRadius.circular(8 * scaleConfig.borderRadiusScale), + border: Border.all(color: scale.primaryScale.border)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + style: theme.textTheme.labelMedium! + .copyWith(color: scale.primaryScale.appText), + softWrap: true, + textAlign: TextAlign.center, + _instructions), + ElevatedButton( + onPressed: _onClick, + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(_buttonIcon, size: 24).paddingLTRB(0, 8, 8, 8), + Text(textAlign: TextAlign.center, _buttonText) + ])).paddingLTRB(0, 12, 0, 0).toCenter() + ]).paddingAll(12)) + .paddingLTRB(24, 0, 24, 12); + } + + final String _instructions; + final IconData _buttonIcon; + final String _buttonText; + final void Function() _onClick; +} diff --git a/lib/tools/pop_control.dart b/lib/theme/views/pop_control.dart similarity index 100% rename from lib/tools/pop_control.dart rename to lib/theme/views/pop_control.dart diff --git a/lib/theme/views/recovery_key_widget.dart b/lib/theme/views/recovery_key_widget.dart new file mode 100644 index 0000000..e69de29 diff --git a/lib/tools/responsive.dart b/lib/theme/views/responsive.dart similarity index 96% rename from lib/tools/responsive.dart rename to lib/theme/views/responsive.dart index 4ee206b..a80faf6 100644 --- a/lib/tools/responsive.dart +++ b/lib/theme/views/responsive.dart @@ -9,7 +9,7 @@ bool get isWeb => kIsWeb; bool get isDesktop => !isWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS); -const kMobileWidthCutoff = 479.0; +const kMobileWidthCutoff = 500.0; bool isMobileWidth(BuildContext context) => MediaQuery.of(context).size.width < kMobileWidthCutoff; diff --git a/lib/theme/views/styled_scaffold.dart b/lib/theme/views/styled_scaffold.dart index 6be898c..055684b 100644 --- a/lib/theme/views/styled_scaffold.dart +++ b/lib/theme/views/styled_scaffold.dart @@ -12,13 +12,15 @@ class StyledScaffold extends StatelessWidget { final scale = theme.extension()!; final scaleConfig = theme.extension()!; - return clipBorder( - clipEnabled: true, - borderEnabled: scaleConfig.useVisualIndicators, - borderRadius: 16 * scaleConfig.borderRadiusScale, - borderColor: scale.primaryScale.border, - child: Scaffold(appBar: appBar, body: body, key: key)) - .paddingAll(32); + return isDesktop + ? clipBorder( + clipEnabled: true, + borderEnabled: scaleConfig.useVisualIndicators, + borderRadius: 16 * scaleConfig.borderRadiusScale, + borderColor: scale.primaryScale.border, + child: Scaffold(appBar: appBar, body: body, key: key)) + .paddingAll(32) + : Scaffold(appBar: appBar, body: body, key: key); } //////////////////////////////////////////////////////////////////////////// diff --git a/lib/theme/views/views.dart b/lib/theme/views/views.dart index 0bdf87b..642255e 100644 --- a/lib/theme/views/views.dart +++ b/lib/theme/views/views.dart @@ -1,5 +1,11 @@ export 'brightness_preferences.dart'; export 'color_preferences.dart'; +export 'enter_password.dart'; +export 'enter_pin.dart'; +export 'option_box.dart'; +export 'pop_control.dart'; +export 'recovery_key_widget.dart'; +export 'responsive.dart'; export 'scanner_error_widget.dart'; export 'styled_dialog.dart'; export 'styled_scaffold.dart'; diff --git a/lib/theme/views/widget_helpers.dart b/lib/theme/views/widget_helpers.dart index 3577d66..1bd71bc 100644 --- a/lib/theme/views/widget_helpers.dart +++ b/lib/theme/views/widget_helpers.dart @@ -183,9 +183,9 @@ Widget styledTitleContainer({ child: Column(children: [ Text( title, - style: textTheme.titleMedium! + style: textTheme.titleSmall! .copyWith(color: titleColor ?? scale.primaryScale.borderText), - ).paddingLTRB(8, 8, 8, 4), + ).paddingLTRB(8, 6, 8, 2), DecoratedBox( decoration: ShapeDecoration( color: diff --git a/lib/tools/loggy.dart b/lib/tools/loggy.dart index c422ec8..69faeb7 100644 --- a/lib/tools/loggy.dart +++ b/lib/tools/loggy.dart @@ -9,7 +9,7 @@ import 'package:loggy/loggy.dart'; import 'package:veilid_support/veilid_support.dart'; import '../veilid_processor/views/developer.dart'; -import 'responsive.dart'; +import '../theme/views/responsive.dart'; import 'state_logger.dart'; String wrapWithLogColor(LogLevel? level, String text) { diff --git a/lib/tools/tools.dart b/lib/tools/tools.dart index b61570e..2963df0 100644 --- a/lib/tools/tools.dart +++ b/lib/tools/tools.dart @@ -1,13 +1,8 @@ - export 'animations.dart'; -export 'enter_password.dart'; -export 'enter_pin.dart'; export 'loggy.dart'; export 'misc.dart'; export 'package_info.dart'; export 'phono_byte.dart'; -export 'pop_control.dart'; -export 'responsive.dart'; export 'shared_preferences.dart'; export 'state_logger.dart'; export 'stream_listenable.dart'; diff --git a/lib/tools/window_control.dart b/lib/tools/window_control.dart index c6e33d3..37816f3 100644 --- a/lib/tools/window_control.dart +++ b/lib/tools/window_control.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:window_manager/window_manager.dart'; -import '../../tools/responsive.dart'; +import '../theme/views/responsive.dart'; export 'package:window_manager/window_manager.dart' show TitleBarStyle; @@ -21,7 +21,7 @@ Future initializeWindowControl() async { const windowOptions = WindowOptions( size: Size(768, 1024), - //minimumSize: Size(480, 480), + minimumSize: Size(400, 500), center: true, backgroundColor: Colors.transparent, skipTaskbar: false, diff --git a/lib/veilid_processor/views/developer.dart b/lib/veilid_processor/views/developer.dart index 85914ab..ed495ae 100644 --- a/lib/veilid_processor/views/developer.dart +++ b/lib/veilid_processor/views/developer.dart @@ -273,59 +273,61 @@ class _DeveloperPageState extends State { body: GestureDetector( onTap: () => FocusScope.of(context).unfocus(), child: SafeArea( + bottom: false, child: Column(children: [ - Stack(alignment: AlignmentDirectional.center, children: [ - Image.asset('assets/images/ellet.png'), - TerminalView(globalDebugTerminal, - textStyle: kDefaultTerminalStyle, - controller: _terminalController, - keyboardType: TextInputType.none, - //autofocus: true, - backgroundOpacity: _showEllet ? 0.75 : 1.0, - onSecondaryTapDown: (details, offset) async { - await copySelection(context); - }) - ]).expanded(), - TextField( - controller: _debugCommandController, - onTapOutside: (event) { - FocusManager.instance.primaryFocus?.unfocus(); - }, - decoration: InputDecoration( - filled: true, - contentPadding: const EdgeInsets.fromLTRB(8, 2, 8, 2), - enabledBorder: OutlineInputBorder( - borderRadius: BorderRadius.circular( - 8 * scaleConfig.borderRadiusScale), - borderSide: BorderSide.none), - border: OutlineInputBorder( - borderRadius: BorderRadius.circular( - 8 * scaleConfig.borderRadiusScale), - ), - fillColor: scale.primaryScale.subtleBackground, - hintText: translate('developer.command'), - suffixIcon: IconButton( - icon: Icon(Icons.send, - color: _debugCommandController.text.isEmpty - ? scale.primaryScale.primary.withAlpha(0x3F) - : scale.primaryScale.primary), - onPressed: _debugCommandController.text.isEmpty - ? null - : () async { - final debugCommand = _debugCommandController.text; - _debugCommandController.clear(); - await _sendDebugCommand(debugCommand); - }, - )), - onChanged: (_) { - setState(() => {}); - }, - onSubmitted: (debugCommand) async { - _debugCommandController.clear(); - await _sendDebugCommand(debugCommand); - }, - ).paddingAll(4) - ])))); + Stack(alignment: AlignmentDirectional.center, children: [ + Image.asset('assets/images/ellet.png'), + TerminalView(globalDebugTerminal, + textStyle: kDefaultTerminalStyle, + controller: _terminalController, + keyboardType: TextInputType.none, + //autofocus: true, + backgroundOpacity: _showEllet ? 0.75 : 1.0, + onSecondaryTapDown: (details, offset) async { + await copySelection(context); + }) + ]).expanded(), + TextField( + controller: _debugCommandController, + onTapOutside: (event) { + FocusManager.instance.primaryFocus?.unfocus(); + }, + decoration: InputDecoration( + filled: true, + contentPadding: const EdgeInsets.fromLTRB(8, 2, 8, 2), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular( + 8 * scaleConfig.borderRadiusScale), + borderSide: BorderSide.none), + border: OutlineInputBorder( + borderRadius: BorderRadius.circular( + 8 * scaleConfig.borderRadiusScale), + ), + fillColor: scale.primaryScale.subtleBackground, + hintText: translate('developer.command'), + suffixIcon: IconButton( + icon: Icon(Icons.send, + color: _debugCommandController.text.isEmpty + ? scale.primaryScale.primary.withAlpha(0x3F) + : scale.primaryScale.primary), + onPressed: _debugCommandController.text.isEmpty + ? null + : () async { + final debugCommand = + _debugCommandController.text; + _debugCommandController.clear(); + await _sendDebugCommand(debugCommand); + }, + )), + onChanged: (_) { + setState(() => {}); + }, + onSubmitted: (debugCommand) async { + _debugCommandController.clear(); + await _sendDebugCommand(debugCommand); + }, + ).paddingAll(4) + ])))); } @override diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc index d2ecb95..3acb238 100644 --- a/linux/flutter/generated_plugin_registrant.cc +++ b/linux/flutter/generated_plugin_registrant.cc @@ -6,7 +6,9 @@ #include "generated_plugin_registrant.h" +#include #include +#include #include #include #include @@ -14,9 +16,15 @@ #include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) file_saver_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FileSaverPlugin"); + file_saver_plugin_register_with_registrar(file_saver_registrar); g_autoptr(FlPluginRegistrar) pasteboard_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "PasteboardPlugin"); pasteboard_plugin_register_with_registrar(pasteboard_registrar); + g_autoptr(FlPluginRegistrar) printing_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "PrintingPlugin"); + printing_plugin_register_with_registrar(printing_registrar); g_autoptr(FlPluginRegistrar) screen_retriever_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "ScreenRetrieverPlugin"); screen_retriever_plugin_register_with_registrar(screen_retriever_registrar); diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake index 10f8b07..d09262f 100644 --- a/linux/flutter/generated_plugins.cmake +++ b/linux/flutter/generated_plugins.cmake @@ -3,7 +3,9 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_saver pasteboard + printing screen_retriever smart_auth url_launcher_linux diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index b888e6d..c311845 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -5,10 +5,12 @@ import FlutterMacOS import Foundation +import file_saver import mobile_scanner import package_info_plus import pasteboard import path_provider_foundation +import printing import screen_retriever import share_plus import shared_preferences_foundation @@ -19,10 +21,12 @@ import veilid import window_manager func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FileSaverPlugin.register(with: registry.registrar(forPlugin: "FileSaverPlugin")) MobileScannerPlugin.register(with: registry.registrar(forPlugin: "MobileScannerPlugin")) FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) PasteboardPlugin.register(with: registry.registrar(forPlugin: "PasteboardPlugin")) PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) + PrintingPlugin.register(with: registry.registrar(forPlugin: "PrintingPlugin")) ScreenRetrieverPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverPlugin")) SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) diff --git a/macos/Podfile.lock b/macos/Podfile.lock index 98cf433..3a69524 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -1,4 +1,6 @@ PODS: + - file_saver (0.0.1): + - FlutterMacOS - FlutterMacOS (1.0.0) - mobile_scanner (5.1.1): - FlutterMacOS @@ -9,6 +11,8 @@ PODS: - path_provider_foundation (0.0.1): - Flutter - FlutterMacOS + - printing (1.0.0): + - FlutterMacOS - screen_retriever (0.0.1): - FlutterMacOS - share_plus (0.0.1): @@ -29,11 +33,13 @@ PODS: - FlutterMacOS DEPENDENCIES: + - file_saver (from `Flutter/ephemeral/.symlinks/plugins/file_saver/macos`) - FlutterMacOS (from `Flutter/ephemeral`) - mobile_scanner (from `Flutter/ephemeral/.symlinks/plugins/mobile_scanner/macos`) - package_info_plus (from `Flutter/ephemeral/.symlinks/plugins/package_info_plus/macos`) - pasteboard (from `Flutter/ephemeral/.symlinks/plugins/pasteboard/macos`) - path_provider_foundation (from `Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin`) + - printing (from `Flutter/ephemeral/.symlinks/plugins/printing/macos`) - screen_retriever (from `Flutter/ephemeral/.symlinks/plugins/screen_retriever/macos`) - share_plus (from `Flutter/ephemeral/.symlinks/plugins/share_plus/macos`) - shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`) @@ -44,6 +50,8 @@ DEPENDENCIES: - window_manager (from `Flutter/ephemeral/.symlinks/plugins/window_manager/macos`) EXTERNAL SOURCES: + file_saver: + :path: Flutter/ephemeral/.symlinks/plugins/file_saver/macos FlutterMacOS: :path: Flutter/ephemeral mobile_scanner: @@ -54,6 +62,8 @@ EXTERNAL SOURCES: :path: Flutter/ephemeral/.symlinks/plugins/pasteboard/macos path_provider_foundation: :path: Flutter/ephemeral/.symlinks/plugins/path_provider_foundation/darwin + printing: + :path: Flutter/ephemeral/.symlinks/plugins/printing/macos screen_retriever: :path: Flutter/ephemeral/.symlinks/plugins/screen_retriever/macos share_plus: @@ -72,11 +82,13 @@ EXTERNAL SOURCES: :path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos SPEC CHECKSUMS: + file_saver: 44e6fbf666677faf097302460e214e977fdd977b FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24 mobile_scanner: 1efac1e53c294b24e3bb55bcc7f4deee0233a86b package_info_plus: fa739dd842b393193c5ca93c26798dff6e3d0e0c pasteboard: 9b69dba6fedbb04866be632205d532fe2f6b1d99 path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46 + printing: 1dd6a1fce2209ec240698e2439a4adbb9b427637 screen_retriever: 59634572a57080243dd1bf715e55b6c54f241a38 share_plus: 36537c04ce0c3e3f5bd297ce4318b6d5ee5fd6cf shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78 diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements index c55503e..fe015f3 100644 --- a/macos/Runner/DebugProfile.entitlements +++ b/macos/Runner/DebugProfile.entitlements @@ -12,6 +12,8 @@ com.apple.security.network.server + com.apple.security.print + keychain-access-groups $(AppIdentifierPrefix)com.veilid.veilidchat diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements index d5ed4c2..8d195f4 100644 --- a/macos/Runner/Release.entitlements +++ b/macos/Runner/Release.entitlements @@ -10,6 +10,8 @@ com.apple.security.network.server + com.apple.security.print + keychain-access-groups $(AppIdentifierPrefix)com.veilid.veilidchat diff --git a/packages/veilid_support/lib/identity_support/identity_instance.dart b/packages/veilid_support/lib/identity_support/identity_instance.dart index 978a30d..1b6bf1f 100644 --- a/packages/veilid_support/lib/identity_support/identity_instance.dart +++ b/packages/veilid_support/lib/identity_support/identity_instance.dart @@ -19,7 +19,9 @@ class IdentityInstance with _$IdentityInstance { required PublicKey publicKey, // Secret key of identity instance - // Encrypted with DH(publicKey, SuperIdentity.secret) with appended salt + // Encrypted with appended salt, key is DeriveSharedSecret( + // password = SuperIdentity.secret, + // salt = publicKey) // Used to recover accounts without generating a new instance @Uint8ListJsonConverter() required Uint8List encryptedSecretKey, diff --git a/packages/veilid_support/lib/identity_support/writable_super_identity.dart b/packages/veilid_support/lib/identity_support/writable_super_identity.dart index 3d88742..093073f 100644 --- a/packages/veilid_support/lib/identity_support/writable_super_identity.dart +++ b/packages/veilid_support/lib/identity_support/writable_super_identity.dart @@ -69,6 +69,12 @@ class WritableSuperIdentity { /// Delete a super identity with secrets Future delete() async => superIdentity.delete(); + /// Produce a recovery key for this superIdentity + Uint8List get recoveryKey => (BytesBuilder() + ..add(superIdentity.recordKey.decode()) + ..add(superSecret.decode())) + .toBytes(); + /// xxx: migration support, new identities, reveal identity secret etc //////////////////////////////////////////////////////////////////////////// @@ -113,8 +119,8 @@ class WritableSuperIdentity { // Make encrypted secret key final cs = await Veilid.instance.getCryptoSystem(identityRecordKey.kind); - final encryptionKey = await cs.generateSharedSecret( - identityPublicKey, superSecret, identityCryptoDomain); + final encryptionKey = await cs.deriveSharedSecret( + superSecret.decode(), identityPublicKey.decode()); final encryptedSecretKey = await cs.encryptNoAuthWithNonce( identitySecretKey.decode(), encryptionKey); diff --git a/pubspec.lock b/pubspec.lock index 736e2bc..8ab1f26 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -97,6 +97,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.2" + barcode: + dependency: transitive + description: + name: barcode + sha256: ab180ce22c6555d77d45f0178a523669db67f95856e3378259ef2ffeb43e6003 + url: "https://pub.dev" + source: hosted + version: "2.2.8" basic_utils: dependency: "direct main" description: @@ -105,6 +113,14 @@ packages: url: "https://pub.dev" source: hosted version: "5.7.0" + bidi: + dependency: transitive + description: + name: bidi + sha256: "1a7d0c696324b2089f72e7671fd1f1f64fef44c980f3cebc84e803967c597b63" + url: "https://pub.dev" + source: hosted + version: "2.0.10" bloc: dependency: "direct main" description: @@ -237,10 +253,10 @@ packages: dependency: transitive description: name: camera_android - sha256: "3af7f0b55f184d392d2eec238aaa30552ebeef2915e5e094f5488bf50d6d7ca2" + sha256: "981654e0e56a4c735f7ecc7bd3921385eb5f7dd13deaf4a6431255d9731df01a" url: "https://pub.dev" source: hosted - version: "0.10.9+3" + version: "0.10.9+7" camera_avfoundation: dependency: transitive description: @@ -409,6 +425,22 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.1" + dio: + dependency: transitive + description: + name: dio + sha256: e17f6b3097b8c51b72c74c9f071a605c47bcc8893839bd66732457a5ebe73714 + url: "https://pub.dev" + source: hosted + version: "5.5.0+1" + dio_web_adapter: + dependency: transitive + description: + name: dio_web_adapter + sha256: "36c5b2d79eb17cdae41e974b7a8284fec631651d2a6f39a8a2ff22327e90aeac" + url: "https://pub.dev" + source: hosted + version: "1.0.1" equatable: dependency: "direct main" description: @@ -441,6 +473,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.0" + file_saver: + dependency: "direct main" + description: + name: file_saver + sha256: d375b351e3331663abbaf99747abd72f159260c58fbbdbca9f926f02c01bdc48 + url: "https://pub.dev" + source: hosted + version: "0.2.13" fixnum: dependency: "direct main" description: @@ -466,10 +506,10 @@ packages: dependency: "direct main" description: name: flutter_bloc - sha256: f0ecf6e6eb955193ca60af2d5ca39565a86b8a142452c5b24d96fb477428f4d2 + sha256: b594505eac31a0518bdcb4b5b79573b8d9117b193cc80cc12e17d639b10aa27a url: "https://pub.dev" source: hosted - version: "8.1.5" + version: "8.1.6" flutter_cache_manager: dependency: transitive description: @@ -489,9 +529,11 @@ packages: flutter_chat_ui: dependency: "direct main" description: - path: "../flutter_chat_ui" - relative: true - source: path + path: "." + ref: main + resolved-ref: d4b9d507d10f5d640156cacfd754f661f8c0f4c1 + url: "https://gitlab.com/veilid/flutter-chat-ui.git" + source: git version: "1.6.14" flutter_form_builder: dependency: "direct main" @@ -534,10 +576,10 @@ packages: dependency: "direct main" description: name: flutter_native_splash - sha256: edf39bcf4d74aca1eb2c1e43c3e445fd9f494013df7f0da752fefe72020eedc0 + sha256: aa06fec78de2190f3db4319dd60fdc8d12b2626e93ef9828633928c2dcaea840 url: "https://pub.dev" source: hosted - version: "2.4.0" + version: "2.4.1" flutter_parsed_text: dependency: transitive description: @@ -627,10 +669,10 @@ packages: dependency: "direct main" description: name: freezed_annotation - sha256: c3fd9336eb55a38cc1bbd79ab17573113a8deccd0ecbbf926cca3c62803b5c2d + sha256: f54946fdb1fa7b01f780841937b1a80783a20b393485f3f6cdf336fd6f4705f2 url: "https://pub.dev" source: hosted - version: "2.4.1" + version: "2.4.2" frontend_server_client: dependency: transitive description: @@ -659,10 +701,10 @@ packages: dependency: "direct main" description: name: go_router - sha256: abec47eb8c8c36ebf41d0a4c64dbbe7f956e39a012b3aafc530e951bdc12fe3f + sha256: cdae1b9c8bd7efadcef6112e81c903662ef2ce105cbd220a04bbb7c3425b5554 url: "https://pub.dev" source: hosted - version: "14.1.4" + version: "14.2.0" graphs: dependency: transitive description: @@ -931,10 +973,10 @@ packages: dependency: transitive description: name: path_provider_android - sha256: "9c96da072b421e98183f9ea7464898428e764bc0ce5567f27ec8693442e72514" + sha256: bca87b0165ffd7cdb9cad8edd22d18d2201e886d9a9f19b4fb3452ea7df3a72a url: "https://pub.dev" source: hosted - version: "2.2.5" + version: "2.2.6" path_provider_foundation: dependency: transitive description: @@ -967,6 +1009,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.1" + pdf: + dependency: "direct main" + description: + name: pdf + sha256: "81d5522bddc1ef5c28e8f0ee40b71708761753c163e0c93a40df56fd515ea0f0" + url: "https://pub.dev" + source: hosted + version: "3.11.0" + pdf_widget_wrapper: + dependency: transitive + description: + name: pdf_widget_wrapper + sha256: c930860d987213a3d58c7ec3b7ecf8085c3897f773e8dc23da9cae60a5d6d0f5 + url: "https://pub.dev" + source: hosted + version: "1.0.4" petitparser: dependency: transitive description: @@ -995,10 +1053,10 @@ packages: dependency: transitive description: name: platform - sha256: "12220bb4b65720483f8fa9450b4332347737cf8213dd2840d8b2c823e47243ec" + sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65" url: "https://pub.dev" source: hosted - version: "3.1.4" + version: "3.1.5" plugin_platform_interface: dependency: transitive description: @@ -1031,6 +1089,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.2.0" + printing: + dependency: "direct main" + description: + name: printing + sha256: cc4b256a5a89d5345488e3318897b595867f5181b8c5ed6fc63bfa5f2044aec3 + url: "https://pub.dev" + source: hosted + version: "5.13.1" protobuf: dependency: "direct main" description: @@ -1075,10 +1141,10 @@ packages: dependency: "direct main" description: name: qr_code_dart_scan - sha256: "948271f8dc39ab3798341783f0ab7bfdb723054fdc9ea0928c0a5be8503ee01c" + sha256: "52912da40f5e40a197b890108af9d2a6baa0c5812b77bfb085c8ee9e3c4f1f52" url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.8.1" qr_flutter: dependency: "direct main" description: @@ -1135,6 +1201,14 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.9" + screenshot: + dependency: "direct main" + description: + name: screenshot + sha256: "63817697a7835e6ce82add4228e15d233b74d42975c143ad8cfe07009fab866b" + url: "https://pub.dev" + source: hosted + version: "3.0.0" scroll_to_index: dependency: "direct main" description: @@ -1547,7 +1621,7 @@ packages: path: "../veilid/veilid-flutter" relative: true source: path - version: "0.3.2" + version: "0.3.3" veilid_support: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index c5c6a3f..801d5ae 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -28,6 +28,7 @@ dependencies: cupertino_icons: ^1.0.8 equatable: ^2.0.5 fast_immutable_collections: ^10.2.4 + file_saver: ^0.2.13 fixnum: ^1.1.0 flutter: sdk: flutter @@ -63,8 +64,10 @@ dependencies: pasteboard: ^0.2.0 path: ^1.9.0 path_provider: ^2.1.3 + pdf: ^3.11.0 pinput: ^4.0.0 preload_page_view: ^0.2.0 + printing: ^5.13.1 protobuf: ^3.1.0 provider: ^6.1.2 qr_code_dart_scan: ^0.8.0 @@ -72,6 +75,7 @@ dependencies: quickalert: ^1.1.0 radix_colors: ^1.0.4 reorderable_grid: ^1.0.10 + screenshot: ^3.0.0 scroll_to_index: ^3.0.1 searchable_listview: ^2.14.0 share_plus: ^9.0.0 @@ -95,13 +99,13 @@ dependencies: xterm: ^4.0.0 zxing2: ^0.2.3 -dependency_overrides: +# dependency_overrides: # async_tools: # path: ../dart_async_tools # bloc_advanced_tools: # path: ../bloc_advanced_tools - flutter_chat_ui: - path: ../flutter_chat_ui +# flutter_chat_ui: +# path: ../flutter_chat_ui dev_dependencies: build_runner: ^2.4.11 @@ -146,6 +150,8 @@ flutter: - assets/images/title.svg - assets/images/vlogo.svg - assets/images/ellet.png + # Printing + - assets/js/pdf/3.2.146/pdf.min.js # Fonts fonts: - family: Source Code Pro diff --git a/web/index.html b/web/index.html index a9c0bf2..dfd1680 100644 --- a/web/index.html +++ b/web/index.html @@ -56,7 +56,10 @@ } run(); + - + \ No newline at end of file diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index c453077..041a716 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -6,7 +6,9 @@ #include "generated_plugin_registrant.h" +#include #include +#include #include #include #include @@ -15,8 +17,12 @@ #include void RegisterPlugins(flutter::PluginRegistry* registry) { + FileSaverPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FileSaverPlugin")); PasteboardPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("PasteboardPlugin")); + PrintingPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PrintingPlugin")); ScreenRetrieverPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("ScreenRetrieverPlugin")); SharePlusWindowsPluginCApiRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index e705509..17a8144 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -3,7 +3,9 @@ # list(APPEND FLUTTER_PLUGIN_LIST + file_saver pasteboard + printing screen_retriever share_plus smart_auth