PageSourceSearch

https://www.akishima.or.jp/monodukuri4/javascript/pdf.js

js akishima.or.jp collected 2026-10-04 21:30:24 UTC 388,899 bytes, 14,618 lines download raw bytes

1/**
2 * @licstart The following is the entire license notice for the
3 * Javascript code in this page
4 *
5 * Copyright 2021 Mozilla Foundation
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *     http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * @licend The above is the entire license notice for the
20 * Javascript code in this page
21 */
22
23(function webpackUniversalModuleDefinition(root, factory) {
24	if(typeof exports === 'object' && typeof module === 'object')
25		module.exports = factory();
26	else if(typeof define === 'function' && define.amd)
27		define("pdfjs-dist/build/pdf", [], factory);
28	else if(typeof exports === 'object')
29		exports["pdfjs-dist/build/pdf"] = factory();
30	else
31		root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
32})(this, function() {
33return /******/ (() => { // webpackBootstrap
34/******/ 	"use strict";
35/******/ 	var __webpack_modules__ = ([
36/* 0 */,
37/* 1 */
38/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
39
40
41
42Object.defineProperty(exports, "__esModule", ({
43  value: true
44}));
45exports.addLinkAttributes = addLinkAttributes;
46exports.deprecated = deprecated;
47exports.getFilenameFromUrl = getFilenameFromUrl;
48exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
49exports.isDataScheme = isDataScheme;
50exports.isFetchSupported = isFetchSupported;
51exports.isPdfFile = isPdfFile;
52exports.isValidFetchUrl = isValidFetchUrl;
53exports.loadScript = loadScript;
54exports.StatTimer = exports.RenderingCancelledException = exports.PDFDateString = exports.PageViewport = exports.LinkTarget = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.BaseCMapReaderFactory = exports.BaseCanvasFactory = void 0;
55
56var _util = __w_pdfjs_require__(2);
57
58const DEFAULT_LINK_REL = "noopener noreferrer nofollow";
59exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
60const SVG_NS = "http://www.w3.org/2000/svg";
61
62class BaseCanvasFactory {
63  constructor() {
64    if (this.constructor === BaseCanvasFactory) {
65      (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
66    }
67  }
68
69  create(width, height) {
70    (0, _util.unreachable)("Abstract method `create` called.");
71  }
72
73  reset(canvasAndContext, width, height) {
74    if (!canvasAndContext.canvas) {
75      throw new Error("Canvas is not specified");
76    }
77
78    if (width <= 0 || height <= 0) {
79      throw new Error("Invalid canvas size");
80    }
81
82    canvasAndContext.canvas.width = width;
83    canvasAndContext.canvas.height = height;
84  }
85
86  destroy(canvasAndContext) {
87    if (!canvasAndContext.canvas) {
88      throw new Error("Canvas is not specified");
89    }
90
91    canvasAndContext.canvas.width = 0;
92    canvasAndContext.canvas.height = 0;
93    canvasAndContext.canvas = null;
94    canvasAndContext.context = null;
95  }
96
97}
98
99exports.BaseCanvasFactory = BaseCanvasFactory;
100
101class DOMCanvasFactory extends BaseCanvasFactory {
102  constructor({
103    ownerDocument = globalThis.document
104  } = {}) {
105    super();
106    this._document = ownerDocument;
107  }
108
109  create(width, height) {
110    if (width <= 0 || height <= 0) {
111      throw new Error("Invalid canvas size");
112    }
113
114    const canvas = this._document.createElement("canvas");
115
116    const context = canvas.getContext("2d");
117    canvas.width = width;
118    canvas.height = height;
119    return {
120      canvas,
121      context
122    };
123  }
124
125}
126
127exports.DOMCanvasFactory = DOMCanvasFactory;
128
129class BaseCMapReaderFactory {
130  constructor({
131    baseUrl = null,
132    isCompressed = false
133  }) {
134    if (this.constructor === BaseCMapReaderFactory) {
135      (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
136    }
137
138    this.baseUrl = baseUrl;
139    this.isCompressed = isCompressed;
140  }
141
142  async fetch({
143    name
144  }) {
145    if (!this.baseUrl) {
146      throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
147    }
148
149    if (!name) {
150      throw new Error("CMap name must be specified.");
151    }
152
153    const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
154    const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
155    return this._fetchData(url, compressionType).catch(reason => {
156      throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
157    });
158  }
159
160  _fetchData(url, compressionType) {
161    (0, _util.unreachable)("Abstract method `_fetchData` called.");
162  }
163
164}
165
166exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
167
168class DOMCMapReaderFactory extends BaseCMapReaderFactory {
169  _fetchData(url, compressionType) {
170    if (isFetchSupported() && isValidFetchUrl(url, document.baseURI)) {
171      return fetch(url).then(async response => {
172        if (!response.ok) {
173          throw new Error(response.statusText);
174        }
175
176        let cMapData;
177
178        if (this.isCompressed) {
179          cMapData = new Uint8Array(await response.arrayBuffer());
180        } else {
181          cMapData = (0, _util.stringToBytes)(await response.text());
182        }
183
184        return {
185          cMapData,
186          compressionType
187        };
188      });
189    }
190
191    return new Promise((resolve, reject) => {
192      const request = new XMLHttpRequest();
193      request.open("GET", url, true);
194
195      if (this.isCompressed) {
196        request.responseType = "arraybuffer";
197      }
198
199      request.onreadystatechange = () => {
200        if (request.readyState !== XMLHttpRequest.DONE) {
201          return;
202        }
203
204        if (request.status === 200 || request.status === 0) {
205          let cMapData;
206
207          if (this.isCompressed && request.response) {
208            cMapData = new Uint8Array(request.response);
209          } else if (!this.isCompressed && request.responseText) {
210            cMapData = (0, _util.stringToBytes)(request.responseText);
211          }
212
213          if (cMapData) {
214            resolve({
215              cMapData,
216              compressionType
217            });
218            return;
219          }
220        }
221
222        reject(new Error(request.statusText));
223      };
224
225      request.send(null);
226    });
227  }
228
229}
230
231exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
232
233class DOMSVGFactory {
234  create(width, height) {
235    (0, _util.assert)(width > 0 && height > 0, "Invalid SVG dimensions");
236    const svg = document.createElementNS(SVG_NS, "svg:svg");
237    svg.setAttribute("version", "1.1");
238    svg.setAttribute("width", width + "px");
239    svg.setAttribute("height", height + "px");
240    svg.setAttribute("preserveAspectRatio", "none");
241    svg.setAttribute("viewBox", "0 0 " + width + " " + height);
242    return svg;
243  }
244
245  createElement(type) {
246    (0, _util.assert)(typeof type === "string", "Invalid SVG element type");
247    return document.createElementNS(SVG_NS, type);
248  }
249
250}
251
252exports.DOMSVGFactory = DOMSVGFactory;
253
254class PageViewport {
255  constructor({
256    viewBox,
257    scale,
258    rotation,
259    offsetX = 0,
260    offsetY = 0,
261    dontFlip = false
262  }) {
263    this.viewBox = viewBox;
264    this.scale = scale;
265    this.rotation = rotation;
266    this.offsetX = offsetX;
267    this.offsetY = offsetY;
268    const centerX = (viewBox[2] + viewBox[0]) / 2;
269    const centerY = (viewBox[3] + viewBox[1]) / 2;
270    let rotateA, rotateB, rotateC, rotateD;
271    rotation %= 360;
272
273    if (rotation < 0) {
274      rotation += 360;
275    }
276
277    switch (rotation) {
278      case 180:
279        rotateA = -1;
280        rotateB = 0;
281        rotateC = 0;
282        rotateD = 1;
283        break;
284
285      case 90:
286        rotateA = 0;
287        rotateB = 1;
288        rotateC = 1;
289        rotateD = 0;
290        break;
291
292      case 270:
293        rotateA = 0;
294        rotateB = -1;
295        rotateC = -1;
296        rotateD = 0;
297        break;
298
299      case 0:
300        rotateA = 1;
301        rotateB = 0;
302        rotateC = 0;
303        rotateD = -1;
304        break;
305
306      default:
307        throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
308    }
309
310    if (dontFlip) {
311      rotateC = -rotateC;
312      rotateD = -rotateD;
313    }
314
315    let offsetCanvasX, offsetCanvasY;
316    let width, height;
317
318    if (rotateA === 0) {
319      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
320      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
321      width = Math.abs(viewBox[3] - viewBox[1]) * scale;
322      height = Math.abs(viewBox[2] - viewBox[0]) * scale;
323    } else {
324      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
325      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
326      width = Math.abs(viewBox[2] - viewBox[0]) * scale;
327      height = Math.abs(viewBox[3] - viewBox[1]) * scale;
328    }
329
330    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
331    this.width = width;
332    this.height = height;
333  }
334
335  clone({
336    scale = this.scale,
337    rotation = this.rotation,
338    offsetX = this.offsetX,
339    offsetY = this.offsetY,
340    dontFlip = false
341  } = {}) {
342    return new PageViewport({
343      viewBox: this.viewBox.slice(),
344      scale,
345      rotation,
346      offsetX,
347      offsetY,
348      dontFlip
349    });
350  }
351
352  convertToViewportPoint(x, y) {
353    return _util.Util.applyTransform([x, y], this.transform);
354  }
355
356  convertToViewportRectangle(rect) {
357    const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
358
359    const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
360
361    return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
362  }
363
364  convertToPdfPoint(x, y) {
365    return _util.Util.applyInverseTransform([x, y], this.transform);
366  }
367
368}
369
370exports.PageViewport = PageViewport;
371
372class RenderingCancelledException extends _util.BaseException {
373  constructor(msg, type) {
374    super(msg);
375    this.type = type;
376  }
377
378}
379
380exports.RenderingCancelledException = RenderingCancelledException;
381const LinkTarget = {
382  NONE: 0,
383  SELF: 1,
384  BLANK: 2,
385  PARENT: 3,
386  TOP: 4
387};
388exports.LinkTarget = LinkTarget;
389
390function addLinkAttributes(link, {
391  url,
392  target,
393  rel,
394  enabled = true
395} = {}) {
396  (0, _util.assert)(url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.');
397  const urlNullRemoved = (0, _util.removeNullCharacters)(url);
398
399  if (enabled) {
400    link.href = link.title = urlNullRemoved;
401  } else {
402    link.href = "";
403    link.title = `Disabled: ${urlNullRemoved}`;
404
405    link.onclick = () => {
406      return false;
407    };
408  }
409
410  let targetStr = "";
411
412  switch (target) {
413    case LinkTarget.NONE:
414      break;
415
416    case LinkTarget.SELF:
417      targetStr = "_self";
418      break;
419
420    case LinkTarget.BLANK:
421      targetStr = "_blank";
422      break;
423
424    case LinkTarget.PARENT:
425      targetStr = "_parent";
426      break;
427
428    case LinkTarget.TOP:
429      targetStr = "_top";
430      break;
431  }
432
433  link.target = targetStr;
434  link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL;
435}
436
437function isDataScheme(url) {
438  const ii = url.length;
439  let i = 0;
440
441  while (i < ii && url[i].trim() === "") {
442    i++;
443  }
444
445  return url.substring(i, i + 5).toLowerCase() === "data:";
446}
447
448function isPdfFile(filename) {
449  return typeof filename === "string" && /\.pdf$/i.test(filename);
450}
451
452function getFilenameFromUrl(url) {
453  const anchor = url.indexOf("#");
454  const query = url.indexOf("?");
455  const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
456  return url.substring(url.lastIndexOf("/", end) + 1, end);
457}
458
459function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
460  if (typeof url !== "string") {
461    return defaultFilename;
462  }
463
464  if (isDataScheme(url)) {
465    (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
466    return defaultFilename;
467  }
468
469  const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
470  const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
471  const splitURI = reURI.exec(url);
472  let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
473
474  if (suggestedFilename) {
475    suggestedFilename = suggestedFilename[0];
476
477    if (suggestedFilename.includes("%")) {
478      try {
479        suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
480      } catch (ex) {}
481    }
482  }
483
484  return suggestedFilename || defaultFilename;
485}
486
487class StatTimer {
488  constructor() {
489    this.started = Object.create(null);
490    this.times = [];
491  }
492
493  time(name) {
494    if (name in this.started) {
495      (0, _util.warn)(`Timer is already running for ${name}`);
496    }
497
498    this.started[name] = Date.now();
499  }
500
501  timeEnd(name) {
502    if (!(name in this.started)) {
503      (0, _util.warn)(`Timer has not been started for ${name}`);
504    }
505
506    this.times.push({
507      name,
508      start: this.started[name],
509      end: Date.now()
510    });
511    delete this.started[name];
512  }
513
514  toString() {
515    const outBuf = [];
516    let longest = 0;
517
518    for (const time of this.times) {
519      const name = time.name;
520
521      if (name.length > longest) {
522        longest = name.length;
523      }
524    }
525
526    for (const time of this.times) {
527      const duration = time.end - time.start;
528      outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
529    }
530
531    return outBuf.join("");
532  }
533
534}
535
536exports.StatTimer = StatTimer;
537
538function isFetchSupported() {
539  return typeof fetch !== "undefined" && typeof Response !== "undefined" && "body" in Response.prototype && typeof ReadableStream !== "undefined";
540}
541
542function isValidFetchUrl(url, baseUrl) {
543  try {
544    const {
545      protocol
546    } = baseUrl ? new URL(url, baseUrl) : new URL(url);
547    return protocol === "http:" || protocol === "https:";
548  } catch (ex) {
549    return false;
550  }
551}
552
553function loadScript(src, removeScriptElement = false) {
554  return new Promise((resolve, reject) => {
555    const script = document.createElement("script");
556    script.src = src;
557
558    script.onload = function (evt) {
559      if (removeScriptElement) {
560        script.remove();
561      }
562
563      resolve(evt);
564    };
565
566    script.onerror = function () {
567      reject(new Error(`Cannot load script at: ${script.src}`));
568    };
569
570    (document.head || document.documentElement).appendChild(script);
571  });
572}
573
574function deprecated(details) {
575  console.log("Deprecated API usage: " + details);
576}
577
578let pdfDateStringRegex;
579
580class PDFDateString {
581  static toDateObject(input) {
582    if (!input || !(0, _util.isString)(input)) {
583      return null;
584    }
585
586    if (!pdfDateStringRegex) {
587      pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
588    }
589
590    const matches = pdfDateStringRegex.exec(input);
591
592    if (!matches) {
593      return null;
594    }
595
596    const year = parseInt(matches[1], 10);
597    let month = parseInt(matches[2], 10);
598    month = month >= 1 && month <= 12 ? month - 1 : 0;
599    let day = parseInt(matches[3], 10);
600    day = day >= 1 && day <= 31 ? day : 1;
601    let hour = parseInt(matches[4], 10);
602    hour = hour >= 0 && hour <= 23 ? hour : 0;
603    let minute = parseInt(matches[5], 10);
604    minute = minute >= 0 && minute <= 59 ? minute : 0;
605    let second = parseInt(matches[6], 10);
606    second = second >= 0 && second <= 59 ? second : 0;
607    const universalTimeRelation = matches[7] || "Z";
608    let offsetHour = parseInt(matches[8], 10);
609    offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
610    let offsetMinute = parseInt(matches[9], 10) || 0;
611    offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
612
613    if (universalTimeRelation === "-") {
614      hour += offsetHour;
615      minute += offsetMinute;
616    } else if (universalTimeRelation === "+") {
617      hour -= offsetHour;
618      minute -= offsetMinute;
619    }
620
621    return new Date(Date.UTC(year, month, day, hour, minute, second));
622  }
623
624}
625
626exports.PDFDateString = PDFDateString;
627
628/***/ }),
629/* 2 */
630/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
631
632
633
634Object.defineProperty(exports, "__esModule", ({
635  value: true
636}));
637exports.arrayByteLength = arrayByteLength;
638exports.arraysToBytes = arraysToBytes;
639exports.assert = assert;
640exports.bytesToString = bytesToString;
641exports.createObjectURL = createObjectURL;
642exports.createPromiseCapability = createPromiseCapability;
643exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
644exports.escapeString = escapeString;
645exports.getModificationDate = getModificationDate;
646exports.getVerbosityLevel = getVerbosityLevel;
647exports.info = info;
648exports.isArrayBuffer = isArrayBuffer;
649exports.isArrayEqual = isArrayEqual;
650exports.isAscii = isAscii;
651exports.isBool = isBool;
652exports.isNum = isNum;
653exports.isSameOrigin = isSameOrigin;
654exports.isString = isString;
655exports.objectFromMap = objectFromMap;
656exports.objectSize = objectSize;
657exports.removeNullCharacters = removeNullCharacters;
658exports.setVerbosityLevel = setVerbosityLevel;
659exports.shadow = shadow;
660exports.string32 = string32;
661exports.stringToBytes = stringToBytes;
662exports.stringToPDFString = stringToPDFString;
663exports.stringToUTF16BEString = stringToUTF16BEString;
664exports.stringToUTF8String = stringToUTF8String;
665exports.unreachable = unreachable;
666exports.utf8StringToString = utf8StringToString;
667exports.warn = warn;
668exports.VerbosityLevel = exports.Util = exports.UNSUPPORTED_FEATURES = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.IsLittleEndianCached = exports.IsEvalSupportedCached = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
669
670__w_pdfjs_require__(3);
671
672const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
673exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
674const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
675exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
676const PermissionFlag = {
677  PRINT: 0x04,
678  MODIFY_CONTENTS: 0x08,
679  COPY: 0x10,
680  MODIFY_ANNOTATIONS: 0x20,
681  FILL_INTERACTIVE_FORMS: 0x100,
682  COPY_FOR_ACCESSIBILITY: 0x200,
683  ASSEMBLE: 0x400,
684  PRINT_HIGH_QUALITY: 0x800
685};
686exports.PermissionFlag = PermissionFlag;
687const TextRenderingMode = {
688  FILL: 0,
689  STROKE: 1,
690  FILL_STROKE: 2,
691  INVISIBLE: 3,
692  FILL_ADD_TO_PATH: 4,
693  STROKE_ADD_TO_PATH: 5,
694  FILL_STROKE_ADD_TO_PATH: 6,
695  ADD_TO_PATH: 7,
696  FILL_STROKE_MASK: 3,
697  ADD_TO_PATH_FLAG: 4
698};
699exports.TextRenderingMode = TextRenderingMode;
700const ImageKind = {
701  GRAYSCALE_1BPP: 1,
702  RGB_24BPP: 2,
703  RGBA_32BPP: 3
704};
705exports.ImageKind = ImageKind;
706const AnnotationType = {
707  TEXT: 1,
708  LINK: 2,
709  FREETEXT: 3,
710  LINE: 4,
711  SQUARE: 5,
712  CIRCLE: 6,
713  POLYGON: 7,
714  POLYLINE: 8,
715  HIGHLIGHT: 9,
716  UNDERLINE: 10,
717  SQUIGGLY: 11,
718  STRIKEOUT: 12,
719  STAMP: 13,
720  CARET: 14,
721  INK: 15,
722  POPUP: 16,
723  FILEATTACHMENT: 17,
724  SOUND: 18,
725  MOVIE: 19,
726  WIDGET: 20,
727  SCREEN: 21,
728  PRINTERMARK: 22,
729  TRAPNET: 23,
730  WATERMARK: 24,
731  THREED: 25,
732  REDACT: 26
733};
734exports.AnnotationType = AnnotationType;
735const AnnotationStateModelType = {
736  MARKED: "Marked",
737  REVIEW: "Review"
738};
739exports.AnnotationStateModelType = AnnotationStateModelType;
740const AnnotationMarkedState = {
741  MARKED: "Marked",
742  UNMARKED: "Unmarked"
743};
744exports.AnnotationMarkedState = AnnotationMarkedState;
745const AnnotationReviewState = {
746  ACCEPTED: "Accepted",
747  REJECTED: "Rejected",
748  CANCELLED: "Cancelled",
749  COMPLETED: "Completed",
750  NONE: "None"
751};
752exports.AnnotationReviewState = AnnotationReviewState;
753const AnnotationReplyType = {
754  GROUP: "Group",
755  REPLY: "R"
756};
757exports.AnnotationReplyType = AnnotationReplyType;
758const AnnotationFlag = {
759  INVISIBLE: 0x01,
760  HIDDEN: 0x02,
761  PRINT: 0x04,
762  NOZOOM: 0x08,
763  NOROTATE: 0x10,
764  NOVIEW: 0x20,
765  READONLY: 0x40,
766  LOCKED: 0x80,
767  TOGGLENOVIEW: 0x100,
768  LOCKEDCONTENTS: 0x200
769};
770exports.AnnotationFlag = AnnotationFlag;
771const AnnotationFieldFlag = {
772  READONLY: 0x0000001,
773  REQUIRED: 0x0000002,
774  NOEXPORT: 0x0000004,
775  MULTILINE: 0x0001000,
776  PASSWORD: 0x0002000,
777  NOTOGGLETOOFF: 0x0004000,
778  RADIO: 0x0008000,
779  PUSHBUTTON: 0x0010000,
780  COMBO: 0x0020000,
781  EDIT: 0x0040000,
782  SORT: 0x0080000,
783  FILESELECT: 0x0100000,
784  MULTISELECT: 0x0200000,
785  DONOTSPELLCHECK: 0x0400000,
786  DONOTSCROLL: 0x0800000,
787  COMB: 0x1000000,
788  RICHTEXT: 0x2000000,
789  RADIOSINUNISON: 0x2000000,
790  COMMITONSELCHANGE: 0x4000000
791};
792exports.AnnotationFieldFlag = AnnotationFieldFlag;
793const AnnotationBorderStyleType = {
794  SOLID: 1,
795  DASHED: 2,
796  BEVELED: 3,
797  INSET: 4,
798  UNDERLINE: 5
799};
800exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
801const AnnotationActionEventType = {
802  E: "Mouse Enter",
803  X: "Mouse Exit",
804  D: "Mouse Down",
805  U: "Mouse Up",
806  Fo: "Focus",
807  Bl: "Blur",
808  PO: "PageOpen",
809  PC: "PageClose",
810  PV: "PageVisible",
811  PI: "PageInvisible",
812  K: "Keystroke",
813  F: "Format",
814  V: "Validate",
815  C: "Calculate"
816};
817exports.AnnotationActionEventType = AnnotationActionEventType;
818const DocumentActionEventType = {
819  WC: "WillClose",
820  WS: "WillSave",
821  DS: "DidSave",
822  WP: "WillPrint",
823  DP: "DidPrint"
824};
825exports.DocumentActionEventType = DocumentActionEventType;
826const PageActionEventType = {
827  O: "PageOpen",
828  C: "PageClose"
829};
830exports.PageActionEventType = PageActionEventType;
831const StreamType = {
832  UNKNOWN: "UNKNOWN",
833  FLATE: "FLATE",
834  LZW: "LZW",
835  DCT: "DCT",
836  JPX: "JPX",
837  JBIG: "JBIG",
838  A85: "A85",
839  AHX: "AHX",
840  CCF: "CCF",
841  RLX: "RLX"
842};
843exports.StreamType = StreamType;
844const FontType = {
845  UNKNOWN: "UNKNOWN",
846  TYPE1: "TYPE1",
847  TYPE1C: "TYPE1C",
848  CIDFONTTYPE0: "CIDFONTTYPE0",
849  CIDFONTTYPE0C: "CIDFONTTYPE0C",
850  TRUETYPE: "TRUETYPE",
851  CIDFONTTYPE2: "CIDFONTTYPE2",
852  TYPE3: "TYPE3",
853  OPENTYPE: "OPENTYPE",
854  TYPE0: "TYPE0",
855  MMTYPE1: "MMTYPE1"
856};
857exports.FontType = FontType;
858const VerbosityLevel = {
859  ERRORS: 0,
860  WARNINGS: 1,
861  INFOS: 5
862};
863exports.VerbosityLevel = VerbosityLevel;
864const CMapCompressionType = {
865  NONE: 0,
866  BINARY: 1,
867  STREAM: 2
868};
869exports.CMapCompressionType = CMapCompressionType;
870const OPS = {
871  dependency: 1,
872  setLineWidth: 2,
873  setLineCap: 3,
874  setLineJoin: 4,
875  setMiterLimit: 5,
876  setDash: 6,
877  setRenderingIntent: 7,
878  setFlatness: 8,
879  setGState: 9,
880  save: 10,
881  restore: 11,
882  transform: 12,
883  moveTo: 13,
884  lineTo: 14,
885  curveTo: 15,
886  curveTo2: 16,
887  curveTo3: 17,
888  closePath: 18,
889  rectangle: 19,
890  stroke: 20,
891  closeStroke: 21,
892  fill: 22,
893  eoFill: 23,
894  fillStroke: 24,
895  eoFillStroke: 25,
896  closeFillStroke: 26,
897  closeEOFillStroke: 27,
898  endPath: 28,
899  clip: 29,
900  eoClip: 30,
901  beginText: 31,
902  endText: 32,
903  setCharSpacing: 33,
904  setWordSpacing: 34,
905  setHScale: 35,
906  setLeading: 36,
907  setFont: 37,
908  setTextRenderingMode: 38,
909  setTextRise: 39,
910  moveText: 40,
911  setLeadingMoveText: 41,
912  setTextMatrix: 42,
913  nextLine: 43,
914  showText: 44,
915  showSpacedText: 45,
916  nextLineShowText: 46,
917  nextLineSetSpacingShowText: 47,
918  setCharWidth: 48,
919  setCharWidthAndBounds: 49,
920  setStrokeColorSpace: 50,
921  setFillColorSpace: 51,
922  setStrokeColor: 52,
923  setStrokeColorN: 53,
924  setFillColor: 54,
925  setFillColorN: 55,
926  setStrokeGray: 56,
927  setFillGray: 57,
928  setStrokeRGBColor: 58,
929  setFillRGBColor: 59,
930  setStrokeCMYKColor: 60,
931  setFillCMYKColor: 61,
932  shadingFill: 62,
933  beginInlineImage: 63,
934  beginImageData: 64,
935  endInlineImage: 65,
936  paintXObject: 66,
937  markPoint: 67,
938  markPointProps: 68,
939  beginMarkedContent: 69,
940  beginMarkedContentProps: 70,
941  endMarkedContent: 71,
942  beginCompat: 72,
943  endCompat: 73,
944  paintFormXObjectBegin: 74,
945  paintFormXObjectEnd: 75,
946  beginGroup: 76,
947  endGroup: 77,
948  beginAnnotations: 78,
949  endAnnotations: 79,
950  beginAnnotation: 80,
951  endAnnotation: 81,
952  paintJpegXObject: 82,
953  paintImageMaskXObject: 83,
954  paintImageMaskXObjectGroup: 84,
955  paintImageXObject: 85,
956  paintInlineImageXObject: 86,
957  paintInlineImageXObjectGroup: 87,
958  paintImageXObjectRepeat: 88,
959  paintImageMaskXObjectRepeat: 89,
960  paintSolidColorImageMask: 90,
961  constructPath: 91
962};
963exports.OPS = OPS;
964const UNSUPPORTED_FEATURES = {
965  unknown: "unknown",
966  forms: "forms",
967  javaScript: "javaScript",
968  signatures: "signatures",
969  smask: "smask",
970  shadingPattern: "shadingPattern",
971  font: "font",
972  errorTilingPattern: "errorTilingPattern",
973  errorExtGState: "errorExtGState",
974  errorXObject: "errorXObject",
975  errorFontLoadType3: "errorFontLoadType3",
976  errorFontState: "errorFontState",
977  errorFontMissing: "errorFontMissing",
978  errorFontTranslate: "errorFontTranslate",
979  errorColorSpace: "errorColorSpace",
980  errorOperatorList: "errorOperatorList",
981  errorFontToUnicode: "errorFontToUnicode",
982  errorFontLoadNative: "errorFontLoadNative",
983  errorFontBuildPath: "errorFontBuildPath",
984  errorFontGetPath: "errorFontGetPath",
985  errorMarkedContent: "errorMarkedContent"
986};
987exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
988const PasswordResponses = {
989  NEED_PASSWORD: 1,
990  INCORRECT_PASSWORD: 2
991};
992exports.PasswordResponses = PasswordResponses;
993let verbosity = VerbosityLevel.WARNINGS;
994
995function setVerbosityLevel(level) {
996  if (Number.isInteger(level)) {
997    verbosity = level;
998  }
999}
1000
1001function getVerbosityLevel() {
1002  return verbosity;
1003}
1004
1005function info(msg) {
1006  if (verbosity >= VerbosityLevel.INFOS) {
1007    console.log(`Info: ${msg}`);
1008  }
1009}
1010
1011function warn(msg) {
1012  if (verbosity >= VerbosityLevel.WARNINGS) {
1013    console.log(`Warning: ${msg}`);
1014  }
1015}
1016
1017function unreachable(msg) {
1018  throw new Error(msg);
1019}
1020
1021function assert(cond, msg) {
1022  if (!cond) {
1023    unreachable(msg);
1024  }
1025}
1026
1027function isSameOrigin(baseUrl, otherUrl) {
1028  let base;
1029
1030  try {
1031    base = new URL(baseUrl);
1032
1033    if (!base.origin || base.origin === "null") {
1034      return false;
1035    }
1036  } catch (e) {
1037    return false;
1038  }
1039
1040  const other = new URL(otherUrl, base);
1041  return base.origin === other.origin;
1042}
1043
1044function _isValidProtocol(url) {
1045  if (!url) {
1046    return false;
1047  }
1048
1049  switch (url.protocol) {
1050    case "http:":
1051    case "https:":
1052    case "ftp:":
1053    case "mailto:":
1054    case "tel:":
1055      return true;
1056
1057    default:
1058      return false;
1059  }
1060}
1061
1062function createValidAbsoluteUrl(url, baseUrl) {
1063  if (!url) {
1064    return null;
1065  }
1066
1067  try {
1068    const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
1069
1070    if (_isValidProtocol(absoluteUrl)) {
1071      return absoluteUrl;
1072    }
1073  } catch (ex) {}
1074
1075  return null;
1076}
1077
1078function shadow(obj, prop, value) {
1079  Object.defineProperty(obj, prop, {
1080    value,
1081    enumerable: true,
1082    configurable: true,
1083    writable: false
1084  });
1085  return value;
1086}
1087
1088const BaseException = function BaseExceptionClosure() {
1089  function BaseException(message) {
1090    if (this.constructor === BaseException) {
1091      unreachable("Cannot initialize BaseException.");
1092    }
1093
1094    this.message = message;
1095    this.name = this.constructor.name;
1096  }
1097
1098  BaseException.prototype = new Error();
1099  BaseException.constructor = BaseException;
1100  return BaseException;
1101}();
1102
1103exports.BaseException = BaseException;
1104
1105class PasswordException extends BaseException {
1106  constructor(msg, code) {
1107    super(msg);
1108    this.code = code;
1109  }
1110
1111}
1112
1113exports.PasswordException = PasswordException;
1114
1115class UnknownErrorException extends BaseException {
1116  constructor(msg, details) {
1117    super(msg);
1118    this.details = details;
1119  }
1120
1121}
1122
1123exports.UnknownErrorException = UnknownErrorException;
1124
1125class InvalidPDFException extends BaseException {}
1126
1127exports.InvalidPDFException = InvalidPDFException;
1128
1129class MissingPDFException extends BaseException {}
1130
1131exports.MissingPDFException = MissingPDFException;
1132
1133class UnexpectedResponseException extends BaseException {
1134  constructor(msg, status) {
1135    super(msg);
1136    this.status = status;
1137  }
1138
1139}
1140
1141exports.UnexpectedResponseException = UnexpectedResponseException;
1142
1143class FormatError extends BaseException {}
1144
1145exports.FormatError = FormatError;
1146
1147class AbortException extends BaseException {}
1148
1149exports.AbortException = AbortException;
1150const NullCharactersRegExp = /\x00/g;
1151
1152function removeNullCharacters(str) {
1153  if (typeof str !== "string") {
1154    warn("The argument for removeNullCharacters must be a string.");
1155    return str;
1156  }
1157
1158  return str.replace(NullCharactersRegExp, "");
1159}
1160
1161function bytesToString(bytes) {
1162  assert(bytes !== null && typeof bytes === "object" && bytes.length !== undefined, "Invalid argument for bytesToString");
1163  const length = bytes.length;
1164  const MAX_ARGUMENT_COUNT = 8192;
1165
1166  if (length < MAX_ARGUMENT_COUNT) {
1167    return String.fromCharCode.apply(null, bytes);
1168  }
1169
1170  const strBuf = [];
1171
1172  for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
1173    const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
1174    const chunk = bytes.subarray(i, chunkEnd);
1175    strBuf.push(String.fromCharCode.apply(null, chunk));
1176  }
1177
1178  return strBuf.join("");
1179}
1180
1181function stringToBytes(str) {
1182  assert(typeof str === "string", "Invalid argument for stringToBytes");
1183  const length = str.length;
1184  const bytes = new Uint8Array(length);
1185
1186  for (let i = 0; i < length; ++i) {
1187    bytes[i] = str.charCodeAt(i) & 0xff;
vendor: 4,446 bytes, lines 1188-1361
1188  }
1189
1190  return bytes;
1191}
1192
1193function arrayByteLength(arr) {
1194  if (arr.length !== undefined) {
1195    return arr.length;
1196  }
1197
1198  assert(arr.byteLength !== undefined, "arrayByteLength - invalid argument.");
1199  return arr.byteLength;
1200}
1201
1202function arraysToBytes(arr) {
1203  const length = arr.length;
1204
1205  if (length === 1 && arr[0] instanceof Uint8Array) {
1206    return arr[0];
1207  }
1208
1209  let resultLength = 0;
1210
1211  for (let i = 0; i < length; i++) {
1212    resultLength += arrayByteLength(arr[i]);
1213  }
1214
1215  let pos = 0;
1216  const data = new Uint8Array(resultLength);
1217
1218  for (let i = 0; i < length; i++) {
1219    let item = arr[i];
1220
1221    if (!(item instanceof Uint8Array)) {
1222      if (typeof item === "string") {
1223        item = stringToBytes(item);
1224      } else {
1225        item = new Uint8Array(item);
1226      }
1227    }
1228
1229    const itemLength = item.byteLength;
1230    data.set(item, pos);
1231    pos += itemLength;
1232  }
1233
1234  return data;
1235}
1236
1237function string32(value) {
1238  return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
1239}
1240
1241function objectSize(obj) {
1242  return Object.keys(obj).length;
1243}
1244
1245function objectFromMap(map) {
1246  const obj = Object.create(null);
1247
1248  for (const [key, value] of map) {
1249    obj[key] = value;
1250  }
1251
1252  return obj;
1253}
1254
1255function isLittleEndian() {
1256  const buffer8 = new Uint8Array(4);
1257  buffer8[0] = 1;
1258  const view32 = new Uint32Array(buffer8.buffer, 0, 1);
1259  return view32[0] === 1;
1260}
1261
1262const IsLittleEndianCached = {
1263  get value() {
1264    return shadow(this, "value", isLittleEndian());
1265  }
1266
1267};
1268exports.IsLittleEndianCached = IsLittleEndianCached;
1269
1270function isEvalSupported() {
1271  try {
1272    new Function("");
1273    return true;
1274  } catch (e) {
1275    return false;
1276  }
1277}
1278
1279const IsEvalSupportedCached = {
1280  get value() {
1281    return shadow(this, "value", isEvalSupported());
1282  }
1283
1284};
1285exports.IsEvalSupportedCached = IsEvalSupportedCached;
1286const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
1287
1288class Util {
1289  static makeHexColor(r, g, b) {
1290    return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
1291  }
1292
1293  static transform(m1, m2) {
1294    return [m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5]];
1295  }
1296
1297  static applyTransform(p, m) {
1298    const xt = p[0] * m[0] + p[1] * m[2] + m[4];
1299    const yt = p[0] * m[1] + p[1] * m[3] + m[5];
1300    return [xt, yt];
1301  }
1302
1303  static applyInverseTransform(p, m) {
1304    const d = m[0] * m[3] - m[1] * m[2];
1305    const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
1306    const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
1307    return [xt, yt];
1308  }
1309
1310  static getAxialAlignedBoundingBox(r, m) {
1311    const p1 = Util.applyTransform(r, m);
1312    const p2 = Util.applyTransform(r.slice(2, 4), m);
1313    const p3 = Util.applyTransform([r[0], r[3]], m);
1314    const p4 = Util.applyTransform([r[2], r[1]], m);
1315    return [Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1])];
1316  }
1317
1318  static inverseTransform(m) {
1319    const d = m[0] * m[3] - m[1] * m[2];
1320    return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d];
1321  }
1322
1323  static apply3dTransform(m, v) {
1324    return [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
1325  }
1326
1327  static singularValueDecompose2dScale(m) {
1328    const transpose = [m[0], m[2], m[1], m[3]];
1329    const a = m[0] * transpose[0] + m[1] * transpose[2];
1330    const b = m[0] * transpose[1] + m[1] * transpose[3];
1331    const c = m[2] * transpose[0] + m[3] * transpose[2];
1332    const d = m[2] * transpose[1] + m[3] * transpose[3];
1333    const first = (a + d) / 2;
1334    const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
1335    const sx = first + second || 1;
1336    const sy = first - second || 1;
1337    return [Math.sqrt(sx), Math.sqrt(sy)];
1338  }
1339
1340  static normalizeRect(rect) {
1341    const r = rect.slice(0);
1342
1343    if (rect[0] > rect[2]) {
1344      r[0] = rect[2];
1345      r[2] = rect[0];
1346    }
1347
1348    if (rect[1] > rect[3]) {
1349      r[1] = rect[3];
1350      r[3] = rect[1];
1351    }
1352
1353    return r;
1354  }
1355
1356  static intersect(rect1, rect2) {
1357    function compare(a, b) {
1358      return a - b;
1359    }
1360
1361    const orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare);
1362    const orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare);
1363    const result = [];
1364    rect1 = Util.normalizeRect(rect1);
1365    rect2 = Util.normalizeRect(rect2);
1366
1367    if (orderedX[0] === rect1[0] && orderedX[1] === rect2[0] || orderedX[0] === rect2[0] && orderedX[1] === rect1[0]) {
1368      result[0] = orderedX[1];
1369      result[2] = orderedX[2];
1370    } else {
1371      return null;
1372    }
1373
1374    if (orderedY[0] === rect1[1] && orderedY[1] === rect2[1] || orderedY[0] === rect2[1] && orderedY[1] === rect1[1]) {
1375      result[1] = orderedY[1];
1376      result[3] = orderedY[2];
1377    } else {
1378      return null;
1379    }
1380
1381    return result;
1382  }
1383
1384}
1385
1386exports.Util = Util;
1387const PDFStringTranslateTable = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2d8, 0x2c7, 0x2c6, 0x2d9, 0x2dd, 0x2db, 0x2da, 0x2dc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203a, 0x2212, 0x2030, 0x201e, 0x201c, 0x201d, 0x2018, 0x2019, 0x201a, 0x2122, 0xfb01, 0xfb02, 0x141, 0x152, 0x160, 0x178, 0x17d, 0x131, 0x142, 0x153, 0x161, 0x17e, 0, 0x20ac];
1388
1389function stringToPDFString(str) {
1390  const length = str.length,
1391        strBuf = [];
1392
1393  if (str[0] === "\xFE" && str[1] === "\xFF") {
1394    for (let i = 2; i < length; i += 2) {
1395      strBuf.push(String.fromCharCode(str.charCodeAt(i) << 8 | str.charCodeAt(i + 1)));
1396    }
1397  } else if (str[0] === "\xFF" && str[1] === "\xFE") {
1398    for (let i = 2; i < length; i += 2) {
1399      strBuf.push(String.fromCharCode(str.charCodeAt(i + 1) << 8 | str.charCodeAt(i)));
1400    }
1401  } else {
1402    for (let i = 0; i < length; ++i) {
1403      const code = PDFStringTranslateTable[str.charCodeAt(i)];
1404      strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
1405    }
1406  }
1407
1408  return strBuf.join("");
1409}
1410
1411function escapeString(str) {
1412  return str.replace(/([()\\\n\r])/g, match => {
1413    if (match === "\n") {
1414      return "\\n";
1415    } else if (match === "\r") {
1416      return "\\r";
1417    }
1418
1419    return `\\${match}`;
1420  });
1421}
1422
1423function isAscii(str) {
1424  return /^[\x00-\x7F]*$/.test(str);
1425}
1426
1427function stringToUTF16BEString(str) {
1428  const buf = ["\xFE\xFF"];
1429
1430  for (let i = 0, ii = str.length; i < ii; i++) {
1431    const char = str.charCodeAt(i);
1432    buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
1433  }
1434
1435  return buf.join("");
1436}
1437
1438function stringToUTF8String(str) {
1439  return decodeURIComponent(escape(str));
1440}
1441
1442function utf8StringToString(str) {
1443  return unescape(encodeURIComponent(str));
1444}
1445
1446function isBool(v) {
1447  return typeof v === "boolean";
1448}
1449
1450function isNum(v) {
1451  return typeof v === "number";
1452}
1453
1454function isString(v) {
1455  return typeof v === "string";
1456}
1457
1458function isArrayBuffer(v) {
1459  return typeof v === "object" && v !== null && v.byteLength !== undefined;
1460}
1461
1462function isArrayEqual(arr1, arr2) {
1463  if (arr1.length !== arr2.length) {
1464    return false;
1465  }
1466
1467  for (let i = 0, ii = arr1.length; i < ii; i++) {
1468    if (arr1[i] !== arr2[i]) {
1469      return false;
1470    }
1471  }
1472
1473  return true;
1474}
1475
1476function getModificationDate(date = new Date()) {
1477  const buffer = [date.getUTCFullYear().toString(), (date.getUTCMonth() + 1).toString().padStart(2, "0"), date.getUTCDate().toString().padStart(2, "0"), date.getUTCHours().toString().padStart(2, "0"), date.getUTCMinutes().toString().padStart(2, "0"), date.getUTCSeconds().toString().padStart(2, "0")];
1478  return buffer.join("");
1479}
1480
1481function createPromiseCapability() {
1482  const capability = Object.create(null);
1483  let isSettled = false;
1484  Object.defineProperty(capability, "settled", {
1485    get() {
1486      return isSettled;
1487    }
1488
1489  });
1490  capability.promise = new Promise(function (resolve, reject) {
1491    capability.resolve = function (data) {
1492      isSettled = true;
1493      resolve(data);
1494    };
1495
1496    capability.reject = function (reason) {
1497      isSettled = true;
1498      reject(reason);
1499    };
1500  });
1501  return capability;
1502}
1503
1504function createObjectURL(data, contentType = "", forceDataSchema = false) {
1505  if (URL.createObjectURL && !forceDataSchema) {
1506    return URL.createObjectURL(new Blob([data], {
1507      type: contentType
1508    }));
1509  }
1510
1511  const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
1511+/=";
1512  let buffer = `data:${contentType};base64,`;
1513
1514  for (let i = 0, ii = data.length; i < ii; i += 3) {
1515    const b1 = data[i] & 0xff;
1516    const b2 = data[i + 1] & 0xff;
1517    const b3 = data[i + 2] & 0xff;
1518    const d1 = b1 >> 2,
1519          d2 = (b1 & 3) << 4 | b2 >> 4;
1520    const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
1521    const d4 = i + 2 < ii ? b3 & 0x3f : 64;
1522    buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
1523  }
1524
1525  return buffer;
1526}
1527
1528/***/ }),
1529/* 3 */
1530/***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
1531
1532
1533
1534var _is_node = __w_pdfjs_require__(4);
1535
1536;
1537
1538/***/ }),
1539/* 4 */
1540/***/ ((__unused_webpack_module, exports) => {
1541
1542
1543
1544Object.defineProperty(exports, "__esModule", ({
1545  value: true
1546}));
1547exports.isNodeJS = void 0;
1548const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
1549exports.isNodeJS = isNodeJS;
1550
1551/***/ }),
1552/* 5 */
1553/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
1554
1555
1556
1557Object.defineProperty(exports, "__esModule", ({
1558  value: true
1559}));
1560exports.getDocument = getDocument;
1561exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
1562exports.version = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultCMapReaderFactory = exports.DefaultCanvasFactory = exports.build = void 0;
1563
1564var _util = __w_pdfjs_require__(2);
1565
1566var _display_utils = __w_pdfjs_require__(1);
1567
1568var _font_loader = __w_pdfjs_require__(6);
1569
1570var _node_utils = __w_pdfjs_require__(7);
1571
1572var _annotation_storage = __w_pdfjs_require__(8);
1573
1574var _api_compatibility = __w_pdfjs_require__(9);
1575
1576var _canvas = __w_pdfjs_require__(10);
1577
1578var _worker_options = __w_pdfjs_require__(12);
1579
1580var _is_node = __w_pdfjs_require__(4);
1581
1582var _message_handler = __w_pdfjs_require__(13);
1583
1584var _metadata = __w_pdfjs_require__(14);
1585
1586var _optional_content_config = __w_pdfjs_require__(15);
1587
1588var _transport_stream = __w_pdfjs_require__(16);
1589
1590const DEFAULT_RANGE_CHUNK_SIZE = 65536;
1591const RENDERING_CANCELLED_TIMEOUT = 100;
1592const DefaultCanvasFactory = _is_node.isNodeJS ? _node_utils.NodeCanvasFactory : _display_utils.DOMCanvasFactory;
1593exports.DefaultCanvasFactory = DefaultCanvasFactory;
1594const DefaultCMapReaderFactory = _is_node.isNodeJS ? _node_utils.NodeCMapReaderFactory : _display_utils.DOMCMapReaderFactory;
1595exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
1596let createPDFNetworkStream;
1597
1598function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
1599  createPDFNetworkStream = pdfNetworkStreamFactory;
1600}
1601
1602function getDocument(src) {
1603  const task = new PDFDocumentLoadingTask();
1604  let source;
1605
1606  if (typeof src === "string" || src instanceof URL) {
1607    source = {
1608      url: src
1609    };
1610  } else if ((0, _util.isArrayBuffer)(src)) {
1611    source = {
1612      data: src
1613    };
1614  } else if (src instanceof PDFDataRangeTransport) {
1615    source = {
1616      range: src
1617    };
1618  } else {
1619    if (typeof src !== "object") {
1620      throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
1621    }
1622
1623    if (!src.url && !src.data && !src.range) {
1624      throw new Error("Invalid parameter object: need either .data, .range or .url");
1625    }
1626
1627    source = src;
1628  }
1629
1630  const params = Object.create(null);
1631  let rangeTransport = null,
1632      worker = null;
1633
1634  for (const key in source) {
1635    const value = source[key];
1636
1637    switch (key) {
1638      case "url":
1639        if (typeof window !== "undefined") {
1640          try {
1641            params[key] = new URL(value, window.location).href;
1642            continue;
1643          } catch (ex) {
1644            (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
1645          }
1646        } else if (typeof value === "string" || value instanceof URL) {
1647          params[key] = value.toString();
1648          continue;
1649        }
1650
1651        throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
1652
1653      case "range":
1654        rangeTransport = value;
1655        continue;
1656
1657      case "worker":
1658        worker = value;
1659        continue;
1660
1661      case "data":
1662        if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
1663          params[key] = new Uint8Array(value);
1664        } else if (value instanceof Uint8Array) {
1665          break;
1666        } else if (typeof value === "string") {
1667          params[key] = (0, _util.stringToBytes)(value);
1668        } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
1669          params[key] = new Uint8Array(value);
1670        } else if ((0, _util.isArrayBuffer)(value)) {
1671          params[key] = new Uint8Array(value);
1672        } else {
1673          throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
1674        }
1675
1676        continue;
1677    }
1678
1679    params[key] = value;
1680  }
1681
1682  params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
1683  params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
1684  params.ignoreErrors = params.stopAtErrors !== true;
1685  params.fontExtraProperties = params.fontExtraProperties === true;
1686  params.pdfBug = params.pdfBug === true;
1687  params.enableXfa = params.enableXfa === true;
1688
1689  if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
1690    params.docBaseUrl = null;
1691  }
1692
1693  if (!Number.isInteger(params.maxImageSize)) {
1694    params.maxImageSize = -1;
1695  }
1696
1697  if (typeof params.isEvalSupported !== "boolean") {
1698    params.isEvalSupported = true;
1699  }
1700
1701  if (typeof params.disableFontFace !== "boolean") {
1702    params.disableFontFace = _api_compatibility.apiCompatibilityParams.disableFontFace || false;
1703  }
1704
1705  if (typeof params.ownerDocument === "undefined") {
1706    params.ownerDocument = globalThis.document;
1707  }
1708
1709  if (typeof params.disableRange !== "boolean") {
1710    params.disableRange = false;
1711  }
1712
1713  if (typeof params.disableStream !== "boolean") {
1714    params.disableStream = false;
1715  }
1716
1717  if (typeof params.disableAutoFetch !== "boolean") {
1718    params.disableAutoFetch = false;
1719  }
1720
1721  (0, _util.setVerbosityLevel)(params.verbosity);
1722
1723  if (!worker) {
1724    const workerParams = {
1725      verbosity: params.verbosity,
1726      port: _worker_options.GlobalWorkerOptions.workerPort
1727    };
1728    worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
1729    task._worker = worker;
1730  }
1731
1732  const docId = task.docId;
1733  worker.promise.then(function () {
1734    if (task.destroyed) {
1735      throw new Error("Loading aborted");
1736    }
1737
1738    const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
1739
1740    const networkStreamPromise = new Promise(function (resolve) {
1741      let networkStream;
1742
1743      if (rangeTransport) {
1744        networkStream = new _transport_stream.PDFDataTransportStream({
1745          length: params.length,
1746          initialData: params.initialData,
1747          progressiveDone: params.progressiveDone,
1748          contentDispositionFilename: params.contentDispositionFilename,
1749          disableRange: params.disableRange,
1750          disableStream: params.disableStream
1751        }, rangeTransport);
1752      } else if (!params.data) {
1753        networkStream = createPDFNetworkStream({
1754          url: params.url,
1755          length: params.length,
1756          httpHeaders: params.httpHeaders,
1757          withCredentials: params.withCredentials,
1758          rangeChunkSize: params.rangeChunkSize,
1759          disableRange: params.disableRange,
1760          disableStream: params.disableStream
1761        });
1762      }
1763
1764      resolve(networkStream);
1765    });
1766    return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
1767      if (task.destroyed) {
1768        throw new Error("Loading aborted");
1769      }
1770
1771      const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
1772      messageHandler.postMessageTransfers = worker.postMessageTransfers;
1773      const transport = new WorkerTransport(messageHandler, task, networkStream, params);
1774      task._transport = transport;
1775      messageHandler.send("Ready", null);
1776    });
1777  }).catch(task._capability.reject);
1778  return task;
1779}
1780
1781function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
1782  if (worker.destroyed) {
1783    return Promise.reject(new Error("Worker was destroyed"));
1784  }
1785
1786  if (pdfDataRangeTransport) {
1787    source.length = pdfDataRangeTransport.length;
1788    source.initialData = pdfDataRangeTransport.initialData;
1789    source.progressiveDone = pdfDataRangeTransport.progressiveDone;
1790    source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
1791  }
1792
1793  return worker.messageHandler.sendWithPromise("GetDocRequest", {
1794    docId,
1795    apiVersion: '2.9.359',
1796    source: {
1797      data: source.data,
1798      url: source.url,
1799      password: source.password,
1800      disableAutoFetch: source.disableAutoFetch,
1801      rangeChunkSize: source.rangeChunkSize,
1802      length: source.length
1803    },
1804    maxImageSize: source.maxImageSize,
1805    disableFontFace: source.disableFontFace,
1806    postMessageTransfers: worker.postMessageTransfers,
1807    docBaseUrl: source.docBaseUrl,
1808    ignoreErrors: source.ignoreErrors,
1809    isEvalSupported: source.isEvalSupported,
1810    fontExtraProperties: source.fontExtraProperties,
1811    enableXfa: source.enableXfa
1812  }).then(function (workerId) {
1813    if (worker.destroyed) {
1814      throw new Error("Worker was destroyed");
1815    }
1816
1817    return workerId;
1818  });
1819}
1820
1821const PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
1822  let nextDocumentId = 0;
1823
1824  class PDFDocumentLoadingTask {
1825    constructor() {
1826      this._capability = (0, _util.createPromiseCapability)();
1827      this._transport = null;
1828      this._worker = null;
1829      this.docId = "d" + nextDocumentId++;
1830      this.destroyed = false;
1831      this.onPassword = null;
1832      this.onProgress = null;
1833      this.onUnsupportedFeature = null;
1834    }
1835
1836    get promise() {
1837      return this._capability.promise;
1838    }
1839
1840    destroy() {
1841      this.destroyed = true;
1842      const transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy();
1843      return transportDestroyed.then(() => {
1844        this._transport = null;
1845
1846        if (this._worker) {
1847          this._worker.destroy();
1848
1849          this._worker = null;
1850        }
1851      });
1852    }
1853
1854  }
1855
1856  return PDFDocumentLoadingTask;
1857}();
1858
1859class PDFDataRangeTransport {
1860  constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
1861    this.length = length;
1862    this.initialData = initialData;
1863    this.progressiveDone = progressiveDone;
1864    this.contentDispositionFilename = contentDispositionFilename;
1865    this._rangeListeners = [];
1866    this._progressListeners = [];
1867    this._progressiveReadListeners = [];
1868    this._progressiveDoneListeners = [];
1869    this._readyCapability = (0, _util.createPromiseCapability)();
1870  }
1871
1872  addRangeListener(listener) {
1873    this._rangeListeners.push(listener);
1874  }
1875
1876  addProgressListener(listener) {
1877    this._progressListeners.push(listener);
1878  }
1879
1880  addProgressiveReadListener(listener) {
1881    this._progressiveReadListeners.push(listener);
1882  }
1883
1884  addProgressiveDoneListener(listener) {
1885    this._progressiveDoneListeners.push(listener);
1886  }
1887
1888  onDataRange(begin, chunk) {
1889    for (const listener of this._rangeListeners) {
1890      listener(begin, chunk);
1891    }
1892  }
1893
1894  onDataProgress(loaded, total) {
1895    this._readyCapability.promise.then(() => {
1896      for (const listener of this._progressListeners) {
1897        listener(loaded, total);
1898      }
1899    });
1900  }
1901
1902  onDataProgressiveRead(chunk) {
1903    this._readyCapability.promise.then(() => {
1904      for (const listener of this._progressiveReadListeners) {
1905        listener(chunk);
1906      }
1907    });
1908  }
1909
1910  onDataProgressiveDone() {
1911    this._readyCapability.promise.then(() => {
1912      for (const listener of this._progressiveDoneListeners) {
1913        listener();
1914      }
1915    });
1916  }
1917
1918  transportReady() {
1919    this._readyCapability.resolve();
1920  }
1921
1922  requestDataRange(begin, end) {
1923    (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
1924  }
1925
1926  abort() {}
1927
1928}
1929
1930exports.PDFDataRangeTransport = PDFDataRangeTransport;
1931
1932class PDFDocumentProxy {
1933  constructor(pdfInfo, transport) {
1934    this._pdfInfo = pdfInfo;
1935    this._transport = transport;
1936  }
1937
1938  get annotationStorage() {
1939    return this._transport.annotationStorage;
1940  }
1941
1942  get numPages() {
1943    return this._pdfInfo.numPages;
1944  }
1945
1946  get fingerprint() {
1947    return this._pdfInfo.fingerprint;
1948  }
1949
1950  get isPureXfa() {
1951    return this._pdfInfo.isPureXfa;
1952  }
1953
1954  getPage(pageNumber) {
1955    return this._transport.getPage(pageNumber);
1956  }
1957
1958  getPageIndex(ref) {
1959    return this._transport.getPageIndex(ref);
1960  }
1961
1962  getDestinations() {
1963    return this._transport.getDestinations();
1964  }
1965
1966  getDestination(id) {
1967    return this._transport.getDestination(id);
1968  }
1969
1970  getPageLabels() {
1971    return this._transport.getPageLabels();
1972  }
1973
1974  getPageLayout() {
1975    return this._transport.getPageLayout();
1976  }
1977
1978  getPageMode() {
1979    return this._transport.getPageMode();
1980  }
1981
1982  getViewerPreferences() {
1983    return this._transport.getViewerPreferences();
1984  }
1985
1986  getOpenAction() {
1987    return this._transport.getOpenAction();
1988  }
1989
1990  getAttachments() {
1991    return this._transport.getAttachments();
1992  }
1993
1994  getJavaScript() {
1995    return this._transport.getJavaScript();
1996  }
1997
1998  getJSActions() {
1999    return this._transport.getDocJSActions();
2000  }
2001
2002  getOutline() {
2003    return this._transport.getOutline();
2004  }
2005
2006  getOptionalContentConfig() {
2007    return this._transport.getOptionalContentConfig();
2008  }
2009
2010  getPermissions() {
2011    return this._transport.getPermissions();
2012  }
2013
2014  getMetadata() {
2015    return this._transport.getMetadata();
2016  }
2017
2018  getMarkInfo() {
2019    return this._transport.getMarkInfo();
2020  }
2021
2022  getData() {
2023    return this._transport.getData();
2024  }
2025
2026  getDownloadInfo() {
2027    return this._transport.downloadInfoCapability.promise;
2028  }
2029
2030  getStats() {
2031    return this._transport.getStats();
2032  }
2033
2034  cleanup(keepLoadedFonts = false) {
2035    return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
2036  }
2037
2038  destroy() {
2039    return this.loadingTask.destroy();
2040  }
2041
2042  get loadingParams() {
2043    return this._transport.loadingParams;
2044  }
2045
2046  get loadingTask() {
2047    return this._transport.loadingTask;
2048  }
2049
2050  saveDocument() {
2051    if (arguments.length > 0) {
2052      (0, _display_utils.deprecated)("saveDocument no longer accepts any options.");
2053    }
2054
2055    if (this._transport.annotationStorage.size <= 0) {
2056      (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
2057    }
2058
2059    return this._transport.saveDocument();
2060  }
2061
2062  getFieldObjects() {
2063    return this._transport.getFieldObjects();
2064  }
2065
2066  hasJSActions() {
2067    return this._transport.hasJSActions();
2068  }
2069
2070  getCalculationOrderIds() {
2071    return this._transport.getCalculationOrderIds();
2072  }
2073
2074}
2075
2076exports.PDFDocumentProxy = PDFDocumentProxy;
2077
2078class PDFPageProxy {
2079  constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
2080    this._pageIndex = pageIndex;
2081    this._pageInfo = pageInfo;
2082    this._ownerDocument = ownerDocument;
2083    this._transport = transport;
2084    this._stats = pdfBug ? new _display_utils.StatTimer() : null;
2085    this._pdfBug = pdfBug;
2086    this.commonObjs = transport.commonObjs;
2087    this.objs = new PDFObjects();
2088    this.cleanupAfterRender = false;
2089    this.pendingCleanup = false;
2090    this._intentStates = new Map();
2091    this.destroyed = false;
2092  }
2093
2094  get pageNumber() {
2095    return this._pageIndex + 1;
2096  }
2097
2098  get rotate() {
2099    return this._pageInfo.rotate;
2100  }
2101
2102  get ref() {
2103    return this._pageInfo.ref;
2104  }
2105
2106  get userUnit() {
2107    return this._pageInfo.userUnit;
2108  }
2109
2110  get view() {
2111    return this._pageInfo.view;
2112  }
2113
2114  getViewport({
2115    scale,
2116    rotation = this.rotate,
2117    offsetX = 0,
2118    offsetY = 0,
2119    dontFlip = false
2120  } = {}) {
2121    return new _display_utils.PageViewport({
2122      viewBox: this.view,
2123      scale,
2124      rotation,
2125      offsetX,
2126      offsetY,
2127      dontFlip
2128    });
2129  }
2130
2131  getAnnotations({
2132    intent = null
2133  } = {}) {
2134    if (!this._annotationsPromise || this._annotationsIntent !== intent) {
2135      this._annotationsPromise = this._transport.getAnnotations(this._pageIndex, intent);
2136      this._annotationsIntent = intent;
2137    }
2138
2139    return this._annotationsPromise;
2140  }
2141
2142  getJSActions() {
2143    return this._jsActionsPromise || (this._jsActionsPromise = this._transport.getPageJSActions(this._pageIndex));
2144  }
2145
2146  getXfa() {
2147    return this._xfaPromise || (this._xfaPromise = this._transport.getPageXfa(this._pageIndex));
2148  }
2149
2150  render({
2151    canvasContext,
2152    viewport,
2153    intent = "display",
2154    renderInteractiveForms = false,
2155    transform = null,
2156    imageLayer = null,
2157    canvasFactory = null,
2158    background = null,
2159    includeAnnotationStorage = false,
2160    optionalContentConfigPromise = null
2161  }) {
2162    var _intentState;
2163
2164    if (arguments[0]?.annotationStorage !== undefined) {
2165      (0, _display_utils.deprecated)("render no longer accepts an `annotationStorage` option, " + "please use the `includeAnnotationStorage`-boolean instead.");
2166      includeAnnotationStorage || (includeAnnotationStorage = !!arguments[0].annotationStorage);
2167    }
2168
2169    if (this._stats) {
2170      this._stats.time("Overall");
2171    }
2172
2173    const renderingIntent = intent === "print" ? "print" : "display";
2174    this.pendingCleanup = false;
2175
2176    if (!optionalContentConfigPromise) {
2177      optionalContentConfigPromise = this._transport.getOptionalContentConfig();
2178    }
2179
2180    let intentState = this._intentStates.get(renderingIntent);
2181
2182    if (!intentState) {
2183      intentState = Object.create(null);
2184
2185      this._intentStates.set(renderingIntent, intentState);
2186    }
2187
2188    if (intentState.streamReaderCancelTimeout) {
2189      clearTimeout(intentState.streamReaderCancelTimeout);
2190      intentState.streamReaderCancelTimeout = null;
2191    }
2192
2193    const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
2194      ownerDocument: this._ownerDocument
2195    });
2196    const annotationStorage = includeAnnotationStorage ? this._transport.annotationStorage.serializable : null;
2197
2198    if (!intentState.displayReadyCapability) {
2199      intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
2200      intentState.operatorList = {
2201        fnArray: [],
2202        argsArray: [],
2203        lastChunk: false
2204      };
2205
2206      if (this._stats) {
2207        this._stats.time("Page Request");
2208      }
2209
2210      this._pumpOperatorList({
2211        pageIndex: this._pageIndex,
2212        intent: renderingIntent,
2213        renderInteractiveForms: renderInteractiveForms === true,
2214        annotationStorage
2215      });
2216    }
2217
2218    const complete = error => {
2219      intentState.renderTasks.delete(internalRenderTask);
2220
2221      if (this.cleanupAfterRender || renderingIntent === "print") {
2222        this.pendingCleanup = true;
2223      }
2224
2225      this._tryCleanup();
2226
2227      if (error) {
2228        internalRenderTask.capability.reject(error);
2229
2230        this._abortOperatorList({
2231          intentState,
2232          reason: error
2233        });
2234      } else {
2235        internalRenderTask.capability.resolve();
2236      }
2237
2238      if (this._stats) {
2239        this._stats.timeEnd("Rendering");
2240
2241        this._stats.timeEnd("Overall");
2242      }
2243    };
2244
2245    const internalRenderTask = new InternalRenderTask({
2246      callback: complete,
2247      params: {
2248        canvasContext,
2249        viewport,
2250        transform,
2251        imageLayer,
2252        background
2253      },
2254      objs: this.objs,
2255      commonObjs: this.commonObjs,
2256      operatorList: intentState.operatorList,
2257      pageIndex: this._pageIndex,
2258      canvasFactory: canvasFactoryInstance,
2259      useRequestAnimationFrame: renderingIntent !== "print",
2260      pdfBug: this._pdfBug
2261    });
2262    ((_intentState = intentState).renderTasks || (_intentState.renderTasks = new Set())).add(internalRenderTask);
2263    const renderTask = internalRenderTask.task;
2264    Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
2265      if (this.pendingCleanup) {
2266        complete();
2267        return;
2268      }
2269
2270      if (this._stats) {
2271        this._stats.time("Rendering");
2272      }
2273
2274      internalRenderTask.initializeGraphics({
2275        transparency,
2276        optionalContentConfig
2277      });
2278      internalRenderTask.operatorListChanged();
2279    }).catch(complete);
2280    return renderTask;
2281  }
2282
2283  getOperatorList() {
2284    function operatorListChanged() {
2285      if (intentState.operatorList.lastChunk) {
2286        intentState.opListReadCapability.resolve(intentState.operatorList);
2287        intentState.renderTasks.delete(opListTask);
2288      }
2289    }
2290
2291    const renderingIntent = "oplist";
2292
2293    let intentState = this._intentStates.get(renderingIntent);
2294
2295    if (!intentState) {
2296      intentState = Object.create(null);
2297
2298      this._intentStates.set(renderingIntent, intentState);
2299    }
2300
2301    let opListTask;
2302
2303    if (!intentState.opListReadCapability) {
2304      var _intentState2;
2305
2306      opListTask = Object.create(null);
2307      opListTask.operatorListChanged = operatorListChanged;
2308      intentState.opListReadCapability = (0, _util.createPromiseCapability)();
2309      ((_intentState2 = intentState).renderTasks || (_intentState2.renderTasks = new Set())).add(opListTask);
2310      intentState.operatorList = {
2311        fnArray: [],
2312        argsArray: [],
2313        lastChunk: false
2314      };
2315
2316      if (this._stats) {
2317        this._stats.time("Page Request");
2318      }
2319
2320      this._pumpOperatorList({
2321        pageIndex: this._pageIndex,
2322        intent: renderingIntent
2323      });
2324    }
2325
2326    return intentState.opListReadCapability.promise;
2327  }
2328
2329  streamTextContent({
2330    normalizeWhitespace = false,
2331    disableCombineTextItems = false,
2332    includeMarkedContent = false
2333  } = {}) {
2334    const TEXT_CONTENT_CHUNK_SIZE = 100;
2335    return this._transport.messageHandler.sendWithStream("GetTextContent", {
2336      pageIndex: this._pageIndex,
2337      normalizeWhitespace: normalizeWhitespace === true,
2338      combineTextItems: disableCombineTextItems !== true,
2339      includeMarkedContent: includeMarkedContent === true
2340    }, {
2341      highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
2342
2343      size(textContent) {
2344        return textContent.items.length;
2345      }
2346
2347    });
2348  }
2349
2350  getTextContent(params = {}) {
2351    const readableStream = this.streamTextContent(params);
2352    return new Promise(function (resolve, reject) {
2353      function pump() {
2354        reader.read().then(function ({
2355          value,
2356          done
2357        }) {
2358          if (done) {
2359            resolve(textContent);
2360            return;
2361          }
2362
2363          Object.assign(textContent.styles, value.styles);
2364          textContent.items.push(...value.items);
2365          pump();
2366        }, reject);
2367      }
2368
2369      const reader = readableStream.getReader();
2370      const textContent = {
2371        items: [],
2372        styles: Object.create(null)
2373      };
2374      pump();
2375    });
2376  }
2377
2378  getStructTree() {
2379    return this._structTreePromise || (this._structTreePromise = this._transport.getStructTree(this._pageIndex));
2380  }
2381
2382  _destroy() {
2383    this.destroyed = true;
2384    this._transport.pageCache[this._pageIndex] = null;
2385    const waitOn = [];
2386
2387    for (const [intent, intentState] of this._intentStates) {
2388      this._abortOperatorList({
2389        intentState,
2390        reason: new Error("Page was destroyed."),
2391        force: true
2392      });
2393
2394      if (intent === "oplist") {
2395        continue;
2396      }
2397
2398      for (const internalRenderTask of intentState.renderTasks) {
2399        waitOn.push(internalRenderTask.completed);
2400        internalRenderTask.cancel();
2401      }
2402    }
2403
2404    this.objs.clear();
2405    this._annotationsPromise = null;
2406    this._jsActionsPromise = null;
2407    this._xfaPromise = null;
2408    this._structTreePromise = null;
2409    this.pendingCleanup = false;
2410    return Promise.all(waitOn);
2411  }
2412
2413  cleanup(resetStats = false) {
2414    this.pendingCleanup = true;
2415    return this._tryCleanup(resetStats);
2416  }
2417
2418  _tryCleanup(resetStats = false) {
2419    if (!this.pendingCleanup) {
2420      return false;
2421    }
2422
2423    for (const {
2424      renderTasks,
2425      operatorList
2426    } of this._intentStates.values()) {
2427      if (renderTasks.size > 0 || !operatorList.lastChunk) {
2428        return false;
2429      }
2430    }
2431
2432    this._intentStates.clear();
2433
2434    this.objs.clear();
2435    this._annotationsPromise = null;
2436    this._jsActionsPromise = null;
2437    this._xfaPromise = null;
2438    this._structTreePromise = null;
2439
2440    if (resetStats && this._stats) {
2441      this._stats = new _display_utils.StatTimer();
2442    }
2443
2444    this.pendingCleanup = false;
2445    return true;
2446  }
2447
2448  _startRenderPage(transparency, intent) {
2449    const intentState = this._intentStates.get(intent);
2450
2451    if (!intentState) {
2452      return;
2453    }
2454
2455    if (this._stats) {
2456      this._stats.timeEnd("Page Request");
2457    }
2458
2459    if (intentState.displayReadyCapability) {
2460      intentState.displayReadyCapability.resolve(transparency);
2461    }
2462  }
2463
2464  _renderPageChunk(operatorListChunk, intentState) {
2465    for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
2466      intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
2467      intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
2468    }
2469
2470    intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
2471
2472    for (const internalRenderTask of intentState.renderTasks) {
2473      internalRenderTask.operatorListChanged();
2474    }
2475
2476    if (operatorListChunk.lastChunk) {
2477      this._tryCleanup();
2478    }
2479  }
2480
2481  _pumpOperatorList(args) {
2482    (0, _util.assert)(args.intent, 'PDFPageProxy._pumpOperatorList: Expected "intent" argument.');
2483
2484    const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", args);
2485
2486    const reader = readableStream.getReader();
2487
2488    const intentState = this._intentStates.get(args.intent);
2489
2490    intentState.streamReader = reader;
2491
2492    const pump = () => {
2493      reader.read().then(({
2494        value,
2495        done
2496      }) => {
2497        if (done) {
2498          intentState.streamReader = null;
2499          return;
2500        }
2501
2502        if (this._transport.destroyed) {
2503          return;
2504        }
2505
2506        this._renderPageChunk(value, intentState);
2507
2508        pump();
2509      }, reason => {
2510        intentState.streamReader = null;
2511
2512        if (this._transport.destroyed) {
2513          return;
2514        }
2515
2516        if (intentState.operatorList) {
2517          intentState.operatorList.lastChunk = true;
2518
2519          for (const internalRenderTask of intentState.renderTasks) {
2520            internalRenderTask.operatorListChanged();
2521          }
2522
2523          this._tryCleanup();
2524        }
2525
2526        if (intentState.displayReadyCapability) {
2527          intentState.displayReadyCapability.reject(reason);
2528        } else if (intentState.opListReadCapability) {
2529          intentState.opListReadCapability.reject(reason);
2530        } else {
2531          throw reason;
2532        }
2533      });
2534    };
2535
2536    pump();
2537  }
2538
2539  _abortOperatorList({
2540    intentState,
2541    reason,
2542    force = false
2543  }) {
2544    (0, _util.assert)(reason instanceof Error || typeof reason === "object" && reason !== null, 'PDFPageProxy._abortOperatorList: Expected "reason" argument.');
2545
2546    if (!intentState.streamReader) {
2547      return;
2548    }
2549
2550    if (!force) {
2551      if (intentState.renderTasks.size > 0) {
2552        return;
2553      }
2554
2555      if (reason instanceof _display_utils.RenderingCancelledException) {
2556        intentState.streamReaderCancelTimeout = setTimeout(() => {
2557          this._abortOperatorList({
2558            intentState,
2559            reason,
2560            force: true
2561          });
2562
2563          intentState.streamReaderCancelTimeout = null;
2564        }, RENDERING_CANCELLED_TIMEOUT);
2565        return;
2566      }
2567    }
2568
2569    intentState.streamReader.cancel(new _util.AbortException(reason?.message));
2570    intentState.streamReader = null;
2571
2572    if (this._transport.destroyed) {
2573      return;
2574    }
2575
2576    for (const [intent, curIntentState] of this._intentStates) {
2577      if (curIntentState === intentState) {
2578        this._intentStates.delete(intent);
2579
2580        break;
2581      }
2582    }
2583
2584    this.cleanup();
2585  }
2586
2587  get stats() {
2588    return this._stats;
2589  }
2590
2591}
2592
2593exports.PDFPageProxy = PDFPageProxy;
2594
2595class LoopbackPort {
2596  constructor() {
2597    this._listeners = [];
2598    this._deferred = Promise.resolve(undefined);
2599  }
2600
2601  postMessage(obj, transfers) {
2602    function cloneValue(value) {
2603      if (typeof value !== "object" || value === null) {
2604        return value;
2605      }
2606
2607      if (cloned.has(value)) {
2608        return cloned.get(value);
2609      }
2610
2611      let buffer, result;
2612
2613      if ((buffer = value.buffer) && (0, _util.isArrayBuffer)(buffer)) {
2614        if (transfers?.includes(buffer)) {
2615          result = new value.constructor(buffer, value.byteOffset, value.byteLength);
2616        } else {
2617          result = new value.constructor(value);
2618        }
2619
2620        cloned.set(value, result);
2621        return result;
2622      }
2623
2624      if (value instanceof Map) {
2625        result = new Map();
2626        cloned.set(value, result);
2627
2628        for (const [key, val] of value) {
2629          result.set(key, cloneValue(val));
2630        }
2631
2632        return result;
2633      }
2634
2635      if (value instanceof Set) {
2636        result = new Set();
2637        cloned.set(value, result);
2638
2639        for (const val of value) {
2640          result.add(cloneValue(val));
2641        }
2642
2643        return result;
2644      }
2645
2646      if (value instanceof URL) {
2647        throw new Error(`LoopbackPort.postMessage - cannot clone: ${value}`);
2648      }
2649
2650      result = Array.isArray(value) ? [] : Object.create(null);
2651      cloned.set(value, result);
2652
2653      for (const i in value) {
2654        let desc,
2655            p = value;
2656
2657        while (!(desc = Object.getOwnPropertyDescriptor(p, i))) {
2658          p = Object.getPrototypeOf(p);
2659        }
2660
2661        if (typeof desc.value === "undefined") {
2662          continue;
2663        }
2664
2665        if (typeof desc.value === "function") {
2666          if (value.hasOwnProperty?.(i)) {
2667            throw new Error(`LoopbackPort.postMessage - cannot clone: ${value[i]}`);
2668          }
2669
2670          continue;
2671        }
2672
2673        result[i] = cloneValue(desc.value);
2674      }
2675
2676      return result;
2677    }
2678
2679    const cloned = new WeakMap();
2680    const event = {
2681      data: cloneValue(obj)
2682    };
2683
2684    this._deferred.then(() => {
2685      for (const listener of this._listeners) {
2686        listener.call(this, event);
2687      }
2688    });
2689  }
2690
2691  addEventListener(name, listener) {
2692    this._listeners.push(listener);
2693  }
2694
2695  removeEventListener(name, listener) {
2696    const i = this._listeners.indexOf(listener);
2697
2698    this._listeners.splice(i, 1);
2699  }
2700
2701  terminate() {
2702    this._listeners.length = 0;
2703  }
2704
2705}
2706
2707exports.LoopbackPort = LoopbackPort;
2708
2709const PDFWorker = function PDFWorkerClosure() {
2710  const pdfWorkerPorts = new WeakMap();
2711  let isWorkerDisabled = false;
2712  let fallbackWorkerSrc;
2713  let nextFakeWorkerId = 0;
2714  let fakeWorkerCapability;
2715
2716  if (_is_node.isNodeJS && typeof require === "function") {
2717    isWorkerDisabled = true;
2718    fallbackWorkerSrc = "./pdf.worker.js";
2719  } else if (typeof document === "object" && "currentScript" in document) {
2720    const pdfjsFilePath = document.currentScript?.src;
2721
2722    if (pdfjsFilePath) {
2723      fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".worker$1$2");
2724    }
2725  }
2726
2727  function getWorkerSrc() {
2728    if (_worker_options.GlobalWorkerOptions.workerSrc) {
2729      return _worker_options.GlobalWorkerOptions.workerSrc;
2730    }
2731
2732    if (typeof fallbackWorkerSrc !== "undefined") {
2733      if (!_is_node.isNodeJS) {
2734        (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
2735      }
2736
2737      return fallbackWorkerSrc;
2738    }
2739
2740    throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
2741  }
2742
2743  function getMainThreadWorkerMessageHandler() {
2744    let mainWorkerMessageHandler;
2745
2746    try {
2747      mainWorkerMessageHandler = globalThis.pdfjsWorker?.WorkerMessageHandler;
2748    } catch (ex) {}
2749
2750    return mainWorkerMessageHandler || null;
2751  }
2752
2753  function setupFakeWorkerGlobal() {
2754    if (fakeWorkerCapability) {
2755      return fakeWorkerCapability.promise;
2756    }
2757
2758    fakeWorkerCapability = (0, _util.createPromiseCapability)();
2759
2760    const loader = async function () {
2761      const mainWorkerMessageHandler = getMainThreadWorkerMessageHandler();
2762
2763      if (mainWorkerMessageHandler) {
2764        return mainWorkerMessageHandler;
2765      }
2766
2767      if (_is_node.isNodeJS && typeof require === "function") {
2768        const worker = eval("require")(getWorkerSrc());
2769        return worker.WorkerMessageHandler;
2770      }
2771
2772      await (0, _display_utils.loadScript)(getWorkerSrc());
2773      return window.pdfjsWorker.WorkerMessageHandler;
2774    };
2775
2776    loader().then(fakeWorkerCapability.resolve, fakeWorkerCapability.reject);
2777    return fakeWorkerCapability.promise;
2778  }
2779
2780  function createCDNWrapper(url) {
2781    const wrapper = "importScripts('" + url + "');";
2782    return URL.createObjectURL(new Blob([wrapper]));
2783  }
2784
2785  class PDFWorker {
2786    constructor({
2787      name = null,
2788      port = null,
2789      verbosity = (0, _util.getVerbosityLevel)()
2790    } = {}) {
2791      if (port && pdfWorkerPorts.has(port)) {
2792        throw new Error("Cannot use more than one PDFWorker per port");
2793      }
2794
2795      this.name = name;
2796      this.destroyed = false;
2797      this.postMessageTransfers = true;
2798      this.verbosity = verbosity;
2799      this._readyCapability = (0, _util.createPromiseCapability)();
2800      this._port = null;
2801      this._webWorker = null;
2802      this._messageHandler = null;
2803
2804      if (port) {
2805        pdfWorkerPorts.set(port, this);
2806
2807        this._initializeFromPort(port);
2808
2809        return;
2810      }
2811
2812      this._initialize();
2813    }
2814
2815    get promise() {
2816      return this._readyCapability.promise;
2817    }
2818
2819    get port() {
2820      return this._port;
2821    }
2822
2823    get messageHandler() {
2824      return this._messageHandler;
2825    }
2826
2827    _initializeFromPort(port) {
2828      this._port = port;
2829      this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
2830
2831      this._messageHandler.on("ready", function () {});
2832
2833      this._readyCapability.resolve();
2834    }
2835
2836    _initialize() {
2837      if (typeof Worker !== "undefined" && !isWorkerDisabled && !getMainThreadWorkerMessageHandler()) {
2838        let workerSrc = getWorkerSrc();
2839
2840        try {
2841          if (!(0, _util.isSameOrigin)(window.location.href, workerSrc)) {
2842            workerSrc = createCDNWrapper(new URL(workerSrc, window.location).href);
2843          }
2844
2845          const worker = new Worker(workerSrc);
2846          const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
2847
2848          const terminateEarly = () => {
2849            worker.removeEventListener("error", onWorkerError);
2850            messageHandler.destroy();
2851            worker.terminate();
2852
2853            if (this.destroyed) {
2854              this._readyCapability.reject(new Error("Worker was destroyed"));
2855            } else {
2856              this._setupFakeWorker();
2857            }
2858          };
2859
2860          const onWorkerError = () => {
2861            if (!this._webWorker) {
2862              terminateEarly();
2863            }
2864          };
2865
2866          worker.addEventListener("error", onWorkerError);
2867          messageHandler.on("test", data => {
2868            worker.removeEventListener("error", onWorkerError);
2869
2870            if (this.destroyed) {
2871              terminateEarly();
2872              return;
2873            }
2874
2875            if (data) {
2876              this._messageHandler = messageHandler;
2877              this._port = worker;
2878              this._webWorker = worker;
2879
2880              if (!data.supportTransfers) {
2881                this.postMessageTransfers = false;
2882              }
2883
2884              this._readyCapability.resolve();
2885
2886              messageHandler.send("configure", {
2887                verbosity: this.verbosity
2888              });
2889            } else {
2890              this._setupFakeWorker();
2891
2892              messageHandler.destroy();
2893              worker.terminate();
2894            }
2895          });
2896          messageHandler.on("ready", data => {
2897            worker.removeEventListener("error", onWorkerError);
2898
2899            if (this.destroyed) {
2900              terminateEarly();
2901              return;
2902            }
2903
2904            try {
2905              sendTest();
2906            } catch (e) {
2907              this._setupFakeWorker();
2908            }
2909          });
2910
2911          const sendTest = () => {
2912            const testObj = new Uint8Array([this.postMessageTransfers ? 255 : 0]);
2913
2914            try {
2915              messageHandler.send("test", testObj, [testObj.buffer]);
2916            } catch (ex) {
2917              (0, _util.warn)("Cannot use postMessage transfers.");
2918              testObj[0] = 0;
2919              messageHandler.send("test", testObj);
2920            }
2921          };
2922
2923          sendTest();
2924          return;
2925        } catch (e) {
2926          (0, _util.info)("The worker has been disabled.");
2927        }
2928      }
2929
2930      this._setupFakeWorker();
2931    }
2932
2933    _setupFakeWorker() {
2934      if (!isWorkerDisabled) {
2935        (0, _util.warn)("Setting up fake worker.");
2936        isWorkerDisabled = true;
2937      }
2938
2939      setupFakeWorkerGlobal().then(WorkerMessageHandler => {
2940        if (this.destroyed) {
2941          this._readyCapability.reject(new Error("Worker was destroyed"));
2942
2943          return;
2944        }
2945
2946        const port = new LoopbackPort();
2947        this._port = port;
2948        const id = "fake" + nextFakeWorkerId++;
2949        const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
2950        WorkerMessageHandler.setup(workerHandler, port);
2951        const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
2952        this._messageHandler = messageHandler;
2953
2954        this._readyCapability.resolve();
2955
2956        messageHandler.send("configure", {
2957          verbosity: this.verbosity
2958        });
2959      }).catch(reason => {
2960        this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
2961      });
2962    }
2963
2964    destroy() {
2965      this.destroyed = true;
2966
2967      if (this._webWorker) {
2968        this._webWorker.terminate();
2969
2970        this._webWorker = null;
2971      }
2972
2973      pdfWorkerPorts.delete(this._port);
2974      this._port = null;
2975
2976      if (this._messageHandler) {
2977        this._messageHandler.destroy();
2978
2979        this._messageHandler = null;
2980      }
2981    }
2982
2983    static fromPort(params) {
2984      if (!params || !params.port) {
2985        throw new Error("PDFWorker.fromPort - invalid method signature.");
2986      }
2987
2988      if (pdfWorkerPorts.has(params.port)) {
2989        return pdfWorkerPorts.get(params.port);
2990      }
2991
2992      return new PDFWorker(params);
2993    }
2994
2995    static getWorkerSrc() {
2996      return getWorkerSrc();
2997    }
2998
2999  }
3000
3001  return PDFWorker;
3002}();
3003
3004exports.PDFWorker = PDFWorker;
3005
3006class WorkerTransport {
3007  constructor(messageHandler, loadingTask, networkStream, params) {
3008    this.messageHandler = messageHandler;
3009    this.loadingTask = loadingTask;
3010    this.commonObjs = new PDFObjects();
3011    this.fontLoader = new _font_loader.FontLoader({
3012      docId: loadingTask.docId,
3013      onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
3014      ownerDocument: params.ownerDocument
3015    });
3016    this._params = params;
3017    this.CMapReaderFactory = new params.CMapReaderFactory({
3018      baseUrl: params.cMapUrl,
3019      isCompressed: params.cMapPacked
3020    });
3021    this.destroyed = false;
3022    this.destroyCapability = null;
3023    this._passwordCapability = null;
3024    this._networkStream = networkStream;
3025    this._fullReader = null;
3026    this._lastProgress = null;
3027    this.pageCache = [];
3028    this.pagePromises = [];
3029    this.downloadInfoCapability = (0, _util.createPromiseCapability)();
3030    this.setupMessageHandler();
3031  }
3032
3033  get annotationStorage() {
3034    return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
3035  }
3036
3037  destroy() {
3038    if (this.destroyCapability) {
3039      return this.destroyCapability.promise;
3040    }
3041
3042    this.destroyed = true;
3043    this.destroyCapability = (0, _util.createPromiseCapability)();
3044
3045    if (this._passwordCapability) {
3046      this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
3047    }
3048
3049    const waitOn = [];
3050
3051    for (const page of this.pageCache) {
3052      if (page) {
3053        waitOn.push(page._destroy());
3054      }
3055    }
3056
3057    this.pageCache.length = 0;
3058    this.pagePromises.length = 0;
3059
3060    if (this.hasOwnProperty("annotationStorage")) {
3061      this.annotationStorage.resetModified();
3062    }
3063
3064    const terminated = this.messageHandler.sendWithPromise("Terminate", null);
3065    waitOn.push(terminated);
3066    Promise.all(waitOn).then(() => {
3067      this.commonObjs.clear();
3068      this.fontLoader.clear();
3069      this._hasJSActionsPromise = null;
3070
3071      if (this._networkStream) {
3072        this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
3073      }
3074
3075      if (this.messageHandler) {
3076        this.messageHandler.destroy();
3077        this.messageHandler = null;
3078      }
3079
3080      this.destroyCapability.resolve();
3081    }, this.destroyCapability.reject);
3082    return this.destroyCapability.promise;
3083  }
3084
3085  setupMessageHandler() {
3086    const {
3087      messageHandler,
3088      loadingTask
3089    } = this;
3090    messageHandler.on("GetReader", (data, sink) => {
3091      (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
3092      this._fullReader = this._networkStream.getFullReader();
3093
3094      this._fullReader.onProgress = evt => {
3095        this._lastProgress = {
3096          loaded: evt.loaded,
3097          total: evt.total
3098        };
3099      };
3100
3101      sink.onPull = () => {
3102        this._fullReader.read().then(function ({
3103          value,
3104          done
3105        }) {
3106          if (done) {
3107            sink.close();
3108            return;
3109          }
3110
3111          (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
3112          sink.enqueue(new Uint8Array(value), 1, [value]);
3113        }).catch(reason => {
3114          sink.error(reason);
3115        });
3116      };
3117
3118      sink.onCancel = reason => {
3119        this._fullReader.cancel(reason);
3120
3121        sink.ready.catch(readyReason => {
3122          if (this.destroyed) {
3123            return;
3124          }
3125
3126          throw readyReason;
3127        });
3128      };
3129    });
3130    messageHandler.on("ReaderHeadersReady", data => {
3131      const headersCapability = (0, _util.createPromiseCapability)();
3132      const fullReader = this._fullReader;
3133      fullReader.headersReady.then(() => {
3134        if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
3135          if (this._lastProgress && loadingTask.onProgress) {
3136            loadingTask.onProgress(this._lastProgress);
3137          }
3138
3139          fullReader.onProgress = evt => {
3140            if (loadingTask.onProgress) {
3141              loadingTask.onProgress({
3142                loaded: evt.loaded,
3143                total: evt.total
3144              });
3145            }
3146          };
3147        }
3148
3149        headersCapability.resolve({
3150          isStreamingSupported: fullReader.isStreamingSupported,
3151          isRangeSupported: fullReader.isRangeSupported,
3152          contentLength: fullReader.contentLength
3153        });
3154      }, headersCapability.reject);
3155      return headersCapability.promise;
3156    });
3157    messageHandler.on("GetRangeReader", (data, sink) => {
3158      (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
3159
3160      const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
3161
3162      if (!rangeReader) {
3163        sink.close();
3164        return;
3165      }
3166
3167      sink.onPull = () => {
3168        rangeReader.read().then(function ({
3169          value,
3170          done
3171        }) {
3172          if (done) {
3173            sink.close();
3174            return;
3175          }
3176
3177          (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
3178          sink.enqueue(new Uint8Array(value), 1, [value]);
3179        }).catch(reason => {
3180          sink.error(reason);
3181        });
3182      };
3183
3184      sink.onCancel = reason => {
3185        rangeReader.cancel(reason);
3186        sink.ready.catch(readyReason => {
3187          if (this.destroyed) {
3188            return;
3189          }
3190
3191          throw readyReason;
3192        });
3193      };
3194    });
3195    messageHandler.on("GetDoc", ({
3196      pdfInfo
3197    }) => {
3198      this._numPages = pdfInfo.numPages;
3199
3200      loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
3201    });
3202    messageHandler.on("DocException", function (ex) {
3203      let reason;
3204
3205      switch (ex.name) {
3206        case "PasswordException":
3207          reason = new _util.PasswordException(ex.message, ex.code);
3208          break;
3209
3210        case "InvalidPDFException":
3211          reason = new _util.InvalidPDFException(ex.message);
3212          break;
3213
3214        case "MissingPDFException":
3215          reason = new _util.MissingPDFException(ex.message);
3216          break;
3217
3218        case "UnexpectedResponseException":
3219          reason = new _util.UnexpectedResponseException(ex.message, ex.status);
3220          break;
3221
3222        case "UnknownErrorException":
3223          reason = new _util.UnknownErrorException(ex.message, ex.details);
3224          break;
3225      }
3226
3227      if (!(reason instanceof Error)) {
3228        const msg = "DocException - expected a valid Error.";
3229        (0, _util.warn)(msg);
3230      }
3231
3232      loadingTask._capability.reject(reason);
3233    });
3234    messageHandler.on("PasswordRequest", exception => {
3235      this._passwordCapability = (0, _util.createPromiseCapability)();
3236
3237      if (loadingTask.onPassword) {
3238        const updatePassword = password => {
3239          this._passwordCapability.resolve({
3240            password
3241          });
3242        };
3243
3244        try {
3245          loadingTask.onPassword(updatePassword, exception.code);
3246        } catch (ex) {
3247          this._passwordCapability.reject(ex);
3248        }
3249      } else {
3250        this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
3251      }
3252
3253      return this._passwordCapability.promise;
3254    });
3255    messageHandler.on("DataLoaded", data => {
3256      if (loadingTask.onProgress) {
3257        loadingTask.onProgress({
3258          loaded: data.length,
3259          total: data.length
3260        });
3261      }
3262
3263      this.downloadInfoCapability.resolve(data);
3264    });
3265    messageHandler.on("StartRenderPage", data => {
3266      if (this.destroyed) {
3267        return;
3268      }
3269
3270      const page = this.pageCache[data.pageIndex];
3271
3272      page._startRenderPage(data.transparency, data.intent);
3273    });
3274    messageHandler.on("commonobj", data => {
3275      if (this.destroyed) {
3276        return;
3277      }
3278
3279      const [id, type, exportedData] = data;
3280
3281      if (this.commonObjs.has(id)) {
3282        return;
3283      }
3284
3285      switch (type) {
3286        case "Font":
3287          const params = this._params;
3288
3289          if ("error" in exportedData) {
3290            const exportedError = exportedData.error;
3291            (0, _util.warn)(`Error during font loading: ${exportedError}`);
3292            this.commonObjs.resolve(id, exportedError);
3293            break;
3294          }
3295
3296          let fontRegistry = null;
3297
3298          if (params.pdfBug && globalThis.FontInspector?.enabled) {
3299            fontRegistry = {
3300              registerFont(font, url) {
3301                globalThis.FontInspector.fontAdded(font, url);
3302              }
3303
3304            };
3305          }
3306
3307          const font = new _font_loader.FontFaceObject(exportedData, {
3308            isEvalSupported: params.isEvalSupported,
3309            disableFontFace: params.disableFontFace,
3310            ignoreErrors: params.ignoreErrors,
3311            onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
3312            fontRegistry
3313          });
3314          this.fontLoader.bind(font).catch(reason => {
3315            return messageHandler.sendWithPromise("FontFallback", {
3316              id
3317            });
3318          }).finally(() => {
3319            if (!params.fontExtraProperties && font.data) {
3320              font.data = null;
3321            }
3322
3323            this.commonObjs.resolve(id, font);
3324          });
3325          break;
3326
3327        case "FontPath":
3328        case "Image":
3329          this.commonObjs.resolve(id, exportedData);
3330          break;
3331
3332        default:
3333          throw new Error(`Got unknown common object type ${type}`);
3334      }
3335    });
3336    messageHandler.on("obj", data => {
3337      if (this.destroyed) {
3338        return undefined;
3339      }
3340
3341      const [id, pageIndex, type, imageData] = data;
3342      const pageProxy = this.pageCache[pageIndex];
3343
3344      if (pageProxy.objs.has(id)) {
3345        return undefined;
3346      }
3347
3348      switch (type) {
3349        case "Image":
3350          pageProxy.objs.resolve(id, imageData);
3351          const MAX_IMAGE_SIZE_TO_STORE = 8000000;
3352
3353          if (imageData?.data?.length > MAX_IMAGE_SIZE_TO_STORE) {
3354            pageProxy.cleanupAfterRender = true;
3355          }
3356
3357          break;
3358
3359        default:
3360          throw new Error(`Got unknown object type ${type}`);
3361      }
3362
3363      return undefined;
3364    });
3365    messageHandler.on("DocProgress", data => {
3366      if (this.destroyed) {
3367        return;
3368      }
3369
3370      if (loadingTask.onProgress) {
3371        loadingTask.onProgress({
3372          loaded: data.loaded,
3373          total: data.total
3374        });
3375      }
3376    });
3377    messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
3378    messageHandler.on("FetchBuiltInCMap", (data, sink) => {
3379      if (this.destroyed) {
3380        sink.error(new Error("Worker was destroyed"));
3381        return;
3382      }
3383
3384      let fetched = false;
3385
3386      sink.onPull = () => {
3387        if (fetched) {
3388          sink.close();
3389          return;
3390        }
3391
3392        fetched = true;
3393        this.CMapReaderFactory.fetch(data).then(function (builtInCMap) {
3394          sink.enqueue(builtInCMap, 1, [builtInCMap.cMapData.buffer]);
3395        }).catch(function (reason) {
3396          sink.error(reason);
3397        });
3398      };
3399    });
3400  }
3401
3402  _onUnsupportedFeature({
3403    featureId
3404  }) {
3405    if (this.destroyed) {
3406      return;
3407    }
3408
3409    if (this.loadingTask.onUnsupportedFeature) {
3410      this.loadingTask.onUnsupportedFeature(featureId);
3411    }
3412  }
3413
3414  getData() {
3415    return this.messageHandler.sendWithPromise("GetData", null);
3416  }
3417
3418  getPage(pageNumber) {
3419    if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
3420      return Promise.reject(new Error("Invalid page request"));
3421    }
3422
3423    const pageIndex = pageNumber - 1;
3424
3425    if (pageIndex in this.pagePromises) {
3426      return this.pagePromises[pageIndex];
3427    }
3428
3429    const promise = this.messageHandler.sendWithPromise("GetPage", {
3430      pageIndex
3431    }).then(pageInfo => {
3432      if (this.destroyed) {
3433        throw new Error("Transport destroyed");
3434      }
3435
3436      const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
3437      this.pageCache[pageIndex] = page;
3438      return page;
3439    });
3440    this.pagePromises[pageIndex] = promise;
3441    return promise;
3442  }
3443
3444  getPageIndex(ref) {
3445    return this.messageHandler.sendWithPromise("GetPageIndex", {
3446      ref
3447    }).catch(function (reason) {
3448      return Promise.reject(new Error(reason));
3449    });
3450  }
3451
3452  getAnnotations(pageIndex, intent) {
3453    return this.messageHandler.sendWithPromise("GetAnnotations", {
3454      pageIndex,
3455      intent
3456    });
3457  }
3458
3459  saveDocument() {
3460    return this.messageHandler.sendWithPromise("SaveDocument", {
3461      numPages: this._numPages,
3462      annotationStorage: this.annotationStorage.serializable,
3463      filename: this._fullReader?.filename ?? null
3464    }).finally(() => {
3465      this.annotationStorage.resetModified();
3466    });
3467  }
3468
3469  getFieldObjects() {
3470    return this.messageHandler.sendWithPromise("GetFieldObjects", null);
3471  }
3472
3473  hasJSActions() {
3474    return this._hasJSActionsPromise || (this._hasJSActionsPromise = this.messageHandler.sendWithProm
3474ise("HasJSActions", null));
3475  }
3476
3477  getCalculationOrderIds() {
3478    return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
3479  }
3480
3481  getDestinations() {
3482    return this.messageHandler.sendWithPromise("GetDestinations", null);
3483  }
3484
3485  getDestination(id) {
3486    if (typeof id !== "string") {
3487      return Promise.reject(new Error("Invalid destination request."));
3488    }
3489
3490    return this.messageHandler.sendWithPromise("GetDestination", {
3491      id
3492    });
3493  }
3494
3495  getPageLabels() {
3496    return this.messageHandler.sendWithPromise("GetPageLabels", null);
3497  }
3498
3499  getPageLayout() {
3500    return this.messageHandler.sendWithPromise("GetPageLayout", null);
3501  }
3502
3503  getPageMode() {
3504    return this.messageHandler.sendWithPromise("GetPageMode", null);
3505  }
3506
3507  getViewerPreferences() {
3508    return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
3509  }
3510
3511  getOpenAction() {
3512    return this.messageHandler.sendWithPromise("GetOpenAction", null);
3513  }
3514
3515  getAttachments() {
3516    return this.messageHandler.sendWithPromise("GetAttachments", null);
3517  }
3518
3519  getJavaScript() {
3520    return this.messageHandler.sendWithPromise("GetJavaScript", null);
3521  }
3522
3523  getDocJSActions() {
3524    return this.messageHandler.sendWithPromise("GetDocJSActions", null);
3525  }
3526
3527  getPageJSActions(pageIndex) {
3528    return this.messageHandler.sendWithPromise("GetPageJSActions", {
3529      pageIndex
3530    });
3531  }
3532
3533  getPageXfa(pageIndex) {
3534    return this.messageHandler.sendWithPromise("GetPageXfa", {
3535      pageIndex
3536    });
3537  }
3538
3539  getStructTree(pageIndex) {
3540    return this.messageHandler.sendWithPromise("GetStructTree", {
3541      pageIndex
3542    });
3543  }
3544
3545  getOutline() {
3546    return this.messageHandler.sendWithPromise("GetOutline", null);
3547  }
3548
3549  getOptionalContentConfig() {
3550    return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
3551      return new _optional_content_config.OptionalContentConfig(results);
3552    });
3553  }
3554
3555  getPermissions() {
3556    return this.messageHandler.sendWithPromise("GetPermissions", null);
3557  }
3558
3559  getMetadata() {
3560    return this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
3561      return {
3562        info: results[0],
3563        metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
3564        contentDispositionFilename: this._fullReader?.filename ?? null,
3565        contentLength: this._fullReader?.contentLength ?? null
3566      };
3567    });
3568  }
3569
3570  getMarkInfo() {
3571    return this.messageHandler.sendWithPromise("GetMarkInfo", null);
3572  }
3573
3574  getStats() {
3575    return this.messageHandler.sendWithPromise("GetStats", null);
3576  }
3577
3578  async startCleanup(keepLoadedFonts = false) {
3579    await this.messageHandler.sendWithPromise("Cleanup", null);
3580
3581    if (this.destroyed) {
3582      return;
3583    }
3584
3585    for (let i = 0, ii = this.pageCache.length; i < ii; i++) {
3586      const page = this.pageCache[i];
3587
3588      if (!page) {
3589        continue;
3590      }
3591
3592      const cleanupSuccessful = page.cleanup();
3593
3594      if (!cleanupSuccessful) {
3595        throw new Error(`startCleanup: Page ${i + 1} is currently rendering.`);
3596      }
3597    }
3598
3599    this.commonObjs.clear();
3600
3601    if (!keepLoadedFonts) {
3602      this.fontLoader.clear();
3603    }
3604
3605    this._hasJSActionsPromise = null;
3606  }
3607
3608  get loadingParams() {
3609    const params = this._params;
3610    return (0, _util.shadow)(this, "loadingParams", {
3611      disableAutoFetch: params.disableAutoFetch,
3612      disableFontFace: params.disableFontFace
3613    });
3614  }
3615
3616}
3617
3618class PDFObjects {
3619  constructor() {
3620    this._objs = Object.create(null);
3621  }
3622
3623  _ensureObj(objId) {
3624    if (this._objs[objId]) {
3625      return this._objs[objId];
3626    }
3627
3628    return this._objs[objId] = {
3629      capability: (0, _util.createPromiseCapability)(),
3630      data: null,
3631      resolved: false
3632    };
3633  }
3634
3635  get(objId, callback = null) {
3636    if (callback) {
3637      this._ensureObj(objId).capability.promise.then(callback);
3638
3639      return null;
3640    }
3641
3642    const obj = this._objs[objId];
3643
3644    if (!obj || !obj.resolved) {
3645      throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
3646    }
3647
3648    return obj.data;
3649  }
3650
3651  has(objId) {
3652    const obj = this._objs[objId];
3653    return obj?.resolved || false;
3654  }
3655
3656  resolve(objId, data) {
3657    const obj = this._ensureObj(objId);
3658
3659    obj.resolved = true;
3660    obj.data = data;
3661    obj.capability.resolve(data);
3662  }
3663
3664  clear() {
3665    this._objs = Object.create(null);
3666  }
3667
3668}
3669
3670class RenderTask {
3671  constructor(internalRenderTask) {
3672    this._internalRenderTask = internalRenderTask;
3673    this.onContinue = null;
3674  }
3675
3676  get promise() {
3677    return this._internalRenderTask.capability.promise;
3678  }
3679
3680  cancel() {
3681    this._internalRenderTask.cancel();
3682  }
3683
3684}
3685
3686const InternalRenderTask = function InternalRenderTaskClosure() {
3687  const canvasInRendering = new WeakSet();
3688
3689  class InternalRenderTask {
3690    constructor({
3691      callback,
3692      params,
3693      objs,
3694      commonObjs,
3695      operatorList,
3696      pageIndex,
3697      canvasFactory,
3698      useRequestAnimationFrame = false,
3699      pdfBug = false
3700    }) {
3701      this.callback = callback;
3702      this.params = params;
3703      this.objs = objs;
3704      this.commonObjs = commonObjs;
3705      this.operatorListIdx = null;
3706      this.operatorList = operatorList;
3707      this._pageIndex = pageIndex;
3708      this.canvasFactory = canvasFactory;
3709      this._pdfBug = pdfBug;
3710      this.running = false;
3711      this.graphicsReadyCallback = null;
3712      this.graphicsReady = false;
3713      this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
3714      this.cancelled = false;
3715      this.capability = (0, _util.createPromiseCapability)();
3716      this.task = new RenderTask(this);
3717      this._cancelBound = this.cancel.bind(this);
3718      this._continueBound = this._continue.bind(this);
3719      this._scheduleNextBound = this._scheduleNext.bind(this);
3720      this._nextBound = this._next.bind(this);
3721      this._canvas = params.canvasContext.canvas;
3722    }
3723
3724    get completed() {
3725      return this.capability.promise.catch(function () {});
3726    }
3727
3728    initializeGraphics({
3729      transparency = false,
3730      optionalContentConfig
3731    }) {
3732      if (this.cancelled) {
3733        return;
3734      }
3735
3736      if (this._canvas) {
3737        if (canvasInRendering.has(this._canvas)) {
3738          throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
3739        }
3740
3741        canvasInRendering.add(this._canvas);
3742      }
3743
3744      if (this._pdfBug && globalThis.StepperManager?.enabled) {
3745        this.stepper = globalThis.StepperManager.create(this._pageIndex);
3746        this.stepper.init(this.operatorList);
3747        this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
3748      }
3749
3750      const {
3751        canvasContext,
3752        viewport,
3753        transform,
3754        imageLayer,
3755        background
3756      } = this.params;
3757      this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig);
3758      this.gfx.beginDrawing({
3759        transform,
3760        viewport,
3761        transparency,
3762        background
3763      });
3764      this.operatorListIdx = 0;
3765      this.graphicsReady = true;
3766
3767      if (this.graphicsReadyCallback) {
3768        this.graphicsReadyCallback();
3769      }
3770    }
3771
3772    cancel(error = null) {
3773      this.running = false;
3774      this.cancelled = true;
3775
3776      if (this.gfx) {
3777        this.gfx.endDrawing();
3778      }
3779
3780      if (this._canvas) {
3781        canvasInRendering.delete(this._canvas);
3782      }
3783
3784      this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
3785    }
3786
3787    operatorListChanged() {
3788      if (!this.graphicsReady) {
3789        if (!this.graphicsReadyCallback) {
3790          this.graphicsReadyCallback = this._continueBound;
3791        }
3792
3793        return;
3794      }
3795
3796      if (this.stepper) {
3797        this.stepper.updateOperatorList(this.operatorList);
3798      }
3799
3800      if (this.running) {
3801        return;
3802      }
3803
3804      this._continue();
3805    }
3806
3807    _continue() {
3808      this.running = true;
3809
3810      if (this.cancelled) {
3811        return;
3812      }
3813
3814      if (this.task.onContinue) {
3815        this.task.onContinue(this._scheduleNextBound);
3816      } else {
3817        this._scheduleNext();
3818      }
3819    }
3820
3821    _scheduleNext() {
3822      if (this._useRequestAnimationFrame) {
3823        window.requestAnimationFrame(() => {
3824          this._nextBound().catch(this._cancelBound);
3825        });
3826      } else {
3827        Promise.resolve().then(this._nextBound).catch(this._cancelBound);
3828      }
3829    }
3830
3831    async _next() {
3832      if (this.cancelled) {
3833        return;
3834      }
3835
3836      this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
3837
3838      if (this.operatorListIdx === this.operatorList.argsArray.length) {
3839        this.running = false;
3840
3841        if (this.operatorList.lastChunk) {
3842          this.gfx.endDrawing();
3843
3844          if (this._canvas) {
3845            canvasInRendering.delete(this._canvas);
3846          }
3847
3848          this.callback();
3849        }
3850      }
3851    }
3852
3853  }
3854
3855  return InternalRenderTask;
3856}();
3857
3858const version = '2.9.359';
3859exports.version = version;
3860const build = 'e667c8cbc';
3861exports.build = build;
3862
3863/***/ }),
3864/* 6 */
3865/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3866
3867
3868
3869Object.defineProperty(exports, "__esModule", ({
3870  value: true
3871}));
3872exports.FontLoader = exports.FontFaceObject = void 0;
3873
3874var _util = __w_pdfjs_require__(2);
3875
3876class BaseFontLoader {
3877  constructor({
3878    docId,
3879    onUnsupportedFeature,
3880    ownerDocument = globalThis.document
3881  }) {
3882    if (this.constructor === BaseFontLoader) {
3883      (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
3884    }
3885
3886    this.docId = docId;
3887    this._onUnsupportedFeature = onUnsupportedFeature;
3888    this._document = ownerDocument;
3889    this.nativeFontFaces = [];
3890    this.styleElement = null;
3891  }
3892
3893  addNativeFontFace(nativeFontFace) {
3894    this.nativeFontFaces.push(nativeFontFace);
3895
3896    this._document.fonts.add(nativeFontFace);
3897  }
3898
3899  insertRule(rule) {
3900    let styleElement = this.styleElement;
3901
3902    if (!styleElement) {
3903      styleElement = this.styleElement = this._document.createElement("style");
3904      styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
3905
3906      this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
3907    }
3908
3909    const styleSheet = styleElement.sheet;
3910    styleSheet.insertRule(rule, styleSheet.cssRules.length);
3911  }
3912
3913  clear() {
3914    for (const nativeFontFace of this.nativeFontFaces) {
3915      this._document.fonts.delete(nativeFontFace);
3916    }
3917
3918    this.nativeFontFaces.length = 0;
3919
3920    if (this.styleElement) {
3921      this.styleElement.remove();
3922      this.styleElement = null;
3923    }
3924  }
3925
3926  async bind(font) {
3927    if (font.attached || font.missingFile) {
3928      return;
3929    }
3930
3931    font.attached = true;
3932
3933    if (this.isFontLoadingAPISupported) {
3934      const nativeFontFace = font.createNativeFontFace();
3935
3936      if (nativeFontFace) {
3937        this.addNativeFontFace(nativeFontFace);
3938
3939        try {
3940          await nativeFontFace.loaded;
3941        } catch (ex) {
3942          this._onUnsupportedFeature({
3943            featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
3944          });
3945
3946          (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
3947          font.disableFontFace = true;
3948          throw ex;
3949        }
3950      }
3951
3952      return;
3953    }
3954
3955    const rule = font.createFontFaceRule();
3956
3957    if (rule) {
3958      this.insertRule(rule);
3959
3960      if (this.isSyncFontLoadingSupported) {
3961        return;
3962      }
3963
3964      await new Promise(resolve => {
3965        const request = this._queueLoadingCallback(resolve);
3966
3967        this._prepareFontLoadEvent([rule], [font], request);
3968      });
3969    }
3970  }
3971
3972  _queueLoadingCallback(callback) {
3973    (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
3974  }
3975
3976  get isFontLoadingAPISupported() {
3977    return (0, _util.shadow)(this, "isFontLoadingAPISupported", !!this._document?.fonts);
3978  }
3979
3980  get isSyncFontLoadingSupported() {
3981    (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
3982  }
3983
3984  get _loadTestFont() {
3985    (0, _util.unreachable)("Abstract method `_loadTestFont`.");
3986  }
3987
3988  _prepareFontLoadEvent(rules, fontsToLoad, request) {
3989    (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
3990  }
3991
3992}
3993
3994let FontLoader;
3995exports.FontLoader = FontLoader;
3996{
3997  exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
3998    constructor(params) {
3999      super(params);
4000      this.loadingContext = {
4001        requests: [],
4002        nextRequestId: 0
4003      };
4004      this.loadTestFontId = 0;
4005    }
4006
4007    get isSyncFontLoadingSupported() {
4008      let supported = false;
4009
4010      if (typeof navigator === "undefined") {
4011        supported = true;
4012      } else {
4013        const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
4014
4015        if (m?.[1] >= 14) {
4016          supported = true;
4017        }
4018      }
4019
4020      return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
4021    }
4022
4023    _queueLoadingCallback(callback) {
4024      function completeRequest() {
4025        (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
4026        request.done = true;
4027
4028        while (context.requests.length > 0 && context.requests[0].done) {
4029          const otherRequest = context.requests.shift();
4030          setTimeout(otherRequest.callback, 0);
4031        }
4032      }
4033
4034      const context = this.loadingContext;
4035      const request = {
4036        id: `pdfjs-font-loading-${context.nextRequestId++}`,
4037        done: false,
4038        complete: completeRequest,
4039        callback
4040      };
4041      context.requests.push(request);
4042      return request;
4043    }
4044
4045    get _loadTestFont() {
4046      const getLoadTestFont = function () {
4047        return atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQA" + "FQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAA" + "ALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgA" + "AAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1" + "AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD" + "6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACM" + "AooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4D" + "IP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAA" + "AAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUA" + "AQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgAB" + "AAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABY" + "AAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAA" + "AC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAA" + "AAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQAC" + "AQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3" + "Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTj" + "FQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");
4048      };
4049
4050      return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
4051    }
4052
4053    _prepareFontLoadEvent(rules, fonts, request) {
4054      function int32(data, offset) {
4055        return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
4056      }
4057
4058      function spliceString(s, offset, remove, insert) {
4059        const chunk1 = s.substring(0, offset);
4060        const chunk2 = s.substring(offset + remove);
4061        return chunk1 + insert + chunk2;
4062      }
4063
4064      let i, ii;
4065
4066      const canvas = this._document.createElement("canvas");
4067
4068      canvas.width = 1;
4069      canvas.height = 1;
4070      const ctx = canvas.getContext("2d");
4071      let called = 0;
4072
4073      function isFontReady(name, callback) {
4074        called++;
4075
4076        if (called > 30) {
4077          (0, _util.warn)("Load test font never loaded.");
4078          callback();
4079          return;
4080        }
4081
4082        ctx.font = "30px " + name;
4083        ctx.fillText(".", 0, 20);
4084        const imageData = ctx.getImageData(0, 0, 1, 1);
4085
4086        if (imageData.data[3] > 0) {
4087          callback();
4088          return;
4089        }
4090
4091        setTimeout(isFontReady.bind(null, name, callback));
4092      }
4093
4094      const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
4095      let data = this._loadTestFont;
4096      const COMMENT_OFFSET = 976;
4097      data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
4098      const CFF_CHECKSUM_OFFSET = 16;
4099      const XXXX_VALUE = 0x58585858;
4100      let checksum = int32(data, CFF_CHECKSUM_OFFSET);
4101
4102      for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
4103        checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
4104      }
4105
4106      if (i < loadTestFontId.length) {
4107        checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
4108      }
4109
4110      data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
4111      const url = `url(data:font/opentype;base64,${btoa(data)});`;
4112      const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
4113      this.insertRule(rule);
4114      const names = [];
4115
4116      for (const font of fonts) {
4117        names.push(font.loadedName);
4118      }
4119
4120      names.push(loadTestFontId);
4121
4122      const div = this._document.createElement("div");
4123
4124      div.style.visibility = "hidden";
4125      div.style.width = div.style.height = "10px";
4126      div.style.position = "absolute";
4127      div.style.top = div.style.left = "0px";
4128
4129      for (const name of names) {
4130        const span = this._document.createElement("span");
4131
4132        span.textContent = "Hi";
4133        span.style.fontFamily = name;
4134        div.appendChild(span);
4135      }
4136
4137      this._document.body.appendChild(div);
4138
4139      isFontReady(loadTestFontId, () => {
4140        this._document.body.removeChild(div);
4141
4142        request.complete();
4143      });
4144    }
4145
4146  };
4147}
4148
4149class FontFaceObject {
4150  constructor(translatedData, {
4151    isEvalSupported = true,
4152    disableFontFace = false,
4153    ignoreErrors = false,
4154    onUnsupportedFeature,
4155    fontRegistry = null
4156  }) {
4157    this.compiledGlyphs = Object.create(null);
4158
4159    for (const i in translatedData) {
4160      this[i] = translatedData[i];
4161    }
4162
4163    this.isEvalSupported = isEvalSupported !== false;
4164    this.disableFontFace = disableFontFace === true;
4165    this.ignoreErrors = ignoreErrors === true;
4166    this._onUnsupportedFeature = onUnsupportedFeature;
4167    this.fontRegistry = fontRegistry;
4168  }
4169
4170  createNativeFontFace() {
4171    if (!this.data || this.disableFontFace) {
4172      return null;
4173    }
4174
4175    let nativeFontFace;
4176
4177    if (!this.cssFontInfo) {
4178      nativeFontFace = new FontFace(this.loadedName, this.data, {});
4179    } else {
4180      const css = {
4181        weight: this.cssFontInfo.fontWeight
4182      };
4183
4184      if (this.cssFontInfo.italicAngle) {
4185        css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
4186      }
4187
4188      nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
4189    }
4190
4191    if (this.fontRegistry) {
4192      this.fontRegistry.registerFont(this);
4193    }
4194
4195    return nativeFontFace;
4196  }
4197
4198  createFontFaceRule() {
4199    if (!this.data || this.disableFontFace) {
4200      return null;
4201    }
4202
4203    const data = (0, _util.bytesToString)(this.data);
4204    const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
4205    let rule;
4206
4207    if (!this.cssFontInfo) {
4208      rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
4209    } else {
4210      let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
4211
4212      if (this.cssFontInfo.italicAngle) {
4213        css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
4214      }
4215
4216      rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
4217    }
4218
4219    if (this.fontRegistry) {
4220      this.fontRegistry.registerFont(this, url);
4221    }
4222
4223    return rule;
4224  }
4225
4226  getPathGenerator(objs, character) {
4227    if (this.compiledGlyphs[character] !== undefined) {
4228      return this.compiledGlyphs[character];
4229    }
4230
4231    let cmds;
4232
4233    try {
4234      cmds = objs.get(this.loadedName + "_path_" + character);
4235    } catch (ex) {
4236      if (!this.ignoreErrors) {
4237        throw ex;
4238      }
4239
4240      this._onUnsupportedFeature({
4241        featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
4242      });
4243
4244      (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
4245      return this.compiledGlyphs[character] = function (c, size) {};
4246    }
4247
4248    if (this.isEvalSupported && _util.IsEvalSupportedCached.value) {
4249      const jsBuf = [];
4250
4251      for (const current of cmds) {
4252        const args = current.args !== undefined ? current.args.join(",") : "";
4253        jsBuf.push("c.", current.cmd, "(", args, ");\n");
4254      }
4255
4256      return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
4257    }
4258
4259    return this.compiledGlyphs[character] = function (c, size) {
4260      for (const current of cmds) {
4261        if (current.cmd === "scale") {
4262          current.args = [size, -size];
4263        }
4264
4265        c[current.cmd].apply(c, current.args);
4266      }
4267    };
4268  }
4269
4270}
4271
4272exports.FontFaceObject = FontFaceObject;
4273
4274/***/ }),
4275/* 7 */
4276/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4277
4278
4279
4280Object.defineProperty(exports, "__esModule", ({
4281  value: true
4282}));
4283exports.NodeCMapReaderFactory = exports.NodeCanvasFactory = void 0;
4284
4285var _display_utils = __w_pdfjs_require__(1);
4286
4287var _is_node = __w_pdfjs_require__(4);
4288
4289var _util = __w_pdfjs_require__(2);
4290
4291let NodeCanvasFactory = class {
4292  constructor() {
4293    (0, _util.unreachable)("Not implemented: NodeCanvasFactory");
4294  }
4295
4296};
4297exports.NodeCanvasFactory = NodeCanvasFactory;
4298let NodeCMapReaderFactory = class {
4299  constructor() {
4300    (0, _util.unreachable)("Not implemented: NodeCMapReaderFactory");
4301  }
4302
4303};
4304exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
4305
4306if (_is_node.isNodeJS) {
4307  exports.NodeCanvasFactory = NodeCanvasFactory = class extends _display_utils.BaseCanvasFactory {
4308    create(width, height) {
4309      if (width <= 0 || height <= 0) {
4310        throw new Error("Invalid canvas size");
4311      }
4312
4313      const Canvas = require("canvas");
4314
4315      const canvas = Canvas.createCanvas(width, height);
4316      return {
4317        canvas,
4318        context: canvas.getContext("2d")
4319      };
4320    }
4321
4322  };
4323  exports.NodeCMapReaderFactory = NodeCMapReaderFactory = class extends _display_utils.BaseCMapReaderFactory {
4324    _fetchData(url, compressionType) {
4325      return new Promise((resolve, reject) => {
4326        const fs = require("fs");
4327
4328        fs.readFile(url, (error, data) => {
4329          if (error || !data) {
4330            reject(new Error(error));
4331            return;
4332          }
4333
4334          resolve({
4335            cMapData: new Uint8Array(data),
4336            compressionType
4337          });
4338        });
4339      });
4340    }
4341
4342  };
4343}
4344
4345/***/ }),
4346/* 8 */
4347/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4348
4349
4350
4351Object.defineProperty(exports, "__esModule", ({
4352  value: true
4353}));
4354exports.AnnotationStorage = void 0;
4355
4356var _util = __w_pdfjs_require__(2);
4357
4358class AnnotationStorage {
4359  constructor() {
4360    this._storage = new Map();
4361    this._modified = false;
4362    this.onSetModified = null;
4363    this.onResetModified = null;
4364  }
4365
4366  getValue(key, defaultValue) {
4367    const obj = this._storage.get(key);
4368
4369    return obj !== undefined ? obj : defaultValue;
4370  }
4371
4372  setValue(key, value) {
4373    const obj = this._storage.get(key);
4374
4375    let modified = false;
4376
4377    if (obj !== undefined) {
4378      for (const [entry, val] of Object.entries(value)) {
4379        if (obj[entry] !== val) {
4380          modified = true;
4381          obj[entry] = val;
4382        }
4383      }
4384    } else {
4385      this._storage.set(key, value);
4386
4387      modified = true;
4388    }
4389
4390    if (modified) {
4391      this._setModified();
4392    }
4393  }
4394
4395  getAll() {
4396    return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
4397  }
4398
4399  get size() {
4400    return this._storage.size;
4401  }
4402
4403  _setModified() {
4404    if (!this._modified) {
4405      this._modified = true;
4406
4407      if (typeof this.onSetModified === "function") {
4408        this.onSetModified();
4409      }
4410    }
4411  }
4412
4413  resetModified() {
4414    if (this._modified) {
4415      this._modified = false;
4416
4417      if (typeof this.onResetModified === "function") {
4418        this.onResetModified();
4419      }
4420    }
4421  }
4422
4423  get serializable() {
4424    return this._storage.size > 0 ? this._storage : null;
4425  }
4426
4427}
4428
4429exports.AnnotationStorage = AnnotationStorage;
4430
4431/***/ }),
4432/* 9 */
4433/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4434
4435
4436
4437Object.defineProperty(exports, "__esModule", ({
4438  value: true
4439}));
4440exports.apiCompatibilityParams = void 0;
4441
4442var _is_node = __w_pdfjs_require__(4);
4443
4444const compatibilityParams = Object.create(null);
4445{
4446  (function checkFontFace() {
4447    if (_is_node.isNodeJS) {
4448      compatibilityParams.disableFontFace = true;
4449    }
4450  })();
4451}
4452const apiCompatibilityParams = Object.freeze(compatibilityParams);
4453exports.apiCompatibilityParams = apiCompatibilityParams;
4454
4455/***/ }),
4456/* 10 */
4457/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4458
4459
4460
4461Object.defineProperty(exports, "__esModule", ({
4462  value: true
4463}));
4464exports.CanvasGraphics = void 0;
4465
4466var _util = __w_pdfjs_require__(2);
4467
4468var _pattern_helper = __w_pdfjs_require__(11);
4469
4470const MIN_FONT_SIZE = 16;
4471const MAX_FONT_SIZE = 100;
4472const MAX_GROUP_SIZE = 4096;
4473const COMPILE_TYPE3_GLYPHS = true;
4474const MAX_SIZE_TO_COMPILE = 1000;
4475const FULL_CHUNK_HEIGHT = 16;
4476const LINEWIDTH_SCALE_FACTOR = 1.000001;
4477
4478function addContextCurrentTransform(ctx) {
4479  if (ctx.mozCurrentTransform) {
4480    return;
4481  }
4482
4483  ctx._originalSave = ctx.save;
4484  ctx._originalRestore = ctx.restore;
4485  ctx._originalRotate = ctx.rotate;
4486  ctx._originalScale = ctx.scale;
4487  ctx._originalTranslate = ctx.translate;
4488  ctx._originalTransform = ctx.transform;
4489  ctx._originalSetTransform = ctx.setTransform;
4490  ctx._originalResetTransform = ctx.resetTransform;
4491  ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
4492  ctx._transformStack = [];
4493
4494  try {
4495    const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
4496    ctx._setLineWidth = desc.set;
4497    ctx._getLineWidth = desc.get;
4498    Object.defineProperty(ctx, "lineWidth", {
4499      set: function setLineWidth(width) {
4500        this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
4501      },
4502      get: function getLineWidth() {
4503        return this._getLineWidth();
4504      }
4505    });
4506  } catch (_) {}
4507
4508  Object.defineProperty(ctx, "mozCurrentTransform", {
4509    get: function getCurrentTransform() {
4510      return this._transformMatrix;
4511    }
4512  });
4513  Object.defineProperty(ctx, "mozCurrentTransformInverse", {
4514    get: function getCurrentTransformInverse() {
4515      const [a, b, c, d, e, f] = this._transformMatrix;
4516      const ad_bc = a * d - b * c;
4517      const bc_ad = b * c - a * d;
4518      return [d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc];
4519    }
4520  });
4521
4522  ctx.save = function ctxSave() {
4523    const old = this._transformMatrix;
4524
4525    this._transformStack.push(old);
4526
4527    this._transformMatrix = old.slice(0, 6);
4528
4529    this._originalSave();
4530  };
4531
4532  ctx.restore = function ctxRestore() {
4533    const prev = this._transformStack.pop();
4534
4535    if (prev) {
4536      this._transformMatrix = prev;
4537
4538      this._originalRestore();
4539    }
4540  };
4541
4542  ctx.translate = function ctxTranslate(x, y) {
4543    const m = this._transformMatrix;
4544    m[4] = m[0] * x + m[2] * y + m[4];
4545    m[5] = m[1] * x + m[3] * y + m[5];
4546
4547    this._originalTranslate(x, y);
4548  };
4549
4550  ctx.scale = function ctxScale(x, y) {
4551    const m = this._transformMatrix;
4552    m[0] = m[0] * x;
4553    m[1] = m[1] * x;
4554    m[2] = m[2] * y;
4555    m[3] = m[3] * y;
4556
4557    this._originalScale(x, y);
4558  };
4559
4560  ctx.transform = function ctxTransform(a, b, c, d, e, f) {
4561    const m = this._transformMatrix;
4562    this._transformMatrix = [m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5]];
4563
4564    ctx._originalTransform(a, b, c, d, e, f);
4565  };
4566
4567  ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
4568    this._transformMatrix = [a, b, c, d, e, f];
4569
4570    ctx._originalSetTransform(a, b, c, d, e, f);
4571  };
4572
4573  ctx.resetTransform = function ctxResetTransform() {
4574    this._transformMatrix = [1, 0, 0, 1, 0, 0];
4575
4576    ctx._originalResetTransform();
4577  };
4578
4579  ctx.rotate = function ctxRotate(angle) {
4580    const cosValue = Math.cos(angle);
4581    const sinValue = Math.sin(angle);
4582    const m = this._transformMatrix;
4583    this._transformMatrix = [m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * -sinValue + m[2] * cosValue, m[1] * -sinValue + m[3] * cosValue, m[4], m[5]];
4584
4585    this._originalRotate(angle);
4586  };
4587}
4588
4589class CachedCanvases {
4590  constructor(canvasFactory) {
4591    this.canvasFactory = canvasFactory;
4592    this.cache = Object.create(null);
4593  }
4594
4595  getCanvas(id, width, height, trackTransform) {
4596    let canvasEntry;
4597
4598    if (this.cache[id] !== undefined) {
4599      canvasEntry = this.cache[id];
4600      this.canvasFactory.reset(canvasEntry, width, height);
4601      canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
4602    } else {
4603      canvasEntry = this.canvasFactory.create(width, height);
4604      this.cache[id] = canvasEntry;
4605    }
4606
4607    if (trackTransform) {
4608      addContextCurrentTransform(canvasEntry.context);
4609    }
4610
4611    return canvasEntry;
4612  }
4613
4614  clear() {
4615    for (const id in this.cache) {
4616      const canvasEntry = this.cache[id];
4617      this.canvasFactory.destroy(canvasEntry);
4618      delete this.cache[id];
4619    }
4620  }
4621
4622}
4623
4624function compileType3Glyph(imgData) {
4625  const POINT_TO_PROCESS_LIMIT = 1000;
4626  const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
4627  const width = imgData.width,
4628        height = imgData.height,
4629        width1 = width + 1;
4630  let i, ii, j, j0;
4631  const points = new Uint8Array(width1 * (height + 1));
4632  const lineSize = width + 7 & ~7,
4633        data0 = imgData.data;
4634  const data = new Uint8Array(lineSize * height);
4635  let pos = 0;
4636
4637  for (i = 0, ii = data0.length; i < ii; i++) {
4638    const elem = data0[i];
4639    let mask = 128;
4640
4641    while (mask > 0) {
4642      data[pos++] = elem & mask ? 0 : 255;
4643      mask >>= 1;
4644    }
4645  }
4646
4647  let count = 0;
4648  pos = 0;
4649
4650  if (data[pos] !== 0) {
4651    points[0] = 1;
4652    ++count;
4653  }
4654
4655  for (j = 1; j < width; j++) {
4656    if (data[pos] !== data[pos + 1]) {
4657      points[j] = data[pos] ? 2 : 1;
4658      ++count;
4659    }
4660
4661    pos++;
4662  }
4663
4664  if (data[pos] !== 0) {
4665    points[j] = 2;
4666    ++count;
4667  }
4668
4669  for (i = 1; i < height; i++) {
4670    pos = i * lineSize;
4671    j0 = i * width1;
4672
4673    if (data[pos - lineSize] !== data[pos]) {
4674      points[j0] = data[pos] ? 1 : 8;
4675      ++count;
4676    }
4677
4678    let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
4679
4680    for (j = 1; j < width; j++) {
4681      sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
4682
4683      if (POINT_TYPES[sum]) {
4684        points[j0 + j] = POINT_TYPES[sum];
4685        ++count;
4686      }
4687
4688      pos++;
4689    }
4690
4691    if (data[pos - lineSize] !== data[pos]) {
4692      points[j0 + j] = data[pos] ? 2 : 4;
4693      ++count;
4694    }
4695
4696    if (count > POINT_TO_PROCESS_LIMIT) {
4697      return null;
4698    }
4699  }
4700
4701  pos = lineSize * (height - 1);
4702  j0 = i * width1;
4703
4704  if (data[pos] !== 0) {
4705    points[j0] = 8;
4706    ++count;
4707  }
4708
4709  for (j = 1; j < width; j++) {
4710    if (data[pos] !== data[pos + 1]) {
4711      points[j0 + j] = data[pos] ? 4 : 8;
4712      ++count;
4713    }
4714
4715    pos++;
4716  }
4717
4718  if (data[pos] !== 0) {
4719    points[j0 + j] = 4;
4720    ++count;
4721  }
4722
4723  if (count > POINT_TO_PROCESS_LIMIT) {
4724    return null;
4725  }
4726
4727  const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
4728  const outlines = [];
4729
4730  for (i = 0; count && i <= height; i++) {
4731    let p = i * width1;
4732    const end = p + width;
4733
4734    while (p < end && !points[p]) {
4735      p++;
4736    }
4737
4738    if (p === end) {
4739      continue;
4740    }
4741
4742    const coords = [p % width1, i];
4743    const p0 = p;
4744    let type = points[p];
4745
4746    do {
4747      const step = steps[type];
4748
4749      do {
4750        p += step;
4751      } while (!points[p]);
4752
4753      const pp = points[p];
4754
4755      if (pp !== 5 && pp !== 10) {
4756        type = pp;
4757        points[p] = 0;
4758      } else {
4759        type = pp & 0x33 * type >> 4;
4760        points[p] &= type >> 2 | type << 2;
4761      }
4762
4763      coords.push(p % width1, p / width1 | 0);
4764
4765      if (!points[p]) {
4766        --count;
4767      }
4768    } while (p0 !== p);
4769
4770    outlines.push(coords);
4771    --i;
4772  }
4773
4774  const drawOutline = function (c) {
4775    c.save();
4776    c.scale(1 / width, -1 / height);
4777    c.translate(0, -height);
4778    c.beginPath();
4779
4780    for (let k = 0, kk = outlines.length; k < kk; k++) {
4781      const o = outlines[k];
4782      c.moveTo(o[0], o[1]);
4783
4784      for (let l = 2, ll = o.length; l < ll;
4784 l += 2) {
4785        c.lineTo(o[l], o[l + 1]);
4786      }
4787    }
4788
4789    c.fill();
4790    c.beginPath();
4791    c.restore();
4792  };
4793
4794  return drawOutline;
4795}
4796
4797class CanvasExtraState {
4798  constructor() {
4799    this.alphaIsShape = false;
4800    this.fontSize = 0;
4801    this.fontSizeScale = 1;
4802    this.textMatrix = _util.IDENTITY_MATRIX;
4803    this.textMatrixScale = 1;
4804    this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
4805    this.leading = 0;
4806    this.x = 0;
4807    this.y = 0;
4808    this.lineX = 0;
4809    this.lineY = 0;
4810    this.charSpacing = 0;
4811    this.wordSpacing = 0;
4812    this.textHScale = 1;
4813    this.textRenderingMode = _util.TextRenderingMode.FILL;
4814    this.textRise = 0;
4815    this.fillColor = "#000000";
4816    this.strokeColor = "#000000";
4817    this.patternFill = false;
4818    this.fillAlpha = 1;
4819    this.strokeAlpha = 1;
4820    this.lineWidth = 1;
4821    this.activeSMask = null;
4822    this.resumeSMaskCtx = null;
4823    this.transferMaps = null;
4824  }
4825
4826  clone() {
4827    return Object.create(this);
4828  }
4829
4830  setCurrentPoint(x, y) {
4831    this.x = x;
4832    this.y = y;
4833  }
4834
4835}
4836
4837const CanvasGraphics = function CanvasGraphicsClosure() {
4838  const EXECUTION_TIME = 15;
4839  const EXECUTION_STEPS = 10;
4840
4841  function putBinaryImageData(ctx, imgData, transferMaps = null) {
4842    if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
4843      ctx.putImageData(imgData, 0, 0);
4844      return;
4845    }
4846
4847    const height = imgData.height,
4848          width = imgData.width;
4849    const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
4850    const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
4851    const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
4852    const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
4853    let srcPos = 0,
4854        destPos;
4855    const src = imgData.data;
4856    const dest = chunkImgData.data;
4857    let i, j, thisChunkHeight, elemsInThisChunk;
4858    let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
4859
4860    if (transferMaps) {
4861      switch (transferMaps.length) {
4862        case 1:
4863          transferMapRed = transferMaps[0];
4864          transferMapGreen = transferMaps[0];
4865          transferMapBlue = transferMaps[0];
4866          transferMapGray = transferMaps[0];
4867          break;
4868
4869        case 4:
4870          transferMapRed = transferMaps[0];
4871          transferMapGreen = transferMaps[1];
4872          transferMapBlue = transferMaps[2];
4873          transferMapGray = transferMaps[3];
4874          break;
4875      }
4876    }
4877
4878    if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
4879      const srcLength = src.byteLength;
4880      const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
4881      const dest32DataLength = dest32.length;
4882      const fullSrcDiff = width + 7 >> 3;
4883      let white = 0xffffffff;
4884      let black = _util.IsLittleEndianCached.value ? 0xff000000 : 0x000000ff;
4885
4886      if (transferMapGray) {
4887        if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
4888          [white, black] = [black, white];
4889        }
4890      }
4891
4892      for (i = 0; i < totalChunks; i++) {
4893        thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
4894        destPos = 0;
4895
4896        for (j = 0; j < thisChunkHeight; j++) {
4897          const srcDiff = srcLength - srcPos;
4898          let k = 0;
4899          const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
4900          const kEndUnrolled = kEnd & ~7;
4901          let mask = 0;
4902          let srcByte = 0;
4903
4904          for (; k < kEndUnrolled; k += 8) {
4905            srcByte = src[srcPos++];
4906            dest32[destPos++] = srcByte & 128 ? white : black;
4907            dest32[destPos++] = srcByte & 64 ? white : black;
4908            dest32[destPos++] = srcByte & 32 ? white : black;
4909            dest32[destPos++] = srcByte & 16 ? white : black;
4910            dest32[destPos++] = srcByte & 8 ? white : black;
4911            dest32[destPos++] = srcByte & 4 ? white : black;
4912            dest32[destPos++] = srcByte & 2 ? white : black;
4913            dest32[destPos++] = srcByte & 1 ? white : black;
4914          }
4915
4916          for (; k < kEnd; k++) {
4917            if (mask === 0) {
4918              srcByte = src[srcPos++];
4919              mask = 128;
4920            }
4921
4922            dest32[destPos++] = srcByte & mask ? white : black;
4923            mask >>= 1;
4924          }
4925        }
4926
4927        while (destPos < dest32DataLength) {
4928          dest32[destPos++] = 0;
4929        }
4930
4931        ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
4932      }
4933    } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
4934      const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
4935      j = 0;
4936      elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
4937
4938      for (i = 0; i < fullChunks; i++) {
4939        dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
4940        srcPos += elemsInThisChunk;
4941
4942        if (hasTransferMaps) {
4943          for (let k = 0; k < elemsInThisChunk; k += 4) {
4944            if (transferMapRed) {
4945              dest[k + 0] = transferMapRed[dest[k + 0]];
4946            }
4947
4948            if (transferMapGreen) {
4949              dest[k + 1] = transferMapGreen[dest[k + 1]];
4950            }
4951
4952            if (transferMapBlue) {
4953              dest[k + 2] = transferMapBlue[dest[k + 2]];
4954            }
4955          }
4956        }
4957
4958        ctx.putImageData(chunkImgData, 0, j);
4959        j += FULL_CHUNK_HEIGHT;
4960      }
4961
4962      if (i < totalChunks) {
4963        elemsInThisChunk = width * partialChunkHeight * 4;
4964        dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
4965
4966        if (hasTransferMaps) {
4967          for (let k = 0; k < elemsInThisChunk; k += 4) {
4968            if (transferMapRed) {
4969              dest[k + 0] = transferMapRed[dest[k + 0]];
4970            }
4971
4972            if (transferMapGreen) {
4973              dest[k + 1] = transferMapGreen[dest[k + 1]];
4974            }
4975
4976            if (transferMapBlue) {
4977              dest[k + 2] = transferMapBlue[dest[k + 2]];
4978            }
4979          }
4980        }
4981
4982        ctx.putImageData(chunkImgData, 0, j);
4983      }
4984    } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
4985      const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
4986      thisChunkHeight = FULL_CHUNK_HEIGHT;
4987      elemsInThisChunk = width * thisChunkHeight;
4988
4989      for (i = 0; i < totalChunks; i++) {
4990        if (i >= fullChunks) {
4991          thisChunkHeight = partialChunkHeight;
4992          elemsInThisChunk = width * thisChunkHeight;
4993        }
4994
4995        destPos = 0;
4996
4997        for (j = elemsInThisChunk; j--;) {
4998          dest[destPos++] = src[srcPos++];
4999          dest[destPos++] = src[srcPos++];
5000          dest[destPos++] = src[srcPos++];
5001          dest[destPos++] = 255;
5002        }
5003
5004        if (hasTransferMaps) {
5005          for (let k = 0; k < destPos; k += 4) {
5006            if (transferMapRed) {
5007              dest[k + 0] = transferMapRed[dest[k + 0]];
5008            }
5009
5010            if (transferMapGreen) {
5011              dest[k + 1] = transferMapGreen[dest[k + 1]];
5012            }
5013
5014            if (transferMapBlue) {
5015              dest[k + 2] = transferMapBlue[dest[k + 2]];
5016            }
5017          }
5018        }
5019
5020        ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5021      }
5022    } else {
5023      throw new Error(`bad image kind: ${imgData.kind}`);
5024    }
5025  }
5026
5027  function putBinaryImageMask(ctx, imgData) {
5028    const height = imgData.height,
5029          width = imgData.width;
5030    const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5031    const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5032    const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5033    const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5034    let srcPos = 0;
5035    const src = imgData.data;
5036    const dest = chunkImgData.data;
5037
5038    for (let i = 0; i < totalChunks; i++) {
5039      const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5040      let destPos = 3;
5041
5042      for (let j = 0; j < thisChunkHeight; j++) {
5043        let elem,
5044            mask = 0;
5045
5046        for (let k = 0; k < width; k++) {
5047          if (!mask) {
5048            elem = src[srcPos++];
5049            mask = 128;
5050          }
5051
5052          dest[destPos] = elem & mask ? 0 : 255;
5053          destPos += 4;
5054          mask >>= 1;
5055        }
5056      }
5057
5058      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5059    }
5060  }
5061
5062  function copyCtxState(sourceCtx, destCtx) {
5063    const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
5064
5065    for (let i = 0, ii = properties.length; i < ii; i++) {
5066      const property = properties[i];
5067
5068      if (sourceCtx[property] !== undefined) {
5069        destCtx[property] = sourceCtx[property];
5070      }
5071    }
5072
5073    if (sourceCtx.setLineDash !== undefined) {
5074      destCtx.setLineDash(sourceCtx.getLineDash());
5075      destCtx.lineDashOffset = sourceCtx.lineDashOffset;
5076    }
5077  }
5078
5079  function resetCtxToDefault(ctx) {
5080    ctx.strokeStyle = "#000000";
5081    ctx.fillStyle = "#000000";
5082    ctx.fillRule = "nonzero";
5083    ctx.globalAlpha = 1;
5084    ctx.lineWidth = 1;
5085    ctx.lineCap = "butt";
5086    ctx.lineJoin = "miter";
5087    ctx.miterLimit = 10;
5088    ctx.globalCompositeOperation = "source-over";
5089    ctx.font = "10px sans-serif";
5090
5091    if (ctx.setLineDash !== undefined) {
5092      ctx.setLineDash([]);
5093      ctx.lineDashOffset = 0;
5094    }
5095  }
5096
5097  function composeSMaskBackdrop(bytes, r0, g0, b0) {
5098    const length = bytes.length;
5099
5100    for (let i = 3; i < length; i += 4) {
5101      const alpha = bytes[i];
5102
5103      if (alpha === 0) {
5104        bytes[i - 3] = r0;
5105        bytes[i - 2] = g0;
5106        bytes[i - 1] = b0;
5107      } else if (alpha < 255) {
5108        const alpha_ = 255 - alpha;
5109        bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
5110        bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
5111        bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
5112      }
5113    }
5114  }
5115
5116  function composeSMaskAlpha(maskData, layerData, transferMap) {
5117    const length = maskData.length;
5118    const scale = 1 / 255;
5119
5120    for (let i = 3; i < length; i += 4) {
5121      const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
5122      layerData[i] = layerData[i] * alpha * scale | 0;
5123    }
5124  }
5125
5126  function composeSMaskLuminosity(maskData, layerData, transferMap) {
5127    const length = maskData.length;
5128
5129    for (let i = 3; i < length; i += 4) {
5130      const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
5131      layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
5132    }
5133  }
5134
5135  function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) {
5136    const hasBackdrop = !!backdrop;
5137    const r0 = hasBackdrop ? backdrop[0] : 0;
5138    const g0 = hasBackdrop ? backdrop[1] : 0;
5139    const b0 = hasBackdrop ? backdrop[2] : 0;
5140    let composeFn;
5141
5142    if (subtype === "Luminosity") {
5143      composeFn = composeSMaskLuminosity;
5144    } else {
5145      composeFn = composeSMaskAlpha;
5146    }
5147
5148    const PIXELS_TO_PROCESS = 1048576;
5149    const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
5150
5151    for (let row = 0; row < height; row += chunkSize) {
5152      const chunkHeight = Math.min(chunkSize, height - row);
5153      const maskData = maskCtx.getImageData(0, row, width, chunkHeight);
5154      const layerData = layerCtx.getImageData(0, row, width, chunkHeight);
5155
5156      if (hasBackdrop) {
5157        composeSMaskBackdrop(maskData.data, r0, g0, b0);
5158      }
5159
5160      composeFn(maskData.data, layerData.data, transferMap);
5161      maskCtx.putImageData(layerData, 0, row);
5162    }
5163  }
5164
5165  function composeSMask(ctx, smask, layerCtx) {
5166    const mask = smask.canvas;
5167    const maskCtx = smask.context;
5168    ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY);
5169    genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, smask.backdrop, smask.transferMap);
5170    ctx.drawImage(mask, 0, 0);
5171  }
5172
5173  const LINE_CAP_STYLES = ["butt", "round", "square"];
5174  const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
5175  const NORMAL_CLIP = {};
5176  const EO_CLIP = {};
5177
5178  class CanvasGraphics {
5179    constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig) {
5180      this.ctx = canvasCtx;
5181      this.current = new CanvasExtraState();
5182      this.stateStack = [];
5183      this.pendingClip = null;
5184      this.pendingEOFill = false;
5185      this.res = null;
5186      this.xobjs = null;
5187      this.commonObjs = commonObjs;
5188      this.objs = objs;
5189      this.canvasFactory = canvasFactory;
5190      this.imageLayer = imageLayer;
5191      this.groupStack = [];
5192      this.processingType3 = null;
5193      this.baseTransform = null;
5194      this.baseTransformStack = [];
5195      this.groupLevel = 0;
5196      this.smaskStack = [];
5197      this.smaskCounter = 0;
5198      this.tempSMask = null;
5199      this.contentVisible = true;
5200      this.markedContentStack = [];
5201      this.optionalContentConfig = optionalContentConfig;
5202      this.cachedCanvases = new CachedCanvases(this.canvasFactory);
5203
5204      if (canvasCtx) {
5205        addContextCurrentTransform(canvasCtx);
5206      }
5207
5208      this._cachedGetSinglePixelWidth = null;
5209    }
5210
5211    beginDrawing({
5212      transform,
5213      viewport,
5214      transparency = false,
5215      background = null
5216    }) {
5217      const width = this.ctx.canvas.width;
5218      const height = this.ctx.canvas.height;
5219      this.ctx.save();
5220      this.ctx.fillStyle = background || "rgb(255, 255, 255)";
5221      this.ctx.fillRect(0, 0, width, height);
5222      this.ctx.restore();
5223
5224      if (transparency) {
5225        const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
5226        this.compositeCtx = this.ctx;
5227        this.transparentCanvas = transparentCanvas.canvas;
5228        this.ctx = transparentCanvas.context;
5229        this.ctx.save();
5230        this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
5231      }
5232
5233      this.ctx.save();
5234      resetCtxToDefault(this.ctx);
5235
5236      if (transform) {
5237        this.ctx.transform.apply(this.ctx, transform);
5238      }
5239
5240      this.ctx.transform.apply(this.ctx, viewport.transform);
5241      this.baseTransform = this.ctx.mozCurrentTransform.slice();
5242      this._combinedScaleFactor = Math.hypot(this.baseTransform[0], this.baseTransform[2]);
5243
5244      if (this.imageLayer) {
5245        this.imageLayer.beginLayout();
5246      }
5247    }
5248
5249    executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
5250      const argsArray = operatorList.argsArray;
5251      const fnArray = operatorList.fnArray;
5252      let i = executionStartIdx || 0;
5253      const argsArrayLen = argsArray.length;
5254
5255      if (argsArrayLen === i) {
5256        return i;
5257      }
5258
5259      const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
5260      const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
5261      let steps = 0;
5262      const commonObjs = this.commonObjs;
5263      const objs = this.objs;
5264      let fnId;
5265
5266      while (true) {
5267        if (stepper !== undefined && i === stepper.nextBreakPoint) {
5268          stepper.breakIt(i, continueCallback);
5269          return i;
5270        }
5271
5272        fnId = fnArray[i];
5273
5274        if (fnId !== _util.OPS.dependency) {
5275          this[fnId].apply(this, argsArray[i]);
5276        } else {
5277          for (const depObjId of argsArray[i]) {
5278            const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
5279
5280            if (!objsPool.has(depObjId)) {
5281              objsPool.get(depObjId, continueCallback);
5282              return i;
5283            }
5284          }
5285        }
5286
5287        i++;
5288
5289        if (i === argsArrayLen) {
5290          return i;
5291        }
5292
5293        if (chunkOperations && ++steps > EXECUTION_STEPS) {
5294          if (Date.now() > endTime) {
5295            continueCallback();
5296            return i;
5297          }
5298
5299          steps = 0;
5300        }
5301      }
5302    }
5303
5304    endDrawing() {
5305      while (this.stateStack.length || this.current.activeSMask !== null) {
5306        this.restore();
5307      }
5308
5309      this.ctx.restore();
5310
5311      if (this.transparentCanvas) {
5312        this.ctx = this.compositeCtx;
5313        this.ctx.save();
5314        this.ctx.setTransform(1, 0, 0, 1, 0, 0);
5315        this.ctx.drawImage(this.transparentCanvas, 0, 0);
5316        this.ctx.restore();
5317        this.transparentCanvas = null;
5318      }
5319
5320      this.cachedCanvases.clear();
5321
5322      if (this.imageLayer) {
5323        this.imageLayer.endLayout();
5324      }
5325    }
5326
5327    setLineWidth(width) {
5328      this.current.lineWidth = width;
5329      this.ctx.lineWidth = width;
5330    }
5331
5332    setLineCap(style) {
5333      this.ctx.lineCap = LINE_CAP_STYLES[style];
5334    }
5335
5336    setLineJoin(style) {
5337      this.ctx.lineJoin = LINE_JOIN_STYLES[style];
5338    }
5339
5340    setMiterLimit(limit) {
5341      this.ctx.miterLimit = limit;
5342    }
5343
5344    setDash(dashArray, dashPhase) {
5345      const ctx = this.ctx;
5346
5347      if (ctx.setLineDash !== undefined) {
5348        ctx.setLineDash(dashArray);
5349        ctx.lineDashOffset = dashPhase;
5350      }
5351    }
5352
5353    setRenderingIntent(intent) {}
5354
5355    setFlatness(flatness) {}
5356
5357    setGState(states) {
5358      for (let i = 0, ii = states.length; i < ii; i++) {
5359        const state = states[i];
5360        const key = state[0];
5361        const value = state[1];
5362
5363        switch (key) {
5364          case "LW":
5365            this.setLineWidth(value);
5366            break;
5367
5368          case "LC":
5369            this.setLineCap(value);
5370            break;
5371
5372          case "LJ":
5373            this.setLineJoin(value);
5374            break;
5375
5376          case "ML":
5377            this.setMiterLimit(value);
5378            break;
5379
5380          case "D":
5381            this.setDash(value[0], value[1]);
5382            break;
5383
5384          case "RI":
5385            this.setRenderingIntent(value);
5386            break;
5387
5388          case "FL":
5389            this.setFlatness(value);
5390            break;
5391
5392          case "Font":
5393            this.setFont(value[0], value[1]);
5394            break;
5395
5396          case "CA":
5397            this.current.strokeAlpha = state[1];
5398            break;
5399
5400          case "ca":
5401            this.current.fillAlpha = state[1];
5402            this.ctx.globalAlpha = state[1];
5403            break;
5404
5405          case "BM":
5406            this.ctx.globalCompositeOperation = value;
5407            break;
5408
5409          case "SMask":
5410            if (this.current.activeSMask) {
5411              if (this.stateStack.length > 0 && this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask) {
5412                this.suspendSMaskGroup();
5413              } else {
5414                this.endSMaskGroup();
5415              }
5416            }
5417
5418            this.current.activeSMask = value ? this.tempSMask : null;
5419
5420            if (this.current.activeSMask) {
5421              this.beginSMaskGroup();
5422            }
5423
5424            this.tempSMask = null;
5425            break;
5426
5427          case "TR":
5428            this.current.transferMaps = value;
5429        }
5430      }
5431    }
5432
5433    beginSMaskGroup() {
5434      const activeSMask = this.current.activeSMask;
5435      const drawnWidth = activeSMask.canvas.width;
5436      const drawnHeight = activeSMask.canvas.height;
5437      const cacheId = "smaskGroupAt" + this.groupLevel;
5438      const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
5439      const currentCtx = this.ctx;
5440      const currentTransform = currentCtx.mozCurrentTransform;
5441      this.ctx.save();
5442      const groupCtx = scratchCanvas.context;
5443      groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY);
5444      groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY);
5445      groupCtx.transform.apply(groupCtx, currentTransform);
5446      activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse;
5447      copyCtxState(currentCtx, groupCtx);
5448      this.ctx = groupCtx;
5449      this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
5450      this.groupStack.push(currentCtx);
5451      this.groupLevel++;
5452    }
5453
5454    suspendSMaskGroup() {
5455      const groupCtx = this.ctx;
5456      this.groupLevel--;
5457      this.ctx = this.groupStack.pop();
5458      composeSMask(this.ctx, this.current.activeSMask, groupCtx);
5459      this.ctx.restore();
5460      this.ctx.save();
5461      copyCtxState(groupCtx, this.ctx);
5462      this.current.resumeSMaskCtx = groupCtx;
5463
5464      const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
5465
5466      this.ctx.transform.apply(this.ctx, deltaTransform);
5467      groupCtx.save();
5468      groupCtx.setTransform(1, 0, 0, 1, 0, 0);
5469      groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height);
5470      groupCtx.restore();
5471    }
5472
5473    resumeSMaskGroup() {
5474      const groupCtx = this.current.resumeSMaskCtx;
5475      const currentCtx = this.ctx;
5476      this.ctx = groupCtx;
5477      this.groupStack.push(currentCtx);
5478      this.groupLevel++;
5479    }
5480
5481    endSMaskGroup() {
5482      const groupCtx = this.ctx;
5483      this.groupLevel--;
5484      this.ctx = this.groupStack.pop();
5485      composeSMask(this.ctx, this.current.activeSMask, groupCtx);
5486      this.ctx.restore();
5487      copyCtxState(groupCtx, this.ctx);
5488
5489      const deltaTransform = _util.Util.transform(this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform);
5490
5491      this.ctx.transform.apply(this.ctx, deltaTransform);
5492    }
5493
5494    save() {
5495      this.ctx.save();
5496      const old = this.current;
5497      this.stateStack.push(old);
5498      this.current = old.clone();
5499      this.current.resumeSMaskCtx = null;
5500    }
5501
5502    restore() {
5503      if (this.current.resumeSMaskCtx) {
5504        this.resumeSMaskGroup();
5505      }
5506
5507      if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) {
5508        this.endSMaskGroup();
5509      }
5510
5511      if (this.stateStack.length !== 0) {
5512        this.current = this.stateStack.pop();
5513        this.ctx.restore();
5514        this.pendingClip = null;
5515        this._cachedGetSinglePixelWidth = null;
5516      } else {
5517        this.current.activeSMask = null;
5518      }
5519    }
5520
5521    transform(a, b, c, d, e, f) {
5522      this.ctx.transform(a, b, c, d, e, f);
5523      this._cachedGetSinglePixelWidth = null;
5524    }
5525
5526    constructPath(ops, args) {
5527      const ctx = this.ctx;
5528      const current = this.current;
5529      let x = current.x,
5530          y = current.y;
5531
5532      for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
5533        switch (ops[i] | 0) {
5534          case _util.OPS.rectangle:
5535            x = args[j++];
5536            y = args[j++];
5537            const width = args[j++];
5538            const height = args[j++];
5539            const xw = x + width;
5540            const yh = y + height;
5541            ctx.moveTo(x, y);
5542
5543            if (width === 0 || height === 0) {
5544              ctx.lineTo(xw, yh);
5545            } else {
5546              ctx.lineTo(xw, y);
5547              ctx.lineTo(xw, yh);
5548              ctx.lineTo(x, yh);
5549            }
5550
5551            ctx.closePath();
5552            break;
5553
5554          case _util.OPS.moveTo:
5555            x = args[j++];
5556            y = args[j++];
5557            ctx.moveTo(x, y);
5558            break;
5559
5560          case _util.OPS.lineTo:
5561            x = args[j++];
5562            y = args[j++];
5563            ctx.lineTo(x, y);
5564            break;
5565
5566          case _util.OPS.curveTo:
5567            x = args[j + 4];
5568            y = args[j + 5];
5569            ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
5570            j += 6;
5571            break;
5572
5573          case _util.OPS.curveTo2:
5574            ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
5575            x = args[j + 2];
5576            y = args[j + 3];
5577            j += 4;
5578            break;
5579
5580          case _util.OPS.curveTo3:
5581            x = args[j + 2];
5582            y = args[j + 3];
5583            ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
5584            j += 4;
5585            break;
5586
5587          case _util.OPS.closePath:
5588            ctx.closePath();
5589            break;
5590        }
5591      }
5592
5593      current.setCurrentPoint(x, y);
5594    }
5595
5596    closePath() {
5597      this.ctx.closePath();
5598    }
5599
5600    stroke(consumePath) {
5601      consumePath = typeof consumePath !== "undefined" ? consumePath : true;
5602      const ctx = this.ctx;
5603      const strokeColor = this.current.strokeColor;
5604      ctx.globalAlpha = this.current.strokeAlpha;
5605
5606      if (this.contentVisible) {
5607        if (typeof strokeColor === "object" && strokeColor?.getPattern) {
5608          const lineWidth = this.getSinglePixelWidth();
5609          ctx.save();
5610          ctx.strokeStyle = strokeColor.getPattern(ctx, this);
5611          ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
5612          ctx.stroke();
5613          ctx.restore();
5614        } else {
5615          const lineWidth = this.getSinglePixelWidth();
5616
5617          if (lineWidth < 0 && -lineWidth >= this.current.lineWidth) {
5618            ctx.save();
5619            ctx.resetTransform();
5620            ctx.lineWidth = Math.round(this._combinedScaleFactor);
5621            ctx.stroke();
5622            ctx.restore();
5623          } else {
5624            ctx.lineWidth = Math.max(lineWidth, this.current.lineWidth);
5625            ctx.stroke();
5626          }
5627        }
5628      }
5629
5630      if (consumePath) {
5631        this.consumePath();
5632      }
5633
5634      ctx.globalAlpha = this.current.fillAlpha;
5635    }
5636
5637    closeStroke() {
5638      this.closePath();
5639      this.stroke();
5640    }
5641
5642    fill(consumePath) {
5643      consumePath = typeof consumePath !== "undefined" ? consumePath : true;
5644      const ctx = this.ctx;
5645      const fillColor = this.current.fillColor;
5646      const isPatternFill = this.current.patternFill;
5647      let needRestore = false;
5648
5649      if (isPatternFill) {
5650        ctx.save();
5651        ctx.fillStyle = fillColor.getPattern(ctx, this);
5652        needRestore = true;
5653      }
5654
5655      if (this.contentVisible) {
5656        if (this.pendingEOFill) {
5657          ctx.fill("evenodd");
5658          this.pendingEOFill = false;
5659        } else {
5660          ctx.fill();
5661        }
5662      }
5663
5664      if (needRestore) {
5665        ctx.restore();
5666      }
5667
5668      if (consumePath) {
5669        this.consumePath();
5670      }
5671    }
5672
5673    eoFill() {
5674      this.pendingEOFill = true;
5675      this.fill();
5676    }
5677
5678    fillStroke() {
5679      this.fill(false);
5680      this.stroke(false);
5681      this.consumePath();
5682    }
5683
5684    eoFillStroke() {
5685      this.pendingEOFill = true;
5686      this.fillStroke();
5687    }
5688
5689    closeFillStroke() {
5690      this.closePath();
5691      this.fillStroke();
5692    }
5693
5694    closeEOFillStroke() {
5695      this.pendingEOFill = true;
5696      this.closePath();
5697      this.fillStroke();
5698    }
5699
5700    endPath() {
5701      this.consumePath();
5702    }
5703
5704    clip() {
5705      this.pendingClip = NORMAL_CLIP;
5706    }
5707
5708    eoClip() {
5709      this.pendingClip = EO_CLIP;
5710    }
5711
5712    beginText() {
5713      this.current.textMatrix = _util.IDENTITY_MATRIX;
5714      this.current.textMatrixScale = 1;
5715      this.current.x = this.current.lineX = 0;
5716      this.current.y = this.current.lineY = 0;
5717    }
5718
5719    endText() {
5720      const paths = this.pendingTextPaths;
5721      const ctx = this.ctx;
5722
5723      if (paths === undefined) {
5724        ctx.beginPath();
5725        return;
5726      }
5727
5728      ctx.save();
5729      ctx.beginPath();
5730
5731      for (let i = 0; i < paths.length; i++) {
5732        const path = paths[i];
5733        ctx.setTransform.apply(ctx, path.transform);
5734        ctx.translate(path.x, path.y);
5735        path.addToPath(ctx, path.fontSize);
5736      }
5737
5738      ctx.restore();
5739      ctx.clip();
5740      ctx.beginPath();
5741      delete this.pendingTextPaths;
5742    }
5743
5744    setCharSpacing(spacing) {
5745      this.current.charSpacing = spacing;
5746    }
5747
5748    setWordSpacing(spacing) {
5749      this.current.wordSpacing = spacing;
5750    }
5751
5752    setHScale(scale) {
5753      this.current.textHScale = scale / 100;
5754    }
5755
5756    setLeading(leading) {
5757      this.current.leading = -leading;
5758    }
5759
5760    setFont(fontRefName, size) {
5761      const fontObj = this.commonObjs.get(fontRefName);
5762      const current = this.current;
5763
5764      if (!fontObj) {
5765        throw new Error(`Can't find font for ${fontRefName}`);
5766      }
5767
5768      current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
5769
5770      if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
5771        (0, _util.warn)("Invalid font matrix for font " + fontRefName);
5772      }
5773
5774      if (size < 0) {
5775        size = -size;
5776        current.fontDirection = -1;
5777      } else {
5778        current.fontDirection = 1;
5779      }
5780
5781      this.current.font = fontObj;
5782      this.current.fontSize = size;
5783
5784      if (fontObj.isType3Font) {
5785        return;
5786      }
5787
5788      const name = fontObj.loadedName || "sans-serif";
5789      let bold = "normal";
5790
5791      if (fontObj.black) {
5792        bold = "900";
5793      } else if (fontObj.bold) {
5794        bold = "bold";
5795      }
5796
5797      const italic = fontObj.italic ? "italic" : "normal";
5798      const typeface = `"${name}", ${fontObj.fallbackName}`;
5799      let browserFontSize = size;
5800
5801      if (size < MIN_FONT_SIZE) {
5802        browserFontSize = MIN_FONT_SIZE;
5803      } else if (size > MAX_FONT_SIZE) {
5804        browserFontSize = MAX_FONT_SIZE;
5805      }
5806
5807      this.current.fontSizeScale = size / browserFontSize;
5808      this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
5809    }
5810
5811    setTextRenderingMode(mode) {
5812      this.current.textRenderingMode = mode;
5813    }
5814
5815    setTextRise(rise) {
5816      this.current.textRise = rise;
5817    }
5818
5819    moveText(x, y) {
5820      this.current.x = this.current.lineX += x;
5821      this.current.y = this.current.lineY += y;
5822    }
5823
5824    setLeadingMoveText(x, y) {
5825      this.setLeading(-y);
5826      this.moveText(x, y);
5827    }
5828
5829    setTextMatrix(a, b, c, d, e, f) {
5830      this.current.textMatrix = [a, b, c, d, e, f];
5831      this.current.textMatrixScale = Math.hypot(a, b);
5832      this.current.x = this.current.lineX = 0;
5833      this.current.y = this.current.lineY = 0;
5834    }
5835
5836    nextLine() {
5837      this.moveText(0, this.current.leading);
5838    }
5839
5840    paintChar(character, x, y, patternTransform, resetLineWidthToOne) {
5841      const ctx = this.ctx;
5842      const current = this.current;
5843      const font = current.font;
5844      const textRenderingMode = current.textRenderingMode;
5845      const fontSize = current.fontSize / current.fontSizeScale;
5846      const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
5847      const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
5848      const patternFill = current.patternFill && !font.missingFile;
5849      let addToPath;
5850
5851      if (font.disableFontFace || isAddToPathSet || patternFill) {
5852        addToPath = font.getPathGenerator(this.commonObjs, character);
5853      }
5854
5855      if (font.disableFontFace || patternFill) {
5856        ctx.save();
5857        ctx.translate(x, y);
5858        ctx.beginPath();
5859        addToPath(ctx, fontSize);
5860
5861        if (patternTransform) {
5862          ctx.setTransform.apply(ctx, patternTransform);
5863        }
5864
5865        if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
5866          ctx.fill();
5867        }
5868
5869        if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
5870          if (resetLineWidthToOne) {
5871            ctx.resetTransform();
5872            ctx.lineWidth = Math.round(this._combinedScaleFactor);
5873          }
5874
5875          ctx.stroke();
5876        }
5877
5878        ctx.restore();
5879      } else {
5880        if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
5881          ctx.fillText(character, x, y);
5882        }
5883
5884        if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
5885          if (resetLineWidthToOne) {
5886            ctx.save();
5887            ctx.moveTo(x, y);
5888            ctx.resetTransform();
5889            ctx.lineWidth = Math.round(this._combinedScaleFactor);
5890            ctx.strokeText(character, 0, 0);
5891            ctx.restore();
5892          } else {
5893            ctx.strokeText(character, x, y);
5894          }
5895        }
5896      }
5897
5898      if (isAddToPathSet) {
5899        const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
5900        paths.push({
5901          transform: ctx.mozCurrentTransform,
5902          x,
5903          y,
5904          fontSize,
5905          addToPath
5906        });
5907      }
5908    }
5909
5910    get isFontSubpixelAAEnabled() {
5911      const {
5912        context: ctx
5913      } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10);
5914      ctx.scale(1.5, 1);
5915      ctx.fillText("I", 0, 10);
5916      const data = ctx.getImageData(0, 0, 10, 10).data;
5917      let enabled = false;
5918
5919      for (let i = 3; i < data.length; i += 4) {
5920        if (data[i] > 0 && data[i] < 255) {
5921          enabled = true;
5922          break;
5923        }
5924      }
5925
5926      return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
5927    }
5928
5929    showText(glyphs) {
5930      const current = this.current;
5931      const font = current.font;
5932
5933      if (font.isType3Font) {
5934        return this.showType3Text(glyphs);
5935      }
5936
5937      const fontSize = current.fontSize;
5938
5939      if (fontSize === 0) {
5940        return undefined;
5941      }
5942
5943      const ctx = this.ctx;
5944      const fontSizeScale = current.fontSizeScale;
5945      const charSpacing = current.charSpacing;
5946      const wordSpacing = current.wordSpacing;
5947      const fontDirection = current.fontDirection;
5948      const textHScale = current.textHScale * fontDirection;
5949      const glyphsLength = glyphs.length;
5950      const vertical = font.vertical;
5951      const spacingDir = vertical ? 1 : -1;
5952      const defaultVMetrics = font.defaultVMetrics;
5953      const widthAdvanceScale = fontSize * current.fontMatrix[0];
5954      const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
5955      ctx.save();
5956      let patternTransform;
5957
5958      if (current.patternFill) {
5959        ctx.save();
5960        const pattern = current.fillColor.getPattern(ctx, this);
5961        patternTransform = ctx.mozCurrentTransform;
5962        ctx.restore();
5963        ctx.fillStyle = pattern;
5964      }
5965
5966      ctx.transform.apply(ctx, current.textMatrix);
5967      ctx.translate(current.x, current.y + current.textRise);
5968
5969      if (fontDirection > 0) {
5970        ctx.scale(textHScale, -1);
5971      } else {
5972        ctx.scale(textHScale, 1);
5973      }
5974
5975      let lineWidth = current.lineWidth;
5976      let resetLineWidthToOne = false;
5977      const scale = current.textMatrixScale;
5978
5979      if (scale === 0 || lineWidth === 0) {
5980        const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
5981
5982        if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
5983          this._cachedGetSinglePixelWidth = null;
5984          lineWidth = this.getSinglePixelWidth();
5985          resetLineWidthToOne = lineWidth < 0;
5986        }
5987      } else {
5988        lineWidth /= scale;
5989      }
5990
5991      if (fontSizeScale !== 1.0) {
5992        ctx.scale(fontSizeScale, fontSizeScale);
5993        lineWidth /= fontSizeScale;
5994      }
5995
5996      ctx.lineWidth = lineWidth;
5997      let x = 0,
5998          i;
5999
6000      for (i = 0; i < glyphsLength; ++i) {
6001        const glyph = glyphs[i];
6002
6003        if ((0, _util.isNum)(glyph)) {
6004          x += spacingDir * glyph * fontSize / 1000;
6005          continue;
6006        }
6007
6008        let restoreNeeded = false;
6009        const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6010        const character = glyph.fontChar;
6011        const accent = glyph.accent;
6012        let scaledX, scaledY;
6013        let width = glyph.width;
6014
6015        if (vertical) {
6016          const vmetric = glyph.vmetric || defaultVMetrics;
6017          const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
6018          const vy = vmetric[2] * widthAdvanceScale;
6019          width = vmetric ? -vmetric[0] : width;
6020          scaledX = vx / fontSizeScale;
6021          scaledY = (x + vy) / fontSizeScale;
6022        } else {
6023          scaledX = x / fontSizeScale;
6024          scaledY = 0;
6025        }
6026
6027        if (font.remeasure && width > 0) {
6028          const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
6029
6030          if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
6031            const characterScaleX = width / measuredWidth;
6032            restoreNeeded = true;
6033            ctx.save();
6034            ctx.scale(characterScaleX, 1);
6035            scaledX /= characterScaleX;
6036          } else if (width !== measuredWidth) {
6037            scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
6038          }
6039        }
6040
6041        if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
6042          if (simpleFillText && !accent) {
6043            ctx.fillText(character, scaledX, scaledY);
6044          } else {
6045            this.paintChar(character, scaledX, scaledY, patternTransform, resetLineWidthToOne);
6046
6047            if (accent) {
6048              const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
6049              const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
6050              this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform, resetLineWidthToOne);
6051            }
6052          }
6053        }
6054
6055        let charWidth;
6056
6057        if (vertical) {
6058          charWidth = width * widthAdvanceScale - spacing * fontDirection;
6059        } else {
6060          charWidth = width * widthAdvanceScale + spacing * fontDirection;
6061        }
6062
6063        x += charWidth;
6064
6065        if (restoreNeeded) {
6066          ctx.restore();
6067        }
6068      }
6069
6070      if (vertical) {
6071        current.y -= x;
6072      } else {
6073        current.x += x * textHScale;
6074      }
6075
6076      ctx.restore();
6077      return undefined;
6078    }
6079
6080    showType3Text(glyphs) {
6081      const ctx = this.ctx;
6082      const current = this.current;
6083      const font = current.font;
6084      const fontSize = current.fontSize;
6085      const fontDirection = current.fontDirection;
6086      const spacingDir = font.vertical ? 1 : -1;
6087      const charSpacing = current.charSpacing;
6088      const wordSpacing = current.wordSpacing;
6089      const textHScale = current.textHScale * fontDirection;
6090      const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6091      const glyphsLength = glyphs.length;
6092      const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
6093      let i, glyph, width, spacingLength;
6094
6095      if (isTextInvisible || fontSize === 0) {
6096        return;
6097      }
6098
6099      this._cachedGetSinglePixelWidth = null;
6100      ctx.save();
6101      ctx.transform.apply(ctx, current.textMatrix);
6102      ctx.translate(current.x, current.y);
6103      ctx.scale(textHScale, fontDirection);
6104
6105      for (i = 0; i < glyphsLength; ++i) {
6106        glyph = glyphs[i];
6107
6108        if ((0, _util.isNum)(glyph)) {
6109          spacingLength = spacingDir * glyph * fontSize / 1000;
6110          this.ctx.translate(spacingLength, 0);
6111          current.x += spacingLength * textHScale;
6112          continue;
6113        }
6114
6115        const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6116        const operatorList = font.charProcOperatorList[glyph.operatorListId];
6117
6118        if (!operatorList) {
6119          (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
6120          continue;
6121        }
6122
6123        if (this.contentVisible) {
6124          this.processingType3 = glyph;
6125          this.save();
6126          ctx.scale(fontSize, fontSize);
6127          ctx.transform.apply(ctx, fontMatrix);
6128          this.executeOperatorList(operatorList);
6129          this.restore();
6130        }
6131
6132        const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
6133
6134        width = transformed[0] * fontSize + spacing;
6135        ctx.translate(width, 0);
6136        current.x += width * textHScale;
6137      }
6138
6139      ctx.restore();
6140      this.processingType3 = null;
6141    }
6142
6143    setCharWidth(xWidth, yWidth) {}
6144
6145    setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
6146      this.ctx.rect(llx, lly, urx - llx, ury - lly);
6147      this.clip();
6148      this.endPath();
6149    }
6150
6151    getColorN_Pattern(IR) {
6152      let pattern;
6153
6154      if (IR[0] === "TilingPattern") {
6155        const color = IR[1];
6156        const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
6157        const canvasGraphicsFactory = {
6158          createCanvasGraphics: ctx => {
6159            return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
6160          }
6161        };
6162        pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
6163      } else {
6164        pattern = (0, _pattern_helper.getShadingPattern)(IR);
6165      }
6166
6167      return pattern;
6168    }
6169
6170    setStrokeColorN() {
6171      this.current.strokeColor = this.getColorN_Pattern(arguments);
6172    }
6173
6174    setFillColorN() {
6175      this.current.fillColor = this.getColorN_Pattern(arguments);
6176      this.current.patternFill = true;
6177    }
6178
6179    setStrokeRGBColor(r, g, b) {
6180      const color = _util.Util.makeHexColor(r, g, b);
6181
6182      this.ctx.strokeStyle = color;
6183      this.current.strokeColor = color;
6184    }
6185
6186    setFillRGBColor(r, g, b) {
6187      const color = _util.Util.makeHexColor(r, g, b);
6188
6189      this.ctx.fillStyle = color;
6190      this.current.fillColor = color;
6191      this.current.patternFill = false;
6192    }
6193
6194    shadingFill(patternIR) {
6195      if (!this.contentVisible) {
6196        return;
6197      }
6198
6199      const ctx = this.ctx;
6200      this.save();
6201      const pattern = (0, _pattern_helper.getShadingPattern)(patternIR);
6202      ctx.fillStyle = pattern.getPattern(ctx, this, true);
6203      const inv = ctx.mozCurrentTransformInverse;
6204
6205      if (inv) {
6206        const canvas = ctx.canvas;
6207        const width = canvas.width;
6208        const height = canvas.height;
6209
6210        const bl = _util.Util.applyTransform([0, 0], inv);
6211
6212        const br = _util.Util.applyTransform([0, height], inv);
6213
6214        const ul = _util.Util.applyTransform([width, 0], inv);
6215
6216        const ur = _util.Util.applyTransform([width, height], inv);
6217
6218        const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
6219        const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
6220        const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
6221        const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
6222        this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
6223      } else {
6224        this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
6225      }
6226
6227      this.restore();
6228    }
6229
6230    beginInlineImage() {
6231      (0, _util.unreachable)("Should not call beginInlineImage");
6232    }
6233
6234    beginImageData() {
6235      (0, _util.unreachable)("Should not call beginImageData");
6236    }
6237
6238    paintFormXObjectBegin(matrix, bbox) {
6239      if (!this.contentVisible) {
6240        return;
6241      }
6242
6243      this.save();
6244      this.baseTransformStack.push(this.baseTransform);
6245
6246      if (Array.isArray(matrix) && matrix.length === 6) {
6247        this.transform.apply(this, matrix);
6248      }
6249
6250      this.baseTransform = this.ctx.mozCurrentTransform;
6251
6252      if (bbox) {
6253        const width = bbox[2] - bbox[0];
6254        const height = bbox[3] - bbox[1];
6255        this.ctx.rect(bbox[0], bbox[1], width, height);
6256        this.clip();
6257        this.endPath();
6258      }
6259    }
6260
6261    paintFormXObjectEnd() {
6262      if (!this.contentVisible) {
6263        return;
6264      }
6265
6266      this.restore();
6267      this.baseTransform = this.baseTransformStack.pop();
6268    }
6269
6270    beginGroup(group) {
6271      if (!this.contentVisible) {
6272        return;
6273      }
6274
6275      this.save();
6276      const currentCtx = this.ctx;
6277
6278      if (!group.isolated) {
6279        (0, _util.info)("TODO: Support non-isolated groups.");
6280      }
6281
6282      if (group.knockout) {
6283        (0, _util.warn)("Knockout groups not supported.");
6284      }
6285
6286      const currentTransform = currentCtx.mozCurrentTransform;
6287
6288      if (group.matrix) {
6289        currentCtx.transform.apply(currentCtx, group.matrix);
6290      }
6291
6292      if (!group.bbox) {
6293        throw new Error("Bounding box is required.");
6294      }
6295
6296      let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
6297
6298      const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
6299      bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
6300      const offsetX = Math.floor(bounds[0]);
6301      const offsetY = Math.floor(bounds[1]);
6302      let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
6303      let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
6304      let scaleX = 1,
6305          scaleY = 1;
6306
6307      if (drawnWidth > MAX_GROUP_SIZE) {
6308        scaleX = drawnWidth / MAX_GROUP_SIZE;
6309        drawnWidth = MAX_GROUP_SIZE;
6310      }
6311
6312      if (drawnHeight > MAX_GROUP_SIZE) {
6313        scaleY = drawnHeight / MAX_GROUP_SIZE;
6314        drawnHeight = MAX_GROUP_SIZE;
6315      }
6316
6317      let cacheId = "groupAt" + this.groupLevel;
6318
6319      if (group.smask) {
6320        cacheId += "_smask_" + this.smaskCounter++ % 2;
6321      }
6322
6323      const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
6324      const groupCtx = scratchCanvas.context;
6325      groupCtx.scale(1 / scaleX, 1 / scaleY);
6326      groupCtx.translate(-offsetX, -offsetY);
6327      groupCtx.transform.apply(groupCtx, currentTransform);
6328
6329      if (group.smask) {
6330        this.smaskStack.push({
6331          canvas: scratchCanvas.canvas,
6332          context: groupCtx,
6333          offsetX,
6334          offsetY,
6335          scaleX,
6336          scaleY,
6337          subtype: group.smask.subtype,
6338          backdrop: group.smask.backdrop,
6339          transferMap: group.smask.transferMap || null,
6340          startTransformInverse: null
6341        });
6342      } else {
6343        currentCtx.setTransform(1, 0, 0, 1, 0, 0);
6344        currentCtx.translate(offsetX, offsetY);
6345        currentCtx.scale(scaleX, scaleY);
6346      }
6347
6348      copyCtxState(currentCtx, groupCtx);
6349      this.ctx = groupCtx;
6350      this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
6351      this.groupStack.push(currentCtx);
6352      this.groupLevel++;
6353      this.current.activeSMask = null;
6354    }
6355
6356    endGroup(group) {
6357      if (!this.contentVisible) {
6358        return;
6359      }
6360
6361      this.groupLevel--;
6362      const groupCtx = this.ctx;
6363      this.ctx = this.groupStack.pop();
6364
6365      if (this.ctx.imageSmoothingEnabled !== undefined) {
6366        this.ctx.imageSmoothingEnabled = false;
6367      } else {
6368        this.ctx.mozImageSmoothingEnabled = false;
6369      }
6370
6371      if (group.smask) {
6372        this.tempSMask = this.smaskStack.pop();
6373      } else {
6374        this.ctx.drawImage(groupCtx.canvas, 0, 0);
6375      }
6376
6377      this.restore();
6378    }
6379
6380    beginAnnotations() {
6381      this.save();
6382
6383      if (this.baseTransform) {
6384        this.ctx.setTransform.apply(this.ctx, this.baseTransform);
6385      }
6386    }
6387
6388    endAnnotations() {
6389      this.restore();
6390    }
6391
6392    beginAnnotation(rect, transform, matrix) {
6393      this.save();
6394      resetCtxToDefault(this.ctx);
6395      this.current = new CanvasExtraState();
6396
6397      if (Array.isArray(rect) && rect.length === 4) {
6398        const width = rect[2] - rect[0];
6399        const height = rect[3] - rect[1];
6400        this.ctx.rect(rect[0], rect[1], width, height);
6401        this.clip();
6402        this.endPath();
6403      }
6404
6405      this.transform.apply(this, transform);
6406      this.transform.apply(this, matrix);
6407    }
6408
6409    endAnnotation() {
6410      this.restore();
6411    }
6412
6413    paintImageMaskXObject(img) {
6414      if (!this.contentVisible) {
6415        return;
6416      }
6417
6418      const ctx = this.ctx;
6419      const width = img.width,
6420            height = img.height;
6421      const fillColor = this.current.fillColor;
6422      const isPatternFill = this.current.patternFill;
6423      const glyph = this.processingType3;
6424
6425      if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) {
6426        if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) {
6427          glyph.compiled = compileType3Glyph({
6428            data: img.data,
6429            width,
6430            height
6431          });
6432        } else {
6433          glyph.compiled = null;
6434        }
6435      }
6436
6437      if (glyph?.compiled) {
6438        glyph.compiled(ctx);
6439        return;
6440      }
6441
6442      const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
6443      const maskCtx = maskCanvas.context;
6444      maskCtx.save();
6445      putBinaryImageMask(maskCtx, img);
6446      maskCtx.globalCompositeOperation = "source-in";
6447      maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
6448      maskCtx.fillRect(0, 0, width, height);
6449      maskCtx.restore();
6450      this.paintInlineImageXObject(maskCanvas.canvas);
6451    }
6452
6453    paintImageMaskXObjectRepeat(imgData, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
6454      if (!this.contentVisible) {
6455        return;
6456      }
6457
6458      const width = imgData.width;
6459      const height = imgData.height;
6460      const fillColor = this.current.fillColor;
6461      const isPatternFill = this.current.patternFill;
6462      const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
6463      const maskCtx = maskCanvas.context;
6464      maskCtx.save();
6465      putBinaryImageMask(maskCtx, imgData);
6466      maskCtx.globalCompositeOperation = "source-in";
6467      maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
6468      maskCtx.fillRect(0, 0, width, height);
6469      maskCtx.restore();
6470      const ctx = this.ctx;
6471
6472      for (let i = 0, ii = positions.length; i < ii; i += 2) {
6473        ctx.save();
6474        ctx.transform(scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]);
6475        ctx.scale(1, -1);
6476        ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
6477        ctx.restore();
6478      }
6479    }
6480
6481    paintImageMaskXObjectGroup(images) {
6482      if (!this.contentVisible) {
6483        return;
6484      }
6485
6486      const ctx = this.ctx;
6487      const fillColor = this.current.fillColor;
6488      const isPatternFill = this.current.patternFill;
6489
6490      for (let i = 0, ii = images.length; i < ii; i++) {
6491        const image = images[i];
6492        const width = image.width,
6493              height = image.height;
6494        const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height);
6495        const maskCtx = maskCanvas.context;
6496        maskCtx.save();
6497        putBinaryImageMask(maskCtx, image);
6498        maskCtx.globalCompositeOperation = "source-in";
6499        maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor;
6500        maskCtx.fillRect(0, 0, width, height);
6501        maskCtx.restore();
6502        ctx.save();
6503        ctx.transform.apply(ctx, image.transform);
6504        ctx.scale(1, -1);
6505        ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
6506        ctx.restore();
6507      }
6508    }
6509
6510    paintImageXObject(objId) {
6511      if (!this.contentVisible) {
6512        return;
6513      }
6514
6515      const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
6516
6517      if (!imgData) {
6518        (0, _util.warn)("Dependent image isn't ready yet");
6519        return;
6520      }
6521
6522      this.paintInlineImageXObject(imgData);
6523    }
6524
6525    paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
6526      if (!this.contentVisible) {
6527        return;
6528      }
6529
6530      const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
6531
6532      if (!imgData) {
6533        (0, _util.warn)("Dependent image isn't ready yet");
6534        return;
6535      }
6536
6537      const width = imgData.width;
6538      const height = imgData.height;
6539      const map = [];
6540
6541      for (let i = 0, ii = positions.length; i < ii; i += 2) {
6542        map.push({
6543          transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
6544          x: 0,
6545          y: 0,
6546          w: width,
6547          h: height
6548        });
6549      }
6550
6551      this.paintInlineImageXObjectGroup(imgData, map);
6552    }
6553
6554    paintInlineImageXObject(imgData) {
6555      if (!this.contentVisible) {
6556        return;
6557      }
6558
6559      const width = imgData.width;
6560      const height = imgData.height;
6561      const ctx = this.ctx;
6562      this.save();
6563      ctx.scale(1 / width, -1 / height);
6564      const currentTransform = ctx.mozCurrentTransformInverse;
6565      let widthScale = Math.max(Math.hypot(currentTransform[0], currentTransform[1]), 1);
6566      let heightScale = Math.max(Math.hypot(currentTransform[2], currentTransform[3]), 1
6566);
6567      let imgToPaint, tmpCanvas, tmpCtx;
6568
6569      if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
6570        imgToPaint = imgData;
6571      } else {
6572        tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height);
6573        tmpCtx = tmpCanvas.context;
6574        putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
6575        imgToPaint = tmpCanvas.canvas;
6576      }
6577
6578      let paintWidth = width,
6579          paintHeight = height;
6580      let tmpCanvasId = "prescale1";
6581
6582      while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
6583        let newWidth = paintWidth,
6584            newHeight = paintHeight;
6585
6586        if (widthScale > 2 && paintWidth > 1) {
6587          newWidth = Math.ceil(paintWidth / 2);
6588          widthScale /= paintWidth / newWidth;
6589        }
6590
6591        if (heightScale > 2 && paintHeight > 1) {
6592          newHeight = Math.ceil(paintHeight / 2);
6593          heightScale /= paintHeight / newHeight;
6594        }
6595
6596        tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight);
6597        tmpCtx = tmpCanvas.context;
6598        tmpCtx.clearRect(0, 0, newWidth, newHeight);
6599        tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
6600        imgToPaint = tmpCanvas.canvas;
6601        paintWidth = newWidth;
6602        paintHeight = newHeight;
6603        tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
6604      }
6605
6606      ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height);
6607
6608      if (this.imageLayer) {
6609        const position = this.getCanvasPosition(0, -height);
6610        this.imageLayer.appendImage({
6611          imgData,
6612          left: position[0],
6613          top: position[1],
6614          width: width / currentTransform[0],
6615          height: height / currentTransform[3]
6616        });
6617      }
6618
6619      this.restore();
6620    }
6621
6622    paintInlineImageXObjectGroup(imgData, map) {
6623      if (!this.contentVisible) {
6624        return;
6625      }
6626
6627      const ctx = this.ctx;
6628      const w = imgData.width;
6629      const h = imgData.height;
6630      const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h);
6631      const tmpCtx = tmpCanvas.context;
6632      putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
6633
6634      for (let i = 0, ii = map.length; i < ii; i++) {
6635        const entry = map[i];
6636        ctx.save();
6637        ctx.transform.apply(ctx, entry.transform);
6638        ctx.scale(1, -1);
6639        ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
6640
6641        if (this.imageLayer) {
6642          const position = this.getCanvasPosition(entry.x, entry.y);
6643          this.imageLayer.appendImage({
6644            imgData,
6645            left: position[0],
6646            top: position[1],
6647            width: w,
6648            height: h
6649          });
6650        }
6651
6652        ctx.restore();
6653      }
6654    }
6655
6656    paintSolidColorImageMask() {
6657      if (!this.contentVisible) {
6658        return;
6659      }
6660
6661      this.ctx.fillRect(0, 0, 1, 1);
6662    }
6663
6664    markPoint(tag) {}
6665
6666    markPointProps(tag, properties) {}
6667
6668    beginMarkedContent(tag) {
6669      this.markedContentStack.push({
6670        visible: true
6671      });
6672    }
6673
6674    beginMarkedContentProps(tag, properties) {
6675      if (tag === "OC") {
6676        this.markedContentStack.push({
6677          visible: this.optionalContentConfig.isVisible(properties)
6678        });
6679      } else {
6680        this.markedContentStack.push({
6681          visible: true
6682        });
6683      }
6684
6685      this.contentVisible = this.isContentVisible();
6686    }
6687
6688    endMarkedContent() {
6689      this.markedContentStack.pop();
6690      this.contentVisible = this.isContentVisible();
6691    }
6692
6693    beginCompat() {}
6694
6695    endCompat() {}
6696
6697    consumePath() {
6698      const ctx = this.ctx;
6699
6700      if (this.pendingClip) {
6701        if (this.pendingClip === EO_CLIP) {
6702          ctx.clip("evenodd");
6703        } else {
6704          ctx.clip();
6705        }
6706
6707        this.pendingClip = null;
6708      }
6709
6710      ctx.beginPath();
6711    }
6712
6713    getSinglePixelWidth() {
6714      if (this._cachedGetSinglePixelWidth === null) {
6715        const m = this.ctx.mozCurrentTransform;
6716        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
6717        const sqNorm1 = m[0] ** 2 + m[2] ** 2;
6718        const sqNorm2 = m[1] ** 2 + m[3] ** 2;
6719        const pixelHeight = Math.sqrt(Math.max(sqNorm1, sqNorm2)) / absDet;
6720
6721        if (sqNorm1 !== sqNorm2 && this._combinedScaleFactor * pixelHeight > 1) {
6722          this._cachedGetSinglePixelWidth = -(this._combinedScaleFactor * pixelHeight);
6723        } else if (absDet > Number.EPSILON) {
6724          this._cachedGetSinglePixelWidth = pixelHeight;
6725        } else {
6726          this._cachedGetSinglePixelWidth = 1;
6727        }
6728      }
6729
6730      return this._cachedGetSinglePixelWidth;
6731    }
6732
6733    getCanvasPosition(x, y) {
6734      const transform = this.ctx.mozCurrentTransform;
6735      return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
6736    }
6737
6738    isContentVisible() {
6739      for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
6740        if (!this.markedContentStack[i].visible) {
6741          return false;
6742        }
6743      }
6744
6745      return true;
6746    }
6747
6748  }
6749
6750  for (const op in _util.OPS) {
6751    CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
6752  }
6753
6754  return CanvasGraphics;
6755}();
6756
6757exports.CanvasGraphics = CanvasGraphics;
6758
6759/***/ }),
6760/* 11 */
6761/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
6762
6763
6764
6765Object.defineProperty(exports, "__esModule", ({
6766  value: true
6767}));
6768exports.getShadingPattern = getShadingPattern;
6769exports.TilingPattern = void 0;
6770
6771var _util = __w_pdfjs_require__(2);
6772
6773let svgElement;
6774
6775function createMatrix(matrix) {
6776  if (typeof DOMMatrix !== "undefined") {
6777    return new DOMMatrix(matrix);
6778  }
6779
6780  if (!svgElement) {
6781    svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");
6782  }
6783
6784  return svgElement.createSVGMatrix(matrix);
6785}
6786
6787function applyBoundingBox(ctx, bbox) {
6788  if (!bbox || typeof Path2D === "undefined") {
6789    return;
6790  }
6791
6792  const width = bbox[2] - bbox[0];
6793  const height = bbox[3] - bbox[1];
6794  const region = new Path2D();
6795  region.rect(bbox[0], bbox[1], width, height);
6796  ctx.clip(region);
6797}
6798
6799class BaseShadingPattern {
6800  constructor() {
6801    if (this.constructor === BaseShadingPattern) {
6802      (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
6803    }
6804  }
6805
6806  getPattern() {
6807    (0, _util.unreachable)("Abstract method `getPattern` called.");
6808  }
6809
6810}
6811
6812class RadialAxialShadingPattern extends BaseShadingPattern {
6813  constructor(IR) {
6814    super();
6815    this._type = IR[1];
6816    this._bbox = IR[2];
6817    this._colorStops = IR[3];
6818    this._p0 = IR[4];
6819    this._p1 = IR[5];
6820    this._r0 = IR[6];
6821    this._r1 = IR[7];
6822    this._matrix = IR[8];
6823  }
6824
6825  getPattern(ctx, owner, shadingFill) {
6826    const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", ctx.canvas.width, ctx.canvas.height, true);
6827    const tmpCtx = tmpCanvas.context;
6828    tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
6829    tmpCtx.beginPath();
6830    tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
6831
6832    if (!shadingFill) {
6833      tmpCtx.setTransform.apply(tmpCtx, owner.baseTransform);
6834
6835      if (this._matrix) {
6836        tmpCtx.transform.apply(tmpCtx, this._matrix);
6837      }
6838    } else {
6839      tmpCtx.setTransform.apply(tmpCtx, ctx.mozCurrentTransform);
6840    }
6841
6842    applyBoundingBox(tmpCtx, this._bbox);
6843    let grad;
6844
6845    if (this._type === "axial") {
6846      grad = tmpCtx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
6847    } else if (this._type === "radial") {
6848      grad = tmpCtx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
6849    }
6850
6851    for (const colorStop of this._colorStops) {
6852      grad.addColorStop(colorStop[0], colorStop[1]);
6853    }
6854
6855    tmpCtx.fillStyle = grad;
6856    tmpCtx.fill();
6857    const pattern = ctx.createPattern(tmpCanvas.canvas, "repeat");
6858    pattern.setTransform(createMatrix(ctx.mozCurrentTransformInverse));
6859    return pattern;
6860  }
6861
6862}
6863
6864function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
6865  const coords = context.coords,
6866        colors = context.colors;
6867  const bytes = data.data,
6868        rowSize = data.width * 4;
6869  let tmp;
6870
6871  if (coords[p1 + 1] > coords[p2 + 1]) {
6872    tmp = p1;
6873    p1 = p2;
6874    p2 = tmp;
6875    tmp = c1;
6876    c1 = c2;
6877    c2 = tmp;
6878  }
6879
6880  if (coords[p2 + 1] > coords[p3 + 1]) {
6881    tmp = p2;
6882    p2 = p3;
6883    p3 = tmp;
6884    tmp = c2;
6885    c2 = c3;
6886    c3 = tmp;
6887  }
6888
6889  if (coords[p1 + 1] > coords[p2 + 1]) {
6890    tmp = p1;
6891    p1 = p2;
6892    p2 = tmp;
6893    tmp = c1;
6894    c1 = c2;
6895    c2 = tmp;
6896  }
6897
6898  const x1 = (coords[p1] + context.offsetX) * context.scaleX;
6899  const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
6900  const x2 = (coords[p2] + context.offsetX) * context.scaleX;
6901  const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
6902  const x3 = (coords[p3] + context.offsetX) * context.scaleX;
6903  const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
6904
6905  if (y1 >= y3) {
6906    return;
6907  }
6908
6909  const c1r = colors[c1],
6910        c1g = colors[c1 + 1],
6911        c1b = colors[c1 + 2];
6912  const c2r = colors[c2],
6913        c2g = colors[c2 + 1],
6914        c2b = colors[c2 + 2];
6915  const c3r = colors[c3],
6916        c3g = colors[c3 + 1],
6917        c3b = colors[c3 + 2];
6918  const minY = Math.round(y1),
6919        maxY = Math.round(y3);
6920  let xa, car, cag, cab;
6921  let xb, cbr, cbg, cbb;
6922
6923  for (let y = minY; y <= maxY; y++) {
6924    if (y < y2) {
6925      let k;
6926
6927      if (y < y1) {
6928        k = 0;
6929      } else if (y1 === y2) {
6930        k = 1;
6931      } else {
6932        k = (y1 - y) / (y1 - y2);
6933      }
6934
6935      xa = x1 - (x1 - x2) * k;
6936      car = c1r - (c1r - c2r) * k;
6937      cag = c1g - (c1g - c2g) * k;
6938      cab = c1b - (c1b - c2b) * k;
6939    } else {
6940      let k;
6941
6942      if (y > y3) {
6943        k = 1;
6944      } else if (y2 === y3) {
6945        k = 0;
6946      } else {
6947        k = (y2 - y) / (y2 - y3);
6948      }
6949
6950      xa = x2 - (x2 - x3) * k;
6951      car = c2r - (c2r - c3r) * k;
6952      cag = c2g - (c2g - c3g) * k;
6953      cab = c2b - (c2b - c3b) * k;
6954    }
6955
6956    let k;
6957
6958    if (y < y1) {
6959      k = 0;
6960    } else if (y > y3) {
6961      k = 1;
6962    } else {
6963      k = (y1 - y) / (y1 - y3);
6964    }
6965
6966    xb = x1 - (x1 - x3) * k;
6967    cbr = c1r - (c1r - c3r) * k;
6968    cbg = c1g - (c1g - c3g) * k;
6969    cbb = c1b - (c1b - c3b) * k;
6970    const x1_ = Math.round(Math.min(xa, xb));
6971    const x2_ = Math.round(Math.max(xa, xb));
6972    let j = rowSize * y + x1_ * 4;
6973
6974    for (let x = x1_; x <= x2_; x++) {
6975      k = (xa - x) / (xa - xb);
6976
6977      if (k < 0) {
6978        k = 0;
6979      } else if (k > 1) {
6980        k = 1;
6981      }
6982
6983      bytes[j++] = car - (car - cbr) * k | 0;
6984      bytes[j++] = cag - (cag - cbg) * k | 0;
6985      bytes[j++] = cab - (cab - cbb) * k | 0;
6986      bytes[j++] = 255;
6987    }
6988  }
6989}
6990
6991function drawFigure(data, figure, context) {
6992  const ps = figure.coords;
6993  const cs = figure.colors;
6994  let i, ii;
6995
6996  switch (figure.type) {
6997    case "lattice":
6998      const verticesPerRow = figure.verticesPerRow;
6999      const rows = Math.floor(ps.length / verticesPerRow) - 1;
7000      const cols = verticesPerRow - 1;
7001
7002      for (i = 0; i < rows; i++) {
7003        let q = i * verticesPerRow;
7004
7005        for (let j = 0; j < cols; j++, q++) {
7006          drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
7007          drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
7008        }
7009      }
7010
7011      break;
7012
7013    case "triangles":
7014      for (i = 0, ii = ps.length; i < ii; i += 3) {
7015        drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
7016      }
7017
7018      break;
7019
7020    default:
7021      throw new Error("illegal figure");
7022  }
7023}
7024
7025class MeshShadingPattern extends BaseShadingPattern {
7026  constructor(IR) {
7027    super();
7028    this._coords = IR[2];
7029    this._colors = IR[3];
7030    this._figures = IR[4];
7031    this._bounds = IR[5];
7032    this._matrix = IR[6];
7033    this._bbox = IR[7];
7034    this._background = IR[8];
7035  }
7036
7037  _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
7038    const EXPECTED_SCALE = 1.1;
7039    const MAX_PATTERN_SIZE = 3000;
7040    const BORDER_SIZE = 2;
7041    const offsetX = Math.floor(this._bounds[0]);
7042    const offsetY = Math.floor(this._bounds[1]);
7043    const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
7044    const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
7045    const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7046    const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
7047    const scaleX = boundsWidth / width;
7048    const scaleY = boundsHeight / height;
7049    const context = {
7050      coords: this._coords,
7051      colors: this._colors,
7052      offsetX: -offsetX,
7053      offsetY: -offsetY,
7054      scaleX: 1 / scaleX,
7055      scaleY: 1 / scaleY
7056    };
7057    const paddedWidth = width + BORDER_SIZE * 2;
7058    const paddedHeight = height + BORDER_SIZE * 2;
7059    const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
7060    const tmpCtx = tmpCanvas.context;
7061    const data = tmpCtx.createImageData(width, height);
7062
7063    if (backgroundColor) {
7064      const bytes = data.data;
7065
7066      for (let i = 0, ii = bytes.length; i < ii; i += 4) {
7067        bytes[i] = backgroundColor[0];
7068        bytes[i + 1] = backgroundColor[1];
7069        bytes[i + 2] = backgroundColor[2];
7070        bytes[i + 3] = 255;
7071      }
7072    }
7073
7074    for (const figure of this._figures) {
7075      drawFigure(data, figure, context);
7076    }
7077
7078    tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
7079    const canvas = tmpCanvas.canvas;
7080    return {
7081      canvas,
7082      offsetX: offsetX - BORDER_SIZE * scaleX,
7083      offsetY: offsetY - BORDER_SIZE * scaleY,
7084      scaleX,
7085      scaleY
7086    };
7087  }
7088
7089  getPattern(ctx, owner, shadingFill) {
7090    applyBoundingBox(ctx, this._bbox);
7091    let scale;
7092
7093    if (shadingFill) {
7094      scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
7095    } else {
7096      scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
7097
7098      if (this._matrix) {
7099        const matrixScale = _util.Util.singularValueDecompose2dScale(this._matrix);
7100
7101        scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
7102      }
7103    }
7104
7105    const temporaryPatternCanvas = this._createMeshCanvas(scale, shadingFill ? null : this._background, owner.cachedCanvases);
7106
7107    if (!shadingFill) {
7108      ctx.setTransform.apply(ctx, owner.baseTransform);
7109
7110      if (this._matrix) {
7111        ctx.transform.apply(ctx, this._matrix);
7112      }
7113    }
7114
7115    ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
7116    ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
7117    return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
7118  }
7119
7120}
7121
7122class DummyShadingPattern extends BaseShadingPattern {
7123  getPattern() {
7124    return "hotpink";
7125  }
7126
7127}
7128
7129function getShadingPattern(IR) {
7130  switch (IR[0]) {
7131    case "RadialAxial":
7132      return new RadialAxialShadingPattern(IR);
7133
7134    case "Mesh":
7135      return new MeshShadingPattern(IR);
7136
7137    case "Dummy":
7138      return new DummyShadingPattern();
7139  }
7140
7141  throw new Error(`Unknown IR type: ${IR[0]}`);
7142}
7143
7144const PaintType = {
7145  COLORED: 1,
7146  UNCOLORED: 2
7147};
7148
7149class TilingPattern {
7150  static get MAX_PATTERN_SIZE() {
7151    return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
7152  }
7153
7154  constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
7155    this.operatorList = IR[2];
7156    this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
7157    this.bbox = IR[4];
7158    this.xstep = IR[5];
7159    this.ystep = IR[6];
7160    this.paintType = IR[7];
7161    this.tilingType = IR[8];
7162    this.color = color;
7163    this.ctx = ctx;
7164    this.canvasGraphicsFactory = canvasGraphicsFactory;
7165    this.baseTransform = baseTransform;
7166  }
7167
7168  createPatternCanvas(owner) {
7169    const operatorList = this.operatorList;
7170    const bbox = this.bbox;
7171    const xstep = this.xstep;
7172    const ystep = this.ystep;
7173    const paintType = this.paintType;
7174    const tilingType = this.tilingType;
7175    const color = this.color;
7176    const canvasGraphicsFactory = this.canvasGraphicsFactory;
7177    (0, _util.info)("TilingType: " + tilingType);
7178    const x0 = bbox[0],
7179          y0 = bbox[1],
7180          x1 = bbox[2],
7181          y1 = bbox[3];
7182
7183    const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
7184
7185    const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
7186
7187    const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
7188    const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
7189    const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
7190    const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
7191    const tmpCtx = tmpCanvas.context;
7192    const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
7193    graphics.groupLevel = owner.groupLevel;
7194    this.setFillAndStrokeStyleToContext(graphics, paintType, color);
7195    graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
7196    this.clipBbox(graphics, bbox, x0, y0, x1, y1);
7197    graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
7198    graphics.executeOperatorList(operatorList);
7199    graphics.endDrawing();
7200    return {
7201      canvas: tmpCanvas.canvas,
7202      scaleX: dimx.scale,
7203      scaleY: dimy.scale
7204    };
7205  }
7206
7207  getSizeAndScale(step, realOutputSize, scale) {
7208    step = Math.abs(step);
7209    const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
7210    let size = Math.ceil(step * scale);
7211
7212    if (size >= maxSize) {
7213      size = maxSize;
7214    } else {
7215      scale = size / step;
7216    }
7217
7218    return {
7219      scale,
7220      size
7221    };
7222  }
7223
7224  clipBbox(graphics, bbox, x0, y0, x1, y1) {
7225    if (Array.isArray(bbox) && bbox.length === 4) {
7226      const bboxWidth = x1 - x0;
7227      const bboxHeight = y1 - y0;
7228      graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
7229      graphics.clip();
7230      graphics.endPath();
7231    }
7232  }
7233
7234  setFillAndStrokeStyleToContext(graphics, paintType, color) {
7235    const context = graphics.ctx,
7236          current = graphics.current;
7237
7238    switch (paintType) {
7239      case PaintType.COLORED:
7240        const ctx = this.ctx;
7241        context.fillStyle = ctx.fillStyle;
7242        context.strokeStyle = ctx.strokeStyle;
7243        current.fillColor = ctx.fillStyle;
7244        current.strokeColor = ctx.strokeStyle;
7245        break;
7246
7247      case PaintType.UNCOLORED:
7248        const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
7249
7250        context.fillStyle = cssColor;
7251        context.strokeStyle = cssColor;
7252        current.fillColor = cssColor;
7253        current.strokeColor = cssColor;
7254        break;
7255
7256      default:
7257        throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
7258    }
7259  }
7260
7261  getPattern(ctx, owner, shadingFill) {
7262    ctx = this.ctx;
7263    let matrix = ctx.mozCurrentTransformInverse;
7264
7265    if (!shadingFill) {
7266      matrix = _util.Util.transform(matrix, owner.baseTransform);
7267
7268      if (this.matrix) {
7269        matrix = _util.Util.transform(matrix, this.matrix);
7270      }
7271    }
7272
7273    const temporaryPatternCanvas = this.createPatternCanvas(owner);
7274    let domMatrix = createMatrix(matrix);
7275    domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
7276    const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
7277    pattern.setTransform(domMatrix);
7278    return pattern;
7279  }
7280
7281}
7282
7283exports.TilingPattern = TilingPattern;
7284
7285/***/ }),
7286/* 12 */
7287/***/ ((__unused_webpack_module, exports) => {
7288
7289
7290
7291Object.defineProperty(exports, "__esModule", ({
7292  value: true
7293}));
7294exports.GlobalWorkerOptions = void 0;
7295const GlobalWorkerOptions = Object.create(null);
7296exports.GlobalWorkerOptions = GlobalWorkerOptions;
7297GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
7298GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
7299
7300/***/ }),
7301/* 13 */
7302/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7303
7304
7305
7306Object.defineProperty(exports, "__esModule", ({
7307  value: true
7308}));
7309exports.MessageHandler = void 0;
7310
7311var _util = __w_pdfjs_require__(2);
7312
7313const CallbackKind = {
7314  UNKNOWN: 0,
7315  DATA: 1,
7316  ERROR: 2
7317};
7318const StreamKind = {
7319  UNKNOWN: 0,
7320  CANCEL: 1,
7321  CANCEL_COMPLETE: 2,
7322  CLOSE: 3,
7323  ENQUEUE: 4,
7324  ERROR: 5,
7325  PULL: 6,
7326  PULL_COMPLETE: 7,
7327  START_COMPLETE: 8
7328};
7329
7330function wrapReason(reason) {
7331  if (typeof reason !== "object" || reason === null) {
7332    return reason;
7333  }
7334
7335  switch (reason.name) {
7336    case "AbortException":
7337      return new _util.AbortException(reason.message);
7338
7339    case "MissingPDFException":
7340      return new _util.MissingPDFException(reason.message);
7341
7342    case "UnexpectedResponseException":
7343      return new _util.UnexpectedResponseException(reason.message, reason.status);
7344
7345    case "UnknownErrorException":
7346      return new _util.UnknownErrorException(reason.message, reason.details);
7347
7348    default:
7349      return new _util.UnknownErrorException(reason.message, reason.toString());
7350  }
7351}
7352
7353class MessageHandler {
7354  constructor(sourceName, targetName, comObj) {
7355    this.sourceName = sourceName;
7356    this.targetName = targetName;
7357    this.comObj = comObj;
7358    this.callbackId = 1;
7359    this.streamId = 1;
7360    this.postMessageTransfers = true;
7361    this.streamSinks = Object.create(null);
7362    this.streamControllers = Object.create(null);
7363    this.callbackCapabilities = Object.create(null);
7364    this.actionHandler = Object.create(null);
7365
7366    this._onComObjOnMessage = event => {
7367      const data = event.data;
7368
7369      if (data.targetName !== this.sourceName) {
7370        return;
7371      }
7372
7373      if (data.stream) {
7374        this._processStreamMessage(data);
7375
7376        return;
7377      }
7378
7379      if (data.callback) {
7380        const callbackId = data.callbackId;
7381        const capability = this.callbackCapabilities[callbackId];
7382
7383        if (!capability) {
7384          throw new Error(`Cannot resolve callback ${callbackId}`);
7385        }
7386
7387        delete this.callbackCapabilities[callbackId];
7388
7389        if (data.callback === CallbackKind.DATA) {
7390          capability.resolve(data.data);
7391        } else if (data.callback === CallbackKind.ERROR) {
7392          capability.reject(wrapReason(data.reason));
7393        } else {
7394          throw new Error("Unexpected callback case");
7395        }
7396
7397        return;
7398      }
7399
7400      const action = this.actionHandler[data.action];
7401
7402      if (!action) {
7403        throw new Error(`Unknown action from worker: ${data.action}`);
7404      }
7405
7406      if (data.callbackId) {
7407        const cbSourceName = this.sourceName;
7408        const cbTargetName = data.sourceName;
7409        new Promise(function (resolve) {
7410          resolve(action(data.data));
7411        }).then(function (result) {
7412          comObj.postMessage({
7413            sourceName: cbSourceName,
7414            targetName: cbTargetName,
7415            callback: CallbackKind.DATA,
7416            callbackId: data.callbackId,
7417            data: result
7418          });
7419        }, function (reason) {
7420          comObj.postMessage({
7421            sourceName: cbSourceName,
7422            targetName: cbTargetName,
7423            callback: CallbackKind.ERROR,
7424            callbackId: data.callbackId,
7425            reason: wrapReason(reason)
7426          });
7427        });
7428        return;
7429      }
7430
7431      if (data.streamId) {
7432        this._createStreamSink(data);
7433
7434        return;
7435      }
7436
7437      action(data.data);
7438    };
7439
7440    comObj.addEventListener("message", this._onComObjOnMessage);
7441  }
7442
7443  on(actionName, handler) {
7444    const ah = this.actionHandler;
7445
7446    if (ah[actionName]) {
7447      throw new Error(`There is already an actionName called "${actionName}"`);
7448    }
7449
7450    ah[actionName] = handler;
7451  }
7452
7453  send(actionName, data, transfers) {
7454    this._postMessage({
7455      sourceName: this.sourceName,
7456      targetName: this.targetName,
7457      action: actionName,
7458      data
7459    }, transfers);
7460  }
7461
7462  sendWithPromise(actionName, data, transfers) {
7463    const callbackId = this.callbackId++;
7464    const capability = (0, _util.createPromiseCapability)();
7465    this.callbackCapabilities[callbackId] = capability;
7466
7467    try {
7468      this._postMessage({
7469        sourceName: this.sourceName,
7470        targetName: this.targetName,
7471        action: actionName,
7472        callbackId,
7473        data
7474      }, transfers);
7475    } catch (ex) {
7476      capability.reject(ex);
7477    }
7478
7479    return capability.promise;
7480  }
7481
7482  sendWithStream(actionName, data, queueingStrategy, transfers) {
7483    const streamId = this.streamId++;
7484    const sourceName = this.sourceName;
7485    const targetName = this.targetName;
7486    const comObj = this.comObj;
7487    return new ReadableStream({
7488      start: controller => {
7489        const startCapability = (0, _util.createPromiseCapability)();
7490        this.streamControllers[streamId] = {
7491          controller,
7492          startCall: startCapability,
7493          pullCall: null,
7494          cancelCall: null,
7495          isClosed: false
7496        };
7497
7498        this._postMessage({
7499          sourceName,
7500          targetName,
7501          action: actionName,
7502          streamId,
7503          data,
7504          desiredSize: controller.desiredSize
7505        }, transfers);
7506
7507        return startCapability.promise;
7508      },
7509      pull: controller => {
7510        const pullCapability = (0, _util.createPromiseCapability)();
7511        this.streamControllers[streamId].pullCall = pullCapability;
7512        comObj.postMessage({
7513          sourceName,
7514          targetName,
7515          stream: StreamKind.PULL,
7516          streamId,
7517          desiredSize: controller.desiredSize
7518        });
7519        return pullCapability.promise;
7520      },
7521      cancel: reason => {
7522        (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
7523        const cancelCapability = (0, _util.createPromiseCapability)();
7524        this.streamControllers[streamId].cancelCall = cancelCapability;
7525        this.streamControllers[streamId].isClosed = true;
7526        comObj.postMessage({
7527          sourceName,
7528          targetName,
7529          stream: StreamKind.CANCEL,
7530          streamId,
7531          reason: wrapReason(reason)
7532        });
7533        return cancelCapability.promise;
7534      }
7535    }, queueingStrategy);
7536  }
7537
7538  _createStreamSink(data) {
7539    const self = this;
7540    const action = this.actionHandler[data.action];
7541    const streamId = data.streamId;
7542    const sourceName = this.sourceName;
7543    const targetName = data.sourceName;
7544    const comObj = this.comObj;
7545    const streamSink = {
7546      enqueue(chunk, size = 1, transfers) {
7547        if (this.isCancelled) {
7548          return;
7549        }
7550
7551        const lastDesiredSize = this.desiredSize;
7552        this.desiredSize -= size;
7553
7554        if (lastDesiredSize > 0 && this.desiredSize <= 0) {
7555          this.sinkCapability = (0, _util.createPromiseCapability)();
7556          this.ready = this.sinkCapability.promise;
7557        }
7558
7559        self._postMessage({
7560          sourceName,
7561          targetName,
7562          stream: StreamKind.ENQUEUE,
7563          streamId,
7564          chunk
7565        }, transfers);
7566      },
7567
7568      close() {
7569        if (this.isCancelled) {
7570          return;
7571        }
7572
7573        this.isCancelled = true;
7574        comObj.postMessage({
7575          sourceName,
7576          targetName,
7577          stream: StreamKind.CLOSE,
7578          streamId
7579        });
7580        delete self.streamSinks[streamId];
7581      },
7582
7583      error(reason) {
7584        (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
7585
7586        if (this.isCancelled) {
7587          return;
7588        }
7589
7590        this.isCancelled = true;
7591        comObj.postMessage({
7592          sourceName,
7593          targetName,
7594          stream: StreamKind.ERROR,
7595          streamId,
7596          reason: wrapReason(reason)
7597        });
7598      },
7599
7600      sinkCapability: (0, _util.createPromiseCapability)(),
7601      onPull: null,
7602      onCancel: null,
7603      isCancelled: false,
7604      desiredSize: data.desiredSize,
7605      ready: null
7606    };
7607    streamSink.sinkCapability.resolve();
7608    streamSink.ready = streamSink.sinkCapability.promise;
7609    this.streamSinks[streamId] = streamSink;
7610    new Promise(function (resolve) {
7611      resolve(action(data.data, streamSink));
7612    }).then(function () {
7613      comObj.postMessage({
7614        sourceName,
7615        targetName,
7616        stream: StreamKind.START_COMPLETE,
7617        streamId,
7618        success: true
7619      });
7620    }, function (reason) {
7621      comObj.postMessage({
7622        sourceName,
7623        targetName,
7624        stream: StreamKind.START_COMPLETE,
7625        streamId,
7626        reason: wrapReason(reason)
7627      });
7628    });
7629  }
7630
7631  _processStreamMessage(data) {
7632    const streamId = data.streamId;
7633    const sourceName = this.sourceName;
7634    const targetName = data.sourceName;
7635    const comObj = this.comObj;
7636
7637    switch (data.stream) {
7638      case StreamKind.START_COMPLETE:
7639        if (data.success) {
7640          this.streamControllers[streamId].startCall.resolve();
7641        } else {
7642          this.streamControllers[streamId].startCall.reject(wrapReason(data.reason));
7643        }
7644
7645        break;
7646
7647      case StreamKind.PULL_COMPLETE:
7648        if (data.success) {
7649          this.streamControllers[streamId].pullCall.resolve();
7650        } else {
7651          this.streamControllers[streamId].pullCall.reject(wrapReason(data.reason));
7652        }
7653
7654        break;
7655
7656      case StreamKind.PULL:
7657        if (!this.streamSinks[streamId]) {
7658          comObj.postMessage({
7659            sourceName,
7660            targetName,
7661            stream: StreamKind.PULL_COMPLETE,
7662            streamId,
7663            success: true
7664          });
7665          break;
7666        }
7667
7668        if (this.streamSinks[streamId].desiredSize <= 0 && data.desiredSize > 0) {
7669          this.streamSinks[streamId].sinkCapability.resolve();
7670        }
7671
7672        this.streamSinks[streamId].desiredSize = data.desiredSize;
7673        const {
7674          onPull
7675        } = this.streamSinks[data.streamId];
7676        new Promise(function (resolve) {
7677          resolve(onPull && onPull());
7678        }).then(function () {
7679          comObj.postMessage({
7680            sourceName,
7681            targetName,
7682            stream: StreamKind.PULL_COMPLETE,
7683            streamId,
7684            success: true
7685          });
7686        }, function (reason) {
7687          comObj.postMessage({
7688            sourceName,
7689            targetName,
7690            stream: StreamKind.PULL_COMPLETE,
7691            streamId,
7692            reason: wrapReason(reason)
7693          });
7694        });
7695        break;
7696
7697      case StreamKind.ENQUEUE:
7698        (0, _util.assert)(this.streamControllers[streamId], "enqueue should have stream controller");
7699
7700        if (this.streamControllers[streamId].isClosed) {
7701          break;
7702        }
7703
7704        this.streamControllers[streamId].controller.enqueue(data.chunk);
7705        break;
7706
7707      case StreamKind.CLOSE:
7708        (0, _util.assert)(this.streamControllers[streamId], "close should have stream controller");
7709
7710        if (this.streamControllers[streamId].isClosed) {
7711          break;
7712        }
7713
7714        this.streamControllers[streamId].isClosed = true;
7715        this.streamControllers[streamId].controller.close();
7716
7717        this._deleteStreamController(streamId);
7718
7719        break;
7720
7721      case StreamKind.ERROR:
7722        (0, _util.assert)(this.streamControllers[streamId], "error should have stream controller");
7723        this.streamControllers[streamId].controller.error(wrapReason(data.reason));
7724
7725        this._deleteStreamController(streamId);
7726
7727        break;
7728
7729      case StreamKind.CANCEL_COMPLETE:
7730        if (data.success) {
7731          this.streamControllers[streamId].cancelCall.resolve();
7732        } else {
7733          this.streamControllers[streamId].cancelCall.reject(wrapReason(data.reason));
7734        }
7735
7736        this._deleteStreamController(streamId);
7737
7738        break;
7739
7740      case StreamKind.CANCEL:
7741        if (!this.streamSinks[streamId]) {
7742          break;
7743        }
7744
7745        const {
7746          onCancel
7747        } = this.streamSinks[data.streamId];
7748        new Promise(function (resolve) {
7749          resolve(onCancel && onCancel(wrapReason(data.reason)));
7750        }).then(function () {
7751          comObj.postMessage({
7752            sourceName,
7753            targetName,
7754            stream: StreamKind.CANCEL_COMPLETE,
7755            streamId,
7756            success: true
7757          });
7758        }, function (reason) {
7759          comObj.postMessage({
7760            sourceName,
7761            targetName,
7762            stream: StreamKind.CANCEL_COMPLETE,
7763            streamId,
7764            reason: wrapReason(reason)
7765          });
7766        });
7767        this.streamSinks[streamId].sinkCapability.reject(wrapReason(data.reason));
7768        this.streamSinks[streamId].isCancelled = true;
7769        delete this.streamSinks[streamId];
7770        break;
7771
7772      default:
7773        throw new Error("Unexpected stream case");
7774    }
7775  }
7776
7777  async _deleteStreamController(streamId) {
7778    await Promise.allSettled([this.streamControllers[streamId].startCall, this.streamControllers[streamId].pullCall, this.streamControllers[streamId].cancelCall].map(function (capability) {
7779      return capability && capability.promise;
7780    }));
7781    delete this.streamControllers[streamId];
7782  }
7783
7784  _postMessage(message, transfers) {
7785    if (transfers && this.postMessageTransfers) {
7786      this.comObj.postMessage(message, transfers);
7787    } else {
7788      this.comObj.postMessage(message);
7789    }
7790  }
7791
7792  destroy() {
7793    this.comObj.removeEventListener("message", this._onComObjOnMessage);
7794  }
7795
7796}
7797
7798exports.MessageHandler = MessageHandler;
7799
7800/***/ }),
7801/* 14 */
7802/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7803
7804
7805
7806Object.defineProperty(exports, "__esModule", ({
7807  value: true
7808}));
7809exports.Metadata = void 0;
7810
7811var _util = __w_pdfjs_require__(2);
7812
7813class Metadata {
7814  constructor({
7815    parsedData,
7816    rawData
7817  }) {
7818    this._metadataMap = parsedData;
7819    this._data = rawData;
7820  }
7821
7822  getRaw() {
7823    return this._data;
7824  }
7825
7826  get(name) {
7827    return this._metadataMap.get(name) ?? null;
7828  }
7829
7830  getAll() {
7831    return (0, _util.objectFromMap)(this._metadataMap);
7832  }
7833
7834  has(name) {
7835    return this._metadataMap.has(name);
7836  }
7837
7838}
7839
7840exports.Metadata = Metadata;
7841
7842/***/ }),
7843/* 15 */
7844/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7845
7846
7847
7848Object.defineProperty(exports, "__esModule", ({
7849  value: true
7850}));
7851exports.OptionalContentConfig = void 0;
7852
7853var _util = __w_pdfjs_require__(2);
7854
7855class OptionalContentGroup {
7856  constructor(name, intent) {
7857    this.visible = true;
7858    this.name = name;
7859    this.intent = intent;
7860  }
7861
7862}
7863
7864class OptionalContentConfig {
7865  constructor(data) {
7866    this.name = null;
7867    this.creator = null;
7868    this._order = null;
7869    this._groups = new Map();
7870
7871    if (data === null) {
7872      return;
7873    }
7874
7875    this.name = data.name;
7876    this.creator = data.creator;
7877    this._order = data.order;
7878
7879    for (const group of data.groups) {
7880      this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
7881    }
7882
7883    if (data.baseState === "OFF") {
7884      for (const group of this._groups) {
7885        group.visible = false;
7886      }
7887    }
7888
7889    for (const on of data.on) {
7890      this._groups.get(on).visible = true;
7891    }
7892
7893    for (const off of data.off) {
7894      this._groups.get(off).visible = false;
7895    }
7896  }
7897
7898  _evaluateVisibilityExpression(array) {
7899    const length = array.length;
7900
7901    if (length < 2) {
7902      return true;
7903    }
7904
7905    const operator = array[0];
7906
7907    for (let i = 1; i < length; i++) {
7908      const element = array[i];
7909      let state;
7910
7911      if (Array.isArray(element)) {
7912        state = this._evaluateVisibilityExpression(element);
7913      } else if (this._groups.has(element)) {
7914        state = this._groups.get(element).visible;
7915      } else {
7916        (0, _util.warn)(`Optional content group not found: ${element}`);
7917        return true;
7918      }
7919
7920      switch (operator) {
7921        case "And":
7922          if (!state) {
7923            return false;
7924          }
7925
7926          break;
7927
7928        case "Or":
7929          if (state) {
7930            return true;
7931          }
7932
7933          break;
7934
7935        case "Not":
7936          return !state;
7937
7938        default:
7939          return true;
7940      }
7941    }
7942
7943    return operator === "And";
7944  }
7945
7946  isVisible(group) {
7947    if (group.type === "OCG") {
7948      if (!this._groups.has(group.id)) {
7949        (0, _util.warn)(`Optional content group not found: ${group.id}`);
7950        return true;
7951      }
7952
7953      return this._groups.get(group.id).visible;
7954    } else if (group.type === "OCMD") {
7955      if (group.expression) {
7956        return this._evaluateVisibilityExpression(group.expression);
7957      }
7958
7959      if (!group.policy || group.policy === "AnyOn") {
7960        for (const id of group.ids) {
7961          if (!this._groups.has(id)) {
7962            (0, _util.warn)(`Optional content group not found: ${id}`);
7963            return true;
7964          }
7965
7966          if (this._groups.get(id).visible) {
7967            return true;
7968          }
7969        }
7970
7971        return false;
7972      } else if (group.policy === "AllOn") {
7973        for (const id of group.ids) {
7974          if (!this._groups.has(id)) {
7975            (0, _util.warn)(`Optional content group not found: ${id}`);
7976            return true;
7977          }
7978
7979          if (!this._groups.get(id).visible) {
7980            return false;
7981          }
7982        }
7983
7984        return true;
7985      } else if (group.policy === "AnyOff") {
7986        for (const id of group.ids) {
7987          if (!this._groups.has(id)) {
7988            (0, _util.warn)(`Optional content group not found: ${id}`);
7989            return true;
7990          }
7991
7992          if (!this._groups.get(id).visible) {
7993            return true;
7994          }
7995        }
7996
7997        return false;
7998      } else if (group.policy === "AllOff") {
7999        for (const id of group.ids) {
8000          if (!this._groups.has(id)) {
8001            (0, _util.warn)(`Optional content group not found: ${id}`);
8002            return true;
8003          }
8004
8005          if (this._groups.get(id).visible) {
8006            return false;
8007          }
8008        }
8009
8010        return true;
8011      }
8012
8013      (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
8014      return true;
8015    }
8016
8017    (0, _util.warn)(`Unknown group type ${group.type}.`);
8018    return true;
8019  }
8020
8021  setVisibility(id, visible = true) {
8022    if (!this._groups.has(id)) {
8023      (0, _util.warn)(`Optional content group not found: ${id}`);
8024      return;
8025    }
8026
8027    this._groups.get(id).visible = !!visible;
8028  }
8029
8030  getOrder() {
8031    if (!this._groups.size) {
8032      return null;
8033    }
8034
8035    if (this._order) {
8036      return this._order.slice();
8037    }
8038
8039    return Array.from(this._groups.keys());
8040  }
8041
8042  getGroups() {
8043    return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null;
8044  }
8045
8046  getGroup(id) {
8047    return this._groups.get(id) || null;
8048  }
8049
8050}
8051
8052exports.OptionalContentConfig = OptionalContentConfig;
8053
8054/***/ }),
8055/* 16 */
8056/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8057
8058
8059
8060Object.defineProperty(exports, "__esModule", ({
8061  value: true
8062}));
8063exports.PDFDataTransportStream = void 0;
8064
8065var _util = __w_pdfjs_require__(2);
8066
8067var _display_utils = __w_pdfjs_require__(1);
8068
8069class PDFDataTransportStream {
8070  constructor(params, pdfDataRangeTransport) {
8071    (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
8072    this._queuedChunks = [];
8073    this._progressiveDone = params.progressiveDone || false;
8074    this._contentDispositionFilename = params.contentDispositionFilename || null;
8075    const initialData = params.initialData;
8076
8077    if (initialData?.length > 0) {
8078      const buffer = new Uint8Array(initialData).buffer;
8079
8080      this._queuedChunks.push(buffer);
8081    }
8082
8083    this._pdfDataRangeTransport = pdfDataRangeTransport;
8084    this._isStreamingSupported = !params.disableStream;
8085    this._isRangeSupported = !params.disableRange;
8086    this._contentLength = params.length;
8087    this._fullRequestReader = null;
8088    this._rangeReaders = [];
8089
8090    this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
8091      this._onReceiveData({
8092        begin,
8093        chunk
8094      });
8095    });
8096
8097    this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
8098      this._onProgress({
8099        loaded,
8100        total
8101      });
8102    });
8103
8104    this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
8105      this._onReceiveData({
8106        chunk
8107      });
8108    });
8109
8110    this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
8111      this._onProgressiveDone();
8112    });
8113
8114    this._pdfDataRangeTransport.transportReady();
8115  }
8116
8117  _onReceiveData(args) {
8118    const buffer = new Uint8Array(args.chunk).buffer;
8119
8120    if (args.begin === undefined) {
8121      if (this._fullRequestReader) {
8122        this._fullRequestReader._enqueue(buffer);
8123      } else {
8124        this._queuedChunks.push(buffer);
8125      }
8126    } else {
8127      const found = this._rangeReaders.some(function (rangeReader) {
8128        if (rangeReader._begin !== args.begin) {
8129          return false;
8130        }
8131
8132        rangeReader._enqueue(buffer);
8133
8134        return true;
8135      });
8136
8137      (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
8138    }
8139  }
8140
8141  get _progressiveDataLength() {
8142    return this._fullRequestReader?._loaded ?? 0;
8143  }
8144
8145  _onProgress(evt) {
8146    if (evt.total === undefined) {
8147      const firstReader = this._rangeReaders[0];
8148
8149      if (firstReader?.onProgress) {
8150        firstReader.onProgress({
8151          loaded: evt.loaded
8152        });
8153      }
8154    } else {
8155      const fullReader = this._fullRequestReader;
8156
8157      if (fullReader?.onProgress) {
8158        fullReader.onProgress({
8159          loaded: evt.loaded,
8160          total: evt.total
8161        });
8162      }
8163    }
8164  }
8165
8166  _onProgressiveDone() {
8167    if (this._fullRequestReader) {
8168      this._fullRequestReader.progressiveDone();
8169    }
8170
8171    this._progressiveDone = true;
8172  }
8173
8174  _removeRangeReader(reader) {
8175    const i = this._rangeReaders.indexOf(reader);
8176
8177    if (i >= 0) {
8178      this._rangeReaders.splice(i, 1);
8179    }
8180  }
8181
8182  getFullReader() {
8183    (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
8184    const queuedChunks = this._queuedChunks;
8185    this._queuedChunks = null;
8186    return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
8187  }
8188
8189  getRangeReader(begin, end) {
8190    if (end <= this._progressiveDataLength) {
8191      return null;
8192    }
8193
8194    const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
8195
8196    this._pdfDataRangeTransport.requestDataRange(begin, end);
8197
8198    this._rangeReaders.push(reader);
8199
8200    return reader;
8201  }
8202
8203  cancelAllRequests(reason) {
8204    if (this._fullRequestReader) {
8205      this._fullRequestReader.cancel(reason);
8206    }
8207
8208    for (const reader of this._rangeReaders.slice(0)) {
8209      reader.cancel(reason);
8210    }
8211
8212    this._pdfDataRangeTransport.abort();
8213  }
8214
8215}
8216
8217exports.PDFDataTransportStream = PDFDataTransportStream;
8218
8219class PDFDataTransportStreamReader {
8220  constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
8221    this._stream = stream;
8222    this._done = progressiveDone || false;
8223    this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
8224    this._queuedChunks = queuedChunks || [];
8225    this._loaded = 0;
8226
8227    for (const chunk of this._queuedChunks) {
8228      this._loaded += chunk.byteLength;
8229    }
8230
8231    this._requests = [];
8232    this._headersReady = Promise.resolve();
8233    stream._fullRequestReader = this;
8234    this.onProgress = null;
8235  }
8236
8237  _enqueue(chunk) {
8238    if (this._done) {
8239      return;
8240    }
8241
8242    if (this._requests.length > 0) {
8243      const requestCapability = this._requests.shift();
8244
8245      requestCapability.resolve({
8246        value: chunk,
8247        done: false
8248      });
8249    } else {
8250      this._queuedChunks.push(chunk);
8251    }
8252
8253    this._loaded += chunk.byteLength;
8254  }
8255
8256  get headersReady() {
8257    return this._headersReady;
8258  }
8259
8260  get filename() {
8261    return this._filename;
8262  }
8263
8264  get isRangeSupported() {
8265    return this._stream._isRangeSupported;
8266  }
8267
8268  get isStreamingSupported() {
8269    return this._stream._isStreamingSupported;
8270  }
8271
8272  get contentLength() {
8273    return this._stream._contentLength;
8274  }
8275
8276  async read() {
8277    if (this._queuedChunks.length > 0) {
8278      const chunk = this._queuedChunks.shift();
8279
8280      return {
8281        value: chunk,
8282        done: false
8283      };
8284    }
8285
8286    if (this._done) {
8287      return {
8288        value: undefined,
8289        done: true
8290      };
8291    }
8292
8293    const requestCapability = (0, _util.createPromiseCapability)();
8294
8295    this._requests.push(requestCapability);
8296
8297    return requestCapability.promise;
8298  }
8299
8300  cancel(reason) {
8301    this._done = true;
8302
8303    for (const requestCapability of this._requests) {
8304      requestCapability.resolve({
8305        value: undefined,
8306        done: true
8307      });
8308    }
8309
8310    this._requests.length = 0;
8311  }
8312
8313  progressiveDone() {
8314    if (this._done) {
8315      return;
8316    }
8317
8318    this._done = true;
8319  }
8320
8321}
8322
8323class PDFDataTransportStreamRangeReader {
8324  constructor(stream, begin, end) {
8325    this._stream = stream;
8326    this._begin = begin;
8327    this._end = end;
8328    this._queuedChunk = null;
8329    this._requests = [];
8330    this._done = false;
8331    this.onProgress = null;
8332  }
8333
8334  _enqueue(chunk) {
8335    if (this._done) {
8336      return;
8337    }
8338
8339    if (this._requests.length === 0) {
8340      this._queuedChunk = chunk;
8341    } else {
8342      const requestsCapability = this._requests.shift();
8343
8344      requestsCapability.resolve({
8345        value: chunk,
8346        done: false
8347      });
8348
8349      for (const requestCapability of this._requests) {
8350        requestCapability.resolve({
8351          value: undefined,
8352          done: true
8353        });
8354      }
8355
8356      this._requests.length = 0;
8357    }
8358
8359    this._done = true;
8360
8361    this._stream._removeRangeReader(this);
8362  }
8363
8364  get isStreamingSupported() {
8365    return false;
8366  }
8367
8368  async read() {
8369    if (this._queuedChunk) {
8370      const chunk = this._queuedChunk;
8371      this._queuedChunk = null;
8372      return {
8373        value: chunk,
8374        done: false
8375      };
8376    }
8377
8378    if (this._done) {
8379      return {
8380        value: undefined,
8381        done: true
8382      };
8383    }
8384
8385    const requestCapability = (0, _util.createPromiseCapability)();
8386
8387    this._requests.push(requestCapability);
8388
8389    return requestCapability.promise;
8390  }
8391
8392  cancel(reason) {
8393    this._done = true;
8394
8395    for (const requestCapability of this._requests) {
8396      requestCapability.resolve({
8397        value: undefined,
8398        done: true
8399      });
8400    }
8401
8402    this._requests.length = 0;
8403
8404    this._stream._removeRangeReader(this);
8405  }
8406
8407}
8408
8409/***/ }),
8410/* 17 */
8411/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8412
8413
8414
8415Object.defineProperty(exports, "__esModule", ({
8416  value: true
8417}));
8418exports.AnnotationLayer = void 0;
8419
8420var _display_utils = __w_pdfjs_require__(1);
8421
8422var _util = __w_pdfjs_require__(2);
8423
8424var _annotation_storage = __w_pdfjs_require__(8);
8425
8426var _scripting_utils = __w_pdfjs_require__(18);
8427
8428class AnnotationElementFactory {
8429  static create(parameters) {
8430    const subtype = parameters.data.annotationType;
8431
8432    switch (subtype) {
8433      case _util.AnnotationType.LINK:
8434        return new LinkAnnotationElement(parameters);
8435
8436      case _util.AnnotationType.TEXT:
8437        return new TextAnnotationElement(parameters);
8438
8439      case _util.AnnotationType.WIDGET:
8440        const fieldType = parameters.data.fieldType;
8441
8442        switch (fieldType) {
8443          case "Tx":
8444            return new TextWidgetAnnotationElement(parameters);
8445
8446          case "Btn":
8447            if (parameters.data.radioButton) {
8448              return new RadioButtonWidgetAnnotationElement(parameters);
8449            } else if (parameters.data.checkBox) {
8450              return new CheckboxWidgetAnnotationElement(parameters);
8451            }
8452
8453            return new PushButtonWidgetAnnotationElement(parameters);
8454
8455          case "Ch":
8456            return new ChoiceWidgetAnnotationElement(parameters);
8457        }
8458
8459        return new WidgetAnnotationElement(parameters);
8460
8461      case _util.AnnotationType.POPUP:
8462        return new PopupAnnotationElement(parameters);
8463
8464      case _util.AnnotationType.FREETEXT:
8465        return new FreeTextAnnotationElement(parameters);
8466
8467      case _util.AnnotationType.LINE:
8468        return new LineAnnotationElement(parameters);
8469
8470      case _util.AnnotationType.SQUARE:
8471        return new SquareAnnotationElement(parameters);
8472
8473      case _util.AnnotationType.CIRCLE:
8474        return new CircleAnnotationElement(parameters);
8475
8476      case _util.AnnotationType.POLYLINE:
8477        return new PolylineAnnotationElement(parameters);
8478
8479      case _util.AnnotationType.CARET:
8480        return new CaretAnnotationElement(parameters);
8481
8482      case _util.AnnotationType.INK:
8483        return new InkAnnotationElement(parameters);
8484
8485      case _util.AnnotationType.POLYGON:
8486        return new PolygonAnnotationElement(parameters);
8487
8488      case _util.AnnotationType.HIGHLIGHT:
8489        return new HighlightAnnotationElement(parameters);
8490
8491      case _util.AnnotationType.UNDERLINE:
8492        return new UnderlineAnnotationElement(parameters);
8493
8494      case _util.AnnotationType.SQUIGGLY:
8495        return new SquigglyAnnotationElement(parameters);
8496
8497      case _util.AnnotationType.STRIKEOUT:
8498        return new StrikeOutAnnotationElement(parameters);
8499
8500      case _util.AnnotationType.STAMP:
8501        return new StampAnnotationElement(parameters);
8502
8503      case _util.AnnotationType.FILEATTACHMENT:
8504        return new FileAttachmentAnnotationElement(parameters);
8505
8506      default:
8507        return new AnnotationElement(parameters);
8508    }
8509  }
8510
8511}
8512
8513class AnnotationElement {
8514  constructor(parameters, {
8515    isRenderable = false,
8516    ignoreBorder = false,
8517    createQuadrilaterals = false
8518  }
8518 = {}) {
8519    this.isRenderable = isRenderable;
8520    this.data = parameters.data;
8521    this.layer = parameters.layer;
8522    this.page = parameters.page;
8523    this.viewport = parameters.viewport;
8524    this.linkService = parameters.linkService;
8525    this.downloadManager = parameters.downloadManager;
8526    this.imageResourcesPath = parameters.imageResourcesPath;
8527    this.renderInteractiveForms = parameters.renderInteractiveForms;
8528    this.svgFactory = parameters.svgFactory;
8529    this.annotationStorage = parameters.annotationStorage;
8530    this.enableScripting = parameters.enableScripting;
8531    this.hasJSActions = parameters.hasJSActions;
8532    this._mouseState = parameters.mouseState;
8533
8534    if (isRenderable) {
8535      this.container = this._createContainer(ignoreBorder);
8536    }
8537
8538    if (createQuadrilaterals) {
8539      this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
8540    }
8541  }
8542
8543  _createContainer(ignoreBorder = false) {
8544    const data = this.data,
8545          page = this.page,
8546          viewport = this.viewport;
8547    const container = document.createElement("section");
8548    let width = data.rect[2] - data.rect[0];
8549    let height = data.rect[3] - data.rect[1];
8550    container.setAttribute("data-annotation-id", data.id);
8551
8552    const rect = _util.Util.normalizeRect([data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1]]);
8553
8554    container.style.transform = `matrix(${viewport.transform.join(",")})`;
8555    container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
8556
8557    if (!ignoreBorder && data.borderStyle.width > 0) {
8558      container.style.borderWidth = `${data.borderStyle.width}px`;
8559
8560      if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
8561        width = width - 2 * data.borderStyle.width;
8562        height = height - 2 * data.borderStyle.width;
8563      }
8564
8565      const horizontalRadius = data.borderStyle.horizontalCornerRadius;
8566      const verticalRadius = data.borderStyle.verticalCornerRadius;
8567
8568      if (horizontalRadius > 0 || verticalRadius > 0) {
8569        const radius = `${horizontalRadius}px / ${verticalRadius}px`;
8570        container.style.borderRadius = radius;
8571      }
8572
8573      switch (data.borderStyle.style) {
8574        case _util.AnnotationBorderStyleType.SOLID:
8575          container.style.borderStyle = "solid";
8576          break;
8577
8578        case _util.AnnotationBorderStyleType.DASHED:
8579          container.style.borderStyle = "dashed";
8580          break;
8581
8582        case _util.AnnotationBorderStyleType.BEVELED:
8583          (0, _util.warn)("Unimplemented border style: beveled");
8584          break;
8585
8586        case _util.AnnotationBorderStyleType.INSET:
8587          (0, _util.warn)("Unimplemented border style: inset");
8588          break;
8589
8590        case _util.AnnotationBorderStyleType.UNDERLINE:
8591          container.style.borderBottomStyle = "solid";
8592          break;
8593
8594        default:
8595          break;
8596      }
8597
8598      if (data.color) {
8599        container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
8600      } else {
8601        container.style.borderWidth = 0;
8602      }
8603    }
8604
8605    container.style.left = `${rect[0]}px`;
8606    container.style.top = `${rect[1]}px`;
8607    container.style.width = `${width}px`;
8608    container.style.height = `${height}px`;
8609    return container;
8610  }
8611
8612  _createQuadrilaterals(ignoreBorder = false) {
8613    if (!this.data.quadPoints) {
8614      return null;
8615    }
8616
8617    const quadrilaterals = [];
8618    const savedRect = this.data.rect;
8619
8620    for (const quadPoint of this.data.quadPoints) {
8621      this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
8622      quadrilaterals.push(this._createContainer(ignoreBorder));
8623    }
8624
8625    this.data.rect = savedRect;
8626    return quadrilaterals;
8627  }
8628
8629  _createPopup(trigger, data) {
8630    let container = this.container;
8631
8632    if (this.quadrilaterals) {
8633      trigger = trigger || this.quadrilaterals;
8634      container = this.quadrilaterals[0];
8635    }
8636
8637    if (!trigger) {
8638      trigger = document.createElement("div");
8639      trigger.style.height = container.style.height;
8640      trigger.style.width = container.style.width;
8641      container.appendChild(trigger);
8642    }
8643
8644    const popupElement = new PopupElement({
8645      container,
8646      trigger,
8647      color: data.color,
8648      title: data.title,
8649      modificationDate: data.modificationDate,
8650      contents: data.contents,
8651      hideWrapper: true
8652    });
8653    const popup = popupElement.render();
8654    popup.style.left = container.style.width;
8655    container.appendChild(popup);
8656  }
8657
8658  _renderQuadrilaterals(className) {
8659    for (const quadrilateral of this.quadrilaterals) {
8660      quadrilateral.className = className;
8661    }
8662
8663    return this.quadrilaterals;
8664  }
8665
8666  render() {
8667    (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
8668  }
8669
8670}
8671
8672class LinkAnnotationElement extends AnnotationElement {
8673  constructor(parameters) {
8674    const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"]));
8675    super(parameters, {
8676      isRenderable,
8677      createQuadrilaterals: true
8678    });
8679  }
8680
8681  render() {
8682    const {
8683      data,
8684      linkService
8685    } = this;
8686    const link = document.createElement("a");
8687
8688    if (data.url) {
8689      (0, _display_utils.addLinkAttributes)(link, {
8690        url: data.url,
8691        target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget,
8692        rel: linkService.externalLinkRel,
8693        enabled: linkService.externalLinkEnabled
8694      });
8695    } else if (data.action) {
8696      this._bindNamedAction(link, data.action);
8697    } else if (data.dest) {
8698      this._bindLink(link, data.dest);
8699    } else if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
8700      this._bindJSAction(link, data);
8701    } else {
8702      this._bindLink(link, "");
8703    }
8704
8705    if (this.quadrilaterals) {
8706      return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
8707        const linkElement = index === 0 ? link : link.cloneNode();
8708        quadrilateral.appendChild(linkElement);
8709        return quadrilateral;
8710      });
8711    }
8712
8713    this.container.className = "linkAnnotation";
8714    this.container.appendChild(link);
8715    return this.container;
8716  }
8717
8718  _bindLink(link, destination) {
8719    link.href = this.linkService.getDestinationHash(destination);
8720
8721    link.onclick = () => {
8722      if (destination) {
8723        this.linkService.goToDestination(destination);
8724      }
8725
8726      return false;
8727    };
8728
8729    if (destination || destination === "") {
8730      link.className = "internalLink";
8731    }
8732  }
8733
8734  _bindNamedAction(link, action) {
8735    link.href = this.linkService.getAnchorUrl("");
8736
8737    link.onclick = () => {
8738      this.linkService.executeNamedAction(action);
8739      return false;
8740    };
8741
8742    link.className = "internalLink";
8743  }
8744
8745  _bindJSAction(link, data) {
8746    link.href = this.linkService.getAnchorUrl("");
8747    const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
8748
8749    for (const name of Object.keys(data.actions)) {
8750      const jsName = map.get(name);
8751
8752      if (!jsName) {
8753        continue;
8754      }
8755
8756      link[jsName] = () => {
8757        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
8758          source: this,
8759          detail: {
8760            id: data.id,
8761            name
8762          }
8763        });
8764        return false;
8765      };
8766    }
8767
8768    link.className = "internalLink";
8769  }
8770
8771}
8772
8773class TextAnnotationElement extends AnnotationElement {
8774  constructor(parameters) {
8775    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
8776    super(parameters, {
8777      isRenderable
8778    });
8779  }
8780
8781  render() {
8782    this.container.className = "textAnnotation";
8783    const image = document.createElement("img");
8784    image.style.height = this.container.style.height;
8785    image.style.width = this.container.style.width;
8786    image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
8787    image.alt = "[{{type}} Annotation]";
8788    image.dataset.l10nId = "text_annotation_type";
8789    image.dataset.l10nArgs = JSON.stringify({
8790      type: this.data.name
8791    });
8792
8793    if (!this.data.hasPopup) {
8794      this._createPopup(image, this.data);
8795    }
8796
8797    this.container.appendChild(image);
8798    return this.container;
8799  }
8800
8801}
8802
8803class WidgetAnnotationElement extends AnnotationElement {
8804  render() {
8805    if (this.data.alternativeText) {
8806      this.container.title = this.data.alternativeText;
8807    }
8808
8809    return this.container;
8810  }
8811
8812  _getKeyModifier(event) {
8813    return navigator.platform.includes("Win") && event.ctrlKey || navigator.platform.includes("Mac") && event.metaKey;
8814  }
8815
8816  _setEventListener(element, baseName, eventName, valueGetter) {
8817    if (baseName.includes("mouse")) {
8818      element.addEventListener(baseName, event => {
8819        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
8820          source: this,
8821          detail: {
8822            id: this.data.id,
8823            name: eventName,
8824            value: valueGetter(event),
8825            shift: event.shiftKey,
8826            modifier: this._getKeyModifier(event)
8827          }
8828        });
8829      });
8830    } else {
8831      element.addEventListener(baseName, event => {
8832        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
8833          source: this,
8834          detail: {
8835            id: this.data.id,
8836            name: eventName,
8837            value: event.target.checked
8838          }
8839        });
8840      });
8841    }
8842  }
8843
8844  _setEventListeners(element, names, getter) {
8845    for (const [baseName, eventName] of names) {
8846      if (eventName === "Action" || this.data.actions?.[eventName]) {
8847        this._setEventListener(element, baseName, eventName, getter);
8848      }
8849    }
8850  }
8851
8852  _dispatchEventFromSandbox(actions, jsEvent) {
8853    const setColor = (jsName, styleName, event) => {
8854      const color = event.detail[jsName];
8855      event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
8856    };
8857
8858    const commonActions = {
8859      display: event => {
8860        const hidden = event.detail.display % 2 === 1;
8861        event.target.style.visibility = hidden ? "hidden" : "visible";
8862        this.annotationStorage.setValue(this.data.id, {
8863          hidden,
8864          print: event.detail.display === 0 || event.detail.display === 3
8865        });
8866      },
8867      print: event => {
8868        this.annotationStorage.setValue(this.data.id, {
8869          print: event.detail.print
8870        });
8871      },
8872      hidden: event => {
8873        event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
8874        this.annotationStorage.setValue(this.data.id, {
8875          hidden: event.detail.hidden
8876        });
8877      },
8878      focus: event => {
8879        setTimeout(() =>
8879 event.target.focus({
8880          preventScroll: false
8881        }), 0);
8882      },
8883      userName: event => {
8884        event.target.title = event.detail.userName;
8885      },
8886      readonly: event => {
8887        if (event.detail.readonly) {
8888          event.target.setAttribute("readonly", "");
8889        } else {
8890          event.target.removeAttribute("readonly");
8891        }
8892      },
8893      required: event => {
8894        if (event.detail.required) {
8895          event.target.setAttribute("required", "");
8896        } else {
8897          event.target.removeAttribute("required");
8898        }
8899      },
8900      bgColor: event => {
8901        setColor("bgColor", "backgroundColor", event);
8902      },
8903      fillColor: event => {
8904        setColor("fillColor", "backgroundColor", event);
8905      },
8906      fgColor: event => {
8907        setColor("fgColor", "color", event);
8908      },
8909      textColor: event => {
8910        setColor("textColor", "color", event);
8911      },
8912      borderColor: event => {
8913        setColor("borderColor", "borderColor", event);
8914      },
8915      strokeColor: event => {
8916        setColor("strokeColor", "borderColor", event);
8917      }
8918    };
8919
8920    for (const name of Object.keys(jsEvent.detail)) {
8921      const action = actions[name] || commonActions[name];
8922
8923      if (action) {
8924        action(jsEvent);
8925      }
8926    }
8927  }
8928
8929}
8930
8931class TextWidgetAnnotationElement extends WidgetAnnotationElement {
8932  constructor(parameters) {
8933    const isRenderable = parameters.renderInteractiveForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
8934    super(parameters, {
8935      isRenderable
8936    });
8937  }
8938
8939  setPropertyOnSiblings(base, key, value, keyInStorage) {
8940    const storage = this.annotationStorage;
8941
8942    for (const element of document.getElementsByName(base.name)) {
8943      if (element !== base) {
8944        element[key] = value;
8945        const data = Object.create(null);
8946        data[keyInStorage] = value;
8947        storage.setValue(element.getAttribute("id"), data);
8948      }
8949    }
8950  }
8951
8952  render() {
8953    const storage = this.annotationStorage;
8954    const id = this.data.id;
8955    this.container.className = "textWidgetAnnotation";
8956    let element = null;
8957
8958    if (this.renderInteractiveForms) {
8959      const storedData = storage.getValue(id, {
8960        value: this.data.fieldValue,
8961        valueAsString: this.data.fieldValue
8962      });
8963      const textContent = storedData.valueAsString || storedData.value || "";
8964      const elementData = {
8965        userValue: null,
8966        formattedValue: null,
8967        beforeInputSelectionRange: null,
8968        beforeInputValue: null
8969      };
8970
8971      if (this.data.multiLine) {
8972        element = document.createElement("textarea");
8973        element.textContent = textContent;
8974      } else {
8975        element = document.createElement("input");
8976        element.type = "text";
8977        element.setAttribute("value", textContent);
8978      }
8979
8980      elementData.userValue = textContent;
8981      element.setAttribute("id", id);
8982      element.addEventListener("input", event => {
8983        storage.setValue(id, {
8984          value: event.target.value
8985        });
8986        this.setPropertyOnSiblings(element, "value", event.target.value, "value");
8987      });
8988
8989      let blurListener = event => {
8990        if (elementData.formattedValue) {
8991          event.target.value = elementData.formattedValue;
8992        }
8993
8994        event.target.scrollLeft = 0;
8995        elementData.beforeInputSelectionRange = null;
8996      };
8997
8998      if (this.enableScripting && this.hasJSActions) {
8999        element.addEventListener("focus", event => {
9000          if (elementData.userValue) {
9001            event.target.value = elementData.userValue;
9002          }
9003        });
9004        element.addEventListener("updatefromsandbox", jsEvent => {
9005          const actions = {
9006            value(event) {
9007              elementData.userValue = event.detail.value || "";
9008              storage.setValue(id, {
9009                value: elementData.userValue.toString()
9010              });
9011
9012              if (!elementData.formattedValue) {
9013                event.target.value = elementData.userValue;
9014              }
9015            },
9016
9017            valueAsString(event) {
9018              elementData.formattedValue = event.detail.valueAsString || "";
9019
9020              if (event.target !== document.activeElement) {
9021                event.target.value = elementData.formattedValue;
9022              }
9023
9024              storage.setValue(id, {
9025                formattedValue: elementData.formattedValue
9026              });
9027            },
9028
9029            selRange(event) {
9030              const [selStart, selEnd] = event.detail.selRange;
9031
9032              if (selStart >= 0 && selEnd < event.target.value.length) {
9033                event.target.setSelectionRange(selStart, selEnd);
9034              }
9035            }
9036
9037          };
9038
9039          this._dispatchEventFromSandbox(actions, jsEvent);
9040        });
9041        element.addEventListener("keydown", event => {
9042          elementData.beforeInputValue = event.target.value;
9043          let commitKey = -1;
9044
9045          if (event.key === "Escape") {
9046            commitKey = 0;
9047          } else if (event.key === "Enter") {
9048            commitKey = 2;
9049          } else if (event.key === "Tab") {
9050            commitKey = 3;
9051          }
9052
9053          if (commitKey === -1) {
9054            return;
9055          }
9056
9057          elementData.userValue = event.target.value;
9058          this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9059            source: this,
9060            detail: {
9061              id,
9062              name: "Keystroke",
9063              value: event.target.value,
9064              willCommit: true,
9065              commitKey,
9066              selStart: event.target.selectionStart,
9067              selEnd: event.target.selectionEnd
9068            }
9069          });
9070        });
9071        const _blurListener = blurListener;
9072        blurListener = null;
9073        element.addEventListener("blur", event => {
9074          if (this._mouseState.isDown) {
9075            elementData.userValue = event.target.value;
9076            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9077              source: this,
9078              detail: {
9079                id,
9080                name: "Keystroke",
9081                value: event.target.value,
9082                willCommit: true,
9083                commitKey: 1,
9084                selStart: event.target.selectionStart,
9085                selEnd: event.target.selectionEnd
9086              }
9087            });
9088          }
9089
9090          _blurListener(event);
9091        });
9092        element.addEventListener("mousedown", event => {
9093          elementData.beforeInputValue = event.target.value;
9094          elementData.beforeInputSelectionRange = null;
9095        });
9096        element.addEventListener("keyup", event => {
9097          if (event.target.selectionStart === event.target.selectionEnd) {
9098            elementData.beforeInputSelectionRange = null;
9099          }
9100        });
9101        element.addEventListener("select", event => {
9102          elementData.beforeInputSelectionRange = [event.target.selectionStart, event.target.selectionEnd];
9103        });
9104
9105        if (this.data.actions?.Keystroke) {
9106          element.addEventListener("input", event => {
9107            let selStart = -1;
9108            let selEnd = -1;
9109
9110            if (elementData.beforeInputSelectionRange) {
9111              [selStart, selEnd] = elementData.beforeInputSelectionRange;
9112            }
9113
9114            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9115              source: this,
9116              detail: {
9117                id,
9118                name: "Keystroke",
9119                value: elementData.beforeInputValue,
9120                change: event.data,
9121                willCommit: false,
9122                selStart,
9123                selEnd
9124              }
9125            });
9126          });
9127        }
9128
9129        this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
9130      }
9131
9132      if (blurListener) {
9133        element.addEventListener("blur", blurListener);
9134      }
9135
9136      element.disabled = this.data.readOnly;
9137      element.name = this.data.fieldName;
9138
9139      if (this.data.maxLen !== null) {
9140        element.maxLength = this.data.maxLen;
9141      }
9142
9143      if (this.data.comb) {
9144        const fieldWidth = this.data.rect[2] - this.data.rect[0];
9145        const combWidth = fieldWidth / this.data.maxLen;
9146        element.classList.add("comb");
9147        element.style.letterSpacing = `calc(${combWidth}px - 1ch)`;
9148      }
9149    } else {
9150      element = document.createElement("div");
9151      element.textContent = this.data.fieldValue;
9152      element.style.verticalAlign = "middle";
9153      element.style.display = "table-cell";
9154    }
9155
9156    this._setTextStyle(element);
9157
9158    this.container.appendChild(element);
9159    return this.container;
9160  }
9161
9162  _setTextStyle(element) {
9163    const TEXT_ALIGNMENT = ["left", "center", "right"];
9164    const {
9165      fontSize,
9166      fontColor
9167    } = this.data.defaultAppearanceData;
9168    const style = element.style;
9169
9170    if (fontSize) {
9171      style.fontSize = `${fontSize}px`;
9172    }
9173
9174    style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
9175
9176    if (this.data.textAlignment !== null) {
9177      style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
9178    }
9179  }
9180
9181}
9182
9183class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
9184  constructor(parameters) {
9185    super(parameters, {
9186      isRenderable: parameters.renderInteractiveForms
9187    });
9188  }
9189
9190  render() {
9191    const storage = this.annotationStorage;
9192    const data = this.data;
9193    const id = data.id;
9194    let value = storage.getValue(id, {
9195      value: data.fieldValue && (data.exportValue && data.exportValue === data.fieldValue || !data.exportValue && data.fieldValue !== "Off")
9196    }).value;
9197
9198    if (typeof value === "string") {
9199      value = value !== "Off";
9200      storage.setValue(id, {
9201        value
9202      });
9203    }
9204
9205    this.container.className = "buttonWidgetAnnotation checkBox";
9206    const element = document.createElement("input");
9207    element.disabled = data.readOnly;
9208    element.type = "checkbox";
9209    element.name = this.data.fieldName;
9210
9211    if (value) {
9212      element.setAttribute("checked", true);
9213    }
9214
9215    element.setAttribute("id", id);
9216    element.addEventListener("change", function (event) {
9217      const name = event.target.name;
9218
9219      for (const checkbox of document.getElementsByName(name)) {
9220        if (checkbox !== event.target) {
9221          checkbox.checked = false;
9222          storage.setValue(checkbox.parentNode.getAttribute("data-annotation-id"), {
9223            value: false
9224          });
9225        }
9226      }
9227
9228      storage.setValue(id, {
9229        value: event.target.checked
9230      });
9231    });
9232
9233    if (this.enableScripting && this.hasJSActions) {
9234      element.addEventListener("updatefromsandbox", jsEvent => {
9235        const actions = {
9236          value(event) {
9237            event.target.checked = event.detail.value !== "Off";
9238            storage.setValue(id, {
9239              value: event.target.checked
9240            });
9241          }
9242
9243        };
9244
9245        this._dispatchEventFromSandbox(actions, jsEvent);
9246      });
9247
9248      this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
9249    }
9250
9251    this.container.appendChild(element);
9252    return this.container;
9253  }
9254
9255}
9256
9257class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
9258  constructor(parameters) {
9259    super(parameters, {
9260      isRenderable: parameters.renderInteractiveForms
9261    });
9262  }
9263
9264  render() {
9265    this.container.className = "buttonWidgetAnnotation radioButton";
9266    const storage = this.annotationStorage;
9267    const data = this.data;
9268    const id = data.id;
9269    let value = storage.getValue(id, {
9270      value: data.fieldValue === data.buttonValue
9271    }).value;
9272
9273    if (typeof value === "string") {
9274      value = value !== data.buttonValue;
9275      storage.setValue(id, {
9276        value
9277      });
9278    }
9279
9280    const element = document.createElement("input");
9281    element.disabled = data.readOnly;
9282    element.type = "radio";
9283    element.name = data.fieldName;
9284
9285    if (value) {
9286      element.setAttribute("checked", true);
9287    }
9288
9289    element.setAttribute("id", id);
9290    element.addEventListener("change", function (event) {
9291      const {
9292        target
9293      } = event;
9294
9295      for (const radio of document.getElementsByName(target.name)) {
9296        if (radio !== target) {
9297          storage.setValue(radio.getAttribute("id"), {
9298            value: false
9299          });
9300        }
9301      }
9302
9303      storage.setValue(id, {
9304        value: target.checked
9305      });
9306    });
9307
9308    if (this.enableScripting && this.hasJSActions) {
9309      const pdfButtonValue = data.buttonValue;
9310      element.addEventListener("updatefromsandbox", jsEvent => {
9311        const actions = {
9312          value(event) {
9313            const checked = pdfButtonValue === event.detail.value;
9314
9315            for (const radio of document.getElementsByName(event.target.name)) {
9316              const radioId = radio.getAttribute("id");
9317              radio.checked = radioId === id && checked;
9318              storage.setValue(radioId, {
9319                value: radio.checked
9320              });
9321            }
9322          }
9323
9324        };
9325
9326        this._dispatchEventFromSandbox(actions, jsEvent);
9327      });
9328
9329      this._setEventListeners(element, [["change", "Validate"], ["change", "Action"], ["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.checked);
9330    }
9331
9332    this.container.appendChild(element);
9333    return this.container;
9334  }
9335
9336}
9337
9338class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
9339  render() {
9340    const container = super.render();
9341    container.className = "buttonWidgetAnnotation pushButton";
9342
9343    if (this.data.alternativeText) {
9344      container.title = this.data.alternativeText;
9345    }
9346
9347    return container;
9348  }
9349
9350}
9351
9352class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
9353  constructor(parameters) {
9354    super(parameters, {
9355      isRenderable: parameters.renderInteractiveForms
9356    });
9357  }
9358
9359  render() {
9360    this.container.className = "choiceWidgetAnnotation";
9361    const storage = this.annotationStorage;
9362    const id = this.data.id;
9363    storage.getValue(id, {
9364      value: this.data.fieldValue.length > 0 ? this.data.fieldValue[0] : undefined
9365    });
9366    const selectElement = document.createElement("select");
9367    selectElement.disabled = this.data.readOnly;
9368    selectElement.name = this.data.fieldName;
9369    selectElement.setAttribute("id", id);
9370
9371    if (!this.data.combo) {
9372      selectElement.size = this.data.options.length;
9373
9374      if (this.data.multiSelect) {
9375        selectElement.multiple = true;
9376      }
9377    }
9378
9379    for (const option of this.data.options) {
9380      const optionElement = document.createElement("option");
9381      optionElement.textContent = option.displayValue;
9382      optionElement.value = option.exportValue;
9383
9384      if (this.data.fieldValue.includes(option.exportValue)) {
9385        optionElement.setAttribute("selected", true);
9386      }
9387
9388      selectElement.appendChild(optionElement);
9389    }
9390
9391    const getValue = (event, isExport) => {
9392      const name = isExport ? "value" : "textContent";
9393      const options = event.target.options;
9394
9395      if (!event.target.multiple) {
9396        return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
9397      }
9398
9399      return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
9400    };
9401
9402    const getItems = event => {
9403      const options = event.target.options;
9404      return Array.prototype.map.call(options, option => {
9405        return {
9406          displayValue: option.textContent,
9407          exportValue: option.value
9408        };
9409      });
9410    };
9411
9412    if (this.enableScripting && this.hasJSActions) {
9413      selectElement.addEventListener("updatefromsandbox", jsEvent => {
9414        const actions = {
9415          value(event) {
9416            const options = selectElement.options;
9417            const value = event.detail.value;
9418            const values = new Set(Array.isArray(value) ? value : [value]);
9419            Array.prototype.forEach.call(options, option => {
9420              option.selected = values.has(option.value);
9421            });
9422            storage.setValue(id, {
9423              value: getValue(event, true)
9424            });
9425          },
9426
9427          multipleSelection(event) {
9428            selectElement.multiple = true;
9429          },
9430
9431          remove(event) {
9432            const options = selectElement.options;
9433            const index = event.detail.remove;
9434            options[index].selected = false;
9435            selectElement.remove(index);
9436
9437            if (options.length > 0) {
9438              const i = Array.prototype.findIndex.call(options, option => option.selected);
9439
9440              if (i === -1) {
9441                options[0].selected = true;
9442              }
9443            }
9444
9445            storage.setValue(id, {
9446              value: getValue(event, true),
9447              items: getItems(event)
9448            });
9449          },
9450
9451          clear(event) {
9452            while (selectElement.length !== 0) {
9453              selectElement.remove(0);
9454            }
9455
9456            storage.setValue(id, {
9457              value: null,
9458              items: []
9459            });
9460          },
9461
9462          insert(event) {
9463            const {
9464              index,
9465              displayValue,
9466              exportValue
9467            } = event.detail.insert;
9468            const optionElement = document.createElement("option");
9469            optionElement.textContent = displayValue;
9470            optionElement.value = exportValue;
9471            selectElement.insertBefore(optionElement, selectElement.children[index]);
9472            storage.setValue(id, {
9473              value: getValue(event, true),
9474              items: getItems(event)
9475            });
9476          },
9477
9478          items(event) {
9479            const {
9480              items
9481            } = event.detail;
9482
9483            while (selectElement.length !== 0) {
9484              selectElement.remove(0);
9485            }
9486
9487            for (const item of items) {
9488              const {
9489                displayValue,
9490                exportValue
9491              } = item;
9492              const optionElement = document.createElement("option");
9493              optionElement.textContent = displayValue;
9494              optionElement.value = exportValue;
9495              selectElement.appendChild(optionElement);
9496            }
9497
9498            if (selectElement.options.length > 0) {
9499              selectElement.options[0].selected = true;
9500            }
9501
9502            storage.setValue(id, {
9503              value: getValue(event, true),
9504              items: getItems(event)
9505            });
9506          },
9507
9508          indices(event) {
9509            const indices = new Set(event.detail.indices);
9510            const options = event.target.options;
9511            Array.prototype.forEach.call(options, (option, i) => {
9512              option.selected = indices.has(i);
9513            });
9514            storage.setValue(id, {
9515              value: getValue(event, true)
9516            });
9517          },
9518
9519          editable(event) {
9520            event.target.disabled = !event.detail.editable;
9521          }
9522
9523        };
9524
9525        this._dispatchEventFromSandbox(actions, jsEvent);
9526      });
9527      selectElement.addEventListener("input", event => {
9528        const exportValue = getValue(event, true);
9529        const value = getValue(event, false);
9530        storage.setValue(id, {
9531          value: exportValue
9532        });
9533        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
9534          source: this,
9535          detail: {
9536            id,
9537            name: "Keystroke",
9538            value,
9539            changeEx: exportValue,
9540            willCommit: true,
9541            commitKey: 1,
9542            keyDown: false
9543          }
9544        });
9545      });
9546
9547      this._setEventListeners(selectElement, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"], ["input", "Action"]], event => event.target.checked);
9548    } else {
9549      selectElement.addEventListener("input", function (event) {
9550        storage.setValue(id, {
9551          value: getValue(event)
9552        });
9553      });
9554    }
9555
9556    this.container.appendChild(selectElement);
9557    return this.container;
9558  }
9559
9560}
9561
9562class PopupAnnotationElement extends AnnotationElement {
9563  constructor(parameters) {
9564    const isRenderable = !!(parameters.data.title || parameters.data.contents);
9565    super(parameters, {
9566      isRenderable
9567    });
9568  }
9569
9570  render() {
9571    const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
9572    this.container.className = "popupAnnotation";
9573
9574    if (IGNORE_TYPES.includes(this.data.parentType)) {
9575      return this.container;
9576    }
9577
9578    const selector = `[data-annotation-id="${this.data.parentId}"]`;
9579    const parentElements = this.layer.querySelectorAll(selector);
9580
9581    if (parentElements.length === 0) {
9582      return this.container;
9583    }
9584
9585    const popup = new PopupElement({
9586      container: this.container,
9587      trigger: Array.from(parentElements),
9588      color: this.data.color,
9589      title: this.data.title,
9590      modificationDate: this.data.modificationDate,
9591      contents: this.data.contents
9592    });
9593    const page = this.page;
9594
9595    const rect = _util.Util.normalizeRect([this.data.parentRect[0], page.view[3] - this.data.parentRect[1] + page.view[1], this.data.parentRect[2], page.view[3] - this.data.parentRect[3] + page.view[1]]);
9596
9597    const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
9598    const popupTop = rect[1];
9599    this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}
9599px`;
9600    this.container.style.left = `${popupLeft}px`;
9601    this.container.style.top = `${popupTop}px`;
9602    this.container.appendChild(popup.render());
9603    return this.container;
9604  }
9605
9606}
9607
9608class PopupElement {
9609  constructor(parameters) {
9610    this.container = parameters.container;
9611    this.trigger = parameters.trigger;
9612    this.color = parameters.color;
9613    this.title = parameters.title;
9614    this.modificationDate = parameters.modificationDate;
9615    this.contents = parameters.contents;
9616    this.hideWrapper = parameters.hideWrapper || false;
9617    this.pinned = false;
9618  }
9619
9620  render() {
9621    const BACKGROUND_ENLIGHT = 0.7;
9622    const wrapper = document.createElement("div");
9623    wrapper.className = "popupWrapper";
9624    this.hideElement = this.hideWrapper ? wrapper : this.container;
9625    this.hideElement.hidden = true;
9626    const popup = document.createElement("div");
9627    popup.className = "popup";
9628    const color = this.color;
9629
9630    if (color) {
9631      const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
9632      const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
9633      const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
9634      popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
9635    }
9636
9637    const title = document.createElement("h1");
9638    title.textContent = this.title;
9639    popup.appendChild(title);
9640
9641    const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
9642
9643    if (dateObject) {
9644      const modificationDate = document.createElement("span");
9645      modificationDate.textContent = "{{date}}, {{time}}";
9646      modificationDate.dataset.l10nId = "annotation_date_string";
9647      modificationDate.dataset.l10nArgs = JSON.stringify({
9648        date: dateObject.toLocaleDateString(),
9649        time: dateObject.toLocaleTimeString()
9650      });
9651      popup.appendChild(modificationDate);
9652    }
9653
9654    const contents = this._formatContents(this.contents);
9655
9656    popup.appendChild(contents);
9657
9658    if (!Array.isArray(this.trigger)) {
9659      this.trigger = [this.trigger];
9660    }
9661
9662    for (const element of this.trigger) {
9663      element.addEventListener("click", this._toggle.bind(this));
9664      element.addEventListener("mouseover", this._show.bind(this, false));
9665      element.addEventListener("mouseout", this._hide.bind(this, false));
9666    }
9667
9668    popup.addEventListener("click", this._hide.bind(this, true));
9669    wrapper.appendChild(popup);
9670    return wrapper;
9671  }
9672
9673  _formatContents(contents) {
9674    const p = document.createElement("p");
9675    const lines = contents.split(/(?:\r\n?|\n)/);
9676
9677    for (let i = 0, ii = lines.length; i < ii; ++i) {
9678      const line = lines[i];
9679      p.appendChild(document.createTextNode(line));
9680
9681      if (i < ii - 1) {
9682        p.appendChild(document.createElement("br"));
9683      }
9684    }
9685
9686    return p;
9687  }
9688
9689  _toggle() {
9690    if (this.pinned) {
9691      this._hide(true);
9692    } else {
9693      this._show(true);
9694    }
9695  }
9696
9697  _show(pin = false) {
9698    if (pin) {
9699      this.pinned = true;
9700    }
9701
9702    if (this.hideElement.hidden) {
9703      this.hideElement.hidden = false;
9704      this.container.style.zIndex += 1;
9705    }
9706  }
9707
9708  _hide(unpin = true) {
9709    if (unpin) {
9710      this.pinned = false;
9711    }
9712
9713    if (!this.hideElement.hidden && !this.pinned) {
9714      this.hideElement.hidden = true;
9715      this.container.style.zIndex -= 1;
9716    }
9717  }
9718
9719}
9720
9721class FreeTextAnnotationElement extends AnnotationElement {
9722  constructor(parameters) {
9723    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9724    super(parameters, {
9725      isRenderable,
9726      ignoreBorder: true
9727    });
9728  }
9729
9730  render() {
9731    this.container.className = "freeTextAnnotation";
9732
9733    if (!this.data.hasPopup) {
9734      this._createPopup(null, this.data);
9735    }
9736
9737    return this.container;
9738  }
9739
9740}
9741
9742class LineAnnotationElement extends AnnotationElement {
9743  constructor(parameters) {
9744    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9745    super(parameters, {
9746      isRenderable,
9747      ignoreBorder: true
9748    });
9749  }
9750
9751  render() {
9752    this.container.className = "lineAnnotation";
9753    const data = this.data;
9754    const width = data.rect[2] - data.rect[0];
9755    const height = data.rect[3] - data.rect[1];
9756    const svg = this.svgFactory.create(width, height);
9757    const line = this.svgFactory.createElement("svg:line");
9758    line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
9759    line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
9760    line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
9761    line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
9762    line.setAttribute("stroke-width", data.borderStyle.width || 1);
9763    line.setAttribute("stroke", "transparent");
9764    svg.appendChild(line);
9765    this.container.append(svg);
9766
9767    this._createPopup(line, data);
9768
9769    return this.container;
9770  }
9771
9772}
9773
9774class SquareAnnotationElement extends AnnotationElement {
9775  constructor(parameters) {
9776    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9777    super(parameters, {
9778      isRenderable,
9779      ignoreBorder: true
9780    });
9781  }
9782
9783  render() {
9784    this.container.className = "squareAnnotation";
9785    const data = this.data;
9786    const width = data.rect[2] - data.rect[0];
9787    const height = data.rect[3] - data.rect[1];
9788    const svg = this.svgFactory.create(width, height);
9789    const borderWidth = data.borderStyle.width;
9790    const square = this.svgFactory.createElement("svg:rect");
9791    square.setAttribute("x", borderWidth / 2);
9792    square.setAttribute("y", borderWidth / 2);
9793    square.setAttribute("width", width - borderWidth);
9794    square.setAttribute("height", height - borderWidth);
9795    square.setAttribute("stroke-width", borderWidth || 1);
9796    square.setAttribute("stroke", "transparent");
9797    square.setAttribute("fill", "none");
9798    svg.appendChild(square);
9799    this.container.append(svg);
9800
9801    this._createPopup(square, data);
9802
9803    return this.container;
9804  }
9805
9806}
9807
9808class CircleAnnotationElement extends AnnotationElement {
9809  constructor(parameters) {
9810    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9811    super(parameters, {
9812      isRenderable,
9813      ignoreBorder: true
9814    });
9815  }
9816
9817  render() {
9818    this.container.className = "circleAnnotation";
9819    const data = this.data;
9820    const width = data.rect[2] - data.rect[0];
9821    const height = data.rect[3] - data.rect[1];
9822    const svg = this.svgFactory.create(width, height);
9823    const borderWidth = data.borderStyle.width;
9824    const circle = this.svgFactory.createElement("svg:ellipse");
9825    circle.setAttribute("cx", width / 2);
9826    circle.setAttribute("cy", height / 2);
9827    circle.setAttribute("rx", width / 2 - borderWidth / 2);
9828    circle.setAttribute("ry", height / 2 - borderWidth / 2);
9829    circle.setAttribute("stroke-width", borderWidth || 1);
9830    circle.setAttribute("stroke", "transparent");
9831    circle.setAttribute("fill", "none");
9832    svg.appendChild(circle);
9833    this.container.append(svg);
9834
9835    this._createPopup(circle, data);
9836
9837    return this.container;
9838  }
9839
9840}
9841
9842class PolylineAnnotationElement extends AnnotationElement {
9843  constructor(parameters) {
9844    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9845    super(parameters, {
9846      isRenderable,
9847      ignoreBorder: true
9848    });
9849    this.containerClassName = "polylineAnnotation";
9850    this.svgElementName = "svg:polyline";
9851  }
9852
9853  render() {
9854    this.container.className = this.containerClassName;
9855    const data = this.data;
9856    const width = data.rect[2] - data.rect[0];
9857    const height = data.rect[3] - data.rect[1];
9858    const svg = this.svgFactory.create(width, height);
9859    let points = [];
9860
9861    for (const coordinate of data.vertices) {
9862      const x = coordinate.x - data.rect[0];
9863      const y = data.rect[3] - coordinate.y;
9864      points.push(x + "," + y);
9865    }
9866
9867    points = points.join(" ");
9868    const polyline = this.svgFactory.createElement(this.svgElementName);
9869    polyline.setAttribute("points", points);
9870    polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
9871    polyline.setAttribute("stroke", "transparent");
9872    polyline.setAttribute("fill", "none");
9873    svg.appendChild(polyline);
9874    this.container.append(svg);
9875
9876    this._createPopup(polyline, data);
9877
9878    return this.container;
9879  }
9880
9881}
9882
9883class PolygonAnnotationElement extends PolylineAnnotationElement {
9884  constructor(parameters) {
9885    super(parameters);
9886    this.containerClassName = "polygonAnnotation";
9887    this.svgElementName = "svg:polygon";
9888  }
9889
9890}
9891
9892class CaretAnnotationElement extends AnnotationElement {
9893  constructor(parameters) {
9894    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9895    super(parameters, {
9896      isRenderable,
9897      ignoreBorder: true
9898    });
9899  }
9900
9901  render() {
9902    this.container.className = "caretAnnotation";
9903
9904    if (!this.data.hasPopup) {
9905      this._createPopup(null, this.data);
9906    }
9907
9908    return this.container;
9909  }
9910
9911}
9912
9913class InkAnnotationElement extends AnnotationElement {
9914  constructor(parameters) {
9915    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9916    super(parameters, {
9917      isRenderable,
9918      ignoreBorder: true
9919    });
9920    this.containerClassName = "inkAnnotation";
9921    this.svgElementName = "svg:polyline";
9922  }
9923
9924  render() {
9925    this.container.className = this.containerClassName;
9926    const data = this.data;
9927    const width = data.rect[2] - data.rect[0];
9928    const height = data.rect[3] - data.rect[1];
9929    const svg = this.svgFactory.create(width, height);
9930
9931    for (const inkList of data.inkLists) {
9932      let points = [];
9933
9934      for (const coordinate of inkList) {
9935        const x = coordinate.x - data.rect[0];
9936        const y = data.rect[3] - coordinate.y;
9937        points.push(`${x},${y}`);
9938      }
9939
9940      points = points.join(" ");
9941      const polyline = this.svgFactory.createElement(this.svgElementName);
9942      polyline.setAttribute("points", points);
9943      polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
9944      polyline.setAttribute("stroke", "transparent");
9945      polyline.setAttribute("fill", "none");
9946
9947      this._createPopup(polyline, data);
9948
9949      svg.appendChild(polyline);
9950    }
9951
9952    this.container.append(svg);
9953    return this.container;
9954  }
9955
9956}
9957
9958class HighlightAnnotationElement extends AnnotationElement {
9959  constructor(parameters) {
9960    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9961    super(parameters, {
9962      isRenderable,
9963      ignoreBorder: true,
9964      createQuadrilaterals: true
9965    });
9966  }
9967
9968  render() {
9969    if (!this.data.hasPopup) {
9970      this._createPopup(null, this.data);
9971    }
9972
9973    if (this.quadrilaterals) {
9974      return this._renderQuadrilaterals("highlightAnnotation");
9975    }
9976
9977    this.container.className = "highlightAnnotation";
9978    return this.container;
9979  }
9980
9981}
9982
9983class UnderlineAnnotationElement extends AnnotationElement {
9984  constructor(parameters) {
9985    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
9986    super(parameters, {
9987      isRenderable,
9988      ignoreBorder: true,
9989      createQuadrilaterals: true
9990    });
9991  }
9992
9993  render() {
9994    if (!this.data.hasPopup) {
9995      this._createPopup(null, this.data);
9996    }
9997
9998    if (this.quadrilaterals) {
9999      return this._renderQuadrilaterals("underlineAnnotation");
10000    }
10001
10002    this.container.className = "underlineAnnotation";
10003    return this.container;
10004  }
10005
10006}
10007
10008class SquigglyAnnotationElement extends AnnotationElement {
10009  constructor(parameters) {
10010    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
10011    super(parameters, {
10012      isRenderable,
10013      ignoreBorder: true,
10014      createQuadrilaterals: true
10015    });
10016  }
10017
10018  render() {
10019    if (!this.data.hasPopup) {
10020      this._createPopup(null, this.data);
10021    }
10022
10023    if (this.quadrilaterals) {
10024      return this._renderQuadrilaterals("squigglyAnnotation");
10025    }
10026
10027    this.container.className = "squigglyAnnotation";
10028    return this.container;
10029  }
10030
10031}
10032
10033class StrikeOutAnnotationElement extends AnnotationElement {
10034  constructor(parameters) {
10035    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
10036    super(parameters, {
10037      isRenderable,
10038      ignoreBorder: true,
10039      createQuadrilaterals: true
10040    });
10041  }
10042
10043  render() {
10044    if (!this.data.hasPopup) {
10045      this._createPopup(null, this.data);
10046    }
10047
10048    if (this.quadrilaterals) {
10049      return this._renderQuadrilaterals("strikeoutAnnotation");
10050    }
10051
10052    this.container.className = "strikeoutAnnotation";
10053    return this.container;
10054  }
10055
10056}
10057
10058class StampAnnotationElement extends AnnotationElement {
10059  constructor(parameters) {
10060    const isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
10061    super(parameters, {
10062      isRenderable,
10063      ignoreBorder: true
10064    });
10065  }
10066
10067  render() {
10068    this.container.className = "stampAnnotation";
10069
10070    if (!this.data.hasPopup) {
10071      this._createPopup(null, this.data);
10072    }
10073
10074    return this.container;
10075  }
10076
10077}
10078
10079class FileAttachmentAnnotationElement extends AnnotationElement {
10080  constructor(parameters) {
10081    super(parameters, {
10082      isRenderable: true
10083    });
10084    const {
10085      filename,
10086      content
10087    } = this.data.file;
10088    this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
10089    this.content = content;
10090    this.linkService.eventBus?.dispatch("fileattachmentannotation", {
10091      source: this,
10092      id: (0, _util.stringToPDFString)(filename),
10093      filename,
10094      content
10095    });
10096  }
10097
10098  render() {
10099    this.container.className = "fileAttachmentAnnotation";
10100    const trigger = document.createElement("div");
10101    trigger.style.height = this.container.style.height;
10102    trigger.style.width = this.container.style.width;
10103    trigger.addEventListener("dblclick", this._download.bind(this));
10104
10105    if (!this.data.hasPopup && (this.data.title || this.data.contents)) {
10106      this._createPopup(trigger, this.data);
10107    }
10108
10109    this.container.appendChild(trigger);
10110    return this.container;
10111  }
10112
10113  _download() {
10114    this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
10115  }
10116
10117}
10118
10119class AnnotationLayer {
10120  static render(parameters) {
10121    const sortedAnnotations = [],
10122          popupAnnotations = [];
10123
10124    for (const data of parameters.annotations) {
10125      if (!data) {
10126        continue;
10127      }
10128
10129      if (data.annotationType === _util.AnnotationType.POPUP) {
10130        popupAnnotations.push(data);
10131        continue;
10132      }
10133
10134      sortedAnnotations.push(data);
10135    }
10136
10137    if (popupAnnotations.length) {
10138      sortedAnnotations.push(...popupAnnotations);
10139    }
10140
10141    for (const data of sortedAnnotations) {
10142      const element = AnnotationElementFactory.create({
10143        data,
10144        layer: parameters.div,
10145        page: parameters.page,
10146        viewport: parameters.viewport,
10147        linkService: parameters.linkService,
10148        downloadManager: parameters.downloadManager,
10149        imageResourcesPath: parameters.imageResourcesPath || "",
10150        renderInteractiveForms: parameters.renderInteractiveForms !== false,
10151        svgFactory: new _display_utils.DOMSVGFactory(),
10152        annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
10153        enableScripting: parameters.enableScripting,
10154        hasJSActions: parameters.hasJSActions,
10155        mouseState: parameters.mouseState || {
10156          isDown: false
10157        }
10158      });
10159
10160      if (element.isRenderable) {
10161        const rendered = element.render();
10162
10163        if (data.hidden) {
10164          rendered.style.visibility = "hidden";
10165        }
10166
10167        if (Array.isArray(rendered)) {
10168          for (const renderedElement of rendered) {
10169            parameters.div.appendChild(renderedElement);
10170          }
10171        } else {
10172          if (element instanceof PopupAnnotationElement) {
10173            parameters.div.prepend(rendered);
10174          } else {
10175            parameters.div.appendChild(rendered);
10176          }
10177        }
10178      }
10179    }
10180  }
10181
10182  static update(parameters) {
10183    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
10184
10185    for (const data of parameters.annotations) {
10186      const elements = parameters.div.querySelectorAll(`[data-annotation-id="${data.id}"]`);
10187
10188      if (elements) {
10189        for (const element of elements) {
10190          element.style.transform = transform;
10191        }
10192      }
10193    }
10194
10195    parameters.div.hidden = false;
10196  }
10197
10198}
10199
10200exports.AnnotationLayer = AnnotationLayer;
10201
10202/***/ }),
10203/* 18 */
10204/***/ ((__unused_webpack_module, exports) => {
10205
10206
10207
10208Object.defineProperty(exports, "__esModule", ({
10209  value: true
10210}));
10211exports.ColorConverters = void 0;
10212
10213function makeColorComp(n) {
10214  return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
10215}
10216
10217class ColorConverters {
10218  static CMYK_G([c, y, m, k]) {
10219    return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
10220  }
10221
10222  static G_CMYK([g]) {
10223    return ["CMYK", 0, 0, 0, 1 - g];
10224  }
10225
10226  static G_RGB([g]) {
10227    return ["RGB", g, g, g];
10228  }
10229
10230  static G_HTML([g]) {
10231    const G = makeColorComp(g);
10232    return `#${G}${G}${G}`;
10233  }
10234
10235  static RGB_G([r, g, b]) {
10236    return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
10237  }
10238
10239  static RGB_HTML([r, g, b]) {
10240    const R = makeColorComp(r);
10241    const G = makeColorComp(g);
10242    const B = makeColorComp(b);
10243    return `#${R}${G}${B}`;
10244  }
10245
10246  static T_HTML() {
10247    return "#00000000";
10248  }
10249
10250  static CMYK_RGB([c, y, m, k]) {
10251    return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
10252  }
10253
10254  static CMYK_HTML(components) {
10255    return this.RGB_HTML(this.CMYK_RGB(components));
10256  }
10257
10258  static RGB_CMYK([r, g, b]) {
10259    const c = 1 - r;
10260    const m = 1 - g;
10261    const y = 1 - b;
10262    const k = Math.min(c, m, y);
10263    return ["CMYK", c, m, y, k];
10264  }
10265
10266}
10267
10268exports.ColorConverters = ColorConverters;
10269
10270/***/ }),
10271/* 19 */
10272/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
10273
10274
10275
10276Object.defineProperty(exports, "__esModule", ({
10277  value: true
10278}));
10279exports.renderTextLayer = renderTextLayer;
10280
10281var _util = __w_pdfjs_require__(2);
10282
10283const MAX_TEXT_DIVS_TO_RENDER = 100000;
10284const DEFAULT_FONT_SIZE = 30;
10285const DEFAULT_FONT_ASCENT = 0.8;
10286const ascentCache = new Map();
10287const AllWhitespaceRegexp = /^\s+$/g;
10288
10289function getAscent(fontFamily, ctx) {
10290  const cachedAscent = ascentCache.get(fontFamily);
10291
10292  if (cachedAscent) {
10293    return cachedAscent;
10294  }
10295
10296  ctx.save();
10297  ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
10298  const metrics = ctx.measureText("");
10299  let ascent = metrics.fontBoundingBoxAscent;
10300  let descent = Math.abs(metrics.fontBoundingBoxDescent);
10301
10302  if (ascent) {
10303    ctx.restore();
10304    const ratio = ascent / (ascent + descent);
10305    ascentCache.set(fontFamily, ratio);
10306    return ratio;
10307  }
10308
10309  ctx.strokeStyle = "red";
10310  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
10311  ctx.strokeText("g", 0, 0);
10312  let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
10313  descent = 0;
10314
10315  for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
10316    if (pixels[i] > 0) {
10317      descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
10318      break;
10319    }
10320  }
10321
10322  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
10323  ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
10324  pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
10325  ascent = 0;
10326
10327  for (let i = 0, ii = pixels.length; i < ii; i += 4) {
10328    if (pixels[i] > 0) {
10329      ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
10330      break;
10331    }
10332  }
10333
10334  ctx.restore();
10335
10336  if (ascent) {
10337    const ratio = ascent / (ascent + descent);
10338    ascentCache.set(fontFamily, ratio);
10339    return ratio;
10340  }
10341
10342  ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
10343  return DEFAULT_FONT_ASCENT;
10344}
10345
10346function appendText(task, geom, styles, ctx) {
10347  const textDiv = document.createElement("span");
10348  const textDivProperties = {
10349    angle: 0,
10350    canvasWidth: 0,
10351    hasText: geom.str !== "",
10352    hasEOL: geom.hasEOL,
10353    originalTransform: null,
10354    paddingBottom: 0,
10355    paddingLeft: 0,
10356    paddingRight: 0,
10357    paddingTop: 0,
10358    scale: 1
10359  };
10360
10361  task._textDivs.push(textDiv);
10362
10363  const tx = _util.Util.transform(task._viewport.transform, geom.transform);
10364
10365  let angle = Math.atan2(tx[1], tx[0]);
10366  const style = styles[geom.fontName];
10367
10368  if (style.vertical) {
10369    angle += Math.PI / 2;
10370  }
10371
10372  const fontHeight = Math.hypot(tx[2], tx[3]);
10373  const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
10374  let left, top;
10375
10376  if (angle === 0) {
10377    left = tx[4];
10378    top = tx[5] - fontAscent;
10379  } else {
10380    left = tx[4] + fontAscent * Math.sin(angle);
10381    top = tx[5] - fontAscent * Math.cos(angle);
10382  }
10383
10384  textDiv.style.left = `${left}px`;
10385  textDiv.style.top = `${top}px`;
10386  textDiv.style.fontSize = `${fontHeight}px`;
10387  textDiv.style.fontFamily = style.fontFamily;
10388  textDiv.setAttribute("role", "presentation");
10389  textDiv.textContent = geom.str;
10390  textDiv.dir = geom.dir;
10391
10392  if (task._fontInspectorEnabled) {
10393    textDiv.dataset.fontName = geom.fontName;
10394  }
10395
10396  if (angle !== 0) {
10397    textDivProperties.angle = angle * (180 / Math.PI);
10398  }
10399
10400  let shouldScaleText = false;
10401
10402  if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
10403    shouldScaleText = true;
10404  } else if (geom.transform[0] !== geom.transform[3]) {
10405    const absScaleX = Math.abs(geom.transform[0]),
10406          absScaleY = Math.abs(geom.transform[3]);
10407
10408    if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
10409      shouldScaleText = true;
10410    }
10411  }
10412
10413  if (shouldScaleText) {
10414    if (style.vertical) {
10415      textDivProperties.canvasWidth = geom.height * task._viewport.scale;
10416    } else {
10417      textDivProperties.canvasWidth = geom.width * task._viewport.scale;
10418    }
10419  }
10420
10421  task._textDivProperties.set(textDiv, textDivProperties);
10422
10423  if (task._textContentStream) {
10424    task._layoutText(textDiv);
10425  }
10426
10427  if (task._enhanceTextSelection && textDivProperties.hasText) {
10428    let angleCos = 1,
10429        angleSin = 0;
10430
10431    if (angle !== 0) {
10432      angleCos = Math.cos(angle);
10433      angleSin = Math.sin(angle);
10434    }
10435
10436    const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
10437    const divHeight = fontHeight;
10438    let m, b;
10439
10440    if (angle !== 0) {
10441      m = [angleCos, angleSin, -angleSin, angleCos, left, top];
10442      b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
10443    } else {
10444      b = [left, top, left + divWidth, top + divHeight];
10445    }
10446
10447    task._bounds.push({
10448      left: b[0],
10449      top: b[1],
10450      right: b[2],
10451      bottom: b[3],
10452      div: textDiv,
10453      size: [divWidth, divHeight],
10454      m
10455    });
10456  }
10457}
10458
10459function render(task) {
10460  if (task._canceled) {
10461    return;
10462  }
10463
10464  const textDivs = task._textDivs;
10465  const capability = task._capability;
10466  const textDivsLength = textDivs.length;
10467
10468  if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
10469    task._renderingDone = true;
10470    capability.resolve();
10471    return;
10472  }
10473
10474  if (!task._textContentStream) {
10475    for (let i = 0; i < textDivsLength; i++) {
10476      task._layoutText(textDivs[i]);
10477    }
10478  }
10479
10480  task._renderingDone = true;
10481  capability.resolve();
10482}
10483
10484function findPositiveMin(ts, offset, count) {
10485  let result = 0;
10486
10487  for (let i = 0; i < count; i++) {
10488    const t = ts[offset++];
10489
10490    if (t > 0) {
10491      result = result ? Math.min(t, result) : t;
10492    }
10493  }
10494
10495  return result;
10496}
10497
10498function expand(task) {
10499  const bounds = task._bounds;
10500  const viewport = task._viewport;
10501  const expanded = expandBounds(viewport.width, viewport.height, bounds);
10502
10503  for (let i = 0; i < expanded.length; i++) {
10504    const div = bounds[i].div;
10505
10506    const divProperties = task._textDivProperties.get(div);
10507
10508    if (divProperties.angle === 0) {
10509      divProperties.paddingLeft = bounds[i].left - expanded[i].left;
10510      divProperties.paddingTop = bounds[i].top - expanded[i].top;
10511      divProperties.paddingRight = expanded[i].right - bounds[i].right;
10512      divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
10513
10514      task._textDivProperties.set(div, divProperties);
10515
10516      continue;
10517    }
10518
10519    const e = expanded[i],
10520          b = bounds[i];
10521    const m = b.m,
10522          c = m[0],
10523          s = m[1];
10524    const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
10525    const ts = new Float64Array(64);
10526
10527    for (let j = 0, jj = points.length; j < jj; j++) {
10528      const t = _util.Util.applyTransform(points[j], m);
10529
10530      ts[j + 0] = c && (e.left - t[0]) / c;
10531      ts[j + 4] = s && (e.top - t[1]) / s;
10532      ts[j + 8] = c && (e.right - t[0]) / c;
10533      ts[j + 12] = s && (e.bottom - t[1]) / s;
10534      ts[j + 16] = s && (e.left - t[0]) / -s;
10535      ts[j + 20] = c && (e.top - t[1]) / c;
10536      ts[j + 24] = s && (e.right - t[0]) / -s;
10537      ts[j + 28] = c && (e.bottom - t[1]) / c;
10538      ts[j + 32] = c && (e.left - t[0]) / -c;
10539      ts[j + 36] = s && (e.top - t[1]) / -s;
10540      ts[j + 40] = c && (e.right - t[0]) / -c;
10541      ts[j + 44] = s && (e.bottom - t[1]) / -s;
10542      ts[j + 48] = s && (e.left - t[0]) / s;
10543      ts[j + 52] = c && (e.top - t[1]) / -c;
10544      ts[j + 56] = s && (e.right - t[0]) / s;
10545      ts[j + 60] = c && (e.bottom - t[1]) / -c;
10546    }
10547
10548    const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
10549    divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
10550    divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
10551    divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
10552    divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
10553
10554    task._textDivProperties.set(div, divProperties);
10555  }
10556}
10557
10558function expandBounds(width, height, boxes) {
10559  const bounds = boxes.map(function (box, i) {
10560    return {
10561      x1: box.left,
10562      y1: box.top,
10563      x2: box.right,
10564      y2: box.bottom,
10565      index: i,
10566      x1New: undefined,
10567      x2New: undefined
10568    };
10569  });
10570  expandBoundsLTR(width, bounds);
10571  const expanded = new Array(boxes.length);
10572
10573  for (const b of bounds) {
10574    const i = b.index;
10575    expanded[i] = {
10576      left: b.x1New,
10577      top: 0,
10578      right: b.x2New,
10579      bottom: 0
10580    };
10581  }
10582
10583  boxes.map(function (box, i) {
10584    const e = expanded[i],
10585          b = bounds[i];
10586    b.x1 = box.top;
10587    b.y1 = width - e.right;
10588    b.x2 = box.bottom;
10589    b.y2 = width - e.left;
10590    b.index = i;
10591    b.x1New = undefined;
10592    b.x2New = undefined;
10593  });
10594  expandBoundsLTR(height, bounds);
10595
10596  for (const b of bounds) {
10597    const i = b.index;
10598    expanded[i].top = b.x1New;
10599    expanded[i].bottom = b.x2New;
10600  }
10601
10602  return expanded;
10603}
10604
10605function expandBoundsLTR(width, bounds) {
10606  bounds.sort(function (a, b) {
10607    return a.x1 - b.x1 || a.index - b.index;
10608  });
10609  const fakeBoundary = {
10610    x1: -Infinity,
10611    y1: -Infinity,
10612    x2: 0,
10613    y2: Infinity,
10614    index: -1,
10615    x1New: 0,
10616    x2New: 0
10617  };
10618  const horizon = [{
10619    start: -Infinity,
10620    end: Infinity,
10621    boundary: fakeBoundary
10622  }];
10623
10624  for (const boundary of bounds) {
10625    let i = 0;
10626
10627    while (i < horizon.length && horizon[i].end <= boundary.y1) {
10628      i++;
10629    }
10630
10631    let j = horizon.length - 1;
10632
10633    while (j >= 0 && horizon[j].start >= boundary.y2) {
10634      j--;
10635    }
10636
10637    let horizonPart, affectedBoundary;
10638    let q,
10639        k,
10640        maxXNew = -Infinity;
10641
10642    for (q = i; q <= j; q++) {
10643      horizonPart = horizon[q];
10644      affectedBoundary = horizonPart.boundary;
10645      let xNew;
10646
10647      if (affectedBoundary.x2 > boundary.x1) {
10648        xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
10649      } else if (affectedBoundary.x2New === undefined) {
10650        xNew = (affectedBoundary.x2 + boundary.x1) / 2;
10651      } else {
10652        xNew = affectedBoundary.x2New;
10653      }
10654
10655      if (xNew > maxXNew) {
10656        maxXNew = xNew;
10657      }
10658    }
10659
10660    boundary.x1New = maxXNew;
10661
10662    for (q = i; q <= j; q++) {
10663      horizonPart = horizon[q];
10664      affectedBoundary = horizonPart.boundary;
10665
10666      if (affectedBoundary.x2New === undefined) {
10667        if (affectedBoundary.x2 > boundary.x1) {
10668          if (affectedBoundary.index > boundary.index) {
10669            affectedBoundary.x2New = affectedBoundary.x2;
10670          }
10671        } else {
10672          affectedBoundary.x2New = maxXNew;
10673        }
10674      } else if (affectedBoundary.x2New > maxXNew) {
10675        affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
10676      }
10677    }
10678
10679    const changedHorizon = [];
10680    let lastBoundary = null;
10681
10682    for (q = i; q <= j; q++) {
10683      horizonPart = horizon[q];
10684      affectedBoundary = horizonPart.boundary;
10685      const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
10686
10687      if (lastBoundary === useBoundary) {
10688        changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
10689      } else {
10690        changedHorizon.push({
10691          start: horizonPart.start,
10692          end: horizonPart.end,
10693          boundary: useBoundary
10694        });
10695        lastBoundary = useBoundary;
10696      }
10697    }
10698
10699    if (horizon[i].start < boundary.y1) {
10700      changedHorizon[0].start = boundary.y1;
10701      changedHorizon.unshift({
10702        start: horizon[i].start,
10703        end: boundary.y1,
10704        boundary: horizon[i].boundary
10705      });
10706    }
10707
10708    if (boundary.y2 < horizon[j].end) {
10709      changedHorizon[changedHorizon.length - 1].end = boundary.y2;
10710      changedHorizon.push({
10711        start: boundary.y2,
10712        end: horizon[j].end,
10713        boundary: horizon[j].boundary
10714      });
10715    }
10716
10717    for (q = i; q <= j; q++) {
10718      horizonPart = horizon[q];
10719      affectedBoundary = horizonPart.boundary;
10720
10721      if (affectedBoundary.x2New !== undefined) {
10722        continue;
10723      }
10724
10725      let used = false;
10726
10727      for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
10728        used = horizon[k].boundary === affectedBoundary;
10729      }
10730
10731      for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
10732        used = horizon[k].boundary === affectedBoundary;
10733      }
10734
10735      for (k = 0; !used && k < changedHorizon.length; k++) {
10736        used = changedHorizon[k].boundary === affectedBoundary;
10737      }
10738
10739      if (!used) {
10740        affectedBoundary.x2New = maxXNew;
10741      }
10742    }
10743
10744    Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
10745  }
10746
10747  for (const horizonPart of horizon) {
10748    const affectedBoundary = horizonPart.boundary;
10749
10750    if (affectedBoundary.x2New === undefined) {
10751      affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
10752    }
10753  }
10754}
10755
10756class TextLayerRenderTask {
10757  constructor({
10758    textContent,
10759    textContentStream,
10760    container,
10761    viewport,
10762    textDivs,
10763    textContentItemsStr,
10764    enhanceTextSelection
10765  }) {
10766    this._textContent = textContent;
10767    this._textContentStream = textContentStream;
10768    this._container = container;
10769    this._document = container.ownerDocument;
10770    this._viewport = viewport;
10771    this._textDivs = textDivs || [];
10772    this._textContentItemsStr = textContentItemsStr || [];
10773    this._enhanceTextSelection = !!enhanceTextSelection;
10774    this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
10775    this._reader = null;
10776    this._layoutTextLastFontSize = null;
10777    this._layoutTextLastFontFamily = null;
10778    this._layoutTextCtx = null;
10779    this._textDivProperties = new WeakMap();
10780    this._renderingDone = false;
10781    this._canceled = false;
10782    this._capability = (0, _util.createPromiseCapability)();
10783    this._renderTimer = null;
10784    this._bounds = [];
10785
10786    this._capability.promise.finally(() => {
10787      if (this._layoutTextCtx) {
10788        this._layoutTextCtx.canvas.width = 0;
10789        this._layoutTextCtx.canvas.height = 0;
10790        this._layoutTextCtx = null;
10791      }
10792    }).catch(() => {});
10793  }
10794
10795  get promise() {
10796    return this._capability.promise;
10797  }
10798
10799  cancel() {
10800    this._canceled = true;
10801
10802    if (this._reader) {
10803      this._reader.cancel(new _util.AbortException("TextLayer task cancelled."));
10804
10805      this._reader = null;
10806    }
10807
10808    if (this._renderTimer !== null) {
10809      clearTimeout(this._renderTimer);
10810      this._renderTimer = null;
10811    }
10812
10813    this._capability.reject(new Error("TextLayer task cancelled."));
10814  }
10815
10816  _processItems(items, styleCache) {
10817    for (let i = 0, len = items.length; i < len; i++) {
10818      if (items[i].str === undefined) {
10819        if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
10820          const parent = this._container;
10821          this._container = document.createElement("span");
10822
10823          this._container.classList.add("markedContent");
10824
10825          if (items[i].id !== null) {
10826            this._container.setAttribute("id", `${items[i].id}`);
10827          }
10828
10829          parent.appendChild(this._container);
10830        } else if (items[i].type === "endMarkedContent") {
10831          this._container = this._container.parentNode;
10832        }
10833
10834        continue;
10835      }
10836
10837      this._textContentItemsStr.push(items[i].str);
10838
10839      appendText(this, items[i], styleCache, this._layoutTextCtx);
10840    }
10841  }
10842
10843  _layoutText(textDiv) {
10844    const textDivProperties = this._textDivProperties.get(textDiv);
10845
10846    let transform = "";
10847
10848    if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
10849      const {
10850        fontSize,
10851        fontFamily
10852      } = textDiv.style;
10853
10854      if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
10855        this._layoutTextCtx.font = `${fontSize} ${fontFamily}`;
10856        this._layoutTextLastFontSize = fontSize;
10857        this._layoutTextLastFontFamily = fontFamily;
10858      }
10859
10860      const {
10861        width
10862      } = this._layoutTextCtx.measureText(textDiv.textContent);
10863
10864      if (width > 0) {
10865        textDivProperties.scale = textDivProperties.canvasWidth / width;
10866        transform = `scaleX(${textDivProperties.scale})`;
10867      }
10868    }
10869
10870    if (textDivProperties.angle !== 0) {
10871      transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
10872    }
10873
10874    if (transform.length > 0) {
10875      if (this._enhanceTextSelection) {
10876        textDivProperties.originalTransform = transform;
10877      }
10878
10879      textDiv.style.transform = transform;
10880    }
10881
10882    if (textDivProperties.hasText) {
10883      this._container.appendChild(textDiv);
10884    }
10885
10886    if (textDivProperties.hasEOL) {
10887      const br = document.createElement("br");
10888      br.setAttribute("role", "presentation");
10889
10890      this._container.appendChild(br);
10891    }
10892  }
10893
10894  _render(timeout = 0) {
10895    const capability = (0, _util.createPromiseCapability)();
10896    let styleCache = Object.create(null);
10897
10898    const canvas = this._document.createElement("canvas");
10899
10900    canvas.height = canvas.width = DEFAULT_FONT_SIZE;
10901    canvas.mozOpaque = true;
10902    this._layoutTextCtx = canvas.getContext("2d", {
10903      alpha: false
10904    });
10905
10906    if (this._textContent) {
10907      const textItems = this._textContent.items;
10908      const textStyles = this._textContent.styles;
10909
10910      this._processItems(textItems, textStyles);
10911
10912      capability.resolve();
10913    } else if (this._textContentStream) {
10914      const pump = () => {
10915        this._reader.read().then(({
10916          value,
10917          done
10918        }) => {
10919          if (done) {
10920            capability.resolve();
10921            return;
10922          }
10923
10924          Object.assign(styleCache, value.styles);
10925
10926          this._processItems(value.items, styleCache);
10927
10928          pump();
10929        }, capability.reject);
10930      };
10931
10932      this._reader = this._textContentStream.getReader();
10933      pump();
10934    } else {
10935      throw new Error('Neither "textContent" nor "textContentStream"' + " parameters specified.");
10936    }
10937
10938    capability.promise.then(() => {
10939      styleCache = null;
10940
10941      if (!timeout) {
10942        render(this);
10943      } else {
10944        this._renderTimer = setTimeout(() => {
10945          render(this);
10946          this._renderTimer = null;
10947        }, timeout);
10948      }
10949    }, this._capability.reject);
10950  }
10951
10952  expandTextDivs(expandDivs = false) {
10953    if (!this._enhanceTextSelection || !this._renderingDone) {
10954      return;
10955    }
10956
10957    if (this._bounds !== null) {
10958      expand(this);
10959      this._bounds = null;
10960    }
10961
10962    const transformBuf = [],
10963          paddingBuf = [];
10964
10965    for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
10966      const div = this._textDivs[i];
10967
10968      const divProps = this._textDivProperties.get(div);
10969
10970      if (!divProps.hasText) {
10971        continue;
10972      }
10973
10974      if (expandDivs) {
10975        transformBuf.length = 0;
10976        paddingBuf.length = 0;
10977
10978        if (divProps.originalTransform) {
10979          transformBuf.push(divProps.originalTransform);
10980        }
10981
10982        if (divProps.paddingTop > 0) {
10983          paddingBuf.push(`${divProps.paddingTop}px`);
10984          transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
10985        } else {
10986          paddingBuf.push(0);
10987        }
10988
10989        if (divProps.paddingRight > 0) {
10990          paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
10991        } else {
10992          paddingBuf.push(0);
10993        }
10994
10995        if (divProps.paddingBottom > 0) {
10996          paddingBuf.push(`${divProps.paddingBottom}px`);
10997        } else {
10998          paddingBuf.push(0);
10999        }
11000
11001        if (divProps.paddingLeft > 0) {
11002          paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
11003          transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
11004        } else {
11005          paddingBuf.push(0);
11006        }
11007
11008        div.style.padding = paddingBuf.join(" ");
11009
11010        if (transformBuf.length) {
11011          div.style.transform = transformBuf.join(" ");
11012        }
11013      } else {
11014        div.style.padding = null;
11015        div.style.transform = divProps.originalTransform;
11016      }
11017    }
11018  }
11019
11020}
11021
11022function renderTextLayer(renderParameters) {
11023  const task = new TextLayerRenderTask({
11024    textContent: renderParameters.textContent,
11025    textContentStream: renderParameters.textContentStream,
11026    container: renderParameters.container,
11027    viewport: renderParameters.viewport,
11028    textDivs: renderParameters.textDivs,
11029    textContentItemsStr: renderParameters.textContentItemsStr,
11030    enhanceTextSelection: renderParameters.enhanceTextSelection
11031  });
11032
11033  task._render(renderParameters.timeout);
11034
11035  return task;
11036}
11037
11038/***/ }),
11039/* 20 */
11040/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11041
11042
11043
11044Object.defineProperty(exports, "__esModule", ({
11045  value: true
11046}));
11047exports.SVGGraphics = void 0;
11048
11049var _util = __w_pdfjs_require__(2);
11050
11051var _display_utils = __w_pdfjs_require__(1);
11052
11053var _is_node = __w_pdfjs_require__(4);
11054
11055let SVGGraphics = class {
11056  constructor() {
11057    (0, _util.unreachable)("Not implemented: SVGGraphics");
11058  }
11059
11060};
11061exports.SVGGraphics = SVGGraphics;
11062{
11063  const SVG_DEFAULTS = {
11064    fontStyle: "normal",
11065    fontWeight: "normal",
11066    fillColor: "#000000"
11067  };
11068  const XML_NS = "http://www.w3.org/XML/1998/namespace";
11069  const XLINK_NS = "http://www.w3.org/1999/xlink";
11070  const LINE_CAP_STYLES = ["butt", "round", "square"];
11071  const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
11072
11073  const convertImgDataToPng = function () {
11074    const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
11075    const CHUNK_WRAPPER_SIZE = 12;
11076    const crcTable = new Int32Array(256);
11077
11078    for (let i = 0; i < 256; i++) {
11079      let c = i;
11080
11081      for (let h = 0; h < 8; h++) {
11082        if (c & 1) {
11083          c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
11084        } else {
11085          c = c >> 1 & 0x7fffffff;
11086        }
11087      }
11088
11089      crcTable[i] = c;
11090    }
11091
11092    function crc32(data, start, end) {
11093      let crc = -1;
11094
11095      for (let i = start; i < end; i++) {
11096        const a = (crc ^ data[i]) & 0xff;
11097        const b = crcTable[a];
11098        crc = crc >>> 8 ^ b;
11099      }
11100
11101      return crc ^ -1;
11102    }
11103
11104    function writePngChunk(type, body, data, offset) {
11105      let p = offset;
11106      const len = body.length;
11107      data[p] = len >> 24 & 0xff;
11108      data[p + 1] = len >> 16 & 0xff;
11109      data[p + 2] = len >> 8 & 0xff;
11110      data[p + 3] = len & 0xff;
11111      p += 4;
11112      data[p] = type.charCodeAt(0) & 0xff;
11113      data[p + 1] = type.charCodeAt(1) & 0xff;
11114      data[p + 2] = type.charCodeAt(2) & 0xff;
11115      data[p + 3] = type.charCodeAt(3) & 0xff;
11116      p += 4;
11117      data.set(body, p);
11118      p += body.length;
11119      const crc = crc32(data, offset + 4, p);
11120      data[p] = crc >> 24 & 0xff;
11121      data[p + 1] = crc >> 16 & 0xff;
11122      data[p + 2] = crc >> 8 & 0xff;
11123      data[p + 3] = crc & 0xff;
11124    }
11125
11126    function adler32(data, start, end) {
11127      let a = 1;
11128      let b = 0;
11129
11130      for (let i = start; i < end; ++i) {
11131        a = (a + (data[i] & 0xff)) % 65521;
11132        b = (b + a) % 65521;
11133      }
11134
11135      return b << 16 | a;
11136    }
11137
11138    function deflateSync(literals) {
11139      if (!_is_node.isNodeJS) {
11140        return deflateSyncUncompressed(literals);
11141      }
11142
11143      try {
11144        let input;
11145
11146        if (parseInt(process.versions.node) >= 8) {
11147          input = literals;
11148        } else {
11149          input = Buffer.from(literals);
11150        }
11151
11152        const output = require("zlib").deflateSync(input, {
11153          level: 9
11154        });
11155
11156        return output instanceof Uint8Array ? output : new Uint8Array(output);
11157      } catch (e) {
11158        (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
11159      }
11160
11161      return deflateSyncUncompressed(literals);
11162    }
11163
11164    function deflateSyncUncompressed(literals) {
11165      let len = literals.length;
11166      const maxBlockLength = 0xffff;
11167      const deflateBlocks = Math.ceil(len / maxBlockLength);
11168      const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
11169      let pi = 0;
11170      idat[pi++] = 0x78;
11171      idat[pi++] = 0x9c;
11172      let pos = 0;
11173
11174      while (len > maxBlockLength) {
11175        idat[pi++] = 0x00;
11176        idat[pi++] = 0xff;
11177        idat[pi++] = 0xff;
11178        idat[pi++] = 0x00;
11179        idat[pi++] = 0x00;
11180        idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
11181        pi += maxBlockLength;
11182        pos += maxBlockLength;
11183        len -= maxBlockLength;
11184      }
11185
11186      idat[pi++] = 0x01;
11187      idat[pi++] = len & 0xff;
11188      idat[pi++] = len >> 8 & 0xff;
11189      idat[pi++] = ~len & 0xffff & 0xff;
11190      idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
11191      idat.set(literals.subarray(pos), pi);
11192      pi += literals.length - pos;
11193      const adler = adler32(literals, 0, literals.length);
11194      idat[pi++] = adler >> 24 & 0xff;
11195      idat[pi++] = adler >> 16 & 0xff;
11196      idat[pi++] = adler >> 8 & 0xff;
11197      idat[pi++] = adler & 0xff;
11198      return idat;
11199    }
11200
11201    function encode(imgData, kind, forceDataSchema, isMask) {
11202      const width = imgData.width;
11203      const height = imgData.height;
11204      let bitDepth, colorType, lineSize;
11205      const bytes = imgData.data;
11206
11207      switch (kind) {
11208        case _util.ImageKind.GRAYSCALE_1BPP:
11209          colorType = 0;
11210          bitDepth = 1;
11211          lineSize = width + 7 >> 3;
11212          break;
11213
11214        case _util.ImageKind.RGB_24BPP:
11215          colorType = 2;
11216          bitDepth = 8;
11217          lineSize = width * 3;
11218          break;
11219
11220        case _util.ImageKind.RGBA_32BPP:
11221          colorType = 6;
11222          bitDepth = 8;
11223          lineSize = width * 4;
11224          break;
11225
11226        default:
11227          throw new Error("invalid format");
11228      }
11229
11230      const literals = new Uint8Array((1 + lineSize) * height);
11231      let offsetLiterals = 0,
11232          offsetBytes = 0;
11233
11234      for (let y = 0; y < height; ++y) {
11235        literals[offsetLiterals++] = 0;
11236        literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
11237        offsetBytes += lineSize;
11238        offsetLiterals += lineSize;
11239      }
11240
11241      if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
11242        offsetLiterals = 0;
11243
11244        for (let y = 0; y < height; y++) {
11245          offsetLiterals++;
11246
11247          for (let i = 0; i < lineSize; i++) {
11248            literals[offsetLiterals++] ^= 0xff;
11249          }
11250        }
11251      }
11252
11253      const ihdr = new Uint8Array([width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, colorType, 0x00, 0x00, 0x00]);
11254      const idat = deflateSync(literals);
11255      const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
11256      const data = new Uint8Array(pngLength);
11257      let offset = 0;
11258      data.set(PNG_HEADER, offset);
11259      offset += PNG_HEADER.length;
11260      writePngChunk("IHDR", ihdr, data, offset);
11261      offset += CHUNK_WRAPPER_SIZE + ihdr.length;
11262      writePngChunk("IDATA", idat, data, offset);
11263      offset += CHUNK_WRAPPER_SIZE + idat.length;
11264      writePngChunk("IEND", new Uint8Array(0), data, offset);
11265      return (0, _util.createObjectURL)(data, "image/png", forceDataSchema);
11266    }
11267
11268    return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
11269      const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
11270      return encode(imgData, kind, forceDataSchema, isMask);
11271    };
11272  }();
11273
11274  class SVGExtraState {
11275    constructor() {
11276      this.fontSizeScale = 1;
11277      this.fontWeight = SVG_DEFAULTS.fontWeight;
11278      this.fontSize = 0;
11279      this.textMatrix = _util.IDENTITY_MATRIX;
11280      this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
11281      this.leading = 0;
11282      this.textRenderingMode = _util.TextRenderingMode.FILL;
11283      this.textMatrixScale = 1;
11284      this.x = 0;
11285      this.y = 0;
11286      this.lineX = 0;
11287      this.lineY = 0;
11288      this.charSpacing = 0;
11289      this.wordSpacing = 0;
11290      this.textHScale = 1;
11291      this.textRise = 0;
11292      this.fillColor = SVG_DEFAULTS.fillColor;
11293      this.strokeColor = "#000000";
11294      this.fillAlpha = 1;
11295      this.strokeAlpha = 1;
11296      this.lineWidth = 1;
11297      this.lineJoin = "";
11298      this.lineCap = "";
11299      this.miterLimit = 0;
11300      this.dashArray = [];
11301      this.dashPhase = 0;
11302      this.dependencies = [];
11303      this.activeClipUrl = null;
11304      this.clipGroup = null;
11305      this.maskId = "";
11306    }
11307
11308    clone() {
11309      return Object.create(this);
11310    }
11311
11312    setCurrentPoint(x, y) {
11313      this.x = x;
11314      this.y = y;
11315    }
11316
11317  }
11318
11319  function opListToTree(opList) {
11320    let opTree = [];
11321    const tmp = [];
11322
11323    for (const opListElement of opList) {
11324      if (opListElement.fn === "save") {
11325        opTree.push({
11326          fnId: 92,
11327          fn: "group",
11328          items: []
11329        });
11330        tmp.push(opTree);
11331        opTree = opTree[opTree.length - 1].items;
11332        continue;
11333      }
11334
11335      if (opListElement.fn === "restore") {
11336        opTree = tmp.pop();
11337      } else {
11338        opTree.push(opListElement);
11339      }
11340    }
11341
11342    return opTree;
11343  }
11344
11345  function pf(value) {
11346    if (Number.isInteger(value)) {
11347      return value.toString();
11348    }
11349
11350    const s = value.toFixed(10);
11351    let i = s.length - 1;
11352
11353    if (s[i] !== "0") {
11354      return s;
11355    }
11356
11357    do {
11358      i--;
11359    } while (s[i] === "0");
11360
11361    return s.substring(0, s[i] === "." ? i : i + 1);
11362  }
11363
11364  function pm(m) {
11365    if (m[4] === 0 && m[5] === 0) {
11366      if (m[1] === 0 && m[2] === 0) {
11367        if (m[0] === 1 && m[3] === 1) {
11368          return "";
11369        }
11370
11371        return `scale(${pf(m[0])} ${pf(m[3])})`;
11372      }
11373
11374      if (m[0] === m[3] && m[1] === -m[2]) {
11375        const a = Math.acos(m[0]) * 180 / Math.PI;
11376        return `rotate(${pf(a)})`;
11377      }
11378    } else {
11379      if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
11380        return `translate(${pf(m[4])} ${pf(m[5])})`;
11381      }
11382    }
11383
11384    return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
11385  }
11386
11387  let clipCount = 0;
11388  let maskCount = 0;
11389  let shadingCount = 0;
11390  exports.SVGGraphics = SVGGraphics = class {
11391    constructor(commonObjs, objs, forceDataSchema = false) {
11392      this.svgFactory = new _display_utils.DOMSVGFactory();
11393      this.current = new SVGExtraState();
11394      this.transformMatrix = _util.IDENTITY_MATRIX;
11395      this.transformStack = [];
11396      this.extraStack = [];
11397      this.commonObjs = commonObjs;
11398      this.objs = objs;
11399      this.pendingClip = null;
11400      this.pendingEOFill = false;
11401      this.embedFonts = false;
11402      this.embeddedFonts = Object.create(null);
11403      this.cssStyle = null;
11404      this.forceDataSchema = !!forceDataSchema;
11405      this._operatorIdMapping = [];
11406
11407      for (const op in _util.OPS) {
11408        this._operatorIdMapping[_util.OPS[op]] = op;
11409      }
11410    }
11411
11412    save() {
11413      this.transformStack.push(this.transformMatrix);
11414      const old = this.current;
11415      this.extraStack.push(old);
11416      this.current = old.clone();
11417    }
11418
11419    restore() {
11420      this.transformMatrix = this.transformStack.pop();
11421      this.current = this.extraStack.pop();
11422      this.pendingClip = null;
11423      this.tgrp = null;
11424    }
11425
11426    group(items) {
11427      this.save();
11428      this.executeOpTree(items);
11429      this.restore();
11430    }
11431
11432    loadDependencies(operatorList) {
11433      const fnArray = operatorList.fnArray;
11434      const argsArray = operatorList.argsArray;
11435
11436      for (let i = 0, ii = fnArray.length; i < ii; i++) {
11437        if (fnArray[i] !== _util.OPS.dependency) {
11438          continue;
11439        }
11440
11441        for (const obj of argsArray[i]) {
11442          const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
11443          const promise = new Promise(resolve => {
11444            objsPool.get(obj, resolve);
11445          });
11446          this.current.dependencies.push(promise);
11447        }
11448      }
11449
11450      return Promise.all(this.current.dependencies);
11451    }
11452
11453    transform(a, b, c, d, e, f) {
11454      const transformMatrix = [a, b, c, d, e, f];
11455      this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
11456      this.tgrp = null;
11457    }
11458
11459    getSVG(operatorList, viewport) {
11460      this.viewport = viewport;
11461
11462      const svgElement = this._initialize(viewport);
11463
11464      return this.loadDependencies(operatorList).then(() => {
11465        this.transformMatrix = _util.IDENTITY_MATRIX;
11466        this.executeOpTree(this.convertOpList(operatorList));
11467        return svgElement;
11468      });
11469    }
11470
11471    convertOpList(operatorList) {
11472      const operatorIdMapping = this._operatorIdMapping;
11473      const argsArray = operatorList.argsArray;
11474      const fnArray = operatorList.fnArray;
11475      const opList = [];
11476
11477      for (let i = 0, ii = fnArray.length; i < ii; i++) {
11478        const fnId = fnArray[i];
11479        opList.push({
11480          fnId,
11481          fn: operatorIdMapping[fnId],
11482          args: argsArray[i]
11483        });
11484      }
11485
11486      return opListToTree(opList);
11487    }
11488
11489    executeOpTree(opTree) {
11490      for (const opTreeElement of opTree) {
11491        const fn = opTreeElement.fn;
11492        const fnId = opTreeElement.fnId;
11493        const args = opTreeElement.args;
11494
11495        switch (fnId | 0) {
11496          case _util.OPS.beginText:
11497            this.beginText();
11498            break;
11499
11500          case _util.OPS.dependency:
11501            break;
11502
11503          case _util.OPS.setLeading:
11504            this.setLeading(args);
11505            break;
11506
11507          case _util.OPS.setLeadingMoveText:
11508            this.setLeadingMoveText(args[0], args[1]);
11509            break;
11510
11511          case _util.OPS.setFont:
11512            this.setFont(args);
11513            break;
11514
11515          case _util.OPS.showText:
11516            this.showText(args[0]);
11517            break;
11518
11519          case _util.OPS.showSpacedText:
11520            this.showText(args[0]);
11521            break;
11522
11523          case _util.OPS.endText:
11524            this.endText();
11525            break;
11526
11527          case _util.OPS.moveText:
11528            this.moveText(args[0], args[1]);
11529            break;
11530
11531          case _util.OPS.setCharSpacing:
11532            this.setCharSpacing(args[0]);
11533            break;
11534
11535          case _util.OPS.setWordSpacing:
11536            this.setWordSpacing(args[0]);
11537            break;
11538
11539          case _util.OPS.setHScale:
11540            this.setHScale(args[0]);
11541            break;
11542
11543          case _util.OPS.setTextMatrix:
11544            this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
11545            break;
11546
11547          case _util.OPS.setTextRise:
11548            this.setTextRise(args[0]);
11549            break;
11550
11551          case _util.OPS.setTextRenderingMode:
11552            this.setTextRenderingMode(args[0]);
11553            break;
11554
11555          case _util.OPS.setLineWidth:
11556            this.setLineWidth(args[0]);
11557            break;
11558
11559          case _util.OPS.setLineJoin:
11560            this.setLineJoin(args[0]);
11561            break;
11562
11563          case _util.OPS.setLineCap:
11564            this.setLineCap(args[0]);
11565            break;
11566
11567          case _util.OPS.setMiterLimit:
11568            this.setMiterLimit(args[0]);
11569            break;
11570
11571          case _util.OPS.setFillRGBColor:
11572            this.setFillRGBColor(args[0], args[1], args[2]);
11573            break;
11574
11575          case _util.OPS.setStrokeRGBColor:
11576            this.setStrokeRGBColor(args[0], args[1], args[2]);
11577            break;
11578
11579          case _util.OPS.setStrokeColorN:
11580            this.setStrokeColorN(args);
11581            break;
11582
11583          case _util.OPS.setFillColorN:
11584            this.setFillColorN(args);
11585            break;
11586
11587          case _util.OPS.shadingFill:
11588            this.shadingFill(args[0]);
11589            break;
11590
11591          case _util.OPS.setDash:
11592            this.setDash(args[0], args[1]);
11593            break;
11594
11595          case _util.OPS.setRenderingIntent:
11596            this.setRenderingIntent(args[0]);
11597            break;
11598
11599          case _util.OPS.setFlatness:
11600            this.setFlatness(args[0]);
11601            break;
11602
11603          case _util.OPS.setGState:
11604            this.setGState(args[0]);
11605            break;
11606
11607          case _util.OPS.fill:
11608            this.fill();
11609            break;
11610
11611          case _util.OPS.eoFill:
11612            this.eoFill();
11613            break;
11614
11615          case _util.OPS.stroke:
11616            this.stroke();
11617            break;
11618
11619          case _util.OPS.fillStroke:
11620            this.fillStroke();
11621            break;
11622
11623          case _util.OPS.eoFillStroke:
11624            this.eoFillStroke();
11625            break;
11626
11627          case _util.OPS.clip:
11628            this.clip("nonzero");
11629            break;
11630
11631          case _util.OPS.eoClip:
11632            this.clip("evenodd");
11633            break;
11634
11635          case _util.OPS.paintSolidColorImageMask:
11636            this.paintSolidColorImageMask();
11637            break;
11638
11639          case _util.OPS.paintImageXObject:
11640            this.paintImageXObject(args[0]);
11641            break;
11642
11643          case _util.OPS.paintInlineImageXObject:
11644            this.paintInlineImageXObject(args[0]);
11645            break;
11646
11647          case _util.OPS.paintImageMaskXObject:
11648            this.paintImageMaskXObject(args[0]);
11649            break;
11650
11651          case _util.OPS.paintFormXObjectBegin:
11652            this.paintFormXObjectBegin(args[0], args[1]);
11653            break;
11654
11655          case _util.OPS.paintFormXObjectEnd:
11656            this.paintFormXObjectEnd();
11657            break;
11658
11659          case _util.OPS.closePath:
11660            this.closePath();
11661            break;
11662
11663          case _util.OPS.closeStroke:
11664            this.closeStroke();
11665            break;
11666
11667          case _util.OPS.closeFillStroke:
11668            this.closeFillStroke();
11669            break;
11670
11671          case _util.OPS.closeEOFillStroke:
11672            this.closeEOFillStroke();
11673            break;
11674
11675          case _util.OPS.nextLine:
11676            this.nextLine();
11677            break;
11678
11679          case _util.OPS.transform:
11680            this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
11681            break;
11682
11683          case _util.OPS.constructPath:
11684            this.constructPath(args[0], args[1]);
11685            break;
11686
11687          case _util.OPS.endPath:
11688            this.endPath();
11689            break;
11690
11691          case 92:
11692            this.group(opTreeElement.items);
11693            break;
11694
11695          default:
11696            (0, _util.warn)(`Unimplemented operator ${fn}`);
11697            break;
11698        }
11699      }
11700    }
11701
11702    setWordSpacing(wordSpacing) {
11703      this.current.wordSpacing = wordSpacing;
11704    }
11705
11706    setCharSpacing(charSpacing) {
11707      this.current.charSpacing = charSpacing;
11708    }
11709
11710    nextLine() {
11711      this.moveText(0, this.current.leading);
11712    }
11713
11714    setTextMatrix(a, b, c, d, e, f) {
11715      const current = this.current;
11716      current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
11717      current.textMatrixScale = Math.hypot(a, b);
11718      current.x = current.lineX = 0;
11719      current.y = current.lineY = 0;
11720      current.xcoords = [];
11721      current.ycoords = [];
11722      current.tspan = this.svgFactory.createElement("svg:tspan");
11723      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
11724      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
11725      current.tspan.setAttributeNS(null, "y", pf(-current.y));
11726      current.txtElement = this.svgFactory.createElement("svg:text");
11727      current.txtElement.appendChild(current.tspan);
11728    }
11729
11730    beginText() {
11731      const current = this.current;
11732      current.x = current.lineX = 0;
11733      current.y = current.lineY = 0;
11734      current.textMatrix = _util.IDENTITY_MATRIX;
11735      current.lineMatrix = _util.IDENTITY_MATRIX;
11736      current.textMatrixScale = 1;
11737      current.tspan = this.svgFactory.createElement("svg:tspan");
11738      current.txtElement = this.svgFactory.createElement("svg:text");
11739      current.txtgrp = this.svgFactory.createElement("svg:g");
11740      current.xcoords = [];
11741      current.ycoords = [];
11742    }
11743
11744    moveText(x, y) {
11745      const current = this.current;
11746      current.x = current.lineX += x;
11747      current.y = current.lineY += y;
11748      current.xcoords = [];
11749      current.ycoords = [];
11750      current.tspan = this.svgFactory.createElement("svg:tspan");
11751      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
11752      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
11753      current.tspan.setAttributeNS(null, "y", pf(-current.y));
11754    }
11755
11756    showText(glyphs) {
11757      const current = this.current;
11758      const font = current.font;
11759      const fontSize = current.fontSize;
11760
11761      if (fontSize === 0) {
11762        return;
11763      }
11764
11765      const fontSizeScale = current.fontSizeScale;
11766      const charSpacing = current.charSpacing;
11767      const wordSpacing = current.wordSpacing;
11768      const fontDirection = current.fontDirection;
11769      const textHScale = current.textHScale * fontDirection;
11770      const vertical = font.vertical;
11771      const spacingDir = vertical ? 1 : -1;
11772      const defaultVMetrics = font.defaultVMetrics;
11773      const widthAdvanceScale = fontSize * current.fontMatrix[0];
11774      let x = 0;
11775
11776      for (const glyph of glyphs) {
11777        if (glyph === null) {
11778          x += fontDirection * wordSpacing;
11779          continue;
11780        }
11780 else if ((0, _util.isNum)(glyph)) {
11781          x += spacingDir * glyph * fontSize / 1000;
11782          continue;
11783        }
11784
11785        const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
11786        const character = glyph.fontChar;
11787        let scaledX, scaledY;
11788        let width = glyph.width;
11789
11790        if (vertical) {
11791          let vx;
11792          const vmetric = glyph.vmetric || defaultVMetrics;
11793          vx = glyph.vmetric ? vmetric[1] : width * 0.5;
11794          vx = -vx * widthAdvanceScale;
11795          const vy = vmetric[2] * widthAdvanceScale;
11796          width = vmetric ? -vmetric[0] : width;
11797          scaledX = vx / fontSizeScale;
11798          scaledY = (x + vy) / fontSizeScale;
11799        } else {
11800          scaledX = x / fontSizeScale;
11801          scaledY = 0;
11802        }
11803
11804        if (glyph.isInFont || font.missingFile) {
11805          current.xcoords.push(current.x + scaledX);
11806
11807          if (vertical) {
11808            current.ycoords.push(-current.y + scaledY);
11809          }
11810
11811          current.tspan.textContent += character;
11812        } else {}
11813
11814        let charWidth;
11815
11816        if (vertical) {
11817          charWidth = width * widthAdvanceScale - spacing * fontDirection;
11818        } else {
11819          charWidth = width * widthAdvanceScale + spacing * fontDirection;
11820        }
11821
11822        x += charWidth;
11823      }
11824
11825      current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
11826
11827      if (vertical) {
11828        current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
11829      } else {
11830        current.tspan.setAttributeNS(null, "y", pf(-current.y));
11831      }
11832
11833      if (vertical) {
11834        current.y -= x;
11835      } else {
11836        current.x += x * textHScale;
11837      }
11838
11839      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
11840      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
11841
11842      if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
11843        current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
11844      }
11845
11846      if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
11847        current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
11848      }
11849
11850      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
11851
11852      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
11853        if (current.fillColor !== SVG_DEFAULTS.fillColor) {
11854          current.tspan.setAttributeNS(null, "fill", current.fillColor);
11855        }
11856
11857        if (current.fillAlpha < 1) {
11858          current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
11859        }
11860      } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
11861        current.tspan.setAttributeNS(null, "fill", "transparent");
11862      } else {
11863        current.tspan.setAttributeNS(null, "fill", "none");
11864      }
11865
11866      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
11867        const lineWidthScale = 1 / (current.textMatrixScale || 1);
11868
11869        this._setStrokeAttributes(current.tspan, lineWidthScale);
11870      }
11871
11872      let textMatrix = current.textMatrix;
11873
11874      if (current.textRise !== 0) {
11875        textMatrix = textMatrix.slice();
11876        textMatrix[5] += current.textRise;
11877      }
11878
11879      current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
11880      current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
11881      current.txtElement.appendChild(current.tspan);
11882      current.txtgrp.appendChild(current.txtElement);
11883
11884      this._ensureTransformGroup().appendChild(current.txtElement);
11885    }
11886
11887    setLeadingMoveText(x, y) {
11888      this.setLeading(-y);
11889      this.moveText(x, y);
11890    }
11891
11892    addFontStyle(fontObj) {
11893      if (!fontObj.data) {
11894        throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
11895      }
11896
11897      if (!this.cssStyle) {
11898        this.cssStyle = this.svgFactory.createElement("svg:style");
11899        this.cssStyle.setAttributeNS(null, "type", "text/css");
11900        this.defs.appendChild(this.cssStyle);
11901      }
11902
11903      const url = (0, _util.createObjectURL)(fontObj.data, fontObj.mimetype, this.forceDataSchema);
11904      this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
11905    }
11906
11907    setFont(details) {
11908      const current = this.current;
11909      const fontObj = this.commonObjs.get(details[0]);
11910      let size = details[1];
11911      current.font = fontObj;
11912
11913      if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
11914        this.addFontStyle(fontObj);
11915        this.embeddedFonts[fontObj.loadedName] = fontObj;
11916      }
11917
11918      current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
11919      let bold = "normal";
11920
11921      if (fontObj.black) {
11922        bold = "900";
11923      } else if (fontObj.bold) {
11924        bold = "bold";
11925      }
11926
11927      const italic = fontObj.italic ? "italic" : "normal";
11928
11929      if (size < 0) {
11930        size = -size;
11931        current.fontDirection = -1;
11932      } else {
11933        current.fontDirection = 1;
11934      }
11935
11936      current.fontSize = size;
11937      current.fontFamily = fontObj.loadedName;
11938      current.fontWeight = bold;
11939      current.fontStyle = italic;
11940      current.tspan = this.svgFactory.createElement("svg:tspan");
11941      current.tspan.setAttributeNS(null, "y", pf(-current.y));
11942      current.xcoords = [];
11943      current.ycoords = [];
11944    }
11945
11946    endText() {
11947      const current = this.current;
11948
11949      if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
11950        current.element = current.txtElement;
11951        this.clip("nonzero");
11952        this.endPath();
11953      }
11954    }
11955
11956    setLineWidth(width) {
11957      if (width > 0) {
11958        this.current.lineWidth = width;
11959      }
11960    }
11961
11962    setLineCap(style) {
11963      this.current.lineCap = LINE_CAP_STYLES[style];
11964    }
11965
11966    setLineJoin(style) {
11967      this.current.lineJoin = LINE_JOIN_STYLES[style];
11968    }
11969
11970    setMiterLimit(limit) {
11971      this.current.miterLimit = limit;
11972    }
11973
11974    setStrokeAlpha(strokeAlpha) {
11975      this.current.strokeAlpha = strokeAlpha;
11976    }
11977
11978    setStrokeRGBColor(r, g, b) {
11979      this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
11980    }
11981
11982    setFillAlpha(fillAlpha) {
11983      this.current.fillAlpha = fillAlpha;
11984    }
11985
11986    setFillRGBColor(r, g, b) {
11987      this.current.fillColor = _util.Util.makeHexColor(r, g, b);
11988      this.current.tspan = this.svgFactory.createElement("svg:tspan");
11989      this.current.xcoords = [];
11990      this.current.ycoords = [];
11991    }
11992
11993    setStrokeColorN(args) {
11994      this.current.strokeColor = this._makeColorN_Pattern(args);
11995    }
11996
11997    setFillColorN(args) {
11998      this.current.fillColor = this._makeColorN_Pattern(args);
11999    }
12000
12001    shadingFill(args) {
12002      const width = this.viewport.width;
12003      const height = this.viewport.height;
12004
12005      const inv = _util.Util.inverseTransform(this.transformMatrix);
12006
12007      const bl = _util.Util.applyTransform([0, 0], inv);
12008
12009      const br = _util.Util.applyTransform([0, height], inv);
12010
12011      const ul = _util.Util.applyTransform([width, 0], inv);
12012
12013      const ur = _util.Util.applyTransform([width, height], inv);
12014
12015      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
12016      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
12017      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
12018      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
12019      const rect = this.svgFactory.createElement("svg:rect");
12020      rect.setAttributeNS(null, "x", x0);
12021      rect.setAttributeNS(null, "y", y0);
12022      rect.setAttributeNS(null, "width", x1 - x0);
12023      rect.setAttributeNS(null, "height", y1 - y0);
12024      rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
12025
12026      if (this.current.fillAlpha < 1) {
12027        rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
12028      }
12029
12030      this._ensureTransformGroup().appendChild(rect);
12031    }
12032
12033    _makeColorN_Pattern(args) {
12034      if (args[0] === "TilingPattern") {
12035        return this._makeTilingPattern(args);
12036      }
12037
12038      return this._makeShadingPattern(args);
12039    }
12040
12041    _makeTilingPattern(args) {
12042      const color = args[1];
12043      const operatorList = args[2];
12044      const matrix = args[3] || _util.IDENTITY_MATRIX;
12045      const [x0, y0, x1, y1] = args[4];
12046      const xstep = args[5];
12047      const ystep = args[6];
12048      const paintType = args[7];
12049      const tilingId = `shading${shadingCount++}`;
12050
12051      const [tx0, ty0] = _util.Util.applyTransform([x0, y0], matrix);
12052
12053      const [tx1, ty1] = _util.Util.applyTransform([x1, y1], matrix);
12054
12055      const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
12056
12057      const txstep = xstep * xscale;
12058      const tystep = ystep * yscale;
12059      const tiling = this.svgFactory.createElement("svg:pattern");
12060      tiling.setAttributeNS(null, "id", tilingId);
12061      tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
12062      tiling.setAttributeNS(null, "width", txstep);
12063      tiling.setAttributeNS(null, "height", tystep);
12064      tiling.setAttributeNS(null, "x", `${tx0}`);
12065      tiling.setAttributeNS(null, "y", `${ty0}`);
12066      const svg = this.svg;
12067      const transformMatrix = this.transformMatrix;
12068      const fillColor = this.current.fillColor;
12069      const strokeColor = this.current.strokeColor;
12070      const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
12071      this.svg = bbox;
12072      this.transformMatrix = matrix;
12073
12074      if (paintType === 2) {
12075        const cssColor = _util.Util.makeHexColor(...color);
12076
12077        this.current.fillColor = cssColor;
12078        this.current.strokeColor = cssColor;
12079      }
12080
12081      this.executeOpTree(this.convertOpList(operatorList));
12082      this.svg = svg;
12083      this.transformMatrix = transformMatrix;
12084      this.current.fillColor = fillColor;
12085      this.current.strokeColor = strokeColor;
12086      tiling.appendChild(bbox.childNodes[0]);
12087      this.defs.appendChild(tiling);
12088      return `url(#${tilingId})`;
12089    }
12090
12091    _makeShadingPattern(args) {
12092      switch (args[0]) {
12093        case "RadialAxial":
12094          const shadingId = `shading${shadingCount++}`;
12095          const colorStops = args[3];
12096          let gradient;
12097
12098          switch (args[1]) {
12099            case "axial":
12100              const point0 = args[4];
12101              const point1 = args[5];
12102              gradient = this.svgFactory.createElement("svg:linearGradient");
12103              gradient.setAttributeNS(null, "id", shadingId);
12104              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
12105              gradient.setAttributeNS(null, "x1", point0[0]);
12106              gradient.setAttributeNS(null, "y1", point0[1]);
12107              gradient.setAttributeNS(null, "x2", point1[0]);
12108              gradient.setAttributeNS(null, "y2", point1[1]);
12109              break;
12110
12111            case "radial":
12112              const focalPoint = args[4];
12113              const circlePoint = args[5];
12114              const focalRadius = args[6];
12115              const circleRadius = args[7];
12116              gradient = this.svgFactory.createElement("svg:radialGradient");
12117              gradient.setAttributeNS(null, "id", shadingId);
12118              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
12119              gradient.setAttributeNS(null, "cx", circlePoint[0]);
12120              gradient.setAttributeNS(null, "cy", circlePoint[1]);
12121              gradient.setAttributeNS(null, "r", circleRadius);
12122              gradient.setAttributeNS(null, "fx", focalPoint[0]);
12123              gradient.setAttributeNS(null, "fy", focalPoint[1]);
12124              gradient.setAttributeNS(null, "fr", focalRadius);
12125              break;
12126
12127            default:
12128              throw new Error(`Unknown RadialAxial type: ${args[1]}`);
12129          }
12130
12131          for (const colorStop of colorStops) {
12132            const stop = this.svgFactory.createElement("svg:stop");
12133            stop.setAttributeNS(null, "offset", colorStop[0]);
12134            stop.setAttributeNS(null, "stop-color", colorStop[1]);
12135            gradient.appendChild(stop);
12136          }
12137
12138          this.defs.appendChild(gradient);
12139          return `url(#${shadingId})`;
12140
12141        case "Mesh":
12142          (0, _util.warn)("Unimplemented pattern Mesh");
12143          return null;
12144
12145        case "Dummy":
12146          return "hotpink";
12147
12148        default:
12149          throw new Error(`Unknown IR type: ${args[0]}`);
12150      }
12151    }
12152
12153    setDash(dashArray, dashPhase) {
12154      this.current.dashArray = dashArray;
12155      this.current.dashPhase = dashPhase;
12156    }
12157
12158    constructPath(ops, args) {
12159      const current = this.current;
12160      let x = current.x,
12161          y = current.y;
12162      let d = [];
12163      let j = 0;
12164
12165      for (const op of ops) {
12166        switch (op | 0) {
12167          case _util.OPS.rectangle:
12168            x = args[j++];
12169            y = args[j++];
12170            const width = args[j++];
12171            const height = args[j++];
12172            const xw = x + width;
12173            const yh = y + height;
12174            d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
12175            break;
12176
12177          case _util.OPS.moveTo:
12178            x = args[j++];
12179            y = args[j++];
12180            d.push("M", pf(x), pf(y));
12181            break;
12182
12183          case _util.OPS.lineTo:
12184            x = args[j++];
12185            y = args[j++];
12186            d.push("L", pf(x), pf(y));
12187            break;
12188
12189          case _util.OPS.curveTo:
12190            x = args[j + 4];
12191            y = args[j + 5];
12192            d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
12193            j += 6;
12194            break;
12195
12196          case _util.OPS.curveTo2:
12197            d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
12198            x = args[j + 2];
12199            y = args[j + 3];
12200            j += 4;
12201            break;
12202
12203          case _util.OPS.curveTo3:
12204            x = args[j + 2];
12205            y = args[j + 3];
12206            d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
12207            j += 4;
12208            break;
12209
12210          case _util.OPS.closePath:
12211            d.push("Z");
12212            break;
12213        }
12214      }
12215
12216      d = d.join(" ");
12217
12218      if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
12219        d = current.path.getAttributeNS(null, "d") + d;
12220      } else {
12221        current.path = this.svgFactory.createElement("svg:path");
12222
12223        this._ensureTransformGroup().appendChild(current.path);
12224      }
12225
12226      current.path.setAttributeNS(null, "d", d);
12227      current.path.setAttributeNS(null, "fill", "none");
12228      current.element = current.path;
12229      current.setCurrentPoint(x, y);
12230    }
12231
12232    endPath() {
12233      const current = this.current;
12234      current.path = null;
12235
12236      if (!this.pendingClip) {
12237        return;
12238      }
12239
12240      if (!current.element) {
12241        this.pendingClip = null;
12242        return;
12243      }
12244
12245      const clipId = `clippath${clipCount++}`;
12246      const clipPath = this.svgFactory.createElement("svg:clipPath");
12247      clipPath.setAttributeNS(null, "id", clipId);
12248      clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
12249      const clipElement = current.element.cloneNode(true);
12250
12251      if (this.pendingClip === "evenodd") {
12252        clipElement.setAttributeNS(null, "clip-rule", "evenodd");
12253      } else {
12254        clipElement.setAttributeNS(null, "clip-rule", "nonzero");
12255      }
12256
12257      this.pendingClip = null;
12258      clipPath.appendChild(clipElement);
12259      this.defs.appendChild(clipPath);
12260
12261      if (current.activeClipUrl) {
12262        current.clipGroup = null;
12263
12264        for (const prev of this.extraStack) {
12265          prev.clipGroup = null;
12266        }
12267
12268        clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
12269      }
12270
12271      current.activeClipUrl = `url(#${clipId})`;
12272      this.tgrp = null;
12273    }
12274
12275    clip(type) {
12276      this.pendingClip = type;
12277    }
12278
12279    closePath() {
12280      const current = this.current;
12281
12282      if (current.path) {
12283        const d = `${current.path.getAttributeNS(null, "d")}Z`;
12284        current.path.setAttributeNS(null, "d", d);
12285      }
12286    }
12287
12288    setLeading(leading) {
12289      this.current.leading = -leading;
12290    }
12291
12292    setTextRise(textRise) {
12293      this.current.textRise = textRise;
12294    }
12295
12296    setTextRenderingMode(textRenderingMode) {
12297      this.current.textRenderingMode = textRenderingMode;
12298    }
12299
12300    setHScale(scale) {
12301      this.current.textHScale = scale / 100;
12302    }
12303
12304    setRenderingIntent(intent) {}
12305
12306    setFlatness(flatness) {}
12307
12308    setGState(states) {
12309      for (const [key, value] of states) {
12310        switch (key) {
12311          case "LW":
12312            this.setLineWidth(value);
12313            break;
12314
12315          case "LC":
12316            this.setLineCap(value);
12317            break;
12318
12319          case "LJ":
12320            this.setLineJoin(value);
12321            break;
12322
12323          case "ML":
12324            this.setMiterLimit(value);
12325            break;
12326
12327          case "D":
12328            this.setDash(value[0], value[1]);
12329            break;
12330
12331          case "RI":
12332            this.setRenderingIntent(value);
12333            break;
12334
12335          case "FL":
12336            this.setFlatness(value);
12337            break;
12338
12339          case "Font":
12340            this.setFont(value);
12341            break;
12342
12343          case "CA":
12344            this.setStrokeAlpha(value);
12345            break;
12346
12347          case "ca":
12348            this.setFillAlpha(value);
12349            break;
12350
12351          default:
12352            (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
12353            break;
12354        }
12355      }
12356    }
12357
12358    fill() {
12359      const current = this.current;
12360
12361      if (current.element) {
12362        current.element.setAttributeNS(null, "fill", current.fillColor);
12363        current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
12364        this.endPath();
12365      }
12366    }
12367
12368    stroke() {
12369      const current = this.current;
12370
12371      if (current.element) {
12372        this._setStrokeAttributes(current.element);
12373
12374        current.element.setAttributeNS(null, "fill", "none");
12375        this.endPath();
12376      }
12377    }
12378
12379    _setStrokeAttributes(element, lineWidthScale = 1) {
12380      const current = this.current;
12381      let dashArray = current.dashArray;
12382
12383      if (lineWidthScale !== 1 && dashArray.length > 0) {
12384        dashArray = dashArray.map(function (value) {
12385          return lineWidthScale * value;
12386        });
12387      }
12388
12389      element.setAttributeNS(null, "stroke", current.strokeColor);
12390      element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
12391      element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
12392      element.setAttributeNS(null, "stroke-linecap", current.lineCap);
12393      element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
12394      element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
12395      element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
12396      element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
12397    }
12398
12399    eoFill() {
12400      if (this.current.element) {
12401        this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
12402      }
12403
12404      this.fill();
12405    }
12406
12407    fillStroke() {
12408      this.stroke();
12409      this.fill();
12410    }
12411
12412    eoFillStroke() {
12413      if (this.current.element) {
12414        this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
12415      }
12416
12417      this.fillStroke();
12418    }
12419
12420    closeStroke() {
12421      this.closePath();
12422      this.stroke();
12423    }
12424
12425    closeFillStroke() {
12426      this.closePath();
12427      this.fillStroke();
12428    }
12429
12430    closeEOFillStroke() {
12431      this.closePath();
12432      this.eoFillStroke();
12433    }
12434
12435    paintSolidColorImageMask() {
12436      const rect = this.svgFactory.createElement("svg:rect");
12437      rect.setAttributeNS(null, "x", "0");
12438      rect.setAttributeNS(null, "y", "0");
12439      rect.setAttributeNS(null, "width", "1px");
12440      rect.setAttributeNS(null, "height", "1px");
12441      rect.setAttributeNS(null, "fill", this.current.fillColor);
12442
12443      this._ensureTransformGroup().appendChild(rect);
12444    }
12445
12446    paintImageXObject(objId) {
12447      const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
12448
12449      if (!imgData) {
12450        (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
12451        return;
12452      }
12453
12454      this.paintInlineImageXObject(imgData);
12455    }
12456
12457    paintInlineImageXObject(imgData, mask) {
12458      const width = imgData.width;
12459      const height = imgData.height;
12460      const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
12461      const cliprect = this.svgFactory.createElement("svg:rect");
12462      cliprect.setAttributeNS(null, "x", "0");
12463      cliprect.setAttributeNS(null, "y", "0");
12464      cliprect.setAttributeNS(null, "width", pf(width));
12465      cliprect.setAttributeNS(null, "height", pf(height));
12466      this.current.element = cliprect;
12467      this.clip("nonzero");
12468      const imgEl = this.svgFactory.createElement("svg:image");
12469      imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
12470      imgEl.setAttributeNS(null, "x", "0");
12471      imgEl.setAttributeNS(null, "y", pf(-height));
12472      imgEl.setAttributeNS(null, "width", pf(width) + "px");
12473      imgEl.setAttributeNS(null, "height", pf(height) + "px");
12474      imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
12475
12476      if (mask) {
12477        mask.appendChild(imgEl);
12478      } else {
12479        this._ensureTransformGroup().appendChild(imgEl);
12480      }
12481    }
12482
12483    paintImageMaskXObject(imgData) {
12484      const current = this.current;
12485      const width = imgData.width;
12486      const height = imgData.height;
12487      const fillColor = current.fillColor;
12488      current.maskId = `mask${maskCount++}`;
12489      const mask = this.svgFactory.createElement("svg:mask");
12490      mask.setAttributeNS(null, "id", current.maskId);
12491      const rect = this.svgFactory.createElement("svg:rect");
12492      rect.setAttributeNS(null, "x", "0");
12493      rect.setAttributeNS(null, "y", "0");
12494      rect.setAttributeNS(null, "width", pf(width));
12495      rect.setAttributeNS(null, "height", pf(height));
12496      rect.setAttributeNS(null, "fill", fillColor);
12497      rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
12498      this.defs.appendChild(mask);
12499
12500      this._ensureTransformGroup().appendChild(rect);
12501
12502      this.paintInlineImageXObject(imgData, mask);
12503    }
12504
12505    paintFormXObjectBegin(matrix, bbox) {
12506      if (Array.isArray(matrix) && matrix.length === 6) {
12507        this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
12508      }
12509
12510      if (bbox) {
12511        const width = bbox[2] - bbox[0];
12512        const height = bbox[3] - bbox[1];
12513        const cliprect = this.svgFactory.createElement("svg:rect");
12514        cliprect.setAttributeNS(null, "x", bbox[0]);
12515        cliprect.setAttributeNS(null, "y", bbox[1]);
12516        cliprect.setAttributeNS(null, "width", pf(width));
12517        cliprect.setAttributeNS(null, "height", pf(height));
12518        this.current.element = cliprect;
12519        this.clip("nonzero");
12520        this.endPath();
12521      }
12522    }
12523
12524    paintFormXObjectEnd() {}
12525
12526    _initialize(viewport) {
12527      const svg = this.svgFactory.create(viewport.width, viewport.height);
12528      const definitions = this.svgFactory.createElement("svg:defs");
12529      svg.appendChild(definitions);
12530      this.defs = definitions;
12531      const rootGroup = this.svgFactory.createElement("svg:g");
12532      rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
12533      svg.appendChild(rootGroup);
12534      this.svg = rootGroup;
12535      return svg;
12536    }
12537
12538    _ensureClipGroup() {
12539      if (!this.current.clipGroup) {
12540        const clipGroup = this.svgFactory.createElement("svg:g");
12541        clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
12542        this.svg.appendChild(clipGroup);
12543        this.current.clipGroup = clipGroup;
12544      }
12545
12546      return this.current.clipGroup;
12547    }
12548
12549    _ensureTransformGroup() {
12550      if (!this.tgrp) {
12551        this.tgrp = this.svgFactory.createElement("svg:g");
12552        this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
12553
12554        if (this.current.activeClipUrl) {
12555          this._ensureClipGroup().appendChild(this.tgrp);
12556        } else {
12557          this.svg.appendChild(this.tgrp);
12558        }
12559      }
12560
12561      return this.tgrp;
12562    }
12563
12564  };
12565}
12566
12567/***/ }),
12568/* 21 */
12569/***/ ((__unused_webpack_module, exports) => {
12570
12571
12572
12573Object.defineProperty(exports, "__esModule", ({
12574  value: true
12575}));
12576exports.XfaLayer = void 0;
12577
12578class XfaLayer {
12579  static setupStorage(html, fieldId, element, storage) {
12580    const storedData = storage.getValue(fieldId, {
12581      value: null
12582    });
12583
12584    switch (element.name) {
12585      case "textarea":
12586        html.textContent = storedData.value !== null ? storedData.value : "";
12587        html.addEventListener("input", event => {
12588          storage.setValue(fieldId, {
12589            value: event.target.value
12590          });
12591        });
12592        break;
12593
12594      case "input":
12595        if (storedData.value !== null) {
12596          html.setAttribute("value", storedData.value);
12597        }
12598
12599        if (element.attributes.type === "radio") {
12600          html.addEventListener("change", event => {
12601            const {
12602              target
12603            } = event;
12604
12605            for (const radio of document.getElementsByName(target.name)) {
12606              if (radio !== target) {
12607                const id = radio.id;
12608                storage.setValue(id.split("-")[0], {
12609                  value: false
12610                });
12611              }
12612            }
12613
12614            storage.setValue(fieldId, {
12615              value: target.checked
12616            });
12617          });
12618        } else {
12619          html.addEventListener("input", event => {
12620            storage.setValue(fieldId, {
12621              value: event.target.value
12622            });
12623          });
12624        }
12625
12626        break;
12627
12628      case "select":
12629        if (storedData.value !== null) {
12630          for (const option of element.children) {
12631            if (option.attributes.value === storedData.value) {
12632              option.attributes.selected = true;
12633            }
12634          }
12635        }
12636
12637        html.addEventListener("input", event => {
12638          const options = event.target.options;
12639          const value = options.selectedIndex === -1 ? null : options[options.selectedIndex].value;
12640          storage.setValue(fieldId, {
12641            value
12642          });
12643        });
12644        break;
12645    }
12646  }
12647
12648  static setAttributes(html, element, storage) {
12649    const {
12650      attributes
12651    } = element;
12652
12653    for (const [key, value] of Object.entries(attributes)) {
12654      if (value === null || value === undefined || key === "fieldId") {
12655        continue;
12656      }
12657
12658      if (key !== "style") {
12659        if (key === "textContent") {
12660          html.textContent = value;
12661        } else {
12662          html.setAttribute(key, value);
12663        }
12664      } else {
12665        Object.assign(html.style, value);
12666      }
12667    }
12668
12669    if (storage && attributes.fieldId !== undefined) {
12670      this.setupStorage(html, attributes.fieldId, element, storage);
12671    }
12672  }
12673
12674  static render(parameters) {
12675    const storage = parameters.annotationStorage;
12676    const root = parameters.xfa;
12677    const rootHtml = document.createElement(root.name);
12678
12679    if (root.attributes) {
12680      this.setAttributes(rootHtml, root);
12681    }
12682
12683    const stack = [[root, -1, rootHtml]];
12684    const rootDiv = parameters.div;
12685    rootDiv.appendChild(rootHtml);
12686    const coeffs = parameters.viewport.transform.join(",");
12687    rootDiv.style.transform = `matrix(${coeffs})`;
12688    rootDiv.setAttribute("class", "xfaLayer xfaFont");
12689
12690    while (stack.length > 0) {
12691      const [parent, i, html] = stack[stack.length - 1];
12692
12693      if (i + 1 === parent.children.length) {
12694        stack.pop();
12695        continue;
12696      }
12697
12698      const child = parent.children[++stack[stack.length - 1][1]];
12699
12700      if (child === null) {
12701        continue;
12702      }
12703
12704      const {
12705        name
12706      } = child;
12707
12708      if (name === "#text") {
12709        html.appendChild(document.createTextNode(child.value));
12710        continue;
12711      }
12712
12713      const childHtml = document.createElement(name);
12714      html.appendChild(childHtml);
12715
12716      if (child.attributes) {
12717        this.setAttributes(childHtml, child, storage);
12718      }
12719
12720      if (child.children && child.children.length > 0) {
12721        stack.push([child, -1, childHtml]);
12722      } else if (child.value) {
12723        childHtml.appendChild(document.createTextNode(child.value));
12724      }
12725    }
12726  }
12727
12728  static update(parameters) {
12729    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
12730    parameters.div.style.transform = transform;
12731    parameters.div.hidden = false;
12732  }
12733
12734}
12735
12736exports.XfaLayer = XfaLayer;
12737
12738/***/ }),
12739/* 22 */
12740/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
12741
12742
12743
12744Object.defineProperty(exports, "__esModule", ({
12745  value: true
12746}));
12747exports.PDFNodeStream = void 0;
12748
12749var _util = __w_pdfjs_require__(2);
12750
12751var _network_utils = __w_pdfjs_require__(23);
12752
12753;
12754
12755const fs = require("fs");
12756
12757const http = require("http");
12758
12759const https = require("https");
12760
12761const url = require("url");
12762
12763const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
12764
12765function parseUrl(sourceUrl) {
12766  const parsedUrl = url.parse(sourceUrl);
12767
12768  if (parsedUrl.protocol === "file:" || parsedUrl.host) {
12769    return parsedUrl;
12770  }
12771
12772  if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
12773    return url.parse(`file:///${sourceUrl}`);
12774  }
12775
12776  if (!parsedUrl.host) {
12777    parsedUrl.protocol = "file:";
12778  }
12779
12780  return parsedUrl;
12781}
12782
12783class PDFNodeStream {
12784  constructor(source) {
12785    this.source = source;
12786    this.url = parseUrl(source.url);
12787    this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
12788    this.isFsUrl = this.url.protocol === "file:";
12789    this.httpHeaders = this.isHttp && source.httpHeaders || {};
12790    this._fullRequestReader = null;
12791    this._rangeRequestReaders = [];
12792  }
12793
12794  get _progressiveDataLength() {
12795    return this._fullRequestReader?._loaded ?? 0;
12796  }
12797
12798  getFullReader() {
12799    (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
12800    this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
12801    return this._fullRequestReader;
12802  }
12803
12804  getRangeReader(start, end) {
12805    if (end <= this._progressiveDataLength) {
12806      return null;
12807    }
12808
12809    const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
12810
12811    this._rangeRequestReaders.push(rangeReader);
12812
12813    return rangeReader;
12814  }
12815
12816  cancelAllRequests(reason) {
12817    if (this._fullRequestReader) {
12818      this._fullRequestReader.cancel(reason);
12819    }
12820
12821    for (const reader of this._rangeRequestReaders.slice(0)) {
12822      reader.cancel(reason);
12823    }
12824  }
12825
12826}
12827
12828exports.PDFNodeStream = PDFNodeStream;
12829
12830class BaseFullReader {
12831  constructor(stream) {
12832    this._url = stream.url;
12833    this._done = false;
12834    this._storedError = null;
12835    this.onProgress = null;
12836    const source = stream.source;
12837    this._contentLength = source.length;
12838    this._loaded = 0;
12839    this._filename = null;
12840    this._disableRange = source.disableRange || false;
12841    this._rangeChunkSize = source.rangeChunkSize;
12842
12843    if (!this._rangeChunkSize && !this._disableRange) {
12844      this._disableRange = true;
12845    }
12846
12847    this._isStreamingSupported = !source.disableStream;
12848    this._isRangeSupported = !source.disableRange;
12849    this._readableStream = null;
12850    this._readCapability = (0, _util.createPromiseCapability)();
12851    this._headersCapability = (0, _util.createPromiseCapability)();
12852  }
12853
12854  get headersReady() {
12855    return this._headersCapability.promise;
12856  }
12857
12858  get filename() {
12859    return this._filename;
12860  }
12861
12862  get contentLength() {
12863    return this._contentLength;
12864  }
12865
12866  get isRangeSupported() {
12867    return this._isRangeSupported;
12868  }
12869
12870  get isStreamingSupported() {
12871    return this._isStreamingSupported;
12872  }
12873
12874  async read() {
12875    await this._readCapability.promise;
12876
12877    if (this._done) {
12878      return {
12879        value: undefined,
12880        done: true
12881      };
12882    }
12883
12884    if (this._storedError) {
12885      throw this._storedError;
12886    }
12887
12888    const chunk = this._readableStream.read();
12889
12890    if (chunk === null) {
12891      this._readCapability = (0, _util.createPromiseCapability)();
12892      return this.read();
12893    }
12894
12895    this._loaded += chunk.length;
12896
12897    if (this.onProgress) {
12898      this.onProgress({
12899        loaded: this._loaded,
12900        total: this._contentLength
12901      });
12902    }
12903
12904    const buffer = new Uint8Array(chunk).buffer;
12905    return {
12906      value: buffer,
12907      done: false
12908    };
12909  }
12910
12911  cancel(reason) {
12912    if (!this._readableStream) {
12913      this._error(reason);
12914
12915      return;
12916    }
12917
12918    this._readableStream.destroy(reason);
12919  }
12920
12921  _error(reason) {
12922    this._storedError = reason;
12923
12924    this._readCapability.resolve();
12925  }
12926
12927  _setReadableStream(readableStream) {
12928    this._readableStream = readableStream;
12929    readableStream.on("readable", () => {
12930      this._readCapability.resolve();
12931    });
12932    readableStream.on("end", () => {
12933      readableStream.destroy();
12934      this._done = true;
12935
12936      this._readCapability.resolve();
12937    });
12938    readableStream.on("error", reason => {
12939      this._error(reason);
12940    });
12941
12942    if (!this._isStreamingSupported && this._isRangeSupported) {
12943      this._error(new _util.AbortException("streaming is disabled"));
12944    }
12945
12946    if (this._storedError) {
12947      this._readableStream.destroy(this._storedError);
12948    }
12949  }
12950
12951}
12952
12953class BaseRangeReader {
12954  constructor(stream) {
12955    this._url = stream.url;
12956    this._done = false;
12957    this._storedError = null;
12958    this.onProgress = null;
12959    this._loaded = 0;
12960    this._readableStream = null;
12961    this._readCapability = (0, _util.createPromiseCapability)();
12962    const source = stream.source;
12963    this._isStreamingSupported = !source.disableStream;
12964  }
12965
12966  get isStreamingSupported() {
12967    return this._isStreamingSupported;
12968  }
12969
12970  async read() {
12971    await this._readCapability.promise;
12972
12973    if (this._done) {
12974      return {
12975        value: undefined,
12976        done: true
12977      };
12978    }
12979
12980    if (this._storedError) {
12981      throw this._storedError;
12982    }
12983
12984    const chunk = this._readableStream.read();
12985
12986    if (chunk === null) {
12987      this._readCapability = (0, _util.createPromiseCapability)();
12988      return this.read();
12989    }
12990
12991    this._loaded += chunk.length;
12992
12993    if (this.onProgress) {
12994      this.onProgress({
12995        loaded: this._loaded
12996      });
12997    }
12998
12999    const buffer = new Uint8Array(chunk).buffer;
13000    return {
13001      value: buffer,
13002      done: false
13003    };
13004  }
13005
13006  cancel(reason) {
13007    if (!this._readableStream) {
13008      this._error(reason);
13009
13010      return;
13011    }
13012
13013    this._readableStream.destroy(reason);
13014  }
13015
13016  _error(reason) {
13017    this._storedError = reason;
13018
13019    this._readCapability.resolve();
13020  }
13021
13022  _setReadableStream(readableStream) {
13023    this._readableStream = readableStream;
13024    readableStream.on("readable", () => {
13025      this._readCapability.resolve();
13026    });
13027    readableStream.on("end", () => {
13028      readableStream.destroy();
13029      this._done = true;
13030
13031      this._readCapability.resolve();
13032    });
13033    readableStream.on("error", reason => {
13034      this._error(reason);
13035    });
13036
13037    if (this._storedError) {
13038      this._readableStream.destroy(this._storedError);
13039    }
13040  }
13041
13042}
13043
13044function createRequestOptions(parsedUrl, headers) {
13045  return {
13046    protocol: parsedUrl.protocol,
13047    auth: parsedUrl.auth,
13048    host: parsedUrl.hostname,
13049    port: parsedUrl.port,
13050    path: parsedUrl.path,
13051    method: "GET",
13052    headers
13053  };
13054}
13055
13056class PDFNodeStreamFullReader extends BaseFullReader {
13057  constructor(stream) {
13058    super(stream);
13059
13060    const handleResponse = response => {
13061      if (response.statusCode === 404) {
13062        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
13063        this._storedError = error;
13064
13065        this._headersCapability.reject(error);
13066
13067        return;
13068      }
13069
13070      this._headersCapability.resolve();
13071
13072      this._setReadableStream(response);
13073
13074      const getResponseHeader = name => {
13075        return this._readableStream.headers[name.toLowerCase()];
13076      };
13077
13078      const {
13079        allowRangeRequests,
13080        suggestedLength
13081      } = (0, _network_utils.validateRangeRequestCapabilities)({
13082        getResponseHeader,
13083        isHttp: stream.isHttp,
13084        rangeChunkSize: this._rangeChunkSize,
13085        disableRange: this._disableRange
13086      });
13087      this._isRangeSupported = allowRangeRequests;
13088      this._contentLength = suggestedLength || this._contentLength;
13089      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
13090    };
13091
13092    this._request = null;
13093
13094    if (this._url.protocol === "http:") {
13095      this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
13096    } else {
13097      this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
13098    }
13099
13100    this._request.on("error", reason => {
13101      this._storedError = reason;
13102
13103      this._headersCapability.reject(reason);
13104    });
13105
13106    this._request.end();
13107  }
13108
13109}
13110
13111class PDFNodeStreamRangeReader extends BaseRangeReader {
13112  constructor(stream, start, end) {
13113    super(stream);
13114    this._httpHeaders = {};
13115
13116    for (const property in stream.httpHeaders) {
13117      const value = stream.httpHeaders[property];
13118
13119      if (typeof value === "undefined") {
13120        continue;
13121      }
13122
13123      this._httpHeaders[property] = value;
13124    }
13125
13126    this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
13127
13128    const handleResponse = response => {
13129      if (response.statusCode === 404) {
13130        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
13131        this._storedError = error;
13132        return;
13133      }
13134
13135      this._setReadableStream(response);
13136    };
13137
13138    this._request = null;
13139
13140    if (this._url.protocol === "http:") {
13141      this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
13142    } else {
13143      this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
13144    }
13145
13146    this._request.on("error", reason => {
13147      this._storedError = reason;
13148    });
13149
13150    this._request.end();
13151  }
13152
13153}
13154
13155class PDFNodeStreamFsFullReader extends BaseFullReader {
13156  constructor(stream) {
13157    super(stream);
13158    let path = decodeURIComponent(this._url.path);
13159
13160    if (fileUriRegex.test(this._url.href)) {
13161      path = path.replace(/^\//, "");
13162    }
13163
13164    fs.lstat(path, (error, stat) => {
13165      if (error) {
13166        if (error.code === "ENOENT") {
13167          error = new _util.MissingPDFException(`Missing PDF "${path}".`);
13168        }
13169
13170        this._storedError = error;
13171
13172        this._headersCapability.reject(error);
13173
13174        return;
13175      }
13176
13177      this._contentLength = stat.size;
13178
13179      this._setReadableStream(fs.createReadStream(path));
13180
13181      this._headersCapability.resolve();
13182    });
13183  }
13184
13185}
13186
13187class PDFNodeStreamFsRangeReader extends BaseRangeReader {
13188  constructor(stream, start, end) {
13189    super(stream);
13190    let path = decodeURIComponent(this._url.path);
13191
13192    if (fileUriRegex.test(this._url.href)) {
13193      path = path.replace(/^\//, "");
13194    }
13195
13196    this._setReadableStream(fs.createReadStream(path, {
13197      start,
13198      end: end - 1
13199    }));
13200  }
13201
13202}
13203
13204/***/ }),
13205/* 23 */
13206/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
13207
13208
13209
13210Object.defineProperty(exports, "__esModule", ({
13211  value: true
13212}));
13213exports.createResponseStatusError = createResponseStatusError;
13214exports.extractFilenameFromHeader = extractFilenameFromHeader;
13215exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
13216exports.validateResponseStatus = validateResponseStatus;
13217
13218var _util = __w_pdfjs_require__(2);
13219
13220var _content_disposition = __w_pdfjs_require__(24);
13221
13222var _display_utils = __w_pdfjs_require__(1);
13223
13224function validateRangeRequestCapabilities({
13225  getResponseHeader,
13226  isHttp,
13227  rangeChunkSize,
13228  disableRange
13229}) {
13230  (0, _util.assert)(rangeChunkSize > 0, "Range chunk size must be larger than zero");
13231  const returnValues = {
13232    allowRangeRequests: false,
13233    suggestedLength: undefined
13234  };
13235  const length = parseInt(getResponseHeader("Content-Length"), 10);
13236
13237  if (!Number.isInteger(length)) {
13238    return returnValues;
13239  }
13240
13241  returnValues.suggestedLength = length;
13242
13243  if (length <= 2 * rangeChunkSize) {
13244    return returnValues;
13245  }
13246
13247  if (disableRange || !isHttp) {
13248    return returnValues;
13249  }
13250
13251  if (getResponseHeader("Accept-Ranges") !== "bytes") {
13252    return returnValues;
13253  }
13254
13255  const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
13256
13257  if (contentEncoding !== "identity") {
13258    return returnValues;
13259  }
13260
13261  returnValues.allowRangeRequests = true;
13262  return returnValues;
13263}
13264
13265function extractFilenameFromHeader(getResponseHeader) {
13266  const contentDisposition = getResponseHeader("Content-Disposition");
13267
13268  if (contentDisposition) {
13269    let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
13270
13271    if (filename.includes("%")) {
13272      try {
13273        filename = decodeURIComponent(filename);
13274      } catch (ex) {}
13275    }
13276
13277    if ((0, _display_utils.isPdfFile)(filename)) {
13278      return filename;
13279    }
13280  }
13281
13282  return null;
13283}
13284
13285function createResponseStatusError(status, url) {
13286  if (status === 404 || status === 0 && url.startsWith("file:")) {
13287    return new _util.MissingPDFException('Missing PDF "' + url + '".');
13288  }
13289
13290  return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
13291}
13292
13293function validateResponseStatus(status) {
13294  return status === 200 || status === 206;
13295}
13296
13297/***/ }),
13298/* 24 */
13299/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
13300
13301
13302
13303Object.defineProperty(exports, "__esModule", ({
13304  value: true
13305}));
13306exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
13307
13308var _util = __w_pdfjs_require__(2);
13309
13310function getFilenameFromContentDispositionHeader(contentDisposition) {
13311  let needsEncodingFixup = true;
13312  let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
13313
13314  if (tmp) {
13315    tmp = tmp[1];
13316    let filename = rfc2616unquote(tmp);
13317    filename = unescape(filename);
13318    filename = rfc5987decode(filename);
13319    filename = rfc2047decode(filename);
13320    return fixupEncoding(filename);
13321  }
13322
13323  tmp = rfc2231getparam(contentDisposition);
13324
13325  if (tmp) {
13326    const filename = rfc2047decode(tmp);
13327    return fixupEncoding(filename);
13328  }
13329
13330  tmp = toParamRegExp("filename", "i").exec(contentDisposition);
13331
13332  if (tmp) {
13333    tmp = tmp[1];
13334    let filename = rfc2616unquote(tmp);
13335    filename = rfc2047decode(filename);
13336    return fixupEncoding(filename);
13337  }
13338
13339  function toParamRegExp(attributePattern, flags) {
13340    return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
13341  }
13342
13343  function textdecode(encoding, value) {
13344    if (encoding) {
13345      if (!/^[\x00-\xFF]+$/.test(value)) {
13346        return value;
13347      }
13348
13349      try {
13350        const decoder = new TextDecoder(encoding, {
13351          fatal: true
13352        });
13353        const buffer = (0, _util.stringToBytes)(value);
13354        value = decoder.decode(buffer);
13355        needsEncodingFixup = false;
13356      } catch (e) {
13357        if (/^utf-?8$/i.test(encoding)) {
13358          try {
13359            value = decodeURIComponent(escape(value));
13360            needsEncodingFixup = false;
13361          } catch (err) {}
13362        }
13363      }
13364    }
13365
13366    return value;
13367  }
13368
13369  function fixupEncoding(value) {
13370    if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
13371      value = textdecode("utf-8", value);
13372
13373      if (needsEncodingFixup) {
13374        value = textdecode("iso-8859-1", value);
13375      }
13376    }
13377
13378    return value;
13379  }
13380
13381  function rfc2231getparam(contentDispositionStr) {
13382    const matches = [];
13383    let match;
13384    const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
13385
13386    while ((match = iter.exec(contentDispositionStr)) !== null) {
13387      let [, n, quot, part] = match;
13388      n = parseInt(n, 10);
13389
13390      if (n in matches) {
13391        if (n === 0) {
13392          break;
13393        }
13394
13395        continue;
13396      }
13397
13398      matches[n] = [quot, part];
13399    }
13400
13401    const parts = [];
13402
13403    for (let n = 0; n < matches.length; ++n) {
13404      if (!(n in matches)) {
13405        break;
13406      }
13407
13408      let [quot, part] = matches[n];
13409      part = rfc2616unquote(part);
13410
13411      if (quot) {
13412        part = unescape(part);
13413
13414        if (n === 0) {
13415          part = rfc5987decode(part);
13416        }
13417      }
13418
13419      parts.push(part);
13420    }
13421
13422    return parts.join("");
13423  }
13424
13425  function rfc2616unquote(value) {
13426    if (value.startsWith('"')) {
13427      const parts = value.slice(1).split('\\"');
13428
13429      for (let i = 0; i < parts.length; ++i) {
13430        const quotindex = parts[i].indexOf('"');
13431
13432        if (quotindex !== -1) {
13433          parts[i] = parts[i].slice(0, quotindex);
13434          parts.length = i + 1;
13435        }
13436
13437        parts[i] = parts[i].replace(/\\(.)/g, "$1");
13438      }
13439
13440      value = parts.join('"');
13441    }
13442
13443    return value;
13444  }
13445
13446  function rfc5987decode(extvalue) {
13447    const encodingend = extvalue.indexOf("'");
13448
13449    if (encodingend === -1) {
13450      return extvalue;
13451    }
13452
13453    const encoding = extvalue.slice(0, encodingend);
13454    const langvalue = extvalue.slice(encodingend + 1);
13455    const value = langvalue.replace(/^[^']*'/, "");
13456    return textdecode(encoding, value);
13457  }
13458
13459  function rfc2047decode(value) {
13460    if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
13461      return value;
13462    }
13463
13464    return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
13465      if (encoding === "q" || encoding === "Q") {
13466        text = text.replace(/_/g, " ");
13467        text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
13468          return String.fromCharCode(parseInt(hex, 16));
13469        });
13470        return textdecode(charset, text);
13471      }
13472
13473      try {
13474        text = atob(text);
13475      } catch (e) {}
13476
13477      return textdecode(charset, text);
13478    });
13479  }
13480
13481  return "";
13482}
13483
13484/***/ }),
13485/* 25 */
13486/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
13487
13488
13489
13490Object.defineProperty(exports, "__esModule", ({
13491  value: true
13492}));
13493exports.PDFNetworkStream = void 0;
13494
13495var _util = __w_pdfjs_require__(2);
13496
13497var _network_utils = __w_pdfjs_require__(23);
13498
13499;
13500const OK_RESPONSE = 200;
13501const PARTIAL_CONTENT_RESPONSE = 206;
13502
13503function getArrayBuffer(xhr) {
13504  const data = xhr.response;
13505
13506  if (typeof data !== "string") {
13507    return data;
13508  }
13509
13510  const array = (0, _util.stringToBytes)(data);
13511  return array.buffer;
13512}
13513
13514class NetworkManager {
13515  constructor(url, args) {
13516    this.url = url;
13517    args = args || {};
13518    this.isHttp = /^https?:/i.test(url);
13519    this.httpHeaders = this.isHttp && args.httpHeaders || {};
13520    this.withCredentials = args.withCredentials || false;
13521
13522    this.getXhr = args.getXhr || function NetworkManager_getXhr() {
13523      return new XMLHttpRequest();
13524    };
13525
13526    this.currXhrId = 0;
13527    this.pendingRequests = Object.create(null);
13528  }
13529
13530  requestRange(begin, end, listeners) {
13531    const args = {
13532      begin,
13533      end
13534    };
13535
13536    for (const prop in listeners) {
13537      args[prop] = listeners[prop];
13538    }
13539
13540    return this.request(args);
13541  }
13542
13543  requestFull(listeners) {
13544    return this.request(listeners);
13545  }
13546
13547  request(args) {
13548    const xhr = this.getXhr();
13549    const xhrId = this.currXhrId++;
13550    const pendingRequest = this.pendingRequests[xhrId] = {
13551      xhr
13552    };
13553    xhr.open("GET", this.url);
13554    xhr.withCredentials = this.withCredentials;
13555
13556    for (const property in this.httpHeaders) {
13557      const value = this.httpHeaders[property];
13558
13559      if (typeof value === "undefined") {
13560        continue;
13561      }
13562
13563      xhr.setRequestHeader(property, value);
13564    }
13565
13566    if (this.isHttp && "begin" in args && "end" in args) {
13567      xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
13568      pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
13569    } else {
13570      pendingRequest.expectedStatus = OK_RESPONSE;
13571    }
13572
13573    xhr.responseType = "arraybuffer";
13574
13575    if (args.onError) {
13576      xhr.onerror = function (evt) {
13577        args.onError(xhr.status);
13578      };
13579    }
13580
13581    xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
13582    xhr.onprogress = this.onProgress.bind(this, xhrId);
13583    pendingRequest.onHeadersReceived = args.onHeadersReceived;
13584    pendingRequest.onDone = args.onDone;
13585    pendingRequest.onError = args.onError;
13586    pendingRequest.onProgress = args.onProgress;
13587    xhr.send(null);
13588    return xhrId;
13589  }
13590
13591  onProgress(xhrId, evt) {
13592    const pendingRequest = this.pendingRequests[xhrId];
13593
13594    if (!pendingRequest) {
13595      return;
13596    }
13597
13598    if (pendingRequest.onProgress) {
13599      pendingRequest.onProgress(evt);
13600    }
13601  }
13602
13603  onStateChange(xhrId, evt) {
13604    const pendingRequest = this.pendingRequests[xhrId];
13605
13606    if (!pendingRequest) {
13607      return;
13608    }
13609
13610    const xhr = pendingRequest.xhr;
13611
13612    if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
13613      pendingRequest.onHeadersReceived();
13614      delete pendingRequest.onHeadersReceived;
13615    }
13616
13617    if (xhr.readyState !== 4) {
13618      return;
13619    }
13620
13621    if (!(xhrId in this.pendingRequests)) {
13622      return;
13623    }
13624
13625    delete this.pendingRequests[xhrId];
13626
13627    if (xhr.status === 0 && this.isHttp) {
13628      if (pendingRequest.onError) {
13629        pendingRequest.onError(xhr.status);
13630      }
13631
13632      return;
13633    }
13634
13635    const xhrStatus = xhr.status || OK_RESPONSE;
13636    const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
13637
13638    if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
13639      if (pendingRequest.onError) {
13640        pendingRequest.onError(xhr.status);
13641      }
13642
13643      return;
13644    }
13645
13646    const chunk = getArrayBuffer(xhr);
13647
13648    if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
13649      const rangeHeader = xhr.getResponseHeader("Content-Range");
13650      const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
13651      pendingRequest.onDone({
13652        begin: parseInt(matches[1], 10),
13653        chunk
13654      });
13655    } else if (chunk) {
13656      pendingRequest.onDone({
13657        begin: 0,
13658        chunk
13659      });
13660    } else if (pendingRequest.onError) {
13661      pendingRequest.onError(xhr.status);
13662    }
13663  }
13664
13665  getRequestXhr(xhrId) {
13666    return this.pendingRequests[xhrId].xhr;
13667  }
13668
13669  isPendingRequest(xhrId) {
13670    return xhrId in this.pendingRequests;
13671  }
13672
13673  abortRequest(xhrId) {
13674    const xhr = this.pendingRequests[xhrId].xhr;
13675    delete this.pendingRequests[xhrId];
13676    xhr.abort();
13677  }
13678
13679}
13680
13681class PDFNetworkStream {
13682  constructor(source) {
13683    this._source = source;
13684    this._manager = new NetworkManager(source.url, {
13685      httpHeaders: source.httpHeaders,
13686      withCredentials: source.withCredentials
13687    });
13688    this._rangeChunkSize = source.rangeChunkSize;
13689    this._fullRequestReader = null;
13690    this._rangeRequestReaders = [];
13691  }
13692
13693  _onRangeRequestReaderClosed(reader) {
13694    const i = this._rangeRequestReaders.indexOf(reader);
13695
13696    if (i >= 0) {
13697      this._rangeRequestReaders.splice(i, 1);
13698    }
13699  }
13700
13701  getFullReader() {
13702    (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
13703    this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
13704    return this._fullRequestReader;
13705  }
13706
13707  getRangeReader(begin, end) {
13708    const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
13709    reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
13710
13711    this._rangeRequestReaders.push(reader);
13712
13713    return reader;
13714  }
13715
13716  cancelAllRequests(reason) {
13717    if (this._fullRequestReader) {
13718      this._fullRequestReader.cancel(reason);
13719    }
13720
13721    for (const reader of this._rangeRequestReaders.slice(0)) {
13722      reader.cancel(reason);
13723    }
13724  }
13725
13726}
13727
13728exports.PDFNetworkStream = PDFNetworkStream;
13729
13730class PDFNetworkStreamFullRequestReader {
13731  constructor(manager, source) {
13732    this._manager = manager;
13733    const args = {
13734      onHeadersReceived: this._onHeadersReceived.bind(this),
13735      onDone: this._onDone.bind(this),
13736      onError: this._onError.bind(this),
13737      onProgress: this._onProgress.bind(this)
13738    };
13739    this._url = source.url;
13740    this._fullRequestId = manager.requestFull(args);
13741    this._headersReceivedCapability = (0, _util.createPromiseCapability)();
13742    this._disableRange = source.disableRange || false;
13743    this._contentLength = source.length;
13744    this._rangeChunkSize = source.rangeChunkSize;
13745
13746    if (!this._rangeChunkSize && !this._disableRange) {
13747      this._disableRange = true;
13748    }
13749
13750    this._isStreamingSupported = false;
13751    this._isRangeSupported = false;
13752    this._cachedChunks = [];
13753    this._requests = [];
13754    this._done = false;
13755    this._storedError = undefined;
13756    this._filename = null;
13757    this.onProgress = null;
13758  }
13759
13760  _onHeadersReceived() {
13761    const fullRequestXhrId = this._fullRequestId;
13762
13763    const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
13764
13765    const getResponseHeader = name => {
13766      return fullRequestXhr.getResponseHeader(name);
13767    };
13768
13769    const {
13770      allowRangeRequests,
13771      suggestedLength
13772    } = (0, _network_utils.validateRangeRequestCapabilities)({
13773      getResponseHeader,
13774      isHttp: this._manager.isHttp,
13775      rangeChunkSize: this._rangeChunkSize,
13776      disableRange: this._disableRange
13777    });
13778
13779    if (allowRangeRequests) {
13780      this._isRangeSupported = true;
13781    }
13782
13783    this._contentLength = suggestedLength || this._contentLength;
13784    this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
13785
13786    if (this._isRangeSupported) {
13787      this._manager.abortRequest(fullRequestXhrId);
13788    }
13789
13790    this._headersReceivedCapability.resolve();
13791  }
13792
13793  _onDone(args) {
13794    if (args) {
13795      if (this._requests.length > 0) {
13796        const requestCapability = this._requests.shift();
13797
13798        requestCapability.resolve({
13799          value: args.chunk,
13800          done: false
13801        });
13802      } else {
13803        this._cachedChunks.push(args.chunk);
13804      }
13805    }
13806
13807    this._done = true;
13808
13809    if (this._cachedChunks.length > 0) {
13810      return;
13811    }
13812
13813    for (const requestCapability of this._requests) {
13814      requestCapability.resolve({
13815        value: undefined,
13816        done: true
13817      });
13818    }
13819
13820    this._requests.length = 0;
13821  }
13822
13823  _onError(status) {
13824    const url = this._url;
13825    const exception = (0, _network_utils.createResponseStatusError)(status, url);
13826    this._storedError = exception;
13827
13828    this._headersReceivedCapability.reject(exception);
13829
13830    for (const requestCapability of this._requests) {
13831      requestCapability.reject(exception);
13832    }
13833
13834    this._requests.length = 0;
13835    this._cachedChunks.length = 0;
13836  }
13837
13838  _onProgress(data) {
13839    if (this.onProgress) {
13840      this.onProgress({
13841        loaded: data.loaded,
13842        total: data.lengthComputable ? data.total : this._contentLength
13843      });
13844    }
13845  }
13846
13847  get filename() {
13848    return this._filename;
13849  }
13850
13851  get isRangeSupported() {
13852    return this._isRangeSupported;
13853  }
13854
13855  get isStreamingSupported() {
13856    return this._isStreamingSupported;
13857  }
13858
13859  get contentLength() {
13860    return this._contentLength;
13861  }
13862
13863  get headersReady() {
13864    return this._headersReceivedCapability.promise;
13865  }
13866
13867  async read() {
13868    if (this._storedError) {
13869      throw this._storedError;
13870    }
13871
13872    if (this._cachedChunks.length > 0) {
13873      const chunk = this._cachedChunks.shift();
13874
13875      return {
13876        value: chunk,
13877        done: false
13878      };
13879    }
13880
13881    if (this._done) {
13882      return {
13883        value: undefined,
13884        done: true
13885      };
13886    }
13887
13888    const requestCapability = (0, _util.createPromiseCapability)();
13889
13890    this._requests.push(requestCapability);
13891
13892    return requestCapability.promise;
13893  }
13894
13895  cancel(reason) {
13896    this._done = true;
13897
13898    this._headersReceivedCapability.reject(reason);
13899
13900    for (const requestCapability of this._requests) {
13901      requestCapability.resolve({
13902        value: undefined,
13903        done: true
13904      });
13905    }
13906
13907    this._requests.length = 0;
13908
13909    if (this._manager.isPendingRequest(this._fullRequestId)) {
13910      this._manager.abortRequest(this._fullRequestId);
13911    }
13912
13913    this._fullRequestReader = null;
13914  }
13915
13916}
13917
13918class PDFNetworkStreamRangeRequestReader {
13919  constructor(manager, begin, end) {
13920    this._manager = manager;
13921    const args = {
13922      onDone: this._onDone.bind(this),
13923      onProgress: this._onProgress.bind(this)
13924    };
13925    this._requestId = manager.requestRange(begin, end, args);
13926    this._requests = [];
13927    this._queuedChunk = null;
13928    this._done = false;
13929    this.onProgress = null;
13930    this.onClosed = null;
13931  }
13932
13933  _close() {
13934    if (this.onClosed) {
13935      this.onClosed(this);
13936    }
13937  }
13938
13939  _onDone(data) {
13940    const chunk = data.chunk;
13941
13942    if (this._requests.length > 0) {
13943      const requestCapability = this._requests.shift();
13944
13945      requestCapability.resolve({
13946        value: chunk,
13947        done: false
13948      });
13949    } else {
13950      this._queuedChunk = chunk;
13951    }
13952
13953    this._done = true;
13954
13955    for (const requestCapability of this._requests) {
13956      requestCapability.resolve({
13957        value: undefined,
13958        done: true
13959      });
13960    }
13961
13962    this._requests.length = 0;
13963
13964    this._close();
13965  }
13966
13967  _onProgress(evt) {
13968    if (!this.isStreamingSupported && this.onProgress) {
13969      this.onProgress({
13970        loaded: evt.loaded
13971      });
13972    }
13973  }
13974
13975  get isStreamingSupported() {
13976    return false;
13977  }
13978
13979  async read() {
13980    if (this._queuedChunk !== null) {
13981      const chunk = this._queuedChunk;
13982      this._queuedChunk = null;
13983      return {
13984        value: chunk,
13985        done: false
13986      };
13987    }
13988
13989    if (this._done) {
13990      return {
13991        value: undefined,
13992        done: true
13993      };
13994    }
13995
13996    const requestCapability = (0, _util.createPromiseCapability)();
13997
13998    this._requests.push(requestCapability);
13999
14000    return requestCapability.promise;
14001  }
14002
14003  cancel(reason) {
14004    this._done = true;
14005
14006    for (const requestCapability of this._requests) {
14007      requestCapability.resolve({
14008        value: undefined,
14009        done: true
14010      });
14011    }
14012
14013    this._requests.length = 0;
14014
14015    if (this._manager.isPendingRequest(this._requestId)) {
14016      this._manager.abortRequest(this._requestId);
14017    }
14018
14019    this._close();
14020  }
14021
14022}
14023
14024/***/ }),
14025/* 26 */
14026/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14027
14028
14029
14030Object.defineProperty(exports, "__esModule", ({
14031  value: true
14032}));
14033exports.PDFFetchStream = void 0;
14034
14035var _util = __w_pdfjs_require__(2);
14036
14037var _network_utils = __w_pdfjs_require__(23);
14038
14039;
14040
14041function createFetchOptions(headers, withCredentials, abortController) {
14042  return {
14043    method: "GET",
14044    headers,
14045    signal: abortController?.signal,
14046    mode: "cors",
14047    credentials: withCredentials ? "include" : "same-origin",
14048    redirect: "follow"
14049  };
14050}
14051
14052function createHeaders(httpHeaders) {
14053  const headers = new Headers();
14054
14055  for (const property in httpHeaders) {
14056    const value = httpHeaders[property];
14057
14058    if (typeof value === "undefined") {
14059      continue;
14060    }
14061
14062    headers.append(property, value);
14063  }
14064
14065  return headers;
14066}
14067
14068class PDFFetchStream {
14069  constructor(source) {
14070    this.source = source;
14071    this.isHttp = /^https?:/i.test(source.url);
14072    this.httpHeaders = this.isHttp && source.httpHeaders || {};
14073    this._fullRequestReader = null;
14074    this._rangeRequestReaders = [];
14075  }
14076
14077  get _progressiveDataLength() {
14078    return this._fullRequestReader?._loaded ?? 0;
14079  }
14080
14081  getFullReader() {
14082    (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
14083    this._fullRequestReader = new PDFFetchStreamReader(this);
14084    return this._fullRequestReader;
14085  }
14086
14087  getRangeReader(begin, end) {
14088    if (end <= this._progressiveDataLength) {
14089      return null;
14090    }
14091
14092    const reader = new PDFFetchStreamRangeReader(this, begin, end);
14093
14094    this._rangeRequestReaders.push(reader);
14095
14096    return reader;
14097  }
14098
14099  cancelAllRequests(reason) {
14100    if (this._fullRequestReader) {
14101      this._fullRequestReader.cancel(reason);
14102    }
14103
14104    for (const reader of this._rangeRequestReaders.slice(0)) {
14105      reader.cancel(reason);
14106    }
14107  }
14108
14109}
14110
14111exports.PDFFetchStream = PDFFetchStream;
14112
14113class PDFFetchStreamReader {
14114  constructor(stream) {
14115    this._stream = stream;
14116    this._reader = null;
14117    this._loaded = 0;
14118    this._filename = null;
14119    const source = stream.source;
14120    this._withCredentials = source.withCredentials || false;
14121    this._contentLength = source.length;
14122    this._headersCapability = (0, _util.createPromiseCapability)();
14123    this._disableRange = source.disableRange || false;
14124    this._rangeChunkSize = source.rangeChunkSize;
14125
14126    if (!this._rangeChunkSize && !this._disableRange) {
14127      this._disableRange = true;
14128    }
14129
14130    if (typeof AbortController !== "undefined") {
14131      this._abortController = new AbortController();
14132    }
14133
14134    this._isStreamingSupported = !source.disableStream;
14135    this._isRangeSupported = !source.disableRange;
14136    this._headers = createHeaders(this._stream.httpHeaders);
14137    const url = source.url;
14138    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
14139      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
14140        throw (0, _network_utils.createResponseStatusError)(response.status, url);
14141      }
14142
14143      this._reader = response.body.getReader();
14144
14145      this._headersCapability.resolve();
14146
14147      const getResponseHeader = name => {
14148        return response.headers.get(name);
14149      };
14150
14151      const {
14152        allowRangeRequests,
14153        suggestedLength
14154      } = (0, _network_utils.validateRangeRequestCapabilities)({
14155        getResponseHeader,
14156        isHttp: this._stream.isHttp,
14157        rangeChunkSize: this._rangeChunkSize,
14158        disableRange: this._disableRange
14159      });
14160      this._isRangeSupported = allowRangeRequests;
14161      this._contentLength = suggestedLength || this._contentLength;
14162      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
14163
14164      if (!this._isStreamingSupported && this._isRangeSupported) {
14165        this.cancel(new _util.AbortException("Streaming is disabled."));
14166      }
14167    }).catch(this._headersCapability.reject);
14168    this.onProgress = null;
14169  }
14170
14171  get headersReady() {
14172    return this._headersCapability.promise;
14173  }
14174
14175  get filename() {
14176    return this._filename;
14177  }
14178
14179  get contentLength() {
14180    return this._contentLength;
14181  }
14182
14183  get isRangeSupported() {
14184    return this._isRangeSupported;
14185  }
14186
14187  get isStreamingSupported() {
14188    return this._isStreamingSupported;
14189  }
14190
14191  async read() {
14192    await this._headersCapability.promise;
14193    const {
14194      value,
14195      done
14196    } = await this._reader.read();
14197
14198    if (done) {
14199      return {
14200        value,
14201        done
14202      };
14203    }
14204
14205    this._loaded += value.byteLength;
14206
14207    if (this.onProgress) {
14208      this.onProgress({
14209        loaded: this._loaded,
14210        total: this._contentLength
14211      });
14212    }
14213
14214    const buffer = new Uint8Array(value).buffer;
14215    return {
14216      value: buffer,
14217      done: false
14218    };
14219  }
14220
14221  cancel(reason) {
14222    if (this._reader) {
14223      this._reader.cancel(reason);
14224    }
14225
14226    if (this._abortController) {
14227      this._abortController.abort();
14228    }
14229  }
14230
14231}
14232
14233class PDFFetchStreamRangeReader {
14234  constructor(stream, begin, end) {
14235    this._stream = stream;
14236    this._reader = null;
14237    this._loaded = 0;
14238    const source = stream.source;
14239    this._withCredentials = source.withCredentials || false;
14240    this._readCapability = (0, _util.createPromiseCapability)();
14241    this._isStreamingSupported = !source.disableStream;
14242
14243    if (typeof AbortController !== "undefined") {
14244      this._abortController = new AbortController();
14245    }
14246
14247    this._headers = createHeaders(this._stream.httpHeaders);
14248
14249    this._headers.append("Range", `bytes=${begin}-${end - 1}`);
14250
14251    const url = source.url;
14252    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
14253      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
14254        throw (0, _network_utils.createResponseStatusError)(response.status, url);
14255      }
14256
14257      this._readCapability.resolve();
14258
14259      this._reader = response.body.getReader();
14260    }).catch(reason => {
14261      if (reason?.name === "AbortError") {
14262        return;
14263      }
14264
14265      throw reason;
14266    });
14267    this.onProgress = null;
14268  }
14269
14270  get isStreamingSupported() {
14271    return this._isStreamingSupported;
14272  }
14273
14274  async read() {
14275    await this._readCapability.promise;
14276    const {
14277      value,
14278      done
14279    } = await this._reader.read();
14280
14281    if (done) {
14282      return {
14283        value,
14284        done
14285      };
14286    }
14287
14288    this._loaded += value.byteLength;
14289
14290    if (this.onProgress) {
14291      this.onProgress({
14292        loaded: this._loaded
14293      });
14294    }
14295
14296    const buffer = new Uint8Array(value).buffer;
14297    return {
14298      value: buffer,
14299      done: false
14300    };
14301  }
14302
14303  cancel(reason) {
14304    if (this._reader) {
14305      this._reader.cancel(reason);
14306    }
14307
14308    if (this._abortController) {
14309      this._abortController.abort();
14310    }
14311  }
14312
14313}
14314
14315/***/ })
14316/******/ 	]);
14317/************************************************************************/
14318/******/ 	// The module cache
14319/******/ 	var __webpack_module_cache__ = {};
14320/******/ 	
14321/******/ 	// The require function
14322/******/ 	function __w_pdfjs_require__(moduleId) {
14323/******/ 		// Check if module is in cache
14324/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
14325/******/ 		if (cachedModule !== undefined) {
14326/******/ 			return cachedModule.exports;
14327/******/ 		}
14328/******/ 		// Create a new module (and put it into the cache)
14329/******/ 		var module = __webpack_module_cache__[moduleId] = {
14330/******/ 			// no module.id needed
14331/******/ 			// no module.loaded needed
14332/******/ 			exports: {}
14333/******/ 		};
14334/******/ 	
14335/******/ 		// Execute the module function
14336/******/ 		__webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
14337/******/ 	
14338/******/ 		// Return the exports of the module
14339/******/ 		return module.exports;
14340/******/ 	}
14341/******/ 	
14342/************************************************************************/
14343var __webpack_exports__ = {};
14344// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
14345(() => {
14346var exports = __webpack_exports__;
14347
14348
14349Object.defineProperty(exports, "__esModule", ({
14350  value: true
14351}));
14352Object.defineProperty(exports, "addLinkAttributes", ({
14353  enumerable: true,
14354  get: function () {
14355    return _display_utils.addLinkAttributes;
14356  }
14357}));
14358Object.defineProperty(exports, "getFilenameFromUrl", ({
14359  enumerable: true,
14360  get: function () {
14361    return _display_utils.getFilenameFromUrl;
14362  }
14363}));
14364Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
14365  enumerable: true,
14366  get: function () {
14367    return _display_utils.getPdfFilenameFromUrl;
14368  }
14369}));
14370Object.defineProperty(exports, "isPdfFile", ({
14371  enumerable: true,
14372  get: function () {
14373    return _display_utils.isPdfFile;
14374  }
14375}));
14376Object.defineProperty(exports, "LinkTarget", ({
14377  enumerable: true,
14378  get: function () {
14379    return _display_utils.LinkTarget;
14380  }
14381}));
14382Object.defineProperty(exports, "loadScript", ({
14383  enumerable: true,
14384  get: function () {
14385    return _display_utils.loadScript;
14386  }
14387}));
14388Object.defineProperty(exports, "PDFDateString", ({
14389  enumerable: true,
14390  get: function () {
14391    return _display_utils.PDFDateString;
14392  }
14393}));
14394Object.defineProperty(exports, "RenderingCancelledException", ({
14395  enumerable: true,
14396  get: function () {
14397    return _display_utils.RenderingCancelledException;
14398  }
14399}));
14400Object.defineProperty(exports, "build", ({
14401  enumerable: true,
14402  get: function () {
14403    return _api.build;
14404  }
14405}));
14406Object.defineProperty(exports, "getDocument", ({
14407  enumerable: true,
14408  get: function () {
14409    return _api.getDocument;
14410  }
14411}));
14412Object.defineProperty(exports, "LoopbackPort", ({
14413  enumerable: true,
14414  get: function () {
14415    return _api.LoopbackPort;
14416  }
14417}));
14418Object.defineProperty(exports, "PDFDataRangeTransport", ({
14419  enumerable: true,
14420  get: function () {
14421    return _api.PDFDataRangeTransport;
14422  }
14423}));
14424Object.defineProperty(exports, "PDFWorker", ({
14425  enumerable: true,
14426  get: function () {
14427    return _api.PDFWorker;
14428  }
14429}));
14430Object.defineProperty(exports, "version", ({
14431  enumerable: true,
14432  get: function () {
14433    return _api.version;
14434  }
14435}));
14436Object.defineProperty(exports, "CMapCompressionType", ({
14437  enumerable: true,
14438  get: function () {
14439    return _util.CMapCompressionType;
14440  }
14441}));
14442Object.defineProperty(exports, "createObjectURL", ({
14443  enumerable: true,
14444  get: function () {
14445    return _util.createObjectURL;
14446  }
14447}));
14448Object.defineProperty(exports, "createPromiseCapability", ({
14449  enumerable: true,
14450  get: function () {
14451    return _util.createPromiseCapability;
14452  }
14453}));
14454Object.defineProperty(exports, "createValidAbsoluteUrl", ({
14455  enumerable: true,
14456  get: function () {
14457    return _util.createValidAbsoluteUrl;
14458  }
14459}));
14460Object.defineProperty(exports, "InvalidPDFException", ({
14461  enumerable: true,
14462  get: function () {
14463    return _util.InvalidPDFException;
14464  }
14465}));
14466Object.defineProperty(exports, "MissingPDFException", ({
14467  enumerable: true,
14468  get: function () {
14469    return _util.MissingPDFException;
14470  }
14471}));
14472Object.defineProperty(exports, "OPS", ({
14473  enumerable: true,
14474  get: function () {
14475    return _util.OPS;
14476  }
14477}));
14478Object.defineProperty(exports, "PasswordResponses", ({
14479  enumerable: true,
14480  get: function () {
14481    return _util.PasswordResponses;
14482  }
14483}));
14484Object.defineProperty(exports, "PermissionFlag", ({
14485  enumerable: true,
14486  get: function () {
14487    return _util.PermissionFlag;
14488  }
14489}));
14490Object.defineProperty(exports, "removeNullCharacters", ({
14491  enumerable: true,
14492  get: function () {
14493    return _util.removeNullCharacters;
14494  }
14495}));
14496Object.defineProperty(exports, "shadow", ({
14497  enumerable: true,
14498  get: function () {
14499    return _util.shadow;
14500  }
14501}));
14502Object.defineProperty(exports, "UnexpectedResponseException", ({
14503  enumerable: true,
14504  get: function () {
14505    return _util.UnexpectedResponseException;
14506  }
14507}));
14508Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
14509  enumerable: true,
14510  get: function () {
14511    return _util.UNSUPPORTED_FEATURES;
14512  }
14513}));
14514Object.defineProperty(exports, "Util", ({
14515  enumerable: true,
14516  get: function () {
14517    return _util.Util;
14518  }
14519}));
14520Object.defineProperty(exports, "VerbosityLevel", ({
14521  enumerable: true,
14522  get: function () {
14523    return _util.VerbosityLevel;
14524  }
14525}));
14526Object.defineProperty(exports, "AnnotationLayer", ({
14527  enumerable: true,
14528  get: function () {
14529    return _annotation_layer.AnnotationLayer;
14530  }
14531}));
14532Object.defineProperty(exports, "apiCompatibilityParams", ({
14533  enumerable: true,
14534  get: function () {
14535    return _api_compatibility.apiCompatibilityParams;
14536  }
14537}));
14538Object.defineProperty(exports, "GlobalWorkerOptions", ({
14539  enumerable: true,
14540  get: function () {
14541    return _worker_options.GlobalWorkerOptions;
14542  }
14543}));
14544Object.defineProperty(exports, "renderTextLayer", ({
14545  enumerable: true,
14546  get: function () {
14547    return _text_layer.renderTextLayer;
14548  }
14549}));
14550Object.defineProperty(exports, "SVGGraphics", ({
14551  enumerable: true,
14552  get: function () {
14553    return _svg.SVGGraphics;
14554  }
14555}));
14556Object.defineProperty(exports, "XfaLayer", ({
14557  enumerable: true,
14558  get: function () {
14559    return _xfa_layer.XfaLayer;
14560  }
14561}));
14562
14563var _display_utils = __w_pdfjs_require__(1);
14564
14565var _api = __w_pdfjs_require__(5);
14566
14567var _util = __w_pdfjs_require__(2);
14568
14569var _annotation_layer = __w_pdfjs_require__(17);
14570
14571var _api_compatibility = __w_pdfjs_require__(9);
14572
14573var _worker_options = __w_pdfjs_require__(12);
14574
14575var _text_layer = __w_pdfjs_require__(19);
14576
14577var _svg = __w_pdfjs_require__(20);
14578
14579var _xfa_layer = __w_pdfjs_require__(21);
14580
14581const pdfjsVersion = '2.9.359';
14582const pdfjsBuild = 'e667c8cbc';
14583{
14584  const {
14585    isNodeJS
14586  } = __w_pdfjs_require__(4);
14587
14588  if (isNodeJS) {
14589    const PDFNodeStream = __w_pdfjs_require__(22).PDFNodeStream;
14590
14591    (0, _api.setPDFNetworkStreamFactory)(params => {
14592      return new PDFNodeStream(params);
14593    });
14594  } else {
14595    const PDFNetworkStream = __w_pdfjs_require__(25).PDFNetworkStream;
14596
14597    let PDFFetchStream;
14598
14599    if ((0, _display_utils.isFetchSupported)()) {
14600      PDFFetchStream = __w_pdfjs_require__(26).PDFFetchStream;
14601    }
14602
14603    (0, _api.setPDFNetworkStreamFactory)(params => {
14604      if (PDFFetchStream && (0, _display_utils.isValidFetchUrl)(params.url)) {
14605        return new PDFFetchStream(params);
14606      }
14607
14608      return new PDFNetworkStream(params);
14609    });
14610  }
14611}
14612})();
14613
14614/******/ 	return __webpack_exports__;
14615/******/ })()
14616;
14617});
vendor: 32 bytes, lines 14617-14618
14617
14618//# sourceMappingURL=pdf.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.