PageSourceSearch

https://aziziye.gov.tr/Areas/WebPart/Contents/CanvasPDF/js/pdf.js

js aziziye.gov.tr collected 2026-10-02 21:09:00 UTC 431,671 bytes, 16,403 lines download raw bytes

vendor: 4,942 bytes, lines 1-159
1(function webpackUniversalModuleDefinition(root, factory) {
2	if(typeof exports === 'object' && typeof module === 'object')
3		module.exports = factory();
4	else if(typeof define === 'function' && define.amd)
5		define("pdfjs-dist/build/pdf", [], factory);
6	else if(typeof exports === 'object')
7		exports["pdfjs-dist/build/pdf"] = factory();
8	else
9		root["pdfjs-dist/build/pdf"] = root.pdfjsLib = factory();
10})(this, () => {
11return  (() => { 
12	"use strict";
13 	var __webpack_modules__ = ([
14,
15
16 ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
17
18
19
20Object.defineProperty(exports, "__esModule", ({
21  value: true
22}));
23exports.VerbosityLevel = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.UNSUPPORTED_FEATURES = exports.TextRenderingMode = exports.StreamType = exports.RenderingIntentFlag = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.PageActionEventType = exports.OPS = exports.MissingPDFException = exports.InvalidPDFException = exports.ImageKind = exports.IDENTITY_MATRIX = exports.FormatError = exports.FontType = exports.FeatureTest = exports.FONT_IDENTITY_MATRIX = exports.DocumentActionEventType = exports.CMapCompressionType = exports.BaseException = exports.AnnotationType = exports.AnnotationStateModelType = exports.AnnotationReviewState = exports.AnnotationReplyType = exports.AnnotationMode = exports.AnnotationMarkedState = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.AnnotationActionEventType = exports.AbortException = void 0;
24exports.arrayByteLength = arrayByteLength;
25exports.arraysToBytes = arraysToBytes;
26exports.assert = assert;
27exports.bytesToString = bytesToString;
28exports.createPromiseCapability = createPromiseCapability;
29exports.createValidAbsoluteUrl = createValidAbsoluteUrl;
30exports.escapeString = escapeString;
31exports.getModificationDate = getModificationDate;
32exports.getVerbosityLevel = getVerbosityLevel;
33exports.info = info;
34exports.isArrayBuffer = isArrayBuffer;
35exports.isArrayEqual = isArrayEqual;
36exports.isAscii = isAscii;
37exports.objectFromMap = objectFromMap;
38exports.objectSize = objectSize;
39exports.setVerbosityLevel = setVerbosityLevel;
40exports.shadow = shadow;
41exports.string32 = string32;
42exports.stringToBytes = stringToBytes;
43exports.stringToPDFString = stringToPDFString;
44exports.stringToUTF16BEString = stringToUTF16BEString;
45exports.stringToUTF8String = stringToUTF8String;
46exports.unreachable = unreachable;
47exports.utf8StringToString = utf8StringToString;
48exports.warn = warn;
49
50__w_pdfjs_require__(2);
51
52const IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0];
53exports.IDENTITY_MATRIX = IDENTITY_MATRIX;
54const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
55exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX;
56const RenderingIntentFlag = {
57  ANY: 0x01,
58  DISPLAY: 0x02,
59  PRINT: 0x04,
60  ANNOTATIONS_FORMS: 0x10,
61  ANNOTATIONS_STORAGE: 0x20,
62  ANNOTATIONS_DISABLE: 0x40,
63  OPLIST: 0x100
64};
65exports.RenderingIntentFlag = RenderingIntentFlag;
66const AnnotationMode = {
67  DISABLE: 0,
68  ENABLE: 1,
69  ENABLE_FORMS: 2,
70  ENABLE_STORAGE: 3
71};
72exports.AnnotationMode = AnnotationMode;
73const PermissionFlag = {
74  PRINT: 0x04,
75  MODIFY_CONTENTS: 0x08,
76  COPY: 0x10,
77  MODIFY_ANNOTATIONS: 0x20,
78  FILL_INTERACTIVE_FORMS: 0x100,
79  COPY_FOR_ACCESSIBILITY: 0x200,
80  ASSEMBLE: 0x400,
81  PRINT_HIGH_QUALITY: 0x800
82};
83exports.PermissionFlag = PermissionFlag;
84const TextRenderingMode = {
85  FILL: 0,
86  STROKE: 1,
87  FILL_STROKE: 2,
88  INVISIBLE: 3,
89  FILL_ADD_TO_PATH: 4,
90  STROKE_ADD_TO_PATH: 5,
91  FILL_STROKE_ADD_TO_PATH: 6,
92  ADD_TO_PATH: 7,
93  FILL_STROKE_MASK: 3,
94  ADD_TO_PATH_FLAG: 4
95};
96exports.TextRenderingMode = TextRenderingMode;
97const ImageKind = {
98  GRAYSCALE_1BPP: 1,
99  RGB_24BPP: 2,
100  RGBA_32BPP: 3
101};
102exports.ImageKind = ImageKind;
103const AnnotationType = {
104  TEXT: 1,
105  LINK: 2,
106  FREETEXT: 3,
107  LINE: 4,
108  SQUARE: 5,
109  CIRCLE: 6,
110  POLYGON: 7,
111  POLYLINE: 8,
112  HIGHLIGHT: 9,
113  UNDERLINE: 10,
114  SQUIGGLY: 11,
115  STRIKEOUT: 12,
116  STAMP: 13,
117  CARET: 14,
118  INK: 15,
119  POPUP: 16,
120  FILEATTACHMENT: 17,
121  SOUND: 18,
122  MOVIE: 19,
123  WIDGET: 20,
124  SCREEN: 21,
125  PRINTERMARK: 22,
126  TRAPNET: 23,
127  WATERMARK: 24,
128  THREED: 25,
129  REDACT: 26
130};
131exports.AnnotationType = AnnotationType;
132const AnnotationStateModelType = {
133  MARKED: "Marked",
134  REVIEW: "Review"
135};
136exports.AnnotationStateModelType = AnnotationStateModelType;
137const AnnotationMarkedState = {
138  MARKED: "Marked",
139  UNMARKED: "Unmarked"
140};
141exports.AnnotationMarkedState = AnnotationMarkedState;
142const AnnotationReviewState = {
143  ACCEPTED: "Accepted",
144  REJECTED: "Rejected",
145  CANCELLED: "Cancelled",
146  COMPLETED: "Completed",
147  NONE: "None"
148};
149exports.AnnotationReviewState = AnnotationReviewState;
150const AnnotationReplyType = {
151  GROUP: "Group",
152  REPLY: "R"
153};
154exports.AnnotationReplyType = AnnotationReplyType;
155const AnnotationFlag = {
156  INVISIBLE: 0x01,
157  HIDDEN: 0x02,
158  PRINT: 0x04,
159  NOZOOM: 0x08,
160  NOROTATE: 0x10,
161  NOVIEW: 0x20,
162  READONLY: 0x40,
163  LOCKED: 0x80,
164  TOGGLENOVIEW: 0x100,
165  LOCKEDCONTENTS: 0x200
166};
167exports.AnnotationFlag = AnnotationFlag;
168const AnnotationFieldFlag = {
169  READONLY: 0x0000001,
170  REQUIRED: 0x0000002,
171  NOEXPORT: 0x0000004,
172  MULTILINE: 0x0001000,
173  PASSWORD: 0x0002000,
174  NOTOGGLETOOFF: 0x0004000,
175  RADIO: 0x0008000,
176  PUSHBUTTON: 0x0010000,
177  COMBO: 0x0020000,
178  EDIT: 0x0040000,
179  SORT: 0x0080000,
180  FILESELECT: 0x0100000,
181  MULTISELECT: 0x0200000,
182  DONOTSPELLCHECK: 0x0400000,
183  DONOTSCROLL: 0x0800000,
184  COMB: 0x1000000,
185  RICHTEXT: 0x2000000,
186  RADIOSINUNISON: 0x2000000,
187  COMMITONSELCHANGE: 0x4000000
188};
189exports.AnnotationFieldFlag = AnnotationFieldFlag;
190const AnnotationBorderStyleType = {
191  SOLID: 1,
192  DASHED: 2,
193  BEVELED: 3,
194  INSET: 4,
195  UNDERLINE: 5
196};
197exports.AnnotationBorderStyleType = AnnotationBorderStyleType;
198const AnnotationActionEventType = {
199  E: "Mouse Enter",
200  X: "Mouse Exit",
201  D: "Mouse Down",
202  U: "Mouse Up",
203  Fo: "Focus",
204  Bl: "Blur",
205  PO: "PageOpen",
206  PC: "PageClose",
207  PV: "PageVisible",
208  PI: "PageInvisible",
209  K: "Keystroke",
210  F: "Format",
211  V: "Validate",
212  C: "Calculate"
213};
214exports.AnnotationActionEventType = AnnotationActionEventType;
215const DocumentActionEventType = {
216  WC: "WillClose",
217  WS: "WillSave",
218  DS: "DidSave",
219  WP: "WillPrint",
220  DP: "DidPrint"
221};
222exports.DocumentActionEventType = DocumentActionEventType;
223const PageActionEventType = {
224  O: "PageOpen",
225  C: "PageClose"
226};
227exports.PageActionEventType = PageActionEventType;
228const StreamType = {
229  UNKNOWN: "UNKNOWN",
230  FLATE: "FLATE",
231  LZW: "LZW",
232  DCT: "DCT",
233  JPX: "JPX",
234  JBIG: "JBIG",
235  A85: "A85",
236  AHX: "AHX",
237  CCF: "CCF",
238  RLX: "RLX"
239};
240exports.StreamType = StreamType;
241const FontType = {
242  UNKNOWN: "UNKNOWN",
243  TYPE1: "TYPE1",
244  TYPE1STANDARD: "TYPE1STANDARD",
245  TYPE1C: "TYPE1C",
246  CIDFONTTYPE0: "CIDFONTTYPE0",
247  CIDFONTTYPE0C: "CIDFONTTYPE0C",
248  TRUETYPE: "TRUETYPE",
249  CIDFONTTYPE2: "CIDFONTTYPE2",
250  TYPE3: "TYPE3",
251  OPENTYPE: "OPENTYPE",
252  TYPE0: "TYPE0",
253  MMTYPE1: "MMTYPE1"
254};
255exports.FontType = FontType;
256const VerbosityLevel = {
257  ERRORS: 0,
258  WARNINGS: 1,
259  INFOS: 5
260};
261exports.VerbosityLevel = VerbosityLevel;
262const CMapCompressionType = {
263  NONE: 0,
264  BINARY: 1,
265  STREAM: 2
266};
267exports.CMapCompressionType = CMapCompressionType;
268const OPS = {
269  dependency: 1,
270  setLineWidth: 2,
271  setLineCap: 3,
272  setLineJoin: 4,
273  setMiterLimit: 5,
274  setDash: 6,
275  setRenderingIntent: 7,
276  setFlatness: 8,
277  setGState: 9,
278  save: 10,
279  restore: 11,
280  transform: 12,
281  moveTo: 13,
282  lineTo: 14,
283  curveTo: 15,
284  curveTo2: 16,
vendor: 18,558 bytes, lines 285-1056
285  curveTo3: 17,
286  closePath: 18,
287  rectangle: 19,
288  stroke: 20,
289  closeStroke: 21,
290  fill: 22,
291  eoFill: 23,
292  fillStroke: 24,
293  eoFillStroke: 25,
294  closeFillStroke: 26,
295  closeEOFillStroke: 27,
296  endPath: 28,
297  clip: 29,
298  eoClip: 30,
299  beginText: 31,
300  endText: 32,
301  setCharSpacing: 33,
302  setWordSpacing: 34,
303  setHScale: 35,
304  setLeading: 36,
305  setFont: 37,
306  setTextRenderingMode: 38,
307  setTextRise: 39,
308  moveText: 40,
309  setLeadingMoveText: 41,
310  setTextMatrix: 42,
311  nextLine: 43,
312  showText: 44,
313  showSpacedText: 45,
314  nextLineShowText: 46,
315  nextLineSetSpacingShowText: 47,
316  setCharWidth: 48,
317  setCharWidthAndBounds: 49,
318  setStrokeColorSpace: 50,
319  setFillColorSpace: 51,
320  setStrokeColor: 52,
321  setStrokeColorN: 53,
322  setFillColor: 54,
323  setFillColorN: 55,
324  setStrokeGray: 56,
325  setFillGray: 57,
326  setStrokeRGBColor: 58,
327  setFillRGBColor: 59,
328  setStrokeCMYKColor: 60,
329  setFillCMYKColor: 61,
330  shadingFill: 62,
331  beginInlineImage: 63,
332  beginImageData: 64,
333  endInlineImage: 65,
334  paintXObject: 66,
335  markPoint: 67,
336  markPointProps: 68,
337  beginMarkedContent: 69,
338  beginMarkedContentProps: 70,
339  endMarkedContent: 71,
340  beginCompat: 72,
341  endCompat: 73,
342  paintFormXObjectBegin: 74,
343  paintFormXObjectEnd: 75,
344  beginGroup: 76,
345  endGroup: 77,
346  beginAnnotations: 78,
347  endAnnotations: 79,
348  beginAnnotation: 80,
349  endAnnotation: 81,
350  paintJpegXObject: 82,
351  paintImageMaskXObject: 83,
352  paintImageMaskXObjectGroup: 84,
353  paintImageXObject: 85,
354  paintInlineImageXObject: 86,
355  paintInlineImageXObjectGroup: 87,
356  paintImageXObjectRepeat: 88,
357  paintImageMaskXObjectRepeat: 89,
358  paintSolidColorImageMask: 90,
359  constructPath: 91
360};
361exports.OPS = OPS;
362const UNSUPPORTED_FEATURES = {
363  unknown: "unknown",
364  forms: "forms",
365  javaScript: "javaScript",
366  signatures: "signatures",
367  smask: "smask",
368  shadingPattern: "shadingPattern",
369  font: "font",
370  errorTilingPattern: "errorTilingPattern",
371  errorExtGState: "errorExtGState",
372  errorXObject: "errorXObject",
373  errorFontLoadType3: "errorFontLoadType3",
374  errorFontState: "errorFontState",
375  errorFontMissing: "errorFontMissing",
376  errorFontTranslate: "errorFontTranslate",
377  errorColorSpace: "errorColorSpace",
378  errorOperatorList: "errorOperatorList",
379  errorFontToUnicode: "errorFontToUnicode",
380  errorFontLoadNative: "errorFontLoadNative",
381  errorFontBuildPath: "errorFontBuildPath",
382  errorFontGetPath: "errorFontGetPath",
383  errorMarkedContent: "errorMarkedContent",
384  errorContentSubStream: "errorContentSubStream"
385};
386exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES;
387const PasswordResponses = {
388  NEED_PASSWORD: 1,
389  INCORRECT_PASSWORD: 2
390};
391exports.PasswordResponses = PasswordResponses;
392let verbosity = VerbosityLevel.WARNINGS;
393
394function setVerbosityLevel(level) {
395  if (Number.isInteger(level)) {
396    verbosity = level;
397  }
398}
399
400function getVerbosityLevel() {
401  return verbosity;
402}
403
404function info(msg) {
405  if (verbosity >= VerbosityLevel.INFOS) {
406    console.log(`Info: ${msg}`);
407  }
408}
409
410function warn(msg) {
411  if (verbosity >= VerbosityLevel.WARNINGS) {
412    console.log(`Warning: ${msg}`);
413  }
414}
415
416function unreachable(msg) {
417  throw new Error(msg);
418}
419
420function assert(cond, msg) {
421  if (!cond) {
422    unreachable(msg);
423  }
424}
425
426function _isValidProtocol(url) {
427  if (!url) {
428    return false;
429  }
430
431  switch (url.protocol) {
432    case "http:":
433    case "https:":
434    case "ftp:":
435    case "mailto:":
436    case "tel:":
437      return true;
438
439    default:
440      return false;
441  }
442}
443
444function createValidAbsoluteUrl(url, baseUrl = null, options = null) {
445  if (!url) {
446    return null;
447  }
448
449  try {
450    if (options && typeof url === "string") {
451      if (options.addDefaultProtocol && url.startsWith("www.")) {
452        const dots = url.match(/\./g);
453
454        if (dots && dots.length >= 2) {
455          url = `http://${url}`;
456        }
457      }
458
459      if (options.tryConvertEncoding) {
460        try {
461          url = stringToUTF8String(url);
462        } catch (ex) {}
463      }
464    }
465
466    const absoluteUrl = baseUrl ? new URL(url, baseUrl) : new URL(url);
467
468    if (_isValidProtocol(absoluteUrl)) {
469      return absoluteUrl;
470    }
471  } catch (ex) {}
472
473  return null;
474}
475
476function shadow(obj, prop, value) {
477  Object.defineProperty(obj, prop, {
478    value,
479    enumerable: true,
480    configurable: true,
481    writable: false
482  });
483  return value;
484}
485
486const BaseException = function BaseExceptionClosure() {
487  function BaseException(message, name) {
488    if (this.constructor === BaseException) {
489      unreachable("Cannot initialize BaseException.");
490    }
491
492    this.message = message;
493    this.name = name;
494  }
495
496  BaseException.prototype = new Error();
497  BaseException.constructor = BaseException;
498  return BaseException;
499}();
500
501exports.BaseException = BaseException;
502
503class PasswordException extends BaseException {
504  constructor(msg, code) {
505    super(msg, "PasswordException");
506    this.code = code;
507  }
508
509}
510
511exports.PasswordException = PasswordException;
512
513class UnknownErrorException extends BaseException {
514  constructor(msg, details) {
515    super(msg, "UnknownErrorException");
516    this.details = details;
517  }
518
519}
520
521exports.UnknownErrorException = UnknownErrorException;
522
523class InvalidPDFException extends BaseException {
524  constructor(msg) {
525    super(msg, "InvalidPDFException");
526  }
527
528}
529
530exports.InvalidPDFException = InvalidPDFException;
531
532class MissingPDFException extends BaseException {
533  constructor(msg) {
534    super(msg, "MissingPDFException");
535  }
536
537}
538
539exports.MissingPDFException = MissingPDFException;
540
541class UnexpectedResponseException extends BaseException {
542  constructor(msg, status) {
543    super(msg, "UnexpectedResponseException");
544    this.status = status;
545  }
546
547}
548
549exports.UnexpectedResponseException = UnexpectedResponseException;
550
551class FormatError extends BaseException {
552  constructor(msg) {
553    super(msg, "FormatError");
554  }
555
556}
557
558exports.FormatError = FormatError;
559
560class AbortException extends BaseException {
561  constructor(msg) {
562    super(msg, "AbortException");
563  }
564
565}
566
567exports.AbortException = AbortException;
568
569function bytesToString(bytes) {
570  if (typeof bytes !== "object" || bytes === null || bytes.length === undefined) {
571    unreachable("Invalid argument for bytesToString");
572  }
573
574  const length = bytes.length;
575  const MAX_ARGUMENT_COUNT = 8192;
576
577  if (length < MAX_ARGUMENT_COUNT) {
578    return String.fromCharCode.apply(null, bytes);
579  }
580
581  const strBuf = [];
582
583  for (let i = 0; i < length; i += MAX_ARGUMENT_COUNT) {
584    const chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length);
585    const chunk = bytes.subarray(i, chunkEnd);
586    strBuf.push(String.fromCharCode.apply(null, chunk));
587  }
588
589  return strBuf.join("");
590}
591
592function stringToBytes(str) {
593  if (typeof str !== "string") {
594    unreachable("Invalid argument for stringToBytes");
595  }
596
597  const length = str.length;
598  const bytes = new Uint8Array(length);
599
600  for (let i = 0; i < length; ++i) {
601    bytes[i] = str.charCodeAt(i) & 0xff;
602  }
603
604  return bytes;
605}
606
607function arrayByteLength(arr) {
608  if (arr.length !== undefined) {
609    return arr.length;
610  }
611
612  if (arr.byteLength !== undefined) {
613    return arr.byteLength;
614  }
615
616  unreachable("Invalid argument for arrayByteLength");
617}
618
619function arraysToBytes(arr) {
620  const length = arr.length;
621
622  if (length === 1 && arr[0] instanceof Uint8Array) {
623    return arr[0];
624  }
625
626  let resultLength = 0;
627
628  for (let i = 0; i < length; i++) {
629    resultLength += arrayByteLength(arr[i]);
630  }
631
632  let pos = 0;
633  const data = new Uint8Array(resultLength);
634
635  for (let i = 0; i < length; i++) {
636    let item = arr[i];
637
638    if (!(item instanceof Uint8Array)) {
639      if (typeof item === "string") {
640        item = stringToBytes(item);
641      } else {
642        item = new Uint8Array(item);
643      }
644    }
645
646    const itemLength = item.byteLength;
647    data.set(item, pos);
648    pos += itemLength;
649  }
650
651  return data;
652}
653
654function string32(value) {
655  return String.fromCharCode(value >> 24 & 0xff, value >> 16 & 0xff, value >> 8 & 0xff, value & 0xff);
656}
657
658function objectSize(obj) {
659  return Object.keys(obj).length;
660}
661
662function objectFromMap(map) {
663  const obj = Object.create(null);
664
665  for (const [key, value] of map) {
666    obj[key] = value;
667  }
668
669  return obj;
670}
671
672function isLittleEndian() {
673  const buffer8 = new Uint8Array(4);
674  buffer8[0] = 1;
675  const view32 = new Uint32Array(buffer8.buffer, 0, 1);
676  return view32[0] === 1;
677}
678
679function isEvalSupported() {
680  try {
681    new Function("");
682    return true;
683  } catch (e) {
684    return false;
685  }
686}
687
688class FeatureTest {
689  static get isLittleEndian() {
690    return shadow(this, "isLittleEndian", isLittleEndian());
691  }
692
693  static get isEvalSupported() {
694    return shadow(this, "isEvalSupported", isEvalSupported());
695  }
696
697  static get isOffscreenCanvasSupported() {
698    return shadow(this, "isOffscreenCanvasSupported", typeof OffscreenCanvas !== "undefined");
699  }
700
701}
702
703exports.FeatureTest = FeatureTest;
704const hexNumbers = [...Array(256).keys()].map(n => n.toString(16).padStart(2, "0"));
705
706class Util {
707  static makeHexColor(r, g, b) {
708    return `#${hexNumbers[r]}${hexNumbers[g]}${hexNumbers[b]}`;
709  }
710
711  static scaleMinMax(transform, minMax) {
712    let temp;
713
714    if (transform[0]) {
715      if (transform[0] < 0) {
716        temp = minMax[0];
717        minMax[0] = minMax[1];
718        minMax[1] = temp;
719      }
720
721      minMax[0] *= transform[0];
722      minMax[1] *= transform[0];
723
724      if (transform[3] < 0) {
725        temp = minMax[2];
726        minMax[2] = minMax[3];
727        minMax[3] = temp;
728      }
729
730      minMax[2] *= transform[3];
731      minMax[3] *= transform[3];
732    } else {
733      temp = minMax[0];
734      minMax[0] = minMax[2];
735      minMax[2] = temp;
736      temp = minMax[1];
737      minMax[1] = minMax[3];
738      minMax[3] = temp;
739
740      if (transform[1] < 0) {
741        temp = minMax[2];
742        minMax[2] = minMax[3];
743        minMax[3] = temp;
744      }
745
746      minMax[2] *= transform[1];
747      minMax[3] *= transform[1];
748
749      if (transform[2] < 0) {
750        temp = minMax[0];
751        minMax[0] = minMax[1];
752        minMax[1] = temp;
753      }
754
755      minMax[0] *= transform[2];
756      minMax[1] *= transform[2];
757    }
758
759    minMax[0] += transform[4];
760    minMax[1] += transform[4];
761    minMax[2] += transform[5];
762    minMax[3] += transform[5];
763  }
764
765  static transform(m1, m2) {
766    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]];
767  }
768
769  static applyTransform(p, m) {
770    const xt = p[0] * m[0] + p[1] * m[2] + m[4];
771    const yt = p[0] * m[1] + p[1] * m[3] + m[5];
772    return [xt, yt];
773  }
774
775  static applyInverseTransform(p, m) {
776    const d = m[0] * m[3] - m[1] * m[2];
777    const xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d;
778    const yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d;
779    return [xt, yt];
780  }
781
782  static getAxialAlignedBoundingBox(r, m) {
783    const p1 = Util.applyTransform(r, m);
784    const p2 = Util.applyTransform(r.slice(2, 4), m);
785    const p3 = Util.applyTransform([r[0], r[3]], m);
786    const p4 = Util.applyTransform([r[2], r[1]], m);
787    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])];
788  }
789
790  static inverseTransform(m) {
791    const d = m[0] * m[3] - m[1] * m[2];
792    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];
793  }
794
795  static apply3dTransform(m, v) {
796    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]];
797  }
798
799  static singularValueDecompose2dScale(m) {
800    const transpose = [m[0], m[2], m[1], m[3]];
801    const a = m[0] * transpose[0] + m[1] * transpose[2];
802    const b = m[0] * transpose[1] + m[1] * transpose[3];
803    const c = m[2] * transpose[0] + m[3] * transpose[2];
804    const d = m[2] * transpose[1] + m[3] * transpose[3];
805    const first = (a + d) / 2;
806    const second = Math.sqrt((a + d) ** 2 - 4 * (a * d - c * b)) / 2;
807    const sx = first + second || 1;
808    const sy = first - second || 1;
809    return [Math.sqrt(sx), Math.sqrt(sy)];
810  }
811
812  static normalizeRect(rect) {
813    const r = rect.slice(0);
814
815    if (rect[0] > rect[2]) {
816      r[0] = rect[2];
817      r[2] = rect[0];
818    }
819
820    if (rect[1] > rect[3]) {
821      r[1] = rect[3];
822      r[3] = rect[1];
823    }
824
825    return r;
826  }
827
828  static intersect(rect1, rect2) {
829    const xLow = Math.max(Math.min(rect1[0], rect1[2]), Math.min(rect2[0], rect2[2]));
830    const xHigh = Math.min(Math.max(rect1[0], rect1[2]), Math.max(rect2[0], rect2[2]));
831
832    if (xLow > xHigh) {
833      return null;
834    }
835
836    const yLow = Math.max(Math.min(rect1[1], rect1[3]), Math.min(rect2[1], rect2[3]));
837    const yHigh = Math.min(Math.max(rect1[1], rect1[3]), Math.max(rect2[1], rect2[3]));
838
839    if (yLow > yHigh) {
840      return null;
841    }
842
843    return [xLow, yLow, xHigh, yHigh];
844  }
845
846  static bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3) {
847    const tvalues = [],
848          bounds = [[], []];
849    let a, b, c, t, t1, t2, b2ac, sqrtb2ac;
850
851    for (let i = 0; i < 2; ++i) {
852      if (i === 0) {
853        b = 6 * x0 - 12 * x1 + 6 * x2;
854        a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
855        c = 3 * x1 - 3 * x0;
856      } else {
857        b = 6 * y0 - 12 * y1 + 6 * y2;
858        a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
859        c = 3 * y1 - 3 * y0;
860      }
861
862      if (Math.abs(a) < 1e-12) {
863        if (Math.abs(b) < 1e-12) {
864          continue;
865        }
866
867        t = -c / b;
868
869        if (0 < t && t < 1) {
870          tvalues.push(t);
871        }
872
873        continue;
874      }
875
876      b2ac = b * b - 4 * c * a;
877      sqrtb2ac = Math.sqrt(b2ac);
878
879      if (b2ac < 0) {
880        continue;
881      }
882
883      t1 = (-b + sqrtb2ac) / (2 * a);
884
885      if (0 < t1 && t1 < 1) {
886        tvalues.push(t1);
887      }
888
889      t2 = (-b - sqrtb2ac) / (2 * a);
890
891      if (0 < t2 && t2 < 1) {
892        tvalues.push(t2);
893      }
894    }
895
896    let j = tvalues.length,
897        mt;
898    const jlen = j;
899
900    while (j--) {
901      t = tvalues[j];
902      mt = 1 - t;
903      bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3;
904      bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3;
905    }
906
907    bounds[0][jlen] = x0;
908    bounds[1][jlen] = y0;
909    bounds[0][jlen + 1] = x3;
910    bounds[1][jlen + 1] = y3;
911    bounds[0].length = bounds[1].length = jlen + 2;
912    return [Math.min(...bounds[0]), Math.min(...bounds[1]), Math.max(...bounds[0]), Math.max(...bounds[1])];
913  }
914
915}
916
917exports.Util = Util;
918const 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];
919
920function stringToPDFString(str) {
921  if (str[0] >= "\xEF") {
922    let encoding;
923
924    if (str[0] === "\xFE" && str[1] === "\xFF") {
925      encoding = "utf-16be";
926    } else if (str[0] === "\xFF" && str[1] === "\xFE") {
927      encoding = "utf-16le";
928    } else if (str[0] === "\xEF" && str[1] === "\xBB" && str[2] === "\xBF") {
929      encoding = "utf-8";
930    }
931
932    if (encoding) {
933      try {
934        const decoder = new TextDecoder(encoding, {
935          fatal: true
936        });
937        const buffer = stringToBytes(str);
938        return decoder.decode(buffer);
939      } catch (ex) {
940        warn(`stringToPDFString: "${ex}".`);
941      }
942    }
943  }
944
945  const strBuf = [];
946
947  for (let i = 0, ii = str.length; i < ii; i++) {
948    const code = PDFStringTranslateTable[str.charCodeAt(i)];
949    strBuf.push(code ? String.fromCharCode(code) : str.charAt(i));
950  }
951
952  return strBuf.join("");
953}
954
955function escapeString(str) {
956  return str.replace(/([()\\\n\r])/g, match => {
957    if (match === "\n") {
958      return "\\n";
959    } else if (match === "\r") {
960      return "\\r";
961    }
962
963    return `\\${match}`;
964  });
965}
966
967function isAscii(str) {
968  return /^[\x00-\x7F]*$/.test(str);
969}
970
971function stringToUTF16BEString(str) {
972  const buf = ["\xFE\xFF"];
973
974  for (let i = 0, ii = str.length; i < ii; i++) {
975    const char = str.charCodeAt(i);
976    buf.push(String.fromCharCode(char >> 8 & 0xff), String.fromCharCode(char & 0xff));
977  }
978
979  return buf.join("");
980}
981
982function stringToUTF8String(str) {
983  return decodeURIComponent(escape(str));
984}
985
986function utf8StringToString(str) {
987  return unescape(encodeURIComponent(str));
988}
989
990function isArrayBuffer(v) {
991  return typeof v === "object" && v !== null && v.byteLength !== undefined;
992}
993
994function isArrayEqual(arr1, arr2) {
995  if (arr1.length !== arr2.length) {
996    return false;
997  }
998
999  for (let i = 0, ii = arr1.length; i < ii; i++) {
1000    if (arr1[i] !== arr2[i]) {
1001      return false;
1002    }
1003  }
1004
1005  return true;
1006}
1007
1008function getModificationDate(date = new Date()) {
1009  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")];
1010  return buffer.join("");
1011}
1012
1013function createPromiseCapability() {
1014  const capability = Object.create(null);
1015  let isSettled = false;
1016  Object.defineProperty(capability, "settled", {
1017    get() {
1018      return isSettled;
1019    }
1020
1021  });
1022  capability.promise = new Promise(function (resolve, reject) {
1023    capability.resolve = function (data) {
1024      isSettled = true;
1025      resolve(data);
1026    };
1027
1028    capability.reject = function (reason) {
1029      isSettled = true;
1030      reject(reason);
1031    };
1032  });
1033  return capability;
1034}
1035
1036/***/ }),
1037/* 2 */
1038/***/ ((__unused_webpack_module, __unused_webpack_exports, __w_pdfjs_require__) => {
1039
1040
1041
1042var _is_node = __w_pdfjs_require__(3);
1043
1044;
1045
1046/***/ }),
1047/* 3 */
1048/***/ ((__unused_webpack_module, exports) => {
1049
1050
1051
1052Object.defineProperty(exports, "__esModule", ({
1053  value: true
1054}));
1055exports.isNodeJS = void 0;
1056const isNodeJS = typeof process === "object" && process + "" === "[object process]" && !process.versions.nw && !(process.versions.electron && process.type && process.type !== "browser");
1057exports.isNodeJS = isNodeJS;
1058
1059/***/ }),
1060/* 4 */
1061/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
1062
1063
1064
1065Object.defineProperty(exports, "__esModule", ({
1066  value: true
1067}));
1068exports.build = exports.RenderTask = exports.PDFWorkerUtil = exports.PDFWorker = exports.PDFPageProxy = exports.PDFDocumentProxy = exports.PDFDocumentLoadingTask = exports.PDFDataRangeTransport = exports.LoopbackPort = exports.DefaultStandardFontDataFactory = exports.DefaultCanvasFactory = exports.DefaultCMapReaderFactory = void 0;
1069exports.getDocument = getDocument;
1070exports.setPDFNetworkStreamFactory = setPDFNetworkStreamFactory;
1071exports.version = void 0;
1072
1073var _util = __w_pdfjs_require__(1);
1074
1075var _display_utils = __w_pdfjs_require__(5);
1076
1077var _font_loader = __w_pdfjs_require__(7);
1078
1079var _annotation_storage = __w_pdfjs_require__(8);
1080
1081var _canvas = __w_pdfjs_require__(10);
1082
1083var _worker_options = __w_pdfjs_require__(13);
1084
1085var _is_node = __w_pdfjs_require__(3);
1086
1087var _message_handler = __w_pdfjs_require__(14);
1088
1089var _metadata = __w_pdfjs_require__(15);
1090
1091var _optional_content_config = __w_pdfjs_require__(16);
1092
1093var _transport_stream = __w_pdfjs_require__(17);
1094
1095var _xfa_text = __w_pdfjs_require__(18);
1096
1097const DEFAULT_RANGE_CHUNK_SIZE = 65536;
1098const RENDERING_CANCELLED_TIMEOUT = 100;
1099let DefaultCanvasFactory = _display_utils.DOMCanvasFactory;
1100exports.DefaultCanvasFactory = DefaultCanvasFactory;
1101let DefaultCMapReaderFactory = _display_utils.DOMCMapReaderFactory;
1102exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory;
1103let DefaultStandardFontDataFactory = _display_utils.DOMStandardFontDataFactory;
1104exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory;
1105
1106if (_is_node.isNodeJS) {
1107  const {
1108    NodeCanvasFactory,
1109    NodeCMapReaderFactory,
1110    NodeStandardFontDataFactory
1111  } = __w_pdfjs_require__(19);
1112
1113  exports.DefaultCanvasFactory = DefaultCanvasFactory = NodeCanvasFactory;
1114  exports.DefaultCMapReaderFactory = DefaultCMapReaderFactory = NodeCMapReaderFactory;
1115  exports.DefaultStandardFontDataFactory = DefaultStandardFontDataFactory = NodeStandardFontDataFactory;
1116}
1117
1118let createPDFNetworkStream;
1119
1120function setPDFNetworkStreamFactory(pdfNetworkStreamFactory) {
1121  createPDFNetworkStream = pdfNetworkStreamFactory;
1122}
1123
1124function getDocument(src) {
1125  const task = new PDFDocumentLoadingTask();
1126  let source;
1127
1128  if (typeof src === "string" || src instanceof URL) {
1129    source = {
1130      url: src
1131    };
1132  } else if ((0, _util.isArrayBuffer)(src)) {
1133    source = {
1134      data: src
1135    };
1136  } else if (src instanceof PDFDataRangeTransport) {
1137    source = {
1138      range: src
1139    };
1140  } else {
1141    if (typeof src !== "object") {
1142      throw new Error("Invalid parameter in getDocument, " + "need either string, URL, Uint8Array, or parameter object.");
1143    }
1144
1145    if (!src.url && !src.data && !src.range) {
1146      throw new Error("Invalid parameter object: need either .data, .range or .url");
1147    }
1148
1149    source = src;
1150  }
1151
1152  const params = Object.create(null);
1153  let rangeTransport = null,
1154      worker = null;
1155
1156  for (const key in source) {
1157    const value = source[key];
1158
1159    switch (key) {
1160      case "url":
1161        if (typeof window !== "undefined") {
1162          try {
1163            params[key] = new URL(value, window.location).href;
1164            continue;
1165          } catch (ex) {
1166            (0, _util.warn)(`Cannot create valid URL: "${ex}".`);
1167          }
1168        } else if (typeof value === "string" || value instanceof URL) {
1169          params[key] = value.toString();
1170          continue;
1171        }
1172
1173        throw new Error("Invalid PDF url data: " + "either string or URL-object is expected in the url property.");
1174
1175      case "range":
1176        rangeTransport = value;
1177        continue;
1178
1179      case "worker":
1180        worker = value;
1181        continue;
1182
1183      case "data":
1184        if (_is_node.isNodeJS && typeof Buffer !== "undefined" && value instanceof Buffer) {
1185          params[key] = new Uint8Array(value);
1186        } else if (value instanceof Uint8Array) {
1187          break;
1188        } else if (typeof value === "string") {
1189          params[key] = (0, _util.stringToBytes)(value);
1190        } else if (typeof value === "object" && value !== null && !isNaN(value.length)) {
1191          params[key] = new Uint8Array(value);
1192        } else if ((0, _util.isArrayBuffer)(value)) {
1193          params[key] = new Uint8Array(value);
1194        } else {
1195          throw new Error("Invalid PDF binary data: either typed array, " + "string, or array-like object is expected in the data property.");
1196        }
1197
1198        continue;
1199    }
1200
1201    params[key] = value;
1202  }
1203
1204  params.CMapReaderFactory = params.CMapReaderFactory || DefaultCMapReaderFactory;
1205  params.StandardFontDataFactory = params.StandardFontDataFactory || DefaultStandardFontDataFactory;
1206  params.ignoreErrors = params.stopAtErrors !== true;
1207  params.fontExtraProperties = params.fontExtraProperties === true;
1208  params.pdfBug = params.pdfBug === true;
1209  params.enableXfa = params.enableXfa === true;
1210
1211  if (!Number.isInteger(params.rangeChunkSize) || params.rangeChunkSize < 1) {
1212    params.rangeChunkSize = DEFAULT_RANGE_CHUNK_SIZE;
1213  }
1214
1215  if (typeof params.docBaseUrl !== "string" || (0, _display_utils.isDataScheme)(params.docBaseUrl)) {
1216    params.docBaseUrl = null;
1217  }
1218
1219  if (!Number.isInteger(params.maxImageSize) || params.maxImageSize < -1) {
1220    params.maxImageSize = -1;
1221  }
1222
1223  if (typeof params.cMapUrl !== "string") {
1224    params.cMapUrl = null;
1225  }
1226
1227  if (typeof params.standardFontDataUrl !== "string") {
1228    params.standardFontDataUrl = null;
1229  }
1230
1231  if (typeof params.useWorkerFetch !== "boolean") {
1232    params.useWorkerFetch = params.CMapReaderFactory === _display_utils.DOMCMapReaderFactory && params.StandardFontDataFactory === _display_utils.DOMStandardFontDataFactory;
1233  }
1234
1235  if (typeof params.isEvalSupported !== "boolean") {
1236    params.isEvalSupported = true;
1237  }
1238
1239  if (typeof params.disableFontFace !== "boolean") {
1240    params.disableFontFace = _is_node.isNodeJS;
1241  }
1242
1243  if (typeof params.useSystemFonts !== "boolean") {
1244    params.useSystemFonts = !_is_node.isNodeJS && !params.disableFontFace;
1245  }
1246
1247  if (typeof params.ownerDocument !== "object" || params.ownerDocument === null) {
1248    params.ownerDocument = globalThis.document;
1249  }
1250
1251  if (typeof params.disableRange !== "boolean") {
1252    params.disableRange = false;
1253  }
1254
1255  if (typeof params.disableStream !== "boolean") {
1256    params.disableStream = false;
1257  }
1258
1259  if (typeof params.disableAutoFetch !== "boolean") {
1260    params.disableAutoFetch = false;
1261  }
1262
1263  (0, _util.setVerbosityLevel)(params.verbosity);
1264
1265  if (!worker) {
1266    const workerParams = {
1267      verbosity: params.verbosity,
1268      port: _worker_options.GlobalWorkerOptions.workerPort
1269    };
1270    worker = workerParams.port ? PDFWorker.fromPort(workerParams) : new PDFWorker(workerParams);
1271    task._worker = worker;
1272  }
1273
1274  const docId = task.docId;
1275  worker.promise.then(function () {
1276    if (task.destroyed) {
1277      throw new Error("Loading aborted");
1278    }
1279
1280    const workerIdPromise = _fetchDocument(worker, params, rangeTransport, docId);
1281
1282    const networkStreamPromise = new Promise(function (resolve) {
1283      let networkStream;
1284
1285      if (rangeTransport) {
1286        networkStream = new _transport_stream.PDFDataTransportStream({
1287          length: params.length,
1288          initialData: params.initialData,
1289          progressiveDone: params.progressiveDone,
1290          contentDispositionFilename: params.contentDispositionFilename,
1291          disableRange: params.disableRange,
1292          disableStream: params.disableStream
1293        }, rangeTransport);
1294      } else if (!params.data) {
1295        networkStream = createPDFNetworkStream({
1296          url: params.url,
1297          length: params.length,
1298          httpHeaders: params.httpHeaders,
1299          withCredentials: params.withCredentials,
1300          rangeChunkSize: params.rangeChunkSize,
1301          disableRange: params.disableRange,
1302          disableStream: params.disableStream
1303        });
1304      }
1305
1306      resolve(networkStream);
1307    });
1308    return Promise.all([workerIdPromise, networkStreamPromise]).then(function ([workerId, networkStream]) {
1309      if (task.destroyed) {
1310        throw new Error("Loading aborted");
1311      }
1312
1313      const messageHandler = new _message_handler.MessageHandler(docId, workerId, worker.port);
1314      const transport = new WorkerTransport(messageHandler, task, networkStream, params);
1315      task._transport = transport;
1316      messageHandler.send("Ready", null);
1317    });
1318  }).catch(task._capability.reject);
1319  return task;
1320}
1321
1322async function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
1323  if (worker.destroyed) {
1324    throw new Error("Worker was destroyed");
1325  }
1326
1327  if (pdfDataRangeTransport) {
1328    source.length = pdfDataRangeTransport.length;
1329    source.initialData = pdfDataRangeTransport.initialData;
1330    source.progressiveDone = pdfDataRangeTransport.progressiveDone;
1331    source.contentDispositionFilename = pdfDataRangeTransport.contentDispositionFilename;
1332  }
1333
1334  const workerId = await worker.messageHandler.sendWithPromise("GetDocRequest", {
1335    docId,
1336    apiVersion: '2.15.24',
1337    source: {
1338      data: source.data,
1339      url: source.url,
1340      password: source.password,
1341      disableAutoFetch: source.disableAutoFetch,
1342      rangeChunkSize: source.rangeChunkSize,
1343      length: source.length
1344    },
1345    maxImageSize: source.maxImageSize,
1346    disableFontFace: source.disableFontFace,
1347    docBaseUrl: source.docBaseUrl,
1348    ignoreErrors: source.ignoreErrors,
1349    isEvalSupported: source.isEvalSupported,
1350    fontExtraProperties: source.fontExtraProperties,
1351    enableXfa: source.enableXfa,
1352    useSystemFonts: source.useSystemFonts,
1353    cMapUrl: source.useWorkerFetch ? source.cMapUrl : null,
1354    standardFontDataUrl: source.useWorkerFetch ? source.standardFontDataUrl : null
1355  });
1356
1357  if (worker.destroyed) {
1358    throw new Error("Worker was destroyed");
1359  }
1360
1361  return workerId;
1362}
1363
1364class PDFDocumentLoadingTask {
1365  static #docId = 0;
1366
1367  constructor() {
1368    this._capability = (0, _util.createPromiseCapability)();
1369    this._transport = null;
1370    this._worker = null;
1371    this.docId = `d${PDFDocumentLoadingTask.#docId++}`;
1372    this.destroyed = false;
1373    this.onPassword = null;
1374    this.onProgress = null;
1375    this.onUnsupportedFeature = null;
1376  }
1377
1378  get promise() {
1379    return this._capability.promise;
1380  }
1381
1382  async destroy() {
1383    this.destroyed = true;
1384    await this._transport?.destroy();
1385    this._transport = null;
1386
1387    if (this._worker) {
1388      this._worker.destroy();
1389
1390      this._worker = null;
1391    }
1392  }
1393
1394}
1395
1396exports.PDFDocumentLoadingTask = PDFDocumentLoadingTask;
1397
1398class PDFDataRangeTransport {
1399  constructor(length, initialData, progressiveDone = false, contentDispositionFilename = null) {
1400    this.length = length;
1401    this.initialData = initialData;
1402    this.progressiveDone = progressiveDone;
1403    this.contentDispositionFilename = contentDispositionFilename;
1404    this._rangeListeners = [];
1405    this._progressListeners = [];
1406    this._progressiveReadListeners = [];
1407    this._progressiveDoneListeners = [];
1408    this._readyCapability = (0, _util.createPromiseCapability)();
1409  }
1410
1411  addRangeListener(listener) {
1412    this._rangeListeners.push(listener);
1413  }
1414
1415  addProgressListener(listener) {
1416    this._progressListeners.push(listener);
1417  }
1418
1419  addProgressiveReadListener(listener) {
1420    this._progressiveReadListeners.push(listener);
1421  }
1422
1423  addProgressiveDoneListener(listener) {
1424    this._progressiveDoneListeners.push(listener);
1425  }
1426
1427  onDataRange(begin, chunk) {
1428    for (const listener of this._rangeListeners) {
1429      listener(begin, chunk);
1430    }
1431  }
1432
1433  onDataProgress(loaded, total) {
1434    this._readyCapability.promise.then(() => {
1435      for (const listener of this._progressListeners) {
1436        listener(loaded, total);
1437      }
1438    });
1439  }
1440
1441  onDataProgressiveRead(chunk) {
1442    this._readyCapability.promise.then(() => {
1443      for (const listener of this._progressiveReadListeners) {
1444        listener(chunk);
1445      }
1446    });
1447  }
1448
1449  onDataProgressiveDone() {
1450    this._readyCapability.promise.then(() => {
1451      for (const listener of this._progressiveDoneListeners) {
1452        listener();
1453      }
1454    });
1455  }
1456
1457  transportReady() {
1458    this._readyCapability.resolve();
1459  }
1460
1461  requestDataRange(begin, end) {
1462    (0, _util.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange");
1463  }
1464
1465  abort() {}
1466
1467}
1468
1469exports.PDFDataRangeTransport = PDFDataRangeTransport;
1470
1471class PDFDocumentProxy {
1472  constructor(pdfInfo, transport) {
1473    this._pdfInfo = pdfInfo;
1474    this._transport = transport;
1475    Object.defineProperty(this, "fingerprint", {
1476      get() {
1477        (0, _display_utils.deprecated)("`PDFDocumentProxy.fingerprint`, " + "please use `PDFDocumentProxy.fingerprints` instead.");
1478        return this.fingerprints[0];
1479      }
1480
1481    });
1482    Object.defineProperty(this, "getStats", {
1483      value: async () => {
1484        (0, _display_utils.deprecated)("`PDFDocumentProxy.getStats`, " + "please use the `PDFDocumentProxy.stats`-getter instead.");
1485        return this.stats || {
1486          streamTypes: {},
1487          fontTypes: {}
1488        };
1489      }
1490    });
1491  }
1492
1493  get annotationStorage() {
1494    return this._transport.annotationStorage;
1495  }
1496
1497  get numPages() {
1498    return this._pdfInfo.numPages;
1499  }
1500
1501  get fingerprints() {
1502    return this._pdfInfo.fingerprints;
1503  }
1504
1505  get stats() {
1506    return this._transport.stats;
1507  }
1508
1509  get isPureXfa() {
1510    return !!this._transport._htmlForXfa;
1511  }
1512
1513  get allXfaHtml() {
1514    return this._transport._htmlForXfa;
1515  }
1516
1517  getPage(pageNumber) {
1518    return this._transport.getPage(pageNumber);
1519  }
1520
1521  getPageIndex(ref) {
1522    return this._transport.getPageIndex(ref);
1523  }
1524
1525  getDestinations() {
1526    return this._transport.getDestinations();
1527  }
1528
1529  getDestination(id) {
1530    return this._transport.getDestination(id);
1531  }
1532
1533  getPageLabels() {
1534    return this._transport.getPageLabels();
1535  }
1536
1537  getPageLayout() {
1538    return this._transport.getPageLayout();
1539  }
1540
1541  getPageMode() {
1542    return this._transport.getPageMode();
1543  }
1544
1545  getViewerPreferences() {
1546    return this._transport.getViewerPreferences();
1547  }
1548
1549  getOpenAction() {
1550    return this._transport.getOpenAction();
1551  }
1552
1553  getAttachments() {
1554    return this._transport.getAttachments();
1555  }
1556
1557  getJavaScript() {
1558    return this._transport.getJavaScript();
1559  }
1560
1561  getJSActions() {
1562    return this._transport.getDocJSActions();
1563  }
1564
1565  getOutline() {
1566    return this._transport.getOutline();
1567  }
1568
1569  getOptionalContentConfig() {
1570    return this._transport.getOptionalContentConfig();
1571  }
1572
1573  getPermissions() {
1574    return this._transport.getPermissions();
1575  }
1576
1577  getMetadata() {
1578    return this._transport.getMetadata();
1579  }
1580
1581  getMarkInfo() {
1582    return this._transport.getMarkInfo();
1583  }
1584
1585  getData() {
1586    return this._transport.getData();
1587  }
1588
1589  getDownloadInfo() {
1590    return this._transport.downloadInfoCapability.promise;
1591  }
1592
1593  cleanup(keepLoadedFonts = false) {
1594    return this._transport.startCleanup(keepLoadedFonts || this.isPureXfa);
1595  }
1596
1597  destroy() {
1598    return this.loadingTask.destroy();
1599  }
1600
1601  get loadingParams() {
1602    return this._transport.loadingParams;
1603  }
1604
1605  get loadingTask() {
1606    return this._transport.loadingTask;
1607  }
1608
1609  saveDocument() {
1610    if (this._transport.annotationStorage.size <= 0) {
1611      (0, _display_utils.deprecated)("saveDocument called while `annotationStorage` is empty, " + "please use the getData-method instead.");
1612    }
1613
1614    return this._transport.saveDocument();
1615  }
1616
1617  getFieldObjects() {
1618    return this._transport.getFieldObjects();
1619  }
1620
1621  hasJSActions() {
1622    return this._transport.hasJSActions();
1623  }
1624
1625  getCalculationOrderIds() {
1626    return this._transport.getCalculationOrderIds();
1627  }
1628
1629}
1630
1631exports.PDFDocumentProxy = PDFDocumentProxy;
1632
1633class PDFPageProxy {
1634  constructor(pageIndex, pageInfo, transport, ownerDocument, pdfBug = false) {
1635    this._pageIndex = pageIndex;
1636    this._pageInfo = pageInfo;
1637    this._ownerDocument = ownerDocument;
1638    this._transport = transport;
1639    this._stats = pdfBug ? new _display_utils.StatTimer() : null;
1640    this._pdfBug = pdfBug;
1641    this.commonObjs = transport.commonObjs;
1642    this.objs = new PDFObjects();
1643    this._bitmaps = new Set();
1644    this.cleanupAfterRender = false;
1645    this.pendingCleanup = false;
1646    this._intentStates = new Map();
1647    this._annotationPromises = new Map();
1648    this.destroyed = false;
1649  }
1650
1651  get pageNumber() {
1652    return this._pageIndex + 1;
1653  }
1654
1655  get rotate() {
1656    return this._pageInfo.rotate;
1657  }
1658
1659  get ref() {
1660    return this._pageInfo.ref;
1661  }
1662
1663  get userUnit() {
1664    return this._pageInfo.userUnit;
1665  }
1666
1667  get view() {
1668    return this._pageInfo.view;
1669  }
1670
1671  getViewport({
1672    scale,
1673    rotation = this.rotate,
1674    offsetX = 0,
1675    offsetY = 0,
1676    dontFlip = false
1677  } = {}) {
1678    return new _display_utils.PageViewport({
1679      viewBox: this.view,
1680      scale,
1681      rotation,
1682      offsetX,
1683      offsetY,
1684      dontFlip
1685    });
1686  }
1687
1688  getAnnotations({
1689    intent = "display"
1690  } = {}) {
1691    const intentArgs = this._transport.getRenderingIntent(intent);
1692
1693    let promise = this._annotationPromises.get(intentArgs.cacheKey);
1694
1695    if (!promise) {
1696      promise = this._transport.getAnnotations(this._pageIndex, intentArgs.renderingIntent);
1697
1698      this._annotationPromises.set(intentArgs.cacheKey, promise);
1699
1700      promise = promise.then(annotations => {
1701        for (const annotation of annotations) {
1702          if (annotation.titleObj !== undefined) {
1703            Object.defineProperty(annotation, "title", {
1704              get() {
1705                (0, _display_utils.deprecated)("`title`-property on annotation, please use `titleObj` instead.");
1706                return annotation.titleObj.str;
1707              }
1708
1709            });
1710          }
1711
1712          if (annotation.contentsObj !== undefined) {
1713            Object.defineProperty(annotation, "contents", {
1714              get() {
1715                (0, _display_utils.deprecated)("`contents`-property on annotation, please use `contentsObj` instead.");
1716                return annotation.contentsObj.str;
1717              }
1718
1719            });
1720          }
1721        }
1722
1723        return annotations;
1724      });
1725    }
1726
1727    return promise;
1728  }
1729
1730  getJSActions() {
1731    return this._jsActionsPromise ||= this._transport.getPageJSActions(this._pageIndex);
1732  }
1733
1734  async getXfa() {
1735    return this._transport._htmlForXfa?.children[this._pageIndex] || null;
1736  }
1737
1738  render({
1739    canvasContext,
1740    viewport,
1741    intent = "display",
1742    annotationMode = _util.AnnotationMode.ENABLE,
1743    transform = null,
1744    imageLayer = null,
1745    canvasFactory = null,
1746    background = null,
1747    optionalContentConfigPromise = null,
1748    annotationCanvasMap = null,
1749    pageColors = null
1750  }) {
1751    if (arguments[0]?.renderInteractiveForms !== undefined) {
1752      (0, _display_utils.deprecated)("render no longer accepts the `renderInteractiveForms`-option, " + "please use the `annotationMode`-option instead.");
1753
1754      if (arguments[0].renderInteractiveForms === true && annotationMode === _util.AnnotationMode.ENABLE) {
1755        annotationMode = _util.AnnotationMode.ENABLE_FORMS;
1756      }
1757    }
1758
1759    if (arguments[0]?.includeAnnotationStorage !== undefined) {
1760      (0, _display_utils.deprecated)("render no longer accepts the `includeAnnotationStorage`-option, " + "please use the `annotationMode`-option instead.");
1761
1762      if (arguments[0].includeAnnotationStorage === true && annotationMode === _util.AnnotationMode.ENABLE) {
1763        annotationMode = _util.AnnotationMode.ENABLE_STORAGE;
1764      }
1765    }
1766
1767    if (this._stats) {
1768      this._stats.time("Overall");
1769    }
1770
1771    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode);
1772
1773    this.pendingCleanup = false;
1774
1775    if (!optionalContentConfigPromise) {
1776      optionalContentConfigPromise = this._transport.getOptionalContentConfig();
1777    }
1778
1779    let intentState = this._intentStates.get(intentArgs.cacheKey);
1780
1781    if (!intentState) {
1782      intentState = Object.create(null);
1783
1784      this._intentStates.set(intentArgs.cacheKey, intentState);
1785    }
1786
1787    if (intentState.streamReaderCancelTimeout) {
1788      clearTimeout(intentState.streamReaderCancelTimeout);
1789      intentState.streamReaderCancelTimeout = null;
1790    }
1791
1792    const canvasFactoryInstance = canvasFactory || new DefaultCanvasFactory({
1793      ownerDocument: this._ownerDocument
1794    });
1795    const intentPrint = !!(intentArgs.renderingIntent & _util.RenderingIntentFlag.PRINT);
1796
1797    if (!intentState.displayReadyCapability) {
1798      intentState.displayReadyCapability = (0, _util.createPromiseCapability)();
1799      intentState.operatorList = {
1800        fnArray: [],
1801        argsArray: [],
1802        lastChunk: false
1803      };
1804
1805      if (this._stats) {
1806        this._stats.time("Page Request");
1807      }
1808
1809      this._pumpOperatorList(intentArgs);
1810    }
1811
1812    const complete = error => {
1813      intentState.renderTasks.delete(internalRenderTask);
1814
1815      if (this.cleanupAfterRender || intentPrint) {
1816        this.pendingCleanup = true;
1817      }
1818
1819      this._tryCleanup();
1820
1821      if (error) {
1822        internalRenderTask.capability.reject(error);
1823
1824        this._abortOperatorList({
1825          intentState,
1826          reason: error instanceof Error ? error : new Error(error)
1827        });
1828      } else {
1829        internalRenderTask.capability.resolve();
1830      }
1831
1832      if (this._stats) {
1833        this._stats.timeEnd("Rendering");
1834
1835        this._stats.timeEnd("Overall");
1836      }
1837    };
1838
1839    const internalRenderTask = new InternalRenderTask({
1840      callback: complete,
1841      params: {
1842        canvasContext,
1843        viewport,
1844        transform,
1845        imageLayer,
1846        background
1847      },
1848      objs: this.objs,
1849      commonObjs: this.commonObjs,
1850      annotationCanvasMap,
1851      operatorList: intentState.operatorList,
1852      pageIndex: this._pageIndex,
1853      canvasFactory: canvasFactoryInstance,
1854      useRequestAnimationFrame: !intentPrint,
1855      pdfBug: this._pdfBug,
1856      pageColors
1857    });
1858    (intentState.renderTasks ||= new Set()).add(internalRenderTask);
1859    const renderTask = internalRenderTask.task;
1860    Promise.all([intentState.displayReadyCapability.promise, optionalContentConfigPromise]).then(([transparency, optionalContentConfig]) => {
1861      if (this.pendingCleanup) {
1862        complete();
1863        return;
1864      }
1865
1866      if (this._stats) {
1867        this._stats.time("Rendering");
1868      }
1869
1870      internalRenderTask.initializeGraphics({
1871        transparency,
1872        optionalContentConfig
1873      });
1874      internalRenderTask.operatorListChanged();
1875    }).catch(complete);
1876    return renderTask;
1877  }
1878
1879  getOperatorList({
1880    intent = "display",
1881    annotationMode = _util.AnnotationMode.ENABLE
1882  } = {}) {
1883    function operatorListChanged() {
1884      if (intentState.operatorList.lastChunk) {
1885        intentState.opListReadCapability.resolve(intentState.operatorList);
1886        intentState.renderTasks.delete(opListTask);
1887      }
1888    }
1889
1890    const intentArgs = this._transport.getRenderingIntent(intent, annotationMode, true);
1891
1892    let intentState = this._intentStates.get(intentArgs.cacheKey);
1893
1894    if (!intentState) {
1895      intentState = Object.create(null);
1896
1897      this._intentStates.set(intentArgs.cacheKey, intentState);
1898    }
1899
1900    let opListTask;
1901
1902    if (!intentState.opListReadCapability) {
1903      opListTask = Object.create(null);
1904      opListTask.operatorListChanged = operatorListChanged;
1905      intentState.opListReadCapability = (0, _util.createPromiseCapability)();
1906      (intentState.renderTasks ||= new Set()).add(opListTask);
1907      intentState.operatorList = {
1908        fnArray: [],
1909        argsArray: [],
1910        lastChunk: false
1911      };
1912
1913      if (this._stats) {
1914        this._stats.time("Page Request");
1915      }
1916
1917      this._pumpOperatorList(intentArgs);
1918    }
1919
1920    return intentState.opListReadCapability.promise;
1921  }
1922
1923  streamTextContent({
1924    disableCombineTextItems = false,
1925    includeMarkedContent = false
1926  } = {}) {
1927    const TEXT_CONTENT_CHUNK_SIZE = 100;
1928    return this._transport.messageHandler.sendWithStream("GetTextContent", {
1929      pageIndex: this._pageIndex,
1930      combineTextItems: disableCombineTextItems !== true,
1931      includeMarkedContent: includeMarkedContent === true
1932    }, {
1933      highWaterMark: TEXT_CONTENT_CHUNK_SIZE,
1934
1935      size(textContent) {
1936        return textContent.items.length;
1937      }
1938
1939    });
1940  }
1941
1942  getTextContent(params = {}) {
1943    if (this._transport._htmlForXfa) {
1944      return this.getXfa().then(xfa => {
1945        return _xfa_text.XfaText.textContent(xfa);
1946      });
1947    }
1948
1949    const readableStream = this.streamTextContent(params);
1950    return new Promise(function (resolve, reject) {
1951      function pump() {
1952        reader.read().then(function ({
1953          value,
1954          done
1955        }) {
1956          if (done) {
1957            resolve(textContent);
1958            return;
1959          }
1960
1961          Object.assign(textContent.styles, value.styles);
1962          textContent.items.push(...value.items);
1963          pump();
1964        }, reject);
1965      }
1966
1967      const reader = readableStream.getReader();
1968      const textContent = {
1969        items: [],
1970        styles: Object.create(null)
1971      };
1972      pump();
1973    });
1974  }
1975
1976  getStructTree() {
1977    return this._structTreePromise ||= this._transport.getStructTree(this._pageIndex);
1978  }
1979
1980  _destroy() {
1981    this.destroyed = true;
1982    const waitOn = [];
1983
1984    for (const intentState of this._intentStates.values()) {
1985      this._abortOperatorList({
1986        intentState,
1987        reason: new Error("Page was destroyed."),
1988        force: true
1989      });
1990
1991      if (intentState.opListReadCapability) {
1992        continue;
1993      }
1994
1995      for (const internalRenderTask of intentState.renderTasks) {
1996        waitOn.push(internalRenderTask.completed);
1997        internalRenderTask.cancel();
1998      }
1999    }
2000
2001    this.objs.clear();
2002
2003    for (const bitmap of this._bitmaps) {
2004      bitmap.close();
2005    }
2006
2007    this._bitmaps.clear();
2008
2009    this._annotationPromises.clear();
2010
2011    this._jsActionsPromise = null;
2012    this._structTreePromise = null;
2013    this.pendingCleanup = false;
2014    return Promise.all(waitOn);
2015  }
2016
2017  cleanup(resetStats = false) {
2018    this.pendingCleanup = true;
2019    return this._tryCleanup(resetStats);
2020  }
2021
2022  _tryCleanup(resetStats = false) {
2023    if (!this.pendingCleanup) {
2024      return false;
2025    }
2026
2027    for (const {
2028      renderTasks,
2029      operatorList
2030    } of this._intentStates.values()) {
2031      if (renderTasks.size > 0 || !operatorList.lastChunk) {
2032        return false;
2033      }
2034    }
2035
2036    this._intentStates.clear();
2037
2038    this.objs.clear();
2039
2040    this._annotationPromises.clear();
2041
2042    this._jsActionsPromise = null;
2043    this._structTreePromise = null;
2044
2045    if (resetStats && this._stats) {
2046      this._stats = new _display_utils.StatTimer();
2047    }
2048
2049    for (const bitmap of this._bitmaps) {
2050      bitmap.close();
2051    }
2052
2053    this._bitmaps.clear();
2054
2055    this.pendingCleanup = false;
2056    return true;
2057  }
2058
2059  _startRenderPage(transparency, cacheKey) {
2060    const intentState = this._intentStates.get(cacheKey);
2061
2062    if (!intentState) {
2063      return;
2064    }
2065
2066    if (this._stats) {
2067      this._stats.timeEnd("Page Request");
2068    }
2069
2070    if (intentState.displayReadyCapability) {
2071      intentState.displayReadyCapability.resolve(transparency);
2072    }
2073  }
2074
2075  _renderPageChunk(operatorListChunk, intentState) {
2076    for (let i = 0, ii = operatorListChunk.length; i < ii; i++) {
2077      intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]);
2078      intentState.operatorList.argsArray.push(operatorListChunk.argsArray[i]);
2079    }
2080
2081    intentState.operatorList.lastChunk = operatorListChunk.lastChunk;
2082
2083    for (const internalRenderTask of intentState.renderTasks) {
2084      internalRenderTask.operatorListChanged();
2085    }
2086
2087    if (operatorListChunk.lastChunk) {
2088      this._tryCleanup();
2089    }
2090  }
2091
2092  _pumpOperatorList({
2093    renderingIntent,
2094    cacheKey
2095  }) {
2096    const readableStream = this._transport.messageHandler.sendWithStream("GetOperatorList", {
2097      pageIndex: this._pageIndex,
2098      intent: renderingIntent,
2099      cacheKey,
2100      annotationStorage: renderingIntent & _util.RenderingIntentFlag.ANNOTATIONS_STORAGE ? this._transport.annotationStorage.serializable : null
2101    });
2102
2103    const reader = readableStream.getReader();
2104
2105    const intentState = this._intentStates.get(cacheKey);
2106
2107    intentState.streamReader = reader;
2108
2109    const pump = () => {
2110      reader.read().then(({
2111        value,
2112        done
2113      }) => {
2114        if (done) {
2115          intentState.streamReader = null;
2116          return;
2117        }
2118
2119        if (this._transport.destroyed) {
2120          return;
2121        }
2122
2123        this._renderPageChunk(value, intentState);
2124
2125        pump();
2126      }, reason => {
2127        intentState.streamReader = null;
2128
2129        if (this._transport.destroyed) {
2130          return;
2131        }
2132
2133        if (intentState.operatorList) {
2134          intentState.operatorList.lastChunk = true;
2135
2136          for (const internalRenderTask of intentState.renderTasks) {
2137            internalRenderTask.operatorListChanged();
2138          }
2139
2140          this._tryCleanup();
2141        }
2142
2143        if (intentState.displayReadyCapability) {
2144          intentState.displayReadyCapability.reject(reason);
2145        } else if (intentState.opListReadCapability) {
2146          intentState.opListReadCapability.reject(reason);
2147        } else {
2148          throw reason;
2149        }
2150      });
2151    };
2152
2153    pump();
2154  }
2155
2156  _abortOperatorList({
2157    intentState,
2158    reason,
2159    force = false
2160  }) {
2161    if (!intentState.streamReader) {
2162      return;
2163    }
2164
2165    if (!force) {
2166      if (intentState.renderTasks.size > 0) {
2167        return;
2168      }
2169
2170      if (reason instanceof _display_utils.RenderingCancelledException) {
2171        intentState.streamReaderCancelTimeout = setTimeout(() => {
2172          this._abortOperatorList({
2173            intentState,
2174            reason,
2175            force: true
2176          });
2177
2178          intentState.streamReaderCancelTimeout = null;
2179        }, RENDERING_CANCELLED_TIMEOUT);
2180        return;
2181      }
2182    }
2183
2184    intentState.streamReader.cancel(new _util.AbortException(reason.message)).catch(() => {});
2185    intentState.streamReader = null;
2186
2187    if (this._transport.destroyed) {
2188      return;
2189    }
2190
2191    for (const [curCacheKey, curIntentState] of this._intentStates) {
2192      if (curIntentState === intentState) {
2193        this._intentStates.delete(curCacheKey);
2194
2195        break;
2196      }
2197    }
2198
2199    this.cleanup();
2200  }
2201
2202  get stats() {
2203    return this._stats;
2204  }
2205
2206}
2207
2208exports.PDFPageProxy = PDFPageProxy;
2209
2210class LoopbackPort {
2211  constructor() {
2212    this._listeners = [];
2213    this._deferred = Promise.resolve();
2214  }
2215
2216  postMessage(obj, transfers) {
2217    const event = {
2218      data: structuredClone(obj, transfers)
2219    };
2220
2221    this._deferred.then(() => {
2222      for (const listener of this._listeners) {
2223        listener.call(this, event);
2224      }
2225    });
2226  }
2227
2228  addEventListener(name, listener) {
2229    this._listeners.push(listener);
2230  }
2231
2232  removeEventListener(name, listener) {
2233    const i = this._listeners.indexOf(listener);
2234
2235    this._listeners.splice(i, 1);
2236  }
2237
2238  terminate() {
2239    this._listeners.length = 0;
2240  }
2241
2242}
2243
2244exports.LoopbackPort = LoopbackPort;
2245const PDFWorkerUtil = {
2246  isWorkerDisabled: false,
2247  fallbackWorkerSrc: null,
2248  fakeWorkerId: 0
2249};
2250exports.PDFWorkerUtil = PDFWorkerUtil;
2251{
2252  if (_is_node.isNodeJS && typeof require === "function") {
2253    PDFWorkerUtil.isWorkerDisabled = true;
2254      PDFWorkerUtil.fallbackWorkerSrc = "~/Areas/WebPart/Contents/CanvasPDF/js/pdf.worker.js";
2255  } else if (typeof document === "object") {
2256    const pdfjsFilePath = document?.currentScript?.src;
2257
2258    if (pdfjsFilePath) {
2259      PDFWorkerUtil.fallbackWorkerSrc = pdfjsFilePath.replace(/(\.(?:min\.)?js)(\?.*)?$/i, ".w
2259orker$1$2");
2260    }
2261  }
2262
2263  PDFWorkerUtil.isSameOrigin = function (baseUrl, otherUrl) {
2264    let base;
2265
2266    try {
2267      base = new URL(baseUrl);
2268
2269      if (!base.origin || base.origin === "null") {
2270        return false;
2271      }
2272    } catch (e) {
2273      return false;
2274    }
2275
2276    const other = new URL(otherUrl, base);
2277    return base.origin === other.origin;
2278  };
2279
2280  PDFWorkerUtil.createCDNWrapper = function (url) {
2281    const wrapper = `importScripts("${url}");`;
2282    return URL.createObjectURL(new Blob([wrapper]));
2283  };
2284}
2285
2286class PDFWorker {
2287  static #workerPorts = new WeakMap();
2288
2289  constructor({
2290    name = null,
2291    port = null,
2292    verbosity = (0, _util.getVerbosityLevel)()
2293  } = {}) {
2294    if (port && PDFWorker.#workerPorts.has(port)) {
2295      throw new Error("Cannot use more than one PDFWorker per port.");
2296    }
2297
2298    this.name = name;
2299    this.destroyed = false;
2300    this.verbosity = verbosity;
2301    this._readyCapability = (0, _util.createPromiseCapability)();
2302    this._port = null;
2303    this._webWorker = null;
2304    this._messageHandler = null;
2305
2306    if (port) {
2307      PDFWorker.#workerPorts.set(port, this);
2308
2309      this._initializeFromPort(port);
2310
2311      return;
2312    }
2313
2314    this._initialize();
2315  }
2316
2317  get promise() {
2318    return this._readyCapability.promise;
2319  }
2320
2321  get port() {
2322    return this._port;
2323  }
2324
2325  get messageHandler() {
2326    return this._messageHandler;
2327  }
2328
2329  _initializeFromPort(port) {
2330    this._port = port;
2331    this._messageHandler = new _message_handler.MessageHandler("main", "worker", port);
2332
2333    this._messageHandler.on("ready", function () {});
2334
2335    this._readyCapability.resolve();
2336  }
2337
2338  _initialize() {
2339    if (typeof Worker !== "undefined" && !PDFWorkerUtil.isWorkerDisabled && !PDFWorker._mainThreadWorkerMessageHandler) {
2340      let workerSrc = PDFWorker.workerSrc;
2341
2342      try {
2343        if (!PDFWorkerUtil.isSameOrigin(window.location.href, workerSrc)) {
2344          workerSrc = PDFWorkerUtil.createCDNWrapper(new URL(workerSrc, window.location).href);
2345        }
2346
2347        const worker = new Worker(workerSrc);
2348        const messageHandler = new _message_handler.MessageHandler("main", "worker", worker);
2349
2350        const terminateEarly = () => {
2351          worker.removeEventListener("error", onWorkerError);
2352          messageHandler.destroy();
2353          worker.terminate();
2354
2355          if (this.destroyed) {
2356            this._readyCapability.reject(new Error("Worker was destroyed"));
2357          } else {
2358            this._setupFakeWorker();
2359          }
2360        };
2361
2362        const onWorkerError = () => {
2363          if (!this._webWorker) {
2364            terminateEarly();
2365          }
2366        };
2367
2368        worker.addEventListener("error", onWorkerError);
2369        messageHandler.on("test", data => {
2370          worker.removeEventListener("error", onWorkerError);
2371
2372          if (this.destroyed) {
2373            terminateEarly();
2374            return;
2375          }
2376
2377          if (data) {
2378            this._messageHandler = messageHandler;
2379            this._port = worker;
2380            this._webWorker = worker;
2381
2382            this._readyCapability.resolve();
2383
2384            messageHandler.send("configure", {
2385              verbosity: this.verbosity
2386            });
2387          } else {
2388            this._setupFakeWorker();
2389
2390            messageHandler.destroy();
2391            worker.terminate();
2392          }
2393        });
2394        messageHandler.on("ready", data => {
2395          worker.removeEventListener("error", onWorkerError);
2396
2397          if (this.destroyed) {
2398            terminateEarly();
2399            return;
2400          }
2401
2402          try {
2403            sendTest();
2404          } catch (e) {
2405            this._setupFakeWorker();
2406          }
2407        });
2408
2409        const sendTest = () => {
2410          const testObj = new Uint8Array();
2411          messageHandler.send("test", testObj, [testObj.buffer]);
2412        };
2413
2414        sendTest();
2415        return;
2416      } catch (e) {
2417        (0, _util.info)("The worker has been disabled.");
2418      }
2419    }
2420
2421    this._setupFakeWorker();
2422  }
2423
2424  _setupFakeWorker() {
2425    if (!PDFWorkerUtil.isWorkerDisabled) {
2426      (0, _util.warn)("Setting up fake worker.");
2427      PDFWorkerUtil.isWorkerDisabled = true;
2428    }
2429
2430    PDFWorker._setupFakeWorkerGlobal.then(WorkerMessageHandler => {
2431      if (this.destroyed) {
2432        this._readyCapability.reject(new Error("Worker was destroyed"));
2433
2434        return;
2435      }
2436
2437      const port = new LoopbackPort();
2438      this._port = port;
2439      const id = `fake${PDFWorkerUtil.fakeWorkerId++}`;
2440      const workerHandler = new _message_handler.MessageHandler(id + "_worker", id, port);
2441      WorkerMessageHandler.setup(workerHandler, port);
2442      const messageHandler = new _message_handler.MessageHandler(id, id + "_worker", port);
2443      this._messageHandler = messageHandler;
2444
2445      this._readyCapability.resolve();
2446
2447      messageHandler.send("configure", {
2448        verbosity: this.verbosity
2449      });
2450    }).catch(reason => {
2451      this._readyCapability.reject(new Error(`Setting up fake worker failed: "${reason.message}".`));
2452    });
2453  }
2454
2455  destroy() {
2456    this.destroyed = true;
2457
2458    if (this._webWorker) {
2459      this._webWorker.terminate();
2460
2461      this._webWorker = null;
2462    }
2463
2464    PDFWorker.#workerPorts.delete(this._port);
2465    this._port = null;
2466
2467    if (this._messageHandler) {
2468      this._messageHandler.destroy();
2469
2470      this._messageHandler = null;
2471    }
2472  }
2473
2474  static fromPort(params) {
2475    if (!params?.port) {
2476      throw new Error("PDFWorker.fromPort - invalid method signature.");
2477    }
2478
2479    if (this.#workerPorts.has(params.port)) {
2480      return this.#workerPorts.get(params.port);
2481    }
2482
2483    return new PDFWorker(params);
2484  }
2485
2486  static get workerSrc() {
2487    if (_worker_options.GlobalWorkerOptions.workerSrc) {
2488      return _worker_options.GlobalWorkerOptions.workerSrc;
2489    }
2490
2491    if (PDFWorkerUtil.fallbackWorkerSrc !== null) {
2492      if (!_is_node.isNodeJS) {
2493        (0, _display_utils.deprecated)('No "GlobalWorkerOptions.workerSrc" specified.');
2494      }
2495
2496      return PDFWorkerUtil.fallbackWorkerSrc;
2497    }
2498
2499    throw new Error('No "GlobalWorkerOptions.workerSrc" specified.');
2500  }
2501
2502  static get _mainThreadWorkerMessageHandler() {
2503    try {
2504      return globalThis.pdfjsWorker?.WorkerMessageHandler || null;
2505    } catch (ex) {
2506      return null;
2507    }
2508  }
2509
2510  static get _setupFakeWorkerGlobal() {
2511    const loader = async () => {
2512      const mainWorkerMessageHandler = this._mainThreadWorkerMessageHandler;
2513
2514      if (mainWorkerMessageHandler) {
2515        return mainWorkerMessageHandler;
2516      }
2517
2518      if (_is_node.isNodeJS && typeof require === "function") {
2519        const worker = eval("require")(this.workerSrc);
2520        return worker.WorkerMessageHandler;
2521      }
2522
2523      await (0, _display_utils.loadScript)(this.workerSrc);
2524      return window.pdfjsWorker.WorkerMessageHandler;
2525    };
2526
2527    return (0, _util.shadow)(this, "_setupFakeWorkerGlobal", loader());
2528  }
2529
2530}
2531
2532exports.PDFWorker = PDFWorker;
2533{
2534  PDFWorker.getWorkerSrc = function () {
2535    (0, _display_utils.deprecated)("`PDFWorker.getWorkerSrc()`, please use `PDFWorker.workerSrc` instead.");
2536    return this.workerSrc;
2537  };
2538}
2539
2540class WorkerTransport {
2541  #docStats = null;
2542  #pageCache = new Map();
2543  #pagePromises = new Map();
2544  #metadataPromise = null;
2545
2546  constructor(messageHandler, loadingTask, networkStream, params) {
2547    this.messageHandler = messageHandler;
2548    this.loadingTask = loadingTask;
2549    this.commonObjs = new PDFObjects();
2550    this.fontLoader = new _font_loader.FontLoader({
2551      docId: loadingTask.docId,
2552      onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
2553      ownerDocument: params.ownerDocument,
2554      styleElement: params.styleElement
2555    });
2556    this._params = params;
2557
2558    if (!params.useWorkerFetch) {
2559      this.CMapReaderFactory = new params.CMapReaderFactory({
2560        baseUrl: params.cMapUrl,
2561        isCompressed: params.cMapPacked
2562      });
2563      this.StandardFontDataFactory = new params.StandardFontDataFactory({
2564        baseUrl: params.standardFontDataUrl
2565      });
2566    }
2567
2568    this.destroyed = false;
2569    this.destroyCapability = null;
2570    this._passwordCapability = null;
2571    this._networkStream = networkStream;
2572    this._fullReader = null;
2573    this._lastProgress = null;
2574    this.downloadInfoCapability = (0, _util.createPromiseCapability)();
2575    this.setupMessageHandler();
2576  }
2577
2578  get annotationStorage() {
2579    return (0, _util.shadow)(this, "annotationStorage", new _annotation_storage.AnnotationStorage());
2580  }
2581
2582  get stats() {
2583    return this.#docStats;
2584  }
2585
2586  getRenderingIntent(intent, annotationMode = _util.AnnotationMode.ENABLE, isOpList = false) {
2587    let renderingIntent = _util.RenderingIntentFlag.DISPLAY;
2588    let annotationHash = "";
2589
2590    switch (intent) {
2591      case "any":
2592        renderingIntent = _util.RenderingIntentFlag.ANY;
2593        break;
2594
2595      case "display":
2596        break;
2597
2598      case "print":
2599        renderingIntent = _util.RenderingIntentFlag.PRINT;
2600        break;
2601
2602      default:
2603        (0, _util.warn)(`getRenderingIntent - invalid intent: ${intent}`);
2604    }
2605
2606    switch (annotationMode) {
2607      case _util.AnnotationMode.DISABLE:
2608        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_DISABLE;
2609        break;
2610
2611      case _util.AnnotationMode.ENABLE:
2612        break;
2613
2614      case _util.AnnotationMode.ENABLE_FORMS:
2615        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_FORMS;
2616        break;
2617
2618      case _util.AnnotationMode.ENABLE_STORAGE:
2619        renderingIntent += _util.RenderingIntentFlag.ANNOTATIONS_STORAGE;
2620        annotationHash = this.annotationStorage.hash;
2621        break;
2622
2623      default:
2624        (0, _util.warn)(`getRenderingIntent - invalid annotationMode: ${annotationMode}`);
2625    }
2626
2627    if (isOpList) {
2628      renderingIntent += _util.RenderingIntentFlag.OPLIST;
2629    }
2630
2631    return {
2632      renderingIntent,
2633      cacheKey: `${renderingIntent}_${annotationHash}`
2634    };
2635  }
2636
2637  destroy() {
2638    if (this.destroyCapability) {
2639      return this.destroyCapability.promise;
2640    }
2641
2642    this.destroyed = true;
2643    this.destroyCapability = (0, _util.createPromiseCapability)();
2644
2645    if (this._passwordCapability) {
2646      this._passwordCapability.reject(new Error("Worker was destroyed during onPassword callback"));
2647    }
2648
2649    const waitOn = [];
2650
2651    for (const page of this.#pageCache.values()) {
2652      waitOn.push(page._destroy());
2653    }
2654
2655    this.#pageCache.clear();
2656    this.#pagePromises.clear();
2657
2658    if (this.hasOwnProperty("annotationStorage")) {
2659      this.annotationStorage.resetModified();
2660    }
2661
2662    const terminated = this.messageHandler.sendWithPromise("Terminate", null);
2663    waitOn.push(terminated);
2664    Promise.all(waitOn).then(() => {
2665      this.commonObjs.clear();
2666      this.fontLoader.clear();
2667      this.#metadataPromise = null;
2668      this._getFieldObjectsPromise = null;
2669      this._hasJSActionsPromise = null;
2670
2671      if (this._networkStream) {
2672        this._networkStream.cancelAllRequests(new _util.AbortException("Worker was terminated."));
2673      }
2674
2675      if (this.messageHandler) {
2676        this.messageHandler.destroy();
2677        this.messageHandler = null;
2678      }
2679
2680      this.destroyCapability.resolve();
2681    }, this.destroyCapability.reject);
2682    return this.destroyCapability.promise;
2683  }
2684
2685  setupMessageHandler() {
2686    const {
2687      messageHandler,
2688      loadingTask
2689    } = this;
2690    messageHandler.on("GetReader", (data, sink) => {
2691      (0, _util.assert)(this._networkStream, "GetReader - no `IPDFStream` instance available.");
2692      this._fullReader = this._networkStream.getFullReader();
2693
2694      this._fullReader.onProgress = evt => {
2695        this._lastProgress = {
2696          loaded: evt.loaded,
2697          total: evt.total
2698        };
2699      };
2700
2701      sink.onPull = () => {
2702        this._fullReader.read().then(function ({
2703          value,
2704          done
2705        }) {
2706          if (done) {
2707            sink.close();
2708            return;
2709          }
2710
2711          (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetReader - expected an ArrayBuffer.");
2712          sink.enqueue(new Uint8Array(value), 1, [value]);
2713        }).catch(reason => {
2714          sink.error(reason);
2715        });
2716      };
2717
2718      sink.onCancel = reason => {
2719        this._fullReader.cancel(reason);
2720
2721        sink.ready.catch(readyReason => {
2722          if (this.destroyed) {
2723            return;
2724          }
2725
2726          throw readyReason;
2727        });
2728      };
2729    });
2730    messageHandler.on("ReaderHeadersReady", data => {
2731      const headersCapability = (0, _util.createPromiseCapability)();
2732      const fullReader = this._fullReader;
2733      fullReader.headersReady.then(() => {
2734        if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
2735          if (this._lastProgress) {
2736            loadingTask.onProgress?.(this._lastProgress);
2737          }
2738
2739          fullReader.onProgress = evt => {
2740            loadingTask.onProgress?.({
2741              loaded: evt.loaded,
2742              total: evt.total
2743            });
2744          };
2745        }
2746
2747        headersCapability.resolve({
2748          isStreamingSupported: fullReader.isStreamingSupported,
2749          isRangeSupported: fullReader.isRangeSupported,
2750          contentLength: fullReader.contentLength
2751        });
2752      }, headersCapability.reject);
2753      return headersCapability.promise;
2754    });
2755    messageHandler.on("GetRangeReader", (data, sink) => {
2756      (0, _util.assert)(this._networkStream, "GetRangeReader - no `IPDFStream` instance available.");
2757
2758      const rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
2759
2760      if (!rangeReader) {
2761        sink.close();
2762        return;
2763      }
2764
2765      sink.onPull = () => {
2766        rangeReader.read().then(function ({
2767          value,
2768          done
2769        }) {
2770          if (done) {
2771            sink.close();
2772            return;
2773          }
2774
2775          (0, _util.assert)((0, _util.isArrayBuffer)(value), "GetRangeReader - expected an ArrayBuffer.");
2776          sink.enqueue(new Uint8Array(value), 1, [value]);
2777        }).catch(reason => {
2778          sink.error(reason);
2779        });
2780      };
2781
2782      sink.onCancel = reason => {
2783        rangeReader.cancel(reason);
2784        sink.ready.catch(readyReason => {
2785          if (this.destroyed) {
2786            return;
2787          }
2788
2789          throw readyReason;
2790        });
2791      };
2792    });
2793    messageHandler.on("GetDoc", ({
2794      pdfInfo
2795    }) => {
2796      this._numPages = pdfInfo.numPages;
2797      this._htmlForXfa = pdfInfo.htmlForXfa;
2798      delete pdfInfo.htmlForXfa;
2799
2800      loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
2801    });
2802    messageHandler.on("DocException", function (ex) {
2803      let reason;
2804
2805      switch (ex.name) {
2806        case "PasswordException":
2807          reason = new _util.PasswordException(ex.message, ex.code);
2808          break;
2809
2810        case "InvalidPDFException":
2811          reason = new _util.InvalidPDFException(ex.message);
2812          break;
2813
2814        case "MissingPDFException":
2815          reason = new _util.MissingPDFException(ex.message);
2816          break;
2817
2818        case "UnexpectedResponseException":
2819          reason = new _util.UnexpectedResponseException(ex.message, ex.status);
2820          break;
2821
2822        case "UnknownErrorException":
2823          reason = new _util.UnknownErrorException(ex.message, ex.details);
2824          break;
2825
2826        default:
2827          (0, _util.unreachable)("DocException - expected a valid Error.");
2828      }
2829
2830      loadingTask._capability.reject(reason);
2831    });
2832    messageHandler.on("PasswordRequest", exception => {
2833      this._passwordCapability = (0, _util.createPromiseCapability)();
2834
2835      if (loadingTask.onPassword) {
2836        const updatePassword = password => {
2837          if (password instanceof Error) {
2838            this._passwordCapability.reject(password);
2839          } else {
2840            this._passwordCapability.resolve({
2841              password
2842            });
2843          }
2844        };
2845
2846        try {
2847          loadingTask.onPassword(updatePassword, exception.code);
2848        } catch (ex) {
2849          this._passwordCapability.reject(ex);
2850        }
2851      } else {
2852        this._passwordCapability.reject(new _util.PasswordException(exception.message, exception.code));
2853      }
2854
2855      return this._passwordCapability.promise;
2856    });
2857    messageHandler.on("DataLoaded", data => {
2858      loadingTask.onProgress?.({
2859        loaded: data.length,
2860        total: data.length
2861      });
2862      this.downloadInfoCapability.resolve(data);
2863    });
2864    messageHandler.on("StartRenderPage", data => {
2865      if (this.destroyed) {
2866        return;
2867      }
2868
2869      const page = this.#pageCache.get(data.pageIndex);
2870
2871      page._startRenderPage(data.transparency, data.cacheKey);
2872    });
2873    messageHandler.on("commonobj", ([id, type, exportedData]) => {
2874      if (this.destroyed) {
2875        return;
2876      }
2877
2878      if (this.commonObjs.has(id)) {
2879        return;
2880      }
2881
2882      switch (type) {
2883        case "Font":
2884          const params = this._params;
2885
2886          if ("error" in exportedData) {
2887            const exportedError = exportedData.error;
2888            (0, _util.warn)(`Error during font loading: ${exportedError}`);
2889            this.commonObjs.resolve(id, exportedError);
2890            break;
2891          }
2892
2893          let fontRegistry = null;
2894
2895          if (params.pdfBug && globalThis.FontInspector?.enabled) {
2896            fontRegistry = {
2897              registerFont(font, url) {
2898                globalThis.FontInspector.fontAdded(font, url);
2899              }
2900
2901            };
2902          }
2903
2904          const font = new _font_loader.FontFaceObject(exportedData, {
2905            isEvalSupported: params.isEvalSupported,
2906            disableFontFace: params.disableFontFace,
2907            ignoreErrors: params.ignoreErrors,
2908            onUnsupportedFeature: this._onUnsupportedFeature.bind(this),
2909            fontRegistry
2910          });
2911          this.fontLoader.bind(font).catch(reason => {
2912            return messageHandler.sendWithPromise("FontFallback", {
2913              id
2914            });
2915          }).finally(() => {
2916            if (!params.fontExtraProperties && font.data) {
2917              font.data = null;
2918            }
2919
2920            this.commonObjs.resolve(id, font);
2921          });
2922          break;
2923
2924        case "FontPath":
2925        case "Image":
2926          this.commonObjs.resolve(id, exportedData);
2927          break;
2928
2929        default:
2930          throw new Error(`Got unknown common object type ${type}`);
2931      }
2932    });
2933    messageHandler.on("obj", ([id, pageIndex, type, imageData]) => {
2934      if (this.destroyed) {
2935        return;
2936      }
2937
2938      const pageProxy = this.#pageCache.get(pageIndex);
2939
2940      if (pageProxy.objs.has(id)) {
2941        return;
2942      }
2943
2944      switch (type) {
2945        case "Image":
2946          pageProxy.objs.resolve(id, imageData);
2947          const MAX_IMAGE_SIZE_TO_STORE = 8000000;
2948
2949          if (imageData) {
2950            let length;
2951
2952            if (imageData.bitmap) {
2953              const {
2954                bitmap,
2955                width,
2956                height
2957              } = imageData;
2958              length = width * height * 4;
2959
2960              pageProxy._bitmaps.add(bitmap);
2961            } else {
2962              length = imageData.data?.length || 0;
2963            }
2964
2965            if (length > MAX_IMAGE_SIZE_TO_STORE) {
2966              pageProxy.cleanupAfterRender = true;
2967            }
2968          }
2969
2970          break;
2971
2972        case "Pattern":
2973          pageProxy.objs.resolve(id, imageData);
2974          break;
2975
2976        default:
2977          throw new Error(`Got unknown object type ${type}`);
2978      }
2979    });
2980    messageHandler.on("DocProgress", data => {
2981      if (this.destroyed) {
2982        return;
2983      }
2984
2985      loadingTask.onProgress?.({
2986        loaded: data.loaded,
2987        total: data.total
2988      });
2989    });
2990    messageHandler.on("DocStats", data => {
2991      if (this.destroyed) {
2992        return;
2993      }
2994
2995      this.#docStats = Object.freeze({
2996        streamTypes: Object.freeze(data.streamTypes),
2997        fontTypes: Object.freeze(data.fontTypes)
2998      });
2999    });
3000    messageHandler.on("UnsupportedFeature", this._onUnsupportedFeature.bind(this));
3001    messageHandler.on("FetchBuiltInCMap", data => {
3002      if (this.destroyed) {
3003        return Promise.reject(new Error("Worker was destroyed."));
3004      }
3005
3006      if (!this.CMapReaderFactory) {
3007        return Promise.reject(new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter."));
3008      }
3009
3010      return this.CMapReaderFactory.fetch(data);
3011    });
3012    messageHandler.on("FetchStandardFontData", data => {
3013      if (this.destroyed) {
3014        return Promise.reject(new Error("Worker was destroyed."));
3015      }
3016
3017      if (!this.StandardFontDataFactory) {
3018        return Promise.reject(new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter."));
3019      }
3020
3021      return this.StandardFontDataFactory.fetch(data);
3022    });
3023  }
3024
3025  _onUnsupportedFeature({
3026    featureId
3027  }) {
3028    if (this.destroyed) {
3029      return;
3030    }
3031
3032    this.loadingTask.onUnsupportedFeature?.(featureId);
3033  }
3034
3035  getData() {
3036    return this.messageHandler.sendWithPromise("GetData", null);
3037  }
3038
3039  getPage(pageNumber) {
3040    if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
3041      return Promise.reject(new Error("Invalid page request."));
3042    }
3043
3044    const pageIndex = pageNumber - 1,
3045          cachedPromise = this.#pagePromises.get(pageIndex);
3046
3047    if (cachedPromise) {
3048      return cachedPromise;
3049    }
3050
3051    const promise = this.messageHandler.sendWithPromise("GetPage", {
3052      pageIndex
3053    }).then(pageInfo => {
3054      if (this.destroyed) {
3055        throw new Error("Transport destroyed");
3056      }
3057
3058      const page = new PDFPageProxy(pageIndex, pageInfo, this, this._params.ownerDocument, this._params.pdfBug);
3059      this.#pageCache.set(pageIndex, page);
3060      return page;
3061    });
3062    this.#pagePromises.set(pageIndex, promise);
3063    return promise;
3064  }
3065
3066  getPageIndex(ref) {
3067    if (typeof ref !== "object" || ref === null || !Number.isInteger(ref.num) || ref.num < 0 || !Number.isInteger(ref.gen) || ref.gen < 0) {
3068      return Promise.reject(new Error("Invalid pageIndex request."));
3069    }
3070
3071    return this.messageHandler.sendWithPromise("GetPageIndex", {
3072      num: ref.num,
3073      gen: ref.gen
3074    });
3075  }
3076
3077  getAnnotations(pageIndex, intent) {
3078    return this.messageHandler.sendWithPromise("GetAnnotations", {
3079      pageIndex,
3080      intent
3081    });
3082  }
3083
3084  saveDocument() {
3085    return this.messageHandler.sendWithPromise("SaveDocument", {
3086      isPureXfa: !!this._htmlForXfa,
3087      numPages: this._numPages,
3088      annotationStorage: this.annotationStorage.serializable,
3089      filename: this._fullReader?.filename ?? null
3090    }).finally(() => {
3091      this.annotationStorage.resetModified();
3092    });
3093  }
3094
3095  getFieldObjects() {
3096    return this._getFieldObjectsPromise ||= this.messageHandler.sendWithPromise("GetFieldObjects", null);
3097  }
3098
3099  hasJSActions() {
3100    return this._hasJSActionsPromise ||= this.messageHandler.sendWithPromise("HasJSActions", null);
3101  }
3102
3103  getCalculationOrderIds() {
3104    return this.messageHandler.sendWithPromise("GetCalculationOrderIds", null);
3105  }
3106
3107  getDestinations() {
3108    return this.messageHandler.sendWithPromise("GetDestinations", null);
3109  }
3110
3111  getDestination(id) {
3112    if (typeof id !== "string") {
3113      return Promise.reject(new Error("Invalid destination request."));
3114    }
3115
3116    return this.messageHandler.sendWithPromise("GetDestination", {
3117      id
3118    });
3119  }
3120
3121  getPageLabels() {
3122    return this.messageHandler.sendWithPromise("GetPageLabels", null);
3123  }
3124
3125  getPageLayout() {
3126    return this.messageHandler.sendWithPromise("GetPageLayout", null);
3127  }
3128
3129  getPageMode() {
3130    return this.messageHandler.sendWithPromise("GetPageMode", null);
3131  }
3132
3133  getViewerPreferences() {
3134    return this.messageHandler.sendWithPromise("GetViewerPreferences", null);
3135  }
3136
3137  getOpenAction() {
3138    return this.messageHandler.sendWithPromise("GetOpenAction", null);
3139  }
3140
3141  getAttachments() {
3142    return this.messageHandler.sendWithPromise("GetAttachments", null);
3143  }
3144
3145  getJavaScript() {
3146    return this.messageHandler.sendWithPromise("GetJavaScript", null);
3147  }
3148
3149  getDocJSActions() {
3150    return this.messageHandler.sendWithPromise("GetDocJSActions", null);
3151  }
3152
3153  getPageJSActions(pageIndex) {
3154    return this.messageHandler.sendWithPromise("GetPageJSActions", {
3155      pageIndex
3156    });
3157  }
3158
3159  getStructTree(pageIndex) {
3160    return this.messageHandler.sendWithPromise("GetStructTree", {
3161      pageIndex
3162    });
3163  }
3164
3165  getOutline() {
3166    return this.messageHandler.sendWithPromise("GetOutline", null);
3167  }
3168
3169  getOptionalContentConfig() {
3170    return this.messageHandler.sendWithPromise("GetOptionalContentConfig", null).then(results => {
3171      return new _optional_content_config.OptionalContentConfig(results);
3172    });
3173  }
3174
3175  getPermissions() {
3176    return this.messageHandler.sendWithPromise("GetPermissions", null);
3177  }
3178
3179  getMetadata() {
3180    return this.#metadataPromise ||= this.messageHandler.sendWithPromise("GetMetadata", null).then(results => {
3181      return {
3182        info: results[0],
3183        metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
3184        contentDispositionFilename: this._fullReader?.filename ?? null,
3185        contentLength: this._fullReader?.contentLength ?? null
3186      };
3187    });
3188  }
3189
3190  getMarkInfo() {
3191    return this.messageHandler.sendWithPromise("GetMarkInfo", null);
3192  }
3193
3194  async startCleanup(keepLoadedFonts = false) {
3195    await this.messageHandler.sendWithPromise("Cleanup", null);
3196
3197    if (this.destroyed) {
3198      return;
3199    }
3200
3201    for (const page of this.#pageCache.values()) {
3202      const cleanupSuccessful = page.cleanup();
3203
3204      if (!cleanupSuccessful) {
3205        throw new Error(`startCleanup: Page ${page.pageNumber} is currently rendering.`);
3206      }
3207    }
3208
3209    this.commonObjs.clear();
3210
3211    if (!keepLoadedFonts) {
3212      this.fontLoader.clear();
3213    }
3214
3215    this.#metadataPromise = null;
3216    this._getFieldObjectsPromise = null;
3217    this._hasJSActionsPromise = null;
3218  }
3219
3220  get loadingParams() {
3221    const params = this._params;
3222    return (0, _util.shadow)(this, "loadingParams", {
3223      disableAutoFetch: params.disableAutoFetch,
3224      enableXfa: params.enableXfa
3225    });
3226  }
3227
3228}
3229
3230class PDFObjects {
3231  #objs = Object.create(null);
3232
3233  #ensureObj(objId) {
3234    const obj = this.#objs[objId];
3235
3236    if (obj) {
3237      return obj;
3238    }
3239
3240    return this.#objs[objId] = {
3241      capability: (0, _util.createPromiseCapability)(),
3242      data: null
3243    };
3244  }
3245
3246  get(objId, callback = null) {
3247    if (callback) {
3248      const obj = this.#ensureObj(objId);
3249      obj.capability.promise.then(() => callback(obj.data));
3250      return null;
3251    }
3252
3253    const obj = this.#objs[objId];
3254
3255    if (!obj?.capability.settled) {
3256      throw new Error(`Requesting object that isn't resolved yet ${objId}.`);
3257    }
3258
3259    return obj.data;
3260  }
3261
3262  has(objId) {
3263    const obj = this.#objs[objId];
3264    return obj?.capability.settled || false;
3265  }
3266
3267  resolve(objId, data = null) {
3268    const obj = this.#ensureObj(objId);
3269    obj.data = data;
3270    obj.capability.resolve();
3271  }
3272
3273  clear() {
3274    this.#objs = Object.create(null);
3275  }
3276
3277}
3278
3279class RenderTask {
3280  constructor(internalRenderTask) {
3281    this._internalRenderTask = internalRenderTask;
3282    this.onContinue = null;
3283  }
3284
3285  get promise() {
3286    return this._internalRenderTask.capability.promise;
3287  }
3288
3289  cancel() {
3290    this._internalRenderTask.cancel();
3291  }
3292
3293}
3294
3295exports.RenderTask = RenderTask;
3296
3297class InternalRenderTask {
3298  static #canvasInUse = new WeakSet();
3299
3300  constructor({
3301    callback,
3302    params,
3303    objs,
3304    commonObjs,
3305    annotationCanvasMap,
3306    operatorList,
3307    pageIndex,
3308    canvasFactory,
3309    useRequestAnimationFrame = false,
3310    pdfBug = false,
3311    pageColors = null
3312  }) {
3313    this.callback = callback;
3314    this.params = params;
3315    this.objs = objs;
3316    this.commonObjs = commonObjs;
3317    this.annotationCanvasMap = annotationCanvasMap;
3318    this.operatorListIdx = null;
3319    this.operatorList = operatorList;
3320    this._pageIndex = pageIndex;
3321    this.canvasFactory = canvasFactory;
3322    this._pdfBug = pdfBug;
3323    this.pageColors = pageColors;
3324    this.running = false;
3325    this.graphicsReadyCallback = null;
3326    this.graphicsReady = false;
3327    this._useRequestAnimationFrame = useRequestAnimationFrame === true && typeof window !== "undefined";
3328    this.cancelled = false;
3329    this.capability = (0, _util.createPromiseCapability)();
3330    this.task = new RenderTask(this);
3331    this._cancelBound = this.cancel.bind(this);
3332    this._continueBound = this._continue.bind(this);
3333    this._scheduleNextBound = this._scheduleNext.bind(this);
3334    this._nextBound = this._next.bind(this);
3335    this._canvas = params.canvasContext.canvas;
3336  }
3337
3338  get completed() {
3339    return this.capability.promise.catch(function () {});
3340  }
3341
3342  initializeGraphics({
3343    transparency = false,
3344    optionalContentConfig
3345  }) {
3346    if (this.cancelled) {
3347      return;
3348    }
3349
3350    if (this._canvas) {
3351      if (InternalRenderTask.#canvasInUse.has(this._canvas)) {
3352        throw new Error("Cannot use the same canvas during multiple render() operations. " + "Use different canvas or ensure previous operations were " + "cancelled or completed.");
3353      }
3354
3355      InternalRenderTask.#canvasInUse.add(this._canvas);
3356    }
3357
3358    if (this._pdfBug && globalThis.StepperManager?.enabled) {
3359      this.stepper = globalThis.StepperManager.create(this._pageIndex);
3360      this.stepper.init(this.operatorList);
3361      this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
3362    }
3363
3364    const {
3365      canvasContext,
3366      viewport,
3367      transform,
3368      imageLayer,
3369      background
3370    } = this.params;
3371    this.gfx = new _canvas.CanvasGraphics(canvasContext, this.commonObjs, this.objs, this.canvasFactory, imageLayer, optionalContentConfig, this.annotationCanvasMap, this.pageColors);
3372    this.gfx.beginDrawing({
3373      transform,
3374      viewport,
3375      transparency,
3376      background
3377    });
3378    this.operatorListIdx = 0;
3379    this.graphicsReady = true;
3380
3381    if (this.graphicsReadyCallback) {
3382      this.graphicsReadyCallback();
3383    }
3384  }
3385
3386  cancel(error = null) {
3387    this.running = false;
3388    this.cancelled = true;
3389
3390    if (this.gfx) {
3391      this.gfx.endDrawing();
3392    }
3393
3394    if (this._canvas) {
3395      InternalRenderTask.#canvasInUse.delete(this._canvas);
3396    }
3397
3398    this.callback(error || new _display_utils.RenderingCancelledException(`Rendering cancelled, page ${this._pageIndex + 1}`, "canvas"));
3399  }
3400
3401  operatorListChanged() {
3402    if (!this.graphicsReady) {
3403      if (!this.graphicsReadyCallback) {
3404        this.graphicsReadyCallback = this._continueBound;
3405      }
3406
3407      return;
3408    }
3409
3410    if (this.stepper) {
3411      this.stepper.updateOperatorList(this.operatorList);
3412    }
3413
3414    if (this.running) {
3415      return;
3416    }
3417
3418    this._continue();
3419  }
3420
3421  _continue() {
3422    this.running = true;
3423
3424    if (this.cancelled) {
3425      return;
3426    }
3427
3428    if (this.task.onContinue) {
3429      this.task.onContinue(this._scheduleNextBound);
3430    } else {
3431      this._scheduleNext();
3432    }
3433  }
3434
3435  _scheduleNext() {
3436    if (this._useRequestAnimationFrame) {
3437      window.requestAnimationFrame(() => {
3438        this._nextBound().catch(this._cancelBound);
3439      });
3440    } else {
3441      Promise.resolve().then(this._nextBound).catch(this._cancelBound);
3442    }
3443  }
3444
3445  async _next() {
3446    if (this.cancelled) {
3447      return;
3448    }
3449
3450    this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper);
3451
3452    if (this.operatorListIdx === this.operatorList.argsArray.length) {
3453      this.running = false;
3454
3455      if (this.operatorList.lastChunk) {
3456        this.gfx.endDrawing();
3457
3458        if (this._canvas) {
3459          InternalRenderTask.#canvasInUse.delete(this._canvas);
3460        }
3461
3462        this.callback();
3463      }
3464    }
3465  }
3466
3467}
3468
3469const version = '2.15.24';
3470exports.version = version;
3471const build = '5b02c685d';
3472exports.build = build;
3473
3474/***/ }),
3475/* 5 */
3476/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3477
3478
3479
3480Object.defineProperty(exports, "__esModule", ({
3481  value: true
3482}));
3483exports.StatTimer = exports.RenderingCancelledException = exports.PixelsPerInch = exports.PageViewport = exports.PDFDateString = exports.DOMStandardFontDataFactory = exports.DOMSVGFactory = exports.DOMCanvasFactory = exports.DOMCMapReaderFactory = void 0;
3484exports.deprecated = deprecated;
3485exports.getFilenameFromUrl = getFilenameFromUrl;
3486exports.getPdfFilenameFromUrl = getPdfFilenameFromUrl;
3487exports.getXfaPageViewport = getXfaPageViewport;
3488exports.isDataScheme = isDataScheme;
3489exports.isPdfFile = isPdfFile;
3490exports.isValidFetchUrl = isValidFetchUrl;
3491exports.loadScript = loadScript;
3492
3493var _base_factory = __w_pdfjs_require__(6);
3494
3495var _util = __w_pdfjs_require__(1);
3496
3497const SVG_NS = "http://www.w3.org/2000/svg";
3498
3499class PixelsPerInch {
3500  static CSS = 96.0;
3501  static PDF = 72.0;
3502  static PDF_TO_CSS_UNITS = this.CSS / this.PDF;
3503}
3504
3505exports.PixelsPerInch = PixelsPerInch;
3506
3507class DOMCanvasFactory extends _base_factory.BaseCanvasFactory {
3508  constructor({
3509    ownerDocument = globalThis.document
3510  } = {}) {
3511    super();
3512    this._document = ownerDocument;
3513  }
3514
3515  _createCanvas(width, height) {
3516    const canvas = this._document.createElement("canvas");
3517
3518    canvas.width = width;
3519    canvas.height = height;
3520    return canvas;
3521  }
3522
3523}
3524
3525exports.DOMCanvasFactory = DOMCanvasFactory;
3526
3527async function fetchData(url, asTypedArray = false) {
3528  if (isValidFetchUrl(url, document.baseURI)) {
3529    const response = await fetch(url);
3530
3531    if (!response.ok) {
3532      throw new Error(response.statusText);
3533    }
3534
3535    return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : (0, _util.stringToBytes)(await response.text());
3536  }
3537
3538  return new Promise((resolve, reject) => {
3539    const request = new XMLHttpRequest();
3540    request.open("GET", url, true);
3541
3542    if (asTypedArray) {
3543      request.responseType = "arraybuffer";
3544    }
3545
3546    request.onreadystatechange = () => {
3547      if (request.readyState !== XMLHttpRequest.DONE) {
3548        return;
3549      }
3550
3551      if (request.status === 200 || request.status === 0) {
3552        let data;
3553
3554        if (asTypedArray && request.response) {
3555          data = new Uint8Array(request.response);
3556        } else if (!asTypedArray && request.responseText) {
3557          data = (0, _util.stringToBytes)(request.responseText);
3558        }
3559
3560        if (data) {
3561          resolve(data);
3562          return;
3563        }
3564      }
3565
3566      reject(new Error(request.statusText));
3567    };
3568
3569    request.send(null);
3570  });
3571}
3572
3573class DOMCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
3574  _fetchData(url, compressionType) {
3575    return fetchData(url, this.isCompressed).then(data => {
3576      return {
3577        cMapData: data,
3578        compressionType
3579      };
3580    });
3581  }
3582
3583}
3584
3585exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
3586
3587class DOMStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
3588  _fetchData(url) {
3589    return fetchData(url, true);
3590  }
3591
3592}
3593
3594exports.DOMStandardFontDataFactory = DOMStandardFontDataFactory;
3595
3596class DOMSVGFactory extends _base_factory.BaseSVGFactory {
3597  _createSVG(type) {
3598    return document.createElementNS(SVG_NS, type);
3599  }
3600
3601}
3602
3603exports.DOMSVGFactory = DOMSVGFactory;
3604
3605class PageViewport {
3606  constructor({
3607    viewBox,
3608    scale,
3609    rotation,
3610    offsetX = 0,
3611    offsetY = 0,
3612    dontFlip = false
3613  }) {
3614    this.viewBox = viewBox;
3615    this.scale = scale;
3616    this.rotation = rotation;
3617    this.offsetX = offsetX;
3618    this.offsetY = offsetY;
3619    const centerX = (viewBox[2] + viewBox[0]) / 2;
3620    const centerY = (viewBox[3] + viewBox[1]) / 2;
3621    let rotateA, rotateB, rotateC, rotateD;
3622    rotation %= 360;
3623
3624    if (rotation < 0) {
3625      rotation += 360;
3626    }
3627
3628    switch (rotation) {
3629      case 180:
3630        rotateA = -1;
3631        rotateB = 0;
3632        rotateC = 0;
3633        rotateD = 1;
3634        break;
3635
3636      case 90:
3637        rotateA = 0;
3638        rotateB = 1;
3639        rotateC = 1;
3640        rotateD = 0;
3641        break;
3642
3643      case 270:
3644        rotateA = 0;
3645        rotateB = -1;
3646        rotateC = -1;
3647        rotateD = 0;
3648        break;
3649
3650      case 0:
3651        rotateA = 1;
3652        rotateB = 0;
3653        rotateC = 0;
3654        rotateD = -1;
3655        break;
3656
3657      default:
3658        throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.");
3659    }
3660
3661    if (dontFlip) {
3662      rotateC = -rotateC;
3663      rotateD = -rotateD;
3664    }
3665
3666    let offsetCanvasX, offsetCanvasY;
3667    let width, height;
3668
3669    if (rotateA === 0) {
3670      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
3671      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
3672      width = Math.abs(viewBox[3] - viewBox[1]) * scale;
3673      height = Math.abs(viewBox[2] - viewBox[0]) * scale;
3674    } else {
3675      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
3676      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
3677      width = Math.abs(viewBox[2] - viewBox[0]) * scale;
3678      height = Math.abs(viewBox[3] - viewBox[1]) * scale;
3679    }
3680
3681    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
3682    this.width = width;
3683    this.height = height;
3684  }
3685
3686  clone({
3687    scale = this.scale,
3688    rotation = this.rotation,
3689    offsetX = this.offsetX,
3690    offsetY = this.offsetY,
3691    dontFlip = false
3692  }
3692 = {}) {
3693    return new PageViewport({
3694      viewBox: this.viewBox.slice(),
3695      scale,
3696      rotation,
3697      offsetX,
3698      offsetY,
3699      dontFlip
3700    });
3701  }
3702
3703  convertToViewportPoint(x, y) {
3704    return _util.Util.applyTransform([x, y], this.transform);
3705  }
3706
3707  convertToViewportRectangle(rect) {
3708    const topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
3709
3710    const bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
3711
3712    return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
3713  }
3714
3715  convertToPdfPoint(x, y) {
3716    return _util.Util.applyInverseTransform([x, y], this.transform);
3717  }
3718
3719}
3720
3721exports.PageViewport = PageViewport;
3722
3723class RenderingCancelledException extends _util.BaseException {
3724  constructor(msg, type) {
3725    super(msg, "RenderingCancelledException");
3726    this.type = type;
3727  }
3728
3729}
3730
3731exports.RenderingCancelledException = RenderingCancelledException;
3732
3733function isDataScheme(url) {
3734  const ii = url.length;
3735  let i = 0;
3736
3737  while (i < ii && url[i].trim() === "") {
3738    i++;
3739  }
3740
3741  return url.substring(i, i + 5).toLowerCase() === "data:";
3742}
3743
3744function isPdfFile(filename) {
3745  return typeof filename === "string" && /\.pdf$/i.test(filename);
3746}
3747
3748function getFilenameFromUrl(url) {
3749  const anchor = url.indexOf("#");
3750  const query = url.indexOf("?");
3751  const end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
3752  return url.substring(url.lastIndexOf("/", end) + 1, end);
3753}
3754
3755function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") {
3756  if (typeof url !== "string") {
3757    return defaultFilename;
3758  }
3759
3760  if (isDataScheme(url)) {
3761    (0, _util.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.');
3762    return defaultFilename;
3763  }
3764
3765  const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
3766  const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
3767  const splitURI = reURI.exec(url);
3768  let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
3769
3770  if (suggestedFilename) {
3771    suggestedFilename = suggestedFilename[0];
3772
3773    if (suggestedFilename.includes("%")) {
3774      try {
3775        suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
3776      } catch (ex) {}
3777    }
3778  }
3779
3780  return suggestedFilename || defaultFilename;
3781}
3782
3783class StatTimer {
3784  constructor() {
3785    this.started = Object.create(null);
3786    this.times = [];
3787  }
3788
3789  time(name) {
3790    if (name in this.started) {
3791      (0, _util.warn)(`Timer is already running for ${name}`);
3792    }
3793
3794    this.started[name] = Date.now();
3795  }
3796
3797  timeEnd(name) {
3798    if (!(name in this.started)) {
3799      (0, _util.warn)(`Timer has not been started for ${name}`);
3800    }
3801
3802    this.times.push({
3803      name,
3804      start: this.started[name],
3805      end: Date.now()
3806    });
3807    delete this.started[name];
3808  }
3809
3810  toString() {
3811    const outBuf = [];
3812    let longest = 0;
3813
3814    for (const time of this.times) {
3815      const name = time.name;
3816
3817      if (name.length > longest) {
3818        longest = name.length;
3819      }
3820    }
3821
3822    for (const time of this.times) {
3823      const duration = time.end - time.start;
3824      outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`);
3825    }
3826
3827    return outBuf.join("");
3828  }
3829
3830}
3831
3832exports.StatTimer = StatTimer;
3833
3834function isValidFetchUrl(url, baseUrl) {
3835  try {
3836    const {
3837      protocol
3838    } = baseUrl ? new URL(url, baseUrl) : new URL(url);
3839    return protocol === "http:" || protocol === "https:";
3840  } catch (ex) {
3841    return false;
3842  }
3843}
3844
3845function loadScript(src, removeScriptElement = false) {
3846  return new Promise((resolve, reject) => {
3847    const script = document.createElement("script");
3848    script.src = src;
3849
3850    script.onload = function (evt) {
3851      if (removeScriptElement) {
3852        script.remove();
3853      }
3854
3855      resolve(evt);
3856    };
3857
3858    script.onerror = function () {
3859      reject(new Error(`Cannot load script at: ${script.src}`));
3860    };
3861
3862    (document.head || document.documentElement).appendChild(script);
3863  });
3864}
3865
3866function deprecated(details) {
3867  console.log("Deprecated API usage: " + details);
3868}
3869
3870let pdfDateStringRegex;
3871
3872class PDFDateString {
3873  static toDateObject(input) {
3874    if (!input || typeof input !== "string") {
3875      return null;
3876    }
3877
3878    if (!pdfDateStringRegex) {
3879      pdfDateStringRegex = new RegExp("^D:" + "(\\d{4})" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "(\\d{2})?" + "([Z|+|-])?" + "(\\d{2})?" + "'?" + "(\\d{2})?" + "'?");
3880    }
3881
3882    const matches = pdfDateStringRegex.exec(input);
3883
3884    if (!matches) {
3885      return null;
3886    }
3887
3888    const year = parseInt(matches[1], 10);
3889    let month = parseInt(matches[2], 10);
3890    month = month >= 1 && month <= 12 ? month - 1 : 0;
3891    let day = parseInt(matches[3], 10);
3892    day = day >= 1 && day <= 31 ? day : 1;
3893    let hour = parseInt(matches[4], 10);
3894    hour = hour >= 0 && hour <= 23 ? hour : 0;
3895    let minute = parseInt(matches[5], 10);
3896    minute = minute >= 0 && minute <= 59 ? minute : 0;
3897    let second = parseInt(matches[6], 10);
3898    second = second >= 0 && second <= 59 ? second : 0;
3899    const universalTimeRelation = matches[7] || "Z";
3900    let offsetHour = parseInt(matches[8], 10);
3901    offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
3902    let offsetMinute = parseInt(matches[9], 10) || 0;
3903    offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
3904
3905    if (universalTimeRelation === "-") {
3906      hour += offsetHour;
3907      minute += offsetMinute;
3908    } else if (universalTimeRelation === "+") {
3909      hour -= offsetHour;
3910      minute -= offsetMinute;
3911    }
3912
3913    return new Date(Date.UTC(year, month, day, hour, minute, second));
3914  }
3915
3916}
3917
3918exports.PDFDateString = PDFDateString;
3919
3920function getXfaPageViewport(xfaPage, {
3921  scale = 1,
3922  rotation = 0
3923}) {
3924  const {
3925    width,
3926    height
3927  } = xfaPage.attributes.style;
3928  const viewBox = [0, 0, parseInt(width), parseInt(height)];
3929  return new PageViewport({
3930    viewBox,
3931    scale,
3932    rotation
3933  });
3934}
3935
3936/***/ }),
3937/* 6 */
3938/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
3939
3940
3941
3942Object.defineProperty(exports, "__esModule", ({
3943  value: true
3944}));
3945exports.BaseStandardFontDataFactory = exports.BaseSVGFactory = exports.BaseCanvasFactory = exports.BaseCMapReaderFactory = void 0;
3946
3947var _util = __w_pdfjs_require__(1);
3948
3949class BaseCanvasFactory {
3950  constructor() {
3951    if (this.constructor === BaseCanvasFactory) {
3952      (0, _util.unreachable)("Cannot initialize BaseCanvasFactory.");
3953    }
3954  }
3955
3956  create(width, height) {
3957    if (width <= 0 || height <= 0) {
3958      throw new Error("Invalid canvas size");
3959    }
3960
3961    const canvas = this._createCanvas(width, height);
3962
3963    return {
3964      canvas,
3965      context: canvas.getContext("2d")
3966    };
3967  }
3968
3969  reset(canvasAndContext, width, height) {
3970    if (!canvasAndContext.canvas) {
3971      throw new Error("Canvas is not specified");
3972    }
3973
3974    if (width <= 0 || height <= 0) {
3975      throw new Error("Invalid canvas size");
3976    }
3977
3978    canvasAndContext.canvas.width = width;
3979    canvasAndContext.canvas.height = height;
3980  }
3981
3982  destroy(canvasAndContext) {
3983    if (!canvasAndContext.canvas) {
3984      throw new Error("Canvas is not specified");
3985    }
3986
3987    canvasAndContext.canvas.width = 0;
3988    canvasAndContext.canvas.height = 0;
3989    canvasAndContext.canvas = null;
3990    canvasAndContext.context = null;
3991  }
3992
3993  _createCanvas(width, height) {
3994    (0, _util.unreachable)("Abstract method `_createCanvas` called.");
3995  }
3996
3997}
3998
3999exports.BaseCanvasFactory = BaseCanvasFactory;
4000
4001class BaseCMapReaderFactory {
4002  constructor({
4003    baseUrl = null,
4004    isCompressed = false
4005  }) {
4006    if (this.constructor === BaseCMapReaderFactory) {
4007      (0, _util.unreachable)("Cannot initialize BaseCMapReaderFactory.");
4008    }
4009
4010    this.baseUrl = baseUrl;
4011    this.isCompressed = isCompressed;
4012  }
4013
4014  async fetch({
4015    name
4016  }) {
4017    if (!this.baseUrl) {
4018      throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
4019    }
4020
4021    if (!name) {
4022      throw new Error("CMap name must be specified.");
4023    }
4024
4025    const url = this.baseUrl + name + (this.isCompressed ? ".bcmap" : "");
4026    const compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
4027    return this._fetchData(url, compressionType).catch(reason => {
4028      throw new Error(`Unable to load ${this.isCompressed ? "binary " : ""}CMap at: ${url}`);
4029    });
4030  }
4031
4032  _fetchData(url, compressionType) {
4033    (0, _util.unreachable)("Abstract method `_fetchData` called.");
4034  }
4035
4036}
4037
4038exports.BaseCMapReaderFactory = BaseCMapReaderFactory;
4039
4040class BaseStandardFontDataFactory {
4041  constructor({
4042    baseUrl = null
4043  }) {
4044    if (this.constructor === BaseStandardFontDataFactory) {
4045      (0, _util.unreachable)("Cannot initialize BaseStandardFontDataFactory.");
4046    }
4047
4048    this.baseUrl = baseUrl;
4049  }
4050
4051  async fetch({
4052    filename
4053  }) {
4054    if (!this.baseUrl) {
4055      throw new Error('The standard font "baseUrl" parameter must be specified, ensure that ' + 'the "standardFontDataUrl" API parameter is provided.');
4056    }
4057
4058    if (!filename) {
4059      throw new Error("Font filename must be specified.");
4060    }
4061
4062    const url = `${this.baseUrl}${filename}`;
4063    return this._fetchData(url).catch(reason => {
4064      throw new Error(`Unable to load font data at: ${url}`);
4065    });
4066  }
4067
4068  _fetchData(url) {
4069    (0, _util.unreachable)("Abstract method `_fetchData` called.");
4070  }
4071
4072}
4073
4074exports.BaseStandardFontDataFactory = BaseStandardFontDataFactory;
4075
4076class BaseSVGFactory {
4077  constructor() {
4078    if (this.constructor === BaseSVGFactory) {
4079      (0, _util.unreachable)("Cannot initialize BaseSVGFactory.");
4080    }
4081  }
4082
4083  create(width, height) {
4084    if (width <= 0 || height <= 0) {
4085      throw new Error("Invalid SVG dimensions");
4086    }
4087
4088    const svg = this._createSVG("svg:svg");
4089
4090    svg.setAttribute("version", "1.1");
4091    svg.setAttribute("width", `${width}px`);
4092    svg.setAttribute("height", `${height}px`);
4093    svg.setAttribute("preserveAspectRatio", "none");
4094    svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
4095    return svg;
4096  }
4097
4098  createElement(type) {
4099    if (typeof type !== "string") {
4100      throw new Error("Invalid SVG element type");
4101    }
4102
4103    return this._createSVG(type);
4104  }
4105
4106  _createSVG(type) {
4107    (0, _util.unreachable)("Abstract method `_createSVG` called.");
4108  }
4109
4110}
4111
4112exports.BaseSVGFactory = BaseSVGFactory;
4113
4114/***/ }),
4115/* 7 */
4116/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4117
4118
4119
4120Object.defineProperty(exports, "__esModule", ({
4121  value: true
4122}));
4123exports.FontLoader = exports.FontFaceObject = void 0;
4124
4125var _util = __w_pdfjs_require__(1);
4126
4127class BaseFontLoader {
4128  constructor({
4129    docId,
4130    onUnsupportedFeature,
4131    ownerDocument = globalThis.document,
4132    styleElement = null
4133  }) {
4134    if (this.constructor === BaseFontLoader) {
4135      (0, _util.unreachable)("Cannot initialize BaseFontLoader.");
4136    }
4137
4138    this.docId = docId;
4139    this._onUnsupportedFeature = onUnsupportedFeature;
4140    this._document = ownerDocument;
4141    this.nativeFontFaces = [];
4142    this.styleElement = null;
4143  }
4144
4145  addNativeFontFace(nativeFontFace) {
4146    this.nativeFontFaces.push(nativeFontFace);
4147
4148    this._document.fonts.add(nativeFontFace);
4149  }
4150
4151  insertRule(rule) {
4152    let styleElement = this.styleElement;
4153
4154    if (!styleElement) {
4155      styleElement = this.styleElement = this._document.createElement("style");
4156      styleElement.id = `PDFJS_FONT_STYLE_TAG_${this.docId}`;
4157
4158      this._document.documentElement.getElementsByTagName("head")[0].appendChild(styleElement);
4159    }
4160
4161    const styleSheet = styleElement.sheet;
4162    styleSheet.insertRule(rule, styleSheet.cssRules.length);
4163  }
4164
4165  clear() {
4166    for (const nativeFontFace of this.nativeFontFaces) {
4167      this._document.fonts.delete(nativeFontFace);
4168    }
4169
4170    this.nativeFontFaces.length = 0;
4171
4172    if (this.styleElement) {
4173      this.styleElement.remove();
4174      this.styleElement = null;
4175    }
4176  }
4177
4178  async bind(font) {
4179    if (font.attached || font.missingFile) {
4180      return;
4181    }
4182
4183    font.attached = true;
4184
4185    if (this.isFontLoadingAPISupported) {
4186      const nativeFontFace = font.createNativeFontFace();
4187
4188      if (nativeFontFace) {
4189        this.addNativeFontFace(nativeFontFace);
4190
4191        try {
4192          await nativeFontFace.loaded;
4193        } catch (ex) {
4194          this._onUnsupportedFeature({
4195            featureId: _util.UNSUPPORTED_FEATURES.errorFontLoadNative
4196          });
4197
4198          (0, _util.warn)(`Failed to load font '${nativeFontFace.family}': '${ex}'.`);
4199          font.disableFontFace = true;
4200          throw ex;
4201        }
4202      }
4203
4204      return;
4205    }
4206
4207    const rule = font.createFontFaceRule();
4208
4209    if (rule) {
4210      this.insertRule(rule);
4211
4212      if (this.isSyncFontLoadingSupported) {
4213        return;
4214      }
4215
4216      await new Promise(resolve => {
4217        const request = this._queueLoadingCallback(resolve);
4218
4219        this._prepareFontLoadEvent([rule], [font], request);
4220      });
4221    }
4222  }
4223
4224  _queueLoadingCallback(callback) {
4225    (0, _util.unreachable)("Abstract method `_queueLoadingCallback`.");
4226  }
4227
4228  get isFontLoadingAPISupported() {
4229    const hasFonts = !!this._document?.fonts;
4230    return (0, _util.shadow)(this, "isFontLoadingAPISupported", hasFonts);
4231  }
4232
4233  get isSyncFontLoadingSupported() {
4234    (0, _util.unreachable)("Abstract method `isSyncFontLoadingSupported`.");
4235  }
4236
4237  get _loadTestFont() {
4238    (0, _util.unreachable)("Abstract method `_loadTestFont`.");
4239  }
4240
4241  _prepareFontLoadEvent(rules, fontsToLoad, request) {
4242    (0, _util.unreachable)("Abstract method `_prepareFontLoadEvent`.");
4243  }
4244
4245}
4246
4247let FontLoader;
4248exports.FontLoader = FontLoader;
4249{
4250  exports.FontLoader = FontLoader = class GenericFontLoader extends BaseFontLoader {
4251    constructor(params) {
4252      super(params);
4253      this.loadingContext = {
4254        requests: [],
4255        nextRequestId: 0
4256      };
4257      this.loadTestFontId = 0;
4258    }
4259
4260    get isSyncFontLoadingSupported() {
4261      let supported = false;
4262
4263      if (typeof navigator === "undefined") {
4264        supported = true;
4265      } else {
4266        const m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent);
4267
4268        if (m?.[1] >= 14) {
4269          supported = true;
4270        }
4271      }
4272
4273      return (0, _util.shadow)(this, "isSyncFontLoadingSupported", supported);
4274    }
4275
4276    _queueLoadingCallback(callback) {
4277      function completeRequest() {
4278        (0, _util.assert)(!request.done, "completeRequest() cannot be called twice.");
4279        request.done = true;
4280
4281        while (context.requests.length > 0 && context.requests[0].done) {
4282          const otherRequest = context.requests.shift();
4283          setTimeout(otherRequest.callback, 0);
4284        }
4285      }
4286
4287      const context = this.loadingContext;
4288      const request = {
4289        id: `pdfjs-font-loading-${context.nextRequestId++}`,
4290        done: false,
4291        complete: completeRequest,
4292        callback
4293      };
4294      context.requests.push(request);
4295      return request;
4296    }
4297
4298    get _loadTestFont() {
4299      const getLoadTestFont = function () {
4300        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==");
4301      };
4302
4303      return (0, _util.shadow)(this, "_loadTestFont", getLoadTestFont());
4304    }
4305
4306    _prepareFontLoadEvent(rules, fonts, request) {
4307      function int32(data, offset) {
4308        return data.charCodeAt(offset) << 24 | data.charCodeAt(offset + 1) << 16 | data.charCodeAt(offset + 2) << 8 | data.charCodeAt(offset + 3) & 0xff;
4309      }
4310
4311      function spliceString(s, offset, remove, insert) {
4312        const chunk1 = s.substring(0, offset);
4313        const chunk2 = s.substring(offset + remove);
4314        return chunk1 + insert + chunk2;
4315      }
4316
4317      let i, ii;
4318
4319      const canvas = this._document.createElement("canvas");
4320
4321      canvas.width = 1;
4322      canvas.height = 1;
4323      const ctx = canvas.getContext("2d");
4324      let called = 0;
4325
4326      function isFontReady(name, callback) {
4327        called++;
4328
4329        if (called > 30) {
4330          (0, _util.warn)("Load test font never loaded.");
4331          callback();
4332          return;
4333        }
4334
4335        ctx.font = "30px " + name;
4336        ctx.fillText(".", 0, 20);
4337        const imageData = ctx.getImageData(0, 0, 1, 1);
4338
4339        if (imageData.data[3] > 0) {
4340          callback();
4341          return;
4342        }
4343
4344        setTimeout(isFontReady.bind(null, name, callback));
4345      }
4346
4347      const loadTestFontId = `lt${Date.now()}${this.loadTestFontId++}`;
4348      let data = this._loadTestFont;
4349      const COMMENT_OFFSET = 976;
4350      data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId);
4351      const CFF_CHECKSUM_OFFSET = 16;
4352      const XXXX_VALUE = 0x58585858;
4353      let checksum = int32(data, CFF_CHECKSUM_OFFSET);
4354
4355      for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) {
4356        checksum = checksum - XXXX_VALUE + int32(loadTestFontId, i) | 0;
4357      }
4358
4359      if (i < loadTestFontId.length) {
4360        checksum = checksum - XXXX_VALUE + int32(loadTestFontId + "XXX", i) | 0;
4361      }
4362
4363      data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, (0, _util.string32)(checksum));
4364      const url = `url(data:font/opentype;base64,${btoa(data)});`;
4365      const rule = `@font-face {font-family:"${loadTestFontId}";src:${url}}`;
4366      this.insertRule(rule);
4367      const names = [];
4368
4369      for (const font of fonts) {
4370        names.push(font.loadedName);
4371      }
4372
4373      names.push(loadTestFontId);
4374
4375      const div = this._document.createElement("div");
4376
4377      div.style.visibility = "hidden";
4378      div.style.width = div.style.height = "10px";
4379      div.style.position = "absolute";
4380      div.style.top = div.style.left = "0px";
4381
4382      for (const name of names) {
4383        const span = this._document.createElement("span");
4384
4385        span.textContent = "Hi";
4386        span.style.fontFamily = name;
4387        div.appendChild(span);
4388      }
4389
4390      this._document.body.appendChild(div);
4391
4392      isFontReady(loadTestFontId, () => {
4393        div.remove();
4394        request.complete();
4395      });
4396    }
4397
4398  };
4399}
4400
4401class FontFaceObject {
4402  constructor(translatedData, {
4403    isEvalSupported = true,
4404    disableFontFace = false,
4405    ignoreErrors = false,
4406    onUnsupportedFeature,
4407    fontRegistry = null
4408  }) {
4409    this.compiledGlyphs = Object.create(null);
4410
4411    for (const i in translatedData) {
4412      this[i] = translatedData[i];
4413    }
4414
4415    this.isEvalSupported = isEvalSupported !== false;
4416    this.disableFontFace = disableFontFace === true;
4417    this.ignoreErrors = ignoreErrors === true;
4418    this._onUnsupportedFeature = onUnsupportedFeature;
4419    this.fontRegistry = fontRegistry;
4420  }
4421
4422  createNativeFontFace() {
4423    if (!this.data || this.disableFontFace) {
4424      return null;
4425    }
4426
4427    let nativeFontFace;
4428
4429    if (!this.cssFontInfo) {
4430      nativeFontFace = new FontFace(this.loadedName, this.data, {});
4431    } else {
4432      const css = {
4433        weight: this.cssFontInfo.fontWeight
4434      };
4435
4436      if (this.cssFontInfo.italicAngle) {
4437        css.style = `oblique ${this.cssFontInfo.italicAngle}deg`;
4438      }
4439
4440      nativeFontFace = new FontFace(this.cssFontInfo.fontFamily, this.data, css);
4441    }
4442
4443    if (this.fontRegistry) {
4444      this.fontRegistry.registerFont(this);
4445    }
4446
4447    return nativeFontFace;
4448  }
4449
4450  createFontFaceRule() {
4451    if (!this.data || this.disableFontFace) {
4452      return null;
4453    }
4454
4455    const data = (0, _util.bytesToString)(this.data);
4456    const url = `url(data:${this.mimetype};base64,${btoa(data)});`;
4457    let rule;
4458
4459    if (!this.cssFontInfo) {
4460      rule = `@font-face {font-family:"${this.loadedName}";src:${url}}`;
4461    } else {
4462      let css = `font-weight: ${this.cssFontInfo.fontWeight};`;
4463
4464      if (this.cssFontInfo.italicAngle) {
4465        css += `font-style: oblique ${this.cssFontInfo.italicAngle}deg;`;
4466      }
4467
4468      rule = `@font-face {font-family:"${this.cssFontInfo.fontFamily}";${css}src:${url}}`;
4469    }
4470
4471    if (this.fontRegistry) {
4472      this.fontRegistry.registerFont(this, url);
4473    }
4474
4475    return rule;
4476  }
4477
4478  getPathGenerator(objs, character) {
4479    if (this.compiledGlyphs[character] !== undefined) {
4480      return this.compiledGlyphs[character];
4481    }
4482
4483    let cmds;
4484
4485    try {
4486      cmds = objs.get(this.loadedName + "_path_" + character);
4487    } catch (ex) {
4488      if (!this.ignoreErrors) {
4489        throw ex;
4490      }
4491
4492      this._onUnsupportedFeature({
4493        featureId: _util.UNSUPPORTED_FEATURES.errorFontGetPath
4494      });
4495
4496      (0, _util.warn)(`getPathGenerator - ignoring character: "${ex}".`);
4497      return this.compiledGlyphs[character] = function (c, size) {};
4498    }
4499
4500    if (this.isEvalSupported && _util.FeatureTest.isEvalSupported) {
4501      const jsBuf = [];
4502
4503      for (const current of cmds) {
4504        const args = current.args !== undefined ? current.args.join(",") : "";
4505        jsBuf.push("c.", current.cmd, "(", args, ");\n");
4506      }
4507
4508      return this.compiledGlyphs[character] = new Function("c", "size", jsBuf.join(""));
4509    }
4510
4511    return this.compiledGlyphs[character] = function (c, size) {
4512      for (const current of cmds) {
4513        if (current.cmd === "scale") {
4514          current.args = [size, -size];
4515        }
4516
4517        c[current.cmd].apply(c, current.args);
4518      }
4519    };
4520  }
4521
4522}
4523
4524exports.FontFaceObject = FontFaceObject;
4525
4526/***/ }),
4527/* 8 */
4528/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4529
4530
4531
4532Object.defineProperty(exports, "__esModule", ({
4533  value: true
4534}));
4535exports.AnnotationStorage = void 0;
4536
4537var _murmurhash = __w_pdfjs_require__(9);
4538
4539var _util = __w_pdfjs_require__(1);
4540
4541class AnnotationStorage {
4542  constructor() {
4543    this._storage = new Map();
4544    this._modified = false;
4545    this.onSetModified = null;
4546    this.onResetModified = null;
4547  }
4548
4549  getValue(key, defaultValue) {
4550    const value = this._storage.get(key);
4551
4552    if (value === undefined) {
4553      return defaultValue;
4554    }
4555
4556    return Object.assign(defaultValue, value);
4557  }
4558
4559  getRawValue(key) {
4560    return this._storage.get(key);
4561  }
4562
4563  setValue(key, value) {
4564    const obj = this._storage.get(key);
4565
4566    let modified = false;
4567
4568    if (obj !== undefined) {
4569      for (const [entry, val] of Object.entries(value)) {
4570        if (obj[entry] !== val) {
4571          modified = true;
4572          obj[entry] = val;
4573        }
4574      }
4575    } else {
4576      modified = true;
4577
4578      this._storage.set(key, value);
4579    }
4580
4581    if (modified) {
4582      this._setModified();
4583    }
4584  }
4585
4586  getAll() {
4587    return this._storage.size > 0 ? (0, _util.objectFromMap)(this._storage) : null;
4588  }
4589
4590  get size() {
4591    return this._storage.size;
4592  }
4593
4594  _setModified() {
4595    if (!this._modified) {
4596      this._modified = true;
4597
4598      if (typeof this.onSetModified === "function") {
4599        this.onSetModified();
4600      }
4601    }
4602  }
4603
4604  resetModified() {
4605    if (this._modified) {
4606      this._modified = false;
4607
4608      if (typeof this.onResetModified === "function") {
4609        this.onResetModified();
4610      }
4611    }
4612  }
4613
4614  get serializable() {
4615    return this._storage.size > 0 ? this._storage : null;
4616  }
4617
4618  get hash() {
4619    const hash = new _murmurhash.MurmurHash3_64();
4620
4621    for (const [key, value] of this._storage) {
4622      hash.update(`${key}:${JSON.stringify(value)}`);
4623    }
4624
4625    return hash.hexdigest();
4626  }
4627
4628}
4629
4630exports.AnnotationStorage = AnnotationStorage;
4631
4632/***/ }),
4633/* 9 */
4634/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4635
4636
4637
4638Object.defineProperty(exports, "__esModule", ({
4639  value: true
4640}));
4641exports.MurmurHash3_64 = void 0;
4642
4643var _util = __w_pdfjs_require__(1);
4644
4645const SEED = 0xc3d2e1f0;
4646const MASK_HIGH = 0xffff0000;
4647const MASK_LOW = 0xffff;
4648
4649class MurmurHash3_64 {
4650  constructor(seed) {
4651    this.h1 = seed ? seed & 0xffffffff : SEED;
4652    this.h2 = seed ? seed & 0xffffffff : SEED;
4653  }
4654
4655  update(input) {
4656    let data, length;
4657
4658    if (typeof input === "string") {
4659      data = new Uint8Array(input.length * 2);
4660      length = 0;
4661
4662      for (let i = 0, ii = input.length; i < ii; i++) {
4663        const code = input.charCodeAt(i);
4664
4665        if (code <= 0xff) {
4666          data[length++] = code;
4667        } else {
4668          data[length++] = code >>> 8;
4669          data[length++] = code & 0xff;
4670        }
4671      }
4672    } else if ((0, _util.isArrayBuffer)(input)) {
4673      data = input.slice();
4674      length = data.byteLength;
4675    } else {
4676      throw new Error("Wrong data format in MurmurHash3_64_update. " + "Input must be a string or array.");
4677    }
4678
4679    const blockCounts = length >> 2;
4680    const tailLength = length - blockCounts * 4;
4681    const dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
4682    let k1 = 0,
4683        k2 = 0;
4684    let h1 = this.h1,
4685        h2 = this.h2;
4686    const C1 = 0xcc9e2d51,
4687          C2 = 0x1b873593;
4688    const C1_LOW = C1 & MASK_LOW,
4689          C2_LOW = C2 & MASK_LOW;
4690
4691    for (let i = 0; i < blockCounts; i++) {
4692      if (i & 1) {
4693        k1 = dataUint32[i];
4694        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
4695        k1 = k1 << 15 | k1 >>> 17;
4696        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
4697        h1 ^= k1;
4698        h1 = h1 << 13 | h1 >>> 19;
4699        h1 = h1 * 5 + 0xe6546b64;
4700      } else {
4701        k2 = dataUint32[i];
4702        k2 = k2 * C1 & MASK_HIGH | k2 * C1_LOW & MASK_LOW;
4703        k2 = k2 << 15 | k2 >>> 17;
4704        k2 = k2 * C2 & MASK_HIGH | k2 * C2_LOW & MASK_LOW;
4705        h2 ^= k2;
4706        h2 = h2 << 13 | h2 >>> 19;
4707        h2 = h2 * 5 + 0xe6546b64;
4708      }
4709    }
4710
4711    k1 = 0;
4712
4713    switch (tailLength) {
4714      case 3:
4715        k1 ^= data[blockCounts * 4 + 2] << 16;
4716
4717      case 2:
4718        k1 ^= data[blockCounts * 4 + 1] << 8;
4719
4720      case 1:
4721        k1 ^= data[blockCounts * 4];
4722        k1 = k1 * C1 & MASK_HIGH | k1 * C1_LOW & MASK_LOW;
4723        k1 = k1 << 15 | k1 >>> 17;
4724        k1 = k1 * C2 & MASK_HIGH | k1 * C2_LOW & MASK_LOW;
4725
4726        if (blockCounts & 1) {
4727          h1 ^= k1;
4728        } else {
4729          h2 ^= k1;
4730        }
4731
4732    }
4733
4734    this.h1 = h1;
4735    this.h2 = h2;
4736  }
4737
4738  hexdigest() {
4739    let h1 = this.h1,
4740        h2 = this.h2;
4741    h1 ^= h2 >>> 1;
4742    h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
4743    h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
4744    h1 ^= h2 >>> 1;
4745    h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
4746    h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
4747    h1 ^= h2 >>> 1;
4748    const hex1 = (h1 >>> 0).toString(16),
4749          hex2 = (h2 >>> 0).toString(16);
4750    return hex1.padStart(8, "0") + hex2.padStart(8, "0");
4751  }
4752
4753}
4754
4755exports.MurmurHash3_64 = MurmurHash3_64;
4756
4757/***/ }),
4758/* 10 */
4759/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
4760
4761
4762
4763Object.defineProperty(exports, "__esModule", ({
4764  value: true
4765}));
4766exports.CanvasGraphics = void 0;
4767
4768var _util = __w_pdfjs_require__(1);
4769
4770var _pattern_helper = __w_pdfjs_require__(11);
4771
4772var _image_utils = __w_pdfjs_require__(12);
4773
4774var _is_node = __w_pdfjs_require__(3);
4775
4776var _display_utils = __w_pdfjs_require__(5);
4777
4778const MIN_FONT_SIZE = 16;
4779const MAX_FONT_SIZE = 100;
4780const MAX_GROUP_SIZE = 4096;
4781const EXECUTION_TIME = 15;
4782const EXECUTION_STEPS = 10;
4783const COMPILE_TYPE3_GLYPHS = true;
4784const MAX_SIZE_TO_COMPILE = 1000;
4785const FULL_CHUNK_HEIGHT = 16;
4786const LINEWIDTH_SCALE_FACTOR = 1.000001;
4787
4788function mirrorContextOperations(ctx, destCtx) {
4789  if (ctx._removeMirroring) {
4790    throw new Error("Context is already forwarding operations.");
4791  }
4792
4793  ctx.__originalSave = ctx.save;
4794  ctx.__originalRestore = ctx.restore;
4795  ctx.__originalRotate = ctx.rotate;
4796  ctx.__originalScale = ctx.scale;
4797  ctx.__originalTranslate = ctx.translate;
4798  ctx.__originalTransform = ctx.transform;
4799  ctx.__originalSetTransform = ctx.setTransform;
4800  ctx.__originalResetTransform = ctx.resetTransform;
4801  ctx.__originalClip = ctx.clip;
4802  ctx.__originalMoveTo = ctx.moveTo;
4803  ctx.__originalLineTo = ctx.lineTo;
4804  ctx.__originalBezierCurveTo = ctx.bezierCurveTo;
4805  ctx.__originalRect = ctx.rect;
4806  ctx.__originalClosePath = ctx.closePath;
4807  ctx.__originalBeginPath = ctx.beginPath;
4808
4809  ctx._removeMirroring = () => {
4810    ctx.save = ctx.__originalSave;
4811    ctx.restore = ctx.__originalRestore;
4812    ctx.rotate = ctx.__originalRotate;
4813    ctx.scale = ctx.__originalScale;
4814    ctx.translate = ctx.__originalTranslate;
4815    ctx.transform = ctx.__originalTransform;
4816    ctx.setTransform = ctx.__originalSetTransform;
4817    ctx.resetTransform = ctx.__originalResetTransform;
4818    ctx.clip = ctx.__originalClip;
4819    ctx.moveTo = ctx.__originalMoveTo;
4820    ctx.lineTo = ctx.__originalLineTo;
4821    ctx.bezierCurveTo = ctx.__originalBezierCurveTo;
4822    ctx.rect = ctx.__originalRect;
4823    ctx.closePath = ctx.__originalClosePath;
4824    ctx.beginPath = ctx.__originalBeginPath;
4825    delete ctx._removeMirroring;
4826  };
4827
4828  ctx.save = function ctxSave() {
4829    destCtx.save();
4830
4831    this.__originalSave();
4832  };
4833
4834  ctx.restore = function ctxRestore() {
4835    destCtx.restore();
4836
4837    this.__originalRestore();
4838  };
4839
4840  ctx.translate = function ctxTranslate(x, y) {
4841    destCtx.translate(x, y);
4842
4843    this.__originalTranslate(x, y);
4844  };
4845
4846  ctx.scale = function ctxScale(x, y) {
4847    destCtx.scale(x, y);
4848
4849    this.__originalScale(x, y);
4850  };
4851
4852  ctx.transform = function ctxTransform(a, b, c, d, e, f) {
4853    destCtx.transform(a, b, c, d, e, f);
4854
4855    this.__originalTransform(a, b, c, d, e, f);
4856  };
4857
4858  ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
4859    destCtx.setTransform(a, b, c, d, e, f);
4860
4861    this.__originalSetTransform(a, b, c, d, e, f);
4862  };
4863
4864  ctx.resetTransform = function ctxResetTransform() {
4865    destCtx.resetTransform();
4866
4867    this.__originalResetTransform();
4868  };
4869
4870  ctx.rotate = function ctxRotate(angle) {
4871    destCtx.rotate(angle);
4872
4873    this.__originalRotate(angle);
4874  };
4875
4876  ctx.clip = function ctxRotate(rule) {
4877    destCtx.clip(rule);
4878
4879    this.__originalClip(rule);
4880  };
4881
4882  ctx.moveTo = function (x, y) {
4883    destCtx.moveTo(x, y);
4884
4885    this.__originalMoveTo(x, y);
4886  };
4887
4888  ctx.lineTo = function (x, y) {
4889    destCtx.lineTo(x, y);
4890
4891    this.__originalLineTo(x, y);
4892  };
4893
4894  ctx.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) {
4895    destCtx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
4896
4897    this.__originalBezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
4898  };
4899
4900  ctx.rect = function (x, y, width, height) {
4901    destCtx.rect(x, y, width, height);
4902
4903    this.__originalRect(x, y, width, height);
4904  };
4905
4906  ctx.closePath = function () {
4907    destCtx.closePath();
4908
4909    this.__originalClosePath();
4910  };
4911
4912  ctx.beginPath = function () {
4913    destCtx.beginPath();
4914
4915    this.__originalBeginPath();
4916  };
4917}
4918
4919function addContextCurrentTransform(ctx) {
4920  if (ctx._transformStack) {
4921    ctx._transformStack = [];
4922  }
4923
4924  if (ctx.mozCurrentTransform) {
4925    return;
4926  }
4927
4928  ctx._originalSave = ctx.save;
4929  ctx._originalRestore = ctx.restore;
4930  ctx._originalRotate = ctx.rotate;
4931  ctx._originalScale = ctx.scale;
4932  ctx._originalTranslate = ctx.translate;
4933  ctx._originalTransform = ctx.transform;
4934  ctx._originalSetTransform = ctx.setTransform;
4935  ctx._originalResetTransform = ctx.resetTransform;
4936  ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0];
4937  ctx._transformStack = [];
4938
4939  try {
4940    const desc = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(ctx), "lineWidth");
4941    ctx._setLineWidth = desc.set;
4942    ctx._getLineWidth = desc.get;
4943    Object.defineProperty(ctx, "lineWidth", {
4944      set: function setLineWidth(width) {
4945        this._setLineWidth(width * LINEWIDTH_SCALE_FACTOR);
4946      },
4947      get: function getLineWidth() {
4948        return this._getLineWidth();
4949      }
4950    });
4951  } catch (_) {}
4952
4953  Object.defineProperty(ctx, "mozCurrentTransform", {
4954    get: function getCurrentTransform() {
4955      return this._transformMatrix;
4956    }
4957  });
4958  Object.defineProperty(ctx, "mozCurrentTransformInverse", {
4959    get: function getCurrentTransformInverse() {
4960      const [a, b, c, d, e, f] = this._transformMatrix;
4961      const ad_bc = a * d - b * c;
4962      const bc_ad = b * c - a * d;
4963      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];
4964    }
4965  });
4966
4967  ctx.save = function ctxSave() {
4968    const old = this._transformMatrix;
4969
4970    this._transformStack.push(old);
4971
4972    this._transformMatrix = old.slice(0, 6);
4973
4974    this._originalSave();
4975  };
4976
4977  ctx.restore = function ctxRestore() {
4978    if (this._transformStack.length === 0) {
4979      (0, _util.warn)("Tried to restore a ctx when the stack was already empty.");
4980    }
4981
4982    const prev = this._transformStack.pop();
4983
4984    if (prev) {
4985      this._transformMatrix = prev;
4986
4987      this._originalRestore();
4988    }
4989  };
4990
4991  ctx.translate = function ctxTranslate(x, y) {
4992    const m = this._transformMatrix;
4993    m[4] = m[0] * x + m[2] * y + m[4];
4994    m[5] = m[1] * x + m[3] * y + m[5];
4995
4996    this._originalTranslate(x, y);
4997  };
4998
4999  ctx.scale = function ctxScale(x, y) {
5000    const m = this._transformMatrix;
5001    m[0] *= x;
5002    m[1] *= x;
5003    m[2] *= y;
5004    m[3] *= y;
5005
5006    this._originalScale(x, y);
5007  };
5008
5009  ctx.transform = function ctxTransform(a, b, c, d, e, f) {
5010    const m = this._transformMatrix;
5011    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]];
5012
5013    ctx._originalTransform(a, b, c, d, e, f);
5014  };
5015
5016  ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) {
5017    this._transformMatrix = [a, b, c, d, e, f];
5018
5019    ctx._originalSetTransform(a, b, c, d, e, f);
5020  };
5021
5022  ctx.resetTransform = function ctxResetTransform() {
5023    this._transformMatrix = [1, 0, 0, 1, 0, 0];
5024
5025    ctx._originalResetTransform();
5026  };
5027
5028  ctx.rotate = function ctxRotate(angle) {
5029    const cosValue = Math.cos(angle);
5030    const sinValue = Math.sin(angle);
5031    const m = this._transformMatrix;
5032    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]];
5033
5034    this._originalRotate(angle);
5035  };
5036}
5037
5038class CachedCanvases {
5039  constructor(canvasFactory) {
5040    this.canvasFactory = canvasFactory;
5041    this.cache = Object.create(null);
5042  }
5043
5044  getCanvas(id, width, height, trackTransform) {
5045    let canvasEntry;
5046
5047    if (this.cache[id] !== undefined) {
5048      canvasEntry = this.cache[id];
5049      this.canvasFactory.reset(canvasEntry, width, height);
5050      canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0);
5051    } else {
5052      canvasEntry = this.canvasFactory.create(width, height);
5053      this.cache[id] = canvasEntry;
5054    }
5055
5056    if (trackTransform) {
5057      addContextCurrentTransform(canvasEntry.context);
5058    }
5059
5060    return canvasEntry;
5061  }
5062
5063  delete(id) {
5064    delete this.cache[id];
5065  }
5066
5067  clear() {
5068    for (const id in this.cache) {
5069      const canvasEntry = this.cache[id];
5070      this.canvasFactory.destroy(canvasEntry);
5071      delete this.cache[id];
5072    }
5073  }
5074
5075}
5076
5077function drawImageAtIntegerCoords(ctx, srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH) {
5078  const [a, b, c, d, tx, ty] = ctx.mozCurrentTransform;
5079
5080  if (b === 0 && c === 0) {
5081    const tlX = destX * a + tx;
5082    const rTlX = Math.round(tlX);
5083    const tlY = destY * d + ty;
5084    const rTlY = Math.round(tlY);
5085    const brX = (destX + destW) * a + tx;
5086    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
5087    const brY = (destY + destH) * d + ty;
5088    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
5089    ctx.setTransform(Math.sign(a), 0, 0, Math.sign(d), rTlX, rTlY);
5090    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rWidth, rHeight);
5091    ctx.setTransform(a, b, c, d, tx, ty);
5092    return [rWidth, rHeight];
5093  }
5094
5095  if (a === 0 && d === 0) {
5096    const tlX = destY * c + tx;
5097    const rTlX = Math.round(tlX);
5098    const tlY = destX * b + ty;
5099    const rTlY = Math.round(tlY);
5100    const brX = (destY + destH) * c + tx;
5101    const rWidth = Math.abs(Math.round(brX) - rTlX) || 1;
5102    const brY = (destX + destW) * b + ty;
5103    const rHeight = Math.abs(Math.round(brY) - rTlY) || 1;
5104    ctx.setTransform(0, Math.sign(b), Math.sign(c), 0, rTlX, rTlY);
5105    ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, 0, 0, rHeight, rWidth);
5106    ctx.setTransform(a, b, c, d, tx, ty);
5107    return [rHeight, rWidth];
5108  }
5109
5110  ctx.drawImage(srcImg, srcX, srcY, srcW, srcH, destX, destY, destW, destH);
5111  const scaleX = Math.hypot(a, b);
5112  const scaleY = Math.hypot(c, d);
5113  return [scaleX * destW, scaleY * destH];
5114}
5115
5116function compileType3Glyph(imgData) {
5117  const {
5118    width,
5119    height
5120  } = imgData;
5121
5122  if (!COMPILE_TYPE3_GLYPHS || width > MAX_SIZE_TO_COMPILE || height > MAX_SIZE_TO_COMPILE) {
5123    return null;
5124  }
5125
5126  const POINT_TO_PROCESS_LIMIT = 1000;
5127  const POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]);
5128  const width1 = width + 1;
5129  let points = new Uint8Array(width1 * (height + 1));
5130  let i, j, j0;
5131  const lineSize = width + 7 & ~7;
5132  let data = new Uint8Array(lineSize * height),
5133      pos = 0;
5134
5135  for (const elem of imgData.data) {
5136    let mask = 128;
5137
5138    while (mask > 0) {
5139      data[pos++] = elem & mask ? 0 : 255;
5140      mask >>= 1;
5141    }
5142  }
5143
5144  let count = 0;
5145  pos = 0;
5146
5147  if (data[pos] !== 0) {
5148    points[0] = 1;
5149    ++count;
5150  }
5151
5152  for (j = 1; j < width; j++) {
5153    if (data[pos] !== data[pos + 1]) {
5154      points[j] = data[pos] ? 2 : 1;
5155      ++count;
5156    }
5157
5158    pos++;
5159  }
5160
5161  if (data[pos] !== 0) {
5162    points[j] = 2;
5163    ++count;
5164  }
5165
5166  for (i = 1; i < height; i++) {
5167    pos = i * lineSize;
5168    j0 = i * width1;
5169
5170    if (data[pos - lineSize] !== data[pos]) {
5171      points[j0] = data[pos] ? 1 : 8;
5172      ++count;
5173    }
5174
5175    let sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0);
5176
5177    for (j = 1; j < width; j++) {
5178      sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0);
5179
5180      if (POINT_TYPES[sum]) {
5181        points[j0 + j] = POINT_TYPES[sum];
5182        ++count;
5183      }
5184
5185      pos++;
5186    }
5187
5188    if (data[pos - lineSize] !== data[pos]) {
5189      points[j0 + j] = data[pos] ? 2 : 4;
5190      ++count;
5191    }
5192
5193    if (count > POINT_TO_PROCESS_LIMIT) {
5194      return null;
5195    }
5196  }
5197
5198  pos = lineSize * (height - 1);
5199  j0 = i * width1;
5200
5201  if (data[pos] !== 0) {
5202    points[j0] = 8;
5203    ++count;
5204  }
5205
5206  for (j = 1; j < width; j++) {
5207    if (data[pos] !== data[pos + 1]) {
5208      points[j0 + j] = data[pos] ? 4 : 8;
5209      ++count;
5210    }
5211
5212    pos++;
5213  }
5214
5215  if (data[pos] !== 0) {
5216    points[j0 + j] = 4;
5217    ++count;
5218  }
5219
5220  if (count > POINT_TO_PROCESS_LIMIT) {
5221    return null;
5222  }
5223
5224  const steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]);
5225  let path, outlines, coords;
5226
5227  if (!_is_node.isNodeJS) {
5228    path = new Path2D();
5229  } else {
5230    outlines = [];
5231  }
5232
5233  for (i = 0; count && i <= height; i++) {
5234    let p = i * width1;
5235    const end = p + width;
5236
5237    while (p < end && !points[p]) {
5238      p++;
5239    }
5240
5241    if (p === end) {
5242      continue;
5243    }
5244
5245    if (path) {
5246      path.moveTo(p % width1, i);
5247    } else {
5248      coords = [p % width1, i];
5249    }
5250
5251    const p0 = p;
5252    let type = points[p];
5253
5254    do {
5255      const step = steps[type];
5256
5257      do {
5258        p += step;
5259      } while (!points[p]);
5260
5261      const pp = points[p];
5262
5263      if (pp !== 5 && pp !== 10) {
5264        type = pp;
5265        points[p] = 0;
5266      } else {
5267        type = pp & 0x33 * type >> 4;
5268        points[p] &= type >> 2 | type << 2;
5269      }
5270
5271      if (path) {
5272        path.lineTo(p % width1, p / width1 | 0);
5273      } else {
5274        coords.push(p % width1, p / width1 | 0);
5275      }
5276
5277      if (!points[p]) {
5278        --count;
5279      }
5280    } while (p0 !== p);
5281
5282    if (!path) {
5283      outlines.push(coords);
5284    }
5285
5286    --i;
5287  }
5288
5289  data = null;
5290  points = null;
5291
5292  const drawOutline = function (c) {
5293    c.save();
5294    c.scale(1 / width, -1 / height);
5295    c.translate(0, -height);
5296
5297    if (path) {
5298      c.fill(path);
5299    } else {
5300      c.beginPath();
5301
5302      for (const o of outlines) {
5303        c.moveTo(o[0], o[1]);
5304
5305        for (let l = 2, ll = o.length; l < ll;
5305 l += 2) {
5306          c.lineTo(o[l], o[l + 1]);
5307        }
5308      }
5309
5310      c.fill();
5311    }
5312
5313    c.beginPath();
5314    c.restore();
5315  };
5316
5317  return drawOutline;
5318}
5319
5320class CanvasExtraState {
5321  constructor(width, height) {
5322    this.alphaIsShape = false;
5323    this.fontSize = 0;
5324    this.fontSizeScale = 1;
5325    this.textMatrix = _util.IDENTITY_MATRIX;
5326    this.textMatrixScale = 1;
5327    this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
5328    this.leading = 0;
5329    this.x = 0;
5330    this.y = 0;
5331    this.lineX = 0;
5332    this.lineY = 0;
5333    this.charSpacing = 0;
5334    this.wordSpacing = 0;
5335    this.textHScale = 1;
5336    this.textRenderingMode = _util.TextRenderingMode.FILL;
5337    this.textRise = 0;
5338    this.fillColor = "#000000";
5339    this.strokeColor = "#000000";
5340    this.patternFill = false;
5341    this.fillAlpha = 1;
5342    this.strokeAlpha = 1;
5343    this.lineWidth = 1;
5344    this.activeSMask = null;
5345    this.transferMaps = null;
5346    this.startNewPathAndClipBox([0, 0, width, height]);
5347  }
5348
5349  clone() {
5350    const clone = Object.create(this);
5351    clone.clipBox = this.clipBox.slice();
5352    return clone;
5353  }
5354
5355  setCurrentPoint(x, y) {
5356    this.x = x;
5357    this.y = y;
5358  }
5359
5360  updatePathMinMax(transform, x, y) {
5361    [x, y] = _util.Util.applyTransform([x, y], transform);
5362    this.minX = Math.min(this.minX, x);
5363    this.minY = Math.min(this.minY, y);
5364    this.maxX = Math.max(this.maxX, x);
5365    this.maxY = Math.max(this.maxY, y);
5366  }
5367
5368  updateRectMinMax(transform, rect) {
5369    const p1 = _util.Util.applyTransform(rect, transform);
5370
5371    const p2 = _util.Util.applyTransform(rect.slice(2), transform);
5372
5373    this.minX = Math.min(this.minX, p1[0], p2[0]);
5374    this.minY = Math.min(this.minY, p1[1], p2[1]);
5375    this.maxX = Math.max(this.maxX, p1[0], p2[0]);
5376    this.maxY = Math.max(this.maxY, p1[1], p2[1]);
5377  }
5378
5379  updateScalingPathMinMax(transform, minMax) {
5380    _util.Util.scaleMinMax(transform, minMax);
5381
5382    this.minX = Math.min(this.minX, minMax[0]);
5383    this.maxX = Math.max(this.maxX, minMax[1]);
5384    this.minY = Math.min(this.minY, minMax[2]);
5385    this.maxY = Math.max(this.maxY, minMax[3]);
5386  }
5387
5388  updateCurvePathMinMax(transform, x0, y0, x1, y1, x2, y2, x3, y3, minMax) {
5389    const box = _util.Util.bezierBoundingBox(x0, y0, x1, y1, x2, y2, x3, y3);
5390
5391    if (minMax) {
5392      minMax[0] = Math.min(minMax[0], box[0], box[2]);
5393      minMax[1] = Math.max(minMax[1], box[0], box[2]);
5394      minMax[2] = Math.min(minMax[2], box[1], box[3]);
5395      minMax[3] = Math.max(minMax[3], box[1], box[3]);
5396      return;
5397    }
5398
5399    this.updateRectMinMax(transform, box);
5400  }
5401
5402  getPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5403    const box = [this.minX, this.minY, this.maxX, this.maxY];
5404
5405    if (pathType === _pattern_helper.PathType.STROKE) {
5406      if (!transform) {
5407        (0, _util.unreachable)("Stroke bounding box must include transform.");
5408      }
5409
5410      const scale = _util.Util.singularValueDecompose2dScale(transform);
5411
5412      const xStrokePad = scale[0] * this.lineWidth / 2;
5413      const yStrokePad = scale[1] * this.lineWidth / 2;
5414      box[0] -= xStrokePad;
5415      box[1] -= yStrokePad;
5416      box[2] += xStrokePad;
5417      box[3] += yStrokePad;
5418    }
5419
5420    return box;
5421  }
5422
5423  updateClipFromPath() {
5424    const intersect = _util.Util.intersect(this.clipBox, this.getPathBoundingBox());
5425
5426    this.startNewPathAndClipBox(intersect || [0, 0, 0, 0]);
5427  }
5428
5429  isEmptyClip() {
5430    return this.minX === Infinity;
5431  }
5432
5433  startNewPathAndClipBox(box) {
5434    this.clipBox = box;
5435    this.minX = Infinity;
5436    this.minY = Infinity;
5437    this.maxX = 0;
5438    this.maxY = 0;
5439  }
5440
5441  getClippedPathBoundingBox(pathType = _pattern_helper.PathType.FILL, transform = null) {
5442    return _util.Util.intersect(this.clipBox, this.getPathBoundingBox(pathType, transform));
5443  }
5444
5445}
5446
5447function putBinaryImageData(ctx, imgData, transferMaps = null) {
5448  if (typeof ImageData !== "undefined" && imgData instanceof ImageData) {
5449    ctx.putImageData(imgData, 0, 0);
5450    return;
5451  }
5452
5453  const height = imgData.height,
5454        width = imgData.width;
5455  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5456  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5457  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5458  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5459  let srcPos = 0,
5460      destPos;
5461  const src = imgData.data;
5462  const dest = chunkImgData.data;
5463  let i, j, thisChunkHeight, elemsInThisChunk;
5464  let transferMapRed, transferMapGreen, transferMapBlue, transferMapGray;
5465
5466  if (transferMaps) {
5467    switch (transferMaps.length) {
5468      case 1:
5469        transferMapRed = transferMaps[0];
5470        transferMapGreen = transferMaps[0];
5471        transferMapBlue = transferMaps[0];
5472        transferMapGray = transferMaps[0];
5473        break;
5474
5475      case 4:
5476        transferMapRed = transferMaps[0];
5477        transferMapGreen = transferMaps[1];
5478        transferMapBlue = transferMaps[2];
5479        transferMapGray = transferMaps[3];
5480        break;
5481    }
5482  }
5483
5484  if (imgData.kind === _util.ImageKind.GRAYSCALE_1BPP) {
5485    const srcLength = src.byteLength;
5486    const dest32 = new Uint32Array(dest.buffer, 0, dest.byteLength >> 2);
5487    const dest32DataLength = dest32.length;
5488    const fullSrcDiff = width + 7 >> 3;
5489    let white = 0xffffffff;
5490    let black = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
5491
5492    if (transferMapGray) {
5493      if (transferMapGray[0] === 0xff && transferMapGray[0xff] === 0) {
5494        [white, black] = [black, white];
5495      }
5496    }
5497
5498    for (i = 0; i < totalChunks; i++) {
5499      thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5500      destPos = 0;
5501
5502      for (j = 0; j < thisChunkHeight; j++) {
5503        const srcDiff = srcLength - srcPos;
5504        let k = 0;
5505        const kEnd = srcDiff > fullSrcDiff ? width : srcDiff * 8 - 7;
5506        const kEndUnrolled = kEnd & ~7;
5507        let mask = 0;
5508        let srcByte = 0;
5509
5510        for (; k < kEndUnrolled; k += 8) {
5511          srcByte = src[srcPos++];
5512          dest32[destPos++] = srcByte & 128 ? white : black;
5513          dest32[destPos++] = srcByte & 64 ? white : black;
5514          dest32[destPos++] = srcByte & 32 ? white : black;
5515          dest32[destPos++] = srcByte & 16 ? white : black;
5516          dest32[destPos++] = srcByte & 8 ? white : black;
5517          dest32[destPos++] = srcByte & 4 ? white : black;
5518          dest32[destPos++] = srcByte & 2 ? white : black;
5519          dest32[destPos++] = srcByte & 1 ? white : black;
5520        }
5521
5522        for (; k < kEnd; k++) {
5523          if (mask === 0) {
5524            srcByte = src[srcPos++];
5525            mask = 128;
5526          }
5527
5528          dest32[destPos++] = srcByte & mask ? white : black;
5529          mask >>= 1;
5530        }
5531      }
5532
5533      while (destPos < dest32DataLength) {
5534        dest32[destPos++] = 0;
5535      }
5536
5537      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5538    }
5539  } else if (imgData.kind === _util.ImageKind.RGBA_32BPP) {
5540    const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5541    j = 0;
5542    elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4;
5543
5544    for (i = 0; i < fullChunks; i++) {
5545      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5546      srcPos += elemsInThisChunk;
5547
5548      if (hasTransferMaps) {
5549        for (let k = 0; k < elemsInThisChunk; k += 4) {
5550          if (transferMapRed) {
5551            dest[k + 0] = transferMapRed[dest[k + 0]];
5552          }
5553
5554          if (transferMapGreen) {
5555            dest[k + 1] = transferMapGreen[dest[k + 1]];
5556          }
5557
5558          if (transferMapBlue) {
5559            dest[k + 2] = transferMapBlue[dest[k + 2]];
5560          }
5561        }
5562      }
5563
5564      ctx.putImageData(chunkImgData, 0, j);
5565      j += FULL_CHUNK_HEIGHT;
5566    }
5567
5568    if (i < totalChunks) {
5569      elemsInThisChunk = width * partialChunkHeight * 4;
5570      dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk));
5571
5572      if (hasTransferMaps) {
5573        for (let k = 0; k < elemsInThisChunk; k += 4) {
5574          if (transferMapRed) {
5575            dest[k + 0] = transferMapRed[dest[k + 0]];
5576          }
5577
5578          if (transferMapGreen) {
5579            dest[k + 1] = transferMapGreen[dest[k + 1]];
5580          }
5581
5582          if (transferMapBlue) {
5583            dest[k + 2] = transferMapBlue[dest[k + 2]];
5584          }
5585        }
5586      }
5587
5588      ctx.putImageData(chunkImgData, 0, j);
5589    }
5590  } else if (imgData.kind === _util.ImageKind.RGB_24BPP) {
5591    const hasTransferMaps = !!(transferMapRed || transferMapGreen || transferMapBlue);
5592    thisChunkHeight = FULL_CHUNK_HEIGHT;
5593    elemsInThisChunk = width * thisChunkHeight;
5594
5595    for (i = 0; i < totalChunks; i++) {
5596      if (i >= fullChunks) {
5597        thisChunkHeight = partialChunkHeight;
5598        elemsInThisChunk = width * thisChunkHeight;
5599      }
5600
5601      destPos = 0;
5602
5603      for (j = elemsInThisChunk; j--;) {
5604        dest[destPos++] = src[srcPos++];
5605        dest[destPos++] = src[srcPos++];
5606        dest[destPos++] = src[srcPos++];
5607        dest[destPos++] = 255;
5608      }
5609
5610      if (hasTransferMaps) {
5611        for (let k = 0; k < destPos; k += 4) {
5612          if (transferMapRed) {
5613            dest[k + 0] = transferMapRed[dest[k + 0]];
5614          }
5615
5616          if (transferMapGreen) {
5617            dest[k + 1] = transferMapGreen[dest[k + 1]];
5618          }
5619
5620          if (transferMapBlue) {
5621            dest[k + 2] = transferMapBlue[dest[k + 2]];
5622          }
5623        }
5624      }
5625
5626      ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5627    }
5628  } else {
5629    throw new Error(`bad image kind: ${imgData.kind}`);
5630  }
5631}
5632
5633function putBinaryImageMask(ctx, imgData) {
5634  if (imgData.bitmap) {
5635    ctx.drawImage(imgData.bitmap, 0, 0);
5636    return;
5637  }
5638
5639  const height = imgData.height,
5640        width = imgData.width;
5641  const partialChunkHeight = height % FULL_CHUNK_HEIGHT;
5642  const fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT;
5643  const totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1;
5644  const chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT);
5645  let srcPos = 0;
5646  const src = imgData.data;
5647  const dest = chunkImgData.data;
5648
5649  for (let i = 0; i < totalChunks; i++) {
5650    const thisChunkHeight = i < fullChunks ? FULL_CHUNK_HEIGHT : partialChunkHeight;
5651    ({
5652      srcPos
5653    } = (0, _image_utils.applyMaskImageData)({
5654      src,
5655      srcPos,
5656      dest,
5657      width,
5658      height: thisChunkHeight
5659    }));
5660    ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT);
5661  }
5662}
5663
5664function copyCtxState(sourceCtx, destCtx) {
5665  const properties = ["strokeStyle", "fillStyle", "fillRule", "globalAlpha", "lineWidth", "lineCap", "lineJoin", "miterLimit", "globalCompositeOperation", "font"];
5666
5667  for (let i = 0, ii = properties.length; i < ii; i++) {
5668    const property = properties[i];
5669
5670    if (sourceCtx[property] !== undefined) {
5671      destCtx[property] = sourceCtx[property];
5672    }
5673  }
5674
5675  if (sourceCtx.setLineDash !== undefined) {
5676    destCtx.setLineDash(sourceCtx.getLineDash());
5677    destCtx.lineDashOffset = sourceCtx.lineDashOffset;
5678  }
5679}
5680
5681function resetCtxToDefault(ctx, foregroundColor) {
5682  ctx.strokeStyle = ctx.fillStyle = foregroundColor || "#000000";
5683  ctx.fillRule = "nonzero";
5684  ctx.globalAlpha = 1;
5685  ctx.lineWidth = 1;
5686  ctx.lineCap = "butt";
5687  ctx.lineJoin = "miter";
5688  ctx.miterLimit = 10;
5689  ctx.globalCompositeOperation = "source-over";
5690  ctx.font = "10px sans-serif";
5691
5692  if (ctx.setLineDash !== undefined) {
5693    ctx.setLineDash([]);
5694    ctx.lineDashOffset = 0;
5695  }
5696}
5697
5698function composeSMaskBackdrop(bytes, r0, g0, b0) {
5699  const length = bytes.length;
5700
5701  for (let i = 3; i < length; i += 4) {
5702    const alpha = bytes[i];
5703
5704    if (alpha === 0) {
5705      bytes[i - 3] = r0;
5706      bytes[i - 2] = g0;
5707      bytes[i - 1] = b0;
5708    } else if (alpha < 255) {
5709      const alpha_ = 255 - alpha;
5710      bytes[i - 3] = bytes[i - 3] * alpha + r0 * alpha_ >> 8;
5711      bytes[i - 2] = bytes[i - 2] * alpha + g0 * alpha_ >> 8;
5712      bytes[i - 1] = bytes[i - 1] * alpha + b0 * alpha_ >> 8;
5713    }
5714  }
5715}
5716
5717function composeSMaskAlpha(maskData, layerData, transferMap) {
5718  const length = maskData.length;
5719  const scale = 1 / 255;
5720
5721  for (let i = 3; i < length; i += 4) {
5722    const alpha = transferMap ? transferMap[maskData[i]] : maskData[i];
5723    layerData[i] = layerData[i] * alpha * scale | 0;
5724  }
5725}
5726
5727function composeSMaskLuminosity(maskData, layerData, transferMap) {
5728  const length = maskData.length;
5729
5730  for (let i = 3; i < length; i += 4) {
5731    const y = maskData[i - 3] * 77 + maskData[i - 2] * 152 + maskData[i - 1] * 28;
5732    layerData[i] = transferMap ? layerData[i] * transferMap[y >> 8] >> 8 : layerData[i] * y >> 16;
5733  }
5734}
5735
5736function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap, layerOffsetX, layerOffsetY, maskOffsetX, maskOffsetY) {
5737  const hasBackdrop = !!backdrop;
5738  const r0 = hasBackdrop ? backdrop[0] : 0;
5739  const g0 = hasBackdrop ? backdrop[1] : 0;
5740  const b0 = hasBackdrop ? backdrop[2] : 0;
5741  let composeFn;
5742
5743  if (subtype === "Luminosity") {
5744    composeFn = composeSMaskLuminosity;
5745  } else {
5746    composeFn = composeSMaskAlpha;
5747  }
5748
5749  const PIXELS_TO_PROCESS = 1048576;
5750  const chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width));
5751
5752  for (let row = 0; row < height; row += chunkSize) {
5753    const chunkHeight = Math.min(chunkSize, height - row);
5754    const maskData = maskCtx.getImageData(layerOffsetX - maskOffsetX, row + (layerOffsetY - maskOffsetY), width, chunkHeight);
5755    const layerData = layerCtx.getImageData(layerOffsetX, row + layerOffsetY, width, chunkHeight);
5756
5757    if (hasBackdrop) {
5758      composeSMaskBackdrop(maskData.data, r0, g0, b0);
5759    }
5760
5761    composeFn(maskData.data, layerData.data, transferMap);
5762    layerCtx.putImageData(layerData, layerOffsetX, row + layerOffsetY);
5763  }
5764}
5765
5766function composeSMask(ctx, smask, layerCtx, layerBox) {
5767  const layerOffsetX = layerBox[0];
5768  const layerOffsetY = layerBox[1];
5769  const layerWidth = layerBox[2] - layerOffsetX;
5770  const layerHeight = layerBox[3] - layerOffsetY;
5771
5772  if (layerWidth === 0 || layerHeight === 0) {
5773    return;
5774  }
5775
5776  genericComposeSMask(smask.context, layerCtx, layerWidth, layerHeight, smask.subtype, smask.backdrop, smask.transferMap, layerOffsetX, layerOffsetY, smask.offsetX, smask.offsetY);
5777  ctx.save();
5778  ctx.globalAlpha = 1;
5779  ctx.globalCompositeOperation = "source-over";
5780  ctx.setTransform(1, 0, 0, 1, 0, 0);
5781  ctx.drawImage(layerCtx.canvas, 0, 0);
5782  ctx.restore();
5783}
5784
5785function getImageSmoothingEnabled(transform, interpolate) {
5786  const scale = _util.Util.singularValueDecompose2dScale(transform);
5787
5788  scale[0] = Math.fround(scale[0]);
5789  scale[1] = Math.fround(scale[1]);
5790  const actualScale = Math.fround((globalThis.devicePixelRatio || 1) * _display_utils.PixelsPerInch.PDF_TO_CSS_UNITS);
5791
5792  if (interpolate !== undefined) {
5793    return interpolate;
5794  } else if (scale[0] <= actualScale || scale[1] <= actualScale) {
5795    return true;
5796  }
5797
5798  return false;
5799}
5800
5801const LINE_CAP_STYLES = ["butt", "round", "square"];
5802const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
5803const NORMAL_CLIP = {};
5804const EO_CLIP = {};
5805
5806class CanvasGraphics {
5807  constructor(canvasCtx, commonObjs, objs, canvasFactory, imageLayer, optionalContentConfig, annotationCanvasMap, pageColors) {
5808    this.ctx = canvasCtx;
5809    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
5810    this.stateStack = [];
5811    this.pendingClip = null;
5812    this.pendingEOFill = false;
5813    this.res = null;
5814    this.xobjs = null;
5815    this.commonObjs = commonObjs;
5816    this.objs = objs;
5817    this.canvasFactory = canvasFactory;
5818    this.imageLayer = imageLayer;
5819    this.groupStack = [];
5820    this.processingType3 = null;
5821    this.baseTransform = null;
5822    this.baseTransformStack = [];
5823    this.groupLevel = 0;
5824    this.smaskStack = [];
5825    this.smaskCounter = 0;
5826    this.tempSMask = null;
5827    this.suspendedCtx = null;
5828    this.contentVisible = true;
5829    this.markedContentStack = [];
5830    this.optionalContentConfig = optionalContentConfig;
5831    this.cachedCanvases = new CachedCanvases(this.canvasFactory);
5832    this.cachedPatterns = new Map();
5833    this.annotationCanvasMap = annotationCanvasMap;
5834    this.viewportScale = 1;
5835    this.outputScaleX = 1;
5836    this.outputScaleY = 1;
5837    this.backgroundColor = pageColors?.background || null;
5838    this.foregroundColor = pageColors?.foreground || null;
5839
5840    if (canvasCtx) {
5841      addContextCurrentTransform(canvasCtx);
5842    }
5843
5844    this._cachedScaleForStroking = null;
5845    this._cachedGetSinglePixelWidth = null;
5846    this._cachedBitmapsMap = new Map();
5847  }
5848
5849  getObject(data, fallback = null) {
5850    if (typeof data === "string") {
5851      return data.startsWith("g_") ? this.commonObjs.get(data) : this.objs.get(data);
5852    }
5853
5854    return fallback;
5855  }
5856
5857  beginDrawing({
5858    transform,
5859    viewport,
5860    transparency = false,
5861    background = null
5862  }) {
5863    const width = this.ctx.canvas.width;
5864    const height = this.ctx.canvas.height;
5865    const defaultBackgroundColor = background || "#ffffff";
5866    this.ctx.save();
5867
5868    if (this.foregroundColor && this.backgroundColor) {
5869      this.ctx.fillStyle = this.foregroundColor;
5870      const fg = this.foregroundColor = this.ctx.fillStyle;
5871      this.ctx.fillStyle = this.backgroundColor;
5872      const bg = this.backgroundColor = this.ctx.fillStyle;
5873      let isValidDefaultBg = true;
5874      let defaultBg = defaultBackgroundColor;
5875      this.ctx.fillStyle = defaultBackgroundColor;
5876      defaultBg = this.ctx.fillStyle;
5877      isValidDefaultBg = typeof defaultBg === "string" && /^#[0-9A-Fa-f]{6}$/.test(defaultBg);
5878
5879      if (fg === "#000000" && bg === "#ffffff" || fg === bg || !isValidDefaultBg) {
5880        this.foregroundColor = this.backgroundColor = null;
5881      } else {
5882        const cB = parseInt(defaultBg.slice(1), 16);
5883        const rB = (cB && 0xff0000) >> 16;
5884        const gB = (cB && 0x00ff00) >> 8;
5885        const bB = cB && 0x0000ff;
5886
5887        const newComp = x => {
5888          x /= 255;
5889          return x <= 0.03928 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4;
5890        };
5891
5892        const lumB = Math.round(0.2126 * newComp(rB) + 0.7152 * newComp(gB) + 0.0722 * newComp(bB));
5893
5894        this.selectColor = (r, g, b) => {
5895          const lumC = 0.2126 * newComp(r) + 0.7152 * newComp(g) + 0.0722 * newComp(b);
5896          return Math.round(lumC) === lumB ? bg : fg;
5897        };
5898      }
5899    }
5900
5901    this.ctx.fillStyle = this.backgroundColor || defaultBackgroundColor;
5902    this.ctx.fillRect(0, 0, width, height);
5903    this.ctx.restore();
5904
5905    if (transparency) {
5906      const transparentCanvas = this.cachedCanvases.getCanvas("transparent", width, height, true);
5907      this.compositeCtx = this.ctx;
5908      this.transparentCanvas = transparentCanvas.canvas;
5909      this.ctx = transparentCanvas.context;
5910      this.ctx.save();
5911      this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform);
5912    }
5913
5914    this.ctx.save();
5915    resetCtxToDefault(this.ctx, this.foregroundColor);
5916
5917    if (transform) {
5918      this.ctx.transform.apply(this.ctx, transform);
5919      this.outputScaleX = transform[0];
5920      this.outputScaleY = transform[0];
5921    }
5922
5923    this.ctx.transform.apply(this.ctx, viewport.transform);
5924    this.viewportScale = viewport.scale;
5925    this.baseTransform = this.ctx.mozCurrentTransform.slice();
5926
5927    if (this.imageLayer) {
5928      this.imageLayer.beginLayout();
5929    }
5930  }
5931
5932  executeOperatorList(operatorList, executionStartIdx, continueCallback, stepper) {
5933    const argsArray = operatorList.argsArray;
5934    const fnArray = operatorList.fnArray;
5935    let i = executionStartIdx || 0;
5936    const argsArrayLen = argsArray.length;
5937
5938    if (argsArrayLen === i) {
5939      return i;
5940    }
5941
5942    const chunkOperations = argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === "function";
5943    const endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0;
5944    let steps = 0;
5945    const commonObjs = this.commonObjs;
5946    const objs = this.objs;
5947    let fnId;
5948
5949    while (true) {
5950      if (stepper !== undefined && i === stepper.nextBreakPoint) {
5951        stepper.breakIt(i, continueCallback);
5952        return i;
5953      }
5954
5955      fnId = fnArray[i];
5956
5957      if (fnId !== _util.OPS.dependency) {
5958        this[fnId].apply(this, argsArray[i]);
5959      } else {
5960        for (const depObjId of argsArray[i]) {
5961          const objsPool = depObjId.startsWith("g_") ? commonObjs : objs;
5962
5963          if (!objsPool.has(depObjId)) {
5964            objsPool.get(depObjId, continueCallback);
5965            return i;
5966          }
5967        }
5968      }
5969
5970      i++;
5971
5972      if (i === argsArrayLen) {
5973        return i;
5974      }
5975
5976      if (chunkOperations && ++steps > EXECUTION_STEPS) {
5977        if (Date.now() > endTime) {
5978          continueCallback();
5979          return i;
5980        }
5981
5982        steps = 0;
5983      }
5984    }
5985  }
5986
5987  endDrawing() {
5988    while (this.stateStack.length || this.inSMaskMode) {
5989      this.restore();
5990    }
5991
5992    this.ctx.restore();
5993
5994    if (this.transparentCanvas) {
5995      this.ctx = this.compositeCtx;
5996      this.ctx.save();
5997      this.ctx.setTransform(1, 0, 0, 1, 0, 0);
5998      this.ctx.drawImage(this.transparentCanvas, 0, 0);
5999      this.ctx.restore();
6000      this.transparentCanvas = null;
6001    }
6002
6003    this.cachedCanvases.clear();
6004    this.cachedPatterns.clear();
6005
6006    for (const cache of this._cachedBitmapsMap.values()) {
6007      for (const canvas of cache.values()) {
6008        if (typeof HTMLCanvasElement !== "undefined" && canvas instanceof HTMLCanvasElement) {
6009          canvas.width = canvas.height = 0;
6010        }
6011      }
6012
6013      cache.clear();
6014    }
6015
6016    this._cachedBitmapsMap.clear();
6017
6018    if (this.imageLayer) {
6019      this.imageLayer.endLayout();
6020    }
6021  }
6022
6023  _scaleImage(img, inverseTransform) {
6024    const width = img.width;
6025    const height = img.height;
6026    let widthScale = Math.max(Math.hypot(inverseTransform[0], inverseTransform[1]), 1);
6027    let heightScale = Math.max(Math.hypot(inverseTransform[2], inverseTransform[3]), 1);
6028    let paintWidth = width,
6029        paintHeight = height;
6030    let tmpCanvasId = "prescale1";
6031    let tmpCanvas, tmpCtx;
6032
6033    while (widthScale > 2 && paintWidth > 1 || heightScale > 2 && paintHeight > 1) {
6034      let newWidth = paintWidth,
6035          newHeight = paintHeight;
6036
6037      if (widthScale > 2 && paintWidth > 1) {
6038        newWidth = Math.ceil(paintWidth / 2);
6039        widthScale /= paintWidth / newWidth;
6040      }
6041
6042      if (heightScale > 2 && paintHeight > 1) {
6043        newHeight = Math.ceil(paintHeight / 2);
6044        heightScale /= paintHeight / newHeight;
6045      }
6046
6047      tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight, false);
6048      tmpCtx = tmpCanvas.context;
6049      tmpCtx.clearRect(0, 0, newWidth, newHeight);
6050      tmpCtx.drawImage(img, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight);
6051      img = tmpCanvas.canvas;
6052      paintWidth = newWidth;
6053      paintHeight = newHeight;
6054      tmpCanvasId = tmpCanvasId === "prescale1" ? "prescale2" : "prescale1";
6055    }
6056
6057    return {
6058      img,
6059      paintWidth,
6060      paintHeight
6061    };
6062  }
6063
6064  _createMaskCanvas(img) {
6065    const ctx = this.ctx;
6066    const {
6067      width,
6068      height
6069    } = img;
6070    const fillColor = this.current.fillColor;
6071    const isPatternFill = this.current.patternFill;
6072    const currentTransform = ctx.mozCurrentTransform;
6073    let cache, cacheKey, scaled, maskCanvas;
6074
6075    if ((img.bitmap || img.data) && img.count > 1) {
6076      const mainKey = img.bitmap || img.data.buffer;
6077      const withoutTranslation = currentTransform.slice(0, 4);
6078      cacheKey = JSON.stringify(isPatternFill ? withoutTranslation : [withoutTranslation, fillColor]);
6079      cache = this._cachedBitmapsMap.get(mainKey);
6080
6081      if (!cache) {
6082        cache = new Map();
6083
6084        this._cachedBitmapsMap.set(mainKey, cache);
6085      }
6086
6087      const cachedImage = cache.get(cacheKey);
6088
6089      if (cachedImage && !isPatternFill) {
6090        const offsetX = Math.round(Math.min(currentTransform[0], currentTransform[2]) + currentTransform[4]);
6091        const offsetY = Math.round(Math.min(currentTransform[1], currentTransform[3]) + currentTransform[5]);
6092        return {
6093          canvas: cachedImage,
6094          offsetX,
6095          offsetY
6096        };
6097      }
6098
6099      scaled = cachedImage;
6100    }
6101
6102    if (!scaled) {
6103      maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
6104      putBinaryImageMask(maskCanvas.context, img);
6105    }
6106
6107    let maskToCanvas = _util.Util.transform(currentTransform, [1 / width, 0, 0, -1 / height, 0, 0]);
6108
6109    maskToCanvas = _util.Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
6110
6111    const cord1 = _util.Util.applyTransform([0, 0], maskToCanvas);
6112
6113    const cord2 = _util.Util.applyTransform([width, height], maskToCanvas);
6114
6115    const rect = _util.Util.normalizeRect([cord1[0], cord1[1], cord2[0], cord2[1]]);
6116
6117    const drawnWidth = Math.round(rect[2] - rect[0]) || 1;
6118    const drawnHeight = Math.round(rect[3] - rect[1]) || 1;
6119    const fillCanvas = this.cachedCanvases.getCanvas("fillCanvas", drawnWidth, drawnHeight, true);
6120    const fillCtx = fillCanvas.context;
6121    const offsetX = Math.min(cord1[0], cord2[0]);
6122    const offsetY = Math.min(cord1[1], cord2[1]);
6123    fillCtx.translate(-offsetX, -offsetY);
6124    fillCtx.transform.apply(fillCtx, maskToCanvas);
6125
6126    if (!scaled) {
6127      scaled = this._scaleImage(maskCanvas.canvas, fillCtx.mozCurrentTransformInverse);
6128      scaled = scaled.img;
6129
6130      if (cache && isPatternFill) {
6131        cache.set(cacheKey, scaled);
6132      }
6133    }
6134
6135    fillCtx.imageSmoothingEnabled = getImageSmoothingEnabled(fillCtx.mozCurrentTransform, img.interpolate);
6136    drawImageAtIntegerCoords(fillCtx, scaled, 0, 0, scaled.width, scaled.height, 0, 0, width, height);
6137    fillCtx.globalCompositeOperation = "source-in";
6138
6139    const inverse = _util.Util.transform(fillCtx.mozCurrentTransformInverse, [1, 0, 0, 1, -offsetX, -offsetY]);
6140
6141    fillCtx.fillStyle = isPatternFill ? fillColor.getPattern(ctx, this, inverse, _pattern_helper.PathType.FILL) : fillColor;
6142    fillCtx.fillRect(0, 0, width, height);
6143
6144    if (cache && !isPatternFill) {
6145      this.cachedCanvases.delete("fillCanvas");
6146      cache.set(cacheKey, fillCanvas.canvas);
6147    }
6148
6149    return {
6150      canvas: fillCanvas.canvas,
6151      offsetX: Math.round(offsetX),
6152      offsetY: Math.round(offsetY)
6153    };
6154  }
6155
6156  setLineWidth(width) {
6157    if (width !== this.current.lineWidth) {
6158      this._cachedScaleForStroking = null;
6159    }
6160
6161    this.current.lineWidth = width;
6162    this.ctx.lineWidth = width;
6163  }
6164
6165  setLineCap(style) {
6166    this.ctx.lineCap = LINE_CAP_STYLES[style];
6167  }
6168
6169  setLineJoin(style) {
6170    this.ctx.lineJoin = LINE_JOIN_STYLES[style];
6171  }
6172
6173  setMiterLimit(limit) {
6174    this.ctx.miterLimit = limit;
6175  }
6176
6177  setDash(dashArray, dashPhase) {
6178    const ctx = this.ctx;
6179
6180    if (ctx.setLineDash !== undefined) {
6181      ctx.setLineDash(dashArray);
6182      ctx.lineDashOffset = dashPhase;
6183    }
6184  }
6185
6186  setRenderingIntent(intent) {}
6187
6188  setFlatness(flatness) {}
6189
6190  setGState(states) {
6191    for (let i = 0, ii = states.length; i < ii; i++) {
6192      const state = states[i];
6193      const key = state[0];
6194      const value = state[1];
6195
6196      switch (key) {
6197        case "LW":
6198          this.setLineWidth(value);
6199          break;
6200
6201        case "LC":
6202          this.setLineCap(value);
6203          break;
6204
6205        case "LJ":
6206          this.setLineJoin(value);
6207          break;
6208
6209        case "ML":
6210          this.setMiterLimit(value);
6211          break;
6212
6213        case "D":
6214          this.setDash(value[0], value[1]);
6215          break;
6216
6217        case "RI":
6218          this.setRenderingIntent(value);
6219          break;
6220
6221        case "FL":
6222          this.setFlatness(value);
6223          break;
6224
6225        case "Font":
6226          this.setFont(value[0], value[1]);
6227          break;
6228
6229        case "CA":
6230          this.current.strokeAlpha = state[1];
6231          break;
6232
6233        case "ca":
6234          this.current.fillAlpha = state[1];
6235          this.ctx.globalAlpha = state[1];
6236          break;
6237
6238        case "BM":
6239          this.ctx.globalCompositeOperation = value;
6240          break;
6241
6242        case "SMask":
6243          this.current.activeSMask = value ? this.tempSMask : null;
6244          this.tempSMask = null;
6245          this.checkSMaskState();
6246          break;
6247
6248        case "TR":
6249          this.current.transferMaps = value;
6250      }
6251    }
6252  }
6253
6254  get inSMaskMode() {
6255    return !!this.suspendedCtx;
6256  }
6257
6258  checkSMaskState() {
6259    const inSMaskMode = this.inSMaskMode;
6260
6261    if (this.current.activeSMask && !inSMaskMode) {
6262      this.beginSMaskMode();
6263    } else if (!this.current.activeSMask && inSMaskMode) {
6264      this.endSMaskMode();
6265    }
6266  }
6267
6268  beginSMaskMode() {
6269    if (this.inSMaskMode) {
6270      throw new Error("beginSMaskMode called while already in smask mode");
6271    }
6272
6273    const drawnWidth = this.ctx.canvas.width;
6274    const drawnHeight = this.ctx.canvas.height;
6275    const cacheId = "smaskGroupAt" + this.groupLevel;
6276    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
6277    this.suspendedCtx = this.ctx;
6278    this.ctx = scratchCanvas.context;
6279    const ctx = this.ctx;
6280    ctx.setTransform.apply(ctx, this.suspendedCtx.mozCurrentTransform);
6281    copyCtxState(this.suspendedCtx, ctx);
6282    mirrorContextOperations(ctx, this.suspendedCtx);
6283    this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
6284  }
6285
6286  endSMaskMode() {
6287    if (!this.inSMaskMode) {
6288      throw new Error("endSMaskMode called while not in smask mode");
6289    }
6290
6291    this.ctx._removeMirroring();
6292
6293    copyCtxState(this.ctx, this.suspendedCtx);
6294    this.ctx = this.suspendedCtx;
6295    this.suspendedCtx = null;
6296  }
6297
6298  compose(dirtyBox) {
6299    if (!this.current.activeSMask) {
6300      return;
6301    }
6302
6303    if (!dirtyBox) {
6304      dirtyBox = [0, 0, this.ctx.canvas.width, this.ctx.canvas.height];
6305    } else {
6306      dirtyBox[0] = Math.floor(dirtyBox[0]);
6307      dirtyBox[1] = Math.floor(dirtyBox[1]);
6308      dirtyBox[2] = Math.ceil(dirtyBox[2]);
6309      dirtyBox[3] = Math.ceil(dirtyBox[3]);
6310    }
6311
6312    const smask = this.current.activeSMask;
6313    const suspendedCtx = this.suspendedCtx;
6314    composeSMask(suspendedCtx, smask, this.ctx, dirtyBox);
6315    this.ctx.save();
6316    this.ctx.setTransform(1, 0, 0, 1, 0, 0);
6317    this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
6318    this.ctx.restore();
6319  }
6320
6321  save() {
6322    if (this.inSMaskMode) {
6323      copyCtxState(this.ctx, this.suspendedCtx);
6324      this.suspendedCtx.save();
6325    } else {
6326      this.ctx.save();
6327    }
6328
6329    const old = this.current;
6330    this.stateStack.push(old);
6331    this.current = old.clone();
6332  }
6333
6334  restore() {
6335    if (this.stateStack.length === 0 && this.inSMaskMode) {
6336      this.endSMaskMode();
6337    }
6338
6339    if (this.stateStack.length !== 0) {
6340      this.current = this.stateStack.pop();
6341
6342      if (this.inSMaskMode) {
6343        this.suspendedCtx.restore();
6344        copyCtxState(this.suspendedCtx, this.ctx);
6345      } else {
6346        this.ctx.restore();
6347      }
6348
6349      this.checkSMaskState();
6350      this.pendingClip = null;
6351      this._cachedScaleForStroking = null;
6352      this._cachedGetSinglePixelWidth = null;
6353    }
6354  }
6355
6356  transform(a, b, c, d, e, f) {
6357    this.ctx.transform(a, b, c, d, e, f);
6358    this._cachedScaleForStroking = null;
6359    this._cachedGetSinglePixelWidth = null;
6360  }
6361
6362  constructPath(ops, args, minMax) {
6363    const ctx = this.ctx;
6364    const current = this.current;
6365    let x = current.x,
6366        y = current.y;
6367    let startX, startY;
6368    const currentTransform = ctx.mozCurrentTransform;
6369    const isScalingMatrix = currentTransform[0] === 0 && currentTransform[3] === 0 || currentTransform[1] === 0 && currentTransform[2] === 0;
6370    const minMaxForBezier = isScalingMatrix ? minMax.slice(0) : null;
6371
6372    for (let i = 0, j = 0, ii = ops.length; i < ii; i++) {
6373      switch (ops[i] | 0) {
6374        case _util.OPS.rectangle:
6375          x = args[j++];
6376          y = args[j++];
6377          const width = args[j++];
6378          const height = args[j++];
6379          const xw = x + width;
6380          const yh = y + height;
6381          ctx.moveTo(x, y);
6382
6383          if (width === 0 || height === 0) {
6384            ctx.lineTo(xw, yh);
6385          } else {
6386            ctx.lineTo(xw, y);
6387            ctx.lineTo(xw, yh);
6388            ctx.lineTo(x, yh);
6389          }
6390
6391          if (!isScalingMatrix) {
6392            current.updateRectMinMax(currentTransform, [x, y, xw, yh]);
6393          }
6394
6395          ctx.closePath();
6396          break;
6397
6398        case _util.OPS.moveTo:
6399          x = args[j++];
6400          y = args[j++];
6401          ctx.moveTo(x, y);
6402
6403          if (!isScalingMatrix) {
6404            current.updatePathMinMax(currentTransform, x, y);
6405          }
6406
6407          break;
6408
6409        case _util.OPS.lineTo:
6410          x = args[j++];
6411          y = args[j++];
6412          ctx.lineTo(x, y);
6413
6414          if (!isScalingMatrix) {
6415            current.updatePathMinMax(currentTransform, x, y);
6416          }
6417
6418          break;
6419
6420        case _util.OPS.curveTo:
6421          startX = x;
6422          startY = y;
6423          x = args[j + 4];
6424          y = args[j + 5];
6425          ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y);
6426          current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], args[j + 2], args[j + 3], x, y, minMaxForBezier);
6427          j += 6;
6428          break;
6429
6430        case _util.OPS.curveTo2:
6431          startX = x;
6432          startY = y;
6433          ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]);
6434          current.updateCurvePathMinMax(currentTransform, startX, startY, x, y, args[j], args[j + 1], args[j + 2], args[j + 3], minMaxForBezier);
6435          x = args[j + 2];
6436          y = args[j + 3];
6437          j += 4;
6438          break;
6439
6440        case _util.OPS.curveTo3:
6441          startX = x;
6442          startY = y;
6443          x = args[j + 2];
6444          y = args[j + 3];
6445          ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y);
6446          current.updateCurvePathMinMax(currentTransform, startX, startY, args[j], args[j + 1], x, y, x, y, minMaxForBezier);
6447          j += 4;
6448          break;
6449
6450        case _util.OPS.closePath:
6451          ctx.closePath();
6452          break;
6453      }
6454    }
6455
6456    if (isScalingMatrix) {
6457      current.updateScalingPathMinMax(currentTransform, minMaxForBezier);
6458    }
6459
6460    current.setCurrentPoint(x, y);
6461  }
6462
6463  closePath() {
6464    this.ctx.closePath();
6465  }
6466
6467  stroke(consumePath) {
6468    consumePath = typeof consumePath !== "undefined" ? consumePath : true;
6469    const ctx = this.ctx;
6470    const strokeColor = this.current.strokeColor;
6471    ctx.globalAlpha = this.current.strokeAlpha;
6472
6473    if (this.contentVisible) {
6474      if (typeof strokeColor === "object" && strokeColor?.getPattern) {
6475        ctx.save();
6476        ctx.strokeStyle = strokeColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.STROKE);
6477        this.rescaleAndStroke(false);
6478        ctx.restore();
6479      } else {
6480        this.rescaleAndStroke(true);
6481      }
6482    }
6483
6484    if (consumePath) {
6485      this.consumePath(this.current.getClippedPathBoundingBox());
6486    }
6487
6488    ctx.globalAlpha = this.current.fillAlpha;
6489  }
6490
6491  closeStroke() {
6492    this.closePath();
6493    this.stroke();
6494  }
6495
6496  fill(consumePath) {
6497    consumePath = typeof consumePath !== "undefined" ? consumePath : true;
6498    const ctx = this.ctx;
6499    const fillColor = this.current.fillColor;
6500    const isPatternFill = this.current.patternFill;
6501    let needRestore = false;
6502
6503    if (isPatternFill) {
6504      ctx.save();
6505      ctx.fillStyle = fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
6506      needRestore = true;
6507    }
6508
6509    const intersect = this.current.getClippedPathBoundingBox();
6510
6511    if (this.contentVisible && intersect !== null) {
6512      if (this.pendingEOFill) {
6513        ctx.fill("evenodd");
6514        this.pendingEOFill = false;
6515      } else {
6516        ctx.fill();
6517      }
6518    }
6519
6520    if (needRestore) {
6521      ctx.restore();
6522    }
6523
6524    if (consumePath) {
6525      this.consumePath(intersect);
6526    }
6527  }
6528
6529  eoFill() {
6530    this.pendingEOFill = true;
6531    this.fill();
6532  }
6533
6534  fillStroke() {
6535    this.fill(false);
6536    this.stroke(false);
6537    this.consumePath();
6538  }
6539
6540  eoFillStroke() {
6541    this.pendingEOFill = true;
6542    this.fillStroke();
6543  }
6544
6545  closeFillStroke() {
6546    this.closePath();
6547    this.fillStroke();
6548  }
6549
6550  closeEOFillStroke() {
6551    this.pendingEOFill = true;
6552    this.closePath();
6553    this.fillStroke();
6554  }
6555
6556  endPath() {
6557    this.consumePath();
6558  }
6559
6560  clip() {
6561    this.pendingClip = NORMAL_CLIP;
6562  }
6563
6564  eoClip() {
6565    this.pendingClip = EO_CLIP;
6566  }
6567
6568  beginText() {
6569    this.current.textMatrix = _util.IDENTITY_MATRIX;
6570    this.current.textMatrixScale = 1;
6571    this.current.x = this.current.lineX = 0;
6572    this.current.y = this.current.lineY = 0;
6573  }
6574
6575  endText() {
6576    const paths = this.pendingTextPaths;
6577    const ctx = this.ctx;
6578
6579    if (paths === undefined) {
6580      ctx.beginPath();
6581      return;
6582    }
6583
6584    ctx.save();
6585    ctx.beginPath();
6586
6587    for (let i = 0; i < paths.length; i++) {
6588      const path = paths[i];
6589      ctx.setTransform.apply(ctx, path.transform);
6590      ctx.translate(path.x, path.y);
6591      path.addToPath(ctx, path.fontSize);
6592    }
6593
6594    ctx.restore();
6595    ctx.clip();
6596    ctx.beginPath();
6597    delete this.pendingTextPaths;
6598  }
6599
6600  setCharSpacing(spacing) {
6601    this.current.charSpacing = spacing;
6602  }
6603
6604  setWordSpacing(spacing) {
6605    this.current.wordSpacing = spacing;
6606  }
6607
6608  setHScale(scale) {
6609    this.current.textHScale = scale / 100;
6610  }
6611
6612  setLeading(leading) {
6613    this.current.leading = -leading;
6614  }
6615
6616  setFont(fontRefName, size) {
6617    const fontObj = this.commonObjs.get(fontRefName);
6618    const current = this.current;
6619
6620    if (!fontObj) {
6621      throw new Error(`Can't find font for ${fontRefName}`);
6622    }
6623
6624    current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6625
6626    if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) {
6627      (0, _util.warn)("Invalid font matrix for font " + fontRefName);
6628    }
6629
6630    if (size < 0) {
6631      size = -size;
6632      current.fontDirection = -1;
6633    } else {
6634      current.fontDirection = 1;
6635    }
6636
6637    this.current.font = fontObj;
6638    this.current.fontSize = size;
6639
6640    if (fontObj.isType3Font) {
6641      return;
6642    }
6643
6644    const name = fontObj.loadedName || "sans-serif";
6645    let bold = "normal";
6646
6647    if (fontObj.black) {
6648      bold = "900";
6649    } else if (fontObj.bold) {
6650      bold = "bold";
6651    }
6652
6653    const italic = fontObj.italic ? "italic" : "normal";
6654    const typeface = `"${name}", ${fontObj.fallbackName}`;
6655    let browserFontSize = size;
6656
6657    if (size < MIN_FONT_SIZE) {
6658      browserFontSize = MIN_FONT_SIZE;
6659    } else if (size > MAX_FONT_SIZE) {
6660      browserFontSize = MAX_FONT_SIZE;
6661    }
6662
6663    this.current.fontSizeScale = size / browserFontSize;
6664    this.ctx.font = `${italic} ${bold} ${browserFontSize}px ${typeface}`;
6665  }
6666
6667  setTextRenderingMode(mode) {
6668    this.current.textRenderingMode = mode;
6669  }
6670
6671  setTextRise(rise) {
6672    this.current.textRise = rise;
6673  }
6674
6675  moveText(x, y) {
6676    this.current.x = this.current.lineX += x;
6677    this.current.y = this.current.lineY += y;
6678  }
6679
6680  setLeadingMoveText(x, y) {
6681    this.setLeading(-y);
6682    this.moveText(x, y);
6683  }
6684
6685  setTextMatrix(a, b, c, d, e, f) {
6686    this.current.textMatrix = [a, b, c, d, e, f];
6687    this.current.textMatrixScale = Math.hypot(a, b);
6688    this.current.x = this.current.lineX = 0;
6689    this.current.y = this.current.lineY = 0;
6690  }
6691
6692  nextLine() {
6693    this.moveText(0, this.current.leading);
6694  }
6695
6696  paintChar(character, x, y, patternTransform) {
6697    const ctx = this.ctx;
6698    const current = this.current;
6699    const font = current.font;
6700    const textRenderingMode = current.textRenderingMode;
6701    const fontSize = current.fontSize / current.fontSizeScale;
6702    const fillStrokeMode = textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6703    const isAddToPathSet = !!(textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG);
6704    const patternFill = current.patternFill && !font.missingFile;
6705    let addToPath;
6706
6707    if (font.disableFontFace || isAddToPathSet || patternFill) {
6708      addToPath = font.getPathGenerator(this.commonObjs, character);
6709    }
6710
6711    if (font.disableFontFace || patternFill) {
6712      ctx.save();
6713      ctx.translate(x, y);
6714      ctx.beginPath();
6715      addToPath(ctx, fontSize);
6716
6717      if (patternTransform) {
6718        ctx.setTransform.apply(ctx, patternTransform);
6719      }
6720
6721      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6722        ctx.fill();
6723      }
6724
6725      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6726        ctx.stroke();
6727      }
6728
6729      ctx.restore();
6730    } else {
6731      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6732        ctx.fillText(character, x, y);
6733      }
6734
6735      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6736        ctx.strokeText(character, x, y);
6737      }
6738    }
6739
6740    if (isAddToPathSet) {
6741      const paths = this.pendingTextPaths || (this.pendingTextPaths = []);
6742      paths.push({
6743        transform: ctx.mozCurrentTransform,
6744        x,
6745        y,
6746        fontSize,
6747        addToPath
6748      });
6749    }
6750  }
6751
6752  get isFontSubpixelAAEnabled() {
6753    const {
6754      context: ctx
6755    } = this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled", 10, 10, false);
6756    ctx.scale(1.5, 1);
6757    ctx.fillText("I", 0, 10);
6758    const data = ctx.getImageData(0, 0, 10, 10).data;
6759    let enabled = false;
6760
6761    for (let i = 3; i < data.length; i += 4) {
6762      if (data[i] > 0 && data[i] < 255) {
6763        enabled = true;
6764        break;
6765      }
6766    }
6767
6768    return (0, _util.shadow)(this, "isFontSubpixelAAEnabled", enabled);
6769  }
6770
6771  showText(glyphs) {
6772    const current = this.current;
6773    const font = current.font;
6774
6775    if (font.isType3Font) {
6776      return this.showType3Text(glyphs);
6777    }
6778
6779    const fontSize = current.fontSize;
6780
6781    if (fontSize === 0) {
6782      return undefined;
6783    }
6784
6785    const ctx = this.ctx;
6786    const fontSizeScale = current.fontSizeScale;
6787    const charSpacing = current.charSpacing;
6788    const wordSpacing = current.wordSpacing;
6789    const fontDirection = current.fontDirection;
6790    const textHScale = current.textHScale * fontDirection;
6791    const glyphsLength = glyphs.length;
6792    const vertical = font.vertical;
6793    const spacingDir = vertical ? 1 : -1;
6794    const defaultVMetrics = font.defaultVMetrics;
6795    const widthAdvanceScale = fontSize * current.fontMatrix[0];
6796    const simpleFillText = current.textRenderingMode === _util.TextRenderingMode.FILL && !font.disableFontFace && !current.patternFill;
6797    ctx.save();
6798    ctx.transform.apply(ctx, current.textMatrix);
6799    ctx.translate(current.x, current.y + current.textRise);
6800
6801    if (fontDirection > 0) {
6802      ctx.scale(textHScale, -1);
6803    } else {
6804      ctx.scale(textHScale, 1);
6805    }
6806
6807    let patternTransform;
6808
6809    if (current.patternFill) {
6810      ctx.save();
6811      const pattern = current.fillColor.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL);
6812      patternTransform = ctx.mozCurrentTransform;
6813      ctx.restore();
6814      ctx.fillStyle = pattern;
6815    }
6816
6817    let lineWidth = current.lineWidth;
6818    const scale = current.textMatrixScale;
6819
6820    if (scale === 0 || lineWidth === 0) {
6821      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
6822
6823      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
6824        lineWidth = this.getSinglePixelWidth();
6825      }
6826    } else {
6827      lineWidth /= scale;
6828    }
6829
6830    if (fontSizeScale !== 1.0) {
6831      ctx.scale(fontSizeScale, fontSizeScale);
6832      lineWidth /= fontSizeScale;
6833    }
6834
6835    ctx.lineWidth = lineWidth;
6836    let x = 0,
6837        i;
6838
6839    for (i = 0; i < glyphsLength; ++i) {
6840      const glyph = glyphs[i];
6841
6842      if (typeof glyph === "number") {
6843        x += spacingDir * glyph * fontSize / 1000;
6844        continue;
6845      }
6846
6847      let restoreNeeded = false;
6848      const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6849      const character = glyph.fontChar;
6850      const accent = glyph.accent;
6851      let scaledX, scaledY;
6852      let width = glyph.width;
6853
6854      if (vertical) {
6855        const vmetric = glyph.vmetric || defaultVMetrics;
6856        const vx = -(glyph.vmetric ? vmetric[1] : width * 0.5) * widthAdvanceScale;
6857        const vy = vmetric[2] * widthAdvanceScale;
6858        width = vmetric ? -vmetric[0] : width;
6859        scaledX = vx / fontSizeScale;
6860        scaledY = (x + vy) / fontSizeScale;
6861      } else {
6862        scaledX = x / fontSizeScale;
6863        scaledY = 0;
6864      }
6865
6866      if (font.remeasure && width > 0) {
6867        const measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale;
6868
6869        if (width < measuredWidth && this.isFontSubpixelAAEnabled) {
6870          const characterScaleX = width / measuredWidth;
6871          restoreNeeded = true;
6872          ctx.save();
6873          ctx.scale(characterScaleX, 1);
6874          scaledX /= characterScaleX;
6875        } else if (width !== measuredWidth) {
6876          scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale;
6877        }
6878      }
6879
6880      if (this.contentVisible && (glyph.isInFont || font.missingFile)) {
6881        if (simpleFillText && !accent) {
6882          ctx.fillText(character, scaledX, scaledY);
6883        } else {
6884          this.paintChar(character, scaledX, scaledY, patternTransform);
6885
6886          if (accent) {
6887            const scaledAccentX = scaledX + fontSize * accent.offset.x / fontSizeScale;
6888            const scaledAccentY = scaledY - fontSize * accent.offset.y / fontSizeScale;
6889            this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY, patternTransform);
6890          }
6891        }
6892      }
6893
6894      let charWidth;
6895
6896      if (vertical) {
6897        charWidth = width * widthAdvanceScale - spacing * fontDirection;
6898      } else {
6899        charWidth = width * widthAdvanceScale + spacing * fontDirection;
6900      }
6901
6902      x += charWidth;
6903
6904      if (restoreNeeded) {
6905        ctx.restore();
6906      }
6907    }
6908
6909    if (vertical) {
6910      current.y -= x;
6911    } else {
6912      current.x += x * textHScale;
6913    }
6914
6915    ctx.restore();
6916    this.compose();
6917    return undefined;
6918  }
6919
6920  showType3Text(glyphs) {
6921    const ctx = this.ctx;
6922    const current = this.current;
6923    const font = current.font;
6924    const fontSize = current.fontSize;
6925    const fontDirection = current.fontDirection;
6926    const spacingDir = font.vertical ? 1 : -1;
6927    const charSpacing = current.charSpacing;
6928    const wordSpacing = current.wordSpacing;
6929    const textHScale = current.textHScale * fontDirection;
6930    const fontMatrix = current.fontMatrix || _util.FONT_IDENTITY_MATRIX;
6931    const glyphsLength = glyphs.length;
6932    const isTextInvisible = current.textRenderingMode === _util.TextRenderingMode.INVISIBLE;
6933    let i, glyph, width, spacingLength;
6934
6935    if (isTextInvisible || fontSize === 0) {
6936      return;
6937    }
6938
6939    this._cachedScaleForStroking = null;
6940    this._cachedGetSinglePixelWidth = null;
6941    ctx.save();
6942    ctx.transform.apply(ctx, current.textMatrix);
6943    ctx.translate(current.x, current.y);
6944    ctx.scale(textHScale, fontDirection);
6945
6946    for (i = 0; i < glyphsLength; ++i) {
6947      glyph = glyphs[i];
6948
6949      if (typeof glyph === "number") {
6950        spacingLength = spacingDir * glyph * fontSize / 1000;
6951        this.ctx.translate(spacingLength, 0);
6952        current.x += spacingLength * textHScale;
6953        continue;
6954      }
6955
6956      const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
6957      const operatorList = font.charProcOperatorList[glyph.operatorListId];
6958
6959      if (!operatorList) {
6960        (0, _util.warn)(`Type3 character "${glyph.operatorListId}" is not available.`);
6961        continue;
6962      }
6963
6964      if (this.contentVisible) {
6965        this.processingType3 = glyph;
6966        this.save();
6967        ctx.scale(fontSize, fontSize);
6968        ctx.transform.apply(ctx, fontMatrix);
6969        this.executeOperatorList(operatorList);
6970        this.restore();
6971      }
6972
6973      const transformed = _util.Util.applyTransform([glyph.width, 0], fontMatrix);
6974
6975      width = transformed[0] * fontSize + spacing;
6976      ctx.translate(width, 0);
6977      current.x += width * textHScale;
6978    }
6979
6980    ctx.restore();
6981    this.processingType3 = null;
6982  }
6983
6984  setCharWidth(xWidth, yWidth) {}
6985
6986  setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) {
6987    this.ctx.rect(llx, lly, urx - llx, ury - lly);
6988    this.ctx.clip();
6989    this.endPath();
6990  }
6991
6992  getColorN_Pattern(IR) {
6993    let pattern;
6994
6995    if (IR[0] === "TilingPattern") {
6996      const color = IR[1];
6997      const baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice();
6998      const canvasGraphicsFactory = {
6999        createCanvasGraphics: ctx => {
7000          return new CanvasGraphics(ctx, this.commonObjs, this.objs, this.canvasFactory);
7001        }
7002      };
7003      pattern = new _pattern_helper.TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform);
7004    } else {
7005      pattern = this._getPattern(IR[1], IR[2]);
7006    }
7007
7008    return pattern;
7009  }
7010
7011  setStrokeColorN() {
7012    this.current.strokeColor = this.getColorN_Pattern(arguments);
7013  }
7014
7015  setFillColorN() {
7016    this.current.fillColor = this.getColorN_Pattern(arguments);
7017    this.current.patternFill = true;
7018  }
7019
7020  setStrokeRGBColor(r, g, b) {
7021    const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
7022
7023    this.ctx.strokeStyle = color;
7024    this.current.strokeColor = color;
7025  }
7026
7027  setFillRGBColor(r, g, b) {
7028    const color = this.selectColor?.(r, g, b) || _util.Util.makeHexColor(r, g, b);
7029
7030    this.ctx.fillStyle = color;
7031    this.current.fillColor = color;
7032    this.current.patternFill = false;
7033  }
7034
7035  _getPattern(objId, matrix = null) {
7036    let pattern;
7037
7038    if (this.cachedPatterns.has(objId)) {
7039      pattern = this.cachedPatterns.get(objId);
7040    } else {
7041      pattern = (0, _pattern_helper.getShadingPattern)(this.objs.get(objId));
7042      this.cachedPatterns.set(objId, pattern);
7043    }
7044
7045    if (matrix) {
7046      pattern.matrix = matrix;
7047    }
7048
7049    return pattern;
7050  }
7051
7052  shadingFill(objId) {
7053    if (!this.contentVisible) {
7054      return;
7055    }
7056
7057    const ctx = this.ctx;
7058    this.save();
7059
7060    const pattern = this._getPattern(objId);
7061
7062    ctx.fillStyle = pattern.getPattern(ctx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.SHADING);
7063    const inv = ctx.mozCurrentTransformInverse;
7064
7065    if (inv) {
7066      const canvas = ctx.canvas;
7067      const width = canvas.width;
7068      const height = canvas.height;
7069
7070      const bl = _util.Util.applyTransform([0, 0], inv);
7071
7072      const br = _util.Util.applyTransform([0, height], inv);
7073
7074      const ul = _util.Util.applyTransform([width, 0], inv);
7075
7076      const ur = _util.Util.applyTransform([width, height], inv);
7077
7078      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
7079      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
7080      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
7081      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
7082      this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
7083    } else {
7084      this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10);
7085    }
7086
7087    this.compose(this.current.getClippedPathBoundingBox());
7088    this.restore();
7089  }
7090
7091  beginInlineImage() {
7092    (0, _util.unreachable)("Should not call beginInlineImage");
7093  }
7094
7095  beginImageData() {
7096    (0, _util.unreachable)("Should not call beginImageData");
7097  }
7098
7099  paintFormXObjectBegin(matrix, bbox) {
7100    if (!this.contentVisible) {
7101      return;
7102    }
7103
7104    this.save();
7105    this.baseTransformStack.push(this.baseTransform);
7106
7107    if (Array.isArray(matrix) && matrix.length === 6) {
7108      this.transform.apply(this, matrix);
7109    }
7110
7111    this.baseTransform = this.ctx.mozCurrentTransform;
7112
7113    if (bbox) {
7114      const width = bbox[2] - bbox[0];
7115      const height = bbox[3] - bbox[1];
7116      this.ctx.rect(bbox[0], bbox[1], width, height);
7117      this.current.updateRectMinMax(this.ctx.mozCurrentTransform, bbox);
7118      this.clip();
7119      this.endPath();
7120    }
7121  }
7122
7123  paintFormXObjectEnd() {
7124    if (!this.contentVisible) {
7125      return;
7126    }
7127
7128    this.restore();
7129    this.baseTransform = this.baseTransformStack.pop();
7130  }
7131
7132  beginGroup(group) {
7133    if (!this.contentVisible) {
7134      return;
7135    }
7136
7137    this.save();
7138
7139    if (this.inSMaskMode) {
7140      this.endSMaskMode();
7141      this.current.activeSMask = null;
7142    }
7143
7144    const currentCtx = this.ctx;
7145
7146    if (!group.isolated) {
7147      (0, _util.info)("TODO: Support non-isolated groups.");
7148    }
7149
7150    if (group.knockout) {
7151      (0, _util.warn)("Knockout groups not supported.");
7152    }
7153
7154    const currentTransform = currentCtx.mozCurrentTransform;
7155
7156    if (group.matrix) {
7157      currentCtx.transform.apply(currentCtx, group.matrix);
7158    }
7159
7160    if (!group.bbox) {
7161      throw new Error("Bounding box is required.");
7162    }
7163
7164    let bounds = _util.Util.getAxialAlignedBoundingBox(group.bbox, currentCtx.mozCurrentTransform);
7165
7166    const canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height];
7167    bounds = _util.Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0];
7168    const offsetX = Math.floor(bounds[0]);
7169    const offsetY = Math.floor(bounds[1]);
7170    let drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1);
7171    let drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1);
7172    let scaleX = 1,
7173        scaleY = 1;
7174
7175    if (drawnWidth > MAX_GROUP_SIZE) {
7176      scaleX = drawnWidth / MAX_GROUP_SIZE;
7177      drawnWidth = MAX_GROUP_SIZE;
7178    }
7179
7180    if (drawnHeight > MAX_GROUP_SIZE) {
7181      scaleY = drawnHeight / MAX_GROUP_SIZE;
7182      drawnHeight = MAX_GROUP_SIZE;
7183    }
7184
7185    this.current.startNewPathAndClipBox([0, 0, drawnWidth, drawnHeight]);
7186    let cacheId = "groupAt" + this.groupLevel;
7187
7188    if (group.smask) {
7189      cacheId += "_smask_" + this.smaskCounter++ % 2;
7190    }
7191
7192    const scratchCanvas = this.cachedCanvases.getCanvas(cacheId, drawnWidth, drawnHeight, true);
7193    const groupCtx = scratchCanvas.context;
7194    groupCtx.scale(1 / scaleX, 1 / scaleY);
7195    groupCtx.translate(-offsetX, -offsetY);
7196    groupCtx.transform.apply(groupCtx, currentTransform);
7197
7198    if (group.smask) {
7199      this.smaskStack.push({
7200        canvas: scratchCanvas.canvas,
7201        context: groupCtx,
7202        offsetX,
7203        offsetY,
7204        scaleX,
7205        scaleY,
7206        subtype: group.smask.subtype,
7207        backdrop: group.smask.backdrop,
7208        transferMap: group.smask.transferMap || null,
7209        startTransformInverse: null
7210      });
7211    } else {
7212      currentCtx.setTransform(1, 0, 0, 1, 0, 0);
7213      currentCtx.translate(offsetX, offsetY);
7214      currentCtx.scale(scaleX, scaleY);
7215      currentCtx.save();
7216    }
7217
7218    copyCtxState(currentCtx, groupCtx);
7219    this.ctx = groupCtx;
7220    this.setGState([["BM", "source-over"], ["ca", 1], ["CA", 1]]);
7221    this.groupStack.push(currentCtx);
7222    this.groupLevel++;
7223  }
7224
7225  endGroup(group) {
7226    if (!this.contentVisible) {
7227      return;
7228    }
7229
7230    this.groupLevel--;
7231    const groupCtx = this.ctx;
7232    const ctx = this.groupStack.pop();
7233    this.ctx = ctx;
7234    this.ctx.imageSmoothingEnabled = false;
7235
7236    if (group.smask) {
7237      this.tempSMask = this.smaskStack.pop();
7238      this.restore();
7239    } else {
7240      this.ctx.restore();
7241      const currentMtx = this.ctx.mozCurrentTransform;
7242      this.restore();
7243      this.ctx.save();
7244      this.ctx.setTransform.apply(this.ctx, currentMtx);
7245
7246      const dirtyBox = _util.Util.getAxialAlignedBoundingBox([0, 0, groupCtx.canvas.width, groupCtx.canvas.height], currentMtx);
7247
7248      this.ctx.drawImage(groupCtx.canvas, 0, 0);
7249      this.ctx.restore();
7250      this.compose(dirtyBox);
7251    }
7252  }
7253
7254  beginAnnotations() {
7255    this.save();
7256
7257    if (this.baseTransform) {
7258      this.ctx.setTransform.apply(this.ctx, this.baseTransform);
7259    }
7260  }
7261
7262  endAnnotations() {
7263    this.restore();
7264  }
7265
7266  beginAnnotation(id, rect, transform, matrix, hasOwnCanvas) {
7267    this.save();
7268
7269    if (Array.isArray(rect) && rect.length === 4) {
7270      const width = rect[2] - rect[0];
7271      const height = rect[3] - rect[1];
7272
7273      if (hasOwnCanvas && this.annotationCanvasMap) {
7274        transform = transform.slice();
7275        transform[4] -= rect[0];
7276        transform[5] -= rect[1];
7277        rect = rect.slice();
7278        rect[0] = rect[1] = 0;
7279        rect[2] = width;
7280        rect[3] = height;
7281
7282        const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale(this.ctx.mozCurrentTransform);
7283
7284        const {
7285          viewportScale
7286        } = this;
7287        const canvasWidth = Math.ceil(width * this.outputScaleX * viewportScale);
7288        const canvasHeight = Math.ceil(height * this.outputScaleY * viewportScale);
7289        this.annotationCanvas = this.canvasFactory.create(canvasWidth, canvasHeight);
7290        const {
7291          canvas,
7292          context
7293        } = this.annotationCanvas;
7294        const viewportScaleFactorStr = `var(--zoom-factor) * ${_display_utils.PixelsPerInch.PDF_TO_CSS_UNITS}`;
7295        canvas.style.width = `calc(${width}px * ${viewportScaleFactorStr})`;
7296        canvas.style.height = `calc(${height}px * ${viewportScaleFactorStr})`;
7297        this.annotationCanvasMap.set(id, canvas);
7298        this.annotationCanvas.savedCtx = this.ctx;
7299        this.ctx = context;
7300        this.ctx.setTransform(scaleX, 0, 0, -scaleY, 0, height * scaleY);
7301        addContextCurrentTransform(this.ctx);
7302        resetCtxToDefault(this.ctx, this.foregroundColor);
7303      } else {
7304        resetCtxToDefault(this.ctx, this.foregroundColor);
7305        this.ctx.rect(rect[0], rect[1], width, height);
7306        this.ctx.clip();
7307        this.endPath();
7308      }
7309    }
7310
7311    this.current = new CanvasExtraState(this.ctx.canvas.width, this.ctx.canvas.height);
7312    this.transform.apply(this, transform);
7313    this.transform.apply(this, matrix);
7314  }
7315
7316  endAnnotation() {
7317    if (this.annotationCanvas) {
7318      this.ctx = this.annotationCanvas.savedCtx;
7319      delete this.annotationCanvas.savedCtx;
7320      delete this.annotationCanvas;
7321    }
7322
7323    this.restore();
7324  }
7325
7326  paintImageMaskXObject(img) {
7327    if (!this.contentVisible) {
7328      return;
7329    }
7330
7331    const count = img.count;
7332    img = this.getObject(img.data, img);
7333    img.count = count;
7334    const ctx = this.ctx;
7335    const glyph = this.processingType3;
7336
7337    if (glyph) {
7338      if (glyph.compiled === undefined) {
7339        glyph.compiled = compileType3Glyph(img);
7340      }
7341
7342      if (glyph.compiled) {
7343        glyph.compiled(ctx);
7344        return;
7345      }
7346    }
7347
7348    const mask = this._createMaskCanvas(img);
7349
7350    const maskCanvas = mask.canvas;
7351    ctx.save();
7352    ctx.setTransform(1, 0, 0, 1, 0, 0);
7353    ctx.drawImage(maskCanvas, mask.offsetX, mask.offsetY);
7354    ctx.restore();
7355    this.compose();
7356  }
7357
7358  paintImageMaskXObjectRepeat(img, scaleX, skewX = 0, skewY = 0, scaleY, positions) {
7359    if (!this.contentVisible) {
7360      return;
7361    }
7362
7363    img = this.getObject(img.data, img);
7364    const ctx = this.ctx;
7365    ctx.save();
7366    const currentTransform = ctx.mozCurrentTransform;
7367    ctx.transform(scaleX, skewX, skewY, scaleY, 0, 0);
7368
7369    const mask = this._createMaskCanvas(img);
7370
7371    ctx.setTransform(1, 0, 0, 1, 0, 0);
7372
7373    for (let i = 0, ii = positions.length; i < ii; i += 2) {
7374      const trans = _util.Util.transform(currentTransform, [scaleX, skewX, skewY, scaleY, positions[i], positions[i + 1]]);
7375
7376      const [x, y] = _util.Util.applyTransform([0, 0], trans);
7377
7378      ctx.drawImage(mask.canvas, x, y);
7379    }
7380
7381    ctx.restore();
7382    this.compose();
7383  }
7384
7385  paintImageMaskXObjectGroup(images) {
7386    if (!this.contentVisible) {
7387      return;
7388    }
7389
7390    const ctx = this.ctx;
7391    const fillColor = this.current.fillColor;
7392    const isPatternFill = this.current.patternFill;
7393
7394    for (let i = 0, ii = images.length; i < ii; i++) {
7395      const image = images[i];
7396      const width = image.width,
7397            height = image.height;
7398      const maskCanvas = this.cachedCanvases.getCanvas("maskCanvas", width, height, false);
7399      const maskCtx = maskCanvas.context;
7400      maskCtx.save();
7401      putBinaryImageMask(maskCtx, image);
7402      maskCtx.globalCompositeOperation = "source-in";
7403      maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this, ctx.mozCurrentTransformInverse, _pattern_helper.PathType.FILL) : fillColor;
7404      maskCtx.fillRect(0, 0, width, height);
7405      maskCtx.restore();
7406      ctx.save();
7407      ctx.transform.apply(ctx, image.transform);
7408      ctx.scale(1, -1);
7409      drawImageAtIntegerCoords(ctx, maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1);
7410      ctx.restore();
7411    }
7412
7413    this.compose();
7414  }
7415
7416  paintImageXObject(objId) {
7417    if (!this.contentVisible) {
7418      return;
7419    }
7420
7421    const imgData = this.getObject(objId);
7422
7423    if (!imgData) {
7424      (0, _util.warn)("Dependent image isn't ready yet");
7425      return;
7426    }
7427
7428    this.paintInlineImageXObject(imgData);
7429  }
7430
7431  paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
7432    if (!this.contentVisible) {
7433      return;
7434    }
7435
7436    const imgData = this.getObject(objId);
7437
7438    if (!imgData) {
7439      (0, _util.warn)("Dependent image isn't ready yet");
7440      return;
7441    }
7442
7443    const width = imgData.width;
7444    const height = imgData.height;
7445    const map = [];
7446
7447    for (let i = 0, ii = positions.length; i < ii; i += 2) {
7448      map.push({
7449        transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]],
7450        x: 0,
7451        y: 0,
7452        w: width,
7453        h: height
7454      });
7455    }
7456
7457    this.paintInlineImageXObjectGroup(imgData, map);
7458  }
7459
7460  paintInlineImageXObject(imgData) {
7461    if (!this.contentVisible) {
7462      return;
7463    }
7464
7465    const width = imgData.width;
7466    const height = imgData.height;
7467    const ctx = this.ctx;
7468    this.save();
7469    ctx.scale(1 / width, -1 / height);
7470    let imgToPaint;
7471
7472    if (typeof HTMLElement === "function" && imgData instanceof HTMLElement || !imgData.data) {
7473      imgToPaint = imgData;
7474    } else {
7475      const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", width, height, false);
7476      const tmpCtx = tmpCanvas.context;
7477      putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
7478      imgToPaint = tmpCanvas.canvas;
7479    }
7480
7481    const scaled = this._scaleImage(imgToPaint, ctx.mozCurrentTransformInverse);
7482
7483    ctx.imageSmoothingEnabled = getImageSmoothingEnabled(ctx.mozCurrentTransform, imgData.interpolate);
7484    const [rWidth, rHeight] = drawImageAtIntegerCoords(ctx, scaled.img, 0, 0, scaled.paintWidth, scaled.paintHeight, 0, -height, width, height);
7485
7486    if (this.imageLayer) {
7487      const position = this.getCanvasPosition(0, -height);
7488      this.imageLayer.appendImage({
7489        imgData,
7490        left: position[0],
7491        top: position[1],
7492        width: rWidth,
7493        height: rHeight
7494      });
7495    }
7496
7497    this.compose();
7498    this.restore();
7499  }
7500
7501  paintInlineImageXObjectGroup(imgData, map) {
7502    if (!this.contentVisible) {
7503      return;
7504    }
7505
7506    const ctx = this.ctx;
7507    const w = imgData.width;
7508    const h = imgData.height;
7509    const tmpCanvas = this.cachedCanvases.getCanvas("inlineImage", w, h, false);
7510    const tmpCtx = tmpCanvas.context;
7511    putBinaryImageData(tmpCtx, imgData, this.current.transferMaps);
7512
7513    for (let i = 0, ii = map.length; i < ii; i++) {
7514      const entry = map[i];
7515      ctx.save();
7516      ctx.transform.apply(ctx, entry.transform);
7517      ctx.scale(1, -1);
7518      drawImageAtIntegerCoords(ctx, tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1);
7519
7520      if (this.imageLayer) {
7521        const position = this.getCanvasPosition(entry.x, entry.y);
7522        this.imageLayer.appendImage({
7523          imgData,
7524          left: position[0],
7525          top: position[1],
7526          width: w,
7527          height: h
7528        });
7529      }
7530
7531      ctx.restore();
7532    }
7533
7534    this.compose();
7535  }
7536
7537  paintSolidColorImageMask() {
7538    if (!this.contentVisible) {
7539      return;
7540    }
7541
7542    this.ctx.fillRect(0, 0, 1, 1);
7543    this.compose();
7544  }
7545
7546  markPoint(tag) {}
7547
7548  markPointProps(tag, properties) {}
7549
7550  beginMarkedContent(tag) {
7551    this.markedContentStack.push({
7552      visible: true
7553    });
7554  }
7555
7556  beginMarkedContentProps(tag, properties) {
7557    if (tag === "OC") {
7558      this.markedContentStack.push({
7559        visible: this.optionalContentConfig.isVisible(properties)
7560      });
7561    } else {
7562      this.markedContentStack.push({
7563        visible: true
7564      });
7565    }
7566
7567    this.contentVisible = this.isContentVisible();
7568  }
7569
7570  endMarkedContent() {
7571    this.markedContentStack.pop();
7572    this.contentVisible = this.isContentVisible();
7573  }
7574
7575  beginCompat() {}
7576
7577  endCompat() {}
7578
7579  consumePath(clipBox) {
7580    const isEmpty = this.current.isEmptyClip();
7581
7582    if (this.pendingClip) {
7583      this.current.updateClipFromPath();
7584    }
7585
7586    if (!this.pendingClip) {
7587      this.compose(clipBox);
7588    }
7589
7590    const ctx = this.ctx;
7591
7592    if (this.pendingClip) {
7593      if (!isEmpty) {
7594        if (this.pendingClip === EO_CLIP) {
7595          ctx.clip("evenodd");
7596        } else {
7597          ctx.clip();
7598        }
7599      }
7600
7601      this.pendingClip = null;
7602    }
7603
7604    this.current.startNewPathAndClipBox(this.current.clipBox);
7605    ctx.beginPath();
7606  }
7607
7608  getSinglePixelWidth() {
7609    if (!this._cachedGetSinglePixelWidth) {
7610      const m = this.ctx.mozCurrentTransform;
7611
7612      if (m[1] === 0 && m[2] === 0) {
7613        this._cachedGetSinglePixelWidth = 1 / Math.min(Math.abs(m[0]), Math.abs(m[3]));
7614      } else {
7615        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7616        const normX = Math.hypot(m[0], m[2]);
7617        const normY = Math.hypot(m[1], m[3]);
7618        this._cachedGetSinglePixelWidth = Math.max(normX, normY) / absDet;
7619      }
7620    }
7621
7622    return this._cachedGetSinglePixelWidth;
7623  }
7624
7625  getScaleForStroking() {
7626    if (!this._cachedScaleForStroking) {
7627      const {
7628        lineWidth
7629      } = this.current;
7630      const m = this.ctx.mozCurrentTransform;
7631      let scaleX, scaleY;
7632
7633      if (m[1] === 0 && m[2] === 0) {
7634        const normX = Math.abs(m[0]);
7635        const normY = Math.abs(m[3]);
7636
7637        if (lineWidth === 0) {
7638          scaleX = 1 / normX;
7639          scaleY = 1 / normY;
7640        } else {
7641          const scaledXLineWidth = normX * lineWidth;
7642          const scaledYLineWidth = normY * lineWidth;
7643          scaleX = scaledXLineWidth < 1 ? 1 / scaledXLineWidth : 1;
7644          scaleY = scaledYLineWidth < 1 ? 1 / scaledYLineWidth : 1;
7645        }
7646      } else {
7647        const absDet = Math.abs(m[0] * m[3] - m[2] * m[1]);
7648        const normX = Math.hypot(m[0], m[1]);
7649        const normY = Math.hypot(m[2], m[3]);
7650
7651        if (lineWidth === 0) {
7652          scaleX = normY / absDet;
7653          scaleY = normX / absDet;
7654        } else {
7655          const baseArea = lineWidth * absDet;
7656          scaleX = normY > baseArea ? normY / baseArea : 1;
7657          scaleY = normX > baseArea ? normX / baseArea : 1;
7658        }
7659      }
7660
7661      this._cachedScaleForStroking = [scaleX, scaleY];
7662    }
7663
7664    return this._cachedScaleForStroking;
7665  }
7666
7667  rescaleAndStroke(saveRestore) {
7668    const {
7669      ctx
7670    } = this;
7671    const {
7672      lineWidth
7673    } = this.current;
7674    const [scaleX, scaleY] = this.getScaleForStroking();
7675    ctx.lineWidth = lineWidth || 1;
7676
7677    if (scaleX === 1 && scaleY === 1) {
7678      ctx.stroke();
7679      return;
7680    }
7681
7682    let savedMatrix, savedDashes, savedDashOffset;
7683
7684    if (saveRestore) {
7685      savedMatrix = ctx.mozCurrentTransform.slice();
7686      savedDashes = ctx.getLineDash().slice();
7687      savedDashOffset = ctx.lineDashOffset;
7688    }
7689
7690    ctx.scale(scaleX, scaleY);
7691    const scale = Math.max(scaleX, scaleY);
7692    ctx.setLineDash(ctx.getLineDash().map(x => x / scale));
7693    ctx.lineDashOffset /= scale;
7694    ctx.stroke();
7695
7696    if (saveRestore) {
7697      ctx.setTransform(...savedMatrix);
7698      ctx.setLineDash(savedDashes);
7699      ctx.lineDashOffset = savedDashOffset;
7700    }
7701  }
7702
7703  getCanvasPosition(x, y) {
7704    const transform = this.ctx.mozCurrentTransform;
7705    return [transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5]];
7706  }
7707
7708  isContentVisible() {
7709    for (let i = this.markedContentStack.length - 1; i >= 0; i--) {
7710      if (!this.markedContentStack[i].visible) {
7711        return false;
7712      }
7713    }
7714
7715    return true;
7716  }
7717
7718}
7719
7720exports.CanvasGraphics = CanvasGraphics;
7721
7722for (const op in _util.OPS) {
7723  if (CanvasGraphics.prototype[op] !== undefined) {
7724    CanvasGraphics.prototype[_util.OPS[op]] = CanvasGraphics.prototype[op];
7725  }
7726}
7727
7728/***/ }),
7729/* 11 */
7730/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
7731
7732
7733
7734Object.defineProperty(exports, "__esModule", ({
7735  value: true
7736}));
7737exports.TilingPattern = exports.PathType = void 0;
7738exports.getShadingPattern = getShadingPattern;
7739
7740var _util = __w_pdfjs_require__(1);
7741
7742var _is_node = __w_pdfjs_require__(3);
7743
7744const PathType = {
7745  FILL: "Fill",
7746  STROKE: "Stroke",
7747  SHADING: "Shading"
7748};
7749exports.PathType = PathType;
7750
7751function applyBoundingBox(ctx, bbox) {
7752  if (!bbox || _is_node.isNodeJS) {
7753    return;
7754  }
7755
7756  const width = bbox[2] - bbox[0];
7757  const height = bbox[3] - bbox[1];
7758  const region = new Path2D();
7759  region.rect(bbox[0], bbox[1], width, height);
7760  ctx.clip(region);
7761}
7762
7763class BaseShadingPattern {
7764  constructor() {
7765    if (this.constructor === BaseShadingPattern) {
7766      (0, _util.unreachable)("Cannot initialize BaseShadingPattern.");
7767    }
7768  }
7769
7770  getPattern() {
7771    (0, _util.unreachable)("Abstract method `getPattern` called.");
7772  }
7773
7774}
7775
7776class RadialAxialShadingPattern extends BaseShadingPattern {
7777  constructor(IR) {
7778    super();
7779    this._type = IR[1];
7780    this._bbox = IR[2];
7781    this._colorStops = IR[3];
7782    this._p0 = IR[4];
7783    this._p1 = IR[5];
7784    this._r0 = IR[6];
7785    this._r1 = IR[7];
7786    this.matrix = null;
7787  }
7788
7789  _createGradient(ctx) {
7790    let grad;
7791
7792    if (this._type === "axial") {
7793      grad = ctx.createLinearGradient(this._p0[0], this._p0[1], this._p1[0], this._p1[1]);
7794    } else if (this._type === "radial") {
7795      grad = ctx.createRadialGradient(this._p0[0], this._p0[1], this._r0, this._p1[0], this._p1[1], this._r1);
7796    }
7797
7798    for (const colorStop of this._colorStops) {
7799      grad.addColorStop(colorStop[0], colorStop[1]);
7800    }
7801
7802    return grad;
7803  }
7804
7805  getPattern(ctx, owner, inverse, pathType) {
7806    let pattern;
7807
7808    if (pathType === PathType.STROKE || pathType === PathType.FILL) {
7809      const ownerBBox = owner.current.getClippedPathBoundingBox(pathType, ctx.mozCurrentTransform) || [0, 0, 0, 0];
7810      const width = Math.ceil(ownerBBox[2] - ownerBBox[0]) || 1;
7811      const height = Math.ceil(ownerBBox[3] - ownerBBox[1]) || 1;
7812      const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", width, height, true);
7813      const tmpCtx = tmpCanvas.context;
7814      tmpCtx.clearRect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7815      tmpCtx.beginPath();
7816      tmpCtx.rect(0, 0, tmpCtx.canvas.width, tmpCtx.canvas.height);
7817      tmpCtx.translate(-ownerBBox[0], -ownerBBox[1]);
7818      inverse = _util.Util.transform(inverse, [1, 0, 0, 1, ownerBBox[0], ownerBBox[1]]);
7819      tmpCtx.transform.apply(tmpCtx, owner.baseTransform);
7820
7821      if (this.matrix) {
7822        tmpCtx.transform.apply(tmpCtx, this.matrix);
7823      }
7824
7825      applyBoundingBox(tmpCtx, this._bbox);
7826      tmpCtx.fillStyle = this._createGradient(tmpCtx);
7827      tmpCtx.fill();
7828      pattern = ctx.createPattern(tmpCanvas.canvas, "no-repeat");
7829      const domMatrix = new DOMMatrix(inverse);
7830
vendor: 4,609 bytes, lines 7831-8023
7831      try {
7832        pattern.setTransform(domMatrix);
7833      } catch (ex) {
7834        (0, _util.warn)(`RadialAxialShadingPattern.getPattern: "${ex?.message}".`);
7835      }
7836    } else {
7837      applyBoundingBox(ctx, this._bbox);
7838      pattern = this._createGradient(ctx);
7839    }
7840
7841    return pattern;
7842  }
7843
7844}
7845
7846function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) {
7847  const coords = context.coords,
7848        colors = context.colors;
7849  const bytes = data.data,
7850        rowSize = data.width * 4;
7851  let tmp;
7852
7853  if (coords[p1 + 1] > coords[p2 + 1]) {
7854    tmp = p1;
7855    p1 = p2;
7856    p2 = tmp;
7857    tmp = c1;
7858    c1 = c2;
7859    c2 = tmp;
7860  }
7861
7862  if (coords[p2 + 1] > coords[p3 + 1]) {
7863    tmp = p2;
7864    p2 = p3;
7865    p3 = tmp;
7866    tmp = c2;
7867    c2 = c3;
7868    c3 = tmp;
7869  }
7870
7871  if (coords[p1 + 1] > coords[p2 + 1]) {
7872    tmp = p1;
7873    p1 = p2;
7874    p2 = tmp;
7875    tmp = c1;
7876    c1 = c2;
7877    c2 = tmp;
7878  }
7879
7880  const x1 = (coords[p1] + context.offsetX) * context.scaleX;
7881  const y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY;
7882  const x2 = (coords[p2] + context.offsetX) * context.scaleX;
7883  const y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY;
7884  const x3 = (coords[p3] + context.offsetX) * context.scaleX;
7885  const y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY;
7886
7887  if (y1 >= y3) {
7888    return;
7889  }
7890
7891  const c1r = colors[c1],
7892        c1g = colors[c1 + 1],
7893        c1b = colors[c1 + 2];
7894  const c2r = colors[c2],
7895        c2g = colors[c2 + 1],
7896        c2b = colors[c2 + 2];
7897  const c3r = colors[c3],
7898        c3g = colors[c3 + 1],
7899        c3b = colors[c3 + 2];
7900  const minY = Math.round(y1),
7901        maxY = Math.round(y3);
7902  let xa, car, cag, cab;
7903  let xb, cbr, cbg, cbb;
7904
7905  for (let y = minY; y <= maxY; y++) {
7906    if (y < y2) {
7907      let k;
7908
7909      if (y < y1) {
7910        k = 0;
7911      } else {
7912        k = (y1 - y) / (y1 - y2);
7913      }
7914
7915      xa = x1 - (x1 - x2) * k;
7916      car = c1r - (c1r - c2r) * k;
7917      cag = c1g - (c1g - c2g) * k;
7918      cab = c1b - (c1b - c2b) * k;
7919    } else {
7920      let k;
7921
7922      if (y > y3) {
7923        k = 1;
7924      } else if (y2 === y3) {
7925        k = 0;
7926      } else {
7927        k = (y2 - y) / (y2 - y3);
7928      }
7929
7930      xa = x2 - (x2 - x3) * k;
7931      car = c2r - (c2r - c3r) * k;
7932      cag = c2g - (c2g - c3g) * k;
7933      cab = c2b - (c2b - c3b) * k;
7934    }
7935
7936    let k;
7937
7938    if (y < y1) {
7939      k = 0;
7940    } else if (y > y3) {
7941      k = 1;
7942    } else {
7943      k = (y1 - y) / (y1 - y3);
7944    }
7945
7946    xb = x1 - (x1 - x3) * k;
7947    cbr = c1r - (c1r - c3r) * k;
7948    cbg = c1g - (c1g - c3g) * k;
7949    cbb = c1b - (c1b - c3b) * k;
7950    const x1_ = Math.round(Math.min(xa, xb));
7951    const x2_ = Math.round(Math.max(xa, xb));
7952    let j = rowSize * y + x1_ * 4;
7953
7954    for (let x = x1_; x <= x2_; x++) {
7955      k = (xa - x) / (xa - xb);
7956
7957      if (k < 0) {
7958        k = 0;
7959      } else if (k > 1) {
7960        k = 1;
7961      }
7962
7963      bytes[j++] = car - (car - cbr) * k | 0;
7964      bytes[j++] = cag - (cag - cbg) * k | 0;
7965      bytes[j++] = cab - (cab - cbb) * k | 0;
7966      bytes[j++] = 255;
7967    }
7968  }
7969}
7970
7971function drawFigure(data, figure, context) {
7972  const ps = figure.coords;
7973  const cs = figure.colors;
7974  let i, ii;
7975
7976  switch (figure.type) {
7977    case "lattice":
7978      const verticesPerRow = figure.verticesPerRow;
7979      const rows = Math.floor(ps.length / verticesPerRow) - 1;
7980      const cols = verticesPerRow - 1;
7981
7982      for (i = 0; i < rows; i++) {
7983        let q = i * verticesPerRow;
7984
7985        for (let j = 0; j < cols; j++, q++) {
7986          drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]);
7987          drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]);
7988        }
7989      }
7990
7991      break;
7992
7993    case "triangles":
7994      for (i = 0, ii = ps.length; i < ii; i += 3) {
7995        drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]);
7996      }
7997
7998      break;
7999
8000    default:
8001      throw new Error("illegal figure");
8002  }
8003}
8004
8005class MeshShadingPattern extends BaseShadingPattern {
8006  constructor(IR) {
8007    super();
8008    this._coords = IR[2];
8009    this._colors = IR[3];
8010    this._figures = IR[4];
8011    this._bounds = IR[5];
8012    this._bbox = IR[7];
8013    this._background = IR[8];
8014    this.matrix = null;
8015  }
8016
8017  _createMeshCanvas(combinedScale, backgroundColor, cachedCanvases) {
8018    const EXPECTED_SCALE = 1.1;
8019    const MAX_PATTERN_SIZE = 3000;
8020    const BORDER_SIZE = 2;
8021    const offsetX = Math.floor(this._bounds[0]);
8022    const offsetY = Math.floor(this._bounds[1]);
8023    const boundsWidth = Math.ceil(this._bounds[2]) - offsetX;
8024    const boundsHeight = Math.ceil(this._bounds[3]) - offsetY;
8025    const width = Math.min(Math.ceil(Math.abs(boundsWidth * combinedScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
8026    const height = Math.min(Math.ceil(Math.abs(boundsHeight * combinedScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE);
8027    const scaleX = boundsWidth / width;
8028    const scaleY = boundsHeight / height;
8029    const context = {
8030      coords: this._coords,
8031      colors: this._colors,
8032      offsetX: -offsetX,
8033      offsetY: -offsetY,
8034      scaleX: 1 / scaleX,
8035      scaleY: 1 / scaleY
8036    };
8037    const paddedWidth = width + BORDER_SIZE * 2;
8038    const paddedHeight = height + BORDER_SIZE * 2;
8039    const tmpCanvas = cachedCanvases.getCanvas("mesh", paddedWidth, paddedHeight, false);
8040    const tmpCtx = tmpCanvas.context;
8041    const data = tmpCtx.createImageData(width, height);
8042
8043    if (backgroundColor) {
8044      const bytes = data.data;
8045
8046      for (let i = 0, ii = bytes.length; i < ii; i += 4) {
8047        bytes[i] = backgroundColor[0];
8048        bytes[i + 1] = backgroundColor[1];
8049        bytes[i + 2] = backgroundColor[2];
8050        bytes[i + 3] = 255;
8051      }
8052    }
8053
8054    for (const figure of this._figures) {
8055      drawFigure(data, figure, context);
8056    }
8057
8058    tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE);
8059    const canvas = tmpCanvas.canvas;
8060    return {
8061      canvas,
8062      offsetX: offsetX - BORDER_SIZE * scaleX,
8063      offsetY: offsetY - BORDER_SIZE * scaleY,
8064      scaleX,
8065      scaleY
8066    };
8067  }
8068
8069  getPattern(ctx, owner, inverse, pathType) {
8070    applyBoundingBox(ctx, this._bbox);
8071    let scale;
8072
8073    if (pathType === PathType.SHADING) {
8074      scale = _util.Util.singularValueDecompose2dScale(ctx.mozCurrentTransform);
8075    } else {
8076      scale = _util.Util.singularValueDecompose2dScale(owner.baseTransform);
8077
8078      if (this.matrix) {
8079        const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
8080
8081        scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]];
8082      }
8083    }
8084
8085    const temporaryPatternCanvas = this._createMeshCanvas(scale, pathType === PathType.SHADING ? null : this._background, owner.cachedCanvases);
8086
8087    if (pathType !== PathType.SHADING) {
8088      ctx.setTransform.apply(ctx, owner.baseTransform);
8089
8090      if (this.matrix) {
8091        ctx.transform.apply(ctx, this.matrix);
8092      }
8093    }
8094
8095    ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
8096    ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY);
8097    return ctx.createPattern(temporaryPatternCanvas.canvas, "no-repeat");
8098  }
8099
8100}
8101
8102class DummyShadingPattern extends BaseShadingPattern {
8103  getPattern() {
8104    return "hotpink";
8105  }
8106
8107}
8108
8109function getShadingPattern(IR) {
8110  switch (IR[0]) {
8111    case "RadialAxial":
8112      return new RadialAxialShadingPattern(IR);
8113
8114    case "Mesh":
8115      return new MeshShadingPattern(IR);
8116
8117    case "Dummy":
8118      return new DummyShadingPattern();
8119  }
8120
8121  throw new Error(`Unknown IR type: ${IR[0]}`);
8122}
8123
8124const PaintType = {
8125  COLORED: 1,
8126  UNCOLORED: 2
8127};
8128
8129class TilingPattern {
8130  static get MAX_PATTERN_SIZE() {
8131    return (0, _util.shadow)(this, "MAX_PATTERN_SIZE", 3000);
8132  }
8133
8134  constructor(IR, color, ctx, canvasGraphicsFactory, baseTransform) {
8135    this.operatorList = IR[2];
8136    this.matrix = IR[3] || [1, 0, 0, 1, 0, 0];
8137    this.bbox = IR[4];
8138    this.xstep = IR[5];
8139    this.ystep = IR[6];
8140    this.paintType = IR[7];
8141    this.tilingType = IR[8];
8142    this.color = color;
8143    this.ctx = ctx;
8144    this.canvasGraphicsFactory = canvasGraphicsFactory;
8145    this.baseTransform = baseTransform;
8146  }
8147
8148  createPatternCanvas(owner) {
8149    const operatorList = this.operatorList;
8150    const bbox = this.bbox;
8151    const xstep = this.xstep;
8152    const ystep = this.ystep;
8153    const paintType = this.paintType;
8154    const tilingType = this.tilingType;
8155    const color = this.color;
8156    const canvasGraphicsFactory = this.canvasGraphicsFactory;
8157    (0, _util.info)("TilingType: " + tilingType);
8158    const x0 = bbox[0],
8159          y0 = bbox[1],
8160          x1 = bbox[2],
8161          y1 = bbox[3];
8162
8163    const matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix
8163);
8164
8165    const curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
8166
8167    const combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
8168    const dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
8169    const dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
8170    const tmpCanvas = owner.cachedCanvases.getCanvas("pattern", dimx.size, dimy.size, true);
8171    const tmpCtx = tmpCanvas.context;
8172    const graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
8173    graphics.groupLevel = owner.groupLevel;
8174    this.setFillAndStrokeStyleToContext(graphics, paintType, color);
8175    let adjustedX0 = x0;
8176    let adjustedY0 = y0;
8177    let adjustedX1 = x1;
8178    let adjustedY1 = y1;
8179
8180    if (x0 < 0) {
8181      adjustedX0 = 0;
8182      adjustedX1 += Math.abs(x0);
8183    }
8184
8185    if (y0 < 0) {
8186      adjustedY0 = 0;
8187      adjustedY1 += Math.abs(y0);
8188    }
8189
8190    tmpCtx.translate(-(dimx.scale * adjustedX0), -(dimy.scale * adjustedY0));
8191    graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
8192    tmpCtx.save();
8193    this.clipBbox(graphics, adjustedX0, adjustedY0, adjustedX1, adjustedY1);
8194    graphics.baseTransform = graphics.ctx.mozCurrentTransform.slice();
8195    graphics.executeOperatorList(operatorList);
8196    graphics.endDrawing();
8197    return {
8198      canvas: tmpCanvas.canvas,
8199      scaleX: dimx.scale,
8200      scaleY: dimy.scale,
8201      offsetX: adjustedX0,
8202      offsetY: adjustedY0
8203    };
8204  }
8205
8206  getSizeAndScale(step, realOutputSize, scale) {
8207    step = Math.abs(step);
8208    const maxSize = Math.max(TilingPattern.MAX_PATTERN_SIZE, realOutputSize);
8209    let size = Math.ceil(step * scale);
8210
8211    if (size >= maxSize) {
8212      size = maxSize;
8213    } else {
8214      scale = size / step;
8215    }
8216
8217    return {
8218      scale,
8219      size
8220    };
8221  }
8222
8223  clipBbox(graphics, x0, y0, x1, y1) {
8224    const bboxWidth = x1 - x0;
8225    const bboxHeight = y1 - y0;
8226    graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight);
8227    graphics.current.updateRectMinMax(graphics.ctx.mozCurrentTransform, [x0, y0, x1, y1]);
8228    graphics.clip();
8229    graphics.endPath();
8230  }
8231
8232  setFillAndStrokeStyleToContext(graphics, paintType, color) {
8233    const context = graphics.ctx,
8234          current = graphics.current;
8235
8236    switch (paintType) {
8237      case PaintType.COLORED:
8238        const ctx = this.ctx;
8239        context.fillStyle = ctx.fillStyle;
8240        context.strokeStyle = ctx.strokeStyle;
8241        current.fillColor = ctx.fillStyle;
8242        current.strokeColor = ctx.strokeStyle;
8243        break;
8244
8245      case PaintType.UNCOLORED:
8246        const cssColor = _util.Util.makeHexColor(color[0], color[1], color[2]);
8247
8248        context.fillStyle = cssColor;
8249        context.strokeStyle = cssColor;
8250        current.fillColor = cssColor;
8251        current.strokeColor = cssColor;
8252        break;
8253
8254      default:
8255        throw new _util.FormatError(`Unsupported paint type: ${paintType}`);
8256    }
8257  }
8258
8259  getPattern(ctx, owner, inverse, pathType) {
8260    let matrix = inverse;
8261
8262    if (pathType !== PathType.SHADING) {
8263      matrix = _util.Util.transform(matrix, owner.baseTransform);
8264
8265      if (this.matrix) {
8266        matrix = _util.Util.transform(matrix, this.matrix);
8267      }
8268    }
8269
8270    const temporaryPatternCanvas = this.createPatternCanvas(owner);
8271    let domMatrix = new DOMMatrix(matrix);
8272    domMatrix = domMatrix.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY);
8273    domMatrix = domMatrix.scale(1 / temporaryPatternCanvas.scaleX, 1 / temporaryPatternCanvas.scaleY);
8274    const pattern = ctx.createPattern(temporaryPatternCanvas.canvas, "repeat");
8275
8276    try {
8277      pattern.setTransform(domMatrix);
8278    } catch (ex) {
8279      (0, _util.warn)(`TilingPattern.getPattern: "${ex?.message}".`);
8280    }
8281
8282    return pattern;
8283  }
8284
8285}
8286
8287exports.TilingPattern = TilingPattern;
8288
8289/***/ }),
8290/* 12 */
8291/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8292
8293
8294
8295Object.defineProperty(exports, "__esModule", ({
8296  value: true
8297}));
8298exports.applyMaskImageData = applyMaskImageData;
8299
8300var _util = __w_pdfjs_require__(1);
8301
8302function applyMaskImageData({
8303  src,
8304  srcPos = 0,
8305  dest,
8306  destPos = 0,
8307  width,
8308  height,
8309  inverseDecode = false
8310}) {
8311  const opaque = _util.FeatureTest.isLittleEndian ? 0xff000000 : 0x000000ff;
8312  const [zeroMapping, oneMapping] = !inverseDecode ? [opaque, 0] : [0, opaque];
8313  const widthInSource = width >> 3;
8314  const widthRemainder = width & 7;
8315  const srcLength = src.length;
8316  dest = new Uint32Array(dest.buffer);
8317
8318  for (let i = 0; i < height; i++) {
8319    for (const max = srcPos + widthInSource; srcPos < max; srcPos++) {
8320      const elem = srcPos < srcLength ? src[srcPos] : 255;
8321      dest[destPos++] = elem & 0b10000000 ? oneMapping : zeroMapping;
8322      dest[destPos++] = elem & 0b1000000 ? oneMapping : zeroMapping;
8323      dest[destPos++] = elem & 0b100000 ? oneMapping : zeroMapping;
8324      dest[destPos++] = elem & 0b10000 ? oneMapping : zeroMapping;
8325      dest[destPos++] = elem & 0b1000 ? oneMapping : zeroMapping;
8326      dest[destPos++] = elem & 0b100 ? oneMapping : zeroMapping;
8327      dest[destPos++] = elem & 0b10 ? oneMapping : zeroMapping;
8328      dest[destPos++] = elem & 0b1 ? oneMapping : zeroMapping;
8329    }
8330
8331    if (widthRemainder === 0) {
8332      continue;
8333    }
8334
8335    const elem = srcPos < srcLength ? src[srcPos++] : 255;
8336
8337    for (let j = 0; j < widthRemainder; j++) {
8338      dest[destPos++] = elem & 1 << 7 - j ? oneMapping : zeroMapping;
8339    }
8340  }
8341
8342  return {
8343    srcPos,
8344    destPos
8345  };
8346}
8347
8348/***/ }),
8349/* 13 */
vendor: 15,150 bytes, lines 8350-8937
8350/***/ ((__unused_webpack_module, exports) => {
8351
8352
8353
8354Object.defineProperty(exports, "__esModule", ({
8355  value: true
8356}));
8357exports.GlobalWorkerOptions = void 0;
8358const GlobalWorkerOptions = Object.create(null);
8359exports.GlobalWorkerOptions = GlobalWorkerOptions;
8360GlobalWorkerOptions.workerPort = GlobalWorkerOptions.workerPort === undefined ? null : GlobalWorkerOptions.workerPort;
8361GlobalWorkerOptions.workerSrc = GlobalWorkerOptions.workerSrc === undefined ? "" : GlobalWorkerOptions.workerSrc;
8362
8363/***/ }),
8364/* 14 */
8365/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8366
8367
8368
8369Object.defineProperty(exports, "__esModule", ({
8370  value: true
8371}));
8372exports.MessageHandler = void 0;
8373
8374var _util = __w_pdfjs_require__(1);
8375
8376const CallbackKind = {
8377  UNKNOWN: 0,
8378  DATA: 1,
8379  ERROR: 2
8380};
8381const StreamKind = {
8382  UNKNOWN: 0,
8383  CANCEL: 1,
8384  CANCEL_COMPLETE: 2,
8385  CLOSE: 3,
8386  ENQUEUE: 4,
8387  ERROR: 5,
8388  PULL: 6,
8389  PULL_COMPLETE: 7,
8390  START_COMPLETE: 8
8391};
8392
8393function wrapReason(reason) {
8394  if (!(reason instanceof Error || typeof reason === "object" && reason !== null)) {
8395    (0, _util.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.');
8396  }
8397
8398  switch (reason.name) {
8399    case "AbortException":
8400      return new _util.AbortException(reason.message);
8401
8402    case "MissingPDFException":
8403      return new _util.MissingPDFException(reason.message);
8404
8405    case "PasswordException":
8406      return new _util.PasswordException(reason.message, reason.code);
8407
8408    case "UnexpectedResponseException":
8409      return new _util.UnexpectedResponseException(reason.message, reason.status);
8410
8411    case "UnknownErrorException":
8412      return new _util.UnknownErrorException(reason.message, reason.details);
8413
8414    default:
8415      return new _util.UnknownErrorException(reason.message, reason.toString());
8416  }
8417}
8418
8419class MessageHandler {
8420  constructor(sourceName, targetName, comObj) {
8421    this.sourceName = sourceName;
8422    this.targetName = targetName;
8423    this.comObj = comObj;
8424    this.callbackId = 1;
8425    this.streamId = 1;
8426    this.streamSinks = Object.create(null);
8427    this.streamControllers = Object.create(null);
8428    this.callbackCapabilities = Object.create(null);
8429    this.actionHandler = Object.create(null);
8430
8431    this._onComObjOnMessage = event => {
8432      const data = event.data;
8433
8434      if (data.targetName !== this.sourceName) {
8435        return;
8436      }
8437
8438      if (data.stream) {
8439        this._processStreamMessage(data);
8440
8441        return;
8442      }
8443
8444      if (data.callback) {
8445        const callbackId = data.callbackId;
8446        const capability = this.callbackCapabilities[callbackId];
8447
8448        if (!capability) {
8449          throw new Error(`Cannot resolve callback ${callbackId}`);
8450        }
8451
8452        delete this.callbackCapabilities[callbackId];
8453
8454        if (data.callback === CallbackKind.DATA) {
8455          capability.resolve(data.data);
8456        } else if (data.callback === CallbackKind.ERROR) {
8457          capability.reject(wrapReason(data.reason));
8458        } else {
8459          throw new Error("Unexpected callback case");
8460        }
8461
8462        return;
8463      }
8464
8465      const action = this.actionHandler[data.action];
8466
8467      if (!action) {
8468        throw new Error(`Unknown action from worker: ${data.action}`);
8469      }
8470
8471      if (data.callbackId) {
8472        const cbSourceName = this.sourceName;
8473        const cbTargetName = data.sourceName;
8474        new Promise(function (resolve) {
8475          resolve(action(data.data));
8476        }).then(function (result) {
8477          comObj.postMessage({
8478            sourceName: cbSourceName,
8479            targetName: cbTargetName,
8480            callback: CallbackKind.DATA,
8481            callbackId: data.callbackId,
8482            data: result
8483          });
8484        }, function (reason) {
8485          comObj.postMessage({
8486            sourceName: cbSourceName,
8487            targetName: cbTargetName,
8488            callback: CallbackKind.ERROR,
8489            callbackId: data.callbackId,
8490            reason: wrapReason(reason)
8491          });
8492        });
8493        return;
8494      }
8495
8496      if (data.streamId) {
8497        this._createStreamSink(data);
8498
8499        return;
8500      }
8501
8502      action(data.data);
8503    };
8504
8505    comObj.addEventListener("message", this._onComObjOnMessage);
8506  }
8507
8508  on(actionName, handler) {
8509    const ah = this.actionHandler;
8510
8511    if (ah[actionName]) {
8512      throw new Error(`There is already an actionName called "${actionName}"`);
8513    }
8514
8515    ah[actionName] = handler;
8516  }
8517
8518  send(actionName, data, transfers) {
8519    this.comObj.postMessage({
8520      sourceName: this.sourceName,
8521      targetName: this.targetName,
8522      action: actionName,
8523      data
8524    }, transfers);
8525  }
8526
8527  sendWithPromise(actionName, data, transfers) {
8528    const callbackId = this.callbackId++;
8529    const capability = (0, _util.createPromiseCapability)();
8530    this.callbackCapabilities[callbackId] = capability;
8531
8532    try {
8533      this.comObj.postMessage({
8534        sourceName: this.sourceName,
8535        targetName: this.targetName,
8536        action: actionName,
8537        callbackId,
8538        data
8539      }, transfers);
8540    } catch (ex) {
8541      capability.reject(ex);
8542    }
8543
8544    return capability.promise;
8545  }
8546
8547  sendWithStream(actionName, data, queueingStrategy, transfers) {
8548    const streamId = this.streamId++,
8549          sourceName = this.sourceName,
8550          targetName = this.targetName,
8551          comObj = this.comObj;
8552    return new ReadableStream({
8553      start: controller => {
8554        const startCapability = (0, _util.createPromiseCapability)();
8555        this.streamControllers[streamId] = {
8556          controller,
8557          startCall: startCapability,
8558          pullCall: null,
8559          cancelCall: null,
8560          isClosed: false
8561        };
8562        comObj.postMessage({
8563          sourceName,
8564          targetName,
8565          action: actionName,
8566          streamId,
8567          data,
8568          desiredSize: controller.desiredSize
8569        }, transfers);
8570        return startCapability.promise;
8571      },
8572      pull: controller => {
8573        const pullCapability = (0, _util.createPromiseCapability)();
8574        this.streamControllers[streamId].pullCall = pullCapability;
8575        comObj.postMessage({
8576          sourceName,
8577          targetName,
8578          stream: StreamKind.PULL,
8579          streamId,
8580          desiredSize: controller.desiredSize
8581        });
8582        return pullCapability.promise;
8583      },
8584      cancel: reason => {
8585        (0, _util.assert)(reason instanceof Error, "cancel must have a valid reason");
8586        const cancelCapability = (0, _util.createPromiseCapability)();
8587        this.streamControllers[streamId].cancelCall = cancelCapability;
8588        this.streamControllers[streamId].isClosed = true;
8589        comObj.postMessage({
8590          sourceName,
8591          targetName,
8592          stream: StreamKind.CANCEL,
8593          streamId,
8594          reason: wrapReason(reason)
8595        });
8596        return cancelCapability.promise;
8597      }
8598    }, queueingStrategy);
8599  }
8600
8601  _createStreamSink(data) {
8602    const streamId = data.streamId,
8603          sourceName = this.sourceName,
8604          targetName = data.sourceName,
8605          comObj = this.comObj;
8606    const self = this,
8607          action = this.actionHandler[data.action];
8608    const streamSink = {
8609      enqueue(chunk, size = 1, transfers) {
8610        if (this.isCancelled) {
8611          return;
8612        }
8613
8614        const lastDesiredSize = this.desiredSize;
8615        this.desiredSize -= size;
8616
8617        if (lastDesiredSize > 0 && this.desiredSize <= 0) {
8618          this.sinkCapability = (0, _util.createPromiseCapability)();
8619          this.ready = this.sinkCapability.promise;
8620        }
8621
8622        comObj.postMessage({
8623          sourceName,
8624          targetName,
8625          stream: StreamKind.ENQUEUE,
8626          streamId,
8627          chunk
8628        }, transfers);
8629      },
8630
8631      close() {
8632        if (this.isCancelled) {
8633          return;
8634        }
8635
8636        this.isCancelled = true;
8637        comObj.postMessage({
8638          sourceName,
8639          targetName,
8640          stream: StreamKind.CLOSE,
8641          streamId
8642        });
8643        delete self.streamSinks[streamId];
8644      },
8645
8646      error(reason) {
8647        (0, _util.assert)(reason instanceof Error, "error must have a valid reason");
8648
8649        if (this.isCancelled) {
8650          return;
8651        }
8652
8653        this.isCancelled = true;
8654        comObj.postMessage({
8655          sourceName,
8656          targetName,
8657          stream: StreamKind.ERROR,
8658          streamId,
8659          reason: wrapReason(reason)
8660        });
8661      },
8662
8663      sinkCapability: (0, _util.createPromiseCapability)(),
8664      onPull: null,
8665      onCancel: null,
8666      isCancelled: false,
8667      desiredSize: data.desiredSize,
8668      ready: null
8669    };
8670    streamSink.sinkCapability.resolve();
8671    streamSink.ready = streamSink.sinkCapability.promise;
8672    this.streamSinks[streamId] = streamSink;
8673    new Promise(function (resolve) {
8674      resolve(action(data.data, streamSink));
8675    }).then(function () {
8676      comObj.postMessage({
8677        sourceName,
8678        targetName,
8679        stream: StreamKind.START_COMPLETE,
8680        streamId,
8681        success: true
8682      });
8683    }, function (reason) {
8684      comObj.postMessage({
8685        sourceName,
8686        targetName,
8687        stream: StreamKind.START_COMPLETE,
8688        streamId,
8689        reason: wrapReason(reason)
8690      });
8691    });
8692  }
8693
8694  _processStreamMessage(data) {
8695    const streamId = data.streamId,
8696          sourceName = this.sourceName,
8697          targetName = data.sourceName,
8698          comObj = this.comObj;
8699    const streamController = this.streamControllers[streamId],
8700          streamSink = this.streamSinks[streamId];
8701
8702    switch (data.stream) {
8703      case StreamKind.START_COMPLETE:
8704        if (data.success) {
8705          streamController.startCall.resolve();
8706        } else {
8707          streamController.startCall.reject(wrapReason(data.reason));
8708        }
8709
8710        break;
8711
8712      case StreamKind.PULL_COMPLETE:
8713        if (data.success) {
8714          streamController.pullCall.resolve();
8715        } else {
8716          streamController.pullCall.reject(wrapReason(data.reason));
8717        }
8718
8719        break;
8720
8721      case StreamKind.PULL:
8722        if (!streamSink) {
8723          comObj.postMessage({
8724            sourceName,
8725            targetName,
8726            stream: StreamKind.PULL_COMPLETE,
8727            streamId,
8728            success: true
8729          });
8730          break;
8731        }
8732
8733        if (streamSink.desiredSize <= 0 && data.desiredSize > 0) {
8734          streamSink.sinkCapability.resolve();
8735        }
8736
8737        streamSink.desiredSize = data.desiredSize;
8738        new Promise(function (resolve) {
8739          resolve(streamSink.onPull && streamSink.onPull());
8740        }).then(function () {
8741          comObj.postMessage({
8742            sourceName,
8743            targetName,
8744            stream: StreamKind.PULL_COMPLETE,
8745            streamId,
8746            success: true
8747          });
8748        }, function (reason) {
8749          comObj.postMessage({
8750            sourceName,
8751            targetName,
8752            stream: StreamKind.PULL_COMPLETE,
8753            streamId,
8754            reason: wrapReason(reason)
8755          });
8756        });
8757        break;
8758
8759      case StreamKind.ENQUEUE:
8760        (0, _util.assert)(streamController, "enqueue should have stream controller");
8761
8762        if (streamController.isClosed) {
8763          break;
8764        }
8765
8766        streamController.controller.enqueue(data.chunk);
8767        break;
8768
8769      case StreamKind.CLOSE:
8770        (0, _util.assert)(streamController, "close should have stream controller");
8771
8772        if (streamController.isClosed) {
8773          break;
8774        }
8775
8776        streamController.isClosed = true;
8777        streamController.controller.close();
8778
8779        this._deleteStreamController(streamController, streamId);
8780
8781        break;
8782
8783      case StreamKind.ERROR:
8784        (0, _util.assert)(streamController, "error should have stream controller");
8785        streamController.controller.error(wrapReason(data.reason));
8786
8787        this._deleteStreamController(streamController, streamId);
8788
8789        break;
8790
8791      case StreamKind.CANCEL_COMPLETE:
8792        if (data.success) {
8793          streamController.cancelCall.resolve();
8794        } else {
8795          streamController.cancelCall.reject(wrapReason(data.reason));
8796        }
8797
8798        this._deleteStreamController(streamController, streamId);
8799
8800        break;
8801
8802      case StreamKind.CANCEL:
8803        if (!streamSink) {
8804          break;
8805        }
8806
8807        new Promise(function (resolve) {
8808          resolve(streamSink.onCancel && streamSink.onCancel(wrapReason(data.reason)));
8809        }).then(function () {
8810          comObj.postMessage({
8811            sourceName,
8812            targetName,
8813            stream: StreamKind.CANCEL_COMPLETE,
8814            streamId,
8815            success: true
8816          });
8817        }, function (reason) {
8818          comObj.postMessage({
8819            sourceName,
8820            targetName,
8821            stream: StreamKind.CANCEL_COMPLETE,
8822            streamId,
8823            reason: wrapReason(reason)
8824          });
8825        });
8826        streamSink.sinkCapability.reject(wrapReason(data.reason));
8827        streamSink.isCancelled = true;
8828        delete this.streamSinks[streamId];
8829        break;
8830
8831      default:
8832        throw new Error("Unexpected stream case");
8833    }
8834  }
8835
8836  async _deleteStreamController(streamController, streamId) {
8837    await Promise.allSettled([streamController.startCall && streamController.startCall.promise, streamController.pullCall && streamController.pullCall.promise, streamController.cancelCall && streamController.cancelCall.promise]);
8838    delete this.streamControllers[streamId];
8839  }
8840
8841  destroy() {
8842    this.comObj.removeEventListener("message", this._onComObjOnMessage);
8843  }
8844
8845}
8846
8847exports.MessageHandler = MessageHandler;
8848
8849/***/ }),
8850/* 15 */
8851/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8852
8853
8854
8855Object.defineProperty(exports, "__esModule", ({
8856  value: true
8857}));
8858exports.Metadata = void 0;
8859
8860var _util = __w_pdfjs_require__(1);
8861
8862class Metadata {
8863  #metadataMap;
8864  #data;
8865
8866  constructor({
8867    parsedData,
8868    rawData
8869  }) {
8870    this.#metadataMap = parsedData;
8871    this.#data = rawData;
8872  }
8873
8874  getRaw() {
8875    return this.#data;
8876  }
8877
8878  get(name) {
8879    return this.#metadataMap.get(name) ?? null;
8880  }
8881
8882  getAll() {
8883    return (0, _util.objectFromMap)(this.#metadataMap);
8884  }
8885
8886  has(name) {
8887    return this.#metadataMap.has(name);
8888  }
8889
8890}
8891
8892exports.Metadata = Metadata;
8893
8894/***/ }),
8895/* 16 */
8896/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
8897
8898
8899
8900Object.defineProperty(exports, "__esModule", ({
8901  value: true
8902}));
8903exports.OptionalContentConfig = void 0;
8904
8905var _util = __w_pdfjs_require__(1);
8906
8907class OptionalContentGroup {
8908  constructor(name, intent) {
8909    this.visible = true;
8910    this.name = name;
8911    this.intent = intent;
8912  }
8913
8914}
8915
8916class OptionalContentConfig {
8917  constructor(data) {
8918    this.name = null;
8919    this.creator = null;
8920    this._order = null;
8921    this._groups = new Map();
8922
8923    if (data === null) {
8924      return;
8925    }
8926
8927    this.name = data.name;
8928    this.creator = data.creator;
8929    this._order = data.order;
8930
8931    for (const group of data.groups) {
8932      this._groups.set(group.id, new OptionalContentGroup(group.name, group.intent));
8933    }
8934
8935    if (data.baseState === "OFF") {
8936      for (const group of this._groups) {
8937        group.visible = false;
8938      }
8939    }
8940
8941    for (const on of data.on) {
8942      this._groups.get(on).visible = true;
8943    }
8944
8945    for (const off of data.off) {
8946      this._groups.get(off).visible = false;
8947    }
8948  }
8949
8950  _evaluateVisibilityExpression(array) {
8951    const length = array.length;
8952
8953    if (length < 2) {
8954      return true;
8955    }
8956
8957    const operator = array[0];
8958
8959    for (let i = 1; i < length; i++) {
8960      const element = array[i];
8961      let state;
8962
8963      if (Array.isArray(element)) {
8964        state = this._evaluateVisibilityExpression(element);
8965      } else if (this._groups.has(element)) {
8966        state = this._groups.get(element).visible;
8967      } else {
8968        (0, _util.warn)(`Optional content group not found: ${element}`);
8969        return true;
8970      }
8971
8972      switch (operator) {
8973        case "And":
8974          if (!state) {
8975            return false;
8976          }
8977
8978          break;
8979
8980        case "Or":
8981          if (state) {
8982            return true;
8983          }
8984
8985          break;
8986
8987        case "Not":
8988          return !state;
8989
8990        default:
8991          return true;
8992      }
8993    }
8994
8995    return operator === "And";
8996  }
8997
8998  isVisible(group) {
8999    if (this._groups.size === 0) {
9000      return true;
9001    }
9002
9003    if (!group) {
9004      (0, _util.warn)("Optional content group not defined.");
9005      return true;
9006    }
9007
9008    if (group.type === "OCG") {
9009      if (!this._groups.has(group.id)) {
9010        (0, _util.warn)(`Optional content group not found: ${group.id}`);
9011        return true;
9012      }
9013
9014      return this._groups.get(group.id).visible;
9015    } else if (group.type === "OCMD") {
9016      if (group.expression) {
9017        return this._evaluateVisibilityExpression(group.expression);
9018      }
9019
9020      if (!group.policy || group.policy === "AnyOn") {
9021        for (const id of group.ids) {
9022          if (!this._groups.has(id)) {
9023            (0, _util.warn)(`Optional content group not found: ${id}`);
9024            return true;
9025          }
9026
9027          if (this._groups.get(id).visible) {
9028            return true;
9029          }
9030        }
9031
9032        return false;
9033      } else if (group.policy === "AllOn") {
9034        for (const id of group.ids) {
9035          if (!this._groups.has(id)) {
9036            (0, _util.warn)(`Optional content group not found: ${id}`);
9037            return true;
9038          }
9039
9040          if (!this._groups.get(id).visible) {
9041            return false;
9042          }
9043        }
9044
9045        return true;
9046      } else if (group.policy === "AnyOff") {
9047        for (const id of group.ids) {
9048          if (!this._groups.has(id)) {
9049            (0, _util.warn)(`Optional content group not found: ${id}`);
9050            return true;
9051          }
9052
9053          if (!this._groups.get(id).visible) {
9054            return true;
9055          }
9056        }
9057
9058        return false;
9059      } else if (group.policy === "AllOff") {
9060        for (const id of group.ids) {
9061          if (!this._groups.has(id)) {
9062            (0, _util.warn)(`Optional content group not found: ${id}`);
9063            return true;
9064          }
9065
9066          if (this._groups.get(id).visible) {
9067            return false;
9068          }
9069        }
9070
9071        return true;
9072      }
9073
9074      (0, _util.warn)(`Unknown optional content policy ${group.policy}.`);
9075      return true;
9076    }
9077
9078    (0, _util.warn)(`Unknown group type ${group.type}.`);
9079    return true;
9080  }
9081
9082  setVisibility(id, visible = true) {
9083    if (!this._groups.has(id)) {
9084      (0, _util.warn)(`Optional content group not found: ${id}`);
9085      return;
9086    }
9087
9088    this._groups.get(id).visible = !!visible;
9089  }
9090
9091  getOrder() {
9092    if (!this._groups.size) {
9093      return null;
9094    }
9095
9096    if (this._order) {
9097      return this._order.slice();
9098    }
9099
9100    return Array.from(this._groups.keys());
9101  }
9102
9103  getGroups() {
9104    return this._groups.size > 0 ? (0, _util.objectFromMap)(this._groups) : null;
9105  }
9106
9107  getGroup(id) {
9108    return this._groups.get(id) || null;
9109  }
9110
9111}
9112
9113exports.OptionalContentConfig = OptionalContentConfig;
9114
9115/***/ }),
9116/* 17 */
9117/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9118
9119
9120
9121Object.defineProperty(exports, "__esModule", ({
9122  value: true
9123}));
9124exports.PDFDataTransportStream = void 0;
9125
9126var _util = __w_pdfjs_require__(1);
9127
9128var _display_utils = __w_pdfjs_require__(5);
9129
9130class PDFDataTransportStream {
9131  constructor(params, pdfDataRangeTransport) {
9132    (0, _util.assert)(pdfDataRangeTransport, 'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');
9133    this._queuedChunks = [];
9134    this._progressiveDone = params.progressiveDone || false;
9135    this._contentDispositionFilename = params.contentDispositionFilename || null;
9136    const initialData = params.initialData;
9137
9138    if (initialData?.length > 0) {
9139      const buffer = new Uint8Array(initialData).buffer;
9140
9141      this._queuedChunks.push(buffer);
9142    }
9143
9144    this._pdfDataRangeTransport = pdfDataRangeTransport;
9145    this._isStreamingSupported = !params.disableStream;
9146    this._isRangeSupported = !params.disableRange;
9147    this._contentLength = params.length;
9148    this._fullRequestReader = null;
9149    this._rangeReaders = [];
9150
9151    this._pdfDataRangeTransport.addRangeListener((begin, chunk) => {
9152      this._onReceiveData({
9153        begin,
9154        chunk
9155      });
9156    });
9157
9158    this._pdfDataRangeTransport.addProgressListener((loaded, total) => {
9159      this._onProgress({
9160        loaded,
9161        total
9162      });
9163    });
9164
9165    this._pdfDataRangeTransport.addProgressiveReadListener(chunk => {
9166      this._onReceiveData({
9167        chunk
9168      });
9169    });
9170
9171    this._pdfDataRangeTransport.addProgressiveDoneListener(() => {
9172      this._onProgressiveDone();
9173    });
9174
9175    this._pdfDataRangeTransport.transportReady();
9176  }
9177
9178  _onReceiveData(args) {
9179    const buffer = new Uint8Array(args.chunk).buffer;
9180
9181    if (args.begin === undefined) {
9182      if (this._fullRequestReader) {
9183        this._fullRequestReader._enqueue(buffer);
9184      } else {
9185        this._queuedChunks.push(buffer);
9186      }
9187    } else {
9188      const found = this._rangeReaders.some(function (rangeReader) {
9189        if (rangeReader._begin !== args.begin) {
9190          return false;
9191        }
9192
9193        rangeReader._enqueue(buffer);
9194
9195        return true;
9196      });
9197
9198      (0, _util.assert)(found, "_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.");
9199    }
9200  }
9201
9202  get _progressiveDataLength() {
9203    return this._fullRequestReader?._loaded ?? 0;
9204  }
9205
9206  _onProgress(evt) {
9207    if (evt.total === undefined) {
9208      const firstReader = this._rangeReaders[0];
9209
9210      if (firstReader?.onProgress) {
9211        firstReader.onProgress({
9212          loaded: evt.loaded
9213        });
9214      }
9215    } else {
9216      const fullReader = this._fullRequestReader;
9217
9218      if (fullReader?.onProgress) {
9219        fullReader.onProgress({
9220          loaded: evt.loaded,
9221          total: evt.total
9222        });
9223      }
9224    }
9225  }
9226
9227  _onProgressiveDone() {
9228    if (this._fullRequestReader) {
9229      this._fullRequestReader.progressiveDone();
9230    }
9231
9232    this._progressiveDone = true;
9233  }
9234
9235  _removeRangeReader(reader) {
9236    const i = this._rangeReaders.indexOf(reader);
9237
9238    if (i >= 0) {
9239      this._rangeReaders.splice(i, 1);
9240    }
9241  }
9242
9243  getFullReader() {
9244    (0, _util.assert)(!this._fullRequestReader, "PDFDataTransportStream.getFullReader can only be called once.");
9245    const queuedChunks = this._queuedChunks;
9246    this._queuedChunks = null;
9247    return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone, this._contentDispositionFilename);
9248  }
9249
9250  getRangeReader(begin, end) {
9251    if (end <= this._progressiveDataLength) {
9252      return null;
9253    }
9254
9255    const reader = new PDFDataTransportStreamRangeReader(this, begin, end);
9256
9257    this._pdfDataRangeTransport.requestDataRange(begin, end);
9258
9259    this._rangeReaders.push(reader);
9260
9261    return reader;
9262  }
9263
9264  cancelAllRequests(reason) {
9265    if (this._fullRequestReader) {
9266      this._fullRequestReader.cancel(reason);
9267    }
9268
9269    for (const reader of this._rangeReaders.slice(0)) {
9270      reader.cancel(reason);
9271    }
9272
9273    this._pdfDataRangeTransport.abort();
9274  }
9275
9276}
9277
9278exports.PDFDataTransportStream = PDFDataTransportStream;
9279
9280class PDFDataTransportStreamReader {
9281  constructor(stream, queuedChunks, progressiveDone = false, contentDispositionFilename = null) {
9282    this._stream = stream;
9283    this._done = progressiveDone || false;
9284    this._filename = (0, _display_utils.isPdfFile)(contentDispositionFilename) ? contentDispositionFilename : null;
9285    this._queuedChunks = queuedChunks || [];
9286    this._loaded = 0;
9287
9288    for (const chunk of this._queuedChunks) {
9289      this._loaded += chunk.byteLength;
9290    }
9291
9292    this._requests = [];
9293    this._headersReady = Promise.resolve();
9294    stream._fullRequestReader = this;
9295    this.onProgress = null;
9296  }
9297
9298  _enqueue(chunk) {
9299    if (this._done) {
9300      return;
9301    }
9302
9303    if (this._requests.length > 0) {
9304      const requestCapability = this._requests.shift();
9305
9306      requestCapability.resolve({
9307        value: chunk,
9308        done: false
9309      });
9310    } else {
9311      this._queuedChunks.push(chunk);
9312    }
9313
9314    this._loaded += chunk.byteLength;
9315  }
9316
9317  get headersReady() {
9318    return this._headersReady;
9319  }
9320
9321  get filename() {
9322    return this._filename;
9323  }
9324
9325  get isRangeSupported() {
9326    return this._stream._isRangeSupported;
9327  }
9328
9329  get isStreamingSupported() {
9330    return this._stream._isStreamingSupported;
9331  }
9332
9333  get contentLength() {
9334    return this._stream._contentLength;
9335  }
9336
9337  async read() {
9338    if (this._queuedChunks.length > 0) {
9339      const chunk = this._queuedChunks.shift();
9340
9341      return {
9342        value: chunk,
9343        done: false
9344      };
9345    }
9346
9347    if (this._done) {
9348      return {
9349        value: undefined,
9350        done: true
9351      };
9352    }
9353
9354    const requestCapability = (0, _util.createPromiseCapability)();
9355
9356    this._requests.push(requestCapability);
9357
9358    return requestCapability.promise;
9359  }
9360
9361  cancel(reason) {
9362    this._done = true;
9363
9364    for (const requestCapability of this._requests) {
9365      requestCapability.resolve({
9366        value: undefined,
9367        done: true
9368      });
9369    }
9370
9371    this._requests.length = 0;
9372  }
9373
9374  progressiveDone() {
9375    if (this._done) {
9376      return;
9377    }
9378
9379    this._done = true;
9380  }
9381
9382}
9383
9384class PDFDataTransportStreamRangeReader {
9385  constructor(stream, begin, end) {
9386    this._stream = stream;
9387    this._begin = begin;
9388    this._end = end;
9389    this._queuedChunk = null;
9390    this._requests = [];
9391    this._done = false;
9392    this.onProgress = null;
9393  }
9394
9395  _enqueue(chunk) {
9396    if (this._done) {
9397      return;
9398    }
9399
9400    if (this._requests.length === 0) {
9401      this._queuedChunk = chunk;
9402    } else {
9403      const requestsCapability = this._requests.shift();
9404
9405      requestsCapability.resolve({
9406        value: chunk,
9407        done: false
9408      });
9409
9410      for (const requestCapability of this._requests) {
9411        requestCapability.resolve({
9412          value: undefined,
9413          done: true
9414        });
9415      }
9416
9417      this._requests.length = 0;
9418    }
9419
9420    this._done = true;
9421
9422    this._stream._removeRangeReader(this);
9423  }
9424
9425  get isStreamingSupported() {
9426    return false;
9427  }
9428
9429  async read() {
9430    if (this._queuedChunk) {
9431      const chunk = this._queuedChunk;
9432      this._queuedChunk = null;
9433      return {
9434        value: chunk,
9435        done: false
9436      };
9437    }
9438
9439    if (this._done) {
9440      return {
9441        value: undefined,
9442        done: true
9443      };
9444    }
9445
9446    const requestCapability = (0, _util.createPromiseCapability)();
9447
9448    this._requests.push(requestCapability);
9449
9450    return requestCapability.promise;
9451  }
9452
9453  cancel(reason) {
9454    this._done = true;
9455
9456    for (const requestCapability of this._requests) {
9457      requestCapability.resolve({
9458        value: undefined,
9459        done: true
9460      });
9461    }
9462
9463    this._requests.length = 0;
9464
9465    this._stream._removeRangeReader(this);
9466  }
9467
9468}
9469
9470/***/ }),
9471/* 18 */
9472/***/ ((__unused_webpack_module, exports) => {
9473
9474
9475
9476Object.defineProperty(exports, "__esModule", ({
9477  value: true
9478}));
9479exports.XfaText = void 0;
9480
9481class XfaText {
9482  static textContent(xfa) {
9483    const items = [];
9484    const output = {
9485      items,
9486      styles: Object.create(null)
9487    };
9488
9489    function walk(node) {
9490      if (!node) {
9491        return;
9492      }
9493
9494      let str = null;
9495      const name = node.name;
9496
9497      if (name === "#text") {
9498        str = node.value;
9499      } else if (!XfaText.shouldBuildText(name)) {
9500        return;
9501      } else if (node?.attributes?.textContent) {
9502        str = node.attributes.textContent;
9503      } else if (node.value) {
9504        str = node.value;
9505      }
9506
9507      if (str !== null) {
9508        items.push({
9509          str
9510        });
9511      }
9512
9513      if (!node.children) {
9514        return;
9515      }
9516
9517      for (const child of node.children) {
9518        walk(child);
9519      }
9520    }
9521
9522    walk(xfa);
9523    return output;
9524  }
9525
9526  static shouldBuildText(name) {
9527    return !(name === "textarea" || name === "input" || name === "option" || name === "select");
9528  }
9529
9530}
9531
9532exports.XfaText = XfaText;
9533
9534/***/ }),
9535/* 19 */
9536/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9537
9538
9539
9540Object.defineProperty(exports, "__esModule", ({
9541  value: true
9542}));
9543exports.NodeStandardFontDataFactory = exports.NodeCanvasFactory = exports.NodeCMapReaderFactory = void 0;
9544
9545var _base_factory = __w_pdfjs_require__(6);
9546
9547;
9548
9549const fetchData = function (url) {
9550  return new Promise((resolve, reject) => {
9551    const fs = require("fs");
9552
9553    fs.readFile(url, (error, data) => {
9554      if (error || !data) {
9555        reject(new Error(error));
9556        return;
9557      }
9558
9559      resolve(new Uint8Array(data));
9560    });
9561  });
9562};
9563
9564class NodeCanvasFactory extends _base_factory.BaseCanvasFactory {
9565  _createCanvas(width, height) {
9566    const Canvas = require("canvas");
9567
9568    return Canvas.createCanvas(width, height);
9569  }
9570
9571}
9572
9573exports.NodeCanvasFactory = NodeCanvasFactory;
9574
9575class NodeCMapReaderFactory extends _base_factory.BaseCMapReaderFactory {
9576  _fetchData(url, compressionType) {
9577    return fetchData(url).then(data => {
9578      return {
9579        cMapData: data,
9580        compressionType
9581      };
9582    });
9583  }
9584
9585}
9586
9587exports.NodeCMapReaderFactory = NodeCMapReaderFactory;
9588
9589class NodeStandardFontDataFactory extends _base_factory.BaseStandardFontDataFactory {
9590  _fetchData(url) {
9591    return fetchData(url);
9592  }
9593
9594}
9595
9596exports.NodeStandardFontDataFactory = NodeStandardFontDataFactory;
9597
9598/***/ }),
9599/* 20 */
9600/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
9601
9602
9603
9604Object.defineProperty(exports, "__esModule", ({
9605  value: true
9606}));
9607exports.AnnotationLayer = void 0;
9608
9609var _util = __w_pdfjs_require__(1);
9610
9611var _display_utils = __w_pdfjs_require__(5);
9612
9613var _annotation_storage = __w_pdfjs_require__(8);
9614
9615var _scripting_utils = __w_pdfjs_require__(21);
9616
9617var _xfa_layer = __w_pdfjs_require__(22);
9618
9619const DEFAULT_TAB_INDEX = 1000;
9620const GetElementsByNameSet = new WeakSet();
9621
9622function getRectDims(rect) {
9623  return {
9624    width: rect[2] - rect[0],
9625    height: rect[3] - rect[1]
9626  };
9627}
9628
9629class AnnotationElementFactory {
9630  static create(parameters) {
9631    const subtype = parameters.data.annotationType;
9632
9633    switch (subtype) {
9634      case _util.AnnotationType.LINK:
9635        return new LinkAnnotationElement(parameters);
9636
9637      case _util.AnnotationType.TEXT:
9638        return new TextAnnotationElement(parameters);
9639
9640      case _util.AnnotationType.WIDGET:
9641        const fieldType = parameters.data.fieldType;
9642
9643        switch (fieldType) {
9644          case "Tx":
9645            return new TextWidgetAnnotationElement(parameters);
9646
9647          case "Btn":
9648            if (parameters.data.radioButton) {
9649              return new RadioButtonWidgetAnnotationElement(parameters);
9650            } else if (parameters.data.checkBox) {
9651              return new CheckboxWidgetAnnotationElement(parameters);
9652            }
9653
9654            return new PushButtonWidgetAnnotationElement(parameters);
9655
9656          case "Ch":
9657            return new ChoiceWidgetAnnotationElement(parameters);
9658        }
9659
9660        return new WidgetAnnotationElement(parameters);
9661
9662      case _util.AnnotationType.POPUP:
9663        return new PopupAnnotationElement(parameters);
9664
9665      case _util.AnnotationType.FREETEXT:
9666        return new FreeTextAnnotationElement(parameters);
9667
9668      case _util.AnnotationType.LINE:
9669        return new LineAnnotationElement(parameters);
9670
9671      case _util.AnnotationType.SQUARE:
9672        return new SquareAnnotationElement(parameters);
9673
9674      case _util.AnnotationType.CIRCLE:
9675        return new CircleAnnotationElement(parameters);
9676
9677      case _util.AnnotationType.POLYLINE:
9678        return new PolylineAnnotationElement(parameters);
9679
9680      case _util.AnnotationType.CARET:
9681        return new CaretAnnotationElement(parameters);
9682
9683      case _util.AnnotationType.INK:
9684        return new InkAnnotationElement(parameters);
9685
9686      case _util.AnnotationType.POLYGON:
9687        return new PolygonAnnotationElement(parameters);
9688
9689      case _util.AnnotationType.HIGHLIGHT:
9690        return new HighlightAnnotationElement(parameters);
9691
9692      case _util.AnnotationType.UNDERLINE:
9693        return new UnderlineAnnotationElement(parameters);
9694
9695      case _util.AnnotationType.SQUIGGLY:
9696        return new SquigglyAnnotationElement(parameters);
9697
9698      case _util.AnnotationType.STRIKEOUT:
9699        return new StrikeOutAnnotationElement(parameters);
9700
9701      case _util.AnnotationType.STAMP:
9702        return new StampAnnotationElement(parameters);
9703
9704      case _util.AnnotationType.FILEATTACHMENT:
9705        return new FileAttachmentAnnotationElement(parameters);
9706
9707      default:
9708        return new AnnotationElement(parameters);
9709    }
9710  }
9711
9712}
9713
9714class AnnotationElement {
9715  constructor(parameters, {
9716    isRenderable = false,
9717    ignoreBorder = false,
9718    createQuadrilaterals = false
9719  }
9719 = {}) {
9720    this.isRenderable = isRenderable;
9721    this.data = parameters.data;
9722    this.layer = parameters.layer;
9723    this.page = parameters.page;
9724    this.viewport = parameters.viewport;
9725    this.linkService = parameters.linkService;
9726    this.downloadManager = parameters.downloadManager;
9727    this.imageResourcesPath = parameters.imageResourcesPath;
9728    this.renderForms = parameters.renderForms;
9729    this.svgFactory = parameters.svgFactory;
9730    this.annotationStorage = parameters.annotationStorage;
9731    this.enableScripting = parameters.enableScripting;
9732    this.hasJSActions = parameters.hasJSActions;
9733    this._fieldObjects = parameters.fieldObjects;
9734    this._mouseState = parameters.mouseState;
9735
9736    if (isRenderable) {
9737      this.container = this._createContainer(ignoreBorder);
9738    }
9739
9740    if (createQuadrilaterals) {
9741      this.quadrilaterals = this._createQuadrilaterals(ignoreBorder);
9742    }
9743  }
9744
9745  _createContainer(ignoreBorder = false) {
9746    const data = this.data,
9747          page = this.page,
9748          viewport = this.viewport;
9749    const container = document.createElement("section");
9750    let {
9751      width,
9752      height
9753    } = getRectDims(data.rect);
9754    container.setAttribute("data-annotation-id", data.id);
9755
9756    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]]);
9757
9758    if (data.hasOwnCanvas) {
9759      const transform = viewport.transform.slice();
9760
9761      const [scaleX, scaleY] = _util.Util.singularValueDecompose2dScale(transform);
9762
9763      width = Math.ceil(width * scaleX);
9764      height = Math.ceil(height * scaleY);
9765      rect[0] *= scaleX;
9766      rect[1] *= scaleY;
9767
9768      for (let i = 0; i < 4; i++) {
9769        transform[i] = Math.sign(transform[i]);
9770      }
9771
9772      container.style.transform = `matrix(${transform.join(",")})`;
9773    } else {
9774      container.style.transform = `matrix(${viewport.transform.join(",")})`;
9775    }
9776
9777    container.style.transformOrigin = `${-rect[0]}px ${-rect[1]}px`;
9778
9779    if (!ignoreBorder && data.borderStyle.width > 0) {
9780      container.style.borderWidth = `${data.borderStyle.width}px`;
9781
9782      if (data.borderStyle.style !== _util.AnnotationBorderStyleType.UNDERLINE) {
9783        width -= 2 * data.borderStyle.width;
9784        height -= 2 * data.borderStyle.width;
9785      }
9786
9787      const horizontalRadius = data.borderStyle.horizontalCornerRadius;
9788      const verticalRadius = data.borderStyle.verticalCornerRadius;
9789
9790      if (horizontalRadius > 0 || verticalRadius > 0) {
9791        const radius = `${horizontalRadius}px / ${verticalRadius}px`;
9792        container.style.borderRadius = radius;
9793      }
9794
9795      switch (data.borderStyle.style) {
9796        case _util.AnnotationBorderStyleType.SOLID:
9797          container.style.borderStyle = "solid";
9798          break;
9799
9800        case _util.AnnotationBorderStyleType.DASHED:
9801          container.style.borderStyle = "dashed";
9802          break;
9803
9804        case _util.AnnotationBorderStyleType.BEVELED:
9805          (0, _util.warn)("Unimplemented border style: beveled");
9806          break;
9807
9808        case _util.AnnotationBorderStyleType.INSET:
9809          (0, _util.warn)("Unimplemented border style: inset");
9810          break;
9811
9812        case _util.AnnotationBorderStyleType.UNDERLINE:
9813          container.style.borderBottomStyle = "solid";
9814          break;
9815
9816        default:
9817          break;
9818      }
9819
9820      const borderColor = data.borderColor || data.color || null;
9821
9822      if (borderColor) {
9823        container.style.borderColor = _util.Util.makeHexColor(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0);
9824      } else {
9825        container.style.borderWidth = 0;
9826      }
9827    }
9828
9829    container.style.left = `${rect[0]}px`;
9830    container.style.top = `${rect[1]}px`;
9831
9832    if (data.hasOwnCanvas) {
9833      container.style.width = container.style.height = "auto";
9834    } else {
9835      container.style.width = `${width}px`;
9836      container.style.height = `${height}px`;
9837    }
9838
9839    return container;
9840  }
9841
9842  get _commonActions() {
9843    const setColor = (jsName, styleName, event) => {
9844      const color = event.detail[jsName];
9845      event.target.style[styleName] = _scripting_utils.ColorConverters[`${color[0]}_HTML`](color.slice(1));
9846    };
9847
9848    return (0, _util.shadow)(this, "_commonActions", {
9849      display: event => {
9850        const hidden = event.detail.display % 2 === 1;
9851        event.target.style.visibility = hidden ? "hidden" : "visible";
9852        this.annotationStorage.setValue(this.data.id, {
9853          hidden,
9854          print: event.detail.display === 0 || event.detail.display === 3
9855        });
9856      },
9857      print: event => {
9858        this.annotationStorage.setValue(this.data.id, {
9859          print: event.detail.print
9860        });
9861      },
9862      hidden: event => {
9863        event.target.style.visibility = event.detail.hidden ? "hidden" : "visible";
9864        this.annotationStorage.setValue(this.data.id, {
9865          hidden: event.detail.hidden
9866        });
9867      },
9868      focus: event => {
9869        setTimeout(() =>
9869 event.target.focus({
9870          preventScroll: false
9871        }), 0);
9872      },
9873      userName: event => {
9874        event.target.title = event.detail.userName;
9875      },
9876      readonly: event => {
9877        if (event.detail.readonly) {
9878          event.target.setAttribute("readonly", "");
9879        } else {
9880          event.target.removeAttribute("readonly");
9881        }
9882      },
9883      required: event => {
9884        if (event.detail.required) {
9885          event.target.setAttribute("required", "");
9886        } else {
9887          event.target.removeAttribute("required");
9888        }
9889      },
9890      bgColor: event => {
9891        setColor("bgColor", "backgroundColor", event);
9892      },
9893      fillColor: event => {
9894        setColor("fillColor", "backgroundColor", event);
9895      },
9896      fgColor: event => {
9897        setColor("fgColor", "color", event);
9898      },
9899      textColor: event => {
9900        setColor("textColor", "color", event);
9901      },
9902      borderColor: event => {
9903        setColor("borderColor", "borderColor", event);
9904      },
9905      strokeColor: event => {
9906        setColor("strokeColor", "borderColor", event);
9907      }
9908    });
9909  }
9910
9911  _dispatchEventFromSandbox(actions, jsEvent) {
9912    const commonActions = this._commonActions;
9913
9914    for (const name of Object.keys(jsEvent.detail)) {
9915      const action = actions[name] || commonActions[name];
9916
9917      if (action) {
9918        action(jsEvent);
9919      }
9920    }
9921  }
9922
9923  _setDefaultPropertiesFromJS(element) {
9924    if (!this.enableScripting) {
9925      return;
9926    }
9927
9928    const storedData = this.annotationStorage.getRawValue(this.data.id);
9929
9930    if (!storedData) {
9931      return;
9932    }
9933
9934    const commonActions = this._commonActions;
9935
9936    for (const [actionName, detail] of Object.entries(storedData)) {
9937      const action = commonActions[actionName];
9938
9939      if (action) {
9940        action({
9941          detail,
9942          target: element
9943        });
9944        delete storedData[actionName];
9945      }
9946    }
9947  }
9948
9949  _createQuadrilaterals(ignoreBorder = false) {
9950    if (!this.data.quadPoints) {
9951      return null;
9952    }
9953
9954    const quadrilaterals = [];
9955    const savedRect = this.data.rect;
9956
9957    for (const quadPoint of this.data.quadPoints) {
9958      this.data.rect = [quadPoint[2].x, quadPoint[2].y, quadPoint[1].x, quadPoint[1].y];
9959      quadrilaterals.push(this._createContainer(ignoreBorder));
9960    }
9961
9962    this.data.rect = savedRect;
9963    return quadrilaterals;
9964  }
9965
9966  _createPopup(trigger, data) {
9967    let container = this.container;
9968
9969    if (this.quadrilaterals) {
9970      trigger = trigger || this.quadrilaterals;
9971      container = this.quadrilaterals[0];
9972    }
9973
9974    if (!trigger) {
9975      trigger = document.createElement("div");
9976      trigger.style.height = container.style.height;
9977      trigger.style.width = container.style.width;
9978      container.appendChild(trigger);
9979    }
9980
9981    const popupElement = new PopupElement({
9982      container,
9983      trigger,
9984      color: data.color,
9985      titleObj: data.titleObj,
9986      modificationDate: data.modificationDate,
9987      contentsObj: data.contentsObj,
9988      richText: data.richText,
9989      hideWrapper: true
9990    });
9991    const popup = popupElement.render();
9992    popup.style.left = container.style.width;
9993    container.appendChild(popup);
9994  }
9995
9996  _renderQuadrilaterals(className) {
9997    for (const quadrilateral of this.quadrilaterals) {
9998      quadrilateral.className = className;
9999    }
10000
10001    return this.quadrilaterals;
10002  }
10003
10004  render() {
10005    (0, _util.unreachable)("Abstract method `AnnotationElement.render` called");
10006  }
10007
10008  _getElementsByName(name, skipId = null) {
10009    const fields = [];
10010
10011    if (this._fieldObjects) {
10012      const fieldObj = this._fieldObjects[name];
10013
10014      if (fieldObj) {
10015        for (const {
10016          page,
10017          id,
10018          exportValues
10019        } of fieldObj) {
10020          if (page === -1) {
10021            continue;
10022          }
10023
10024          if (id === skipId) {
10025            continue;
10026          }
10027
10028          const exportValue = typeof exportValues === "string" ? exportValues : null;
10029          const domElement = document.getElementById(id);
10030
10031          if (domElement && !GetElementsByNameSet.has(domElement)) {
10032            (0, _util.warn)(`_getElementsByName - element not allowed: ${id}`);
10033            continue;
10034          }
10035
10036          fields.push({
10037            id,
10038            exportValue,
10039            domElement
10040          });
10041        }
10042      }
10043
10044      return fields;
10045    }
10046
10047    for (const domElement of document.getElementsByName(name)) {
10048      const {
10049        id,
10050        exportValue
10051      } = domElement;
10052
10053      if (id === skipId) {
10054        continue;
10055      }
10056
10057      if (!GetElementsByNameSet.has(domElement)) {
10058        continue;
10059      }
10060
10061      fields.push({
10062        id,
10063        exportValue,
10064        domElement
10065      });
10066    }
10067
10068    return fields;
10069  }
10070
10071  static get platform() {
10072    const platform = typeof navigator !== "undefined" ? navigator.platform : "";
10073    return (0, _util.shadow)(this, "platform", {
10074      isWin: platform.includes("Win"),
10075      isMac: platform.includes("Mac")
10076    });
10077  }
10078
10079}
10080
10081class LinkAnnotationElement extends AnnotationElement {
10082  constructor(parameters, options = null) {
10083    const isRenderable = !!(parameters.data.url || parameters.data.dest || parameters.data.action || parameters.data.isTooltipOnly || parameters.data.resetForm || parameters.data.actions && (parameters.data.actions.Action || parameters.data.actions["Mouse Up"] || parameters.data.actions["Mouse Down"]));
10084    super(parameters, {
10085      isRenderable,
10086      ignoreBorder: !!options?.ignoreBorder,
10087      createQuadrilaterals: true
10088    });
10089  }
10090
10091  render() {
10092    const {
10093      data,
10094      linkService
10095    } = this;
10096    const link = document.createElement("a");
10097
10098    if (data.url) {
10099      linkService.addLinkAttributes(link, data.url, data.newWindow);
10100    } else if (data.action) {
10101      this._bindNamedAction(link, data.action);
10102    } else if (data.dest) {
10103      this._bindLink(link, data.dest);
10104    } else {
10105      let hasClickAction = false;
10106
10107      if (data.actions && (data.actions.Action || data.actions["Mouse Up"] || data.actions["Mouse Down"]) && this.enableScripting && this.hasJSActions) {
10108        hasClickAction = true;
10109
10110        this._bindJSAction(link, data);
10111      }
10112
10113      if (data.resetForm) {
10114        this._bindResetFormAction(link, data.resetForm);
10115      } else if (!hasClickAction) {
10116        this._bindLink(link, "");
10117      }
10118    }
10119
10120    if (this.quadrilaterals) {
10121      return this._renderQuadrilaterals("linkAnnotation").map((quadrilateral, index) => {
10122        const linkElement = index === 0 ? link : link.cloneNode();
10123        quadrilateral.appendChild(linkElement);
10124        return quadrilateral;
10125      });
10126    }
10127
10128    this.container.className = "linkAnnotation";
10129    this.container.appendChild(link);
10130    return this.container;
10131  }
10132
10133  _bindLink(link, destination) {
10134    link.href = this.linkService.getDestinationHash(destination);
10135
10136    link.onclick = () => {
10137      if (destination) {
10138        this.linkService.goToDestination(destination);
10139      }
10140
10141      return false;
10142    };
10143
10144    if (destination || destination === "") {
10145      link.className = "internalLink";
10146    }
10147  }
10148
10149  _bindNamedAction(link, action) {
10150    link.href = this.linkService.getAnchorUrl("");
10151
10152    link.onclick = () => {
10153      this.linkService.executeNamedAction(action);
10154      return false;
10155    };
10156
10157    link.className = "internalLink";
10158  }
10159
10160  _bindJSAction(link, data) {
10161    link.href = this.linkService.getAnchorUrl("");
10162    const map = new Map([["Action", "onclick"], ["Mouse Up", "onmouseup"], ["Mouse Down", "onmousedown"]]);
10163
10164    for (const name of Object.keys(data.actions)) {
10165      const jsName = map.get(name);
10166
10167      if (!jsName) {
10168        continue;
10169      }
10170
10171      link[jsName] = () => {
10172        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10173          source: this,
10174          detail: {
10175            id: data.id,
10176            name
10177          }
10178        });
10179        return false;
10180      };
10181    }
10182
10183    if (!link.onclick) {
10184      link.onclick = () => false;
10185    }
10186
10187    link.className = "internalLink";
10188  }
10189
10190  _bindResetFormAction(link, resetForm) {
10191    const otherClickAction = link.onclick;
10192
10193    if (!otherClickAction) {
10194      link.href = this.linkService.getAnchorUrl("");
10195    }
10196
10197    link.className = "internalLink";
10198
10199    if (!this._fieldObjects) {
10200      (0, _util.warn)(`_bindResetFormAction - "resetForm" action not supported, ` + "ensure that the `fieldObjects` parameter is provided.");
10201
10202      if (!otherClickAction) {
10203        link.onclick = () => false;
10204      }
10205
10206      return;
10207    }
10208
10209    link.onclick = () => {
10210      if (otherClickAction) {
10211        otherClickAction();
10212      }
10213
10214      const {
10215        fields: resetFormFields,
10216        refs: resetFormRefs,
10217        include
10218      } = resetForm;
10219      const allFields = [];
10220
10221      if (resetFormFields.length !== 0 || resetFormRefs.length !== 0) {
10222        const fieldIds = new Set(resetFormRefs);
10223
10224        for (const fieldName of resetFormFields) {
10225          const fields = this._fieldObjects[fieldName] || [];
10226
10227          for (const {
10228            id
10229          } of fields) {
10230            fieldIds.add(id);
10231          }
10232        }
10233
10234        for (const fields of Object.values(this._fieldObjects)) {
10235          for (const field of fields) {
10236            if (fieldIds.has(field.id) === include) {
10237              allFields.push(field);
10238            }
10239          }
10240        }
10241      } else {
10242        for (const fields of Object.values(this._fieldObjects)) {
10243          allFields.push(...fields);
10244        }
10245      }
10246
10247      const storage = this.annotationStorage;
10248      const allIds = [];
10249
10250      for (const field of allFields) {
10251        const {
10252          id
10253        } = field;
10254        allIds.push(id);
10255
10256        switch (field.type) {
10257          case "text":
10258            {
10259              const value = field.defaultValue || "";
10260              storage.setValue(id, {
10261                value
10262              });
10263              break;
10264            }
10265
10266          case "checkbox":
10267          case "radiobutton":
10268            {
10269              const value = field.defaultValue === field.exportValues;
10270              storage.setValue(id, {
10271                value
10272              });
10273              break;
10274            }
10275
10276          case "combobox":
10277          case "listbox":
10278            {
10279              const value = field.defaultValue || "";
10280              storage.setValue(id, {
10281                value
10282              });
10283              break;
10284            }
10285
10286          default:
10287            continue;
10288        }
10289
10290        const domElement = document.getElementById(id);
10291
10292        if (!domElement || !GetElementsByNameSet.has(domElement)) {
10293          continue;
10294        }
10295
10296        domElement.dispatchEvent(new Event("resetform"));
10297      }
10298
10299      if (this.enableScripting) {
10300        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10301          source: this,
10302          detail: {
10303            id: "app",
10304            ids: allIds,
10305            name: "ResetForm"
10306          }
10307        });
10308      }
10309
10310      return false;
10311    };
10312  }
10313
10314}
10315
10316class TextAnnotationElement extends AnnotationElement {
10317  constructor(parameters) {
10318    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
10319    super(parameters, {
10320      isRenderable
10321    });
10322  }
10323
10324  render() {
10325    this.container.className = "textAnnotation";
10326    const image = document.createElement("img");
10327    image.style.height = this.container.style.height;
10328    image.style.width = this.container.style.width;
10329    image.src = this.imageResourcesPath + "annotation-" + this.data.name.toLowerCase() + ".svg";
10330    image.alt = "[{{type}} Annotation]";
10331    image.dataset.l10nId = "text_annotation_type";
10332    image.dataset.l10nArgs = JSON.stringify({
10333      type: this.data.name
10334    });
10335
10336    if (!this.data.hasPopup) {
10337      this._createPopup(image, this.data);
10338    }
10339
10340    this.container.appendChild(image);
10341    return this.container;
10342  }
10343
10344}
10345
10346class WidgetAnnotationElement extends AnnotationElement {
10347  render() {
10348    if (this.data.alternativeText) {
10349      this.container.title = this.data.alternativeText;
10350    }
10351
10352    return this.container;
10353  }
10354
10355  _getKeyModifier(event) {
10356    const {
10357      isWin,
10358      isMac
10359    } = AnnotationElement.platform;
10360    return isWin && event.ctrlKey || isMac && event.metaKey;
10361  }
10362
10363  _setEventListener(element, baseName, eventName, valueGetter) {
10364    if (baseName.includes("mouse")) {
10365      element.addEventListener(baseName, event => {
10366        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10367          source: this,
10368          detail: {
10369            id: this.data.id,
10370            name: eventName,
10371            value: valueGetter(event),
10372            shift: event.shiftKey,
10373            modifier: this._getKeyModifier(event)
10374          }
10375        });
10376      });
10377    } else {
10378      element.addEventListener(baseName, event => {
10379        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10380          source: this,
10381          detail: {
10382            id: this.data.id,
10383            name: eventName,
10384            value: valueGetter(event)
10385          }
10386        });
10387      });
10388    }
10389  }
10390
10391  _setEventListeners(element, names, getter) {
10392    for (const [baseName, eventName] of names) {
10393      if (eventName === "Action" || this.data.actions?.[eventName]) {
10394        this._setEventListener(element, baseName, eventName, getter);
10395      }
10396    }
10397  }
10398
10399  _setBackgroundColor(element) {
10400    const color = this.data.backgroundColor || null;
10401    element.style.backgroundColor = color === null ? "transparent" : _util.Util.makeHexColor(color[0], color[1], color[2]);
10402  }
10403
10404}
10405
10406class TextWidgetAnnotationElement extends WidgetAnnotationElement {
10407  constructor(parameters) {
10408    const isRenderable = parameters.renderForms || !parameters.data.hasAppearance && !!parameters.data.fieldValue;
10409    super(parameters, {
10410      isRenderable
10411    });
10412  }
10413
10414  setPropertyOnSiblings(base, key, value, keyInStorage) {
10415    const storage = this.annotationStorage;
10416
10417    for (const element of this._getElementsByName(base.name, base.id)) {
10418      if (element.domElement) {
10419        element.domElement[key] = value;
10420      }
10421
10422      storage.setValue(element.id, {
10423        [keyInStorage]: value
10424      });
10425    }
10426  }
10427
10428  render() {
10429    const storage = this.annotationStorage;
10430    const id = this.data.id;
10431    this.container.className = "textWidgetAnnotation";
10432    let element = null;
10433
10434    if (this.renderForms) {
10435      const storedData = storage.getValue(id, {
10436        value: this.data.fieldValue
10437      });
10438      const textContent = storedData.formattedValue || storedData.value || "";
10439      const elementData = {
10440        userValue: null,
10441        formattedValue: null,
10442        valueOnFocus: ""
10443      };
10444
10445      if (this.data.multiLine) {
10446        element = document.createElement("textarea");
10447        element.textContent = textContent;
10448      } else {
10449        element = document.createElement("input");
10450        element.type = "text";
10451        element.setAttribute("value", textContent);
10452      }
10453
10454      GetElementsByNameSet.add(element);
10455      element.disabled = this.data.readOnly;
10456      element.name = this.data.fieldName;
10457      element.tabIndex = DEFAULT_TAB_INDEX;
10458      elementData.userValue = textContent;
10459      element.setAttribute("id", id);
10460      element.addEventListener("input", event => {
10461        storage.setValue(id, {
10462          value: event.target.value
10463        });
10464        this.setPropertyOnSiblings(element, "value", event.target.value, "value");
10465      });
10466      element.addEventListener("resetform", event => {
10467        const defaultValue = this.data.defaultFieldValue ?? "";
10468        element.value = elementData.userValue = defaultValue;
10469        elementData.formattedValue = null;
10470      });
10471
10472      let blurListener = event => {
10473        const {
10474          formattedValue
10475        } = elementData;
10476
10477        if (formattedValue !== null && formattedValue !== undefined) {
10478          event.target.value = formattedValue;
10479        }
10480
10481        event.target.scrollLeft = 0;
10482      };
10483
10484      if (this.enableScripting && this.hasJSActions) {
10485        element.addEventListener("focus", event => {
10486          if (elementData.userValue) {
10487            event.target.value = elementData.userValue;
10488          }
10489
10490          elementData.valueOnFocus = event.target.value;
10491        });
10492        element.addEventListener("updatefromsandbox", jsEvent => {
10493          const actions = {
10494            value(event) {
10495              elementData.userValue = event.detail.value ?? "";
10496              storage.setValue(id, {
10497                value: elementData.userValue.toString()
10498              });
10499              event.target.value = elementData.userValue;
10500            },
10501
10502            formattedValue(event) {
10503              const {
10504                formattedValue
10505              } = event.detail;
10506              elementData.formattedValue = formattedValue;
10507
10508              if (formattedValue !== null && formattedValue !== undefined && event.target !== document.activeElement) {
10509                event.target.value = formattedValue;
10510              }
10511
10512              storage.setValue(id, {
10513                formattedValue
10514              });
10515            },
10516
10517            selRange(event) {
10518              event.target.setSelectionRange(...event.detail.selRange);
10519            }
10520
10521          };
10522
10523          this._dispatchEventFromSandbox(actions, jsEvent);
10524        });
10525        element.addEventListener("keydown", event => {
10526          let commitKey = -1;
10527
10528          if (event.key === "Escape") {
10529            commitKey = 0;
10530          } else if (event.key === "Enter") {
10531            commitKey = 2;
10532          } else if (event.key === "Tab") {
10533            commitKey = 3;
10534          }
10535
10536          if (commitKey === -1) {
10537            return;
10538          }
10539
10540          const {
10541            value
10542          } = event.target;
10543
10544          if (elementData.valueOnFocus === value) {
10545            return;
10546          }
10547
10548          elementData.userValue = value;
10549          this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10550            source: this,
10551            detail: {
10552              id,
10553              name: "Keystroke",
10554              value,
10555              willCommit: true,
10556              commitKey,
10557              selStart: event.target.selectionStart,
10558              selEnd: event.target.selectionEnd
10559            }
10560          });
10561        });
10562        const _blurListener = blurListener;
10563        blurListener = null;
10564        element.addEventListener("blur", event => {
10565          const {
10566            value
10567          } = event.target;
10568          elementData.userValue = value;
10569
10570          if (this._mouseState.isDown && elementData.valueOnFocus !== value) {
10571            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10572              source: this,
10573              detail: {
10574                id,
10575                name: "Keystroke",
10576                value,
10577                willCommit: true,
10578                commitKey: 1,
10579                selStart: event.target.selectionStart,
10580                selEnd: event.target.selectionEnd
10581              }
10582            });
10583          }
10584
10585          _blurListener(event);
10586        });
10587
10588        if (this.data.actions?.Keystroke) {
10589          element.addEventListener("beforeinput", event => {
10590            const {
10591              data,
10592              target
10593            } = event;
10594            const {
10595              value,
10596              selectionStart,
10597              selectionEnd
10598            } = target;
10599            let selStart = selectionStart,
10600                selEnd = selectionEnd;
10601
10602            switch (event.inputType) {
10603              case "deleteWordBackward":
10604                {
10605                  const match = value.substring(0, selectionStart).match(/\w*[^\
10605w]*$/);
10606
10607                  if (match) {
10608                    selStart -= match[0].length;
10609                  }
10610
10611                  break;
10612                }
10613
10614              case "deleteWordForward":
10615                {
10616                  const match = value.substring(selectionStart).match(/^[^\w]*\w*/);
10617
10618                  if (match) {
10619                    selEnd += match[0].length;
10620                  }
10621
10622                  break;
10623                }
10624
10625              case "deleteContentBackward":
10626                if (selectionStart === selectionEnd) {
10627                  selStart -= 1;
10628                }
10629
10630                break;
10631
10632              case "deleteContentForward":
10633                if (selectionStart === selectionEnd) {
10634                  selEnd += 1;
10635                }
10636
10637                break;
10638            }
10639
10640            event.preventDefault();
10641            this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
10642              source: this,
10643              detail: {
10644                id,
10645                name: "Keystroke",
10646                value,
10647                change: data || "",
10648                willCommit: false,
10649                selStart,
10650                selEnd
10651              }
10652            });
10653          });
10654        }
10655
10656        this._setEventListeners(element, [["focus", "Focus"], ["blur", "Blur"], ["mousedown", "Mouse Down"], ["mouseenter", "Mouse Enter"], ["mouseleave", "Mouse Exit"], ["mouseup", "Mouse Up"]], event => event.target.value);
10657      }
10658
10659      if (blurListener) {
10660        element.addEventListener("blur", blurListener);
10661      }
10662
10663      if (this.data.maxLen !== null) {
10664        element.maxLength = this.data.maxLen;
10665      }
10666
10667      if (this.data.comb) {
10668        const fieldWidth = this.data.rect[2] - this.data.rect[0];
10669        const combWidth = fieldWidth / this.data.maxLen;
10670        element.classList.add("comb");
10671        element.style.letterSpacing = `calc(${combWidth}px - 1ch)`;
10672      }
10673    } else {
10674      element = document.createElement("div");
10675      element.textContent = this.data.fieldValue;
10676      element.style.verticalAlign = "middle";
10677      element.style.display = "table-cell";
10678    }
10679
10680    this._setTextStyle(element);
10681
10682    this._setBackgroundColor(element);
10683
10684    this._setDefaultPropertiesFromJS(element);
10685
10686    this.container.appendChild(element);
10687    return this.container;
10688  }
10689
10690  _setTextStyle(element) {
10691    const TEXT_ALIGNMENT = ["left", "center", "right"];
10692    const {
10693      fontSize,
10694      fontColor
10695    } = this.data.defaultAppearanceData;
10696    const style = element.style;
10697
10698    if (fontSize) {
10699      style.fontSize = `${fontSize}px`;
10700    }
10701
10702    style.color = _util.Util.makeHexColor(fontColor[0], fontColor[1], fontColor[2]);
10703
10704    if (this.data.textAlignment !== null) {
10705      style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment];
10706    }
10707  }
10708
10709}
10710
10711class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement {
10712  constructor(parameters) {
10713    super(parameters, {
10714      isRenderable: parameters.renderForms
10715    });
10716  }
10717
10718  render() {
10719    const storage = this.annotationStorage;
10720    const data = this.data;
10721    const id = data.id;
10722    let value = storage.getValue(id, {
10723      value: data.exportValue === data.fieldValue
10724    }).value;
10725
10726    if (typeof value === "string") {
10727      value = value !== "Off";
10728      storage.setValue(id, {
10729        value
10730      });
10731    }
10732
10733    this.container.className = "buttonWidgetAnnotation checkBox";
10734    const element = document.createElement("input");
10735    GetElementsByNameSet.add(element);
10736    element.disabled = data.readOnly;
10737    element.type = "checkbox";
10738    element.name = data.fieldName;
10739
10740    if (value) {
10741      element.setAttribute("checked", true);
10742    }
10743
10744    element.setAttribute("id", id);
10745    element.setAttribute("exportValue", data.exportValue);
10746    element.tabIndex = DEFAULT_TAB_INDEX;
10747    element.addEventListener("change", event => {
10748      const {
10749        name,
10750        checked
10751      } = event.target;
10752
10753      for (const checkbox of this._getElementsByName(name, id)) {
10754        const curChecked = checked && checkbox.exportValue === data.exportValue;
10755
10756        if (checkbox.domElement) {
10757          checkbox.domElement.checked = curChecked;
10758        }
10759
10760        storage.setValue(checkbox.id, {
10761          value: curChecked
10762        });
10763      }
10764
10765      storage.setValue(id, {
10766        value: checked
10767      });
10768    });
10769    element.addEventListener("resetform", event => {
10770      const defaultValue = data.defaultFieldValue || "Off";
10771      event.target.checked = defaultValue === data.exportValue;
10772    });
10773
10774    if (this.enableScripting && this.hasJSActions) {
10775      element.addEventListener("updatefromsandbox", jsEvent => {
10776        const actions = {
10777          value(event) {
10778            event.target.checked = event.detail.value !== "Off";
10779            storage.setValue(id, {
10780              value: event.target.checked
10781            });
10782          }
10783
10784        };
10785
10786        this._dispatchEventFromSandbox(actions, jsEvent);
10787      });
10788
10789      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);
10790    }
10791
10792    this._setBackgroundColor(element);
10793
10794    this._setDefaultPropertiesFromJS(element);
10795
10796    this.container.appendChild(element);
10797    return this.container;
10798  }
10799
10800}
10801
10802class RadioButtonWidgetAnnotationElement extends WidgetAnnotationElement {
10803  constructor(parameters) {
10804    super(parameters, {
10805      isRenderable: parameters.renderForms
10806    });
10807  }
10808
10809  render() {
10810    this.container.className = "buttonWidgetAnnotation radioButton";
10811    const storage = this.annotationStorage;
10812    const data = this.data;
10813    const id = data.id;
10814    let value = storage.getValue(id, {
10815      value: data.fieldValue === data.buttonValue
10816    }).value;
10817
10818    if (typeof value === "string") {
10819      value = value !== data.buttonValue;
10820      storage.setValue(id, {
10821        value
10822      });
10823    }
10824
10825    const element = document.createElement("input");
10826    GetElementsByNameSet.add(element);
10827    element.disabled = data.readOnly;
10828    element.type = "radio";
10829    element.name = data.fieldName;
10830
10831    if (value) {
10832      element.setAttribute("checked", true);
10833    }
10834
10835    element.setAttribute("id", id);
10836    element.tabIndex = DEFAULT_TAB_INDEX;
10837    element.addEventListener("change", event => {
10838      const {
10839        name,
10840        checked
10841      } = event.target;
10842
10843      for (const radio of this._getElementsByName(name, id)) {
10844        storage.setValue(radio.id, {
10845          value: false
10846        });
10847      }
10848
10849      storage.setValue(id, {
10850        value: checked
10851      });
10852    });
10853    element.addEventListener("resetform", event => {
10854      const defaultValue = data.defaultFieldValue;
10855      event.target.checked = defaultValue !== null && defaultValue !== undefined && defaultValue === data.buttonValue;
10856    });
10857
10858    if (this.enableScripting && this.hasJSActions) {
10859      const pdfButtonValue = data.buttonValue;
10860      element.addEventListener("updatefromsandbox", jsEvent => {
10861        const actions = {
10862          value: event => {
10863            const checked = pdfButtonValue === event.detail.value;
10864
10865            for (const radio of this._getElementsByName(event.target.name)) {
10866              const curChecked = checked && radio.id === id;
10867
10868              if (radio.domElement) {
10869                radio.domElement.checked = curChecked;
10870              }
10871
10872              storage.setValue(radio.id, {
10873                value: curChecked
10874              });
10875            }
10876          }
10877        };
10878
10879        this._dispatchEventFromSandbox(actions, jsEvent);
10880      });
10881
10882      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);
10883    }
10884
10885    this._setBackgroundColor(element);
10886
10887    this._setDefaultPropertiesFromJS(element);
10888
10889    this.container.appendChild(element);
10890    return this.container;
10891  }
10892
10893}
10894
10895class PushButtonWidgetAnnotationElement extends LinkAnnotationElement {
10896  constructor(parameters) {
10897    super(parameters, {
10898      ignoreBorder: parameters.data.hasAppearance
10899    });
10900  }
10901
10902  render() {
10903    const container = super.render();
10904    container.className = "buttonWidgetAnnotation pushButton";
10905
10906    if (this.data.alternativeText) {
10907      container.title = this.data.alternativeText;
10908    }
10909
10910    this._setDefaultPropertiesFromJS(container);
10911
10912    return container;
10913  }
10914
10915}
10916
10917class ChoiceWidgetAnnotationElement extends WidgetAnnotationElement {
10918  constructor(parameters) {
10919    super(parameters, {
10920      isRenderable: parameters.renderForms
10921    });
10922  }
10923
10924  render() {
10925    this.container.className = "choiceWidgetAnnotation";
10926    const storage = this.annotationStorage;
10927    const id = this.data.id;
10928    const storedData = storage.getValue(id, {
10929      value: this.data.fieldValue
10930    });
10931    let {
10932      fontSize
10933    } = this.data.defaultAppearanceData;
10934
10935    if (!fontSize) {
10936      fontSize = 9;
10937    }
10938
10939    const fontSizeStyle = `calc(${fontSize}px * var(--zoom-factor))`;
10940    const selectElement = document.createElement("select");
10941    GetElementsByNameSet.add(selectElement);
10942    selectElement.disabled = this.data.readOnly;
10943    selectElement.name = this.data.fieldName;
10944    selectElement.setAttribute("id", id);
10945    selectElement.tabIndex = DEFAULT_TAB_INDEX;
10946    selectElement.style.fontSize = `${fontSize}px`;
10947
10948    if (!this.data.combo) {
10949      selectElement.size = this.data.options.length;
10950
10951      if (this.data.multiSelect) {
10952        selectElement.multiple = true;
10953      }
10954    }
10955
10956    selectElement.addEventListener("resetform", event => {
10957      const defaultValue = this.data.defaultFieldValue;
10958
10959      for (const option of selectElement.options) {
10960        option.selected = option.value === defaultValue;
10961      }
10962    });
10963
10964    for (const option of this.data.options) {
10965      const optionElement = document.createElement("option");
10966      optionElement.textContent = option.displayValue;
10967      optionElement.value = option.exportValue;
10968
10969      if (this.data.combo) {
10970        optionElement.style.fontSize = fontSizeStyle;
10971      }
10972
10973      if (storedData.value.includes(option.exportValue)) {
10974        optionElement.setAttribute("selected", true);
10975      }
10976
10977      selectElement.appendChild(optionElement);
10978    }
10979
10980    const getValue = (event, isExport) => {
10981      const name = isExport ? "value" : "textContent";
10982      const options = event.target.options;
10983
10984      if (!event.target.multiple) {
10985        return options.selectedIndex === -1 ? null : options[options.selectedIndex][name];
10986      }
10987
10988      return Array.prototype.filter.call(options, option => option.selected).map(option => option[name]);
10989    };
10990
10991    const getItems = event => {
10992      const options = event.target.options;
10993      return Array.prototype.map.call(options, option => {
10994        return {
10995          displayValue: option.textContent,
10996          exportValue: option.value
10997        };
10998      });
10999    };
11000
11001    if (this.enableScripting && this.hasJSActions) {
11002      selectElement.addEventListener("updatefromsandbox", jsEvent => {
11003        const actions = {
11004          value(event) {
11005            const value = event.detail.value;
11006            const values = new Set(Array.isArray(value) ? value : [value]);
11007
11008            for (const option of selectElement.options) {
11009              option.selected = values.has(option.value);
11010            }
11011
11012            storage.setValue(id, {
11013              value: getValue(event, true)
11014            });
11015          },
11016
11017          multipleSelection(event) {
11018            selectElement.multiple = true;
11019          },
11020
11021          remove(event) {
11022            const options = selectElement.options;
11023            const index = event.detail.remove;
11024            options[index].selected = false;
11025            selectElement.remove(index);
11026
11027            if (options.length > 0) {
11028              const i = Array.prototype.findIndex.call(options, option => option.selected);
11029
11030              if (i === -1) {
11031                options[0].selected = true;
11032              }
11033            }
11034
11035            storage.setValue(id, {
11036              value: getValue(event, true),
11037              items: getItems(event)
11038            });
11039          },
11040
11041          clear(event) {
11042            while (selectElement.length !== 0) {
11043              selectElement.remove(0);
11044            }
11045
11046            storage.setValue(id, {
11047              value: null,
11048              items: []
11049            });
11050          },
11051
11052          insert(event) {
11053            const {
11054              index,
11055              displayValue,
11056              exportValue
11057            } = event.detail.insert;
11058            const optionElement = document.createElement("option");
11059            optionElement.textContent = displayValue;
11060            optionElement.value = exportValue;
11061            selectElement.insertBefore(optionElement, selectElement.children[index]);
11062            storage.setValue(id, {
11063              value: getValue(event, true),
11064              items: getItems(event)
11065            });
11066          },
11067
11068          items(event) {
11069            const {
11070              items
11071            } = event.detail;
11072
11073            while (selectElement.length !== 0) {
11074              selectElement.remove(0);
11075            }
11076
11077            for (const item of items) {
11078              const {
11079                displayValue,
11080                exportValue
11081              } = item;
11082              const optionElement = document.createElement("option");
11083              optionElement.textContent = displayValue;
11084              optionElement.value = exportValue;
11085              selectElement.appendChild(optionElement);
11086            }
11087
11088            if (selectElement.options.length > 0) {
11089              selectElement.options[0].selected = true;
11090            }
11091
11092            storage.setValue(id, {
11093              value: getValue(event, true),
11094              items: getItems(event)
11095            });
11096          },
11097
11098          indices(event) {
11099            const indices = new Set(event.detail.indices);
11100
11101            for (const option of event.target.options) {
11102              option.selected = indices.has(option.index);
11103            }
11104
11105            storage.setValue(id, {
11106              value: getValue(event, true)
11107            });
11108          },
11109
11110          editable(event) {
11111            event.target.disabled = !event.detail.editable;
11112          }
11113
11114        };
11115
11116        this._dispatchEventFromSandbox(actions, jsEvent);
11117      });
11118      selectElement.addEventListener("input", event => {
11119        const exportValue = getValue(event, true);
11120        const value = getValue(event, false);
11121        storage.setValue(id, {
11122          value: exportValue
11123        });
11124        this.linkService.eventBus?.dispatch("dispatcheventinsandbox", {
11125          source: this,
11126          detail: {
11127            id,
11128            name: "Keystroke",
11129            value,
11130            changeEx: exportValue,
11131            willCommit: true,
11132            commitKey: 1,
11133            keyDown: false
11134          }
11135        });
11136      });
11137
11138      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);
11139    } else {
11140      selectElement.addEventListener("input", function (event) {
11141        storage.setValue(id, {
11142          value: getValue(event, true)
11143        });
11144      });
11145    }
11146
11147    this._setBackgroundColor(selectElement);
11148
11149    this._setDefaultPropertiesFromJS(selectElement);
11150
11151    this.container.appendChild(selectElement);
11152    return this.container;
11153  }
11154
11155}
11156
11157class PopupAnnotationElement extends AnnotationElement {
11158  constructor(parameters) {
11159    const isRenderable = !!(parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11160    super(parameters, {
11161      isRenderable
11162    });
11163  }
11164
11165  render() {
11166    const IGNORE_TYPES = ["Line", "Square", "Circle", "PolyLine", "Polygon", "Ink"];
11167    this.container.className = "popupAnnotation";
11168
11169    if (IGNORE_TYPES.includes(this.data.parentType)) {
11170      return this.container;
11171    }
11172
11173    const selector = `[data-annotation-id="${this.data.parentId}"]`;
11174    const parentElements = this.layer.querySelectorAll(selector);
11175
11176    if (parentElements.length === 0) {
11177      return this.container;
11178    }
11179
11180    const popup = new PopupElement({
11181      container: this.container,
11182      trigger: Array.from(parentElements),
11183      color: this.data.color,
11184      titleObj: this.data.titleObj,
11185      modificationDate: this.data.modificationDate,
11186      contentsObj: this.data.contentsObj,
11187      richText: this.data.richText
11188    });
11189    const page = this.page;
11190
11191    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]]);
11192
11193    const popupLeft = rect[0] + this.data.parentRect[2] - this.data.parentRect[0];
11194    const popupTop = rect[1];
11195    this.container.style.transformOrigin = `${-popupLeft}px ${-popupTop}
11195px`;
11196    this.container.style.left = `${popupLeft}px`;
11197    this.container.style.top = `${popupTop}px`;
11198    this.container.appendChild(popup.render());
11199    return this.container;
11200  }
11201
11202}
11203
11204class PopupElement {
11205  constructor(parameters) {
11206    this.container = parameters.container;
11207    this.trigger = parameters.trigger;
11208    this.color = parameters.color;
11209    this.titleObj = parameters.titleObj;
11210    this.modificationDate = parameters.modificationDate;
11211    this.contentsObj = parameters.contentsObj;
11212    this.richText = parameters.richText;
11213    this.hideWrapper = parameters.hideWrapper || false;
11214    this.pinned = false;
11215  }
11216
11217  render() {
11218    const BACKGROUND_ENLIGHT = 0.7;
11219    const wrapper = document.createElement("div");
11220    wrapper.className = "popupWrapper";
11221    this.hideElement = this.hideWrapper ? wrapper : this.container;
11222    this.hideElement.hidden = true;
11223    const popup = document.createElement("div");
11224    popup.className = "popup";
11225    const color = this.color;
11226
11227    if (color) {
11228      const r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0];
11229      const g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1];
11230      const b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2];
11231      popup.style.backgroundColor = _util.Util.makeHexColor(r | 0, g | 0, b | 0);
11232    }
11233
11234    const title = document.createElement("h1");
11235    title.dir = this.titleObj.dir;
11236    title.textContent = this.titleObj.str;
11237    popup.appendChild(title);
11238
11239    const dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
11240
11241    if (dateObject) {
11242      const modificationDate = document.createElement("span");
11243      modificationDate.className = "popupDate";
11244      modificationDate.textContent = "{{date}}, {{time}}";
11245      modificationDate.dataset.l10nId = "annotation_date_string";
11246      modificationDate.dataset.l10nArgs = JSON.stringify({
11247        date: dateObject.toLocaleDateString(),
11248        time: dateObject.toLocaleTimeString()
11249      });
11250      popup.appendChild(modificationDate);
11251    }
11252
11253    if (this.richText?.str && (!this.contentsObj?.str || this.contentsObj.str === this.richText.str)) {
11254      _xfa_layer.XfaLayer.render({
11255        xfaHtml: this.richText.html,
11256        intent: "richText",
11257        div: popup
11258      });
11259
11260      popup.lastChild.className = "richText popupContent";
11261    } else {
11262      const contents = this._formatContents(this.contentsObj);
11263
11264      popup.appendChild(contents);
11265    }
11266
11267    if (!Array.isArray(this.trigger)) {
11268      this.trigger = [this.trigger];
11269    }
11270
11271    for (const element of this.trigger) {
11272      element.addEventListener("click", this._toggle.bind(this));
11273      element.addEventListener("mouseover", this._show.bind(this, false));
11274      element.addEventListener("mouseout", this._hide.bind(this, false));
11275    }
11276
11277    popup.addEventListener("click", this._hide.bind(this, true));
11278    wrapper.appendChild(popup);
11279    return wrapper;
11280  }
11281
11282  _formatContents({
11283    str,
11284    dir
11285  }) {
11286    const p = document.createElement("p");
11287    p.className = "popupContent";
11288    p.dir = dir;
11289    const lines = str.split(/(?:\r\n?|\n)/);
11290
11291    for (let i = 0, ii = lines.length; i < ii; ++i) {
11292      const line = lines[i];
11293      p.appendChild(document.createTextNode(line));
11294
11295      if (i < ii - 1) {
11296        p.appendChild(document.createElement("br"));
11297      }
11298    }
11299
11300    return p;
11301  }
11302
11303  _toggle() {
11304    if (this.pinned) {
11305      this._hide(true);
11306    } else {
11307      this._show(true);
11308    }
11309  }
11310
11311  _show(pin = false) {
11312    if (pin) {
11313      this.pinned = true;
11314    }
11315
11316    if (this.hideElement.hidden) {
11317      this.hideElement.hidden = false;
11318      this.container.style.zIndex += 1;
11319    }
11320  }
11321
11322  _hide(unpin = true) {
11323    if (unpin) {
11324      this.pinned = false;
11325    }
11326
11327    if (!this.hideElement.hidden && !this.pinned) {
11328      this.hideElement.hidden = true;
11329      this.container.style.zIndex -= 1;
11330    }
11331  }
11332
11333}
11334
11335class FreeTextAnnotationElement extends AnnotationElement {
11336  constructor(parameters) {
11337    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11338    super(parameters, {
11339      isRenderable,
11340      ignoreBorder: true
11341    });
11342  }
11343
11344  render() {
11345    this.container.className = "freeTextAnnotation";
11346
11347    if (!this.data.hasPopup) {
11348      this._createPopup(null, this.data);
11349    }
11350
11351    return this.container;
11352  }
11353
11354}
11355
11356class LineAnnotationElement extends AnnotationElement {
11357  constructor(parameters) {
11358    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11359    super(parameters, {
11360      isRenderable,
11361      ignoreBorder: true
11362    });
11363  }
11364
11365  render() {
11366    this.container.className = "lineAnnotation";
11367    const data = this.data;
11368    const {
11369      width,
11370      height
11371    } = getRectDims(data.rect);
11372    const svg = this.svgFactory.create(width, height);
11373    const line = this.svgFactory.createElement("svg:line");
11374    line.setAttribute("x1", data.rect[2] - data.lineCoordinates[0]);
11375    line.setAttribute("y1", data.rect[3] - data.lineCoordinates[1]);
11376    line.setAttribute("x2", data.rect[2] - data.lineCoordinates[2]);
11377    line.setAttribute("y2", data.rect[3] - data.lineCoordinates[3]);
11378    line.setAttribute("stroke-width", data.borderStyle.width || 1);
11379    line.setAttribute("stroke", "transparent");
11380    line.setAttribute("fill", "transparent");
11381    svg.appendChild(line);
11382    this.container.append(svg);
11383
11384    this._createPopup(line, data);
11385
11386    return this.container;
11387  }
11388
11389}
11390
11391class SquareAnnotationElement extends AnnotationElement {
11392  constructor(parameters) {
11393    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11394    super(parameters, {
11395      isRenderable,
11396      ignoreBorder: true
11397    });
11398  }
11399
11400  render() {
11401    this.container.className = "squareAnnotation";
11402    const data = this.data;
11403    const {
11404      width,
11405      height
11406    } = getRectDims(data.rect);
11407    const svg = this.svgFactory.create(width, height);
11408    const borderWidth = data.borderStyle.width;
11409    const square = this.svgFactory.createElement("svg:rect");
11410    square.setAttribute("x", borderWidth / 2);
11411    square.setAttribute("y", borderWidth / 2);
11412    square.setAttribute("width", width - borderWidth);
11413    square.setAttribute("height", height - borderWidth);
11414    square.setAttribute("stroke-width", borderWidth || 1);
11415    square.setAttribute("stroke", "transparent");
11416    square.setAttribute("fill", "transparent");
11417    svg.appendChild(square);
11418    this.container.append(svg);
11419
11420    this._createPopup(square, data);
11421
11422    return this.container;
11423  }
11424
11425}
11426
11427class CircleAnnotationElement extends AnnotationElement {
11428  constructor(parameters) {
11429    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11430    super(parameters, {
11431      isRenderable,
11432      ignoreBorder: true
11433    });
11434  }
11435
11436  render() {
11437    this.container.className = "circleAnnotation";
11438    const data = this.data;
11439    const {
11440      width,
11441      height
11442    } = getRectDims(data.rect);
11443    const svg = this.svgFactory.create(width, height);
11444    const borderWidth = data.borderStyle.width;
11445    const circle = this.svgFactory.createElement("svg:ellipse");
11446    circle.setAttribute("cx", width / 2);
11447    circle.setAttribute("cy", height / 2);
11448    circle.setAttribute("rx", width / 2 - borderWidth / 2);
11449    circle.setAttribute("ry", height / 2 - borderWidth / 2);
11450    circle.setAttribute("stroke-width", borderWidth || 1);
11451    circle.setAttribute("stroke", "transparent");
11452    circle.setAttribute("fill", "transparent");
11453    svg.appendChild(circle);
11454    this.container.append(svg);
11455
11456    this._createPopup(circle, data);
11457
11458    return this.container;
11459  }
11460
11461}
11462
11463class PolylineAnnotationElement extends AnnotationElement {
11464  constructor(parameters) {
11465    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11466    super(parameters, {
11467      isRenderable,
11468      ignoreBorder: true
11469    });
11470    this.containerClassName = "polylineAnnotation";
11471    this.svgElementName = "svg:polyline";
11472  }
11473
11474  render() {
11475    this.container.className = this.containerClassName;
11476    const data = this.data;
11477    const {
11478      width,
11479      height
11480    } = getRectDims(data.rect);
11481    const svg = this.svgFactory.create(width, height);
11482    let points = [];
11483
11484    for (const coordinate of data.vertices) {
11485      const x = coordinate.x - data.rect[0];
11486      const y = data.rect[3] - coordinate.y;
11487      points.push(x + "," + y);
11488    }
11489
11490    points = points.join(" ");
11491    const polyline = this.svgFactory.createElement(this.svgElementName);
11492    polyline.setAttribute("points", points);
11493    polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
11494    polyline.setAttribute("stroke", "transparent");
11495    polyline.setAttribute("fill", "transparent");
11496    svg.appendChild(polyline);
11497    this.container.append(svg);
11498
11499    this._createPopup(polyline, data);
11500
11501    return this.container;
11502  }
11503
11504}
11505
11506class PolygonAnnotationElement extends PolylineAnnotationElement {
11507  constructor(parameters) {
11508    super(parameters);
11509    this.containerClassName = "polygonAnnotation";
11510    this.svgElementName = "svg:polygon";
11511  }
11512
11513}
11514
11515class CaretAnnotationElement extends AnnotationElement {
11516  constructor(parameters) {
11517    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11518    super(parameters, {
11519      isRenderable,
11520      ignoreBorder: true
11521    });
11522  }
11523
11524  render() {
11525    this.container.className = "caretAnnotation";
11526
11527    if (!this.data.hasPopup) {
11528      this._createPopup(null, this.data);
11529    }
11530
11531    return this.container;
11532  }
11533
11534}
11535
11536class InkAnnotationElement extends AnnotationElement {
11537  constructor(parameters) {
11538    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11539    super(parameters, {
11540      isRenderable,
11541      ignoreBorder: true
11542    });
11543    this.containerClassName = "inkAnnotation";
11544    this.svgElementName = "svg:polyline";
11545  }
11546
11547  render() {
11548    this.container.className = this.containerClassName;
11549    const data = this.data;
11550    const {
11551      width,
11552      height
11553    } = getRectDims(data.rect);
11554    const svg = this.svgFactory.create(width, height);
11555
11556    for (const inkList of data.inkLists) {
11557      let points = [];
11558
11559      for (const coordinate of inkList) {
11560        const x = coordinate.x - data.rect[0];
11561        const y = data.rect[3] - coordinate.y;
11562        points.push(`${x},${y}`);
11563      }
11564
11565      points = points.join(" ");
11566      const polyline = this.svgFactory.createElement(this.svgElementName);
11567      polyline.setAttribute("points", points);
11568      polyline.setAttribute("stroke-width", data.borderStyle.width || 1);
11569      polyline.setAttribute("stroke", "transparent");
11570      polyline.setAttribute("fill", "transparent");
11571
11572      this._createPopup(polyline, data);
11573
11574      svg.appendChild(polyline);
11575    }
11576
11577    this.container.append(svg);
11578    return this.container;
11579  }
11580
11581}
11582
11583class HighlightAnnotationElement extends AnnotationElement {
11584  constructor(parameters) {
11585    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11586    super(parameters, {
11587      isRenderable,
11588      ignoreBorder: true,
11589      createQuadrilaterals: true
11590    });
11591  }
11592
11593  render() {
11594    if (!this.data.hasPopup) {
11595      this._createPopup(null, this.data);
11596    }
11597
11598    if (this.quadrilaterals) {
11599      return this._renderQuadrilaterals("highlightAnnotation");
11600    }
11601
11602    this.container.className = "highlightAnnotation";
11603    return this.container;
11604  }
11605
11606}
11607
11608class UnderlineAnnotationElement extends AnnotationElement {
11609  constructor(parameters) {
11610    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11611    super(parameters, {
11612      isRenderable,
11613      ignoreBorder: true,
11614      createQuadrilaterals: true
11615    });
11616  }
11617
11618  render() {
11619    if (!this.data.hasPopup) {
11620      this._createPopup(null, this.data);
11621    }
11622
11623    if (this.quadrilaterals) {
11624      return this._renderQuadrilaterals("underlineAnnotation");
11625    }
11626
11627    this.container.className = "underlineAnnotation";
11628    return this.container;
11629  }
11630
11631}
11632
11633class SquigglyAnnotationElement extends AnnotationElement {
11634  constructor(parameters) {
11635    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11636    super(parameters, {
11637      isRenderable,
11638      ignoreBorder: true,
11639      createQuadrilaterals: true
11640    });
11641  }
11642
11643  render() {
11644    if (!this.data.hasPopup) {
11645      this._createPopup(null, this.data);
11646    }
11647
11648    if (this.quadrilaterals) {
11649      return this._renderQuadrilaterals("squigglyAnnotation");
11650    }
11651
11652    this.container.className = "squigglyAnnotation";
11653    return this.container;
11654  }
11655
11656}
11657
11658class StrikeOutAnnotationElement extends AnnotationElement {
11659  constructor(parameters) {
11660    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11661    super(parameters, {
11662      isRenderable,
11663      ignoreBorder: true,
11664      createQuadrilaterals: true
11665    });
11666  }
11667
11668  render() {
11669    if (!this.data.hasPopup) {
11670      this._createPopup(null, this.data);
11671    }
11672
11673    if (this.quadrilaterals) {
11674      return this._renderQuadrilaterals("strikeoutAnnotation");
11675    }
11676
11677    this.container.className = "strikeoutAnnotation";
11678    return this.container;
11679  }
11680
11681}
11682
11683class StampAnnotationElement extends AnnotationElement {
11684  constructor(parameters) {
11685    const isRenderable = !!(parameters.data.hasPopup || parameters.data.titleObj?.str || parameters.data.contentsObj?.str || parameters.data.richText?.str);
11686    super(parameters, {
11687      isRenderable,
11688      ignoreBorder: true
11689    });
11690  }
11691
11692  render() {
11693    this.container.className = "stampAnnotation";
11694
11695    if (!this.data.hasPopup) {
11696      this._createPopup(null, this.data);
11697    }
11698
11699    return this.container;
11700  }
11701
11702}
11703
11704class FileAttachmentAnnotationElement extends AnnotationElement {
11705  constructor(parameters) {
11706    super(parameters, {
11707      isRenderable: true
11708    });
11709    const {
11710      filename,
11711      content
11712    } = this.data.file;
11713    this.filename = (0, _display_utils.getFilenameFromUrl)(filename);
11714    this.content = content;
11715    this.linkService.eventBus?.dispatch("fileattachmentannotation", {
11716      source: this,
11717      filename,
11718      content
11719    });
11720  }
11721
11722  render() {
11723    this.container.className = "fileAttachmentAnnotation";
11724    const trigger = document.createElement("div");
11725    trigger.style.height = this.container.style.height;
11726    trigger.style.width = this.container.style.width;
11727    trigger.addEventListener("dblclick", this._download.bind(this));
11728
11729    if (!this.data.hasPopup && (this.data.titleObj?.str || this.data.contentsObj?.str || this.data.richText)) {
11730      this._createPopup(trigger, this.data);
11731    }
11732
11733    this.container.appendChild(trigger);
11734    return this.container;
11735  }
11736
11737  _download() {
11738    this.downloadManager?.openOrDownloadData(this.container, this.content, this.filename);
11739  }
11740
11741}
11742
11743class AnnotationLayer {
11744  static render(parameters) {
11745    const sortedAnnotations = [],
11746          popupAnnotations = [];
11747
11748    for (const data of parameters.annotations) {
11749      if (!data) {
11750        continue;
11751      }
11752
11753      const {
11754        width,
11755        height
11756      } = getRectDims(data.rect);
11757
11758      if (width <= 0 || height <= 0) {
11759        continue;
11760      }
11761
11762      if (data.annotationType === _util.AnnotationType.POPUP) {
11763        popupAnnotations.push(data);
11764        continue;
11765      }
11766
11767      sortedAnnotations.push(data);
11768    }
11769
11770    if (popupAnnotations.length) {
11771      sortedAnnotations.push(...popupAnnotations);
11772    }
11773
11774    const div = parameters.div;
11775
11776    for (const data of sortedAnnotations) {
11777      const element = AnnotationElementFactory.create({
11778        data,
11779        layer: div,
11780        page: parameters.page,
11781        viewport: parameters.viewport,
11782        linkService: parameters.linkService,
11783        downloadManager: parameters.downloadManager,
11784        imageResourcesPath: parameters.imageResourcesPath || "",
11785        renderForms: parameters.renderForms !== false,
11786        svgFactory: new _display_utils.DOMSVGFactory(),
11787        annotationStorage: parameters.annotationStorage || new _annotation_storage.AnnotationStorage(),
11788        enableScripting: parameters.enableScripting,
11789        hasJSActions: parameters.hasJSActions,
11790        fieldObjects: parameters.fieldObjects,
11791        mouseState: parameters.mouseState || {
11792          isDown: false
11793        }
11794      });
11795
11796      if (element.isRenderable) {
11797        const rendered = element.render();
11798
11799        if (data.hidden) {
11800          rendered.style.visibility = "hidden";
11801        }
11802
11803        if (Array.isArray(rendered)) {
11804          for (const renderedElement of rendered) {
11805            div.appendChild(renderedElement);
11806          }
11807        } else {
11808          if (element instanceof PopupAnnotationElement) {
11809            div.prepend(rendered);
11810          } else {
11811            div.appendChild(rendered);
11812          }
11813        }
11814      }
11815    }
11816
11817    this.#setAnnotationCanvasMap(div, parameters.annotationCanvasMap);
11818  }
11819
11820  static update(parameters) {
11821    const {
11822      page,
11823      viewport,
11824      annotations,
11825      annotationCanvasMap,
11826      div
11827    } = parameters;
11828    const transform = viewport.transform;
11829    const matrix = `matrix(${transform.join(",")})`;
11830    let scale, ownMatrix;
11831
11832    for (const data of annotations) {
11833      const elements = div.querySelectorAll(`[data-annotation-id="${data.id}"]`);
11834
11835      if (elements) {
11836        for (const element of elements) {
11837          if (data.hasOwnCanvas) {
11838            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]]);
11839
11840            if (!ownMatrix) {
11841              scale = Math.abs(transform[0] || transform[1]);
11842              const ownTransform = transform.slice();
11843
11844              for (let i = 0; i < 4; i++) {
11845                ownTransform[i] = Math.sign(ownTransform[i]);
11846              }
11847
11848              ownMatrix = `matrix(${ownTransform.join(",")})`;
11849            }
11850
11851            const left = rect[0] * scale;
11852            const top = rect[1] * scale;
11853            element.style.left = `${left}px`;
11854            element.style.top = `${top}px`;
11855            element.style.transformOrigin = `${-left}px ${-top}px`;
11856            element.style.transform = ownMatrix;
11857          } else {
11858            element.style.transform = matrix;
11859          }
11860        }
11861      }
11862    }
11863
11864    this.#setAnnotationCanvasMap(div, annotationCanvasMap);
11865    div.hidden = false;
11866  }
11867
11868  static #setAnnotationCanvasMap(div, annotationCanvasMap) {
11869    if (!annotationCanvasMap) {
11870      return;
11871    }
11872
11873    for (const [id, canvas] of annotationCanvasMap) {
11874      const element = div.querySelector(`[data-annotation-id="${id}"]`);
11875
11876      if (!element) {
11877        continue;
11878      }
11879
11880      const {
11881        firstChild
11882      } = element;
11883
11884      if (firstChild.nodeName === "CANVAS") {
11885        element.replaceChild(canvas, firstChild);
11886      } else {
11887        element.insertBefore(canvas, firstChild);
11888      }
11889    }
11890
11891    annotationCanvasMap.clear();
11892  }
11893
11894}
11895
11896exports.AnnotationLayer = AnnotationLayer;
11897
11898/***/ }),
11899/* 21 */
11900/***/ ((__unused_webpack_module, exports) => {
11901
11902
11903
11904Object.defineProperty(exports, "__esModule", ({
11905  value: true
11906}));
11907exports.ColorConverters = void 0;
11908
11909function makeColorComp(n) {
11910  return Math.floor(Math.max(0, Math.min(1, n)) * 255).toString(16).padStart(2, "0");
11911}
11912
11913class ColorConverters {
11914  static CMYK_G([c, y, m, k]) {
11915    return ["G", 1 - Math.min(1, 0.3 * c + 0.59 * m + 0.11 * y + k)];
11916  }
11917
11918  static G_CMYK([g]) {
11919    return ["CMYK", 0, 0, 0, 1 - g];
11920  }
11921
11922  static G_RGB([g]) {
11923    return ["RGB", g, g, g];
11924  }
11925
11926  static G_HTML([g]) {
11927    const G = makeColorComp(g);
11928    return `#${G}${G}${G}`;
11929  }
11930
11931  static RGB_G([r, g, b]) {
11932    return ["G", 0.3 * r + 0.59 * g + 0.11 * b];
11933  }
11934
11935  static RGB_HTML([r, g, b]) {
11936    const R = makeColorComp(r);
11937    const G = makeColorComp(g);
11938    const B = makeColorComp(b);
11939    return `#${R}${G}${B}`;
11940  }
11941
11942  static T_HTML() {
11943    return "#00000000";
11944  }
11945
11946  static CMYK_RGB([c, y, m, k]) {
11947    return ["RGB", 1 - Math.min(1, c + k), 1 - Math.min(1, m + k), 1 - Math.min(1, y + k)];
11948  }
11949
11950  static CMYK_HTML(components) {
11951    return this.RGB_HTML(this.CMYK_RGB(components));
11952  }
11953
11954  static RGB_CMYK([r, g, b]) {
11955    const c = 1 - r;
11956    const m = 1 - g;
11957    const y = 1 - b;
11958    const k = Math.min(c, m, y);
11959    return ["CMYK", c, m, y, k];
11960  }
11961
11962}
11963
11964exports.ColorConverters = ColorConverters;
11965
11966/***/ }),
11967/* 22 */
11968/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
11969
11970
11971
11972Object.defineProperty(exports, "__esModule", ({
11973  value: true
11974}));
11975exports.XfaLayer = void 0;
11976
11977var _xfa_text = __w_pdfjs_require__(18);
11978
11979class XfaLayer {
11980  static setupStorage(html, id, element, storage, intent) {
11981    const storedData = storage.getValue(id, {
11982      value: null
11983    });
11984
11985    switch (element.name) {
11986      case "textarea":
11987        if (storedData.value !== null) {
11988          html.textContent = storedData.value;
11989        }
11990
11991        if (intent === "print") {
11992          break;
11993        }
11994
11995        html.addEventListener("input", event => {
11996          storage.setValue(id, {
11997            value: event.target.value
11998          });
11999        });
12000        break;
12001
12002      case "input":
12003        if (element.attributes.type === "radio" || element.attributes.type === "checkbox") {
12004          if (storedData.value === element.attributes.xfaOn) {
12005            html.setAttribute("checked", true);
12006          } else if (storedData.value === element.attributes.xfaOff) {
12007            html.removeAttribute("checked");
12008          }
12009
12010          if (intent === "print") {
12011            break;
12012          }
12013
12014          html.addEventListener("change", event => {
12015            storage.setValue(id, {
12016              value: event.target.checked ? event.target.getAttribute("xfaOn") : event.target.getAttribute("xfaOff")
12017            });
12018          });
12019        } else {
12020          if (storedData.value !== null) {
12021            html.setAttribute("value", storedData.value);
12022          }
12023
12024          if (intent === "print") {
12025            break;
12026          }
12027
12028          html.addEventListener("input", event => {
12029            storage.setValue(id, {
12030              value: event.target.value
12031            });
12032          });
12033        }
12034
12035        break;
12036
12037      case "select":
12038        if (storedData.value !== null) {
12039          for (const option of element.children) {
12040            if (option.attributes.value === storedData.value) {
12041              option.attributes.selected = true;
12042            }
12043          }
12044        }
12045
12046        html.addEventListener("input", event => {
12047          const options = event.target.options;
12048          const value = options.selectedIndex === -1 ? "" : options[options.selectedIndex].value;
12049          storage.setValue(id, {
12050            value
12051          });
12052        });
12053        break;
12054    }
12055  }
12056
12057  static setAttributes({
12058    html,
12059    element,
12060    storage = null,
12061    intent,
12062    linkService
12063  }) {
12064    const {
12065      attributes
12066    } = element;
12067    const isHTMLAnchorElement = html instanceof HTMLAnchorElement;
12068
12069    if (attributes.type === "radio") {
12070      attributes.name = `${attributes.name}-${intent}`;
12071    }
12072
12073    for (const [key, value] of Object.entries(attributes)) {
12074      if (value === null || value === undefined || key === "dataId") {
12075        continue;
12076      }
12077
12078      if (key !== "style") {
12079        if (key === "textContent") {
12080          html.textContent = value;
12081        } else if (key === "class") {
12082          if (value.length) {
12083            html.setAttribute(key, value.join(" "));
12084          }
12085        } else {
12086          if (isHTMLAnchorElement && (key === "href" || key === "newWindow")) {
12087            continue;
12088          }
12089
12090          html.setAttribute(key, value);
12091        }
12092      } else {
12093        Object.assign(html.style, value);
12094      }
12095    }
12096
12097    if (isHTMLAnchorElement) {
12098      linkService.addLinkAttributes(html, attributes.href, attributes.newWindow);
12099    }
12100
12101    if (storage && attributes.dataId) {
12102      this.setupStorage(html, attributes.dataId, element, storage);
12103    }
12104  }
12105
12106  static render(parameters) {
12107    const storage = parameters.annotationStorage;
12108    const linkService = parameters.linkService;
12109    const root = parameters.xfaHtml;
12110    const intent = parameters.intent || "display";
12111    const rootHtml = document.createElement(root.name);
12112
12113    if (root.attributes) {
12114      this.setAttributes({
12115        html: rootHtml,
12116        element: root,
12117        intent,
12118        linkService
12119      });
12120    }
12121
12122    const stack = [[root, -1, rootHtml]];
12123    const rootDiv = parameters.div;
12124    rootDiv.appendChild(rootHtml);
12125
12126    if (parameters.viewport) {
12127      const transform = `matrix(${parameters.viewport.transform.join(",")})`;
12128      rootDiv.style.transform = transform;
12129    }
12130
12131    if (intent !== "richText") {
12132      rootDiv.setAttribute("class", "xfaLayer xfaFont");
12133    }
12134
12135    const textDivs = [];
12136
12137    while (stack.length > 0) {
12138      const [parent, i, html] = stack[stack.length - 1];
12139
12140      if (i + 1 === parent.children.length) {
12141        stack.pop();
12142        continue;
12143      }
12144
12145      const child = parent.children[++stack[stack.length - 1][1]];
12146
12147      if (child === null) {
12148        continue;
12149      }
12150
12151      const {
12152        name
12153      } = child;
12154
12155      if (name === "#text") {
12156        const node = document.createTextNode(child.value);
12157        textDivs.push(node);
12158        html.appendChild(node);
12159        continue;
12160      }
12161
12162      let childHtml;
12163
12164      if (child?.attributes?.xmlns) {
12165        childHtml = document.createElementNS(child.attributes.xmlns, name);
12166      } else {
12167        childHtml = document.createElement(name);
12168      }
12169
12170      html.appendChild(childHtml);
12171
12172      if (child.attributes) {
12173        this.setAttributes({
12174          html: childHtml,
12175          element: child,
12176          storage,
12177          intent,
12178          linkService
12179        });
12180      }
12181
12182      if (child.children && child.children.length > 0) {
12183        stack.push([child, -1, childHtml]);
12184      } else if (child.value) {
12185        const node = document.createTextNode(child.value);
12186
12187        if (_xfa_text.XfaText.shouldBuildText(name)) {
12188          textDivs.push(node);
12189        }
12190
12191        childHtml.appendChild(node);
12192      }
12193    }
12194
12195    for (const el of rootDiv.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea")) {
12196      el.setAttribute("readOnly", true);
12197    }
12198
12199    return {
12200      textDivs
12201    };
12202  }
12203
12204  static update(parameters) {
12205    const transform = `matrix(${parameters.viewport.transform.join(",")})`;
12206    parameters.div.style.transform = transform;
12207    parameters.div.hidden = false;
12208  }
12209
12210}
12211
12212exports.XfaLayer = XfaLayer;
12213
12214/***/ }),
12215/* 23 */
12216/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
12217
12218
12219
12220Object.defineProperty(exports, "__esModule", ({
12221  value: true
12222}));
12223exports.renderTextLayer = renderTextLayer;
12224
12225var _util = __w_pdfjs_require__(1);
12226
12227const MAX_TEXT_DIVS_TO_RENDER = 100000;
12228const DEFAULT_FONT_SIZE = 30;
12229const DEFAULT_FONT_ASCENT = 0.8;
12230const ascentCache = new Map();
12231const AllWhitespaceRegexp = /^\s+$/g;
12232
12233function getAscent(fontFamily, ctx) {
12234  const cachedAscent = ascentCache.get(fontFamily);
12235
12236  if (cachedAscent) {
12237    return cachedAscent;
12238  }
12239
12240  ctx.save();
12241  ctx.font = `${DEFAULT_FONT_SIZE}px ${fontFamily}`;
12242  const metrics = ctx.measureText("");
12243  let ascent = metrics.fontBoundingBoxAscent;
12244  let descent = Math.abs(metrics.fontBoundingBoxDescent);
12245
12246  if (ascent) {
12247    ctx.restore();
12248    const ratio = ascent / (ascent + descent);
12249    ascentCache.set(fontFamily, ratio);
12250    return ratio;
12251  }
12252
12253  ctx.strokeStyle = "red";
12254  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
12255  ctx.strokeText("g", 0, 0);
12256  let pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
12257  descent = 0;
12258
12259  for (let i = pixels.length - 1 - 3; i >= 0; i -= 4) {
12260    if (pixels[i] > 0) {
12261      descent = Math.ceil(i / 4 / DEFAULT_FONT_SIZE);
12262      break;
12263    }
12264  }
12265
12266  ctx.clearRect(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE);
12267  ctx.strokeText("A", 0, DEFAULT_FONT_SIZE);
12268  pixels = ctx.getImageData(0, 0, DEFAULT_FONT_SIZE, DEFAULT_FONT_SIZE).data;
12269  ascent = 0;
12270
12271  for (let i = 0, ii = pixels.length; i < ii; i += 4) {
12272    if (pixels[i] > 0) {
12273      ascent = DEFAULT_FONT_SIZE - Math.floor(i / 4 / DEFAULT_FONT_SIZE);
12274      break;
12275    }
12276  }
12277
12278  ctx.restore();
12279
12280  if (ascent) {
12281    const ratio = ascent / (ascent + descent);
12282    ascentCache.set(fontFamily, ratio);
12283    return ratio;
12284  }
12285
12286  ascentCache.set(fontFamily, DEFAULT_FONT_ASCENT);
12287  return DEFAULT_FONT_ASCENT;
12288}
12289
12290function appendText(task, geom, styles, ctx) {
12291  const textDiv = document.createElement("span");
12292  const textDivProperties = task._enhanceTextSelection ? {
12293    angle: 0,
12294    canvasWidth: 0,
12295    hasText: geom.str !== "",
12296    hasEOL: geom.hasEOL,
12297    originalTransform: null,
12298    paddingBottom: 0,
12299    paddingLeft: 0,
12300    paddingRight: 0,
12301    paddingTop: 0,
12302    scale: 1
12303  } : {
12304    angle: 0,
12305    canvasWidth: 0,
12306    hasText: geom.str !== "",
12307    hasEOL: geom.hasEOL
12308  };
12309
12310  task._textDivs.push(textDiv);
12311
12312  const tx = _util.Util.transform(task._viewport.transform, geom.transform);
12313
12314  let angle = Math.atan2(tx[1], tx[0]);
12315  const style = styles[geom.fontName];
12316
12317  if (style.vertical) {
12318    angle += Math.PI / 2;
12319  }
12320
12321  const fontHeight = Math.hypot(tx[2], tx[3]);
12322  const fontAscent = fontHeight * getAscent(style.fontFamily, ctx);
12323  let left, top;
12324
12325  if (angle === 0) {
12326    left = tx[4];
12327    top = tx[5] - fontAscent;
12328  } else {
12329    left = tx[4] + fontAscent * Math.sin(angle);
12330    top = tx[5] - fontAscent * Math.cos(angle);
12331  }
12332
12333  textDiv.style.left = `${left}px`;
12334  textDiv.style.top = `${top}px`;
12335  textDiv.style.fontSize = `${fontHeight}px`;
12336  textDiv.style.fontFamily = style.fontFamily;
12337  textDiv.setAttribute("role", "presentation");
12338  textDiv.textContent = geom.str;
12339  textDiv.dir = geom.dir;
12340
12341  if (task._fontInspectorEnabled) {
12342    textDiv.dataset.fontName = geom.fontName;
12343  }
12344
12345  if (angle !== 0) {
12346    textDivProperties.angle = angle * (180 / Math.PI);
12347  }
12348
12349  let shouldScaleText = false;
12350
12351  if (geom.str.length > 1 || task._enhanceTextSelection && AllWhitespaceRegexp.test(geom.str)) {
12352    shouldScaleText = true;
12353  } else if (geom.str !== " " && geom.transform[0] !== geom.transform[3]) {
12354    const absScaleX = Math.abs(geom.transform[0]),
12355          absScaleY = Math.abs(geom.transform[3]);
12356
12357    if (absScaleX !== absScaleY && Math.max(absScaleX, absScaleY) / Math.min(absScaleX, absScaleY) > 1.5) {
12358      shouldScaleText = true;
12359    }
12360  }
12361
12362  if (shouldScaleText) {
12363    if (style.vertical) {
12364      textDivProperties.canvasWidth = geom.height * task._viewport.scale;
12365    } else {
12366      textDivProperties.canvasWidth = geom.width * task._viewport.scale;
12367    }
12368  }
12369
12370  task._textDivProperties.set(textDiv, textDivProperties);
12371
12372  if (task._textContentStream) {
12373    task._layoutText(textDiv);
12374  }
12375
12376  if (task._enhanceTextSelection && textDivProperties.hasText) {
12377    let angleCos = 1,
12378        angleSin = 0;
12379
12380    if (angle !== 0) {
12381      angleCos = Math.cos(angle);
12382      angleSin = Math.sin(angle);
12383    }
12384
12385    const divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale;
12386    const divHeight = fontHeight;
12387    let m, b;
12388
12389    if (angle !== 0) {
12390      m = [angleCos, angleSin, -angleSin, angleCos, left, top];
12391      b = _util.Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m);
12392    } else {
12393      b = [left, top, left + divWidth, top + divHeight];
12394    }
12395
12396    task._bounds.push({
12397      left: b[0],
12398      top: b[1],
12399      right: b[2],
12400      bottom: b[3],
12401      div: textDiv,
12402      size: [divWidth, divHeight],
12403      m
12404    });
12405  }
12406}
12407
12408function render(task) {
12409  if (task._canceled) {
12410    return;
12411  }
12412
12413  const textDivs = task._textDivs;
12414  const capability = task._capability;
12415  const textDivsLength = textDivs.length;
12416
12417  if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) {
12418    task._renderingDone = true;
12419    capability.resolve();
12420    return;
12421  }
12422
12423  if (!task._textContentStream) {
12424    for (let i = 0; i < textDivsLength; i++) {
12425      task._layoutText(textDivs[i]);
12426    }
12427  }
12428
12429  task._renderingDone = true;
12430  capability.resolve();
12431}
12432
12433function findPositiveMin(ts, offset, count) {
12434  let result = 0;
12435
12436  for (let i = 0; i < count; i++) {
12437    const t = ts[offset++];
12438
12439    if (t > 0) {
12440      result = result ? Math.min(t, result) : t;
12441    }
12442  }
12443
12444  return result;
12445}
12446
12447function expand(task) {
12448  const bounds = task._bounds;
12449  const viewport = task._viewport;
12450  const expanded = expandBounds(viewport.width, viewport.height, bounds);
12451
12452  for (let i = 0; i < expanded.length; i++) {
12453    const div = bounds[i].div;
12454
12455    const divProperties = task._textDivProperties.get(div);
12456
12457    if (divProperties.angle === 0) {
12458      divProperties.paddingLeft = bounds[i].left - expanded[i].left;
12459      divProperties.paddingTop = bounds[i].top - expanded[i].top;
12460      divProperties.paddingRight = expanded[i].right - bounds[i].right;
12461      divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom;
12462
12463      task._textDivProperties.set(div, divProperties);
12464
12465      continue;
12466    }
12467
12468    const e = expanded[i],
12469          b = bounds[i];
12470    const m = b.m,
12471          c = m[0],
12472          s = m[1];
12473    const points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size];
12474    const ts = new Float64Array(64);
12475
12476    for (let j = 0, jj = points.length; j < jj; j++) {
12477      const t = _util.Util.applyTransform(points[j], m);
12478
12479      ts[j + 0] = c && (e.left - t[0]) / c;
12480      ts[j + 4] = s && (e.top - t[1]) / s;
12481      ts[j + 8] = c && (e.right - t[0]) / c;
12482      ts[j + 12] = s && (e.bottom - t[1]) / s;
12483      ts[j + 16] = s && (e.left - t[0]) / -s;
12484      ts[j + 20] = c && (e.top - t[1]) / c;
12485      ts[j + 24] = s && (e.right - t[0]) / -s;
12486      ts[j + 28] = c && (e.bottom - t[1]) / c;
12487      ts[j + 32] = c && (e.left - t[0]) / -c;
12488      ts[j + 36] = s && (e.top - t[1]) / -s;
12489      ts[j + 40] = c && (e.right - t[0]) / -c;
12490      ts[j + 44] = s && (e.bottom - t[1]) / -s;
12491      ts[j + 48] = s && (e.left - t[0]) / s;
12492      ts[j + 52] = c && (e.top - t[1]) / -c;
12493      ts[j + 56] = s && (e.right - t[0]) / s;
12494      ts[j + 60] = c && (e.bottom - t[1]) / -c;
12495    }
12496
12497    const boxScale = 1 + Math.min(Math.abs(c), Math.abs(s));
12498    divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale;
12499    divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale;
12500    divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale;
12501    divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale;
12502
12503    task._textDivProperties.set(div, divProperties);
12504  }
12505}
12506
12507function expandBounds(width, height, boxes) {
12508  const bounds = boxes.map(function (box, i) {
12509    return {
12510      x1: box.left,
12511      y1: box.top,
12512      x2: box.right,
12513      y2: box.bottom,
12514      index: i,
12515      x1New: undefined,
12516      x2New: undefined
12517    };
12518  });
12519  expandBoundsLTR(width, bounds);
12520  const expanded = new Array(boxes.length);
12521
12522  for (const b of bounds) {
12523    const i = b.index;
12524    expanded[i] = {
12525      left: b.x1New,
12526      top: 0,
12527      right: b.x2New,
12528      bottom: 0
12529    };
12530  }
12531
12532  boxes.map(function (box, i) {
12533    const e = expanded[i],
12534          b = bounds[i];
12535    b.x1 = box.top;
12536    b.y1 = width - e.right;
12537    b.x2 = box.bottom;
12538    b.y2 = width - e.left;
12539    b.index = i;
12540    b.x1New = undefined;
12541    b.x2New = undefined;
12542  });
12543  expandBoundsLTR(height, bounds);
12544
12545  for (const b of bounds) {
12546    const i = b.index;
12547    expanded[i].top = b.x1New;
12548    expanded[i].bottom = b.x2New;
12549  }
12550
12551  return expanded;
12552}
12553
12554function expandBoundsLTR(width, bounds) {
12555  bounds.sort(function (a, b) {
12556    return a.x1 - b.x1 || a.index - b.index;
12557  });
12558  const fakeBoundary = {
12559    x1: -Infinity,
12560    y1: -Infinity,
12561    x2: 0,
12562    y2: Infinity,
12563    index: -1,
12564    x1New: 0,
12565    x2New: 0
12566  };
12567  const horizon = [{
12568    start: -Infinity,
12569    end: Infinity,
12570    boundary: fakeBoundary
12571  }];
12572
12573  for (const boundary of bounds) {
12574    let i = 0;
12575
12576    while (i < horizon.length && horizon[i].end <= boundary.y1) {
12577      i++;
12578    }
12579
12580    let j = horizon.length - 1;
12581
12582    while (j >= 0 && horizon[j].start >= boundary.y2) {
12583      j--;
12584    }
12585
12586    let horizonPart, affectedBoundary;
12587    let q,
12588        k,
12589        maxXNew = -Infinity;
12590
12591    for (q = i; q <= j; q++) {
12592      horizonPart = horizon[q];
12593      affectedBoundary = horizonPart.boundary;
12594      let xNew;
12595
12596      if (affectedBoundary.x2 > boundary.x1) {
12597        xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1;
12598      } else if (affectedBoundary.x2New === undefined) {
12599        xNew = (affectedBoundary.x2 + boundary.x1) / 2;
12600      } else {
12601        xNew = affectedBoundary.x2New;
12602      }
12603
12604      if (xNew > maxXNew) {
12605        maxXNew = xNew;
12606      }
12607    }
12608
12609    boundary.x1New = maxXNew;
12610
12611    for (q = i; q <= j; q++) {
12612      horizonPart = horizon[q];
12613      affectedBoundary = horizonPart.boundary;
12614
12615      if (affectedBoundary.x2New === undefined) {
12616        if (affectedBoundary.x2 > boundary.x1) {
12617          if (affectedBoundary.index > boundary.index) {
12618            affectedBoundary.x2New = affectedBoundary.x2;
12619          }
12620        } else {
12621          affectedBoundary.x2New = maxXNew;
12622        }
12623      } else if (affectedBoundary.x2New > maxXNew) {
12624        affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2);
12625      }
12626    }
12627
12628    const changedHorizon = [];
12629    let lastBoundary = null;
12630
12631    for (q = i; q <= j; q++) {
12632      horizonPart = horizon[q];
12633      affectedBoundary = horizonPart.boundary;
12634      const useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary;
12635
12636      if (lastBoundary === useBoundary) {
12637        changedHorizon[changedHorizon.length - 1].end = horizonPart.end;
12638      } else {
12639        changedHorizon.push({
12640          start: horizonPart.start,
12641          end: horizonPart.end,
12642          boundary: useBoundary
12643        });
12644        lastBoundary = useBoundary;
12645      }
12646    }
12647
12648    if (horizon[i].start < boundary.y1) {
12649      changedHorizon[0].start = boundary.y1;
12650      changedHorizon.unshift({
12651        start: horizon[i].start,
12652        end: boundary.y1,
12653        boundary: horizon[i].boundary
12654      });
12655    }
12656
12657    if (boundary.y2 < horizon[j].end) {
12658      changedHorizon[changedHorizon.length - 1].end = boundary.y2;
12659      changedHorizon.push({
12660        start: boundary.y2,
12661        end: horizon[j].end,
12662        boundary: horizon[j].boundary
12663      });
12664    }
12665
12666    for (q = i; q <= j; q++) {
12667      horizonPart = horizon[q];
12668      affectedBoundary = horizonPart.boundary;
12669
12670      if (affectedBoundary.x2New !== undefined) {
12671        continue;
12672      }
12673
12674      let used = false;
12675
12676      for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) {
12677        used = horizon[k].boundary === affectedBoundary;
12678      }
12679
12680      for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) {
12681        used = horizon[k].boundary === affectedBoundary;
12682      }
12683
12684      for (k = 0; !used && k < changedHorizon.length; k++) {
12685        used = changedHorizon[k].boundary === affectedBoundary;
12686      }
12687
12688      if (!used) {
12689        affectedBoundary.x2New = maxXNew;
12690      }
12691    }
12692
12693    Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon));
12694  }
12695
12696  for (const horizonPart of horizon) {
12697    const affectedBoundary = horizonPart.boundary;
12698
12699    if (affectedBoundary.x2New === undefined) {
12700      affectedBoundary.x2New = Math.max(width, affectedBoundary.x2);
12701    }
12702  }
12703}
12704
12705class TextLayerRenderTask {
12706  constructor({
12707    textContent,
12708    textContentStream,
12709    container,
12710    viewport,
12711    textDivs,
12712    textContentItemsStr,
12713    enhanceTextSelection
12714  }) {
12715    this._textContent = textContent;
12716    this._textContentStream = textContentStream;
12717    this._container = container;
12718    this._document = container.ownerDocument;
12719    this._viewport = viewport;
12720    this._textDivs = textDivs || [];
12721    this._textContentItemsStr = textContentItemsStr || [];
12722    this._enhanceTextSelection = !!enhanceTextSelection;
12723    this._fontInspectorEnabled = !!globalThis.FontInspector?.enabled;
12724    this._reader = null;
12725    this._layoutTextLastFontSize = null;
12726    this._layoutTextLastFontFamily = null;
12727    this._layoutTextCtx = null;
12728    this._textDivProperties = new WeakMap();
12729    this._renderingDone = false;
12730    this._canceled = false;
12731    this._capability = (0, _util.createPromiseCapability)();
12732    this._renderTimer = null;
12733    this._bounds = [];
12734
12735    this._capability.promise.finally(() => {
12736      if (!this._enhanceTextSelection) {
12737        this._textDivProperties = null;
12738      }
12739
12740      if (this._layoutTextCtx) {
12741        this._layoutTextCtx.canvas.width = 0;
12742        this._layoutTextCtx.canvas.height = 0;
12743        this._layoutTextCtx = null;
12744      }
12745    }).catch(() => {});
12746  }
12747
12748  get promise() {
12749    return this._capability.promise;
12750  }
12751
12752  cancel() {
12753    this._canceled = true;
12754
12755    if (this._reader) {
12756      this._reader.cancel(new _util.AbortException("TextLayer task cancelled.")).catch(() => {});
12757
12758      this._reader = null;
12759    }
12760
12761    if (this._renderTimer !== null) {
12762      clearTimeout(this._renderTimer);
12763      this._renderTimer = null;
12764    }
12765
12766    this._capability.reject(new Error("TextLayer task cancelled."));
12767  }
12768
12769  _processItems(items, styleCache) {
12770    for (let i = 0, len = items.length; i < len; i++) {
12771      if (items[i].str === undefined) {
12772        if (items[i].type === "beginMarkedContentProps" || items[i].type === "beginMarkedContent") {
12773          const parent = this._container;
12774          this._container = document.createElement("span");
12775
12776          this._container.classList.add("markedContent");
12777
12778          if (items[i].id !== null) {
12779            this._container.setAttribute("id", `${items[i].id}`);
12780          }
12781
12782          parent.appendChild(this._container);
12783        } else if (items[i].type === "endMarkedContent") {
12784          this._container = this._container.parentNode;
12785        }
12786
12787        continue;
12788      }
12789
12790      this._textContentItemsStr.push(items[i].str);
12791
12792      appendText(this, items[i], styleCache, this._layoutTextCtx);
12793    }
12794  }
12795
12796  _layoutText(textDiv) {
12797    const textDivProperties = this._textDivProperties.get(textDiv);
12798
12799    let transform = "";
12800
12801    if (textDivProperties.canvasWidth !== 0 && textDivProperties.hasText) {
12802      const {
12803        fontSize,
12804        fontFamily
12805      } = textDiv.style;
12806
12807      if (fontSize !== this._layoutTextLastFontSize || fontFamily !== this._layoutTextLastFontFamily) {
12808        this._layoutTextCtx.font = `${fontSize} ${fontFamily}`;
12809        this._layoutTextLastFontSize = fontSize;
12810        this._layoutTextLastFontFamily = fontFamily;
12811      }
12812
12813      const {
12814        width
12815      } = this._layoutTextCtx.measureText(textDiv.textContent);
12816
12817      if (width > 0) {
12818        const scale = textDivProperties.canvasWidth / width;
12819
12820        if (this._enhanceTextSelection) {
12821          textDivProperties.scale = scale;
12822        }
12823
12824        transform = `scaleX(${scale})`;
12825      }
12826    }
12827
12828    if (textDivProperties.angle !== 0) {
12829      transform = `rotate(${textDivProperties.angle}deg) ${transform}`;
12830    }
12831
12832    if (transform.length > 0) {
12833      if (this._enhanceTextSelection) {
12834        textDivProperties.originalTransform = transform;
12835      }
12836
12837      textDiv.style.transform = transform;
12838    }
12839
12840    if (textDivProperties.hasText) {
12841      this._container.appendChild(textDiv);
12842    }
12843
12844    if (textDivProperties.hasEOL) {
12845      const br = document.createElement("br");
12846      br.setAttribute("role", "presentation");
12847
12848      this._container.appendChild(br);
12849    }
12850  }
12851
12852  _render(timeout = 0) {
12853    const capability = (0, _util.createPromiseCapability)();
12854    let styleCache = Object.create(null);
12855
12856    const canvas = this._document.createElement("canvas");
12857
12858    canvas.height = canvas.width = DEFAULT_FONT_SIZE;
12859    this._layoutTextCtx = canvas.getContext("2d", {
12860      alpha: false
12861    });
12862
12863    if (this._textContent) {
12864      const textItems = this._textContent.items;
12865      const textStyles = this._textContent.styles;
12866
12867      this._processItems(textItems, textStyles);
12868
12869      capability.resolve();
12870    } else if (this._textContentStream) {
12871      const pump = () => {
12872        this._reader.read().then(({
12873          value,
12874          done
12875        }) => {
12876          if (done) {
12877            capability.resolve();
12878            return;
12879          }
12880
12881          Object.assign(styleCache, value.styles);
12882
12883          this._processItems(value.items, styleCache);
12884
12885          pump();
12886        }, capability.reject);
12887      };
12888
12889      this._reader = this._textContentStream.getReader();
12890      pump();
12891    } else {
12892      throw new Error('Neither "textContent" nor "textContentStream" parameters specified.');
12893    }
12894
12895    capability.promise.then(() => {
12896      styleCache = null;
12897
12898      if (!timeout) {
12899        render(this);
12900      } else {
12901        this._renderTimer = setTimeout(() => {
12902          render(this);
12903          this._renderTimer = null;
12904        }, timeout);
12905      }
12906    }, this._capability.reject);
12907  }
12908
12909  expandTextDivs(expandDivs = false) {
12910    if (!this._enhanceTextSelection || !this._renderingDone) {
12911      return;
12912    }
12913
12914    if (this._bounds !== null) {
12915      expand(this);
12916      this._bounds = null;
12917    }
12918
12919    const transformBuf = [],
12920          paddingBuf = [];
12921
12922    for (let i = 0, ii = this._textDivs.length; i < ii; i++) {
12923      const div = this._textDivs[i];
12924
12925      const divProps = this._textDivProperties.get(div);
12926
12927      if (!divProps.hasText) {
12928        continue;
12929      }
12930
12931      if (expandDivs) {
12932        transformBuf.length = 0;
12933        paddingBuf.length = 0;
12934
12935        if (divProps.originalTransform) {
12936          transformBuf.push(divProps.originalTransform);
12937        }
12938
12939        if (divProps.paddingTop > 0) {
12940          paddingBuf.push(`${divProps.paddingTop}px`);
12941          transformBuf.push(`translateY(${-divProps.paddingTop}px)`);
12942        } else {
12943          paddingBuf.push(0);
12944        }
12945
12946        if (divProps.paddingRight > 0) {
12947          paddingBuf.push(`${divProps.paddingRight / divProps.scale}px`);
12948        } else {
12949          paddingBuf.push(0);
12950        }
12951
12952        if (divProps.paddingBottom > 0) {
12953          paddingBuf.push(`${divProps.paddingBottom}px`);
12954        } else {
12955          paddingBuf.push(0);
12956        }
12957
12958        if (divProps.paddingLeft > 0) {
12959          paddingBuf.push(`${divProps.paddingLeft / divProps.scale}px`);
12960          transformBuf.push(`translateX(${-divProps.paddingLeft / divProps.scale}px)`);
12961        } else {
12962          paddingBuf.push(0);
12963        }
12964
12965        div.style.padding = paddingBuf.join(" ");
12966
12967        if (transformBuf.length) {
12968          div.style.transform = transformBuf.join(" ");
12969        }
12970      } else {
12971        div.style.padding = null;
12972        div.style.transform = divProps.originalTransform;
12973      }
12974    }
12975  }
12976
12977}
12978
12979function renderTextLayer(renderParameters) {
12980  const task = new TextLayerRenderTask({
12981    textContent: renderParameters.textContent,
12982    textContentStream: renderParameters.textContentStream,
12983    container: renderParameters.container,
12984    viewport: renderParameters.viewport,
12985    textDivs: renderParameters.textDivs,
12986    textContentItemsStr: renderParameters.textContentItemsStr,
12987    enhanceTextSelection: renderParameters.enhanceTextSelection
12988  });
12989
12990  task._render(renderParameters.timeout);
12991
12992  return task;
12993}
12994
12995/***/ }),
12996/* 24 */
12997/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
12998
12999
13000
13001Object.defineProperty(exports, "__esModule", ({
13002  value: true
13003}));
13004exports.SVGGraphics = void 0;
13005
13006var _util = __w_pdfjs_require__(1);
13007
13008var _display_utils = __w_pdfjs_require__(5);
13009
13010var _is_node = __w_pdfjs_require__(3);
13011
13012let SVGGraphics = class {
13013  constructor() {
13014    (0, _util.unreachable)("Not implemented: SVGGraphics");
13015  }
13016
13017};
13018exports.SVGGraphics = SVGGraphics;
13019{
13020  const SVG_DEFAULTS = {
13021    fontStyle: "normal",
13022    fontWeight: "normal",
13023    fillColor: "#000000"
13024  };
13025  const XML_NS = "http://www.w3.org/XML/1998/namespace";
13026  const XLINK_NS = "http://www.w3.org/1999/xlink";
13027  const LINE_CAP_STYLES = ["butt", "round", "square"];
13028  const LINE_JOIN_STYLES = ["miter", "round", "bevel"];
13029
13030  const createObjectURL = function (data, contentType = "", forceDataSchema = false) {
13031    if (URL.createObjectURL && typeof Blob !== "undefined" && !forceDataSchema) {
13032      return URL.createObjectURL(new Blob([data], {
13033        type: contentType
13034      }));
13035    }
13036
13037    const digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
13038    let buffer = `data:${contentType};base64,`;
13039
13040    for (let i = 0, ii = data.length; i < ii; i += 3) {
13041      const b1 = data[i] & 0xff;
13042      const b2 = data[i + 1] & 0xff;
13043      const b3 = data[i + 2] & 0xff;
13044      const d1 = b1 >> 2,
13045            d2 = (b1 & 3) << 4 | b2 >> 4;
13046      const d3 = i + 1 < ii ? (b2 & 0xf) << 2 | b3 >> 6 : 64;
13047      const d4 = i + 2 < ii ? b3 & 0x3f : 64;
13048      buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4];
13049    }
13050
13051    return buffer;
13052  };
13053
13054  const convertImgDataToPng = function () {
13055    const PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
13056    const CHUNK_WRAPPER_SIZE = 12;
13057    const crcTable = new Int32Array(256);
13058
13059    for (let i = 0; i < 256; i++) {
13060      let c = i;
13061
13062      for (let h = 0; h < 8; h++) {
13063        if (c & 1) {
13064          c = 0xedb88320 ^ c >> 1 & 0x7fffffff;
13065        } else {
13066          c = c >> 1 & 0x7fffffff;
13067        }
13068      }
13069
13070      crcTable[i] = c;
13071    }
13072
13073    function crc32(data, start, end) {
13074      let crc = -1;
13075
13076      for (let i = start; i < end; i++) {
13077        const a = (crc ^ data[i]) & 0xff;
13078        const b = crcTable[a];
13079        crc = crc >>> 8 ^ b;
13080      }
13081
13082      return crc ^ -1;
13083    }
13084
13085    function writePngChunk(type, body, data, offset) {
13086      let p = offset;
13087      const len = body.length;
13088      data[p] = len >> 24 & 0xff;
13089      data[p + 1] = len >> 16 & 0xff;
13090      data[p + 2] = len >> 8 & 0xff;
13091      data[p + 3] = len & 0xff;
13092      p += 4;
13093      data[p] = type.charCodeAt(0) & 0xff;
13094      data[p + 1] = type.charCodeAt(1) & 0xff;
13095      data[p + 2] = type.charCodeAt(2) & 0xff;
13096      data[p + 3] = type.charCodeAt(3) & 0xff;
13097      p += 4;
13098      data.set(body, p);
13099      p += body.length;
13100      const crc = crc32(data, offset + 4, p);
13101      data[p] = crc >> 24 & 0xff;
13102      data[p + 1] = crc >> 16 & 0xff;
13103      data[p + 2] = crc >> 8 & 0xff;
13104      data[p + 3] = crc & 0xff;
13105    }
13106
13107    function adler32(data, start, end) {
13108      let a = 1;
13109      let b = 0;
13110
13111      for (let i = start; i < end; ++i) {
13112        a = (a + (data[i] & 0xff)) % 65521;
13113        b = (b + a) % 65521;
13114      }
13115
13116      return b << 16 | a;
13117    }
13118
13119    function deflateSync(literals) {
13120      if (!_is_node.isNodeJS) {
13121        return deflateSyncUncompressed(literals);
13122      }
13123
13124      try {
13125        let input;
13126
13127        if (parseInt(process.versions.node) >= 8) {
13128          input = literals;
13129        } else {
13130          input = Buffer.from(literals);
13131        }
13132
13133        const output = require("zlib").deflateSync(input, {
13134          level: 9
13135        });
13136
13137        return output instanceof Uint8Array ? output : new Uint8Array(output);
13138      } catch (e) {
13139        (0, _util.warn)("Not compressing PNG because zlib.deflateSync is unavailable: " + e);
13140      }
13141
13142      return deflateSyncUncompressed(literals);
13143    }
13144
13145    function deflateSyncUncompressed(literals) {
13146      let len = literals.length;
13147      const maxBlockLength = 0xffff;
13148      const deflateBlocks = Math.ceil(len / maxBlockLength);
13149      const idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4);
13150      let pi = 0;
13151      idat[pi++] = 0x78;
13152      idat[pi++] = 0x9c;
13153      let pos = 0;
13154
13155      while (len > maxBlockLength) {
13156        idat[pi++] = 0x00;
13157        idat[pi++] = 0xff;
13158        idat[pi++] = 0xff;
13159        idat[pi++] = 0x00;
13160        idat[pi++] = 0x00;
13161        idat.set(literals.subarray(pos, pos + maxBlockLength), pi);
13162        pi += maxBlockLength;
13163        pos += maxBlockLength;
13164        len -= maxBlockLength;
13165      }
13166
13167      idat[pi++] = 0x01;
13168      idat[pi++] = len & 0xff;
13169      idat[pi++] = len >> 8 & 0xff;
13170      idat[pi++] = ~len & 0xffff & 0xff;
13171      idat[pi++] = (~len & 0xffff) >> 8 & 0xff;
13172      idat.set(literals.subarray(pos), pi);
13173      pi += literals.length - pos;
13174      const adler = adler32(literals, 0, literals.length);
13175      idat[pi++] = adler >> 24 & 0xff;
13176      idat[pi++] = adler >> 16 & 0xff;
13177      idat[pi++] = adler >> 8 & 0xff;
13178      idat[pi++] = adler & 0xff;
13179      return idat;
13180    }
13181
13182    function encode(imgData, kind, forceDataSchema, isMask) {
13183      const width = imgData.width;
13184      const height = imgData.height;
13185      let bitDepth, colorType, lineSize;
13186      const bytes = imgData.data;
13187
13188      switch (kind) {
13189        case _util.ImageKind.GRAYSCALE_1BPP:
13190          colorType = 0;
13191          bitDepth = 1;
13192          lineSize = width + 7 >> 3;
13193          break;
13194
13195        case _util.ImageKind.RGB_24BPP:
13196          colorType = 2;
13197          bitDepth = 8;
13198          lineSize = width * 3;
13199          break;
13200
13201        case _util.ImageKind.RGBA_32BPP:
13202          colorType = 6;
13203          bitDepth = 8;
13204          lineSize = width * 4;
13205          break;
13206
13207        default:
13208          throw new Error("invalid format");
13209      }
13210
13211      const literals = new Uint8Array((1 + lineSize) * height);
13212      let offsetLiterals = 0,
13213          offsetBytes = 0;
13214
13215      for (let y = 0; y < height; ++y) {
13216        literals[offsetLiterals++] = 0;
13217        literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals);
13218        offsetBytes += lineSize;
13219        offsetLiterals += lineSize;
13220      }
13221
13222      if (kind === _util.ImageKind.GRAYSCALE_1BPP && isMask) {
13223        offsetLiterals = 0;
13224
13225        for (let y = 0; y < height; y++) {
13226          offsetLiterals++;
13227
13228          for (let i = 0; i < lineSize; i++) {
13229            literals[offsetLiterals++] ^= 0xff;
13230          }
13231        }
13232      }
13233
13234      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]);
13235      const idat = deflateSync(literals);
13236      const pngLength = PNG_HEADER.length + CHUNK_WRAPPER_SIZE * 3 + ihdr.length + idat.length;
13237      const data = new Uint8Array(pngLength);
13238      let offset = 0;
13239      data.set(PNG_HEADER, offset);
13240      offset += PNG_HEADER.length;
13241      writePngChunk("IHDR", ihdr, data, offset);
13242      offset += CHUNK_WRAPPER_SIZE + ihdr.length;
13243      writePngChunk("IDATA", idat, data, offset);
13244      offset += CHUNK_WRAPPER_SIZE + idat.length;
13245      writePngChunk("IEND", new Uint8Array(0), data, offset);
13246      return createObjectURL(data, "image/png", forceDataSchema);
13247    }
13248
13249    return function convertImgDataToPng(imgData, forceDataSchema, isMask) {
13250      const kind = imgData.kind === undefined ? _util.ImageKind.GRAYSCALE_1BPP : imgData.kind;
13251      return encode(imgData, kind, forceDataSchema, isMask);
13252    };
13253  }();
13254
13255  class SVGExtraState {
13256    constructor() {
13257      this.fontSizeScale = 1;
13258      this.fontWeight = SVG_DEFAULTS.fontWeight;
13259      this.fontSize = 0;
13260      this.textMatrix = _util.IDENTITY_MATRIX;
13261      this.fontMatrix = _util.FONT_IDENTITY_MATRIX;
13262      this.leading = 0;
13263      this.textRenderingMode = _util.TextRenderingMode.FILL;
13264      this.textMatrixScale = 1;
13265      this.x = 0;
13266      this.y = 0;
13267      this.lineX = 0;
13268      this.lineY = 0;
13269      this.charSpacing = 0;
13270      this.wordSpacing = 0;
13271      this.textHScale = 1;
13272      this.textRise = 0;
13273      this.fillColor = SVG_DEFAULTS.fillColor;
13274      this.strokeColor = "#000000";
13275      this.fillAlpha = 1;
13276      this.strokeAlpha = 1;
13277      this.lineWidth = 1;
13278      this.lineJoin = "";
13279      this.lineCap = "";
13280      this.miterLimit = 0;
13281      this.dashArray = [];
13282      this.dashPhase = 0;
13283      this.dependencies = [];
13284      this.activeClipUrl = null;
13285      this.clipGroup = null;
13286      this.maskId = "";
13287    }
13288
13289    clone() {
13290      return Object.create(this);
13291    }
13292
13293    setCurrentPoint(x, y) {
13294      this.x = x;
13295      this.y = y;
13296    }
13297
13298  }
13299
13300  function opListToTree(opList) {
13301    let opTree = [];
13302    const tmp = [];
13303
13304    for (const opListElement of opList) {
13305      if (opListElement.fn === "save") {
13306        opTree.push({
13307          fnId: 92,
13308          fn: "group",
13309          items: []
13310        });
13311        tmp.push(opTree);
13312        opTree = opTree[opTree.length - 1].items;
13313        continue;
13314      }
13315
13316      if (opListElement.fn === "restore") {
13317        opTree = tmp.pop();
13318      } else {
13319        opTree.push(opListElement);
13320      }
13321    }
13322
13323    return opTree;
13324  }
13325
13326  function pf(value) {
13327    if (Number.isInteger(value)) {
13328      return value.toString();
13329    }
13330
13331    const s = value.toFixed(10);
13332    let i = s.length - 1;
13333
13334    if (s[i] !== "0") {
13335      return s;
13336    }
13337
13338    do {
13339      i--;
13340    } while (s[i] === "0");
13341
13342    return s.substring(0, s[i] === "." ? i : i + 1);
13343  }
13344
13345  function pm(m) {
13346    if (m[4] === 0 && m[5] === 0) {
13347      if (m[1] === 0 && m[2] === 0) {
13348        if (m[0] === 1 && m[3] === 1) {
13349          return "";
13350        }
13351
13352        return `scale(${pf(m[0])} ${pf(m[3])})`;
13353      }
13354
13355      if (m[0] === m[3] && m[1] === -m[2]) {
13356        const a = Math.acos(m[0]) * 180 / Math.PI;
13357        return `rotate(${pf(a)})`;
13358      }
13359    } else {
13360      if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) {
13361        return `translate(${pf(m[4])} ${pf(m[5])})`;
13362      }
13363    }
13364
13365    return `matrix(${pf(m[0])} ${pf(m[1])} ${pf(m[2])} ${pf(m[3])} ${pf(m[4])} ` + `${pf(m[5])})`;
13366  }
13367
13368  let clipCount = 0;
13369  let maskCount = 0;
13370  let shadingCount = 0;
13371  exports.SVGGraphics = SVGGraphics = class {
13372    constructor(commonObjs, objs, forceDataSchema = false) {
13373      this.svgFactory = new _display_utils.DOMSVGFactory();
13374      this.current = new SVGExtraState();
13375      this.transformMatrix = _util.IDENTITY_MATRIX;
13376      this.transformStack = [];
13377      this.extraStack = [];
13378      this.commonObjs = commonObjs;
13379      this.objs = objs;
13380      this.pendingClip = null;
13381      this.pendingEOFill = false;
13382      this.embedFonts = false;
13383      this.embeddedFonts = Object.create(null);
13384      this.cssStyle = null;
13385      this.forceDataSchema = !!forceDataSchema;
13386      this._operatorIdMapping = [];
13387
13388      for (const op in _util.OPS) {
13389        this._operatorIdMapping[_util.OPS[op]] = op;
13390      }
13391    }
13392
13393    save() {
13394      this.transformStack.push(this.transformMatrix);
13395      const old = this.current;
13396      this.extraStack.push(old);
13397      this.current = old.clone();
13398    }
13399
13400    restore() {
13401      this.transformMatrix = this.transformStack.pop();
13402      this.current = this.extraStack.pop();
13403      this.pendingClip = null;
13404      this.tgrp = null;
13405    }
13406
13407    group(items) {
13408      this.save();
13409      this.executeOpTree(items);
13410      this.restore();
13411    }
13412
13413    loadDependencies(operatorList) {
13414      const fnArray = operatorList.fnArray;
13415      const argsArray = operatorList.argsArray;
13416
13417      for (let i = 0, ii = fnArray.length; i < ii; i++) {
13418        if (fnArray[i] !== _util.OPS.dependency) {
13419          continue;
13420        }
13421
13422        for (const obj of argsArray[i]) {
13423          const objsPool = obj.startsWith("g_") ? this.commonObjs : this.objs;
13424          const promise = new Promise(resolve => {
13425            objsPool.get(obj, resolve);
13426          });
13427          this.current.dependencies.push(promise);
13428        }
13429      }
13430
13431      return Promise.all(this.current.dependencies);
13432    }
13433
13434    transform(a, b, c, d, e, f) {
13435      const transformMatrix = [a, b, c, d, e, f];
13436      this.transformMatrix = _util.Util.transform(this.transformMatrix, transformMatrix);
13437      this.tgrp = null;
13438    }
13439
13440    getSVG(operatorList, viewport) {
13441      this.viewport = viewport;
13442
13443      const svgElement = this._initialize(viewport);
13444
13445      return this.loadDependencies(operatorList).then(() => {
13446        this.transformMatrix = _util.IDENTITY_MATRIX;
13447        this.executeOpTree(this.convertOpList(operatorList));
13448        return svgElement;
13449      });
13450    }
13451
13452    convertOpList(operatorList) {
13453      const operatorIdMapping = this._operatorIdMapping;
13454      const argsArray = operatorList.argsArray;
13455      const fnArray = operatorList.fnArray;
13456      const opList = [];
13457
13458      for (let i = 0, ii = fnArray.length; i < ii; i++) {
13459        const fnId = fnArray[i];
13460        opList.push({
13461          fnId,
13462          fn: operatorIdMapping[fnId],
13463          args: argsArray[i]
13464        });
13465      }
13466
13467      return opListToTree(opList);
13468    }
13469
13470    executeOpTree(opTree) {
13471      for (const opTreeElement of opTree) {
13472        const fn = opTreeElement.fn;
13473        const fnId = opTreeElement.fnId;
13474        const args = opTreeElement.args;
13475
13476        switch (fnId | 0) {
13477          case _util.OPS.beginText:
13478            this.beginText();
13479            break;
13480
13481          case _util.OPS.dependency:
13482            break;
13483
13484          case _util.OPS.setLeading:
13485            this.setLeading(args);
13486            break;
13487
13488          case _util.OPS.setLeadingMoveText:
13489            this.setLeadingMoveText(args[0], args[1]);
13490            break;
13491
13492          case _util.OPS.setFont:
13493            this.setFont(args);
13494            break;
13495
13496          case _util.OPS.showText:
13497            this.showText(args[0]);
13498            break;
13499
13500          case _util.OPS.showSpacedText:
13501            this.showText(args[0]);
13502            break;
13503
13504          case _util.OPS.endText:
13505            this.endText();
13506            break;
13507
13508          case _util.OPS.moveText:
13509            this.moveText(args[0], args[1]);
13510            break;
13511
13512          case _util.OPS.setCharSpacing:
13513            this.setCharSpacing(args[0]);
13514            break;
13515
13516          case _util.OPS.setWordSpacing:
13517            this.setWordSpacing(args[0]);
13518            break;
13519
13520          case _util.OPS.setHScale:
13521            this.setHScale(args[0]);
13522            break;
13523
13524          case _util.OPS.setTextMatrix:
13525            this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]);
13526            break;
13527
13528          case _util.OPS.setTextRise:
13529            this.setTextRise(args[0]);
13530            break;
13531
13532          case _util.OPS.setTextRenderingMode:
13533            this.setTextRenderingMode(args[0]);
13534            break;
13535
13536          case _util.OPS.setLineWidth:
13537            this.setLineWidth(args[0]);
13538            break;
13539
13540          case _util.OPS.setLineJoin:
13541            this.setLineJoin(args[0]);
13542            break;
13543
13544          case _util.OPS.setLineCap:
13545            this.setLineCap(args[0]);
13546            break;
13547
13548          case _util.OPS.setMiterLimit:
13549            this.setMiterLimit(args[0]);
13550            break;
13551
13552          case _util.OPS.setFillRGBColor:
13553            this.setFillRGBColor(args[0], args[1], args[2]);
13554            break;
13555
13556          case _util.OPS.setStrokeRGBColor:
13557            this.setStrokeRGBColor(args[0], args[1], args[2]);
13558            break;
13559
13560          case _util.OPS.setStrokeColorN:
13561            this.setStrokeColorN(args);
13562            break;
13563
13564          case _util.OPS.setFillColorN:
13565            this.setFillColorN(args);
13566            break;
13567
13568          case _util.OPS.shadingFill:
13569            this.shadingFill(args[0]);
13570            break;
13571
13572          case _util.OPS.setDash:
13573            this.setDash(args[0], args[1]);
13574            break;
13575
13576          case _util.OPS.setRenderingIntent:
13577            this.setRenderingIntent(args[0]);
13578            break;
13579
13580          case _util.OPS.setFlatness:
13581            this.setFlatness(args[0]);
13582            break;
13583
13584          case _util.OPS.setGState:
13585            this.setGState(args[0]);
13586            break;
13587
13588          case _util.OPS.fill:
13589            this.fill();
13590            break;
13591
13592          case _util.OPS.eoFill:
13593            this.eoFill();
13594            break;
13595
13596          case _util.OPS.stroke:
13597            this.stroke();
13598            break;
13599
13600          case _util.OPS.fillStroke:
13601            this.fillStroke();
13602            break;
13603
13604          case _util.OPS.eoFillStroke:
13605            this.eoFillStroke();
13606            break;
13607
13608          case _util.OPS.clip:
13609            this.clip("nonzero");
13610            break;
13611
13612          case _util.OPS.eoClip:
13613            this.clip("evenodd");
13614            break;
13615
13616          case _util.OPS.paintSolidColorImageMask:
13617            this.paintSolidColorImageMask();
13618            break;
13619
13620          case _util.OPS.paintImageXObject:
13621            this.paintImageXObject(args[0]);
13622            break;
13623
13624          case _util.OPS.paintInlineImageXObject:
13625            this.paintInlineImageXObject(args[0]);
13626            break;
13627
13628          case _util.OPS.paintImageMaskXObject:
13629            this.paintImageMaskXObject(args[0]);
13630            break;
13631
13632          case _util.OPS.paintFormXObjectBegin:
13633            this.paintFormXObjectBegin(args[0], args[1]);
13634            break;
13635
13636          case _util.OPS.paintFormXObjectEnd:
13637            this.paintFormXObjectEnd();
13638            break;
13639
13640          case _util.OPS.closePath:
13641            this.closePath();
13642            break;
13643
13644          case _util.OPS.closeStroke:
13645            this.closeStroke();
13646            break;
13647
13648          case _util.OPS.closeFillStroke:
13649            this.closeFillStroke();
13650            break;
13651
13652          case _util.OPS.closeEOFillStroke:
13653            this.closeEOFillStroke();
13654            break;
13655
13656          case _util.OPS.nextLine:
13657            this.nextLine();
13658            break;
13659
13660          case _util.OPS.transform:
13661            this.transform(args[0], args[1], args[2], args[3], args[4], args[5]);
13662            break;
13663
13664          case _util.OPS.constructPath:
13665            this.constructPath(args[0], args[1]);
13666            break;
13667
13668          case _util.OPS.endPath:
13669            this.endPath();
13670            break;
13671
13672          case 92:
13673            this.group(opTreeElement.items);
13674            break;
13675
13676          default:
13677            (0, _util.warn)(`Unimplemented operator ${fn}`);
13678            break;
13679        }
13680      }
13681    }
13682
13683    setWordSpacing(wordSpacing) {
13684      this.current.wordSpacing = wordSpacing;
13685    }
13686
13687    setCharSpacing(charSpacing) {
13688      this.current.charSpacing = charSpacing;
13689    }
13690
13691    nextLine() {
13692      this.moveText(0, this.current.leading);
13693    }
13694
13695    setTextMatrix(a, b, c, d, e, f) {
13696      const current = this.current;
13697      current.textMatrix = current.lineMatrix = [a, b, c, d, e, f];
13698      current.textMatrixScale = Math.hypot(a, b);
13699      current.x = current.lineX = 0;
13700      current.y = current.lineY = 0;
13701      current.xcoords = [];
13702      current.ycoords = [];
13703      current.tspan = this.svgFactory.createElement("svg:tspan");
13704      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
13705      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
13706      current.tspan.setAttributeNS(null, "y", pf(-current.y));
13707      current.txtElement = this.svgFactory.createElement("svg:text");
13708      current.txtElement.appendChild(current.tspan);
13709    }
13710
13711    beginText() {
13712      const current = this.current;
13713      current.x = current.lineX = 0;
13714      current.y = current.lineY = 0;
13715      current.textMatrix = _util.IDENTITY_MATRIX;
13716      current.lineMatrix = _util.IDENTITY_MATRIX;
13717      current.textMatrixScale = 1;
13718      current.tspan = this.svgFactory.createElement("svg:tspan");
13719      current.txtElement = this.svgFactory.createElement("svg:text");
13720      current.txtgrp = this.svgFactory.createElement("svg:g");
13721      current.xcoords = [];
13722      current.ycoords = [];
13723    }
13724
13725    moveText(x, y) {
13726      const current = this.current;
13727      current.x = current.lineX += x;
13728      current.y = current.lineY += y;
13729      current.xcoords = [];
13730      current.ycoords = [];
13731      current.tspan = this.svgFactory.createElement("svg:tspan");
13732      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
13733      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
13734      current.tspan.setAttributeNS(null, "y", pf(-current.y));
13735    }
13736
13737    showText(glyphs) {
13738      const current = this.current;
13739      const font = current.font;
13740      const fontSize = current.fontSize;
13741
13742      if (fontSize === 0) {
13743        return;
13744      }
13745
13746      const fontSizeScale = current.fontSizeScale;
13747      const charSpacing = current.charSpacing;
13748      const wordSpacing = current.wordSpacing;
13749      const fontDirection = current.fontDirection;
13750      const textHScale = current.textHScale * fontDirection;
13751      const vertical = font.vertical;
13752      const spacingDir = vertical ? 1 : -1;
13753      const defaultVMetrics = font.defaultVMetrics;
13754      const widthAdvanceScale = fontSize * current.fontMatrix[0];
13755      let x = 0;
13756
13757      for (const glyph of glyphs) {
13758        if (glyph === null) {
13759          x += fontDirection * wordSpacing;
13760          continue;
13761        }
13761 else if (typeof glyph === "number") {
13762          x += spacingDir * glyph * fontSize / 1000;
13763          continue;
13764        }
13765
13766        const spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing;
13767        const character = glyph.fontChar;
13768        let scaledX, scaledY;
13769        let width = glyph.width;
13770
13771        if (vertical) {
13772          let vx;
13773          const vmetric = glyph.vmetric || defaultVMetrics;
13774          vx = glyph.vmetric ? vmetric[1] : width * 0.5;
13775          vx = -vx * widthAdvanceScale;
13776          const vy = vmetric[2] * widthAdvanceScale;
13777          width = vmetric ? -vmetric[0] : width;
13778          scaledX = vx / fontSizeScale;
13779          scaledY = (x + vy) / fontSizeScale;
13780        } else {
13781          scaledX = x / fontSizeScale;
13782          scaledY = 0;
13783        }
13784
13785        if (glyph.isInFont || font.missingFile) {
13786          current.xcoords.push(current.x + scaledX);
13787
13788          if (vertical) {
13789            current.ycoords.push(-current.y + scaledY);
13790          }
13791
13792          current.tspan.textContent += character;
13793        } else {}
13794
13795        let charWidth;
13796
13797        if (vertical) {
13798          charWidth = width * widthAdvanceScale - spacing * fontDirection;
13799        } else {
13800          charWidth = width * widthAdvanceScale + spacing * fontDirection;
13801        }
13802
13803        x += charWidth;
13804      }
13805
13806      current.tspan.setAttributeNS(null, "x", current.xcoords.map(pf).join(" "));
13807
13808      if (vertical) {
13809        current.tspan.setAttributeNS(null, "y", current.ycoords.map(pf).join(" "));
13810      } else {
13811        current.tspan.setAttributeNS(null, "y", pf(-current.y));
13812      }
13813
13814      if (vertical) {
13815        current.y -= x;
13816      } else {
13817        current.x += x * textHScale;
13818      }
13819
13820      current.tspan.setAttributeNS(null, "font-family", current.fontFamily);
13821      current.tspan.setAttributeNS(null, "font-size", `${pf(current.fontSize)}px`);
13822
13823      if (current.fontStyle !== SVG_DEFAULTS.fontStyle) {
13824        current.tspan.setAttributeNS(null, "font-style", current.fontStyle);
13825      }
13826
13827      if (current.fontWeight !== SVG_DEFAULTS.fontWeight) {
13828        current.tspan.setAttributeNS(null, "font-weight", current.fontWeight);
13829      }
13830
13831      const fillStrokeMode = current.textRenderingMode & _util.TextRenderingMode.FILL_STROKE_MASK;
13832
13833      if (fillStrokeMode === _util.TextRenderingMode.FILL || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
13834        if (current.fillColor !== SVG_DEFAULTS.fillColor) {
13835          current.tspan.setAttributeNS(null, "fill", current.fillColor);
13836        }
13837
13838        if (current.fillAlpha < 1) {
13839          current.tspan.setAttributeNS(null, "fill-opacity", current.fillAlpha);
13840        }
13841      } else if (current.textRenderingMode === _util.TextRenderingMode.ADD_TO_PATH) {
13842        current.tspan.setAttributeNS(null, "fill", "transparent");
13843      } else {
13844        current.tspan.setAttributeNS(null, "fill", "none");
13845      }
13846
13847      if (fillStrokeMode === _util.TextRenderingMode.STROKE || fillStrokeMode === _util.TextRenderingMode.FILL_STROKE) {
13848        const lineWidthScale = 1 / (current.textMatrixScale || 1);
13849
13850        this._setStrokeAttributes(current.tspan, lineWidthScale);
13851      }
13852
13853      let textMatrix = current.textMatrix;
13854
13855      if (current.textRise !== 0) {
13856        textMatrix = textMatrix.slice();
13857        textMatrix[5] += current.textRise;
13858      }
13859
13860      current.txtElement.setAttributeNS(null, "transform", `${pm(textMatrix)} scale(${pf(textHScale)}, -1)`);
13861      current.txtElement.setAttributeNS(XML_NS, "xml:space", "preserve");
13862      current.txtElement.appendChild(current.tspan);
13863      current.txtgrp.appendChild(current.txtElement);
13864
13865      this._ensureTransformGroup().appendChild(current.txtElement);
13866    }
13867
13868    setLeadingMoveText(x, y) {
13869      this.setLeading(-y);
13870      this.moveText(x, y);
13871    }
13872
13873    addFontStyle(fontObj) {
13874      if (!fontObj.data) {
13875        throw new Error("addFontStyle: No font data available, " + 'ensure that the "fontExtraProperties" API parameter is set.');
13876      }
13877
13878      if (!this.cssStyle) {
13879        this.cssStyle = this.svgFactory.createElement("svg:style");
13880        this.cssStyle.setAttributeNS(null, "type", "text/css");
13881        this.defs.appendChild(this.cssStyle);
13882      }
13883
13884      const url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema);
13885      this.cssStyle.textContent += `@font-face { font-family: "${fontObj.loadedName}";` + ` src: url(${url}); }\n`;
13886    }
13887
13888    setFont(details) {
13889      const current = this.current;
13890      const fontObj = this.commonObjs.get(details[0]);
13891      let size = details[1];
13892      current.font = fontObj;
13893
13894      if (this.embedFonts && !fontObj.missingFile && !this.embeddedFonts[fontObj.loadedName]) {
13895        this.addFontStyle(fontObj);
13896        this.embeddedFonts[fontObj.loadedName] = fontObj;
13897      }
13898
13899      current.fontMatrix = fontObj.fontMatrix || _util.FONT_IDENTITY_MATRIX;
13900      let bold = "normal";
13901
13902      if (fontObj.black) {
13903        bold = "900";
13904      } else if (fontObj.bold) {
13905        bold = "bold";
13906      }
13907
13908      const italic = fontObj.italic ? "italic" : "normal";
13909
13910      if (size < 0) {
13911        size = -size;
13912        current.fontDirection = -1;
13913      } else {
13914        current.fontDirection = 1;
13915      }
13916
13917      current.fontSize = size;
13918      current.fontFamily = fontObj.loadedName;
13919      current.fontWeight = bold;
13920      current.fontStyle = italic;
13921      current.tspan = this.svgFactory.createElement("svg:tspan");
13922      current.tspan.setAttributeNS(null, "y", pf(-current.y));
13923      current.xcoords = [];
13924      current.ycoords = [];
13925    }
13926
13927    endText() {
13928      const current = this.current;
13929
13930      if (current.textRenderingMode & _util.TextRenderingMode.ADD_TO_PATH_FLAG && current.txtElement?.hasChildNodes()) {
13931        current.element = current.txtElement;
13932        this.clip("nonzero");
13933        this.endPath();
13934      }
13935    }
13936
13937    setLineWidth(width) {
13938      if (width > 0) {
13939        this.current.lineWidth = width;
13940      }
13941    }
13942
13943    setLineCap(style) {
13944      this.current.lineCap = LINE_CAP_STYLES[style];
13945    }
13946
13947    setLineJoin(style) {
13948      this.current.lineJoin = LINE_JOIN_STYLES[style];
13949    }
13950
13951    setMiterLimit(limit) {
13952      this.current.miterLimit = limit;
13953    }
13954
13955    setStrokeAlpha(strokeAlpha) {
13956      this.current.strokeAlpha = strokeAlpha;
13957    }
13958
13959    setStrokeRGBColor(r, g, b) {
13960      this.current.strokeColor = _util.Util.makeHexColor(r, g, b);
13961    }
13962
13963    setFillAlpha(fillAlpha) {
13964      this.current.fillAlpha = fillAlpha;
13965    }
13966
13967    setFillRGBColor(r, g, b) {
13968      this.current.fillColor = _util.Util.makeHexColor(r, g, b);
13969      this.current.tspan = this.svgFactory.createElement("svg:tspan");
13970      this.current.xcoords = [];
13971      this.current.ycoords = [];
13972    }
13973
13974    setStrokeColorN(args) {
13975      this.current.strokeColor = this._makeColorN_Pattern(args);
13976    }
13977
13978    setFillColorN(args) {
13979      this.current.fillColor = this._makeColorN_Pattern(args);
13980    }
13981
13982    shadingFill(args) {
13983      const width = this.viewport.width;
13984      const height = this.viewport.height;
13985
13986      const inv = _util.Util.inverseTransform(this.transformMatrix);
13987
13988      const bl = _util.Util.applyTransform([0, 0], inv);
13989
13990      const br = _util.Util.applyTransform([0, height], inv);
13991
13992      const ul = _util.Util.applyTransform([width, 0], inv);
13993
13994      const ur = _util.Util.applyTransform([width, height], inv);
13995
13996      const x0 = Math.min(bl[0], br[0], ul[0], ur[0]);
13997      const y0 = Math.min(bl[1], br[1], ul[1], ur[1]);
13998      const x1 = Math.max(bl[0], br[0], ul[0], ur[0]);
13999      const y1 = Math.max(bl[1], br[1], ul[1], ur[1]);
14000      const rect = this.svgFactory.createElement("svg:rect");
14001      rect.setAttributeNS(null, "x", x0);
14002      rect.setAttributeNS(null, "y", y0);
14003      rect.setAttributeNS(null, "width", x1 - x0);
14004      rect.setAttributeNS(null, "height", y1 - y0);
14005      rect.setAttributeNS(null, "fill", this._makeShadingPattern(args));
14006
14007      if (this.current.fillAlpha < 1) {
14008        rect.setAttributeNS(null, "fill-opacity", this.current.fillAlpha);
14009      }
14010
14011      this._ensureTransformGroup().appendChild(rect);
14012    }
14013
14014    _makeColorN_Pattern(args) {
14015      if (args[0] === "TilingPattern") {
14016        return this._makeTilingPattern(args);
14017      }
14018
14019      return this._makeShadingPattern(args);
14020    }
14021
14022    _makeTilingPattern(args) {
14023      const color = args[1];
14024      const operatorList = args[2];
14025      const matrix = args[3] || _util.IDENTITY_MATRIX;
14026      const [x0, y0, x1, y1] = args[4];
14027      const xstep = args[5];
14028      const ystep = args[6];
14029      const paintType = args[7];
14030      const tilingId = `shading${shadingCount++}`;
14031
14032      const [tx0, ty0, tx1, ty1] = _util.Util.normalizeRect([..._util.Util.applyTransform([x0, y0
14032], matrix), ..._util.Util.applyTransform([x1, y1], matrix)]);
14033
14034      const [xscale, yscale] = _util.Util.singularValueDecompose2dScale(matrix);
14035
14036      const txstep = xstep * xscale;
14037      const tystep = ystep * yscale;
14038      const tiling = this.svgFactory.createElement("svg:pattern");
14039      tiling.setAttributeNS(null, "id", tilingId);
14040      tiling.setAttributeNS(null, "patternUnits", "userSpaceOnUse");
14041      tiling.setAttributeNS(null, "width", txstep);
14042      tiling.setAttributeNS(null, "height", tystep);
14043      tiling.setAttributeNS(null, "x", `${tx0}`);
14044      tiling.setAttributeNS(null, "y", `${ty0}`);
14045      const svg = this.svg;
14046      const transformMatrix = this.transformMatrix;
14047      const fillColor = this.current.fillColor;
14048      const strokeColor = this.current.strokeColor;
14049      const bbox = this.svgFactory.create(tx1 - tx0, ty1 - ty0);
14050      this.svg = bbox;
14051      this.transformMatrix = matrix;
14052
14053      if (paintType === 2) {
14054        const cssColor = _util.Util.makeHexColor(...color);
14055
14056        this.current.fillColor = cssColor;
14057        this.current.strokeColor = cssColor;
14058      }
14059
14060      this.executeOpTree(this.convertOpList(operatorList));
14061      this.svg = svg;
14062      this.transformMatrix = transformMatrix;
14063      this.current.fillColor = fillColor;
14064      this.current.strokeColor = strokeColor;
14065      tiling.appendChild(bbox.childNodes[0]);
14066      this.defs.appendChild(tiling);
14067      return `url(#${tilingId})`;
14068    }
14069
14070    _makeShadingPattern(args) {
14071      if (typeof args === "string") {
14072        args = this.objs.get(args);
14073      }
14074
14075      switch (args[0]) {
14076        case "RadialAxial":
14077          const shadingId = `shading${shadingCount++}`;
14078          const colorStops = args[3];
14079          let gradient;
14080
14081          switch (args[1]) {
14082            case "axial":
14083              const point0 = args[4];
14084              const point1 = args[5];
14085              gradient = this.svgFactory.createElement("svg:linearGradient");
14086              gradient.setAttributeNS(null, "id", shadingId);
14087              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
14088              gradient.setAttributeNS(null, "x1", point0[0]);
14089              gradient.setAttributeNS(null, "y1", point0[1]);
14090              gradient.setAttributeNS(null, "x2", point1[0]);
14091              gradient.setAttributeNS(null, "y2", point1[1]);
14092              break;
14093
14094            case "radial":
14095              const focalPoint = args[4];
14096              const circlePoint = args[5];
14097              const focalRadius = args[6];
14098              const circleRadius = args[7];
14099              gradient = this.svgFactory.createElement("svg:radialGradient");
14100              gradient.setAttributeNS(null, "id", shadingId);
14101              gradient.setAttributeNS(null, "gradientUnits", "userSpaceOnUse");
14102              gradient.setAttributeNS(null, "cx", circlePoint[0]);
14103              gradient.setAttributeNS(null, "cy", circlePoint[1]);
14104              gradient.setAttributeNS(null, "r", circleRadius);
14105              gradient.setAttributeNS(null, "fx", focalPoint[0]);
14106              gradient.setAttributeNS(null, "fy", focalPoint[1]);
14107              gradient.setAttributeNS(null, "fr", focalRadius);
14108              break;
14109
14110            default:
14111              throw new Error(`Unknown RadialAxial type: ${args[1]}`);
14112          }
14113
14114          for (const colorStop of colorStops) {
14115            const stop = this.svgFactory.createElement("svg:stop");
14116            stop.setAttributeNS(null, "offset", colorStop[0]);
14117            stop.setAttributeNS(null, "stop-color", colorStop[1]);
14118            gradient.appendChild(stop);
14119          }
14120
14121          this.defs.appendChild(gradient);
14122          return `url(#${shadingId})`;
14123
14124        case "Mesh":
14125          (0, _util.warn)("Unimplemented pattern Mesh");
14126          return null;
14127
14128        case "Dummy":
14129          return "hotpink";
14130
14131        default:
14132          throw new Error(`Unknown IR type: ${args[0]}`);
14133      }
14134    }
14135
14136    setDash(dashArray, dashPhase) {
14137      this.current.dashArray = dashArray;
14138      this.current.dashPhase = dashPhase;
14139    }
14140
14141    constructPath(ops, args) {
14142      const current = this.current;
14143      let x = current.x,
14144          y = current.y;
14145      let d = [];
14146      let j = 0;
14147
14148      for (const op of ops) {
14149        switch (op | 0) {
14150          case _util.OPS.rectangle:
14151            x = args[j++];
14152            y = args[j++];
14153            const width = args[j++];
14154            const height = args[j++];
14155            const xw = x + width;
14156            const yh = y + height;
14157            d.push("M", pf(x), pf(y), "L", pf(xw), pf(y), "L", pf(xw), pf(yh), "L", pf(x), pf(yh), "Z");
14158            break;
14159
14160          case _util.OPS.moveTo:
14161            x = args[j++];
14162            y = args[j++];
14163            d.push("M", pf(x), pf(y));
14164            break;
14165
14166          case _util.OPS.lineTo:
14167            x = args[j++];
14168            y = args[j++];
14169            d.push("L", pf(x), pf(y));
14170            break;
14171
14172          case _util.OPS.curveTo:
14173            x = args[j + 4];
14174            y = args[j + 5];
14175            d.push("C", pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y));
14176            j += 6;
14177            break;
14178
14179          case _util.OPS.curveTo2:
14180            d.push("C", pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]));
14181            x = args[j + 2];
14182            y = args[j + 3];
14183            j += 4;
14184            break;
14185
14186          case _util.OPS.curveTo3:
14187            x = args[j + 2];
14188            y = args[j + 3];
14189            d.push("C", pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y));
14190            j += 4;
14191            break;
14192
14193          case _util.OPS.closePath:
14194            d.push("Z");
14195            break;
14196        }
14197      }
14198
14199      d = d.join(" ");
14200
14201      if (current.path && ops.length > 0 && ops[0] !== _util.OPS.rectangle && ops[0] !== _util.OPS.moveTo) {
14202        d = current.path.getAttributeNS(null, "d") + d;
14203      } else {
14204        current.path = this.svgFactory.createElement("svg:path");
14205
14206        this._ensureTransformGroup().appendChild(current.path);
14207      }
14208
14209      current.path.setAttributeNS(null, "d", d);
14210      current.path.setAttributeNS(null, "fill", "none");
14211      current.element = current.path;
14212      current.setCurrentPoint(x, y);
14213    }
14214
14215    endPath() {
14216      const current = this.current;
14217      current.path = null;
14218
14219      if (!this.pendingClip) {
14220        return;
14221      }
14222
14223      if (!current.element) {
14224        this.pendingClip = null;
14225        return;
14226      }
14227
14228      const clipId = `clippath${clipCount++}`;
14229      const clipPath = this.svgFactory.createElement("svg:clipPath");
14230      clipPath.setAttributeNS(null, "id", clipId);
14231      clipPath.setAttributeNS(null, "transform", pm(this.transformMatrix));
14232      const clipElement = current.element.cloneNode(true);
14233
14234      if (this.pendingClip === "evenodd") {
14235        clipElement.setAttributeNS(null, "clip-rule", "evenodd");
14236      } else {
14237        clipElement.setAttributeNS(null, "clip-rule", "nonzero");
14238      }
14239
14240      this.pendingClip = null;
14241      clipPath.appendChild(clipElement);
14242      this.defs.appendChild(clipPath);
14243
14244      if (current.activeClipUrl) {
14245        current.clipGroup = null;
14246
14247        for (const prev of this.extraStack) {
14248          prev.clipGroup = null;
14249        }
14250
14251        clipPath.setAttributeNS(null, "clip-path", current.activeClipUrl);
14252      }
14253
14254      current.activeClipUrl = `url(#${clipId})`;
14255      this.tgrp = null;
14256    }
14257
14258    clip(type) {
14259      this.pendingClip = type;
14260    }
14261
14262    closePath() {
14263      const current = this.current;
14264
14265      if (current.path) {
14266        const d = `${current.path.getAttributeNS(null, "d")}Z`;
14267        current.path.setAttributeNS(null, "d", d);
14268      }
14269    }
14270
14271    setLeading(leading) {
14272      this.current.leading = -leading;
14273    }
14274
14275    setTextRise(textRise) {
14276      this.current.textRise = textRise;
14277    }
14278
14279    setTextRenderingMode(textRenderingMode) {
14280      this.current.textRenderingMode = textRenderingMode;
14281    }
14282
14283    setHScale(scale) {
14284      this.current.textHScale = scale / 100;
14285    }
14286
14287    setRenderingIntent(intent) {}
14288
14289    setFlatness(flatness) {}
14290
14291    setGState(states) {
14292      for (const [key, value] of states) {
14293        switch (key) {
14294          case "LW":
14295            this.setLineWidth(value);
14296            break;
14297
14298          case "LC":
14299            this.setLineCap(value);
14300            break;
14301
14302          case "LJ":
14303            this.setLineJoin(value);
14304            break;
14305
14306          case "ML":
14307            this.setMiterLimit(value);
14308            break;
14309
14310          case "D":
14311            this.setDash(value[0], value[1]);
14312            break;
14313
14314          case "RI":
14315            this.setRenderingIntent(value);
14316            break;
14317
14318          case "FL":
14319            this.setFlatness(value);
14320            break;
14321
14322          case "Font":
14323            this.setFont(value);
14324            break;
14325
14326          case "CA":
14327            this.setStrokeAlpha(value);
14328            break;
14329
14330          case "ca":
14331            this.setFillAlpha(value);
14332            break;
14333
14334          default:
14335            (0, _util.warn)(`Unimplemented graphic state operator ${key}`);
14336            break;
14337        }
14338      }
14339    }
14340
14341    fill() {
14342      const current = this.current;
14343
14344      if (current.element) {
14345        current.element.setAttributeNS(null, "fill", current.fillColor);
14346        current.element.setAttributeNS(null, "fill-opacity", current.fillAlpha);
14347        this.endPath();
14348      }
14349    }
14350
14351    stroke() {
14352      const current = this.current;
14353
14354      if (current.element) {
14355        this._setStrokeAttributes(current.element);
14356
14357        current.element.setAttributeNS(null, "fill", "none");
14358        this.endPath();
14359      }
14360    }
14361
14362    _setStrokeAttributes(element, lineWidthScale = 1) {
14363      const current = this.current;
14364      let dashArray = current.dashArray;
14365
14366      if (lineWidthScale !== 1 && dashArray.length > 0) {
14367        dashArray = dashArray.map(function (value) {
14368          return lineWidthScale * value;
14369        });
14370      }
14371
14372      element.setAttributeNS(null, "stroke", current.strokeColor);
14373      element.setAttributeNS(null, "stroke-opacity", current.strokeAlpha);
14374      element.setAttributeNS(null, "stroke-miterlimit", pf(current.miterLimit));
14375      element.setAttributeNS(null, "stroke-linecap", current.lineCap);
14376      element.setAttributeNS(null, "stroke-linejoin", current.lineJoin);
14377      element.setAttributeNS(null, "stroke-width", pf(lineWidthScale * current.lineWidth) + "px");
14378      element.setAttributeNS(null, "stroke-dasharray", dashArray.map(pf).join(" "));
14379      element.setAttributeNS(null, "stroke-dashoffset", pf(lineWidthScale * current.dashPhase) + "px");
14380    }
14381
14382    eoFill() {
14383      if (this.current.element) {
14384        this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
14385      }
14386
14387      this.fill();
14388    }
14389
14390    fillStroke() {
14391      this.stroke();
14392      this.fill();
14393    }
14394
14395    eoFillStroke() {
14396      if (this.current.element) {
14397        this.current.element.setAttributeNS(null, "fill-rule", "evenodd");
14398      }
14399
14400      this.fillStroke();
14401    }
14402
14403    closeStroke() {
14404      this.closePath();
14405      this.stroke();
14406    }
14407
14408    closeFillStroke() {
14409      this.closePath();
14410      this.fillStroke();
14411    }
14412
14413    closeEOFillStroke() {
14414      this.closePath();
14415      this.eoFillStroke();
14416    }
14417
14418    paintSolidColorImageMask() {
14419      const rect = this.svgFactory.createElement("svg:rect");
14420      rect.setAttributeNS(null, "x", "0");
14421      rect.setAttributeNS(null, "y", "0");
14422      rect.setAttributeNS(null, "width", "1px");
14423      rect.setAttributeNS(null, "height", "1px");
14424      rect.setAttributeNS(null, "fill", this.current.fillColor);
14425
14426      this._ensureTransformGroup().appendChild(rect);
14427    }
14428
14429    paintImageXObject(objId) {
14430      const imgData = objId.startsWith("g_") ? this.commonObjs.get(objId) : this.objs.get(objId);
14431
14432      if (!imgData) {
14433        (0, _util.warn)(`Dependent image with object ID ${objId} is not ready yet`);
14434        return;
14435      }
14436
14437      this.paintInlineImageXObject(imgData);
14438    }
14439
14440    paintInlineImageXObject(imgData, mask) {
14441      const width = imgData.width;
14442      const height = imgData.height;
14443      const imgSrc = convertImgDataToPng(imgData, this.forceDataSchema, !!mask);
14444      const cliprect = this.svgFactory.createElement("svg:rect");
14445      cliprect.setAttributeNS(null, "x", "0");
14446      cliprect.setAttributeNS(null, "y", "0");
14447      cliprect.setAttributeNS(null, "width", pf(width));
14448      cliprect.setAttributeNS(null, "height", pf(height));
14449      this.current.element = cliprect;
14450      this.clip("nonzero");
14451      const imgEl = this.svgFactory.createElement("svg:image");
14452      imgEl.setAttributeNS(XLINK_NS, "xlink:href", imgSrc);
14453      imgEl.setAttributeNS(null, "x", "0");
14454      imgEl.setAttributeNS(null, "y", pf(-height));
14455      imgEl.setAttributeNS(null, "width", pf(width) + "px");
14456      imgEl.setAttributeNS(null, "height", pf(height) + "px");
14457      imgEl.setAttributeNS(null, "transform", `scale(${pf(1 / width)} ${pf(-1 / height)})`);
14458
14459      if (mask) {
14460        mask.appendChild(imgEl);
14461      } else {
14462        this._ensureTransformGroup().appendChild(imgEl);
14463      }
14464    }
14465
14466    paintImageMaskXObject(imgData) {
14467      const current = this.current;
14468      const width = imgData.width;
14469      const height = imgData.height;
14470      const fillColor = current.fillColor;
14471      current.maskId = `mask${maskCount++}`;
14472      const mask = this.svgFactory.createElement("svg:mask");
14473      mask.setAttributeNS(null, "id", current.maskId);
14474      const rect = this.svgFactory.createElement("svg:rect");
14475      rect.setAttributeNS(null, "x", "0");
14476      rect.setAttributeNS(null, "y", "0");
14477      rect.setAttributeNS(null, "width", pf(width));
14478      rect.setAttributeNS(null, "height", pf(height));
14479      rect.setAttributeNS(null, "fill", fillColor);
14480      rect.setAttributeNS(null, "mask", `url(#${current.maskId})`);
14481      this.defs.appendChild(mask);
14482
14483      this._ensureTransformGroup().appendChild(rect);
14484
14485      this.paintInlineImageXObject(imgData, mask);
14486    }
14487
14488    paintFormXObjectBegin(matrix, bbox) {
14489      if (Array.isArray(matrix) && matrix.length === 6) {
14490        this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
14491      }
14492
14493      if (bbox) {
14494        const width = bbox[2] - bbox[0];
14495        const height = bbox[3] - bbox[1];
14496        const cliprect = this.svgFactory.createElement("svg:rect");
14497        cliprect.setAttributeNS(null, "x", bbox[0]);
14498        cliprect.setAttributeNS(null, "y", bbox[1]);
14499        cliprect.setAttributeNS(null, "width", pf(width));
14500        cliprect.setAttributeNS(null, "height", pf(height));
14501        this.current.element = cliprect;
14502        this.clip("nonzero");
14503        this.endPath();
14504      }
14505    }
14506
14507    paintFormXObjectEnd() {}
14508
14509    _initialize(viewport) {
14510      const svg = this.svgFactory.create(viewport.width, viewport.height);
14511      const definitions = this.svgFactory.createElement("svg:defs");
14512      svg.appendChild(definitions);
14513      this.defs = definitions;
14514      const rootGroup = this.svgFactory.createElement("svg:g");
14515      rootGroup.setAttributeNS(null, "transform", pm(viewport.transform));
14516      svg.appendChild(rootGroup);
14517      this.svg = rootGroup;
14518      return svg;
14519    }
14520
14521    _ensureClipGroup() {
14522      if (!this.current.clipGroup) {
14523        const clipGroup = this.svgFactory.createElement("svg:g");
14524        clipGroup.setAttributeNS(null, "clip-path", this.current.activeClipUrl);
14525        this.svg.appendChild(clipGroup);
14526        this.current.clipGroup = clipGroup;
14527      }
14528
14529      return this.current.clipGroup;
14530    }
14531
14532    _ensureTransformGroup() {
14533      if (!this.tgrp) {
14534        this.tgrp = this.svgFactory.createElement("svg:g");
14535        this.tgrp.setAttributeNS(null, "transform", pm(this.transformMatrix));
14536
14537        if (this.current.activeClipUrl) {
14538          this._ensureClipGroup().appendChild(this.tgrp);
14539        } else {
14540          this.svg.appendChild(this.tgrp);
14541        }
14542      }
14543
14544      return this.tgrp;
14545    }
14546
14547  };
14548}
14549
14550/***/ }),
14551/* 25 */
14552/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
14553
14554
14555
14556Object.defineProperty(exports, "__esModule", ({
14557  value: true
14558}));
14559exports.PDFNodeStream = void 0;
14560
14561var _util = __w_pdfjs_require__(1);
14562
14563var _network_utils = __w_pdfjs_require__(26);
14564
14565;
14566
14567const fs = require("fs");
14568
14569const http = require("http");
14570
14571const https = require("https");
14572
14573const url = require("url");
14574
14575const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
14576
14577function parseUrl(sourceUrl) {
14578  const parsedUrl = url.parse(sourceUrl);
14579
14580  if (parsedUrl.protocol === "file:" || parsedUrl.host) {
14581    return parsedUrl;
14582  }
14583
14584  if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
14585    return url.parse(`file:///${sourceUrl}`);
14586  }
14587
14588  if (!parsedUrl.host) {
14589    parsedUrl.protocol = "file:";
14590  }
14591
14592  return parsedUrl;
14593}
14594
14595class PDFNodeStream {
14596  constructor(source) {
14597    this.source = source;
14598    this.url = parseUrl(source.url);
14599    this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
14600    this.isFsUrl = this.url.protocol === "file:";
14601    this.httpHeaders = this.isHttp && source.httpHeaders || {};
14602    this._fullRequestReader = null;
14603    this._rangeRequestReaders = [];
14604  }
14605
14606  get _progressiveDataLength() {
14607    return this._fullRequestReader?._loaded ?? 0;
14608  }
14609
14610  getFullReader() {
14611    (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
14612    this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
14613    return this._fullRequestReader;
14614  }
14615
14616  getRangeReader(start, end) {
14617    if (end <= this._progressiveDataLength) {
14618      return null;
14619    }
14620
14621    const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
14622
14623    this._rangeRequestReaders.push(rangeReader);
14624
14625    return rangeReader;
14626  }
14627
14628  cancelAllRequests(reason) {
14629    if (this._fullRequestReader) {
14630      this._fullRequestReader.cancel(reason);
14631    }
14632
14633    for (const reader of this._rangeRequestReaders.slice(0)) {
14634      reader.cancel(reason);
14635    }
14636  }
14637
14638}
14639
14640exports.PDFNodeStream = PDFNodeStream;
14641
14642class BaseFullReader {
14643  constructor(stream) {
14644    this._url = stream.url;
14645    this._done = false;
14646    this._storedError = null;
14647    this.onProgress = null;
14648    const source = stream.source;
14649    this._contentLength = source.length;
14650    this._loaded = 0;
14651    this._filename = null;
14652    this._disableRange = source.disableRange || false;
14653    this._rangeChunkSize = source.rangeChunkSize;
14654
14655    if (!this._rangeChunkSize && !this._disableRange) {
14656      this._disableRange = true;
14657    }
14658
14659    this._isStreamingSupported = !source.disableStream;
14660    this._isRangeSupported = !source.disableRange;
14661    this._readableStream = null;
14662    this._readCapability = (0, _util.createPromiseCapability)();
14663    this._headersCapability = (0, _util.createPromiseCapability)();
14664  }
14665
14666  get headersReady() {
14667    return this._headersCapability.promise;
14668  }
14669
14670  get filename() {
14671    return this._filename;
14672  }
14673
14674  get contentLength() {
14675    return this._contentLength;
14676  }
14677
14678  get isRangeSupported() {
14679    return this._isRangeSupported;
14680  }
14681
14682  get isStreamingSupported() {
14683    return this._isStreamingSupported;
14684  }
14685
14686  async read() {
14687    await this._readCapability.promise;
14688
14689    if (this._done) {
14690      return {
14691        value: undefined,
14692        done: true
14693      };
14694    }
14695
14696    if (this._storedError) {
14697      throw this._storedError;
14698    }
14699
14700    const chunk = this._readableStream.read();
14701
14702    if (chunk === null) {
14703      this._readCapability = (0, _util.createPromiseCapability)();
14704      return this.read();
14705    }
14706
14707    this._loaded += chunk.length;
14708
14709    if (this.onProgress) {
14710      this.onProgress({
14711        loaded: this._loaded,
14712        total: this._contentLength
14713      });
14714    }
14715
14716    const buffer = new Uint8Array(chunk).buffer;
14717    return {
14718      value: buffer,
14719      done: false
14720    };
14721  }
14722
14723  cancel(reason) {
14724    if (!this._readableStream) {
14725      this._error(reason);
14726
14727      return;
14728    }
14729
14730    this._readableStream.destroy(reason);
14731  }
14732
14733  _error(reason) {
14734    this._storedError = reason;
14735
14736    this._readCapability.resolve();
14737  }
14738
14739  _setReadableStream(readableStream) {
14740    this._readableStream = readableStream;
14741    readableStream.on("readable", () => {
14742      this._readCapability.resolve();
14743    });
14744    readableStream.on("end", () => {
14745      readableStream.destroy();
14746      this._done = true;
14747
14748      this._readCapability.resolve();
14749    });
14750    readableStream.on("error", reason => {
14751      this._error(reason);
14752    });
14753
14754    if (!this._isStreamingSupported && this._isRangeSupported) {
14755      this._error(new _util.AbortException("streaming is disabled"));
14756    }
14757
14758    if (this._storedError) {
14759      this._readableStream.destroy(this._storedError);
14760    }
14761  }
14762
14763}
14764
14765class BaseRangeReader {
14766  constructor(stream) {
14767    this._url = stream.url;
14768    this._done = false;
14769    this._storedError = null;
14770    this.onProgress = null;
14771    this._loaded = 0;
14772    this._readableStream = null;
14773    this._readCapability = (0, _util.createPromiseCapability)();
14774    const source = stream.source;
14775    this._isStreamingSupported = !source.disableStream;
14776  }
14777
14778  get isStreamingSupported() {
14779    return this._isStreamingSupported;
14780  }
14781
14782  async read() {
14783    await this._readCapability.promise;
14784
14785    if (this._done) {
14786      return {
14787        value: undefined,
14788        done: true
14789      };
14790    }
14791
14792    if (this._storedError) {
14793      throw this._storedError;
14794    }
14795
14796    const chunk = this._readableStream.read();
14797
14798    if (chunk === null) {
14799      this._readCapability = (0, _util.createPromiseCapability)();
14800      return this.read();
14801    }
14802
14803    this._loaded += chunk.length;
14804
14805    if (this.onProgress) {
14806      this.onProgress({
14807        loaded: this._loaded
14808      });
14809    }
14810
14811    const buffer = new Uint8Array(chunk).buffer;
14812    return {
14813      value: buffer,
14814      done: false
14815    };
14816  }
14817
14818  cancel(reason) {
14819    if (!this._readableStream) {
14820      this._error(reason);
14821
14822      return;
14823    }
14824
14825    this._readableStream.destroy(reason);
14826  }
14827
14828  _error(reason) {
14829    this._storedError = reason;
14830
14831    this._readCapability.resolve();
14832  }
14833
14834  _setReadableStream(readableStream) {
14835    this._readableStream = readableStream;
14836    readableStream.on("readable", () => {
14837      this._readCapability.resolve();
14838    });
14839    readableStream.on("end", () => {
14840      readableStream.destroy();
14841      this._done = true;
14842
14843      this._readCapability.resolve();
14844    });
14845    readableStream.on("error", reason => {
14846      this._error(reason);
14847    });
14848
14849    if (this._storedError) {
14850      this._readableStream.destroy(this._storedError);
14851    }
14852  }
14853
14854}
14855
14856function createRequestOptions(parsedUrl, headers) {
14857  return {
14858    protocol: parsedUrl.protocol,
14859    auth: parsedUrl.auth,
14860    host: parsedUrl.hostname,
14861    port: parsedUrl.port,
14862    path: parsedUrl.path,
14863    method: "GET",
14864    headers
14865  };
14866}
14867
14868class PDFNodeStreamFullReader extends BaseFullReader {
14869  constructor(stream) {
14870    super(stream);
14871
14872    const handleResponse = response => {
14873      if (response.statusCode === 404) {
14874        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
14875        this._storedError = error;
14876
14877        this._headersCapability.reject(error);
14878
14879        return;
14880      }
14881
14882      this._headersCapability.resolve();
14883
14884      this._setReadableStream(response);
14885
14886      const getResponseHeader = name => {
14887        return this._readableStream.headers[name.toLowerCase()];
14888      };
14889
14890      const {
14891        allowRangeRequests,
14892        suggestedLength
14893      } = (0, _network_utils.validateRangeRequestCapabilities)({
14894        getResponseHeader,
14895        isHttp: stream.isHttp,
14896        rangeChunkSize: this._rangeChunkSize,
14897        disableRange: this._disableRange
14898      });
14899      this._isRangeSupported = allowRangeRequests;
14900      this._contentLength = suggestedLength || this._contentLength;
14901      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
14902    };
14903
14904    this._request = null;
14905
14906    if (this._url.protocol === "http:") {
14907      this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
14908    } else {
14909      this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
14910    }
14911
14912    this._request.on("error", reason => {
14913      this._storedError = reason;
14914
14915      this._headersCapability.reject(reason);
14916    });
14917
14918    this._request.end();
14919  }
14920
14921}
14922
14923class PDFNodeStreamRangeReader extends BaseRangeReader {
14924  constructor(stream, start, end) {
14925    super(stream);
14926    this._httpHeaders = {};
14927
14928    for (const property in stream.httpHeaders) {
14929      const value = stream.httpHeaders[property];
14930
14931      if (typeof value === "undefined") {
14932        continue;
14933      }
14934
14935      this._httpHeaders[property] = value;
14936    }
14937
14938    this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
14939
14940    const handleResponse = response => {
14941      if (response.statusCode === 404) {
14942        const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
14943        this._storedError = error;
14944        return;
14945      }
14946
14947      this._setReadableStream(response);
14948    };
14949
14950    this._request = null;
14951
14952    if (this._url.protocol === "http:") {
14953      this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
14954    } else {
14955      this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
14956    }
14957
14958    this._request.on("error", reason => {
14959      this._storedError = reason;
14960    });
14961
14962    this._request.end();
14963  }
14964
14965}
14966
14967class PDFNodeStreamFsFullReader extends BaseFullReader {
14968  constructor(stream) {
14969    super(stream);
14970    let path = decodeURIComponent(this._url.path);
14971
14972    if (fileUriRegex.test(this._url.href)) {
14973      path = path.replace(/^\//, "");
14974    }
14975
14976    fs.lstat(path, (error, stat) => {
14977      if (error) {
14978        if (error.code === "ENOENT") {
14979          error = new _util.MissingPDFException(`Missing PDF "${path}".`);
14980        }
14981
14982        this._storedError = error;
14983
14984        this._headersCapability.reject(error);
14985
14986        return;
14987      }
14988
14989      this._contentLength = stat.size;
14990
14991      this._setReadableStream(fs.createReadStream(path));
14992
14993      this._headersCapability.resolve();
14994    });
14995  }
14996
14997}
14998
14999class PDFNodeStreamFsRangeReader extends BaseRangeReader {
15000  constructor(stream, start, end) {
15001    super(stream);
15002    let path = decodeURIComponent(this._url.path);
15003
15004    if (fileUriRegex.test(this._url.href)) {
15005      path = path.replace(/^\//, "");
15006    }
15007
15008    this._setReadableStream(fs.createReadStream(path, {
15009      start,
15010      end: end - 1
15011    }));
15012  }
15013
15014}
15015
15016/***/ }),
15017/* 26 */
15018/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
15019
15020
15021
15022Object.defineProperty(exports, "__esModule", ({
15023  value: true
15024}));
15025exports.createResponseStatusError = createResponseStatusError;
15026exports.extractFilenameFromHeader = extractFilenameFromHeader;
15027exports.validateRangeRequestCapabilities = validateRangeRequestCapabilities;
15028exports.validateResponseStatus = validateResponseStatus;
15029
15030var _util = __w_pdfjs_require__(1);
15031
15032var _content_disposition = __w_pdfjs_require__(27);
15033
15034var _display_utils = __w_pdfjs_require__(5);
15035
15036function validateRangeRequestCapabilities({
15037  getResponseHeader,
15038  isHttp,
15039  rangeChunkSize,
15040  disableRange
15041}) {
15042  const returnValues = {
15043    allowRangeRequests: false,
15044    suggestedLength: undefined
15045  };
15046  const length = parseInt(getResponseHeader("Content-Length"), 10);
15047
15048  if (!Number.isInteger(length)) {
15049    return returnValues;
15050  }
15051
15052  returnValues.suggestedLength = length;
15053
15054  if (length <= 2 * rangeChunkSize) {
15055    return returnValues;
15056  }
15057
15058  if (disableRange || !isHttp) {
15059    return returnValues;
15060  }
15061
15062  if (getResponseHeader("Accept-Ranges") !== "bytes") {
15063    return returnValues;
15064  }
15065
15066  const contentEncoding = getResponseHeader("Content-Encoding") || "identity";
15067
15068  if (contentEncoding !== "identity") {
15069    return returnValues;
15070  }
15071
15072  returnValues.allowRangeRequests = true;
15073  return returnValues;
15074}
15075
15076function extractFilenameFromHeader(getResponseHeader) {
15077  const contentDisposition = getResponseHeader("Content-Disposition");
15078
15079  if (contentDisposition) {
15080    let filename = (0, _content_disposition.getFilenameFromContentDispositionHeader)(contentDisposition);
15081
15082    if (filename.includes("%")) {
15083      try {
15084        filename = decodeURIComponent(filename);
15085      } catch (ex) {}
15086    }
15087
15088    if ((0, _display_utils.isPdfFile)(filename)) {
15089      return filename;
15090    }
15091  }
15092
15093  return null;
15094}
15095
15096function createResponseStatusError(status, url) {
15097  if (status === 404 || status === 0 && url.startsWith("file:")) {
15098    return new _util.MissingPDFException('Missing PDF "' + url + '".');
15099  }
15100
15101  return new _util.UnexpectedResponseException(`Unexpected server response (${status}) while retrieving PDF "${url}".`, status);
15102}
15103
15104function validateResponseStatus(status) {
15105  return status === 200 || status === 206;
15106}
15107
15108/***/ }),
15109/* 27 */
15110/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
15111
15112
15113
15114Object.defineProperty(exports, "__esModule", ({
15115  value: true
15116}));
15117exports.getFilenameFromContentDispositionHeader = getFilenameFromContentDispositionHeader;
15118
15119var _util = __w_pdfjs_require__(1);
15120
15121function getFilenameFromContentDispositionHeader(contentDisposition) {
15122  let needsEncodingFixup = true;
15123  let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
15124
15125  if (tmp) {
15126    tmp = tmp[1];
15127    let filename = rfc2616unquote(tmp);
15128    filename = unescape(filename);
15129    filename = rfc5987decode(filename);
15130    filename = rfc2047decode(filename);
15131    return fixupEncoding(filename);
15132  }
15133
15134  tmp = rfc2231getparam(contentDisposition);
15135
15136  if (tmp) {
15137    const filename = rfc2047decode(tmp);
15138    return fixupEncoding(filename);
15139  }
15140
15141  tmp = toParamRegExp("filename", "i").exec(contentDisposition);
15142
15143  if (tmp) {
15144    tmp = tmp[1];
15145    let filename = rfc2616unquote(tmp);
15146    filename = rfc2047decode(filename);
15147    return fixupEncoding(filename);
15148  }
15149
15150  function toParamRegExp(attributePattern, flags) {
15151    return new RegExp("(?:^|;)\\s*" + attributePattern + "\\s*=\\s*" + "(" + '[^";\\s][^;\\s]*' + "|" + '"(?:[^"\\\\]|\\\\"?)+"?' + ")", flags);
15152  }
15153
15154  function textdecode(encoding, value) {
15155    if (encoding) {
15156      if (!/^[\x00-\xFF]+$/.test(value)) {
15157        return value;
15158      }
15159
15160      try {
15161        const decoder = new TextDecoder(encoding, {
15162          fatal: true
15163        });
15164        const buffer = (0, _util.stringToBytes)(value);
15165        value = decoder.decode(buffer);
15166        needsEncodingFixup = false;
15167      } catch (e) {}
15168    }
15169
15170    return value;
15171  }
15172
15173  function fixupEncoding(value) {
15174    if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
15175      value = textdecode("utf-8", value);
15176
15177      if (needsEncodingFixup) {
15178        value = textdecode("iso-8859-1", value);
15179      }
15180    }
15181
15182    return value;
15183  }
15184
15185  function rfc2231getparam(contentDispositionStr) {
15186    const matches = [];
15187    let match;
15188    const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
15189
15190    while ((match = iter.exec(contentDispositionStr)) !== null) {
15191      let [, n, quot, part] = match;
15192      n = parseInt(n, 10);
15193
15194      if (n in matches) {
15195        if (n === 0) {
15196          break;
15197        }
15198
15199        continue;
15200      }
15201
15202      matches[n] = [quot, part];
15203    }
15204
15205    const parts = [];
15206
15207    for (let n = 0; n < matches.length; ++n) {
15208      if (!(n in matches)) {
15209        break;
15210      }
15211
15212      let [quot, part] = matches[n];
15213      part = rfc2616unquote(part);
15214
15215      if (quot) {
15216        part = unescape(part);
15217
15218        if (n === 0) {
15219          part = rfc5987decode(part);
15220        }
15221      }
15222
15223      parts.push(part);
15224    }
15225
15226    return parts.join("");
15227  }
15228
15229  function rfc2616unquote(value) {
15230    if (value.startsWith('"')) {
15231      const parts = value.slice(1).split('\\"');
15232
15233      for (let i = 0; i < parts.length; ++i) {
15234        const quotindex = parts[i].indexOf('"');
15235
15236        if (quotindex !== -1) {
15237          parts[i] = parts[i].slice(0, quotindex);
15238          parts.length = i + 1;
15239        }
15240
15241        parts[i] = parts[i].replace(/\\(.)/g, "$1");
15242      }
15243
15244      value = parts.join('"');
15245    }
15246
15247    return value;
15248  }
15249
15250  function rfc5987decode(extvalue) {
15251    const encodingend = extvalue.indexOf("'");
15252
15253    if (encodingend === -1) {
15254      return extvalue;
15255    }
15256
15257    const encoding = extvalue.slice(0, encodingend);
15258    const langvalue = extvalue.slice(encodingend + 1);
15259    const value = langvalue.replace(/^[^']*'/, "");
15260    return textdecode(encoding, value);
15261  }
15262
15263  function rfc2047decode(value) {
15264    if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
15265      return value;
15266    }
15267
15268    return value.replace(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g, function (matches, charset, encoding, text) {
15269      if (encoding === "q" || encoding === "Q") {
15270        text = text.replace(/_/g, " ");
15271        text = text.replace(/=([0-9a-fA-F]{2})/g, function (match, hex) {
15272          return String.fromCharCode(parseInt(hex, 16));
15273        });
15274        return textdecode(charset, text);
15275      }
15276
15277      try {
15278        text = atob(text);
15279      } catch (e) {}
15280
15281      return textdecode(charset, text);
15282    });
15283  }
15284
15285  return "";
15286}
15287
15288/***/ }),
15289/* 28 */
15290/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
15291
15292
15293
15294Object.defineProperty(exports, "__esModule", ({
15295  value: true
15296}));
15297exports.PDFNetworkStream = void 0;
15298
15299var _util = __w_pdfjs_require__(1);
15300
15301var _network_utils = __w_pdfjs_require__(26);
15302
15303;
15304const OK_RESPONSE = 200;
15305const PARTIAL_CONTENT_RESPONSE = 206;
15306
15307function getArrayBuffer(xhr) {
15308  const data = xhr.response;
15309
15310  if (typeof data !== "string") {
15311    return data;
15312  }
15313
15314  const array = (0, _util.stringToBytes)(data);
15315  return array.buffer;
15316}
15317
15318class NetworkManager {
15319  constructor(url, args = {}) {
15320    this.url = url;
15321    this.isHttp = /^https?:/i.test(url);
15322    this.httpHeaders = this.isHttp && args.httpHeaders || Object.create(null);
15323    this.withCredentials = args.withCredentials || false;
15324
15325    this.getXhr = args.getXhr || function NetworkManager_getXhr() {
15326      return new XMLHttpRequest();
15327    };
15328
15329    this.currXhrId = 0;
15330    this.pendingRequests = Object.create(null);
15331  }
15332
15333  requestRange(begin, end, listeners) {
15334    const args = {
15335      begin,
15336      end
15337    };
15338
15339    for (const prop in listeners) {
15340      args[prop] = listeners[prop];
15341    }
15342
15343    return this.request(args);
15344  }
15345
15346  requestFull(listeners) {
15347    return this.request(listeners);
15348  }
15349
15350  request(args) {
15351    const xhr = this.getXhr();
15352    const xhrId = this.currXhrId++;
15353    const pendingRequest = this.pendingRequests[xhrId] = {
15354      xhr
15355    };
15356    xhr.open("GET", this.url);
15357    xhr.withCredentials = this.withCredentials;
15358
15359    for (const property in this.httpHeaders) {
15360      const value = this.httpHeaders[property];
15361
15362      if (typeof value === "undefined") {
15363        continue;
15364      }
15365
15366      xhr.setRequestHeader(property, value);
15367    }
15368
15369    if (this.isHttp && "begin" in args && "end" in args) {
15370      xhr.setRequestHeader("Range", `bytes=${args.begin}-${args.end - 1}`);
15371      pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
15372    } else {
15373      pendingRequest.expectedStatus = OK_RESPONSE;
15374    }
15375
15376    xhr.responseType = "arraybuffer";
15377
15378    if (args.onError) {
15379      xhr.onerror = function (evt) {
15380        args.onError(xhr.status);
15381      };
15382    }
15383
15384    xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
15385    xhr.onprogress = this.onProgress.bind(this, xhrId);
15386    pendingRequest.onHeadersReceived = args.onHeadersReceived;
15387    pendingRequest.onDone = args.onDone;
15388    pendingRequest.onError = args.onError;
15389    pendingRequest.onProgress = args.onProgress;
15390    xhr.send(null);
15391    return xhrId;
15392  }
15393
15394  onProgress(xhrId, evt) {
15395    const pendingRequest = this.pendingRequests[xhrId];
15396
15397    if (!pendingRequest) {
15398      return;
15399    }
15400
15401    pendingRequest.onProgress?.(evt);
15402  }
15403
15404  onStateChange(xhrId, evt) {
15405    const pendingRequest = this.pendingRequests[xhrId];
15406
15407    if (!pendingRequest) {
15408      return;
15409    }
15410
15411    const xhr = pendingRequest.xhr;
15412
15413    if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
15414      pendingRequest.onHeadersReceived();
15415      delete pendingRequest.onHeadersReceived;
15416    }
15417
15418    if (xhr.readyState !== 4) {
15419      return;
15420    }
15421
15422    if (!(xhrId in this.pendingRequests)) {
15423      return;
15424    }
15425
15426    delete this.pendingRequests[xhrId];
15427
15428    if (xhr.status === 0 && this.isHttp) {
15429      pendingRequest.onError?.(xhr.status);
15430      return;
15431    }
15432
15433    const xhrStatus = xhr.status || OK_RESPONSE;
15434    const ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
15435
15436    if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
15437      pendingRequest.onError?.(xhr.status);
15438      return;
15439    }
15440
15441    const chunk = getArrayBuffer(xhr);
15442
15443    if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
15444      const rangeHeader = xhr.getResponseHeader("Content-Range");
15445      const matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
15446      pendingRequest.onDone({
15447        begin: parseInt(matches[1], 10),
15448        chunk
15449      });
15450    } else if (chunk) {
15451      pendingRequest.onDone({
15452        begin: 0,
15453        chunk
15454      });
15455    } else {
15456      pendingRequest.onError?.(xhr.status);
15457    }
15458  }
15459
15460  getRequestXhr(xhrId) {
15461    return this.pendingRequests[xhrId].xhr;
15462  }
15463
15464  isPendingRequest(xhrId) {
15465    return xhrId in this.pendingRequests;
15466  }
15467
15468  abortRequest(xhrId) {
15469    const xhr = this.pendingRequests[xhrId].xhr;
15470    delete this.pendingRequests[xhrId];
15471    xhr.abort();
15472  }
15473
15474}
15475
15476class PDFNetworkStream {
15477  constructor(source) {
15478    this._source = source;
15479    this._manager = new NetworkManager(source.url, {
15480      httpHeaders: source.httpHeaders,
15481      withCredentials: source.withCredentials
15482    });
15483    this._rangeChunkSize = source.rangeChunkSize;
15484    this._fullRequestReader = null;
15485    this._rangeRequestReaders = [];
15486  }
15487
15488  _onRangeRequestReaderClosed(reader) {
15489    const i = this._rangeRequestReaders.indexOf(reader);
15490
15491    if (i >= 0) {
15492      this._rangeRequestReaders.splice(i, 1);
15493    }
15494  }
15495
15496  getFullReader() {
15497    (0, _util.assert)(!this._fullRequestReader, "PDFNetworkStream.getFullReader can only be called once.");
15498    this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
15499    return this._fullRequestReader;
15500  }
15501
15502  getRangeReader(begin, end) {
15503    const reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
15504    reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
15505
15506    this._rangeRequestReaders.push(reader);
15507
15508    return reader;
15509  }
15510
15511  cancelAllRequests(reason) {
15512    this._fullRequestReader?.cancel(reason);
15513
15514    for (const reader of this._rangeRequestReaders.slice(0)) {
15515      reader.cancel(reason);
15516    }
15517  }
15518
15519}
15520
15521exports.PDFNetworkStream = PDFNetworkStream;
15522
15523class PDFNetworkStreamFullRequestReader {
15524  constructor(manager, source) {
15525    this._manager = manager;
15526    const args = {
15527      onHeadersReceived: this._onHeadersReceived.bind(this),
15528      onDone: this._onDone.bind(this),
15529      onError: this._onError.bind(this),
15530      onProgress: this._onProgress.bind(this)
15531    };
15532    this._url = source.url;
15533    this._fullRequestId = manager.requestFull(args);
15534    this._headersReceivedCapability = (0, _util.createPromiseCapability)();
15535    this._disableRange = source.disableRange || false;
15536    this._contentLength = source.length;
15537    this._rangeChunkSize = source.rangeChunkSize;
15538
15539    if (!this._rangeChunkSize && !this._disableRange) {
15540      this._disableRange = true;
15541    }
15542
15543    this._isStreamingSupported = false;
15544    this._isRangeSupported = false;
15545    this._cachedChunks = [];
15546    this._requests = [];
15547    this._done = false;
15548    this._storedError = undefined;
15549    this._filename = null;
15550    this.onProgress = null;
15551  }
15552
15553  _onHeadersReceived() {
15554    const fullRequestXhrId = this._fullRequestId;
15555
15556    const fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
15557
15558    const getResponseHeader = name => {
15559      return fullRequestXhr.getResponseHeader(name);
15560    };
15561
15562    const {
15563      allowRangeRequests,
15564      suggestedLength
15565    } = (0, _network_utils.validateRangeRequestCapabilities)({
15566      getResponseHeader,
15567      isHttp: this._manager.isHttp,
15568      rangeChunkSize: this._rangeChunkSize,
15569      disableRange: this._disableRange
15570    });
15571
15572    if (allowRangeRequests) {
15573      this._isRangeSupported = true;
15574    }
15575
15576    this._contentLength = suggestedLength || this._contentLength;
15577    this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
15578
15579    if (this._isRangeSupported) {
15580      this._manager.abortRequest(fullRequestXhrId);
15581    }
15582
15583    this._headersReceivedCapability.resolve();
15584  }
15585
15586  _onDone(data) {
15587    if (data) {
15588      if (this._requests.length > 0) {
15589        const requestCapability = this._requests.shift();
15590
15591        requestCapability.resolve({
15592          value: data.chunk,
15593          done: false
15594        });
15595      } else {
15596        this._cachedChunks.push(data.chunk);
15597      }
15598    }
15599
15600    this._done = true;
15601
15602    if (this._cachedChunks.length > 0) {
15603      return;
15604    }
15605
15606    for (const requestCapability of this._requests) {
15607      requestCapability.resolve({
15608        value: undefined,
15609        done: true
15610      });
15611    }
15612
15613    this._requests.length = 0;
15614  }
15615
15616  _onError(status) {
15617    this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
15618
15619    this._headersReceivedCapability.reject(this._storedError);
15620
15621    for (const requestCapability of this._requests) {
15622      requestCapability.reject(this._storedError);
15623    }
15624
15625    this._requests.length = 0;
15626    this._cachedChunks.length = 0;
15627  }
15628
15629  _onProgress(evt) {
15630    this.onProgress?.({
15631      loaded: evt.loaded,
15632      total: evt.lengthComputable ? evt.total : this._contentLength
15633    });
15634  }
15635
15636  get filename() {
15637    return this._filename;
15638  }
15639
15640  get isRangeSupported() {
15641    return this._isRangeSupported;
15642  }
15643
15644  get isStreamingSupported() {
15645    return this._isStreamingSupported;
15646  }
15647
15648  get contentLength() {
15649    return this._contentLength;
15650  }
15651
15652  get headersReady() {
15653    return this._headersReceivedCapability.promise;
15654  }
15655
15656  async read() {
15657    if (this._storedError) {
15658      throw this._storedError;
15659    }
15660
15661    if (this._cachedChunks.length > 0) {
15662      const chunk = this._cachedChunks.shift();
15663
15664      return {
15665        value: chunk,
15666        done: false
15667      };
15668    }
15669
15670    if (this._done) {
15671      return {
15672        value: undefined,
15673        done: true
15674      };
15675    }
15676
15677    const requestCapability = (0, _util.createPromiseCapability)();
15678
15679    this._requests.push(requestCapability);
15680
15681    return requestCapability.promise;
15682  }
15683
15684  cancel(reason) {
15685    this._done = true;
15686
15687    this._headersReceivedCapability.reject(reason);
15688
15689    for (const requestCapability of this._requests) {
15690      requestCapability.resolve({
15691        value: undefined,
15692        done: true
15693      });
15694    }
15695
15696    this._requests.length = 0;
15697
15698    if (this._manager.isPendingRequest(this._fullRequestId)) {
15699      this._manager.abortRequest(this._fullRequestId);
15700    }
15701
15702    this._fullRequestReader = null;
15703  }
15704
15705}
15706
15707class PDFNetworkStreamRangeRequestReader {
15708  constructor(manager, begin, end) {
15709    this._manager = manager;
15710    const args = {
15711      onDone: this._onDone.bind(this),
15712      onError: this._onError.bind(this),
15713      onProgress: this._onProgress.bind(this)
15714    };
15715    this._url = manager.url;
15716    this._requestId = manager.requestRange(begin, end, args);
15717    this._requests = [];
15718    this._queuedChunk = null;
15719    this._done = false;
15720    this._storedError = undefined;
15721    this.onProgress = null;
15722    this.onClosed = null;
15723  }
15724
15725  _close() {
15726    this.onClosed?.(this);
15727  }
15728
15729  _onDone(data) {
15730    const chunk = data.chunk;
15731
15732    if (this._requests.length > 0) {
15733      const requestCapability = this._requests.shift();
15734
15735      requestCapability.resolve({
15736        value: chunk,
15737        done: false
15738      });
15739    } else {
15740      this._queuedChunk = chunk;
15741    }
15742
15743    this._done = true;
15744
15745    for (const requestCapability of this._requests) {
15746      requestCapability.resolve({
15747        value: undefined,
15748        done: true
15749      });
15750    }
15751
15752    this._requests.length = 0;
15753
15754    this._close();
15755  }
15756
15757  _onError(status) {
15758    this._storedError = (0, _network_utils.createResponseStatusError)(status, this._url);
15759
15760    for (const requestCapability of this._requests) {
15761      requestCapability.reject(this._storedError);
15762    }
15763
15764    this._requests.length = 0;
15765    this._queuedChunk = null;
15766  }
15767
15768  _onProgress(evt) {
15769    if (!this.isStreamingSupported) {
15770      this.onProgress?.({
15771        loaded: evt.loaded
15772      });
15773    }
15774  }
15775
15776  get isStreamingSupported() {
15777    return false;
15778  }
15779
15780  async read() {
15781    if (this._storedError) {
15782      throw this._storedError;
15783    }
15784
15785    if (this._queuedChunk !== null) {
15786      const chunk = this._queuedChunk;
15787      this._queuedChunk = null;
15788      return {
15789        value: chunk,
15790        done: false
15791      };
15792    }
15793
15794    if (this._done) {
15795      return {
15796        value: undefined,
15797        done: true
15798      };
15799    }
15800
15801    const requestCapability = (0, _util.createPromiseCapability)();
15802
15803    this._requests.push(requestCapability);
15804
15805    return requestCapability.promise;
15806  }
15807
15808  cancel(reason) {
15809    this._done = true;
15810
15811    for (const requestCapability of this._requests) {
15812      requestCapability.resolve({
15813        value: undefined,
15814        done: true
15815      });
15816    }
15817
15818    this._requests.length = 0;
15819
15820    if (this._manager.isPendingRequest(this._requestId)) {
15821      this._manager.abortRequest(this._requestId);
15822    }
15823
15824    this._close();
15825  }
15826
15827}
15828
15829/***/ }),
15830/* 29 */
15831/***/ ((__unused_webpack_module, exports, __w_pdfjs_require__) => {
15832
15833
15834
15835Object.defineProperty(exports, "__esModule", ({
15836  value: true
15837}));
15838exports.PDFFetchStream = void 0;
15839
15840var _util = __w_pdfjs_require__(1);
15841
15842var _network_utils = __w_pdfjs_require__(26);
15843
15844;
15845
15846function createFetchOptions(headers, withCredentials, abortController) {
15847  return {
15848    method: "GET",
15849    headers,
15850    signal: abortController?.signal,
15851    mode: "cors",
15852    credentials: withCredentials ? "include" : "same-origin",
15853    redirect: "follow"
15854  };
15855}
15856
15857function createHeaders(httpHeaders) {
15858  const headers = new Headers();
15859
15860  for (const property in httpHeaders) {
15861    const value = httpHeaders[property];
15862
15863    if (typeof value === "undefined") {
15864      continue;
15865    }
15866
15867    headers.append(property, value);
15868  }
15869
15870  return headers;
15871}
15872
15873class PDFFetchStream {
15874  constructor(source) {
15875    this.source = source;
15876    this.isHttp = /^https?:/i.test(source.url);
15877    this.httpHeaders = this.isHttp && source.httpHeaders || {};
15878    this._fullRequestReader = null;
15879    this._rangeRequestReaders = [];
15880  }
15881
15882  get _progressiveDataLength() {
15883    return this._fullRequestReader?._loaded ?? 0;
15884  }
15885
15886  getFullReader() {
15887    (0, _util.assert)(!this._fullRequestReader, "PDFFetchStream.getFullReader can only be called once.");
15888    this._fullRequestReader = new PDFFetchStreamReader(this);
15889    return this._fullRequestReader;
15890  }
15891
15892  getRangeReader(begin, end) {
15893    if (end <= this._progressiveDataLength) {
15894      return null;
15895    }
15896
15897    const reader = new PDFFetchStreamRangeReader(this, begin, end);
15898
15899    this._rangeRequestReaders.push(reader);
15900
15901    return reader;
15902  }
15903
15904  cancelAllRequests(reason) {
15905    if (this._fullRequestReader) {
15906      this._fullRequestReader.cancel(reason);
15907    }
15908
15909    for (const reader of this._rangeRequestReaders.slice(0)) {
15910      reader.cancel(reason);
15911    }
15912  }
15913
15914}
15915
15916exports.PDFFetchStream = PDFFetchStream;
15917
15918class PDFFetchStreamReader {
15919  constructor(stream) {
15920    this._stream = stream;
15921    this._reader = null;
15922    this._loaded = 0;
15923    this._filename = null;
15924    const source = stream.source;
15925    this._withCredentials = source.withCredentials || false;
15926    this._contentLength = source.length;
15927    this._headersCapability = (0, _util.createPromiseCapability)();
15928    this._disableRange = source.disableRange || false;
15929    this._rangeChunkSize = source.rangeChunkSize;
15930
15931    if (!this._rangeChunkSize && !this._disableRange) {
15932      this._disableRange = true;
15933    }
15934
15935    if (typeof AbortController !== "undefined") {
15936      this._abortController = new AbortController();
15937    }
15938
15939    this._isStreamingSupported = !source.disableStream;
15940    this._isRangeSupported = !source.disableRange;
15941    this._headers = createHeaders(this._stream.httpHeaders);
15942    const url = source.url;
15943    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
15944      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
15945        throw (0, _network_utils.createResponseStatusError)(response.status, url);
15946      }
15947
15948      this._reader = response.body.getReader();
15949
15950      this._headersCapability.resolve();
15951
15952      const getResponseHeader = name => {
15953        return response.headers.get(name);
15954      };
15955
15956      const {
15957        allowRangeRequests,
15958        suggestedLength
15959      } = (0, _network_utils.validateRangeRequestCapabilities)({
15960        getResponseHeader,
15961        isHttp: this._stream.isHttp,
15962        rangeChunkSize: this._rangeChunkSize,
15963        disableRange: this._disableRange
15964      });
15965      this._isRangeSupported = allowRangeRequests;
15966      this._contentLength = suggestedLength || this._contentLength;
15967      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
15968
15969      if (!this._isStreamingSupported && this._isRangeSupported) {
15970        this.cancel(new _util.AbortException("Streaming is disabled."));
15971      }
15972    }).catch(this._headersCapability.reject);
15973    this.onProgress = null;
15974  }
15975
15976  get headersReady() {
15977    return this._headersCapability.promise;
15978  }
15979
15980  get filename() {
15981    return this._filename;
15982  }
15983
15984  get contentLength() {
15985    return this._contentLength;
15986  }
15987
15988  get isRangeSupported() {
15989    return this._isRangeSupported;
15990  }
15991
15992  get isStreamingSupported() {
15993    return this._isStreamingSupported;
15994  }
15995
15996  async read() {
15997    await this._headersCapability.promise;
15998    const {
15999      value,
16000      done
16001    } = await this._reader.read();
16002
16003    if (done) {
16004      return {
16005        value,
16006        done
16007      };
16008    }
16009
16010    this._loaded += value.byteLength;
16011
16012    if (this.onProgress) {
16013      this.onProgress({
16014        loaded: this._loaded,
16015        total: this._contentLength
16016      });
16017    }
16018
16019    const buffer = new Uint8Array(value).buffer;
16020    return {
16021      value: buffer,
16022      done: false
16023    };
16024  }
16025
16026  cancel(reason) {
16027    if (this._reader) {
16028      this._reader.cancel(reason);
16029    }
16030
16031    if (this._abortController) {
16032      this._abortController.abort();
16033    }
16034  }
16035
16036}
16037
16038class PDFFetchStreamRangeReader {
16039  constructor(stream, begin, end) {
16040    this._stream = stream;
16041    this._reader = null;
16042    this._loaded = 0;
16043    const source = stream.source;
16044    this._withCredentials = source.withCredentials || false;
16045    this._readCapability = (0, _util.createPromiseCapability)();
16046    this._isStreamingSupported = !source.disableStream;
16047
16048    if (typeof AbortController !== "undefined") {
16049      this._abortController = new AbortController();
16050    }
16051
16052    this._headers = createHeaders(this._stream.httpHeaders);
16053
16054    this._headers.append("Range", `bytes=${begin}-${end - 1}`);
16055
16056    const url = source.url;
16057    fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(response => {
16058      if (!(0, _network_utils.validateResponseStatus)(response.status)) {
16059        throw (0, _network_utils.createResponseStatusError)(response.status, url);
16060      }
16061
16062      this._readCapability.resolve();
16063
16064      this._reader = response.body.getReader();
16065    }).catch(this._readCapability.reject);
16066    this.onProgress = null;
16067  }
16068
16069  get isStreamingSupported() {
16070    return this._isStreamingSupported;
16071  }
16072
16073  async read() {
16074    await this._readCapability.promise;
16075    const {
16076      value,
16077      done
16078    } = await this._reader.read();
16079
16080    if (done) {
16081      return {
16082        value,
16083        done
16084      };
16085    }
16086
16087    this._loaded += value.byteLength;
16088
16089    if (this.onProgress) {
16090      this.onProgress({
16091        loaded: this._loaded
16092      });
16093    }
16094
16095    const buffer = new Uint8Array(value).buffer;
16096    return {
16097      value: buffer,
16098      done: false
16099    };
16100  }
16101
16102  cancel(reason) {
16103    if (this._reader) {
16104      this._reader.cancel(reason);
16105    }
16106
16107    if (this._abortController) {
16108      this._abortController.abort();
16109    }
16110  }
16111
16112}
16113
16114/***/ })
16115/******/ 	]);
16116/************************************************************************/
16117/******/ 	// The module cache
16118/******/ 	var __webpack_module_cache__ = {};
16119/******/ 	
16120/******/ 	// The require function
16121/******/ 	function __w_pdfjs_require__(moduleId) {
16122/******/ 		// Check if module is in cache
16123/******/ 		var cachedModule = __webpack_module_cache__[moduleId];
16124/******/ 		if (cachedModule !== undefined) {
16125/******/ 			return cachedModule.exports;
16126/******/ 		}
16127/******/ 		// Create a new module (and put it into the cache)
16128/******/ 		var module = __webpack_module_cache__[moduleId] = {
16129/******/ 			// no module.id needed
16130/******/ 			// no module.loaded needed
16131/******/ 			exports: {}
16132/******/ 		};
16133/******/ 	
16134/******/ 		// Execute the module function
16135/******/ 		__webpack_modules__[moduleId](module, module.exports, __w_pdfjs_require__);
16136/******/ 	
16137/******/ 		// Return the exports of the module
16138/******/ 		return module.exports;
16139/******/ 	}
16140/******/ 	
16141/************************************************************************/
16142var __webpack_exports__ = {};
16143// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
16144(() => {
16145var exports = __webpack_exports__;
16146
16147
16148Object.defineProperty(exports, "__esModule", ({
16149  value: true
16150}));
16151Object.defineProperty(exports, "AnnotationLayer", ({
16152  enumerable: true,
16153  get: function () {
16154    return _annotation_layer.AnnotationLayer;
16155  }
16156}));
16157Object.defineProperty(exports, "AnnotationMode", ({
16158  enumerable: true,
16159  get: function () {
16160    return _util.AnnotationMode;
16161  }
16162}));
16163Object.defineProperty(exports, "CMapCompressionType", ({
16164  enumerable: true,
16165  get: function () {
16166    return _util.CMapCompressionType;
16167  }
16168}));
16169Object.defineProperty(exports, "GlobalWorkerOptions", ({
16170  enumerable: true,
16171  get: function () {
16172    return _worker_options.GlobalWorkerOptions;
16173  }
16174}));
16175Object.defineProperty(exports, "InvalidPDFException", ({
16176  enumerable: true,
16177  get: function () {
16178    return _util.InvalidPDFException;
16179  }
16180}));
16181Object.defineProperty(exports, "LoopbackPort", ({
16182  enumerable: true,
16183  get: function () {
16184    return _api.LoopbackPort;
16185  }
16186}));
16187Object.defineProperty(exports, "MissingPDFException", ({
16188  enumerable: true,
16189  get: function () {
16190    return _util.MissingPDFException;
16191  }
16192}));
16193Object.defineProperty(exports, "OPS", ({
16194  enumerable: true,
16195  get: function () {
16196    return _util.OPS;
16197  }
16198}));
16199Object.defineProperty(exports, "PDFDataRangeTransport", ({
16200  enumerable: true,
16201  get: function () {
16202    return _api.PDFDataRangeTransport;
16203  }
16204}));
16205Object.defineProperty(exports, "PDFDateString", ({
16206  enumerable: true,
16207  get: function () {
16208    return _display_utils.PDFDateString;
16209  }
16210}));
16211Object.defineProperty(exports, "PDFWorker", ({
16212  enumerable: true,
16213  get: function () {
16214    return _api.PDFWorker;
16215  }
16216}));
16217Object.defineProperty(exports, "PasswordResponses", ({
16218  enumerable: true,
16219  get: function () {
16220    return _util.PasswordResponses;
16221  }
16222}));
16223Object.defineProperty(exports, "PermissionFlag", ({
16224  enumerable: true,
16225  get: function () {
16226    return _util.PermissionFlag;
16227  }
16228}));
16229Object.defineProperty(exports, "PixelsPerInch", ({
16230  enumerable: true,
16231  get: function () {
16232    return _display_utils.PixelsPerInch;
16233  }
16234}));
16235Object.defineProperty(exports, "RenderingCancelledException", ({
16236  enumerable: true,
16237  get: function () {
16238    return _display_utils.RenderingCancelledException;
16239  }
16240}));
16241Object.defineProperty(exports, "SVGGraphics", ({
16242  enumerable: true,
16243  get: function () {
16244    return _svg.SVGGraphics;
16245  }
16246}));
16247Object.defineProperty(exports, "UNSUPPORTED_FEATURES", ({
16248  enumerable: true,
16249  get: function () {
16250    return _util.UNSUPPORTED_FEATURES;
16251  }
16252}));
16253Object.defineProperty(exports, "UnexpectedResponseException", ({
16254  enumerable: true,
16255  get: function () {
16256    return _util.UnexpectedResponseException;
16257  }
16258}));
16259Object.defineProperty(exports, "Util", ({
16260  enumerable: true,
16261  get: function () {
16262    return _util.Util;
16263  }
16264}));
16265Object.defineProperty(exports, "VerbosityLevel", ({
16266  enumerable: true,
16267  get: function () {
16268    return _util.VerbosityLevel;
16269  }
16270}));
16271Object.defineProperty(exports, "XfaLayer", ({
16272  enumerable: true,
16273  get: function () {
16274    return _xfa_layer.XfaLayer;
16275  }
16276}));
16277Object.defineProperty(exports, "build", ({
16278  enumerable: true,
16279  get: function () {
16280    return _api.build;
16281  }
16282}));
16283Object.defineProperty(exports, "createPromiseCapability", ({
16284  enumerable: true,
16285  get: function () {
16286    return _util.createPromiseCapability;
16287  }
16288}));
16289Object.defineProperty(exports, "createValidAbsoluteUrl", ({
16290  enumerable: true,
16291  get: function () {
16292    return _util.createValidAbsoluteUrl;
16293  }
16294}));
16295Object.defineProperty(exports, "getDocument", ({
16296  enumerable: true,
16297  get: function () {
16298    return _api.getDocument;
16299  }
16300}));
16301Object.defineProperty(exports, "getFilenameFromUrl", ({
16302  enumerable: true,
16303  get: function () {
16304    return _display_utils.getFilenameFromUrl;
16305  }
16306}));
16307Object.defineProperty(exports, "getPdfFilenameFromUrl", ({
16308  enumerable: true,
16309  get: function () {
16310    return _display_utils.getPdfFilenameFromUrl;
16311  }
16312}));
16313Object.defineProperty(exports, "getXfaPageViewport", ({
16314  enumerable: true,
16315  get: function () {
16316    return _display_utils.getXfaPageViewport;
16317  }
16318}));
16319Object.defineProperty(exports, "isPdfFile", ({
16320  enumerable: true,
16321  get: function () {
16322    return _display_utils.isPdfFile;
16323  }
16324}));
16325Object.defineProperty(exports, "loadScript", ({
16326  enumerable: true,
16327  get: function () {
16328    return _display_utils.loadScript;
16329  }
16330}));
16331Object.defineProperty(exports, "renderTextLayer", ({
16332  enumerable: true,
16333  get: function () {
16334    return _text_layer.renderTextLayer;
16335  }
16336}));
16337Object.defineProperty(exports, "shadow", ({
16338  enumerable: true,
16339  get: function () {
16340    return _util.shadow;
16341  }
16342}));
16343Object.defineProperty(exports, "version", ({
16344  enumerable: true,
16345  get: function () {
16346    return _api.version;
16347  }
16348}));
16349
16350var _util = __w_pdfjs_require__(1);
16351
16352var _api = __w_pdfjs_require__(4);
16353
16354var _display_utils = __w_pdfjs_require__(5);
16355
16356var _annotation_layer = __w_pdfjs_require__(20);
16357
16358var _worker_options = __w_pdfjs_require__(13);
16359
16360var _is_node = __w_pdfjs_require__(3);
16361
16362var _text_layer = __w_pdfjs_require__(23);
16363
16364var _svg = __w_pdfjs_require__(24);
16365
16366var _xfa_layer = __w_pdfjs_require__(22);
16367
16368const pdfjsVersion = '2.15.24';
16369const pdfjsBuild = '5b02c685d';
16370{
16371  if (_is_node.isNodeJS) {
16372    const {
16373      PDFNodeStream
16374    } = __w_pdfjs_require__(25);
16375
16376    (0, _api.setPDFNetworkStreamFactory)(params => {
16377      return new PDFNodeStream(params);
16378    });
16379  } else {
16380    const {
16381      PDFNetworkStream
16382    } = __w_pdfjs_require__(28);
16383
16384    const {
16385      PDFFetchStream
16386    } = __w_pdfjs_require__(29);
16387
16388    (0, _api.setPDFNetworkStreamFactory)(params => {
16389      if ((0, _display_utils.isValidFetchUrl)(params.url)) {
16390        return new PDFFetchStream(params);
16391      }
16392
16393      return new PDFNetworkStream(params);
16394    });
16395  }
16396}
16397})();
16398
16399/******/ 	return __webpack_exports__;
16400/******/ })()
16401;
16402});
16403//# 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.