Kaynağa Gözat

PDF.js version 2.2.228 - See https://github.com/mozilla/pdf.js/releases/tag/v2.2.228

pdfjsbot 5 yıl önce
ebeveyn
işleme
8ca1faf26b
100 değiştirilmiş dosya ile 6122 ekleme ve 4272 silme
  1. 15 0
      CODE_OF_CONDUCT.md
  2. 1 1
      bower.json
  3. 167 264
      build/pdf.js
  4. 0 0
      build/pdf.js.map
  5. 0 0
      build/pdf.min.js
  6. 132 396
      build/pdf.worker.js
  7. 0 0
      build/pdf.worker.js.map
  8. 0 0
      build/pdf.worker.min.js
  9. 158 260
      image_decoders/pdf.image_decoders.js
  10. 0 0
      image_decoders/pdf.image_decoders.js.map
  11. 0 0
      image_decoders/pdf.image_decoders.min.js
  12. 294 224
      lib/core/annotation.js
  13. 1 1
      lib/core/arithmetic_decoder.js
  14. 1 1
      lib/core/bidi.js
  15. 1 1
      lib/core/ccitt.js
  16. 1 1
      lib/core/ccitt_stream.js
  17. 1 1
      lib/core/cff_parser.js
  18. 1 1
      lib/core/charsets.js
  19. 24 14
      lib/core/chunked_stream.js
  20. 17 13
      lib/core/cmap.js
  21. 1 1
      lib/core/colorspace.js
  22. 147 0
      lib/core/core_utils.js
  23. 1 1
      lib/core/crypto.js
  24. 47 40
      lib/core/document.js
  25. 1 1
      lib/core/encodings.js
  26. 346 279
      lib/core/evaluator.js
  27. 1 1
      lib/core/font_renderer.js
  28. 23 11
      lib/core/fonts.js
  29. 1 1
      lib/core/function.js
  30. 2 2
      lib/core/glyphlist.js
  31. 2 2
      lib/core/image.js
  32. 111 0
      lib/core/image_utils.js
  33. 1 1
      lib/core/jbig2.js
  34. 1 1
      lib/core/jbig2_stream.js
  35. 1 1
      lib/core/jpeg_stream.js
  36. 2 1
      lib/core/jpg.js
  37. 1 1
      lib/core/jpx.js
  38. 1 1
      lib/core/jpx_stream.js
  39. 13 13
      lib/core/metrics.js
  40. 37 33
      lib/core/murmurhash3.js
  41. 245 41
      lib/core/obj.js
  42. 43 32
      lib/core/operator_list.js
  43. 228 133
      lib/core/parser.js
  44. 4 2
      lib/core/pattern.js
  45. 17 15
      lib/core/pdf_manager.js
  46. 40 6
      lib/core/primitives.js
  47. 1 1
      lib/core/ps_parser.js
  48. 9 9
      lib/core/standard_fonts.js
  49. 1 1
      lib/core/stream.js
  50. 1 1
      lib/core/type1_parser.js
  51. 2 2
      lib/core/unicode.js
  52. 54 171
      lib/core/worker.js
  53. 277 0
      lib/core/worker_stream.js
  54. 112 33
      lib/display/annotation_layer.js
  55. 211 123
      lib/display/api.js
  56. 1 1
      lib/display/api_compatibility.js
  57. 40 19
      lib/display/canvas.js
  58. 1 1
      lib/display/content_disposition.js
  59. 747 0
      lib/display/display_utils.js
  60. 0 494
      lib/display/dom_utils.js
  61. 19 12
      lib/display/fetch_stream.js
  62. 11 8
      lib/display/font_loader.js
  63. 1 1
      lib/display/metadata.js
  64. 563 521
      lib/display/network.js
  65. 1 1
      lib/display/network_utils.js
  66. 21 12
      lib/display/node_stream.js
  67. 24 25
      lib/display/pattern_helper.js
  68. 475 338
      lib/display/svg.js
  69. 24 14
      lib/display/text_layer.js
  70. 192 70
      lib/display/transport_stream.js
  71. 1 1
      lib/display/webgl.js
  72. 1 1
      lib/display/worker_options.js
  73. 1 1
      lib/display/xml_parser.js
  74. 4 1
      lib/examples/node/domstubs.js
  75. 20 15
      lib/pdf.js
  76. 3 3
      lib/pdf.worker.js
  77. 6 6
      lib/shared/compatibility.js
  78. 1 1
      lib/shared/global_scope.js
  79. 2 2
      lib/shared/is_node.js
  80. 7 7
      lib/shared/message_handler.js
  81. 1 1
      lib/shared/streams_polyfill.js
  82. 1 1
      lib/shared/url_polyfill.js
  83. 13 125
      lib/shared/util.js
  84. 278 93
      lib/test/unit/annotation_spec.js
  85. 198 188
      lib/test/unit/api_spec.js
  86. 1 1
      lib/test/unit/bidi_spec.js
  87. 15 1
      lib/test/unit/cff_parser_spec.js
  88. 3 3
      lib/test/unit/clitests_helper.js
  89. 20 20
      lib/test/unit/cmap_spec.js
  90. 17 12
      lib/test/unit/colorspace_spec.js
  91. 191 0
      lib/test/unit/core_utils_spec.js
  92. 1 1
      lib/test/unit/crypto_spec.js
  93. 8 8
      lib/test/unit/custom_spec.js
  94. 8 8
      lib/test/unit/display_svg_spec.js
  95. 273 0
      lib/test/unit/display_utils_spec.js
  96. 7 12
      lib/test/unit/document_spec.js
  97. 0 89
      lib/test/unit/dom_utils_spec.js
  98. 5 5
      lib/test/unit/encodings_spec.js
  99. 8 10
      lib/test/unit/evaluator_spec.js
  100. 109 0
      lib/test/unit/fetch_stream_spec.js

+ 15 - 0
CODE_OF_CONDUCT.md

@@ -0,0 +1,15 @@
+# Community Participation Guidelines
+
+This repository is governed by Mozilla's code of conduct and etiquette guidelines. 
+For more details, please read the
+[Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). 
+
+## How to Report
+For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page.
+
+<!--
+## Project Specific Etiquette
+
+In some cases, there will be additional project etiquette i.e.: (https://bugzilla.mozilla.org/page.cgi?id=etiquette.html).
+Please update for your project.
+-->

+ 1 - 1
bower.json

@@ -1,6 +1,6 @@
 {
   "name": "pdfjs-dist",
-  "version": "2.1.266",
+  "version": "2.2.228",
   "main": [
     "build/pdf.js",
     "build/pdf.worker.js"

Dosya farkı çok büyük olduğundan ihmal edildi
+ 167 - 264
build/pdf.js


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
build/pdf.js.map


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
build/pdf.min.js


Dosya farkı çok büyük olduğundan ihmal edildi
+ 132 - 396
build/pdf.worker.js


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
build/pdf.worker.js.map


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
build/pdf.worker.min.js


Dosya farkı çok büyük olduğundan ihmal edildi
+ 158 - 260
image_decoders/pdf.image_decoders.js


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
image_decoders/pdf.image_decoders.js.map


Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
image_decoders/pdf.image_decoders.min.js


+ 294 - 224
lib/core/annotation.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.AnnotationFactory = exports.AnnotationBorderStyle = exports.Annotation = void 0;
+exports.MarkupAnnotation = exports.AnnotationFactory = exports.AnnotationBorderStyle = exports.Annotation = void 0;
 
 var _util = require("../shared/util");
 
@@ -34,20 +34,22 @@ var _primitives = require("./primitives");
 
 var _colorspace = require("./colorspace");
 
+var _core_utils = require("./core_utils");
+
 var _operator_list = require("./operator_list");
 
 var _stream = require("./stream");
 
+function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
+
+function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
+
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
 function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
 
 function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
 
-function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
-
-function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
-
 function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
 
 function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
@@ -78,16 +80,15 @@ function () {
       var dict = xref.fetchIfRef(ref);
 
       if (!(0, _primitives.isDict)(dict)) {
-        return;
+        return undefined;
       }
 
-      var id = (0, _primitives.isRef)(ref) ? ref.toString() : 'annot_' + idFactory.createObjId();
+      var id = (0, _primitives.isRef)(ref) ? ref.toString() : "annot_".concat(idFactory.createObjId());
       var subtype = dict.get('Subtype');
       subtype = (0, _primitives.isName)(subtype) ? subtype.name : null;
       var parameters = {
         xref: xref,
         dict: dict,
-        ref: (0, _primitives.isRef)(ref) ? ref : null,
         subtype: subtype,
         id: id,
         pdfManager: pdfManager
@@ -101,7 +102,7 @@ function () {
           return new TextAnnotation(parameters);
 
         case 'Widget':
-          var fieldType = (0, _util.getInheritableProperty)({
+          var fieldType = (0, _core_utils.getInheritableProperty)({
             dict: dict,
             key: 'FT'
           });
@@ -124,6 +125,9 @@ function () {
         case 'Popup':
           return new PopupAnnotation(parameters);
 
+        case 'FreeText':
+          return new FreeTextAnnotation(parameters);
+
         case 'Line':
           return new LineAnnotation(parameters);
 
@@ -139,6 +143,9 @@ function () {
         case 'Polygon':
           return new PolygonAnnotation(parameters);
 
+        case 'Caret':
+          return new CaretAnnotation(parameters);
+
         case 'Ink':
           return new InkAnnotation(parameters);
 
@@ -201,6 +208,8 @@ function () {
     _classCallCheck(this, Annotation);
 
     var dict = params.dict;
+    this.setContents(dict.get('Contents'));
+    this.setModificationDate(dict.get('M'));
     this.setFlags(dict.get('F'));
     this.setRectangle(dict.getArray('Rect'));
     this.setColor(dict.getArray('C'));
@@ -210,8 +219,10 @@ function () {
       annotationFlags: this.flags,
       borderStyle: this.borderStyle,
       color: this.color,
+      contents: this.contents,
       hasAppearance: !!this.appearance,
       id: params.id,
+      modificationDate: this.modificationDate,
       rect: this.rectangle,
       subtype: params.subtype
     };
@@ -232,6 +243,16 @@ function () {
     value: function _isPrintable(flags) {
       return this._hasFlag(flags, _util.AnnotationFlag.PRINT) && !this._hasFlag(flags, _util.AnnotationFlag.INVISIBLE) && !this._hasFlag(flags, _util.AnnotationFlag.HIDDEN);
     }
+  }, {
+    key: "setContents",
+    value: function setContents(contents) {
+      this.contents = (0, _util.stringToPDFString)(contents || '');
+    }
+  }, {
+    key: "setModificationDate",
+    value: function setModificationDate(modificationDate) {
+      this.modificationDate = (0, _util.isString)(modificationDate) ? modificationDate : null;
+    }
   }, {
     key: "setFlags",
     value: function setFlags(flags) {
@@ -303,7 +324,7 @@ function () {
         var dictType = dict.get('Type');
 
         if (!dictType || (0, _primitives.isName)(dictType, 'Border')) {
-          this.borderStyle.setWidth(dict.get('W'));
+          this.borderStyle.setWidth(dict.get('W'), this.rectangle);
           this.borderStyle.setStyle(dict.get('S'));
           this.borderStyle.setDashArray(dict.getArray('D'));
         }
@@ -313,7 +334,7 @@ function () {
         if (Array.isArray(array) && array.length >= 3) {
           this.borderStyle.setHorizontalCornerRadius(array[0]);
           this.borderStyle.setVerticalCornerRadius(array[1]);
-          this.borderStyle.setWidth(array[2]);
+          this.borderStyle.setWidth(array[2], this.rectangle);
 
           if (array.length === 4) {
             this.borderStyle.setDashArray(array[3]);
@@ -352,23 +373,12 @@ function () {
 
       this.appearance = normalAppearanceState.get(as.name);
     }
-  }, {
-    key: "_preparePopup",
-    value: function _preparePopup(dict) {
-      if (!dict.has('C')) {
-        this.data.color = null;
-      }
-
-      this.data.hasPopup = dict.has('Popup');
-      this.data.title = (0, _util.stringToPDFString)(dict.get('T') || '');
-      this.data.contents = (0, _util.stringToPDFString)(dict.get('Contents') || '');
-    }
   }, {
     key: "loadResources",
     value: function loadResources(keys) {
       return this.appearance.dict.getAsync('Resources').then(function (resources) {
         if (!resources) {
-          return;
+          return undefined;
         }
 
         var objectLoader = new _obj.ObjectLoader(resources, keys, resources.xref);
@@ -450,12 +460,24 @@ function () {
   _createClass(AnnotationBorderStyle, [{
     key: "setWidth",
     value: function setWidth(width) {
+      var rect = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [0, 0, 0, 0];
+
       if ((0, _primitives.isName)(width)) {
         this.width = 0;
         return;
       }
 
       if (Number.isInteger(width)) {
+        if (width > 0) {
+          var maxWidth = (rect[2] - rect[0]) / 2;
+          var maxHeight = (rect[3] - rect[1]) / 2;
+
+          if (maxWidth > 0 && maxHeight > 0 && (width > maxWidth || width > maxHeight)) {
+            (0, _util.warn)("AnnotationBorderStyle.setWidth - ignoring width: ".concat(width));
+            width = 1;
+          }
+        }
+
         this.width = width;
       }
     }
@@ -540,41 +562,78 @@ function () {
 
 exports.AnnotationBorderStyle = AnnotationBorderStyle;
 
-var WidgetAnnotation =
+var MarkupAnnotation =
 /*#__PURE__*/
 function (_Annotation) {
-  _inherits(WidgetAnnotation, _Annotation);
+  _inherits(MarkupAnnotation, _Annotation);
 
-  function WidgetAnnotation(params) {
+  function MarkupAnnotation(parameters) {
     var _this2;
 
+    _classCallCheck(this, MarkupAnnotation);
+
+    _this2 = _possibleConstructorReturn(this, _getPrototypeOf(MarkupAnnotation).call(this, parameters));
+    var dict = parameters.dict;
+
+    if (!dict.has('C')) {
+      _this2.data.color = null;
+    }
+
+    _this2.setCreationDate(dict.get('CreationDate'));
+
+    _this2.data.creationDate = _this2.creationDate;
+    _this2.data.hasPopup = dict.has('Popup');
+    _this2.data.title = (0, _util.stringToPDFString)(dict.get('T') || '');
+    return _this2;
+  }
+
+  _createClass(MarkupAnnotation, [{
+    key: "setCreationDate",
+    value: function setCreationDate(creationDate) {
+      this.creationDate = (0, _util.isString)(creationDate) ? creationDate : null;
+    }
+  }]);
+
+  return MarkupAnnotation;
+}(Annotation);
+
+exports.MarkupAnnotation = MarkupAnnotation;
+
+var WidgetAnnotation =
+/*#__PURE__*/
+function (_Annotation2) {
+  _inherits(WidgetAnnotation, _Annotation2);
+
+  function WidgetAnnotation(params) {
+    var _this3;
+
     _classCallCheck(this, WidgetAnnotation);
 
-    _this2 = _possibleConstructorReturn(this, _getPrototypeOf(WidgetAnnotation).call(this, params));
+    _this3 = _possibleConstructorReturn(this, _getPrototypeOf(WidgetAnnotation).call(this, params));
     var dict = params.dict;
-    var data = _this2.data;
+    var data = _this3.data;
     data.annotationType = _util.AnnotationType.WIDGET;
-    data.fieldName = _this2._constructFieldName(dict);
-    data.fieldValue = (0, _util.getInheritableProperty)({
+    data.fieldName = _this3._constructFieldName(dict);
+    data.fieldValue = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'V',
       getArray: true
     });
     data.alternativeText = (0, _util.stringToPDFString)(dict.get('TU') || '');
-    data.defaultAppearance = (0, _util.getInheritableProperty)({
+    data.defaultAppearance = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'DA'
     }) || '';
-    var fieldType = (0, _util.getInheritableProperty)({
+    var fieldType = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'FT'
     });
     data.fieldType = (0, _primitives.isName)(fieldType) ? fieldType.name : null;
-    _this2.fieldResources = (0, _util.getInheritableProperty)({
+    _this3.fieldResources = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'DR'
     }) || _primitives.Dict.empty;
-    data.fieldFlags = (0, _util.getInheritableProperty)({
+    data.fieldFlags = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'Ff'
     });
@@ -583,15 +642,15 @@ function (_Annotation) {
       data.fieldFlags = 0;
     }
 
-    data.readOnly = _this2.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
+    data.readOnly = _this3.hasFieldFlag(_util.AnnotationFieldFlag.READONLY);
 
     if (data.fieldType === 'Sig') {
       data.fieldValue = null;
 
-      _this2.setFlags(_util.AnnotationFlag.HIDDEN);
+      _this3.setFlags(_util.AnnotationFlag.HIDDEN);
     }
 
-    return _this2;
+    return _this3;
   }
 
   _createClass(WidgetAnnotation, [{
@@ -653,14 +712,14 @@ function (_WidgetAnnotation) {
   _inherits(TextWidgetAnnotation, _WidgetAnnotation);
 
   function TextWidgetAnnotation(params) {
-    var _this3;
+    var _this4;
 
     _classCallCheck(this, TextWidgetAnnotation);
 
-    _this3 = _possibleConstructorReturn(this, _getPrototypeOf(TextWidgetAnnotation).call(this, params));
+    _this4 = _possibleConstructorReturn(this, _getPrototypeOf(TextWidgetAnnotation).call(this, params));
     var dict = params.dict;
-    _this3.data.fieldValue = (0, _util.stringToPDFString)(_this3.data.fieldValue || '');
-    var alignment = (0, _util.getInheritableProperty)({
+    _this4.data.fieldValue = (0, _util.stringToPDFString)(_this4.data.fieldValue || '');
+    var alignment = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'Q'
     });
@@ -669,8 +728,8 @@ function (_WidgetAnnotation) {
       alignment = null;
     }
 
-    _this3.data.textAlignment = alignment;
-    var maximumLength = (0, _util.getInheritableProperty)({
+    _this4.data.textAlignment = alignment;
+    var maximumLength = (0, _core_utils.getInheritableProperty)({
       dict: dict,
       key: 'MaxLen'
     });
@@ -679,10 +738,10 @@ function (_WidgetAnnotation) {
       maximumLength = null;
     }
 
-    _this3.data.maxLen = maximumLength;
-    _this3.data.multiLine = _this3.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
-    _this3.data.comb = _this3.hasFieldFlag(_util.AnnotationFieldFlag.COMB) && !_this3.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE) && !_this3.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD) && !_this3.hasFieldFlag(_util.AnnotationFieldFlag.FILESELECT) && _this3.data.maxLen !== null;
-    return _this3;
+    _this4.data.maxLen = maximumLength;
+    _this4.data.multiLine = _this4.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE);
+    _this4.data.comb = _this4.hasFieldFlag(_util.AnnotationFieldFlag.COMB) && !_this4.hasFieldFlag(_util.AnnotationFieldFlag.MULTILINE) && !_this4.hasFieldFlag(_util.AnnotationFieldFlag.PASSWORD) && !_this4.hasFieldFlag(_util.AnnotationFieldFlag.FILESELECT) && _this4.data.maxLen !== null;
+    return _this4;
   }
 
   _createClass(TextWidgetAnnotation, [{
@@ -719,26 +778,26 @@ function (_WidgetAnnotation2) {
   _inherits(ButtonWidgetAnnotation, _WidgetAnnotation2);
 
   function ButtonWidgetAnnotation(params) {
-    var _this4;
+    var _this5;
 
     _classCallCheck(this, ButtonWidgetAnnotation);
 
-    _this4 = _possibleConstructorReturn(this, _getPrototypeOf(ButtonWidgetAnnotation).call(this, params));
-    _this4.data.checkBox = !_this4.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !_this4.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
-    _this4.data.radioButton = _this4.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !_this4.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
-    _this4.data.pushButton = _this4.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
-
-    if (_this4.data.checkBox) {
-      _this4._processCheckBox(params);
-    } else if (_this4.data.radioButton) {
-      _this4._processRadioButton(params);
-    } else if (_this4.data.pushButton) {
-      _this4._processPushButton(params);
+    _this5 = _possibleConstructorReturn(this, _getPrototypeOf(ButtonWidgetAnnotation).call(this, params));
+    _this5.data.checkBox = !_this5.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !_this5.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
+    _this5.data.radioButton = _this5.hasFieldFlag(_util.AnnotationFieldFlag.RADIO) && !_this5.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
+    _this5.data.pushButton = _this5.hasFieldFlag(_util.AnnotationFieldFlag.PUSHBUTTON);
+
+    if (_this5.data.checkBox) {
+      _this5._processCheckBox(params);
+    } else if (_this5.data.radioButton) {
+      _this5._processRadioButton(params);
+    } else if (_this5.data.pushButton) {
+      _this5._processPushButton(params);
     } else {
       (0, _util.warn)('Invalid field flags for button widget annotation');
     }
 
-    return _this4;
+    return _this5;
   }
 
   _createClass(ButtonWidgetAnnotation, [{
@@ -829,13 +888,13 @@ function (_WidgetAnnotation3) {
   _inherits(ChoiceWidgetAnnotation, _WidgetAnnotation3);
 
   function ChoiceWidgetAnnotation(params) {
-    var _this5;
+    var _this6;
 
     _classCallCheck(this, ChoiceWidgetAnnotation);
 
-    _this5 = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceWidgetAnnotation).call(this, params));
-    _this5.data.options = [];
-    var options = (0, _util.getInheritableProperty)({
+    _this6 = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceWidgetAnnotation).call(this, params));
+    _this6.data.options = [];
+    var options = (0, _core_utils.getInheritableProperty)({
       dict: params.dict,
       key: 'Opt'
     });
@@ -846,20 +905,20 @@ function (_WidgetAnnotation3) {
       for (var i = 0, ii = options.length; i < ii; i++) {
         var option = xref.fetchIfRef(options[i]);
         var isOptionArray = Array.isArray(option);
-        _this5.data.options[i] = {
+        _this6.data.options[i] = {
           exportValue: isOptionArray ? xref.fetchIfRef(option[0]) : option,
           displayValue: (0, _util.stringToPDFString)(isOptionArray ? xref.fetchIfRef(option[1]) : option)
         };
       }
     }
 
-    if (!Array.isArray(_this5.data.fieldValue)) {
-      _this5.data.fieldValue = [_this5.data.fieldValue];
+    if (!Array.isArray(_this6.data.fieldValue)) {
+      _this6.data.fieldValue = [_this6.data.fieldValue];
     }
 
-    _this5.data.combo = _this5.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
-    _this5.data.multiSelect = _this5.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
-    return _this5;
+    _this6.data.combo = _this6.hasFieldFlag(_util.AnnotationFieldFlag.COMBO);
+    _this6.data.multiSelect = _this6.hasFieldFlag(_util.AnnotationFieldFlag.MULTISELECT);
+    return _this6;
   }
 
   return ChoiceWidgetAnnotation;
@@ -867,33 +926,31 @@ function (_WidgetAnnotation3) {
 
 var TextAnnotation =
 /*#__PURE__*/
-function (_Annotation2) {
-  _inherits(TextAnnotation, _Annotation2);
+function (_MarkupAnnotation) {
+  _inherits(TextAnnotation, _MarkupAnnotation);
 
   function TextAnnotation(parameters) {
-    var _this6;
+    var _this7;
 
     _classCallCheck(this, TextAnnotation);
 
     var DEFAULT_ICON_SIZE = 22;
-    _this6 = _possibleConstructorReturn(this, _getPrototypeOf(TextAnnotation).call(this, parameters));
-    _this6.data.annotationType = _util.AnnotationType.TEXT;
+    _this7 = _possibleConstructorReturn(this, _getPrototypeOf(TextAnnotation).call(this, parameters));
+    _this7.data.annotationType = _util.AnnotationType.TEXT;
 
-    if (_this6.data.hasAppearance) {
-      _this6.data.name = 'NoIcon';
+    if (_this7.data.hasAppearance) {
+      _this7.data.name = 'NoIcon';
     } else {
-      _this6.data.rect[1] = _this6.data.rect[3] - DEFAULT_ICON_SIZE;
-      _this6.data.rect[2] = _this6.data.rect[0] + DEFAULT_ICON_SIZE;
-      _this6.data.name = parameters.dict.has('Name') ? parameters.dict.get('Name').name : 'Note';
+      _this7.data.rect[1] = _this7.data.rect[3] - DEFAULT_ICON_SIZE;
+      _this7.data.rect[2] = _this7.data.rect[0] + DEFAULT_ICON_SIZE;
+      _this7.data.name = parameters.dict.has('Name') ? parameters.dict.get('Name').name : 'Note';
     }
 
-    _this6._preparePopup(parameters.dict);
-
-    return _this6;
+    return _this7;
   }
 
   return TextAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var LinkAnnotation =
 /*#__PURE__*/
@@ -901,20 +958,20 @@ function (_Annotation3) {
   _inherits(LinkAnnotation, _Annotation3);
 
   function LinkAnnotation(params) {
-    var _this7;
+    var _this8;
 
     _classCallCheck(this, LinkAnnotation);
 
-    _this7 = _possibleConstructorReturn(this, _getPrototypeOf(LinkAnnotation).call(this, params));
-    _this7.data.annotationType = _util.AnnotationType.LINK;
+    _this8 = _possibleConstructorReturn(this, _getPrototypeOf(LinkAnnotation).call(this, params));
+    _this8.data.annotationType = _util.AnnotationType.LINK;
 
     _obj.Catalog.parseDestDictionary({
       destDict: params.dict,
-      resultObj: _this7.data,
+      resultObj: _this8.data,
       docBaseUrl: params.pdfManager.docBaseUrl
     });
 
-    return _this7;
+    return _this8;
   }
 
   return LinkAnnotation;
@@ -926,143 +983,158 @@ function (_Annotation4) {
   _inherits(PopupAnnotation, _Annotation4);
 
   function PopupAnnotation(parameters) {
-    var _this8;
+    var _this9;
 
     _classCallCheck(this, PopupAnnotation);
 
-    _this8 = _possibleConstructorReturn(this, _getPrototypeOf(PopupAnnotation).call(this, parameters));
-    _this8.data.annotationType = _util.AnnotationType.POPUP;
+    _this9 = _possibleConstructorReturn(this, _getPrototypeOf(PopupAnnotation).call(this, parameters));
+    _this9.data.annotationType = _util.AnnotationType.POPUP;
     var dict = parameters.dict;
     var parentItem = dict.get('Parent');
 
     if (!parentItem) {
       (0, _util.warn)('Popup annotation has a missing or invalid parent annotation.');
-      return _possibleConstructorReturn(_this8);
+      return _possibleConstructorReturn(_this9);
     }
 
     var parentSubtype = parentItem.get('Subtype');
-    _this8.data.parentType = (0, _primitives.isName)(parentSubtype) ? parentSubtype.name : null;
-    _this8.data.parentId = dict.getRaw('Parent').toString();
-    _this8.data.title = (0, _util.stringToPDFString)(parentItem.get('T') || '');
-    _this8.data.contents = (0, _util.stringToPDFString)(parentItem.get('Contents') || '');
+    _this9.data.parentType = (0, _primitives.isName)(parentSubtype) ? parentSubtype.name : null;
+    _this9.data.parentId = dict.getRaw('Parent').toString();
+    _this9.data.title = (0, _util.stringToPDFString)(parentItem.get('T') || '');
+    _this9.data.contents = (0, _util.stringToPDFString)(parentItem.get('Contents') || '');
+
+    if (!parentItem.has('M')) {
+      _this9.data.modificationDate = null;
+    } else {
+      _this9.setModificationDate(parentItem.get('M'));
+
+      _this9.data.modificationDate = _this9.modificationDate;
+    }
 
     if (!parentItem.has('C')) {
-      _this8.data.color = null;
+      _this9.data.color = null;
     } else {
-      _this8.setColor(parentItem.getArray('C'));
+      _this9.setColor(parentItem.getArray('C'));
 
-      _this8.data.color = _this8.color;
+      _this9.data.color = _this9.color;
     }
 
-    if (!_this8.viewable) {
+    if (!_this9.viewable) {
       var parentFlags = parentItem.get('F');
 
-      if (_this8._isViewable(parentFlags)) {
-        _this8.setFlags(parentFlags);
+      if (_this9._isViewable(parentFlags)) {
+        _this9.setFlags(parentFlags);
       }
     }
 
-    return _this8;
+    return _this9;
   }
 
   return PopupAnnotation;
 }(Annotation);
 
+var FreeTextAnnotation =
+/*#__PURE__*/
+function (_MarkupAnnotation2) {
+  _inherits(FreeTextAnnotation, _MarkupAnnotation2);
+
+  function FreeTextAnnotation(parameters) {
+    var _this10;
+
+    _classCallCheck(this, FreeTextAnnotation);
+
+    _this10 = _possibleConstructorReturn(this, _getPrototypeOf(FreeTextAnnotation).call(this, parameters));
+    _this10.data.annotationType = _util.AnnotationType.FREETEXT;
+    return _this10;
+  }
+
+  return FreeTextAnnotation;
+}(MarkupAnnotation);
+
 var LineAnnotation =
 /*#__PURE__*/
-function (_Annotation5) {
-  _inherits(LineAnnotation, _Annotation5);
+function (_MarkupAnnotation3) {
+  _inherits(LineAnnotation, _MarkupAnnotation3);
 
   function LineAnnotation(parameters) {
-    var _this9;
+    var _this11;
 
     _classCallCheck(this, LineAnnotation);
 
-    _this9 = _possibleConstructorReturn(this, _getPrototypeOf(LineAnnotation).call(this, parameters));
-    _this9.data.annotationType = _util.AnnotationType.LINE;
+    _this11 = _possibleConstructorReturn(this, _getPrototypeOf(LineAnnotation).call(this, parameters));
+    _this11.data.annotationType = _util.AnnotationType.LINE;
     var dict = parameters.dict;
-    _this9.data.lineCoordinates = _util.Util.normalizeRect(dict.getArray('L'));
-
-    _this9._preparePopup(dict);
-
-    return _this9;
+    _this11.data.lineCoordinates = _util.Util.normalizeRect(dict.getArray('L'));
+    return _this11;
   }
 
   return LineAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var SquareAnnotation =
 /*#__PURE__*/
-function (_Annotation6) {
-  _inherits(SquareAnnotation, _Annotation6);
+function (_MarkupAnnotation4) {
+  _inherits(SquareAnnotation, _MarkupAnnotation4);
 
   function SquareAnnotation(parameters) {
-    var _this10;
+    var _this12;
 
     _classCallCheck(this, SquareAnnotation);
 
-    _this10 = _possibleConstructorReturn(this, _getPrototypeOf(SquareAnnotation).call(this, parameters));
-    _this10.data.annotationType = _util.AnnotationType.SQUARE;
-
-    _this10._preparePopup(parameters.dict);
-
-    return _this10;
+    _this12 = _possibleConstructorReturn(this, _getPrototypeOf(SquareAnnotation).call(this, parameters));
+    _this12.data.annotationType = _util.AnnotationType.SQUARE;
+    return _this12;
   }
 
   return SquareAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var CircleAnnotation =
 /*#__PURE__*/
-function (_Annotation7) {
-  _inherits(CircleAnnotation, _Annotation7);
+function (_MarkupAnnotation5) {
+  _inherits(CircleAnnotation, _MarkupAnnotation5);
 
   function CircleAnnotation(parameters) {
-    var _this11;
+    var _this13;
 
     _classCallCheck(this, CircleAnnotation);
 
-    _this11 = _possibleConstructorReturn(this, _getPrototypeOf(CircleAnnotation).call(this, parameters));
-    _this11.data.annotationType = _util.AnnotationType.CIRCLE;
-
-    _this11._preparePopup(parameters.dict);
-
-    return _this11;
+    _this13 = _possibleConstructorReturn(this, _getPrototypeOf(CircleAnnotation).call(this, parameters));
+    _this13.data.annotationType = _util.AnnotationType.CIRCLE;
+    return _this13;
   }
 
   return CircleAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var PolylineAnnotation =
 /*#__PURE__*/
-function (_Annotation8) {
-  _inherits(PolylineAnnotation, _Annotation8);
+function (_MarkupAnnotation6) {
+  _inherits(PolylineAnnotation, _MarkupAnnotation6);
 
   function PolylineAnnotation(parameters) {
-    var _this12;
+    var _this14;
 
     _classCallCheck(this, PolylineAnnotation);
 
-    _this12 = _possibleConstructorReturn(this, _getPrototypeOf(PolylineAnnotation).call(this, parameters));
-    _this12.data.annotationType = _util.AnnotationType.POLYLINE;
+    _this14 = _possibleConstructorReturn(this, _getPrototypeOf(PolylineAnnotation).call(this, parameters));
+    _this14.data.annotationType = _util.AnnotationType.POLYLINE;
     var dict = parameters.dict;
     var rawVertices = dict.getArray('Vertices');
-    _this12.data.vertices = [];
+    _this14.data.vertices = [];
 
     for (var i = 0, ii = rawVertices.length; i < ii; i += 2) {
-      _this12.data.vertices.push({
+      _this14.data.vertices.push({
         x: rawVertices[i],
         y: rawVertices[i + 1]
       });
     }
 
-    _this12._preparePopup(dict);
-
-    return _this12;
+    return _this14;
   }
 
   return PolylineAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var PolygonAnnotation =
 /*#__PURE__*/
@@ -1070,178 +1142,176 @@ function (_PolylineAnnotation) {
   _inherits(PolygonAnnotation, _PolylineAnnotation);
 
   function PolygonAnnotation(parameters) {
-    var _this13;
+    var _this15;
 
     _classCallCheck(this, PolygonAnnotation);
 
-    _this13 = _possibleConstructorReturn(this, _getPrototypeOf(PolygonAnnotation).call(this, parameters));
-    _this13.data.annotationType = _util.AnnotationType.POLYGON;
-    return _this13;
+    _this15 = _possibleConstructorReturn(this, _getPrototypeOf(PolygonAnnotation).call(this, parameters));
+    _this15.data.annotationType = _util.AnnotationType.POLYGON;
+    return _this15;
   }
 
   return PolygonAnnotation;
 }(PolylineAnnotation);
 
+var CaretAnnotation =
+/*#__PURE__*/
+function (_MarkupAnnotation7) {
+  _inherits(CaretAnnotation, _MarkupAnnotation7);
+
+  function CaretAnnotation(parameters) {
+    var _this16;
+
+    _classCallCheck(this, CaretAnnotation);
+
+    _this16 = _possibleConstructorReturn(this, _getPrototypeOf(CaretAnnotation).call(this, parameters));
+    _this16.data.annotationType = _util.AnnotationType.CARET;
+    return _this16;
+  }
+
+  return CaretAnnotation;
+}(MarkupAnnotation);
+
 var InkAnnotation =
 /*#__PURE__*/
-function (_Annotation9) {
-  _inherits(InkAnnotation, _Annotation9);
+function (_MarkupAnnotation8) {
+  _inherits(InkAnnotation, _MarkupAnnotation8);
 
   function InkAnnotation(parameters) {
-    var _this14;
+    var _this17;
 
     _classCallCheck(this, InkAnnotation);
 
-    _this14 = _possibleConstructorReturn(this, _getPrototypeOf(InkAnnotation).call(this, parameters));
-    _this14.data.annotationType = _util.AnnotationType.INK;
+    _this17 = _possibleConstructorReturn(this, _getPrototypeOf(InkAnnotation).call(this, parameters));
+    _this17.data.annotationType = _util.AnnotationType.INK;
     var dict = parameters.dict;
     var xref = parameters.xref;
     var originalInkLists = dict.getArray('InkList');
-    _this14.data.inkLists = [];
+    _this17.data.inkLists = [];
 
     for (var i = 0, ii = originalInkLists.length; i < ii; ++i) {
-      _this14.data.inkLists.push([]);
+      _this17.data.inkLists.push([]);
 
       for (var j = 0, jj = originalInkLists[i].length; j < jj; j += 2) {
-        _this14.data.inkLists[i].push({
+        _this17.data.inkLists[i].push({
           x: xref.fetchIfRef(originalInkLists[i][j]),
           y: xref.fetchIfRef(originalInkLists[i][j + 1])
         });
       }
     }
 
-    _this14._preparePopup(dict);
-
-    return _this14;
+    return _this17;
   }
 
   return InkAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var HighlightAnnotation =
 /*#__PURE__*/
-function (_Annotation10) {
-  _inherits(HighlightAnnotation, _Annotation10);
+function (_MarkupAnnotation9) {
+  _inherits(HighlightAnnotation, _MarkupAnnotation9);
 
   function HighlightAnnotation(parameters) {
-    var _this15;
+    var _this18;
 
     _classCallCheck(this, HighlightAnnotation);
 
-    _this15 = _possibleConstructorReturn(this, _getPrototypeOf(HighlightAnnotation).call(this, parameters));
-    _this15.data.annotationType = _util.AnnotationType.HIGHLIGHT;
-
-    _this15._preparePopup(parameters.dict);
-
-    return _this15;
+    _this18 = _possibleConstructorReturn(this, _getPrototypeOf(HighlightAnnotation).call(this, parameters));
+    _this18.data.annotationType = _util.AnnotationType.HIGHLIGHT;
+    return _this18;
   }
 
   return HighlightAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var UnderlineAnnotation =
 /*#__PURE__*/
-function (_Annotation11) {
-  _inherits(UnderlineAnnotation, _Annotation11);
+function (_MarkupAnnotation10) {
+  _inherits(UnderlineAnnotation, _MarkupAnnotation10);
 
   function UnderlineAnnotation(parameters) {
-    var _this16;
+    var _this19;
 
     _classCallCheck(this, UnderlineAnnotation);
 
-    _this16 = _possibleConstructorReturn(this, _getPrototypeOf(UnderlineAnnotation).call(this, parameters));
-    _this16.data.annotationType = _util.AnnotationType.UNDERLINE;
-
-    _this16._preparePopup(parameters.dict);
-
-    return _this16;
+    _this19 = _possibleConstructorReturn(this, _getPrototypeOf(UnderlineAnnotation).call(this, parameters));
+    _this19.data.annotationType = _util.AnnotationType.UNDERLINE;
+    return _this19;
   }
 
   return UnderlineAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var SquigglyAnnotation =
 /*#__PURE__*/
-function (_Annotation12) {
-  _inherits(SquigglyAnnotation, _Annotation12);
+function (_MarkupAnnotation11) {
+  _inherits(SquigglyAnnotation, _MarkupAnnotation11);
 
   function SquigglyAnnotation(parameters) {
-    var _this17;
+    var _this20;
 
     _classCallCheck(this, SquigglyAnnotation);
 
-    _this17 = _possibleConstructorReturn(this, _getPrototypeOf(SquigglyAnnotation).call(this, parameters));
-    _this17.data.annotationType = _util.AnnotationType.SQUIGGLY;
-
-    _this17._preparePopup(parameters.dict);
-
-    return _this17;
+    _this20 = _possibleConstructorReturn(this, _getPrototypeOf(SquigglyAnnotation).call(this, parameters));
+    _this20.data.annotationType = _util.AnnotationType.SQUIGGLY;
+    return _this20;
   }
 
   return SquigglyAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var StrikeOutAnnotation =
 /*#__PURE__*/
-function (_Annotation13) {
-  _inherits(StrikeOutAnnotation, _Annotation13);
+function (_MarkupAnnotation12) {
+  _inherits(StrikeOutAnnotation, _MarkupAnnotation12);
 
   function StrikeOutAnnotation(parameters) {
-    var _this18;
+    var _this21;
 
     _classCallCheck(this, StrikeOutAnnotation);
 
-    _this18 = _possibleConstructorReturn(this, _getPrototypeOf(StrikeOutAnnotation).call(this, parameters));
-    _this18.data.annotationType = _util.AnnotationType.STRIKEOUT;
-
-    _this18._preparePopup(parameters.dict);
-
-    return _this18;
+    _this21 = _possibleConstructorReturn(this, _getPrototypeOf(StrikeOutAnnotation).call(this, parameters));
+    _this21.data.annotationType = _util.AnnotationType.STRIKEOUT;
+    return _this21;
   }
 
   return StrikeOutAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var StampAnnotation =
 /*#__PURE__*/
-function (_Annotation14) {
-  _inherits(StampAnnotation, _Annotation14);
+function (_MarkupAnnotation13) {
+  _inherits(StampAnnotation, _MarkupAnnotation13);
 
   function StampAnnotation(parameters) {
-    var _this19;
+    var _this22;
 
     _classCallCheck(this, StampAnnotation);
 
-    _this19 = _possibleConstructorReturn(this, _getPrototypeOf(StampAnnotation).call(this, parameters));
-    _this19.data.annotationType = _util.AnnotationType.STAMP;
-
-    _this19._preparePopup(parameters.dict);
-
-    return _this19;
+    _this22 = _possibleConstructorReturn(this, _getPrototypeOf(StampAnnotation).call(this, parameters));
+    _this22.data.annotationType = _util.AnnotationType.STAMP;
+    return _this22;
   }
 
   return StampAnnotation;
-}(Annotation);
+}(MarkupAnnotation);
 
 var FileAttachmentAnnotation =
 /*#__PURE__*/
-function (_Annotation15) {
-  _inherits(FileAttachmentAnnotation, _Annotation15);
+function (_MarkupAnnotation14) {
+  _inherits(FileAttachmentAnnotation, _MarkupAnnotation14);
 
   function FileAttachmentAnnotation(parameters) {
-    var _this20;
+    var _this23;
 
     _classCallCheck(this, FileAttachmentAnnotation);
 
-    _this20 = _possibleConstructorReturn(this, _getPrototypeOf(FileAttachmentAnnotation).call(this, parameters));
+    _this23 = _possibleConstructorReturn(this, _getPrototypeOf(FileAttachmentAnnotation).call(this, parameters));
     var file = new _obj.FileSpec(parameters.dict.get('FS'), parameters.xref);
-    _this20.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
-    _this20.data.file = file.serializable;
-
-    _this20._preparePopup(parameters.dict);
-
-    return _this20;
+    _this23.data.annotationType = _util.AnnotationType.FILEATTACHMENT;
+    _this23.data.file = file.serializable;
+    return _this23;
   }
 
   return FileAttachmentAnnotation;
-}(Annotation);
+}(MarkupAnnotation);

+ 1 - 1
lib/core/arithmetic_decoder.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/bidi.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/ccitt.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/ccitt_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

Dosya farkı çok büyük olduğundan ihmal edildi
+ 1 - 1
lib/core/cff_parser.js


+ 1 - 1
lib/core/charsets.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 24 - 14
lib/core/chunked_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,6 +28,8 @@ exports.ChunkedStreamManager = exports.ChunkedStream = void 0;
 
 var _util = require("../shared/util");
 
+var _core_utils = require("./core_utils");
+
 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
 function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
@@ -122,6 +124,10 @@ function () {
   }, {
     key: "ensureByte",
     value: function ensureByte(pos) {
+      if (pos < this.progressiveDataLength) {
+        return;
+      }
+
       var chunk = Math.floor(pos / this.chunkSize);
 
       if (chunk === this.lastSuccessfulEnsureByteChunk) {
@@ -129,7 +135,7 @@ function () {
       }
 
       if (!this.loadedChunks[chunk]) {
-        throw new _util.MissingDataException(pos, pos + 1);
+        throw new _core_utils.MissingDataException(pos, pos + 1);
       }
 
       this.lastSuccessfulEnsureByteChunk = chunk;
@@ -151,7 +157,7 @@ function () {
 
       for (var chunk = beginChunk; chunk < endChunk; ++chunk) {
         if (!this.loadedChunks[chunk]) {
-          throw new _util.MissingDataException(begin, end);
+          throw new _core_utils.MissingDataException(begin, end);
         }
       }
     }
@@ -278,7 +284,11 @@ function () {
   }, {
     key: "makeSubStream",
     value: function makeSubStream(start, length, dict) {
-      this.ensureRange(start, start + length);
+      if (length) {
+        this.ensureRange(start, start + length);
+      } else {
+        this.ensureByte(start);
+      }
 
       function ChunkedStreamSubstream() {}
 
@@ -432,8 +442,8 @@ function () {
         _iteratorError = err;
       } finally {
         try {
-          if (!_iteratorNormalCompletion && _iterator.return != null) {
-            _iterator.return();
+          if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+            _iterator["return"]();
           }
         } finally {
           if (_didIteratorError) {
@@ -482,8 +492,8 @@ function () {
         _iteratorError2 = err;
       } finally {
         try {
-          if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
-            _iterator2.return();
+          if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+            _iterator2["return"]();
           }
         } finally {
           if (_didIteratorError2) {
@@ -539,8 +549,8 @@ function () {
         _iteratorError3 = err;
       } finally {
         try {
-          if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
-            _iterator3.return();
+          if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
+            _iterator3["return"]();
           }
         } finally {
           if (_didIteratorError3) {
@@ -646,8 +656,8 @@ function () {
           _iteratorError4 = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
-              _iterator4.return();
+            if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
+              _iterator4["return"]();
             }
           } finally {
             if (_didIteratorError4) {
@@ -675,8 +685,8 @@ function () {
         }
       }
 
-      for (var _i = 0; _i < loadedRequests.length; _i++) {
-        var _requestId = loadedRequests[_i];
+      for (var _i = 0, _loadedRequests = loadedRequests; _i < _loadedRequests.length; _i++) {
+        var _requestId = _loadedRequests[_i];
         var capability = this.promisesByRequest[_requestId];
         delete this.promisesByRequest[_requestId];
         capability.resolve();

+ 17 - 13
lib/core/cmap.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@ var _primitives = require("./primitives");
 
 var _parser = require("./parser");
 
+var _core_utils = require("./core_utils");
+
 var _stream = require("./stream");
 
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
@@ -452,7 +454,9 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
       var useCMap = null;
       var start = new Uint8Array(MAX_NUM_SIZE);
       var end = new Uint8Array(MAX_NUM_SIZE);
-      var char = new Uint8Array(MAX_NUM_SIZE);
+
+      var _char = new Uint8Array(MAX_NUM_SIZE);
+
       var charCode = new Uint8Array(MAX_NUM_SIZE);
       var tmp = new Uint8Array(MAX_NUM_SIZE);
       var code;
@@ -522,20 +526,20 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
             break;
 
           case 2:
-            stream.readHex(char, dataSize);
+            stream.readHex(_char, dataSize);
             code = stream.readNumber();
-            cMap.mapOne(hexToInt(char, dataSize), code);
+            cMap.mapOne(hexToInt(_char, dataSize), code);
 
             for (i = 1; i < subitemsCount; i++) {
-              incHex(char, dataSize);
+              incHex(_char, dataSize);
 
               if (!sequence) {
                 stream.readHexNumber(tmp, dataSize);
-                addHex(char, tmp, dataSize);
+                addHex(_char, tmp, dataSize);
               }
 
               code = stream.readSigned() + (code + 1);
-              cMap.mapOne(hexToInt(char, dataSize), code);
+              cMap.mapOne(hexToInt(_char, dataSize), code);
             }
 
             break;
@@ -566,22 +570,22 @@ var BinaryCMapReader = function BinaryCMapReaderClosure() {
             break;
 
           case 4:
-            stream.readHex(char, ucs2DataSize);
+            stream.readHex(_char, ucs2DataSize);
             stream.readHex(charCode, dataSize);
-            cMap.mapOne(hexToInt(char, ucs2DataSize), hexToStr(charCode, dataSize));
+            cMap.mapOne(hexToInt(_char, ucs2DataSize), hexToStr(charCode, dataSize));
 
             for (i = 1; i < subitemsCount; i++) {
-              incHex(char, ucs2DataSize);
+              incHex(_char, ucs2DataSize);
 
               if (!sequence) {
                 stream.readHexNumber(tmp, ucs2DataSize);
-                addHex(char, tmp, ucs2DataSize);
+                addHex(_char, tmp, ucs2DataSize);
               }
 
               incHex(charCode, dataSize);
               stream.readHexSigned(tmp, dataSize);
               addHex(charCode, tmp, dataSize);
-              cMap.mapOne(hexToInt(char, ucs2DataSize), hexToStr(charCode, dataSize));
+              cMap.mapOne(hexToInt(_char, ucs2DataSize), hexToStr(charCode, dataSize));
             }
 
             break;
@@ -861,7 +865,7 @@ var CMapFactory = function CMapFactoryClosure() {
           }
         }
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 

+ 1 - 1
lib/core/colorspace.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 147 - 0
lib/core/core_utils.js

@@ -0,0 +1,147 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+  value: true
+});
+exports.getLookupTableFactory = getLookupTableFactory;
+exports.getInheritableProperty = getInheritableProperty;
+exports.toRomanNumerals = toRomanNumerals;
+exports.XRefParseException = exports.XRefEntryException = exports.MissingDataException = void 0;
+
+var _util = require("../shared/util");
+
+function getLookupTableFactory(initializer) {
+  var lookup;
+  return function () {
+    if (initializer) {
+      lookup = Object.create(null);
+      initializer(lookup);
+      initializer = null;
+    }
+
+    return lookup;
+  };
+}
+
+var MissingDataException = function MissingDataExceptionClosure() {
+  function MissingDataException(begin, end) {
+    this.begin = begin;
+    this.end = end;
+    this.message = "Missing data [".concat(begin, ", ").concat(end, ")");
+  }
+
+  MissingDataException.prototype = new Error();
+  MissingDataException.prototype.name = 'MissingDataException';
+  MissingDataException.constructor = MissingDataException;
+  return MissingDataException;
+}();
+
+exports.MissingDataException = MissingDataException;
+
+var XRefEntryException = function XRefEntryExceptionClosure() {
+  function XRefEntryException(msg) {
+    this.message = msg;
+  }
+
+  XRefEntryException.prototype = new Error();
+  XRefEntryException.prototype.name = 'XRefEntryException';
+  XRefEntryException.constructor = XRefEntryException;
+  return XRefEntryException;
+}();
+
+exports.XRefEntryException = XRefEntryException;
+
+var XRefParseException = function XRefParseExceptionClosure() {
+  function XRefParseException(msg) {
+    this.message = msg;
+  }
+
+  XRefParseException.prototype = new Error();
+  XRefParseException.prototype.name = 'XRefParseException';
+  XRefParseException.constructor = XRefParseException;
+  return XRefParseException;
+}();
+
+exports.XRefParseException = XRefParseException;
+
+function getInheritableProperty(_ref) {
+  var dict = _ref.dict,
+      key = _ref.key,
+      _ref$getArray = _ref.getArray,
+      getArray = _ref$getArray === void 0 ? false : _ref$getArray,
+      _ref$stopWhenFound = _ref.stopWhenFound,
+      stopWhenFound = _ref$stopWhenFound === void 0 ? true : _ref$stopWhenFound;
+  var LOOP_LIMIT = 100;
+  var loopCount = 0;
+  var values;
+
+  while (dict) {
+    var value = getArray ? dict.getArray(key) : dict.get(key);
+
+    if (value !== undefined) {
+      if (stopWhenFound) {
+        return value;
+      }
+
+      if (!values) {
+        values = [];
+      }
+
+      values.push(value);
+    }
+
+    if (++loopCount > LOOP_LIMIT) {
+      (0, _util.warn)("getInheritableProperty: maximum loop count exceeded for \"".concat(key, "\""));
+      break;
+    }
+
+    dict = dict.get('Parent');
+  }
+
+  return values;
+}
+
+var ROMAN_NUMBER_MAP = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
+
+function toRomanNumerals(number) {
+  var lowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
+  (0, _util.assert)(Number.isInteger(number) && number > 0, 'The number should be a positive integer.');
+  var pos,
+      romanBuf = [];
+
+  while (number >= 1000) {
+    number -= 1000;
+    romanBuf.push('M');
+  }
+
+  pos = number / 100 | 0;
+  number %= 100;
+  romanBuf.push(ROMAN_NUMBER_MAP[pos]);
+  pos = number / 10 | 0;
+  number %= 10;
+  romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
+  romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
+  var romanStr = romanBuf.join('');
+  return lowerCase ? romanStr.toLowerCase() : romanStr;
+}

+ 1 - 1
lib/core/crypto.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 47 - 40
lib/core/document.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@ var _obj = require("./obj");
 
 var _primitives = require("./primitives");
 
+var _core_utils = require("./core_utils");
+
 var _stream2 = require("./stream");
 
 var _annotation = require("./annotation");
@@ -92,13 +94,15 @@ function () {
     this.pdfFunctionFactory = pdfFunctionFactory;
     this.evaluatorOptions = pdfManager.evaluatorOptions;
     this.resourcesPromise = null;
-    var uniquePrefix = "p".concat(this.pageIndex, "_");
     var idCounters = {
       obj: 0
     };
     this.idFactory = {
       createObjId: function createObjId() {
-        return uniquePrefix + ++idCounters.obj;
+        return "p".concat(pageIndex, "_").concat(++idCounters.obj);
+      },
+      getDocId: function getDocId() {
+        return "g_".concat(pdfManager.docId);
       }
     };
   }
@@ -107,7 +111,7 @@ function () {
     key: "_getInheritableProperty",
     value: function _getInheritableProperty(key) {
       var getArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-      var value = (0, _util.getInheritableProperty)({
+      var value = (0, _core_utils.getInheritableProperty)({
         dict: this.pageDict,
         key: key,
         getArray: getArray,
@@ -147,8 +151,8 @@ function () {
           _iteratorError = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion && _iterator.return != null) {
-              _iterator.return();
+            if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+              _iterator["return"]();
             }
           } finally {
             if (_didIteratorError) {
@@ -192,7 +196,6 @@ function () {
       var contentStreamPromise = this.pdfManager.ensure(this, 'getContentStream');
       var resourcesPromise = this.loadResources(['ExtGState', 'ColorSpace', 'Pattern', 'Shading', 'XObject', 'Font']);
       var partialEvaluator = new _evaluator.PartialEvaluator({
-        pdfManager: this.pdfManager,
         xref: this.xref,
         handler: handler,
         pageIndex: this.pageIndex,
@@ -250,8 +253,8 @@ function () {
           _iteratorError2 = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
-              _iterator2.return();
+            if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+              _iterator2["return"]();
             }
           } finally {
             if (_didIteratorError2) {
@@ -276,8 +279,8 @@ function () {
             _iteratorError3 = err;
           } finally {
             try {
-              if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
-                _iterator3.return();
+              if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
+                _iterator3["return"]();
               }
             } finally {
               if (_didIteratorError3) {
@@ -310,7 +313,6 @@ function () {
             contentStream = _ref9[0];
 
         var partialEvaluator = new _evaluator.PartialEvaluator({
-          pdfManager: _this3.pdfManager,
           xref: _this3.xref,
           handler: handler,
           pageIndex: _this3.pageIndex,
@@ -455,22 +457,10 @@ exports.Page = Page;
 var FINGERPRINT_FIRST_BYTES = 1024;
 var EMPTY_FINGERPRINT = '\x00\x00\x00\x00\x00\x00\x00' + '\x00\x00\x00\x00\x00\x00\x00\x00\x00';
 
-function find(stream, needle, limit, backwards) {
-  var pos = stream.pos;
-  var end = stream.end;
-
-  if (pos + limit > end) {
-    limit = end - pos;
-  }
-
-  var strBuf = [];
-
-  for (var i = 0; i < limit; ++i) {
-    strBuf.push(String.fromCharCode(stream.getByte()));
-  }
-
-  var str = strBuf.join('');
-  stream.pos = pos;
+function find(stream, needle, limit) {
+  var backwards = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
+  (0, _util.assert)(limit > 0, 'The "limit" must be a positive integer.');
+  var str = (0, _util.bytesToString)(stream.peekBytes(limit));
   var index = backwards ? str.lastIndexOf(needle) : str.indexOf(needle);
 
   if (index === -1) {
@@ -528,18 +518,32 @@ function () {
           this.xfa = this.acroForm.get('XFA');
           var fields = this.acroForm.get('Fields');
 
-          if ((!fields || !Array.isArray(fields) || fields.length === 0) && !this.xfa) {
+          if ((!Array.isArray(fields) || fields.length === 0) && !this.xfa) {
             this.acroForm = null;
           }
         }
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
         (0, _util.info)('Cannot fetch AcroForm entry; assuming no AcroForms are present');
         this.acroForm = null;
       }
+
+      try {
+        var collection = this.catalog.catDict.get('Collection');
+
+        if ((0, _primitives.isDict)(collection) && collection.getKeys().length > 0) {
+          this.collection = collection;
+        }
+      } catch (ex) {
+        if (ex instanceof _core_utils.MissingDataException) {
+          throw ex;
+        }
+
+        (0, _util.info)('Cannot fetch Collection dictionary.');
+      }
     }
   }, {
     key: "checkHeader",
@@ -585,7 +589,9 @@ function () {
       var catalog = this.catalog,
           linearization = this.linearization;
       (0, _util.assert)(linearization && linearization.pageFirst === pageIndex);
-      var ref = new _primitives.Ref(linearization.objectNumberFirst, 0);
+
+      var ref = _primitives.Ref.get(linearization.objectNumberFirst, 0);
+
       return this.xref.fetchAsync(ref).then(function (obj) {
         if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Type') && obj.has('Contents')) {
           if (ref && !catalog.pageKidsCountCache.has(ref)) {
@@ -596,7 +602,7 @@ function () {
         }
 
         throw new _util.FormatError('The Linearization dictionary doesn\'t point ' + 'to a valid Page dictionary.');
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         (0, _util.info)(reason);
         return catalog.getPageDict(pageIndex);
       });
@@ -635,13 +641,13 @@ function () {
     value: function checkFirstPage() {
       var _this6 = this;
 
-      return this.getPage(0).catch(function (reason) {
-        if (reason instanceof _util.XRefEntryException) {
+      return this.getPage(0)["catch"](function (reason) {
+        if (reason instanceof _core_utils.XRefEntryException) {
           _this6._pagePromises.length = 0;
 
           _this6.cleanup();
 
-          throw new _util.XRefParseException();
+          throw new _core_utils.XRefParseException();
         }
       });
     }
@@ -663,7 +669,7 @@ function () {
       try {
         linearization = _parser.Linearization.create(this.stream);
       } catch (err) {
-        if (err instanceof _util.MissingDataException) {
+        if (err instanceof _core_utils.MissingDataException) {
           throw err;
         }
 
@@ -751,14 +757,15 @@ function () {
         PDFFormatVersion: this.pdfFormatVersion,
         IsLinearized: !!this.linearization,
         IsAcroFormPresent: !!this.acroForm,
-        IsXFAPresent: !!this.xfa
+        IsXFAPresent: !!this.xfa,
+        IsCollectionPresent: !!this.collection
       };
       var infoDict;
 
       try {
         infoDict = this.xref.trailer.get('Info');
       } catch (err) {
-        if (err instanceof _util.MissingDataException) {
+        if (err instanceof _core_utils.MissingDataException) {
           throw err;
         }
 
@@ -805,8 +812,8 @@ function () {
           _iteratorError4 = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
-              _iterator4.return();
+            if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
+              _iterator4["return"]();
             }
           } finally {
             if (_didIteratorError4) {

+ 1 - 1
lib/core/encodings.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 346 - 279
lib/core/evaluator.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,8 +32,6 @@ var _util = require("../shared/util");
 
 var _cmap = require("./cmap");
 
-var _stream = require("./stream");
-
 var _primitives = require("./primitives");
 
 var _fonts = require("./fonts");
@@ -52,8 +50,12 @@ var _bidi = require("./bidi");
 
 var _colorspace = require("./colorspace");
 
+var _stream = require("./stream");
+
 var _glyphlist = require("./glyphlist");
 
+var _core_utils = require("./core_utils");
+
 var _metrics = require("./metrics");
 
 var _function = require("./function");
@@ -62,11 +64,13 @@ var _jpeg_stream = require("./jpeg_stream");
 
 var _murmurhash = require("./murmurhash3");
 
+var _image_utils = require("./image_utils");
+
 var _operator_list = require("./operator_list");
 
 var _image = require("./image");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
 
@@ -82,77 +86,19 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
     isEvalSupported: true
   };
 
-  function NativeImageDecoder(_ref) {
+  function PartialEvaluator(_ref) {
+    var _this = this;
+
     var xref = _ref.xref,
-        resources = _ref.resources,
         handler = _ref.handler,
-        _ref$forceDataSchema = _ref.forceDataSchema,
-        forceDataSchema = _ref$forceDataSchema === void 0 ? false : _ref$forceDataSchema,
+        pageIndex = _ref.pageIndex,
+        idFactory = _ref.idFactory,
+        fontCache = _ref.fontCache,
+        builtInCMapCache = _ref.builtInCMapCache,
+        _ref$options = _ref.options,
+        options = _ref$options === void 0 ? null : _ref$options,
         pdfFunctionFactory = _ref.pdfFunctionFactory;
     this.xref = xref;
-    this.resources = resources;
-    this.handler = handler;
-    this.forceDataSchema = forceDataSchema;
-    this.pdfFunctionFactory = pdfFunctionFactory;
-  }
-
-  NativeImageDecoder.prototype = {
-    canDecode: function canDecode(image) {
-      return image instanceof _jpeg_stream.JpegStream && NativeImageDecoder.isDecodable(image, this.xref, this.resources, this.pdfFunctionFactory);
-    },
-    decode: function decode(image) {
-      var dict = image.dict;
-      var colorSpace = dict.get('ColorSpace', 'CS');
-      colorSpace = _colorspace.ColorSpace.parse(colorSpace, this.xref, this.resources, this.pdfFunctionFactory);
-      return this.handler.sendWithPromise('JpegDecode', [image.getIR(this.forceDataSchema), colorSpace.numComps]).then(function (_ref2) {
-        var data = _ref2.data,
-            width = _ref2.width,
-            height = _ref2.height;
-        return new _stream.Stream(data, 0, data.length, image.dict);
-      });
-    }
-  };
-
-  NativeImageDecoder.isSupported = function (image, xref, res, pdfFunctionFactory) {
-    var dict = image.dict;
-
-    if (dict.has('DecodeParms') || dict.has('DP')) {
-      return false;
-    }
-
-    var cs = _colorspace.ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res, pdfFunctionFactory);
-
-    return (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') && cs.isDefaultDecode(dict.getArray('Decode', 'D'));
-  };
-
-  NativeImageDecoder.isDecodable = function (image, xref, res, pdfFunctionFactory) {
-    var dict = image.dict;
-
-    if (dict.has('DecodeParms') || dict.has('DP')) {
-      return false;
-    }
-
-    var cs = _colorspace.ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res, pdfFunctionFactory);
-
-    var bpc = dict.get('BitsPerComponent', 'BPC') || 1;
-    return (cs.numComps === 1 || cs.numComps === 3) && cs.isDefaultDecode(dict.getArray('Decode', 'D'), bpc);
-  };
-
-  function PartialEvaluator(_ref3) {
-    var _this = this;
-
-    var pdfManager = _ref3.pdfManager,
-        xref = _ref3.xref,
-        handler = _ref3.handler,
-        pageIndex = _ref3.pageIndex,
-        idFactory = _ref3.idFactory,
-        fontCache = _ref3.fontCache,
-        builtInCMapCache = _ref3.builtInCMapCache,
-        _ref3$options = _ref3.options,
-        options = _ref3$options === void 0 ? null : _ref3$options,
-        pdfFunctionFactory = _ref3.pdfFunctionFactory;
-    this.pdfManager = pdfManager;
-    this.xref = xref;
     this.handler = handler;
     this.pageIndex = pageIndex;
     this.idFactory = idFactory;
@@ -160,15 +106,16 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
     this.builtInCMapCache = builtInCMapCache;
     this.options = options || DefaultPartialEvaluatorOptions;
     this.pdfFunctionFactory = pdfFunctionFactory;
+    this.parsingType3Font = false;
 
     this.fetchBuiltInCMap =
     /*#__PURE__*/
     function () {
-      var _ref4 = _asyncToGenerator(
+      var _ref2 = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee(name) {
+      _regenerator["default"].mark(function _callee(name) {
         var data;
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -199,11 +146,11 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
                 return _context.stop();
             }
           }
-        }, _callee, this);
+        }, _callee);
       }));
 
       return function (_x) {
-        return _ref4.apply(this, arguments);
+        return _ref2.apply(this, arguments);
       };
     }();
   }
@@ -435,154 +382,213 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         }
       });
     },
-    buildPaintImageXObject: function buildPaintImageXObject(_ref5) {
-      var _this2 = this;
-
-      var resources = _ref5.resources,
-          image = _ref5.image,
-          _ref5$isInline = _ref5.isInline,
-          isInline = _ref5$isInline === void 0 ? false : _ref5$isInline,
-          operatorList = _ref5.operatorList,
-          cacheKey = _ref5.cacheKey,
-          imageCache = _ref5.imageCache,
-          _ref5$forceDisableNat = _ref5.forceDisableNativeImageDecoder,
-          forceDisableNativeImageDecoder = _ref5$forceDisableNat === void 0 ? false : _ref5$forceDisableNat;
-      var dict = image.dict;
-      var w = dict.get('Width', 'W');
-      var h = dict.get('Height', 'H');
-
-      if (!(w && (0, _util.isNum)(w)) || !(h && (0, _util.isNum)(h))) {
-        (0, _util.warn)('Image dimensions are missing, or not numbers.');
-        return Promise.resolve();
-      }
-
-      var maxImageSize = this.options.maxImageSize;
-
-      if (maxImageSize !== -1 && w * h > maxImageSize) {
-        (0, _util.warn)('Image exceeded maximum allowed size and was removed.');
-        return Promise.resolve();
-      }
-
-      var imageMask = dict.get('ImageMask', 'IM') || false;
-      var imgData, args;
-
-      if (imageMask) {
-        var width = dict.get('Width', 'W');
-        var height = dict.get('Height', 'H');
-        var bitStrideLength = width + 7 >> 3;
-        var imgArray = image.getBytes(bitStrideLength * height, true);
-        var decode = dict.getArray('Decode', 'D');
-        imgData = _image.PDFImage.createMask({
-          imgArray: imgArray,
-          width: width,
-          height: height,
-          imageIsFromDecodeStream: image instanceof _stream.DecodeStream,
-          inverseDecode: !!decode && decode[0] > 0
-        });
-        imgData.cached = true;
-        args = [imgData];
-        operatorList.addOp(_util.OPS.paintImageMaskXObject, args);
-
-        if (cacheKey) {
-          imageCache[cacheKey] = {
-            fn: _util.OPS.paintImageMaskXObject,
-            args: args
-          };
-        }
+    buildPaintImageXObject: function () {
+      var _buildPaintImageXObject = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee2(_ref3) {
+        var _this2 = this;
 
-        return Promise.resolve();
-      }
+        var resources, image, _ref3$isInline, isInline, operatorList, cacheKey, imageCache, _ref3$forceDisableNat, forceDisableNativeImageDecoder, dict, w, h, maxImageSize, imageMask, imgData, args, width, height, bitStrideLength, imgArray, decode, softMask, mask, SMALL_IMAGE_DIMENSIONS, imageObj, nativeImageDecoderSupport, objId, nativeImageDecoder, imgPromise;
 
-      var softMask = dict.get('SMask', 'SM') || false;
-      var mask = dict.get('Mask') || false;
-      var SMALL_IMAGE_DIMENSIONS = 200;
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
+          while (1) {
+            switch (_context2.prev = _context2.next) {
+              case 0:
+                resources = _ref3.resources, image = _ref3.image, _ref3$isInline = _ref3.isInline, isInline = _ref3$isInline === void 0 ? false : _ref3$isInline, operatorList = _ref3.operatorList, cacheKey = _ref3.cacheKey, imageCache = _ref3.imageCache, _ref3$forceDisableNat = _ref3.forceDisableNativeImageDecoder, forceDisableNativeImageDecoder = _ref3$forceDisableNat === void 0 ? false : _ref3$forceDisableNat;
+                dict = image.dict;
+                w = dict.get('Width', 'W');
+                h = dict.get('Height', 'H');
 
-      if (isInline && !softMask && !mask && !(image instanceof _jpeg_stream.JpegStream) && w + h < SMALL_IMAGE_DIMENSIONS) {
-        var imageObj = new _image.PDFImage({
-          xref: this.xref,
-          res: resources,
-          image: image,
-          isInline: isInline,
-          pdfFunctionFactory: this.pdfFunctionFactory
-        });
-        imgData = imageObj.createImageData(true);
-        operatorList.addOp(_util.OPS.paintInlineImageXObject, [imgData]);
-        return Promise.resolve();
-      }
+                if (!(!(w && (0, _util.isNum)(w)) || !(h && (0, _util.isNum)(h)))) {
+                  _context2.next = 7;
+                  break;
+                }
 
-      var nativeImageDecoderSupport = forceDisableNativeImageDecoder ? _util.NativeImageDecoding.NONE : this.options.nativeImageDecoderSupport;
-      var objId = 'img_' + this.idFactory.createObjId();
+                (0, _util.warn)('Image dimensions are missing, or not numbers.');
+                return _context2.abrupt("return", undefined);
 
-      if (nativeImageDecoderSupport !== _util.NativeImageDecoding.NONE && !softMask && !mask && image instanceof _jpeg_stream.JpegStream && NativeImageDecoder.isSupported(image, this.xref, resources, this.pdfFunctionFactory)) {
-        return this.handler.sendWithPromise('obj', [objId, this.pageIndex, 'JpegStream', image.getIR(this.options.forceDataSchema)]).then(function () {
-          operatorList.addDependency(objId);
-          args = [objId, w, h];
-          operatorList.addOp(_util.OPS.paintJpegXObject, args);
+              case 7:
+                maxImageSize = this.options.maxImageSize;
 
-          if (cacheKey) {
-            imageCache[cacheKey] = {
-              fn: _util.OPS.paintJpegXObject,
-              args: args
-            };
-          }
-        }, function (reason) {
-          (0, _util.warn)('Native JPEG decoding failed -- trying to recover: ' + (reason && reason.message));
-          return _this2.buildPaintImageXObject({
-            resources: resources,
-            image: image,
-            isInline: isInline,
-            operatorList: operatorList,
-            cacheKey: cacheKey,
-            imageCache: imageCache,
-            forceDisableNativeImageDecoder: true
-          });
-        });
-      }
+                if (!(maxImageSize !== -1 && w * h > maxImageSize)) {
+                  _context2.next = 11;
+                  break;
+                }
 
-      var nativeImageDecoder = null;
+                (0, _util.warn)('Image exceeded maximum allowed size and was removed.');
+                return _context2.abrupt("return", undefined);
 
-      if (nativeImageDecoderSupport === _util.NativeImageDecoding.DECODE && (image instanceof _jpeg_stream.JpegStream || mask instanceof _jpeg_stream.JpegStream || softMask instanceof _jpeg_stream.JpegStream)) {
-        nativeImageDecoder = new NativeImageDecoder({
-          xref: this.xref,
-          resources: resources,
-          handler: this.handler,
-          forceDataSchema: this.options.forceDataSchema,
-          pdfFunctionFactory: this.pdfFunctionFactory
-        });
-      }
+              case 11:
+                imageMask = dict.get('ImageMask', 'IM') || false;
 
-      operatorList.addDependency(objId);
-      args = [objId, w, h];
+                if (!imageMask) {
+                  _context2.next = 24;
+                  break;
+                }
 
-      _image.PDFImage.buildImage({
-        handler: this.handler,
-        xref: this.xref,
-        res: resources,
-        image: image,
-        isInline: isInline,
-        nativeDecoder: nativeImageDecoder,
-        pdfFunctionFactory: this.pdfFunctionFactory
-      }).then(function (imageObj) {
-        var imgData = imageObj.createImageData(false);
+                width = dict.get('Width', 'W');
+                height = dict.get('Height', 'H');
+                bitStrideLength = width + 7 >> 3;
+                imgArray = image.getBytes(bitStrideLength * height, true);
+                decode = dict.getArray('Decode', 'D');
+                imgData = _image.PDFImage.createMask({
+                  imgArray: imgArray,
+                  width: width,
+                  height: height,
+                  imageIsFromDecodeStream: image instanceof _stream.DecodeStream,
+                  inverseDecode: !!decode && decode[0] > 0
+                });
+                imgData.cached = !!cacheKey;
+                args = [imgData];
+                operatorList.addOp(_util.OPS.paintImageMaskXObject, args);
+
+                if (cacheKey) {
+                  imageCache[cacheKey] = {
+                    fn: _util.OPS.paintImageMaskXObject,
+                    args: args
+                  };
+                }
 
-        _this2.handler.send('obj', [objId, _this2.pageIndex, 'Image', imgData], [imgData.data.buffer]);
-      }).catch(function (reason) {
-        (0, _util.warn)('Unable to decode image: ' + reason);
+                return _context2.abrupt("return", undefined);
 
-        _this2.handler.send('obj', [objId, _this2.pageIndex, 'Image', null]);
-      });
+              case 24:
+                softMask = dict.get('SMask', 'SM') || false;
+                mask = dict.get('Mask') || false;
+                SMALL_IMAGE_DIMENSIONS = 200;
 
-      operatorList.addOp(_util.OPS.paintImageXObject, args);
+                if (!(isInline && !softMask && !mask && !(image instanceof _jpeg_stream.JpegStream) && w + h < SMALL_IMAGE_DIMENSIONS)) {
+                  _context2.next = 32;
+                  break;
+                }
 
-      if (cacheKey) {
-        imageCache[cacheKey] = {
-          fn: _util.OPS.paintImageXObject,
-          args: args
-        };
+                imageObj = new _image.PDFImage({
+                  xref: this.xref,
+                  res: resources,
+                  image: image,
+                  isInline: isInline,
+                  pdfFunctionFactory: this.pdfFunctionFactory
+                });
+                imgData = imageObj.createImageData(true);
+                operatorList.addOp(_util.OPS.paintInlineImageXObject, [imgData]);
+                return _context2.abrupt("return", undefined);
+
+              case 32:
+                nativeImageDecoderSupport = forceDisableNativeImageDecoder ? _util.NativeImageDecoding.NONE : this.options.nativeImageDecoderSupport;
+                objId = "img_".concat(this.idFactory.createObjId());
+
+                if (this.parsingType3Font) {
+                  (0, _util.assert)(nativeImageDecoderSupport === _util.NativeImageDecoding.NONE, 'Type3 image resources should be completely decoded in the worker.');
+                  objId = "".concat(this.idFactory.getDocId(), "_type3res_").concat(objId);
+                }
+
+                if (!(nativeImageDecoderSupport !== _util.NativeImageDecoding.NONE && !softMask && !mask && image instanceof _jpeg_stream.JpegStream && _image_utils.NativeImageDecoder.isSupported(image, this.xref, resources, this.pdfFunctionFactory))) {
+                  _context2.next = 37;
+                  break;
+                }
+
+                return _context2.abrupt("return", this.handler.sendWithPromise('obj', [objId, this.pageIndex, 'JpegStream', image.getIR(this.options.forceDataSchema)]).then(function () {
+                  operatorList.addDependency(objId);
+                  args = [objId, w, h];
+                  operatorList.addOp(_util.OPS.paintJpegXObject, args);
+
+                  if (cacheKey) {
+                    imageCache[cacheKey] = {
+                      fn: _util.OPS.paintJpegXObject,
+                      args: args
+                    };
+                  }
+                }, function (reason) {
+                  (0, _util.warn)('Native JPEG decoding failed -- trying to recover: ' + (reason && reason.message));
+                  return _this2.buildPaintImageXObject({
+                    resources: resources,
+                    image: image,
+                    isInline: isInline,
+                    operatorList: operatorList,
+                    cacheKey: cacheKey,
+                    imageCache: imageCache,
+                    forceDisableNativeImageDecoder: true
+                  });
+                }));
+
+              case 37:
+                nativeImageDecoder = null;
+
+                if (nativeImageDecoderSupport === _util.NativeImageDecoding.DECODE && (image instanceof _jpeg_stream.JpegStream || mask instanceof _jpeg_stream.JpegStream || softMask instanceof _jpeg_stream.JpegStream)) {
+                  nativeImageDecoder = new _image_utils.NativeImageDecoder({
+                    xref: this.xref,
+                    resources: resources,
+                    handler: this.handler,
+                    forceDataSchema: this.options.forceDataSchema,
+                    pdfFunctionFactory: this.pdfFunctionFactory
+                  });
+                }
+
+                operatorList.addDependency(objId);
+                args = [objId, w, h];
+                imgPromise = _image.PDFImage.buildImage({
+                  handler: this.handler,
+                  xref: this.xref,
+                  res: resources,
+                  image: image,
+                  isInline: isInline,
+                  nativeDecoder: nativeImageDecoder,
+                  pdfFunctionFactory: this.pdfFunctionFactory
+                }).then(function (imageObj) {
+                  var imgData = imageObj.createImageData(false);
+
+                  if (_this2.parsingType3Font) {
+                    return _this2.handler.sendWithPromise('commonobj', [objId, 'FontType3Res', imgData], [imgData.data.buffer]);
+                  }
+
+                  _this2.handler.send('obj', [objId, _this2.pageIndex, 'Image', imgData], [imgData.data.buffer]);
+
+                  return undefined;
+                })["catch"](function (reason) {
+                  (0, _util.warn)('Unable to decode image: ' + reason);
+
+                  if (_this2.parsingType3Font) {
+                    return _this2.handler.sendWithPromise('commonobj', [objId, 'FontType3Res', null]);
+                  }
+
+                  _this2.handler.send('obj', [objId, _this2.pageIndex, 'Image', null]);
+
+                  return undefined;
+                });
+
+                if (!this.parsingType3Font) {
+                  _context2.next = 45;
+                  break;
+                }
+
+                _context2.next = 45;
+                return imgPromise;
+
+              case 45:
+                operatorList.addOp(_util.OPS.paintImageXObject, args);
+
+                if (cacheKey) {
+                  imageCache[cacheKey] = {
+                    fn: _util.OPS.paintImageXObject,
+                    args: args
+                  };
+                }
+
+                return _context2.abrupt("return", undefined);
+
+              case 48:
+              case "end":
+                return _context2.stop();
+            }
+          }
+        }, _callee2, this);
+      }));
+
+      function buildPaintImageXObject(_x2) {
+        return _buildPaintImageXObject.apply(this, arguments);
       }
 
-      return Promise.resolve();
-    },
+      return buildPaintImageXObject;
+    }(),
     handleSMask: function PartialEvaluator_handleSmask(smask, resources, operatorList, task, stateManager) {
       var smaskContent = smask.get('G');
       var smaskOptions = {
@@ -658,7 +664,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
 
         return translated.loadType3Data(_this4, resources, operatorList, task).then(function () {
           return translated;
-        }).catch(function (reason) {
+        })["catch"](function (reason) {
           _this4.handler.send('UnsupportedFeature', {
             featureId: _util.UNSUPPORTED_FEATURES.font
           });
@@ -823,7 +829,8 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
 
       var fontCapability = (0, _util.createPromiseCapability)();
       var preEvaluatedFont = this.preEvaluateFont(font);
-      var descriptor = preEvaluatedFont.descriptor;
+      var descriptor = preEvaluatedFont.descriptor,
+          hash = preEvaluatedFont.hash;
       var fontRefIsRef = (0, _primitives.isRef)(fontRef),
           fontID;
 
@@ -831,13 +838,12 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         fontID = fontRef.toString();
       }
 
-      if ((0, _primitives.isDict)(descriptor)) {
+      if (hash && (0, _primitives.isDict)(descriptor)) {
         if (!descriptor.fontAliases) {
           descriptor.fontAliases = Object.create(null);
         }
 
         var fontAliases = descriptor.fontAliases;
-        var hash = preEvaluatedFont.hash;
 
         if (fontAliases[hash]) {
           var aliasFontRef = fontAliases[hash].aliasRef;
@@ -866,11 +872,11 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
           fontID = this.idFactory.createObjId();
         }
 
-        this.fontCache.put('id_' + fontID, fontCapability.promise);
+        this.fontCache.put("id_".concat(fontID), fontCapability.promise);
       }
 
       (0, _util.assert)(fontID, 'The "fontID" must be defined.');
-      font.loadedName = 'g_' + this.pdfManager.docId + '_f' + fontID;
+      font.loadedName = "".concat(this.idFactory.getDocId(), "_f").concat(fontID);
       font.translated = fontCapability.promise;
       var translatedPromise;
 
@@ -887,13 +893,12 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         }
 
         fontCapability.resolve(new TranslatedFont(font.loadedName, translatedFont, font));
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         _this6.handler.send('UnsupportedFeature', {
           featureId: _util.UNSUPPORTED_FEATURES.font
         });
 
         try {
-          var descriptor = preEvaluatedFont.descriptor;
           var fontFile3 = descriptor && descriptor.get('FontFile3');
           var subtype = fontFile3 && fontFile3.get('Subtype');
           var fontType = (0, _fonts.getFontType)(preEvaluatedFont.type, subtype && subtype.name);
@@ -905,7 +910,8 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
       });
       return fontCapability.promise;
     },
-    buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
+    buildPath: function buildPath(operatorList, fn, args) {
+      var parsingText = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
       var lastIndex = operatorList.length - 1;
 
       if (!args) {
@@ -913,47 +919,90 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
       }
 
       if (lastIndex < 0 || operatorList.fnArray[lastIndex] !== _util.OPS.constructPath) {
+        if (parsingText) {
+          (0, _util.warn)("Encountered path operator \"".concat(fn, "\" inside of a text object."));
+          operatorList.addOp(_util.OPS.save, null);
+        }
+
         operatorList.addOp(_util.OPS.constructPath, [[fn], args]);
+
+        if (parsingText) {
+          operatorList.addOp(_util.OPS.restore, null);
+        }
       } else {
         var opArgs = operatorList.argsArray[lastIndex];
         opArgs[0].push(fn);
         Array.prototype.push.apply(opArgs[1], args);
       }
     },
-    handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args, cs, patterns, resources, task) {
-      var patternName = args[args.length - 1];
-      var pattern;
+    handleColorN: function () {
+      var _handleColorN = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee3(operatorList, fn, args, cs, patterns, resources, task) {
+        var patternName, pattern, dict, typeNum, color, shading, matrix;
+        return _regenerator["default"].wrap(function _callee3$(_context3) {
+          while (1) {
+            switch (_context3.prev = _context3.next) {
+              case 0:
+                patternName = args[args.length - 1];
 
-      if ((0, _primitives.isName)(patternName) && (pattern = patterns.get(patternName.name))) {
-        var dict = (0, _primitives.isStream)(pattern) ? pattern.dict : pattern;
-        var typeNum = dict.get('PatternType');
+                if (!((0, _primitives.isName)(patternName) && (pattern = patterns.get(patternName.name)))) {
+                  _context3.next = 16;
+                  break;
+                }
 
-        if (typeNum === TILING_PATTERN) {
-          var color = cs.base ? cs.base.getRgb(args, 0) : null;
-          return this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task);
-        } else if (typeNum === SHADING_PATTERN) {
-          var shading = dict.get('Shading');
-          var matrix = dict.getArray('Matrix');
-          pattern = _pattern.Pattern.parseShading(shading, matrix, this.xref, resources, this.handler, this.pdfFunctionFactory);
-          operatorList.addOp(fn, pattern.getIR());
-          return Promise.resolve();
-        }
+                dict = (0, _primitives.isStream)(pattern) ? pattern.dict : pattern;
+                typeNum = dict.get('PatternType');
+
+                if (!(typeNum === TILING_PATTERN)) {
+                  _context3.next = 9;
+                  break;
+                }
+
+                color = cs.base ? cs.base.getRgb(args, 0) : null;
+                return _context3.abrupt("return", this.handleTilingType(fn, color, resources, pattern, dict, operatorList, task));
+
+              case 9:
+                if (!(typeNum === SHADING_PATTERN)) {
+                  _context3.next = 15;
+                  break;
+                }
+
+                shading = dict.get('Shading');
+                matrix = dict.getArray('Matrix');
+                pattern = _pattern.Pattern.parseShading(shading, matrix, this.xref, resources, this.handler, this.pdfFunctionFactory);
+                operatorList.addOp(fn, pattern.getIR());
+                return _context3.abrupt("return", undefined);
+
+              case 15:
+                throw new _util.FormatError("Unknown PatternType: ".concat(typeNum));
+
+              case 16:
+                throw new _util.FormatError("Unknown PatternName: ".concat(patternName));
+
+              case 17:
+              case "end":
+                return _context3.stop();
+            }
+          }
+        }, _callee3, this);
+      }));
 
-        return Promise.reject(new Error('Unknown PatternType: ' + typeNum));
+      function handleColorN(_x3, _x4, _x5, _x6, _x7, _x8, _x9) {
+        return _handleColorN.apply(this, arguments);
       }
 
-      operatorList.addOp(fn, args);
-      return Promise.resolve();
-    },
-    getOperatorList: function getOperatorList(_ref6) {
+      return handleColorN;
+    }(),
+    getOperatorList: function getOperatorList(_ref4) {
       var _this7 = this;
 
-      var stream = _ref6.stream,
-          task = _ref6.task,
-          resources = _ref6.resources,
-          operatorList = _ref6.operatorList,
-          _ref6$initialState = _ref6.initialState,
-          initialState = _ref6$initialState === void 0 ? null : _ref6$initialState;
+      var stream = _ref4.stream,
+          task = _ref4.task,
+          resources = _ref4.resources,
+          operatorList = _ref4.operatorList,
+          _ref4$initialState = _ref4.initialState,
+          initialState = _ref4$initialState === void 0 ? null : _ref4$initialState;
       resources = resources || _primitives.Dict.empty;
       initialState = initialState || new EvalState();
 
@@ -963,6 +1012,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
 
       var self = this;
       var xref = this.xref;
+      var parsingText = false;
       var imageCache = Object.create(null);
 
       var xobjs = resources.get('XObject') || _primitives.Dict.empty;
@@ -1064,7 +1114,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
                 }
 
                 resolveXObject();
-              }).catch(function (reason) {
+              })["catch"](function (reason) {
                 if (self.options.ignoreErrors) {
                   self.handler.send('UnsupportedFeature', {
                     featureId: _util.UNSUPPORTED_FEATURES.unknown
@@ -1085,6 +1135,14 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
               }));
               return;
 
+            case _util.OPS.beginText:
+              parsingText = true;
+              break;
+
+            case _util.OPS.endText:
+              parsingText = false;
+              break;
+
             case _util.OPS.endInlineImage:
               var cacheKey = args[0].cacheKey;
 
@@ -1266,11 +1324,8 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
             case _util.OPS.curveTo2:
             case _util.OPS.curveTo3:
             case _util.OPS.closePath:
-              self.buildPath(operatorList, fn, args);
-              continue;
-
             case _util.OPS.rectangle:
-              self.buildPath(operatorList, fn, args);
+              self.buildPath(operatorList, fn, args, parsingText);
               continue;
 
             case _util.OPS.markPoint:
@@ -1308,7 +1363,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
 
         closePendingRestoreOPS();
         resolve();
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         if (_this7.options.ignoreErrors) {
           _this7.handler.send('UnsupportedFeature', {
             featureId: _util.UNSUPPORTED_FEATURES.unknown
@@ -1322,21 +1377,21 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         throw reason;
       });
     },
-    getTextContent: function getTextContent(_ref7) {
+    getTextContent: function getTextContent(_ref5) {
       var _this8 = this;
 
-      var stream = _ref7.stream,
-          task = _ref7.task,
-          resources = _ref7.resources,
-          _ref7$stateManager = _ref7.stateManager,
-          stateManager = _ref7$stateManager === void 0 ? null : _ref7$stateManager,
-          _ref7$normalizeWhites = _ref7.normalizeWhitespace,
-          normalizeWhitespace = _ref7$normalizeWhites === void 0 ? false : _ref7$normalizeWhites,
-          _ref7$combineTextItem = _ref7.combineTextItems,
-          combineTextItems = _ref7$combineTextItem === void 0 ? false : _ref7$combineTextItem,
-          sink = _ref7.sink,
-          _ref7$seenStyles = _ref7.seenStyles,
-          seenStyles = _ref7$seenStyles === void 0 ? Object.create(null) : _ref7$seenStyles;
+      var stream = _ref5.stream,
+          task = _ref5.task,
+          resources = _ref5.resources,
+          _ref5$stateManager = _ref5.stateManager,
+          stateManager = _ref5$stateManager === void 0 ? null : _ref5$stateManager,
+          _ref5$normalizeWhites = _ref5.normalizeWhitespace,
+          normalizeWhitespace = _ref5$normalizeWhites === void 0 ? false : _ref5$normalizeWhites,
+          _ref5$combineTextItem = _ref5.combineTextItems,
+          combineTextItems = _ref5$combineTextItem === void 0 ? false : _ref5$combineTextItem,
+          sink = _ref5.sink,
+          _ref5$seenStyles = _ref5.seenStyles,
+          seenStyles = _ref5$seenStyles === void 0 ? Object.create(null) : _ref5$seenStyles;
       resources = resources || _primitives.Dict.empty;
       stateManager = stateManager || new StateManager(new TextState());
       var WhitespaceRegexp = /\s/g;
@@ -1391,12 +1446,11 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         textContentItem.fontName = font.loadedName;
         var tsm = [textState.fontSize * textState.textHScale, 0, 0, textState.fontSize, 0, textState.textRise];
 
-        if (font.isType3Font && textState.fontMatrix !== _util.FONT_IDENTITY_MATRIX && textState.fontSize === 1) {
+        if (font.isType3Font && textState.fontSize <= 1 && !(0, _util.isArrayEqual)(textState.fontMatrix, _util.FONT_IDENTITY_MATRIX)) {
           var glyphHeight = font.bbox[3] - font.bbox[1];
 
           if (glyphHeight > 0) {
-            glyphHeight = glyphHeight * textState.fontMatrix[3];
-            tsm[3] *= glyphHeight;
+            tsm[3] *= glyphHeight * textState.fontMatrix[3];
           }
         }
 
@@ -1846,7 +1900,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
 
                   resolveXObject();
                 }, rejectXObject);
-              }).catch(function (reason) {
+              })["catch"](function (reason) {
                 if (reason instanceof _util.AbortException) {
                   return;
                 }
@@ -1901,7 +1955,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         flushTextContentItem();
         enqueueChunk();
         resolve();
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         if (reason instanceof _util.AbortException) {
           return;
         }
@@ -1919,7 +1973,8 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
     extractDataStructures: function PartialEvaluator_extractDataStructures(dict, baseDict, properties) {
       var _this9 = this;
 
-      var xref = this.xref;
+      var xref = this.xref,
+          cidToGidBytes;
       var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
       var toUnicodePromise = toUnicode ? this.readToUnicode(toUnicode) : Promise.resolve(undefined);
 
@@ -1937,7 +1992,7 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         var cidToGidMap = dict.get('CIDToGIDMap');
 
         if ((0, _primitives.isStream)(cidToGidMap)) {
-          properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
+          cidToGidBytes = cidToGidMap.getBytes();
         }
       }
 
@@ -2014,6 +2069,11 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
         return _this9.buildToUnicode(properties);
       }).then(function (toUnicode) {
         properties.toUnicode = toUnicode;
+
+        if (cidToGidBytes) {
+          properties.cidToGidMap = _this9.readCidToGidMap(cidToGidBytes, toUnicode);
+        }
+
         return properties;
       });
     },
@@ -2194,18 +2254,17 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
 
       return Promise.resolve(null);
     },
-    readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
-      var glyphsData = cidToGidStream.getBytes();
+    readCidToGidMap: function readCidToGidMap(glyphsData, toUnicode) {
       var result = [];
 
       for (var j = 0, jj = glyphsData.length; j < jj; j++) {
         var glyphID = glyphsData[j++] << 8 | glyphsData[j];
+        var code = j >> 1;
 
-        if (glyphID === 0) {
+        if (glyphID === 0 && !toUnicode.has(code)) {
           continue;
         }
 
-        var code = j >> 1;
         result[code] = glyphID;
       }
 
@@ -2440,6 +2499,9 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
           }
         }
 
+        var firstChar = dict.get('FirstChar') || 0;
+        var lastChar = dict.get('LastChar') || (composite ? 0xFFFF : 0xFF);
+        hash.update("".concat(firstChar, "-").concat(lastChar));
         var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
 
         if ((0, _primitives.isStream)(toUnicode)) {
@@ -2645,8 +2707,8 @@ var PartialEvaluator = function PartialEvaluatorClosure() {
       _iteratorError = err;
     } finally {
       try {
-        if (!_iteratorNormalCompletion && _iterator.return != null) {
-          _iterator.return();
+        if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+          _iterator["return"]();
         }
       } finally {
         if (_didIteratorError) {
@@ -2699,7 +2761,9 @@ var TranslatedFont = function TranslatedFontClosure() {
 
       var type3Options = Object.create(evaluator.options);
       type3Options.ignoreErrors = false;
+      type3Options.nativeImageDecoderSupport = _util.NativeImageDecoding.NONE;
       var type3Evaluator = evaluator.clone(type3Options);
+      type3Evaluator.parsingType3Font = true;
       var translatedFont = this.font;
       var loadCharProcsPromise = Promise.resolve();
       var charProcs = this.dict.get('CharProcs');
@@ -2720,7 +2784,7 @@ var TranslatedFont = function TranslatedFontClosure() {
           }).then(function () {
             charProcOperatorList[key] = operatorList.getIR();
             parentOperatorList.addDependencies(operatorList.dependencies);
-          }).catch(function (reason) {
+          })["catch"](function (reason) {
             (0, _util.warn)("Type3 font resource \"".concat(key, "\" is not available."));
             var operatorList = new _operator_list.OperatorList();
             charProcOperatorList[key] = operatorList.getIR();
@@ -2887,7 +2951,7 @@ var EvalState = function EvalStateClosure() {
 }();
 
 var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
-  var getOPMap = (0, _util.getLookupTableFactory)(function (t) {
+  var getOPMap = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['w'] = {
       id: _util.OPS.setLineWidth,
       numArgs: 1,
@@ -3268,7 +3332,10 @@ var EvaluatorPreprocessor = function EvaluatorPreprocessorClosure() {
 
   function EvaluatorPreprocessor(stream, xref, stateManager) {
     this.opMap = getOPMap();
-    this.parser = new _parser.Parser(new _parser.Lexer(stream, this.opMap), false, xref);
+    this.parser = new _parser.Parser({
+      lexer: new _parser.Lexer(stream, this.opMap),
+      xref: xref
+    });
     this.stateManager = stateManager;
     this.nonProcessedArgs = [];
     this._numInvalidPathOPS = 0;

+ 1 - 1
lib/core/font_renderer.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 23 - 11
lib/core/fonts.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -43,6 +43,8 @@ var _font_renderer = require("./font_renderer");
 
 var _cmap = require("./cmap");
 
+var _core_utils = require("./core_utils");
+
 var _stream = require("./stream");
 
 var _type1_parser = require("./type1_parser");
@@ -1422,7 +1424,7 @@ var Font = function FontClosure() {
         };
       }
 
-      function sanitizeMetrics(font, header, metrics, numGlyphs) {
+      function sanitizeMetrics(font, header, metrics, numGlyphs, dupFirstEntry) {
         if (!header) {
           if (metrics) {
             metrics.data = null;
@@ -1460,6 +1462,12 @@ var Font = function FontClosure() {
         if (numMissing > 0) {
           var entries = new Uint8Array(metrics.length + numMissing * 2);
           entries.set(metrics.data);
+
+          if (dupFirstEntry) {
+            entries[metrics.length] = metrics.data[2];
+            entries[metrics.length + 1] = metrics.data[3];
+          }
+
           metrics.data = entries;
         }
       }
@@ -2215,7 +2223,7 @@ var Font = function FontClosure() {
         delete tables['cvt '];
       }
 
-      sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphsOut);
+      sanitizeMetrics(font, tables['hhea'], tables['hmtx'], numGlyphsOut, dupFirstEntry);
 
       if (!tables['head']) {
         throw new _util.FormatError('Required "head" table is not found');
@@ -2831,7 +2839,7 @@ var Type1Font = function Type1FontClosure() {
       headerBytes = stream.getBytes(suggestedLength);
       headerBytesLength = headerBytes.length;
     } catch (ex) {
-      if (ex instanceof _util.MissingDataException) {
+      if (ex instanceof _core_utils.MissingDataException) {
         throw ex;
       }
     }
@@ -3055,20 +3063,22 @@ var Type1Font = function Type1FontClosure() {
       cff.strings = strings;
       cff.globalSubrIndex = new _cff_parser.CFFIndex();
       var count = glyphs.length;
-      var charsetArray = [0];
+      var charsetArray = ['.notdef'];
       var i, ii;
 
       for (i = 0; i < count; i++) {
-        var index = _cff_parser.CFFStandardStrings.indexOf(charstrings[i].glyphName);
+        var glyphName = charstrings[i].glyphName;
+
+        var index = _cff_parser.CFFStandardStrings.indexOf(glyphName);
 
         if (index === -1) {
-          index = 0;
+          strings.add(glyphName);
         }
 
-        charsetArray.push(index >> 8 & 0xff, index & 0xff);
+        charsetArray.push(glyphName);
       }
 
-      cff.charset = new _cff_parser.CFFCharset(false, 0, [], charsetArray);
+      cff.charset = new _cff_parser.CFFCharset(false, 0, charsetArray);
       var charStringsIndex = new _cff_parser.CFFIndex();
       charStringsIndex.add([0x8B, 0x0E]);
 
@@ -3148,16 +3158,18 @@ var CFFFont = function CFFFontClosure() {
 
       if (properties.composite) {
         charCodeToGlyphId = Object.create(null);
+        var charCode;
 
         if (cff.isCIDFont) {
           for (glyphId = 0; glyphId < charsets.length; glyphId++) {
             var cid = charsets[glyphId];
-            var charCode = properties.cMap.charCodeOf(cid);
+            charCode = properties.cMap.charCodeOf(cid);
             charCodeToGlyphId[charCode] = glyphId;
           }
         } else {
           for (glyphId = 0; glyphId < cff.charStrings.count; glyphId++) {
-            charCodeToGlyphId[glyphId] = glyphId;
+            charCode = properties.cMap.charCodeOf(glyphId);
+            charCodeToGlyphId[charCode] = glyphId;
           }
         }
 

+ 1 - 1
lib/core/function.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 2 - 2
lib/core/glyphlist.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@
  */
 "use strict";
 
-var getLookupTableFactory = require('../shared/util').getLookupTableFactory;
+var getLookupTableFactory = require('./core_utils').getLookupTableFactory;
 
 var getGlyphsUnicode = getLookupTableFactory(function (t) {
   t['A'] = 0x0041;

+ 2 - 2
lib/core/image.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -49,7 +49,7 @@ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
 var PDFImage = function PDFImageClosure() {
   function handleImageData(image, nativeDecoder) {
     if (nativeDecoder && nativeDecoder.canDecode(image)) {
-      return nativeDecoder.decode(image).catch(function (reason) {
+      return nativeDecoder.decode(image)["catch"](function (reason) {
         (0, _util.warn)('Native image decoding failed -- trying to recover: ' + (reason && reason.message));
         return image;
       });

+ 111 - 0
lib/core/image_utils.js

@@ -0,0 +1,111 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+  value: true
+});
+exports.NativeImageDecoder = void 0;
+
+var _colorspace = require("./colorspace");
+
+var _jpeg_stream = require("./jpeg_stream");
+
+var _stream = require("./stream");
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var NativeImageDecoder =
+/*#__PURE__*/
+function () {
+  function NativeImageDecoder(_ref) {
+    var xref = _ref.xref,
+        resources = _ref.resources,
+        handler = _ref.handler,
+        _ref$forceDataSchema = _ref.forceDataSchema,
+        forceDataSchema = _ref$forceDataSchema === void 0 ? false : _ref$forceDataSchema,
+        pdfFunctionFactory = _ref.pdfFunctionFactory;
+
+    _classCallCheck(this, NativeImageDecoder);
+
+    this.xref = xref;
+    this.resources = resources;
+    this.handler = handler;
+    this.forceDataSchema = forceDataSchema;
+    this.pdfFunctionFactory = pdfFunctionFactory;
+  }
+
+  _createClass(NativeImageDecoder, [{
+    key: "canDecode",
+    value: function canDecode(image) {
+      return image instanceof _jpeg_stream.JpegStream && NativeImageDecoder.isDecodable(image, this.xref, this.resources, this.pdfFunctionFactory);
+    }
+  }, {
+    key: "decode",
+    value: function decode(image) {
+      var dict = image.dict;
+      var colorSpace = dict.get('ColorSpace', 'CS');
+      colorSpace = _colorspace.ColorSpace.parse(colorSpace, this.xref, this.resources, this.pdfFunctionFactory);
+      return this.handler.sendWithPromise('JpegDecode', [image.getIR(this.forceDataSchema), colorSpace.numComps]).then(function (_ref2) {
+        var data = _ref2.data,
+            width = _ref2.width,
+            height = _ref2.height;
+        return new _stream.Stream(data, 0, data.length, dict);
+      });
+    }
+  }], [{
+    key: "isSupported",
+    value: function isSupported(image, xref, res, pdfFunctionFactory) {
+      var dict = image.dict;
+
+      if (dict.has('DecodeParms') || dict.has('DP')) {
+        return false;
+      }
+
+      var cs = _colorspace.ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res, pdfFunctionFactory);
+
+      return (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') && cs.isDefaultDecode(dict.getArray('Decode', 'D'));
+    }
+  }, {
+    key: "isDecodable",
+    value: function isDecodable(image, xref, res, pdfFunctionFactory) {
+      var dict = image.dict;
+
+      if (dict.has('DecodeParms') || dict.has('DP')) {
+        return false;
+      }
+
+      var cs = _colorspace.ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res, pdfFunctionFactory);
+
+      var bpc = dict.get('BitsPerComponent', 'BPC') || 1;
+      return (cs.numComps === 1 || cs.numComps === 3) && cs.isDefaultDecode(dict.getArray('Decode', 'D'), bpc);
+    }
+  }]);
+
+  return NativeImageDecoder;
+}();
+
+exports.NativeImageDecoder = NativeImageDecoder;

+ 1 - 1
lib/core/jbig2.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/jbig2_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/jpeg_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 2 - 1
lib/core/jpg.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -1016,6 +1016,7 @@ var JpegImage = function JpegImageClosure() {
       }
 
       this.numComponents = this.components.length;
+      return undefined;
     },
     _getLinearizedBlockData: function _getLinearizedBlockData(width, height) {
       var isSourcePDF = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

+ 1 - 1
lib/core/jpx.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/jpx_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 13 - 13
lib/core/metrics.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -26,14 +26,14 @@ Object.defineProperty(exports, "__esModule", {
 });
 exports.getMetrics = void 0;
 
-var _util = require("../shared/util");
+var _core_utils = require("./core_utils");
 
-var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
+var getMetrics = (0, _core_utils.getLookupTableFactory)(function (t) {
   t['Courier'] = 600;
   t['Courier-Bold'] = 600;
   t['Courier-BoldOblique'] = 600;
   t['Courier-Oblique'] = 600;
-  t['Helvetica'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Helvetica'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 278;
     t['exclam'] = 278;
     t['quotedbl'] = 355;
@@ -350,7 +350,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 556;
   });
-  t['Helvetica-Bold'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Helvetica-Bold'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 278;
     t['exclam'] = 333;
     t['quotedbl'] = 474;
@@ -667,7 +667,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 556;
   });
-  t['Helvetica-BoldOblique'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Helvetica-BoldOblique'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 278;
     t['exclam'] = 333;
     t['quotedbl'] = 474;
@@ -984,7 +984,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 556;
   });
-  t['Helvetica-Oblique'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Helvetica-Oblique'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 278;
     t['exclam'] = 278;
     t['quotedbl'] = 355;
@@ -1301,7 +1301,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 556;
   });
-  t['Symbol'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Symbol'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 250;
     t['exclam'] = 333;
     t['universal'] = 713;
@@ -1493,7 +1493,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['bracerightbt'] = 494;
     t['apple'] = 790;
   });
-  t['Times-Roman'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Times-Roman'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 250;
     t['exclam'] = 333;
     t['quotedbl'] = 408;
@@ -1810,7 +1810,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 500;
   });
-  t['Times-Bold'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Times-Bold'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 250;
     t['exclam'] = 333;
     t['quotedbl'] = 555;
@@ -2127,7 +2127,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 500;
   });
-  t['Times-BoldItalic'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Times-BoldItalic'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 250;
     t['exclam'] = 389;
     t['quotedbl'] = 555;
@@ -2444,7 +2444,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 500;
   });
-  t['Times-Italic'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['Times-Italic'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 250;
     t['exclam'] = 333;
     t['quotedbl'] = 420;
@@ -2761,7 +2761,7 @@ var getMetrics = (0, _util.getLookupTableFactory)(function (t) {
     t['imacron'] = 278;
     t['Euro'] = 500;
   });
-  t['ZapfDingbats'] = (0, _util.getLookupTableFactory)(function (t) {
+  t['ZapfDingbats'] = (0, _core_utils.getLookupTableFactory)(function (t) {
     t['space'] = 278;
     t['a1'] = 974;
     t['a2'] = 961;

+ 37 - 33
lib/core/murmurhash3.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -28,18 +28,29 @@ exports.MurmurHash3_64 = void 0;
 
 var _util = require("../shared/util");
 
-var MurmurHash3_64 = function MurmurHash3_64Closure(seed) {
-  var MASK_HIGH = 0xffff0000;
-  var MASK_LOW = 0xffff;
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var SEED = 0xc3d2e1f0;
+var MASK_HIGH = 0xffff0000;
+var MASK_LOW = 0xffff;
+
+var MurmurHash3_64 =
+/*#__PURE__*/
+function () {
   function MurmurHash3_64(seed) {
-    var SEED = 0xc3d2e1f0;
+    _classCallCheck(this, MurmurHash3_64);
+
     this.h1 = seed ? seed & 0xffffffff : SEED;
     this.h2 = seed ? seed & 0xffffffff : SEED;
   }
 
-  MurmurHash3_64.prototype = {
-    update: function MurmurHash3_64_update(input) {
+  _createClass(MurmurHash3_64, [{
+    key: "update",
+    value: function update(input) {
       var data, length;
 
       if ((0, _util.isString)(input)) {
@@ -66,14 +77,14 @@ var MurmurHash3_64 = function MurmurHash3_64Closure(seed) {
       var blockCounts = length >> 2;
       var tailLength = length - blockCounts * 4;
       var dataUint32 = new Uint32Array(data.buffer, 0, blockCounts);
-      var k1 = 0;
-      var k2 = 0;
-      var h1 = this.h1;
-      var h2 = this.h2;
-      var C1 = 0xcc9e2d51;
-      var C2 = 0x1b873593;
-      var C1_LOW = C1 & MASK_LOW;
-      var C2_LOW = C2 & MASK_LOW;
+      var k1 = 0,
+          k2 = 0;
+      var h1 = this.h1,
+          h2 = this.h2;
+      var C1 = 0xcc9e2d51,
+          C2 = 0x1b873593;
+      var C1_LOW = C1 & MASK_LOW,
+          C2_LOW = C2 & MASK_LOW;
 
       for (var _i = 0; _i < blockCounts; _i++) {
         if (_i & 1) {
@@ -120,11 +131,12 @@ var MurmurHash3_64 = function MurmurHash3_64Closure(seed) {
 
       this.h1 = h1;
       this.h2 = h2;
-      return this;
-    },
-    hexdigest: function MurmurHash3_64_hexdigest() {
-      var h1 = this.h1;
-      var h2 = this.h2;
+    }
+  }, {
+    key: "hexdigest",
+    value: function hexdigest() {
+      var h1 = this.h1,
+          h2 = this.h2;
       h1 ^= h2 >>> 1;
       h1 = h1 * 0xed558ccd & MASK_HIGH | h1 * 0x8ccd & MASK_LOW;
       h2 = h2 * 0xff51afd7 & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xafd7ed55 & MASK_HIGH) >>> 16;
@@ -132,20 +144,12 @@ var MurmurHash3_64 = function MurmurHash3_64Closure(seed) {
       h1 = h1 * 0x1a85ec53 & MASK_HIGH | h1 * 0xec53 & MASK_LOW;
       h2 = h2 * 0xc4ceb9fe & MASK_HIGH | ((h2 << 16 | h1 >>> 16) * 0xb9fe1a85 & MASK_HIGH) >>> 16;
       h1 ^= h2 >>> 1;
-
-      for (var i = 0, arr = [h1, h2], str = ''; i < arr.length; i++) {
-        var hex = (arr[i] >>> 0).toString(16);
-
-        while (hex.length < 8) {
-          hex = '0' + hex;
-        }
-
-        str += hex;
-      }
-
-      return str;
+      var hex1 = (h1 >>> 0).toString(16),
+          hex2 = (h2 >>> 0).toString(16);
+      return hex1.padStart(8, '0') + hex2.padStart(8, '0');
     }
-  };
+  }]);
+
   return MurmurHash3_64;
 }();
 

+ 245 - 41
lib/core/obj.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -34,13 +34,15 @@ var _primitives = require("./primitives");
 
 var _parser = require("./parser");
 
+var _core_utils = require("./core_utils");
+
 var _chunked_stream = require("./chunked_stream");
 
 var _crypto = require("./crypto");
 
 var _colorspace = require("./colorspace");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
 
@@ -146,6 +148,7 @@ function () {
         var title = outlineDict.get('Title');
         var flags = outlineDict.get('F') || 0;
         var color = outlineDict.getArray('C');
+        var count = outlineDict.get('Count');
         var rgbColor = blackColor;
 
         if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
@@ -159,7 +162,7 @@ function () {
           newWindow: data.newWindow,
           title: (0, _util.stringToPDFString)(title),
           color: rgbColor,
-          count: outlineDict.get('Count'),
+          count: Number.isInteger(count) ? count : undefined,
           bold: !!(flags & 2),
           italic: !!(flags & 1),
           items: []
@@ -237,6 +240,8 @@ function () {
       } else if (this.catDict.has('Dests')) {
         return this.catDict.get('Dests');
       }
+
+      return undefined;
     }
   }, {
     key: "_readPageLabels",
@@ -311,7 +316,7 @@ function () {
 
           case 'R':
           case 'r':
-            currentLabel = (0, _util.toRomanNumerals)(currentIndex, style === 'r');
+            currentLabel = (0, _core_utils.toRomanNumerals)(currentIndex, style === 'r');
             break;
 
           case 'A':
@@ -371,8 +376,8 @@ function () {
           _iteratorError = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion && _iterator.return != null) {
-              _iterator.return();
+            if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+              _iterator["return"]();
             }
           } finally {
             if (_didIteratorError) {
@@ -387,6 +392,7 @@ function () {
     value: function cleanup() {
       var _this = this;
 
+      (0, _primitives.clearPrimitiveCaches)();
       this.pageKidsCountCache.clear();
       var promises = [];
       this.fontCache.forEach(function (promise) {
@@ -631,7 +637,7 @@ function () {
           try {
             metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
           } catch (e) {
-            if (e instanceof _util.MissingDataException) {
+            if (e instanceof _core_utils.MissingDataException) {
               throw e;
             }
 
@@ -661,7 +667,7 @@ function () {
       try {
         obj = this._readDocumentOutline();
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
@@ -678,7 +684,7 @@ function () {
       try {
         permissions = this._readPermissions();
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
@@ -728,7 +734,7 @@ function () {
       try {
         obj = this._readPageLabels();
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
@@ -737,6 +743,26 @@ function () {
 
       return (0, _util.shadow)(this, 'pageLabels', obj);
     }
+  }, {
+    key: "pageLayout",
+    get: function get() {
+      var obj = this.catDict.get('PageLayout');
+      var pageLayout = '';
+
+      if ((0, _primitives.isName)(obj)) {
+        switch (obj.name) {
+          case 'SinglePage':
+          case 'OneColumn':
+          case 'TwoColumnLeft':
+          case 'TwoColumnRight':
+          case 'TwoPageLeft':
+          case 'TwoPageRight':
+            pageLayout = obj.name;
+        }
+      }
+
+      return (0, _util.shadow)(this, 'pageLayout', pageLayout);
+    }
   }, {
     key: "pageMode",
     get: function get() {
@@ -757,6 +783,162 @@ function () {
 
       return (0, _util.shadow)(this, 'pageMode', pageMode);
     }
+  }, {
+    key: "viewerPreferences",
+    get: function get() {
+      var _this2 = this;
+
+      var ViewerPreferencesValidators = {
+        HideToolbar: _util.isBool,
+        HideMenubar: _util.isBool,
+        HideWindowUI: _util.isBool,
+        FitWindow: _util.isBool,
+        CenterWindow: _util.isBool,
+        DisplayDocTitle: _util.isBool,
+        NonFullScreenPageMode: _primitives.isName,
+        Direction: _primitives.isName,
+        ViewArea: _primitives.isName,
+        ViewClip: _primitives.isName,
+        PrintArea: _primitives.isName,
+        PrintClip: _primitives.isName,
+        PrintScaling: _primitives.isName,
+        Duplex: _primitives.isName,
+        PickTrayByPDFSize: _util.isBool,
+        PrintPageRange: Array.isArray,
+        NumCopies: Number.isInteger
+      };
+      var obj = this.catDict.get('ViewerPreferences');
+      var prefs = Object.create(null);
+
+      if ((0, _primitives.isDict)(obj)) {
+        for (var key in ViewerPreferencesValidators) {
+          if (!obj.has(key)) {
+            continue;
+          }
+
+          var value = obj.get(key);
+
+          if (!ViewerPreferencesValidators[key](value)) {
+            (0, _util.info)("Bad value in ViewerPreferences for \"".concat(key, "\"."));
+            continue;
+          }
+
+          var prefValue = void 0;
+
+          switch (key) {
+            case 'NonFullScreenPageMode':
+              switch (value.name) {
+                case 'UseNone':
+                case 'UseOutlines':
+                case 'UseThumbs':
+                case 'UseOC':
+                  prefValue = value.name;
+                  break;
+
+                default:
+                  prefValue = 'UseNone';
+              }
+
+              break;
+
+            case 'Direction':
+              switch (value.name) {
+                case 'L2R':
+                case 'R2L':
+                  prefValue = value.name;
+                  break;
+
+                default:
+                  prefValue = 'L2R';
+              }
+
+              break;
+
+            case 'ViewArea':
+            case 'ViewClip':
+            case 'PrintArea':
+            case 'PrintClip':
+              switch (value.name) {
+                case 'MediaBox':
+                case 'CropBox':
+                case 'BleedBox':
+                case 'TrimBox':
+                case 'ArtBox':
+                  prefValue = value.name;
+                  break;
+
+                default:
+                  prefValue = 'CropBox';
+              }
+
+              break;
+
+            case 'PrintScaling':
+              switch (value.name) {
+                case 'None':
+                case 'AppDefault':
+                  prefValue = value.name;
+                  break;
+
+                default:
+                  prefValue = 'AppDefault';
+              }
+
+              break;
+
+            case 'Duplex':
+              switch (value.name) {
+                case 'Simplex':
+                case 'DuplexFlipShortEdge':
+                case 'DuplexFlipLongEdge':
+                  prefValue = value.name;
+                  break;
+
+                default:
+                  prefValue = 'None';
+              }
+
+              break;
+
+            case 'PrintPageRange':
+              var length = value.length;
+
+              if (length % 2 !== 0) {
+                break;
+              }
+
+              var isValid = value.every(function (page, i, arr) {
+                return Number.isInteger(page) && page > 0 && (i === 0 || page >= arr[i - 1]) && page <= _this2.numPages;
+              });
+
+              if (isValid) {
+                prefValue = value;
+              }
+
+              break;
+
+            case 'NumCopies':
+              if (value > 0) {
+                prefValue = value;
+              }
+
+              break;
+
+            default:
+              (0, _util.assert)(typeof value === 'boolean');
+              prefValue = value;
+          }
+
+          if (prefValue !== undefined) {
+            prefs[key] = prefValue;
+          } else {
+            (0, _util.info)("Bad value in ViewerPreferences for \"".concat(key, "\"."));
+          }
+        }
+      }
+
+      return (0, _util.shadow)(this, 'viewerPreferences', prefs);
+    }
   }, {
     key: "openActionDestination",
     get: function get() {
@@ -1075,7 +1257,7 @@ var XRef = function XRefClosure() {
       try {
         encrypt = trailerDict.get('Encrypt');
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
@@ -1094,7 +1276,7 @@ var XRef = function XRefClosure() {
       try {
         root = trailerDict.get('Root');
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
@@ -1105,7 +1287,7 @@ var XRef = function XRefClosure() {
         this.root = root;
       } else {
         if (!recoveryMode) {
-          throw new _util.XRefParseException();
+          throw new _core_utils.XRefParseException();
         }
 
         throw new _util.FormatError('Invalid root reference');
@@ -1175,10 +1357,16 @@ var XRef = function XRefClosure() {
           entry.gen = parser.getObj();
           var type = parser.getObj();
 
-          if ((0, _primitives.isCmd)(type, 'f')) {
-            entry.free = true;
-          } else if ((0, _primitives.isCmd)(type, 'n')) {
-            entry.uncompressed = true;
+          if (type instanceof _primitives.Cmd) {
+            switch (type.cmd) {
+              case 'f':
+                entry.free = true;
+                break;
+
+              case 'n':
+                entry.uncompressed = true;
+                break;
+            }
           }
 
           if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
@@ -1462,7 +1650,12 @@ var XRef = function XRefClosure() {
 
       for (i = 0, ii = trailers.length; i < ii; ++i) {
         stream.pos = trailers[i];
-        var parser = new _parser.Parser(new _parser.Lexer(stream), true, this, true);
+        var parser = new _parser.Parser({
+          lexer: new _parser.Lexer(stream),
+          xref: this,
+          allowStreams: true,
+          recoveryMode: true
+        });
         var obj = parser.getObj();
 
         if (!(0, _primitives.isCmd)(obj, 'trailer')) {
@@ -1480,7 +1673,7 @@ var XRef = function XRefClosure() {
         try {
           rootDict = dict.get('Root');
         } catch (ex) {
-          if (ex instanceof _util.MissingDataException) {
+          if (ex instanceof _core_utils.MissingDataException) {
             throw ex;
           }
 
@@ -1520,7 +1713,11 @@ var XRef = function XRefClosure() {
 
           startXRefParsedCache[startXRef] = true;
           stream.pos = startXRef + stream.start;
-          var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
+          var parser = new _parser.Parser({
+            lexer: new _parser.Lexer(stream),
+            xref: this,
+            allowStreams: true
+          });
           var obj = parser.getObj();
           var dict;
 
@@ -1572,7 +1769,7 @@ var XRef = function XRefClosure() {
 
         return this.topDict;
       } catch (e) {
-        if (e instanceof _util.MissingDataException) {
+        if (e instanceof _core_utils.MissingDataException) {
           throw e;
         }
 
@@ -1580,10 +1777,10 @@ var XRef = function XRefClosure() {
       }
 
       if (recoveryMode) {
-        return;
+        return undefined;
       }
 
-      throw new _util.XRefParseException();
+      throw new _core_utils.XRefParseException();
     },
     getEntry: function XRef_getEntry(i) {
       var xrefEntry = this.entries[i];
@@ -1644,11 +1841,15 @@ var XRef = function XRefClosure() {
       var num = ref.num;
 
       if (xrefEntry.gen !== gen) {
-        throw new _util.XRefEntryException("Inconsistent generation in XRef: ".concat(ref));
+        throw new _core_utils.XRefEntryException("Inconsistent generation in XRef: ".concat(ref));
       }
 
       var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
-      var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
+      var parser = new _parser.Parser({
+        lexer: new _parser.Lexer(stream),
+        xref: this,
+        allowStreams: true
+      });
       var obj1 = parser.getObj();
       var obj2 = parser.getObj();
       var obj3 = parser.getObj();
@@ -1661,8 +1862,8 @@ var XRef = function XRefClosure() {
         obj2 = parseInt(obj2, 10);
       }
 
-      if (obj1 !== num || obj2 !== gen || !(0, _primitives.isCmd)(obj3)) {
-        throw new _util.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
+      if (obj1 !== num || obj2 !== gen || !(obj3 instanceof _primitives.Cmd)) {
+        throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
       }
 
       if (obj3.cmd !== 'obj') {
@@ -1674,7 +1875,7 @@ var XRef = function XRefClosure() {
           }
         }
 
-        throw new _util.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
+        throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
       }
 
       if (this.encrypt && !suppressEncryption) {
@@ -1692,7 +1893,7 @@ var XRef = function XRefClosure() {
     fetchCompressed: function fetchCompressed(ref, xrefEntry) {
       var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
       var tableOffset = xrefEntry.offset;
-      var stream = this.fetch(new _primitives.Ref(tableOffset, 0));
+      var stream = this.fetch(_primitives.Ref.get(tableOffset, 0));
 
       if (!(0, _primitives.isStream)(stream)) {
         throw new _util.FormatError('bad ObjStm stream');
@@ -1705,8 +1906,11 @@ var XRef = function XRefClosure() {
         throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
       }
 
-      var parser = new _parser.Parser(new _parser.Lexer(stream), false, this);
-      parser.allowStreams = true;
+      var parser = new _parser.Parser({
+        lexer: new _parser.Lexer(stream),
+        xref: this,
+        allowStreams: true
+      });
       var i,
           entries = [],
           num,
@@ -1745,7 +1949,7 @@ var XRef = function XRefClosure() {
       xrefEntry = entries[xrefEntry.gen];
 
       if (xrefEntry === undefined) {
-        throw new _util.XRefEntryException("Bad (compressed) XRef entry: ".concat(ref));
+        throw new _core_utils.XRefEntryException("Bad (compressed) XRef entry: ".concat(ref));
       }
 
       return xrefEntry;
@@ -1753,8 +1957,8 @@ var XRef = function XRefClosure() {
     fetchIfRefAsync: function () {
       var _fetchIfRefAsync = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee(obj, suppressEncryption) {
-        return _regenerator.default.wrap(function _callee$(_context) {
+      _regenerator["default"].mark(function _callee(obj, suppressEncryption) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -1785,8 +1989,8 @@ var XRef = function XRefClosure() {
     fetchAsync: function () {
       var _fetchAsync = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee2(ref, suppressEncryption) {
-        return _regenerator.default.wrap(function _callee2$(_context2) {
+      _regenerator["default"].mark(function _callee2(ref, suppressEncryption) {
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
           while (1) {
             switch (_context2.prev = _context2.next) {
               case 0:
@@ -1797,7 +2001,7 @@ var XRef = function XRefClosure() {
                 _context2.prev = 4;
                 _context2.t0 = _context2["catch"](0);
 
-                if (_context2.t0 instanceof _util.MissingDataException) {
+                if (_context2.t0 instanceof _core_utils.MissingDataException) {
                   _context2.next = 8;
                   break;
                 }
@@ -2169,7 +2373,7 @@ var ObjectLoader = function () {
       return this.capability.promise;
     },
     _walk: function _walk(nodesToVisit) {
-      var _this2 = this;
+      var _this3 = this;
 
       var nodesToRevisit = [];
       var pendingRequests = [];
@@ -2186,7 +2390,7 @@ var ObjectLoader = function () {
             this.refSet.put(currentNode);
             currentNode = this.xref.fetch(currentNode);
           } catch (ex) {
-            if (!(ex instanceof _util.MissingDataException)) {
+            if (!(ex instanceof _core_utils.MissingDataException)) {
               throw ex;
             }
 
@@ -2228,11 +2432,11 @@ var ObjectLoader = function () {
             var node = nodesToRevisit[_i4];
 
             if ((0, _primitives.isRef)(node)) {
-              _this2.refSet.remove(node);
+              _this3.refSet.remove(node);
             }
           }
 
-          _this2._walk(nodesToRevisit);
+          _this3._walk(nodesToRevisit);
         }, this.capability.reject);
         return;
       }

+ 43 - 32
lib/core/operator_list.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -81,6 +81,8 @@ var QueueOptimizer = function QueueOptimizerClosure() {
       case 3:
         return fnArray[i] === _util.OPS.restore;
     }
+
+    throw new Error("iterateInlineImageGroup - invalid pos: ".concat(pos));
   }, function foundInlineImageGroup(context, i) {
     var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
     var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
@@ -187,6 +189,8 @@ var QueueOptimizer = function QueueOptimizerClosure() {
       case 3:
         return fnArray[i] === _util.OPS.restore;
     }
+
+    throw new Error("iterateImageMaskGroup - invalid pos: ".concat(pos));
   }, function foundImageMaskGroup(context, i) {
     var MIN_IMAGES_IN_MASKS_BLOCK = 10;
     var MAX_IMAGES_IN_MASKS_BLOCK = 100;
@@ -269,7 +273,7 @@ var QueueOptimizer = function QueueOptimizerClosure() {
     var argsArray = context.argsArray;
     var iFirstTransform = context.iCurr - 2;
     return argsArray[iFirstTransform][1] === 0 && argsArray[iFirstTransform][2] === 0;
-  }, function (context, i) {
+  }, function iterateImageGroup(context, i) {
     var fnArray = context.fnArray,
         argsArray = context.argsArray;
     var iFirstSave = context.iCurr - 3;
@@ -311,6 +315,8 @@ var QueueOptimizer = function QueueOptimizerClosure() {
       case 3:
         return fnArray[i] === _util.OPS.restore;
     }
+
+    throw new Error("iterateImageGroup - invalid pos: ".concat(pos));
   }, function (context, i) {
     var MIN_IMAGES_IN_BLOCK = 3;
     var MAX_IMAGES_IN_BLOCK = 1000;
@@ -343,7 +349,7 @@ var QueueOptimizer = function QueueOptimizerClosure() {
     argsArray.splice(iFirstSave, count * 4, args);
     return iFirstSave + 1;
   });
-  addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTextMatrix, _util.OPS.showText, _util.OPS.endText], null, function (context, i) {
+  addState(InitialState, [_util.OPS.beginText, _util.OPS.setFont, _util.OPS.setTextMatrix, _util.OPS.showText, _util.OPS.endText], null, function iterateShowTextGroup(context, i) {
     var fnArray = context.fnArray,
         argsArray = context.argsArray;
     var iFirstSave = context.iCurr - 4;
@@ -377,6 +383,8 @@ var QueueOptimizer = function QueueOptimizerClosure() {
       case 4:
         return fnArray[i] === _util.OPS.endText;
     }
+
+    throw new Error("iterateShowTextGroup - invalid pos: ".concat(pos));
   }, function (context, i) {
     var MIN_CHARS_IN_BLOCK = 3;
     var MAX_CHARS_IN_BLOCK = 1000;
@@ -518,7 +526,8 @@ var NullOptimizer = function NullOptimizerClosure() {
       this.queue.fnArray.push(fn);
       this.queue.argsArray.push(args);
     },
-    flush: function flush() {}
+    flush: function flush() {},
+    reset: function reset() {}
   };
   return NullOptimizer;
 }();
@@ -527,36 +536,12 @@ var OperatorList = function OperatorListClosure() {
   var CHUNK_SIZE = 1000;
   var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5;
 
-  function getTransfers(queue) {
-    var transfers = [];
-    var fnArray = queue.fnArray,
-        argsArray = queue.argsArray;
-
-    for (var i = 0, ii = queue.length; i < ii; i++) {
-      switch (fnArray[i]) {
-        case _util.OPS.paintInlineImageXObject:
-        case _util.OPS.paintInlineImageXObjectGroup:
-        case _util.OPS.paintImageMaskXObject:
-          var arg = argsArray[i][0];
-          ;
-
-          if (!arg.cached) {
-            transfers.push(arg.data.buffer);
-          }
-
-          break;
-      }
-    }
-
-    return transfers;
-  }
-
   function OperatorList(intent, messageHandler, pageIndex) {
     this.messageHandler = messageHandler;
     this.fnArray = [];
     this.argsArray = [];
 
-    if (messageHandler && this.intent !== 'oplist') {
+    if (messageHandler && intent !== 'oplist') {
       this.optimizer = new QueueOptimizer(this);
     } else {
       this.optimizer = new NullOptimizer(this);
@@ -617,9 +602,35 @@ var OperatorList = function OperatorListClosure() {
         length: this.length
       };
     },
-    flush: function flush(lastChunk) {
+
+    get _transfers() {
+      var transfers = [];
+      var fnArray = this.fnArray,
+          argsArray = this.argsArray,
+          length = this.length;
+
+      for (var i = 0; i < length; i++) {
+        switch (fnArray[i]) {
+          case _util.OPS.paintInlineImageXObject:
+          case _util.OPS.paintInlineImageXObjectGroup:
+          case _util.OPS.paintImageMaskXObject:
+            var arg = argsArray[i][0];
+            ;
+
+            if (!arg.cached) {
+              transfers.push(arg.data.buffer);
+            }
+
+            break;
+        }
+      }
+
+      return transfers;
+    },
+
+    flush: function flush() {
+      var lastChunk = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
       this.optimizer.flush();
-      var transfers = getTransfers(this);
       var length = this.length;
       this._totalLength += length;
       this.messageHandler.send('RenderPageChunk', {
@@ -631,7 +642,7 @@ var OperatorList = function OperatorListClosure() {
         },
         pageIndex: this.pageIndex,
         intent: this.intent
-      }, transfers);
+      }, this._transfers);
       this.dependencies = Object.create(null);
       this.fnArray.length = 0;
       this.argsArray.length = 0;

+ 228 - 133
lib/core/parser.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -40,6 +40,14 @@ var _jpeg_stream = require("./jpeg_stream");
 
 var _jpx_stream = require("./jpx_stream");
 
+var _core_utils = require("./core_utils");
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
 var MAX_LENGTH_TO_CACHE = 1000;
 var MAX_ADLER32_LENGTH = 5552;
 
@@ -56,22 +64,36 @@ function computeAdler32(bytes) {
   return b % 65521 << 16 | a % 65521;
 }
 
-var Parser = function ParserClosure() {
-  function Parser(lexer, allowStreams, xref, recoveryMode) {
+var Parser =
+/*#__PURE__*/
+function () {
+  function Parser(_ref) {
+    var lexer = _ref.lexer,
+        xref = _ref.xref,
+        _ref$allowStreams = _ref.allowStreams,
+        allowStreams = _ref$allowStreams === void 0 ? false : _ref$allowStreams,
+        _ref$recoveryMode = _ref.recoveryMode,
+        recoveryMode = _ref$recoveryMode === void 0 ? false : _ref$recoveryMode;
+
+    _classCallCheck(this, Parser);
+
     this.lexer = lexer;
-    this.allowStreams = allowStreams;
     this.xref = xref;
-    this.recoveryMode = recoveryMode || false;
+    this.allowStreams = allowStreams;
+    this.recoveryMode = recoveryMode;
     this.imageCache = Object.create(null);
     this.refill();
   }
 
-  Parser.prototype = {
-    refill: function Parser_refill() {
+  _createClass(Parser, [{
+    key: "refill",
+    value: function refill() {
       this.buf1 = this.lexer.getObj();
       this.buf2 = this.lexer.getObj();
-    },
-    shift: function Parser_shift() {
+    }
+  }, {
+    key: "shift",
+    value: function shift() {
       if ((0, _primitives.isCmd)(this.buf2, 'ID')) {
         this.buf1 = this.buf2;
         this.buf2 = null;
@@ -79,20 +101,24 @@ var Parser = function ParserClosure() {
         this.buf1 = this.buf2;
         this.buf2 = this.lexer.getObj();
       }
-    },
-    tryShift: function Parser_tryShift() {
+    }
+  }, {
+    key: "tryShift",
+    value: function tryShift() {
       try {
         this.shift();
         return true;
       } catch (e) {
-        if (e instanceof _util.MissingDataException) {
+        if (e instanceof _core_utils.MissingDataException) {
           throw e;
         }
 
         return false;
       }
-    },
-    getObj: function Parser_getObj(cipherTransform) {
+    }
+  }, {
+    key: "getObj",
+    value: function getObj(cipherTransform) {
       var buf1 = this.buf1;
       this.shift();
 
@@ -163,7 +189,8 @@ var Parser = function ParserClosure() {
         var num = buf1;
 
         if (Number.isInteger(this.buf1) && (0, _primitives.isCmd)(this.buf2, 'R')) {
-          var ref = new _primitives.Ref(num, this.buf1);
+          var ref = _primitives.Ref.get(num, this.buf1);
+
           this.shift();
           this.shift();
           return ref;
@@ -183,8 +210,10 @@ var Parser = function ParserClosure() {
       }
 
       return buf1;
-    },
-    findDefaultInlineStreamEnd: function findDefaultInlineStreamEnd(stream) {
+    }
+  }, {
+    key: "findDefaultInlineStreamEnd",
+    value: function findDefaultInlineStreamEnd(stream) {
       var E = 0x45,
           I = 0x49,
           SPACE = 0x20,
@@ -250,8 +279,10 @@ var Parser = function ParserClosure() {
       }
 
       return stream.pos - endOffset - startPos;
-    },
-    findDCTDecodeInlineStreamEnd: function Parser_findDCTDecodeInlineStreamEnd(stream) {
+    }
+  }, {
+    key: "findDCTDecodeInlineStreamEnd",
+    value: function findDCTDecodeInlineStreamEnd(stream) {
       var startPos = stream.pos,
           foundEOI = false,
           b,
@@ -339,8 +370,10 @@ var Parser = function ParserClosure() {
 
       this.inlineStreamSkipEI(stream);
       return length;
-    },
-    findASCII85DecodeInlineStreamEnd: function Parser_findASCII85DecodeInlineStreamEnd(stream) {
+    }
+  }, {
+    key: "findASCII85DecodeInlineStreamEnd",
+    value: function findASCII85DecodeInlineStreamEnd(stream) {
       var TILDE = 0x7E,
           GT = 0x3E;
       var startPos = stream.pos,
@@ -348,9 +381,18 @@ var Parser = function ParserClosure() {
           length;
 
       while ((ch = stream.getByte()) !== -1) {
-        if (ch === TILDE && stream.peekByte() === GT) {
-          stream.skip();
-          break;
+        if (ch === TILDE) {
+          ch = stream.peekByte();
+
+          while ((0, _util.isSpace)(ch)) {
+            stream.skip();
+            ch = stream.peekByte();
+          }
+
+          if (ch === GT) {
+            stream.skip();
+            break;
+          }
         }
       }
 
@@ -364,8 +406,10 @@ var Parser = function ParserClosure() {
 
       this.inlineStreamSkipEI(stream);
       return length;
-    },
-    findASCIIHexDecodeInlineStreamEnd: function Parser_findASCIIHexDecodeInlineStreamEnd(stream) {
+    }
+  }, {
+    key: "findASCIIHexDecodeInlineStreamEnd",
+    value: function findASCIIHexDecodeInlineStreamEnd(stream) {
       var GT = 0x3E;
       var startPos = stream.pos,
           ch,
@@ -387,8 +431,10 @@ var Parser = function ParserClosure() {
 
       this.inlineStreamSkipEI(stream);
       return length;
-    },
-    inlineStreamSkipEI: function Parser_inlineStreamSkipEI(stream) {
+    }
+  }, {
+    key: "inlineStreamSkipEI",
+    value: function inlineStreamSkipEI(stream) {
       var E = 0x45,
           I = 0x49;
       var state = 0,
@@ -403,12 +449,14 @@ var Parser = function ParserClosure() {
           break;
         }
       }
-    },
-    makeInlineImage: function Parser_makeInlineImage(cipherTransform) {
+    }
+  }, {
+    key: "makeInlineImage",
+    value: function makeInlineImage(cipherTransform) {
       var lexer = this.lexer;
       var stream = lexer.stream;
-      var dict = new _primitives.Dict(this.xref),
-          dictLength;
+      var dict = new _primitives.Dict(this.xref);
+      var dictLength;
 
       while (!(0, _primitives.isCmd)(this.buf1, 'ID') && !(0, _primitives.isEOF)(this.buf1)) {
         if (!(0, _primitives.isName)(this.buf1)) {
@@ -429,8 +477,8 @@ var Parser = function ParserClosure() {
         dictLength = stream.pos - lexer.beginInlineImagePos;
       }
 
-      var filter = dict.get('Filter', 'F'),
-          filterName;
+      var filter = dict.get('Filter', 'F');
+      var filterName;
 
       if ((0, _primitives.isName)(filter)) {
         filterName = filter.name;
@@ -442,8 +490,8 @@ var Parser = function ParserClosure() {
         }
       }
 
-      var startPos = stream.pos,
-          length;
+      var startPos = stream.pos;
+      var length;
 
       if (filterName === 'DCTDecode' || filterName === 'DCT') {
         length = this.findDCTDecodeInlineStreamEnd(stream);
@@ -484,15 +532,17 @@ var Parser = function ParserClosure() {
       imageStream.dict = dict;
 
       if (cacheKey !== undefined) {
-        imageStream.cacheKey = 'inline_' + length + '_' + cacheKey;
+        imageStream.cacheKey = "inline_".concat(length, "_").concat(cacheKey);
         this.imageCache[cacheKey] = imageStream;
       }
 
       this.buf2 = _primitives.Cmd.get('EI');
       this.shift();
       return imageStream;
-    },
-    _findStreamLength: function _findStreamLength(startPos, signature) {
+    }
+  }, {
+    key: "_findStreamLength",
+    value: function _findStreamLength(startPos, signature) {
       var stream = this.lexer.stream;
       stream.pos = startPos;
       var SCAN_BLOCK_LENGTH = 2048;
@@ -527,8 +577,10 @@ var Parser = function ParserClosure() {
       }
 
       return -1;
-    },
-    makeStream: function Parser_makeStream(dict, cipherTransform) {
+    }
+  }, {
+    key: "makeStream",
+    value: function makeStream(dict, cipherTransform) {
       var lexer = this.lexer;
       var stream = lexer.stream;
       lexer.skipToNextLine();
@@ -536,7 +588,7 @@ var Parser = function ParserClosure() {
       var length = dict.get('Length');
 
       if (!Number.isInteger(length)) {
-        (0, _util.info)('Bad ' + length + ' attribute in stream');
+        (0, _util.info)("Bad length \"".concat(length, "\" in stream"));
         length = 0;
       }
 
@@ -593,8 +645,10 @@ var Parser = function ParserClosure() {
       stream = this.filter(stream, dict, length);
       stream.dict = dict;
       return stream;
-    },
-    filter: function Parser_filter(stream, dict, length) {
+    }
+  }, {
+    key: "filter",
+    value: function filter(stream, dict, length) {
       var filter = dict.get('Filter', 'F');
       var params = dict.get('DecodeParms', 'DP');
 
@@ -616,7 +670,7 @@ var Parser = function ParserClosure() {
           filter = this.xref.fetchIfRef(filterArray[i]);
 
           if (!(0, _primitives.isName)(filter)) {
-            throw new _util.FormatError('Bad filter name: ' + filter);
+            throw new _util.FormatError("Bad filter name \"".concat(filter, "\""));
           }
 
           params = null;
@@ -631,10 +685,12 @@ var Parser = function ParserClosure() {
       }
 
       return stream;
-    },
-    makeFilter: function Parser_makeFilter(stream, name, maybeLength, params) {
+    }
+  }, {
+    key: "makeFilter",
+    value: function makeFilter(stream, name, maybeLength, params) {
       if (maybeLength === 0) {
-        (0, _util.warn)('Empty "' + name + '" stream.');
+        (0, _util.warn)("Empty \"".concat(name, "\" stream."));
         return new _stream.NullStream();
       }
 
@@ -701,54 +757,65 @@ var Parser = function ParserClosure() {
           return new _jbig2_stream.Jbig2Stream(stream, maybeLength, stream.dict, params);
         }
 
-        (0, _util.warn)('filter "' + name + '" not supported yet');
+        (0, _util.warn)("Filter \"".concat(name, "\" is not supported."));
         return stream;
       } catch (ex) {
-        if (ex instanceof _util.MissingDataException) {
+        if (ex instanceof _core_utils.MissingDataException) {
           throw ex;
         }
 
-        (0, _util.warn)('Invalid stream: \"' + ex + '\"');
+        (0, _util.warn)("Invalid stream: \"".concat(ex, "\""));
         return new _stream.NullStream();
       }
     }
-  };
+  }]);
+
   return Parser;
 }();
 
 exports.Parser = Parser;
+var specialChars = [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 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, 2, 0, 2, 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, 2, 0, 2, 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, 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];
 
-var Lexer = function LexerClosure() {
-  function Lexer(stream, knownCommands) {
-    this.stream = stream;
-    this.nextChar();
-    this.strBuf = [];
-    this.knownCommands = knownCommands;
-    this.beginInlineImagePos = -1;
+function toHexDigit(ch) {
+  if (ch >= 0x30 && ch <= 0x39) {
+    return ch & 0x0F;
   }
 
-  var specialChars = [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 2, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 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, 2, 0, 2, 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, 2, 0, 2, 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, 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];
+  if (ch >= 0x41 && ch <= 0x46 || ch >= 0x61 && ch <= 0x66) {
+    return (ch & 0x0F) + 9;
+  }
 
-  function toHexDigit(ch) {
-    if (ch >= 0x30 && ch <= 0x39) {
-      return ch & 0x0F;
-    }
+  return -1;
+}
 
-    if (ch >= 0x41 && ch <= 0x46 || ch >= 0x61 && ch <= 0x66) {
-      return (ch & 0x0F) + 9;
-    }
+var Lexer =
+/*#__PURE__*/
+function () {
+  function Lexer(stream) {
+    var knownCommands = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
+
+    _classCallCheck(this, Lexer);
 
-    return -1;
+    this.stream = stream;
+    this.nextChar();
+    this.strBuf = [];
+    this.knownCommands = knownCommands;
+    this.beginInlineImagePos = -1;
   }
 
-  Lexer.prototype = {
-    nextChar: function Lexer_nextChar() {
+  _createClass(Lexer, [{
+    key: "nextChar",
+    value: function nextChar() {
       return this.currentChar = this.stream.getByte();
-    },
-    peekChar: function Lexer_peekChar() {
+    }
+  }, {
+    key: "peekChar",
+    value: function peekChar() {
       return this.stream.peekByte();
-    },
-    getNumber: function Lexer_getNumber() {
+    }
+  }, {
+    key: "getNumber",
+    value: function getNumber() {
       var ch = this.currentChar;
       var eNotation = false;
       var divideBy = 0;
@@ -811,7 +878,7 @@ var Lexer = function LexerClosure() {
             break;
           }
         } else if (ch === 0x2D) {
-          (0, _util.warn)('Badly formatted number');
+          (0, _util.warn)('Badly formatted number: minus sign in the middle');
         } else if (ch === 0x45 || ch === 0x65) {
           ch = this.peekChar();
 
@@ -837,8 +904,10 @@ var Lexer = function LexerClosure() {
       }
 
       return sign * baseValue;
-    },
-    getString: function Lexer_getString() {
+    }
+  }, {
+    key: "getString",
+    value: function getString() {
       var numParen = 1;
       var done = false;
       var strBuf = this.strBuf;
@@ -961,8 +1030,10 @@ var Lexer = function LexerClosure() {
       }
 
       return strBuf.join('');
-    },
-    getName: function Lexer_getName() {
+    }
+  }, {
+    key: "getName",
+    value: function getName() {
       var ch, previousCh;
       var strBuf = this.strBuf;
       strBuf.length = 0;
@@ -985,7 +1056,7 @@ var Lexer = function LexerClosure() {
             var x2 = toHexDigit(ch);
 
             if (x2 === -1) {
-              (0, _util.warn)('Lexer_getName: Illegal digit (' + String.fromCharCode(ch) + ') in hexadecimal number.');
+              (0, _util.warn)("Lexer_getName: Illegal digit (".concat(String.fromCharCode(ch), ") ") + 'in hexadecimal number.');
               strBuf.push('#', String.fromCharCode(previousCh));
 
               if (specialChars[ch]) {
@@ -1006,18 +1077,19 @@ var Lexer = function LexerClosure() {
       }
 
       if (strBuf.length > 127) {
-        (0, _util.warn)('name token is longer than allowed by the spec: ' + strBuf.length);
+        (0, _util.warn)("Name token is longer than allowed by the spec: ".concat(strBuf.length));
       }
 
       return _primitives.Name.get(strBuf.join(''));
-    },
-    getHexString: function Lexer_getHexString() {
+    }
+  }, {
+    key: "getHexString",
+    value: function getHexString() {
       var strBuf = this.strBuf;
       strBuf.length = 0;
       var ch = this.currentChar;
       var isFirstHex = true;
-      var firstDigit;
-      var secondDigit;
+      var firstDigit, secondDigit;
 
       while (true) {
         if (ch < 0) {
@@ -1034,7 +1106,7 @@ var Lexer = function LexerClosure() {
             firstDigit = toHexDigit(ch);
 
             if (firstDigit === -1) {
-              (0, _util.warn)('Ignoring invalid character "' + ch + '" in hex string');
+              (0, _util.warn)("Ignoring invalid character \"".concat(ch, "\" in hex string"));
               ch = this.nextChar();
               continue;
             }
@@ -1042,7 +1114,7 @@ var Lexer = function LexerClosure() {
             secondDigit = toHexDigit(ch);
 
             if (secondDigit === -1) {
-              (0, _util.warn)('Ignoring invalid character "' + ch + '" in hex string');
+              (0, _util.warn)("Ignoring invalid character \"".concat(ch, "\" in hex string"));
               ch = this.nextChar();
               continue;
             }
@@ -1056,8 +1128,10 @@ var Lexer = function LexerClosure() {
       }
 
       return strBuf.join('');
-    },
-    getObj: function Lexer_getObj() {
+    }
+  }, {
+    key: "getObj",
+    value: function getObj() {
       var comment = false;
       var ch = this.currentChar;
 
@@ -1178,8 +1252,10 @@ var Lexer = function LexerClosure() {
       }
 
       return _primitives.Cmd.get(str);
-    },
-    skipToNextLine: function Lexer_skipToNextLine() {
+    }
+  }, {
+    key: "skipToNextLine",
+    value: function skipToNextLine() {
       var ch = this.currentChar;
 
       while (ch >= 0) {
@@ -1199,63 +1275,82 @@ var Lexer = function LexerClosure() {
         ch = this.nextChar();
       }
     }
-  };
+  }]);
+
   return Lexer;
 }();
 
 exports.Lexer = Lexer;
-var Linearization = {
-  create: function LinearizationCreate(stream) {
-    function getInt(name, allowZeroValue) {
-      var obj = linDict.get(name);
 
-      if (Number.isInteger(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
-        return obj;
+var Linearization =
+/*#__PURE__*/
+function () {
+  function Linearization() {
+    _classCallCheck(this, Linearization);
+  }
+
+  _createClass(Linearization, null, [{
+    key: "create",
+    value: function create(stream) {
+      function getInt(linDict, name) {
+        var allowZeroValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+        var obj = linDict.get(name);
+
+        if (Number.isInteger(obj) && (allowZeroValue ? obj >= 0 : obj > 0)) {
+          return obj;
+        }
+
+        throw new Error("The \"".concat(name, "\" parameter in the linearization ") + 'dictionary is invalid.');
       }
 
-      throw new Error('The "' + name + '" parameter in the linearization ' + 'dictionary is invalid.');
-    }
+      function getHints(linDict) {
+        var hints = linDict.get('H');
+        var hintsLength;
 
-    function getHints() {
-      var hints = linDict.get('H'),
-          hintsLength,
-          item;
+        if (Array.isArray(hints) && ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
+          for (var index = 0; index < hintsLength; index++) {
+            var hint = hints[index];
 
-      if (Array.isArray(hints) && ((hintsLength = hints.length) === 2 || hintsLength === 4)) {
-        for (var index = 0; index < hintsLength; index++) {
-          if (!(Number.isInteger(item = hints[index]) && item > 0)) {
-            throw new Error('Hint (' + index + ') in the linearization dictionary is invalid.');
+            if (!(Number.isInteger(hint) && hint > 0)) {
+              throw new Error("Hint (".concat(index, ") in the linearization dictionary ") + 'is invalid.');
+            }
           }
+
+          return hints;
         }
 
-        return hints;
+        throw new Error('Hint array in the linearization dictionary is invalid.');
       }
 
-      throw new Error('Hint array in the linearization dictionary is invalid.');
-    }
+      var parser = new Parser({
+        lexer: new Lexer(stream),
+        xref: null
+      });
+      var obj1 = parser.getObj();
+      var obj2 = parser.getObj();
+      var obj3 = parser.getObj();
+      var linDict = parser.getObj();
+      var obj, length;
+
+      if (!(Number.isInteger(obj1) && Number.isInteger(obj2) && (0, _primitives.isCmd)(obj3, 'obj') && (0, _primitives.isDict)(linDict) && (0, _util.isNum)(obj = linDict.get('Linearized')) && obj > 0)) {
+        return null;
+      } else if ((length = getInt(linDict, 'L')) !== stream.length) {
+        throw new Error('The "L" parameter in the linearization dictionary ' + 'does not equal the stream length.');
+      }
 
-    var parser = new Parser(new Lexer(stream), false, null);
-    var obj1 = parser.getObj();
-    var obj2 = parser.getObj();
-    var obj3 = parser.getObj();
-    var linDict = parser.getObj();
-    var obj, length;
-
-    if (!(Number.isInteger(obj1) && Number.isInteger(obj2) && (0, _primitives.isCmd)(obj3, 'obj') && (0, _primitives.isDict)(linDict) && (0, _util.isNum)(obj = linDict.get('Linearized')) && obj > 0)) {
-      return null;
-    } else if ((length = getInt('L')) !== stream.length) {
-      throw new Error('The "L" parameter in the linearization dictionary ' + 'does not equal the stream length.');
+      return {
+        length: length,
+        hints: getHints(linDict),
+        objectNumberFirst: getInt(linDict, 'O'),
+        endFirst: getInt(linDict, 'E'),
+        numPages: getInt(linDict, 'N'),
+        mainXRefEntriesOffset: getInt(linDict, 'T'),
+        pageFirst: linDict.has('P') ? getInt(linDict, 'P', true) : 0
+      };
     }
+  }]);
+
+  return Linearization;
+}();
 
-    return {
-      length: length,
-      hints: getHints(),
-      objectNumberFirst: getInt('O'),
-      endFirst: getInt('E'),
-      numPages: getInt('N'),
-      mainXRefEntriesOffset: getInt('T'),
-      pageFirst: linDict.has('P') ? getInt('P', true) : 0
-    };
-  }
-};
 exports.Linearization = Linearization;

+ 4 - 2
lib/core/pattern.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -33,6 +33,8 @@ var _colorspace = require("./colorspace");
 
 var _primitives = require("./primitives");
 
+var _core_utils = require("./core_utils");
+
 var ShadingType = {
   FUNCTION_BASED: 1,
   AXIAL: 2,
@@ -74,7 +76,7 @@ var Pattern = function PatternClosure() {
           throw new _util.FormatError('Unsupported ShadingType: ' + type);
       }
     } catch (ex) {
-      if (ex instanceof _util.MissingDataException) {
+      if (ex instanceof _core_utils.MissingDataException) {
         throw ex;
       }
 

+ 17 - 15
lib/core/pdf_manager.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,11 +32,13 @@ var _util = require("../shared/util");
 
 var _chunked_stream = require("./chunked_stream");
 
+var _core_utils = require("./core_utils");
+
 var _document = require("./document");
 
 var _stream = require("./stream");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
@@ -44,12 +46,12 @@ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) ===
 
 function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
 
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
 function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
 
 function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
 
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
 
 function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
@@ -111,8 +113,8 @@ function () {
     value: function () {
       var _ensure = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee(obj, prop, args) {
-        return _regenerator.default.wrap(function _callee$(_context) {
+      _regenerator["default"].mark(function _callee(obj, prop, args) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -123,7 +125,7 @@ function () {
                 return _context.stop();
             }
           }
-        }, _callee, this);
+        }, _callee);
       }));
 
       function ensure(_x, _x2, _x3) {
@@ -205,7 +207,7 @@ function (_BasePdfManager) {
     _this._docBaseUrl = docBaseUrl;
     _this.evaluatorOptions = evaluatorOptions;
     var stream = new _stream.Stream(data);
-    _this.pdfDocument = new _document.PDFDocument(_assertThisInitialized(_assertThisInitialized(_this)), stream);
+    _this.pdfDocument = new _document.PDFDocument(_assertThisInitialized(_this), stream);
     _this._loadedStreamPromise = Promise.resolve(stream);
     return _this;
   }
@@ -215,9 +217,9 @@ function (_BasePdfManager) {
     value: function () {
       var _ensure2 = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee2(obj, prop, args) {
+      _regenerator["default"].mark(function _callee2(obj, prop, args) {
         var value;
-        return _regenerator.default.wrap(function _callee2$(_context2) {
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
           while (1) {
             switch (_context2.prev = _context2.next) {
               case 0:
@@ -238,7 +240,7 @@ function (_BasePdfManager) {
                 return _context2.stop();
             }
           }
-        }, _callee2, this);
+        }, _callee2);
       }));
 
       function ensure(_x4, _x5, _x6) {
@@ -292,7 +294,7 @@ function (_BasePdfManager2) {
       disableAutoFetch: args.disableAutoFetch,
       rangeChunkSize: args.rangeChunkSize
     });
-    _this2.pdfDocument = new _document.PDFDocument(_assertThisInitialized(_assertThisInitialized(_this2)), _this2.streamManager.getStream());
+    _this2.pdfDocument = new _document.PDFDocument(_assertThisInitialized(_this2), _this2.streamManager.getStream());
     return _this2;
   }
 
@@ -301,9 +303,9 @@ function (_BasePdfManager2) {
     value: function () {
       var _ensure3 = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee3(obj, prop, args) {
+      _regenerator["default"].mark(function _callee3(obj, prop, args) {
         var value;
-        return _regenerator.default.wrap(function _callee3$(_context3) {
+        return _regenerator["default"].wrap(function _callee3$(_context3) {
           while (1) {
             switch (_context3.prev = _context3.next) {
               case 0:
@@ -324,7 +326,7 @@ function (_BasePdfManager2) {
                 _context3.prev = 7;
                 _context3.t0 = _context3["catch"](0);
 
-                if (_context3.t0 instanceof _util.MissingDataException) {
+                if (_context3.t0 instanceof _core_utils.MissingDataException) {
                   _context3.next = 11;
                   break;
                 }

+ 40 - 6
lib/core/primitives.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
+exports.clearPrimitiveCaches = clearPrimitiveCaches;
 exports.isEOF = isEOF;
 exports.isCmd = isCmd;
 exports.isDict = isDict;
@@ -33,42 +34,54 @@ exports.isRefsEqual = isRefsEqual;
 exports.isStream = isStream;
 exports.RefSetCache = exports.RefSet = exports.Ref = exports.Name = exports.Dict = exports.Cmd = exports.EOF = void 0;
 
+var _util = require("../shared/util");
+
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
 var EOF = {};
 exports.EOF = EOF;
 
 var Name = function NameClosure() {
+  var nameCache = Object.create(null);
+
   function Name(name) {
     this.name = name;
   }
 
   Name.prototype = {};
-  var nameCache = Object.create(null);
 
   Name.get = function Name_get(name) {
     var nameValue = nameCache[name];
     return nameValue ? nameValue : nameCache[name] = new Name(name);
   };
 
+  Name._clearCache = function () {
+    nameCache = Object.create(null);
+  };
+
   return Name;
 }();
 
 exports.Name = Name;
 
 var Cmd = function CmdClosure() {
+  var cmdCache = Object.create(null);
+
   function Cmd(cmd) {
     this.cmd = cmd;
   }
 
   Cmd.prototype = {};
-  var cmdCache = Object.create(null);
 
   Cmd.get = function Cmd_get(cmd) {
     var cmdValue = cmdCache[cmd];
     return cmdValue ? cmdValue : cmdCache[cmd] = new Cmd(cmd);
   };
 
+  Cmd._clearCache = function () {
+    cmdCache = Object.create(null);
+  };
+
   return Cmd;
 }();
 
@@ -205,6 +218,8 @@ var Dict = function DictClosure() {
 exports.Dict = Dict;
 
 var Ref = function RefClosure() {
+  var refCache = Object.create(null);
+
   function Ref(num, gen) {
     this.num = num;
     this.gen = gen;
@@ -212,13 +227,24 @@ var Ref = function RefClosure() {
 
   Ref.prototype = {
     toString: function Ref_toString() {
-      if (this.gen !== 0) {
-        return "".concat(this.num, "R").concat(this.gen);
+      if (this.gen === 0) {
+        return "".concat(this.num, "R");
       }
 
-      return "".concat(this.num, "R");
+      return "".concat(this.num, "R").concat(this.gen);
     }
   };
+
+  Ref.get = function (num, gen) {
+    var key = gen === 0 ? "".concat(num, "R") : "".concat(num, "R").concat(gen);
+    var refValue = refCache[key];
+    return refValue ? refValue : refCache[key] = new Ref(num, gen);
+  };
+
+  Ref._clearCache = function () {
+    refCache = Object.create(null);
+  };
+
   return Ref;
 }();
 
@@ -303,4 +329,12 @@ function isRefsEqual(v1, v2) {
 
 function isStream(v) {
   return _typeof(v) === 'object' && v !== null && v.getBytes !== undefined;
+}
+
+function clearPrimitiveCaches() {
+  Cmd._clearCache();
+
+  Name._clearCache();
+
+  Ref._clearCache();
 }

+ 1 - 1
lib/core/ps_parser.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 9 - 9
lib/core/standard_fonts.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -26,9 +26,9 @@ Object.defineProperty(exports, "__esModule", {
 });
 exports.getSupplementalGlyphMapForCalibri = exports.getSupplementalGlyphMapForArialBlack = exports.getGlyphMapForStandardFonts = exports.getSymbolsFonts = exports.getSerifFonts = exports.getNonStdFontMap = exports.getStdFontMap = void 0;
 
-var _util = require("../shared/util");
+var _core_utils = require("./core_utils");
 
-var getStdFontMap = (0, _util.getLookupTableFactory)(function (t) {
+var getStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
   t['ArialNarrow'] = 'Helvetica';
   t['ArialNarrow-Bold'] = 'Helvetica-Bold';
   t['ArialNarrow-BoldItalic'] = 'Helvetica-BoldOblique';
@@ -87,7 +87,7 @@ var getStdFontMap = (0, _util.getLookupTableFactory)(function (t) {
   t['TimesNewRomanPSMT-Italic'] = 'Times-Italic';
 });
 exports.getStdFontMap = getStdFontMap;
-var getNonStdFontMap = (0, _util.getLookupTableFactory)(function (t) {
+var getNonStdFontMap = (0, _core_utils.getLookupTableFactory)(function (t) {
   t['Calibri'] = 'Helvetica';
   t['Calibri-Bold'] = 'Helvetica-Bold';
   t['Calibri-BoldItalic'] = 'Helvetica-BoldOblique';
@@ -125,7 +125,7 @@ var getNonStdFontMap = (0, _util.getLookupTableFactory)(function (t) {
   t['Wingdings'] = 'ZapfDingbats';
 });
 exports.getNonStdFontMap = getNonStdFontMap;
-var getSerifFonts = (0, _util.getLookupTableFactory)(function (t) {
+var getSerifFonts = (0, _core_utils.getLookupTableFactory)(function (t) {
   t['Adobe Jenson'] = true;
   t['Adobe Text'] = true;
   t['Albertus'] = true;
@@ -261,13 +261,13 @@ var getSerifFonts = (0, _util.getLookupTableFactory)(function (t) {
   t['XITS'] = true;
 });
 exports.getSerifFonts = getSerifFonts;
-var getSymbolsFonts = (0, _util.getLookupTableFactory)(function (t) {
+var getSymbolsFonts = (0, _core_utils.getLookupTableFactory)(function (t) {
   t['Dingbats'] = true;
   t['Symbol'] = true;
   t['ZapfDingbats'] = true;
 });
 exports.getSymbolsFonts = getSymbolsFonts;
-var getGlyphMapForStandardFonts = (0, _util.getLookupTableFactory)(function (t) {
+var getGlyphMapForStandardFonts = (0, _core_utils.getLookupTableFactory)(function (t) {
   t[2] = 10;
   t[3] = 32;
   t[4] = 33;
@@ -663,13 +663,13 @@ var getGlyphMapForStandardFonts = (0, _util.getLookupTableFactory)(function (t)
   t[3416] = 8377;
 });
 exports.getGlyphMapForStandardFonts = getGlyphMapForStandardFonts;
-var getSupplementalGlyphMapForArialBlack = (0, _util.getLookupTableFactory)(function (t) {
+var getSupplementalGlyphMapForArialBlack = (0, _core_utils.getLookupTableFactory)(function (t) {
   t[227] = 322;
   t[264] = 261;
   t[291] = 346;
 });
 exports.getSupplementalGlyphMapForArialBlack = getSupplementalGlyphMapForArialBlack;
-var getSupplementalGlyphMapForCalibri = (0, _util.getLookupTableFactory)(function (t) {
+var getSupplementalGlyphMapForCalibri = (0, _core_utils.getLookupTableFactory)(function (t) {
   t[1] = 32;
   t[4] = 65;
   t[17] = 66;

+ 1 - 1
lib/core/stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/core/type1_parser.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 2 - 2
lib/core/unicode.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@
  */
 "use strict";
 
-var getLookupTableFactory = require('../shared/util').getLookupTableFactory;
+var getLookupTableFactory = require('./core_utils').getLookupTableFactory;
 
 var getSpecialPUASymbols = getLookupTableFactory(function (t) {
   t[63721] = 0x00A9;

+ 54 - 171
lib/core/worker.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -30,15 +30,19 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"))
 
 var _util = require("../shared/util");
 
+var _primitives = require("./primitives");
+
 var _pdf_manager = require("./pdf_manager");
 
 var _is_node = _interopRequireDefault(require("../shared/is_node"));
 
 var _message_handler = require("../shared/message_handler");
 
-var _primitives = require("./primitives");
+var _worker_stream = require("./worker_stream");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+var _core_utils = require("./core_utils");
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
@@ -82,141 +86,6 @@ var WorkerTask = function WorkerTaskClosure() {
 }();
 
 exports.WorkerTask = WorkerTask;
-
-var PDFWorkerStream = function PDFWorkerStreamClosure() {
-  function PDFWorkerStream(msgHandler) {
-    this._msgHandler = msgHandler;
-    this._contentLength = null;
-    this._fullRequestReader = null;
-    this._rangeRequestReaders = [];
-  }
-
-  PDFWorkerStream.prototype = {
-    getFullReader: function getFullReader() {
-      (0, _util.assert)(!this._fullRequestReader);
-      this._fullRequestReader = new PDFWorkerStreamReader(this._msgHandler);
-      return this._fullRequestReader;
-    },
-    getRangeReader: function getRangeReader(begin, end) {
-      var reader = new PDFWorkerStreamRangeReader(begin, end, this._msgHandler);
-
-      this._rangeRequestReaders.push(reader);
-
-      return reader;
-    },
-    cancelAllRequests: function cancelAllRequests(reason) {
-      if (this._fullRequestReader) {
-        this._fullRequestReader.cancel(reason);
-      }
-
-      var readers = this._rangeRequestReaders.slice(0);
-
-      readers.forEach(function (reader) {
-        reader.cancel(reason);
-      });
-    }
-  };
-
-  function PDFWorkerStreamReader(msgHandler) {
-    var _this = this;
-
-    this._msgHandler = msgHandler;
-    this._contentLength = null;
-    this._isRangeSupported = false;
-    this._isStreamingSupported = false;
-
-    var readableStream = this._msgHandler.sendWithStream('GetReader');
-
-    this._reader = readableStream.getReader();
-    this._headersReady = this._msgHandler.sendWithPromise('ReaderHeadersReady').then(function (data) {
-      _this._isStreamingSupported = data.isStreamingSupported;
-      _this._isRangeSupported = data.isRangeSupported;
-      _this._contentLength = data.contentLength;
-    });
-  }
-
-  PDFWorkerStreamReader.prototype = {
-    get headersReady() {
-      return this._headersReady;
-    },
-
-    get contentLength() {
-      return this._contentLength;
-    },
-
-    get isStreamingSupported() {
-      return this._isStreamingSupported;
-    },
-
-    get isRangeSupported() {
-      return this._isRangeSupported;
-    },
-
-    read: function read() {
-      return this._reader.read().then(function (_ref) {
-        var value = _ref.value,
-            done = _ref.done;
-
-        if (done) {
-          return {
-            value: undefined,
-            done: true
-          };
-        }
-
-        return {
-          value: value.buffer,
-          done: false
-        };
-      });
-    },
-    cancel: function cancel(reason) {
-      this._reader.cancel(reason);
-    }
-  };
-
-  function PDFWorkerStreamRangeReader(begin, end, msgHandler) {
-    this._msgHandler = msgHandler;
-    this.onProgress = null;
-
-    var readableStream = this._msgHandler.sendWithStream('GetRangeReader', {
-      begin: begin,
-      end: end
-    });
-
-    this._reader = readableStream.getReader();
-  }
-
-  PDFWorkerStreamRangeReader.prototype = {
-    get isStreamingSupported() {
-      return false;
-    },
-
-    read: function read() {
-      return this._reader.read().then(function (_ref2) {
-        var value = _ref2.value,
-            done = _ref2.done;
-
-        if (done) {
-          return {
-            value: undefined,
-            done: true
-          };
-        }
-
-        return {
-          value: value.buffer,
-          done: false
-        };
-      });
-    },
-    cancel: function cancel(reason) {
-      this._reader.cancel(reason);
-    }
-  };
-  return PDFWorkerStream;
-}();
-
 var WorkerMessageHandler = {
   setup: function setup(handler, port) {
     var testMessageProcessed = false;
@@ -265,8 +134,9 @@ var WorkerMessageHandler = {
     var terminated = false;
     var cancelXHRs = null;
     var WorkerTasks = [];
+    var verbosity = (0, _util.getVerbosityLevel)();
     var apiVersion = docParams.apiVersion;
-    var workerVersion = '2.1.266';
+    var workerVersion = '2.2.228';
 
     if (apiVersion !== workerVersion) {
       throw new Error("The API version \"".concat(apiVersion, "\" does not match ") + "the Worker version \"".concat(workerVersion, "\"."));
@@ -301,10 +171,10 @@ var WorkerMessageHandler = {
     function _loadDocument() {
       _loadDocument = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee(recoveryMode) {
-        var _ref6, _ref7, numPages, fingerprint;
+      _regenerator["default"].mark(function _callee(recoveryMode) {
+        var _ref4, _ref5, numPages, fingerprint;
 
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -333,10 +203,10 @@ var WorkerMessageHandler = {
                 return Promise.all([pdfManager.ensureDoc('numPages'), pdfManager.ensureDoc('fingerprint')]);
 
               case 11:
-                _ref6 = _context.sent;
-                _ref7 = _slicedToArray(_ref6, 2);
-                numPages = _ref7[0];
-                fingerprint = _ref7[1];
+                _ref4 = _context.sent;
+                _ref5 = _slicedToArray(_ref4, 2);
+                numPages = _ref5[0];
+                fingerprint = _ref5[1];
                 return _context.abrupt("return", {
                   numPages: numPages,
                   fingerprint: fingerprint
@@ -347,7 +217,7 @@ var WorkerMessageHandler = {
                 return _context.stop();
             }
           }
-        }, _callee, this);
+        }, _callee);
       }));
       return _loadDocument.apply(this, arguments);
     }
@@ -372,7 +242,7 @@ var WorkerMessageHandler = {
           cachedChunks = [];
 
       try {
-        pdfStream = new PDFWorkerStream(handler);
+        pdfStream = new _worker_stream.PDFWorkerStream(handler);
       } catch (ex) {
         pdfManagerCapability.reject(ex);
         return pdfManagerCapability.promise;
@@ -400,7 +270,7 @@ var WorkerMessageHandler = {
         cachedChunks = [];
         pdfManagerCapability.resolve(pdfManager);
         cancelXHRs = null;
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         pdfManagerCapability.reject(reason);
         cancelXHRs = null;
       });
@@ -461,7 +331,7 @@ var WorkerMessageHandler = {
 
         fullRequest.read().then(readChunk, reject);
       });
-      readPromise.catch(function (e) {
+      readPromise["catch"](function (e) {
         pdfManagerCapability.reject(e);
         cancelXHRs = null;
       });
@@ -491,7 +361,7 @@ var WorkerMessageHandler = {
             finishWorkerTask(task);
             pdfManager.updatePassword(data.password);
             pdfManagerReady();
-          }).catch(function (boundException) {
+          })["catch"](function (boundException) {
             finishWorkerTask(task);
             handler.send('PasswordException', boundException);
           }.bind(null, e));
@@ -511,7 +381,7 @@ var WorkerMessageHandler = {
         loadDocument(false).then(onSuccess, function loadFailure(ex) {
           ensureNotTerminated();
 
-          if (!(ex instanceof _util.XRefParseException)) {
+          if (!(ex instanceof _core_utils.XRefParseException)) {
             onFailure(ex);
             return;
           }
@@ -550,12 +420,12 @@ var WorkerMessageHandler = {
 
     handler.on('GetPage', function wphSetupGetPage(data) {
       return pdfManager.getPage(data.pageIndex).then(function (page) {
-        return Promise.all([pdfManager.ensure(page, 'rotate'), pdfManager.ensure(page, 'ref'), pdfManager.ensure(page, 'userUnit'), pdfManager.ensure(page, 'view')]).then(function (_ref3) {
-          var _ref4 = _slicedToArray(_ref3, 4),
-              rotate = _ref4[0],
-              ref = _ref4[1],
-              userUnit = _ref4[2],
-              view = _ref4[3];
+        return Promise.all([pdfManager.ensure(page, 'rotate'), pdfManager.ensure(page, 'ref'), pdfManager.ensure(page, 'userUnit'), pdfManager.ensure(page, 'view')]).then(function (_ref) {
+          var _ref2 = _slicedToArray(_ref, 4),
+              rotate = _ref2[0],
+              ref = _ref2[1],
+              userUnit = _ref2[2],
+              view = _ref2[3];
 
           return {
             rotate: rotate,
@@ -567,7 +437,8 @@ var WorkerMessageHandler = {
       });
     });
     handler.on('GetPageIndex', function wphSetupGetPageIndex(data) {
-      var ref = new _primitives.Ref(data.ref.num, data.ref.gen);
+      var ref = _primitives.Ref.get(data.ref.num, data.ref.gen);
+
       var catalog = pdfManager.pdfDocument.catalog;
       return catalog.getPageIndex(ref);
     });
@@ -580,10 +451,16 @@ var WorkerMessageHandler = {
     handler.on('GetPageLabels', function wphSetupGetPageLabels(data) {
       return pdfManager.ensureCatalog('pageLabels');
     });
+    handler.on('GetPageLayout', function wphSetupGetPageLayout(data) {
+      return pdfManager.ensureCatalog('pageLayout');
+    });
     handler.on('GetPageMode', function wphSetupGetPageMode(data) {
       return pdfManager.ensureCatalog('pageMode');
     });
-    handler.on('getOpenActionDestination', function (data) {
+    handler.on('GetViewerPreferences', function (data) {
+      return pdfManager.ensureCatalog('viewerPreferences');
+    });
+    handler.on('GetOpenActionDestination', function (data) {
       return pdfManager.ensureCatalog('openActionDestination');
     });
     handler.on('GetAttachments', function wphSetupGetAttachments(data) {
@@ -610,9 +487,9 @@ var WorkerMessageHandler = {
     handler.on('GetStats', function wphSetupGetStats(data) {
       return pdfManager.pdfDocument.xref.stats;
     });
-    handler.on('GetAnnotations', function (_ref5) {
-      var pageIndex = _ref5.pageIndex,
-          intent = _ref5.intent;
+    handler.on('GetAnnotations', function (_ref3) {
+      var pageIndex = _ref3.pageIndex,
+          intent = _ref3.intent;
       return pdfManager.getPage(pageIndex).then(function (page) {
         return page.getAnnotationsData(intent);
       });
@@ -622,8 +499,7 @@ var WorkerMessageHandler = {
       pdfManager.getPage(pageIndex).then(function (page) {
         var task = new WorkerTask('RenderPageRequest: page ' + pageIndex);
         startWorkerTask(task);
-        var pageNum = pageIndex + 1;
-        var start = Date.now();
+        var start = verbosity >= _util.VerbosityLevel.INFOS ? Date.now() : 0;
         page.getOperatorList({
           handler: handler,
           task: task,
@@ -631,7 +507,10 @@ var WorkerMessageHandler = {
           renderInteractiveForms: data.renderInteractiveForms
         }).then(function (operatorList) {
           finishWorkerTask(task);
-          (0, _util.info)('page=' + pageNum + ' - getOperatorList: time=' + (Date.now() - start) + 'ms, len=' + operatorList.totalLength);
+
+          if (start) {
+            (0, _util.info)("page=".concat(pageIndex + 1, " - getOperatorList: time=") + "".concat(Date.now() - start, "ms, len=").concat(operatorList.totalLength));
+          }
         }, function (e) {
           finishWorkerTask(task);
 
@@ -663,7 +542,7 @@ var WorkerMessageHandler = {
           }
 
           handler.send('PageError', {
-            pageNum: pageNum,
+            pageIndex: pageIndex,
             error: wrappedException,
             intent: data.intent
           });
@@ -680,8 +559,7 @@ var WorkerMessageHandler = {
       pdfManager.getPage(pageIndex).then(function (page) {
         var task = new WorkerTask('GetTextContent: page ' + pageIndex);
         startWorkerTask(task);
-        var pageNum = pageIndex + 1;
-        var start = Date.now();
+        var start = verbosity >= _util.VerbosityLevel.INFOS ? Date.now() : 0;
         page.extractTextContent({
           handler: handler,
           task: task,
@@ -690,7 +568,11 @@ var WorkerMessageHandler = {
           combineTextItems: data.combineTextItems
         }).then(function () {
           finishWorkerTask(task);
-          (0, _util.info)('text indexing: page=' + pageNum + ' - time=' + (Date.now() - start) + 'ms');
+
+          if (start) {
+            (0, _util.info)("page=".concat(pageIndex + 1, " - getTextContent: time=") + "".concat(Date.now() - start, "ms"));
+          }
+
           sink.close();
         }, function (reason) {
           finishWorkerTask(task);
@@ -722,6 +604,7 @@ var WorkerMessageHandler = {
         cancelXHRs();
       }
 
+      (0, _primitives.clearPrimitiveCaches)();
       var waitOn = [];
       WorkerTasks.forEach(function (task) {
         waitOn.push(task.finished);
@@ -750,6 +633,6 @@ function isMessagePort(maybePort) {
   return typeof maybePort.postMessage === 'function' && 'onmessage' in maybePort;
 }
 
-if (typeof window === 'undefined' && !(0, _is_node.default)() && typeof self !== 'undefined' && isMessagePort(self)) {
+if (typeof window === 'undefined' && !(0, _is_node["default"])() && typeof self !== 'undefined' && isMessagePort(self)) {
   WorkerMessageHandler.initializeFromPort(self);
 }

+ 277 - 0
lib/core/worker_stream.js

@@ -0,0 +1,277 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+  value: true
+});
+exports.PDFWorkerStream = void 0;
+
+var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
+
+var _util = require("../shared/util");
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var PDFWorkerStream =
+/*#__PURE__*/
+function () {
+  function PDFWorkerStream(msgHandler) {
+    _classCallCheck(this, PDFWorkerStream);
+
+    this._msgHandler = msgHandler;
+    this._contentLength = null;
+    this._fullRequestReader = null;
+    this._rangeRequestReaders = [];
+  }
+
+  _createClass(PDFWorkerStream, [{
+    key: "getFullReader",
+    value: function getFullReader() {
+      (0, _util.assert)(!this._fullRequestReader);
+      this._fullRequestReader = new PDFWorkerStreamReader(this._msgHandler);
+      return this._fullRequestReader;
+    }
+  }, {
+    key: "getRangeReader",
+    value: function getRangeReader(begin, end) {
+      var reader = new PDFWorkerStreamRangeReader(begin, end, this._msgHandler);
+
+      this._rangeRequestReaders.push(reader);
+
+      return reader;
+    }
+  }, {
+    key: "cancelAllRequests",
+    value: function cancelAllRequests(reason) {
+      if (this._fullRequestReader) {
+        this._fullRequestReader.cancel(reason);
+      }
+
+      var readers = this._rangeRequestReaders.slice(0);
+
+      readers.forEach(function (reader) {
+        reader.cancel(reason);
+      });
+    }
+  }]);
+
+  return PDFWorkerStream;
+}();
+
+exports.PDFWorkerStream = PDFWorkerStream;
+
+var PDFWorkerStreamReader =
+/*#__PURE__*/
+function () {
+  function PDFWorkerStreamReader(msgHandler) {
+    var _this = this;
+
+    _classCallCheck(this, PDFWorkerStreamReader);
+
+    this._msgHandler = msgHandler;
+    this.onProgress = null;
+    this._contentLength = null;
+    this._isRangeSupported = false;
+    this._isStreamingSupported = false;
+
+    var readableStream = this._msgHandler.sendWithStream('GetReader');
+
+    this._reader = readableStream.getReader();
+    this._headersReady = this._msgHandler.sendWithPromise('ReaderHeadersReady').then(function (data) {
+      _this._isStreamingSupported = data.isStreamingSupported;
+      _this._isRangeSupported = data.isRangeSupported;
+      _this._contentLength = data.contentLength;
+    });
+  }
+
+  _createClass(PDFWorkerStreamReader, [{
+    key: "read",
+    value: function () {
+      var _read = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee() {
+        var _ref, value, done;
+
+        return _regenerator["default"].wrap(function _callee$(_context) {
+          while (1) {
+            switch (_context.prev = _context.next) {
+              case 0:
+                _context.next = 2;
+                return this._reader.read();
+
+              case 2:
+                _ref = _context.sent;
+                value = _ref.value;
+                done = _ref.done;
+
+                if (!done) {
+                  _context.next = 7;
+                  break;
+                }
+
+                return _context.abrupt("return", {
+                  value: undefined,
+                  done: true
+                });
+
+              case 7:
+                return _context.abrupt("return", {
+                  value: value.buffer,
+                  done: false
+                });
+
+              case 8:
+              case "end":
+                return _context.stop();
+            }
+          }
+        }, _callee, this);
+      }));
+
+      function read() {
+        return _read.apply(this, arguments);
+      }
+
+      return read;
+    }()
+  }, {
+    key: "cancel",
+    value: function cancel(reason) {
+      this._reader.cancel(reason);
+    }
+  }, {
+    key: "headersReady",
+    get: function get() {
+      return this._headersReady;
+    }
+  }, {
+    key: "contentLength",
+    get: function get() {
+      return this._contentLength;
+    }
+  }, {
+    key: "isStreamingSupported",
+    get: function get() {
+      return this._isStreamingSupported;
+    }
+  }, {
+    key: "isRangeSupported",
+    get: function get() {
+      return this._isRangeSupported;
+    }
+  }]);
+
+  return PDFWorkerStreamReader;
+}();
+
+var PDFWorkerStreamRangeReader =
+/*#__PURE__*/
+function () {
+  function PDFWorkerStreamRangeReader(begin, end, msgHandler) {
+    _classCallCheck(this, PDFWorkerStreamRangeReader);
+
+    this._msgHandler = msgHandler;
+    this.onProgress = null;
+
+    var readableStream = this._msgHandler.sendWithStream('GetRangeReader', {
+      begin: begin,
+      end: end
+    });
+
+    this._reader = readableStream.getReader();
+  }
+
+  _createClass(PDFWorkerStreamRangeReader, [{
+    key: "read",
+    value: function () {
+      var _read2 = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee2() {
+        var _ref2, value, done;
+
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
+          while (1) {
+            switch (_context2.prev = _context2.next) {
+              case 0:
+                _context2.next = 2;
+                return this._reader.read();
+
+              case 2:
+                _ref2 = _context2.sent;
+                value = _ref2.value;
+                done = _ref2.done;
+
+                if (!done) {
+                  _context2.next = 7;
+                  break;
+                }
+
+                return _context2.abrupt("return", {
+                  value: undefined,
+                  done: true
+                });
+
+              case 7:
+                return _context2.abrupt("return", {
+                  value: value.buffer,
+                  done: false
+                });
+
+              case 8:
+              case "end":
+                return _context2.stop();
+            }
+          }
+        }, _callee2, this);
+      }));
+
+      function read() {
+        return _read2.apply(this, arguments);
+      }
+
+      return read;
+    }()
+  }, {
+    key: "cancel",
+    value: function cancel(reason) {
+      this._reader.cancel(reason);
+    }
+  }, {
+    key: "isStreamingSupported",
+    get: function get() {
+      return false;
+    }
+  }]);
+
+  return PDFWorkerStreamRangeReader;
+}();

+ 112 - 33
lib/display/annotation_layer.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -26,7 +26,7 @@ Object.defineProperty(exports, "__esModule", {
 });
 exports.AnnotationLayer = void 0;
 
-var _dom_utils = require("./dom_utils");
+var _display_utils = require("./display_utils");
 
 var _util = require("../shared/util");
 
@@ -96,6 +96,9 @@ function () {
         case _util.AnnotationType.POPUP:
           return new PopupAnnotationElement(parameters);
 
+        case _util.AnnotationType.FREETEXT:
+          return new FreeTextAnnotationElement(parameters);
+
         case _util.AnnotationType.LINE:
           return new LineAnnotationElement(parameters);
 
@@ -108,6 +111,9 @@ function () {
         case _util.AnnotationType.POLYLINE:
           return new PolylineAnnotationElement(parameters);
 
+        case _util.AnnotationType.CARET:
+          return new CaretAnnotationElement(parameters);
+
         case _util.AnnotationType.INK:
           return new InkAnnotationElement(parameters);
 
@@ -252,6 +258,7 @@ function () {
         trigger: trigger,
         color: data.color,
         title: data.title,
+        modificationDate: data.modificationDate,
         contents: data.contents,
         hideWrapper: true
       });
@@ -288,9 +295,9 @@ function (_AnnotationElement) {
       var data = this.data,
           linkService = this.linkService;
       var link = document.createElement('a');
-      (0, _dom_utils.addLinkAttributes)(link, {
+      (0, _display_utils.addLinkAttributes)(link, {
         url: data.url,
-        target: data.newWindow ? _dom_utils.LinkTarget.BLANK : linkService.externalLinkTarget,
+        target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget,
         rel: linkService.externalLinkRel
       });
 
@@ -655,6 +662,7 @@ function (_AnnotationElement4) {
         trigger: parentElement,
         color: this.data.color,
         title: this.data.title,
+        modificationDate: this.data.modificationDate,
         contents: this.data.contents
       });
       var parentLeft = parseFloat(parentElement.style.left);
@@ -679,6 +687,7 @@ function () {
     this.trigger = parameters.trigger;
     this.color = parameters.color;
     this.title = parameters.title;
+    this.modificationDate = parameters.modificationDate;
     this.contents = parameters.contents;
     this.hideWrapper = parameters.hideWrapper || false;
     this.pinned = false;
@@ -703,16 +712,30 @@ function () {
         popup.style.backgroundColor = _util.Util.makeCssRgb(r | 0, g | 0, b | 0);
       }
 
-      var contents = this._formatContents(this.contents);
-
       var title = document.createElement('h1');
       title.textContent = this.title;
+      popup.appendChild(title);
+
+      var dateObject = _display_utils.PDFDateString.toDateObject(this.modificationDate);
+
+      if (dateObject) {
+        var modificationDate = document.createElement('span');
+        modificationDate.textContent = '{{date}}, {{time}}';
+        modificationDate.dataset.l10nId = 'annotation_date_string';
+        modificationDate.dataset.l10nArgs = JSON.stringify({
+          date: dateObject.toLocaleDateString(),
+          time: dateObject.toLocaleTimeString()
+        });
+        popup.appendChild(modificationDate);
+      }
+
+      var contents = this._formatContents(this.contents);
+
+      popup.appendChild(contents);
       this.trigger.addEventListener('click', this._toggle.bind(this));
       this.trigger.addEventListener('mouseover', this._show.bind(this, false));
       this.trigger.addEventListener('mouseout', this._hide.bind(this, false));
       popup.addEventListener('click', this._hide.bind(this, true));
-      popup.appendChild(title);
-      popup.appendChild(contents);
       wrapper.appendChild(popup);
       return wrapper;
     }
@@ -775,10 +798,38 @@ function () {
   return PopupElement;
 }();
 
-var LineAnnotationElement =
+var FreeTextAnnotationElement =
 /*#__PURE__*/
 function (_AnnotationElement5) {
-  _inherits(LineAnnotationElement, _AnnotationElement5);
+  _inherits(FreeTextAnnotationElement, _AnnotationElement5);
+
+  function FreeTextAnnotationElement(parameters) {
+    _classCallCheck(this, FreeTextAnnotationElement);
+
+    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+    return _possibleConstructorReturn(this, _getPrototypeOf(FreeTextAnnotationElement).call(this, parameters, isRenderable, true));
+  }
+
+  _createClass(FreeTextAnnotationElement, [{
+    key: "render",
+    value: function render() {
+      this.container.className = 'freeTextAnnotation';
+
+      if (!this.data.hasPopup) {
+        this._createPopup(this.container, null, this.data);
+      }
+
+      return this.container;
+    }
+  }]);
+
+  return FreeTextAnnotationElement;
+}(AnnotationElement);
+
+var LineAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement6) {
+  _inherits(LineAnnotationElement, _AnnotationElement6);
 
   function LineAnnotationElement(parameters) {
     _classCallCheck(this, LineAnnotationElement);
@@ -816,8 +867,8 @@ function (_AnnotationElement5) {
 
 var SquareAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement6) {
-  _inherits(SquareAnnotationElement, _AnnotationElement6);
+function (_AnnotationElement7) {
+  _inherits(SquareAnnotationElement, _AnnotationElement7);
 
   function SquareAnnotationElement(parameters) {
     _classCallCheck(this, SquareAnnotationElement);
@@ -857,8 +908,8 @@ function (_AnnotationElement6) {
 
 var CircleAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement7) {
-  _inherits(CircleAnnotationElement, _AnnotationElement7);
+function (_AnnotationElement8) {
+  _inherits(CircleAnnotationElement, _AnnotationElement8);
 
   function CircleAnnotationElement(parameters) {
     _classCallCheck(this, CircleAnnotationElement);
@@ -898,8 +949,8 @@ function (_AnnotationElement7) {
 
 var PolylineAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement8) {
-  _inherits(PolylineAnnotationElement, _AnnotationElement8);
+function (_AnnotationElement9) {
+  _inherits(PolylineAnnotationElement, _AnnotationElement9);
 
   function PolylineAnnotationElement(parameters) {
     var _this3;
@@ -968,10 +1019,38 @@ function (_PolylineAnnotationEl) {
   return PolygonAnnotationElement;
 }(PolylineAnnotationElement);
 
+var CaretAnnotationElement =
+/*#__PURE__*/
+function (_AnnotationElement10) {
+  _inherits(CaretAnnotationElement, _AnnotationElement10);
+
+  function CaretAnnotationElement(parameters) {
+    _classCallCheck(this, CaretAnnotationElement);
+
+    var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents);
+    return _possibleConstructorReturn(this, _getPrototypeOf(CaretAnnotationElement).call(this, parameters, isRenderable, true));
+  }
+
+  _createClass(CaretAnnotationElement, [{
+    key: "render",
+    value: function render() {
+      this.container.className = 'caretAnnotation';
+
+      if (!this.data.hasPopup) {
+        this._createPopup(this.container, null, this.data);
+      }
+
+      return this.container;
+    }
+  }]);
+
+  return CaretAnnotationElement;
+}(AnnotationElement);
+
 var InkAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement9) {
-  _inherits(InkAnnotationElement, _AnnotationElement9);
+function (_AnnotationElement11) {
+  _inherits(InkAnnotationElement, _AnnotationElement11);
 
   function InkAnnotationElement(parameters) {
     var _this5;
@@ -1028,8 +1107,8 @@ function (_AnnotationElement9) {
 
 var HighlightAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement10) {
-  _inherits(HighlightAnnotationElement, _AnnotationElement10);
+function (_AnnotationElement12) {
+  _inherits(HighlightAnnotationElement, _AnnotationElement12);
 
   function HighlightAnnotationElement(parameters) {
     _classCallCheck(this, HighlightAnnotationElement);
@@ -1056,8 +1135,8 @@ function (_AnnotationElement10) {
 
 var UnderlineAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement11) {
-  _inherits(UnderlineAnnotationElement, _AnnotationElement11);
+function (_AnnotationElement13) {
+  _inherits(UnderlineAnnotationElement, _AnnotationElement13);
 
   function UnderlineAnnotationElement(parameters) {
     _classCallCheck(this, UnderlineAnnotationElement);
@@ -1084,8 +1163,8 @@ function (_AnnotationElement11) {
 
 var SquigglyAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement12) {
-  _inherits(SquigglyAnnotationElement, _AnnotationElement12);
+function (_AnnotationElement14) {
+  _inherits(SquigglyAnnotationElement, _AnnotationElement14);
 
   function SquigglyAnnotationElement(parameters) {
     _classCallCheck(this, SquigglyAnnotationElement);
@@ -1112,8 +1191,8 @@ function (_AnnotationElement12) {
 
 var StrikeOutAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement13) {
-  _inherits(StrikeOutAnnotationElement, _AnnotationElement13);
+function (_AnnotationElement15) {
+  _inherits(StrikeOutAnnotationElement, _AnnotationElement15);
 
   function StrikeOutAnnotationElement(parameters) {
     _classCallCheck(this, StrikeOutAnnotationElement);
@@ -1140,8 +1219,8 @@ function (_AnnotationElement13) {
 
 var StampAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement14) {
-  _inherits(StampAnnotationElement, _AnnotationElement14);
+function (_AnnotationElement16) {
+  _inherits(StampAnnotationElement, _AnnotationElement16);
 
   function StampAnnotationElement(parameters) {
     _classCallCheck(this, StampAnnotationElement);
@@ -1168,8 +1247,8 @@ function (_AnnotationElement14) {
 
 var FileAttachmentAnnotationElement =
 /*#__PURE__*/
-function (_AnnotationElement15) {
-  _inherits(FileAttachmentAnnotationElement, _AnnotationElement15);
+function (_AnnotationElement17) {
+  _inherits(FileAttachmentAnnotationElement, _AnnotationElement17);
 
   function FileAttachmentAnnotationElement(parameters) {
     var _this6;
@@ -1180,12 +1259,12 @@ function (_AnnotationElement15) {
     var _this6$data$file = _this6.data.file,
         filename = _this6$data$file.filename,
         content = _this6$data$file.content;
-    _this6.filename = (0, _dom_utils.getFilenameFromUrl)(filename);
+    _this6.filename = (0, _display_utils.getFilenameFromUrl)(filename);
     _this6.content = content;
 
     if (_this6.linkService.eventBus) {
       _this6.linkService.eventBus.dispatch('fileattachmentannotation', {
-        source: _assertThisInitialized(_assertThisInitialized(_this6)),
+        source: _assertThisInitialized(_this6),
         id: (0, _util.stringToPDFString)(filename),
         filename: filename,
         content: content
@@ -1252,7 +1331,7 @@ function () {
           downloadManager: parameters.downloadManager,
           imageResourcesPath: parameters.imageResourcesPath || '',
           renderInteractiveForms: parameters.renderInteractiveForms || false,
-          svgFactory: new _dom_utils.DOMSVGFactory()
+          svgFactory: new _display_utils.DOMSVGFactory()
         });
 
         if (element.isRenderable) {

+ 211 - 123
lib/display/api.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"))
 
 var _util = require("../shared/util");
 
-var _dom_utils = require("./dom_utils");
+var _display_utils = require("./display_utils");
 
 var _font_loader = require("./font_loader");
 
@@ -206,7 +206,7 @@ function getDocument(src) {
   }
 
   params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE;
-  params.CMapReaderFactory = params.CMapReaderFactory || _dom_utils.DOMCMapReaderFactory;
+  params.CMapReaderFactory = params.CMapReaderFactory || _display_utils.DOMCMapReaderFactory;
   params.ignoreErrors = params.stopAtErrors !== true;
   params.pdfBug = params.pdfBug === true;
   var NativeImageDecoderValues = Object.values(_util.NativeImageDecoding);
@@ -272,6 +272,7 @@ function getDocument(src) {
         networkStream = new _transport_stream.PDFDataTransportStream({
           length: params.length,
           initialData: params.initialData,
+          progressiveDone: params.progressiveDone,
           disableRange: params.disableRange,
           disableStream: params.disableStream
         }, rangeTransport);
@@ -293,7 +294,7 @@ function getDocument(src) {
       task._transport = transport;
       messageHandler.send('Ready', null);
     });
-  }).catch(task._capability.reject);
+  })["catch"](task._capability.reject);
   return task;
 }
 
@@ -305,11 +306,12 @@ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) {
   if (pdfDataRangeTransport) {
     source.length = pdfDataRangeTransport.length;
     source.initialData = pdfDataRangeTransport.initialData;
+    source.progressiveDone = pdfDataRangeTransport.progressiveDone;
   }
 
   return worker.messageHandler.sendWithPromise('GetDocRequest', {
     docId: docId,
-    apiVersion: '2.1.266',
+    apiVersion: '2.2.228',
     source: {
       data: source.data,
       url: source.url,
@@ -374,7 +376,7 @@ var PDFDocumentLoadingTask = function PDFDocumentLoadingTaskClosure() {
     }, {
       key: "then",
       value: function then(onFulfilled, onRejected) {
-        (0, _util.deprecated)('PDFDocumentLoadingTask.then method, ' + 'use the `promise` getter instead.');
+        (0, _display_utils.deprecated)('PDFDocumentLoadingTask.then method, ' + 'use the `promise` getter instead.');
         return this.promise.then.apply(this.promise, arguments);
       }
     }, {
@@ -394,13 +396,17 @@ var PDFDataRangeTransport =
 /*#__PURE__*/
 function () {
   function PDFDataRangeTransport(length, initialData) {
+    var progressiveDone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
     _classCallCheck(this, PDFDataRangeTransport);
 
     this.length = length;
     this.initialData = initialData;
+    this.progressiveDone = progressiveDone;
     this._rangeListeners = [];
     this._progressListeners = [];
     this._progressiveReadListeners = [];
+    this._progressiveDoneListeners = [];
     this._readyCapability = (0, _util.createPromiseCapability)();
   }
 
@@ -419,6 +425,11 @@ function () {
     value: function addProgressiveReadListener(listener) {
       this._progressiveReadListeners.push(listener);
     }
+  }, {
+    key: "addProgressiveDoneListener",
+    value: function addProgressiveDoneListener(listener) {
+      this._progressiveDoneListeners.push(listener);
+    }
   }, {
     key: "onDataRange",
     value: function onDataRange(begin, chunk) {
@@ -436,8 +447,8 @@ function () {
         _iteratorError = err;
       } finally {
         try {
-          if (!_iteratorNormalCompletion && _iterator.return != null) {
-            _iterator.return();
+          if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+            _iterator["return"]();
           }
         } finally {
           if (_didIteratorError) {
@@ -448,7 +459,7 @@ function () {
     }
   }, {
     key: "onDataProgress",
-    value: function onDataProgress(loaded) {
+    value: function onDataProgress(loaded, total) {
       var _this2 = this;
 
       this._readyCapability.promise.then(function () {
@@ -459,15 +470,15 @@ function () {
         try {
           for (var _iterator2 = _this2._progressListeners[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
             var listener = _step2.value;
-            listener(loaded);
+            listener(loaded, total);
           }
         } catch (err) {
           _didIteratorError2 = true;
           _iteratorError2 = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
-              _iterator2.return();
+            if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+              _iterator2["return"]();
             }
           } finally {
             if (_didIteratorError2) {
@@ -497,8 +508,8 @@ function () {
           _iteratorError3 = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
-              _iterator3.return();
+            if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
+              _iterator3["return"]();
             }
           } finally {
             if (_didIteratorError3) {
@@ -508,6 +519,37 @@ function () {
         }
       });
     }
+  }, {
+    key: "onDataProgressiveDone",
+    value: function onDataProgressiveDone() {
+      var _this4 = this;
+
+      this._readyCapability.promise.then(function () {
+        var _iteratorNormalCompletion4 = true;
+        var _didIteratorError4 = false;
+        var _iteratorError4 = undefined;
+
+        try {
+          for (var _iterator4 = _this4._progressiveDoneListeners[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
+            var listener = _step4.value;
+            listener();
+          }
+        } catch (err) {
+          _didIteratorError4 = true;
+          _iteratorError4 = err;
+        } finally {
+          try {
+            if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
+              _iterator4["return"]();
+            }
+          } finally {
+            if (_didIteratorError4) {
+              throw _iteratorError4;
+            }
+          }
+        }
+      });
+    }
   }, {
     key: "transportReady",
     value: function transportReady() {
@@ -531,10 +573,9 @@ exports.PDFDataRangeTransport = PDFDataRangeTransport;
 var PDFDocumentProxy =
 /*#__PURE__*/
 function () {
-  function PDFDocumentProxy(pdfInfo, transport, loadingTask) {
+  function PDFDocumentProxy(pdfInfo, transport) {
     _classCallCheck(this, PDFDocumentProxy);
 
-    this.loadingTask = loadingTask;
     this._pdfInfo = pdfInfo;
     this._transport = transport;
   }
@@ -564,11 +605,21 @@ function () {
     value: function getPageLabels() {
       return this._transport.getPageLabels();
     }
+  }, {
+    key: "getPageLayout",
+    value: function getPageLayout() {
+      return this._transport.getPageLayout();
+    }
   }, {
     key: "getPageMode",
     value: function getPageMode() {
       return this._transport.getPageMode();
     }
+  }, {
+    key: "getViewerPreferences",
+    value: function getViewerPreferences() {
+      return this._transport.getViewerPreferences();
+    }
   }, {
     key: "getOpenActionDestination",
     value: function getOpenActionDestination() {
@@ -639,6 +690,11 @@ function () {
     get: function get() {
       return this._transport.loadingParams;
     }
+  }, {
+    key: "loadingTask",
+    get: function get() {
+      return this._transport.loadingTask;
+    }
   }]);
 
   return PDFDocumentProxy;
@@ -657,7 +713,7 @@ function () {
     this.pageIndex = pageIndex;
     this._pageInfo = pageInfo;
     this._transport = transport;
-    this._stats = pdfBug ? new _dom_utils.StatTimer() : _dom_utils.DummyStatTimer;
+    this._stats = pdfBug ? new _display_utils.StatTimer() : _display_utils.DummyStatTimer;
     this._pdfBug = pdfBug;
     this.commonObjs = transport.commonObjs;
     this.objs = new PDFObjects();
@@ -678,13 +734,13 @@ function () {
           dontFlip = _ref$dontFlip === void 0 ? false : _ref$dontFlip;
 
       if (arguments.length > 1 || typeof arguments[0] === 'number') {
-        (0, _util.deprecated)('getViewport is called with obsolete arguments.');
+        (0, _display_utils.deprecated)('getViewport is called with obsolete arguments.');
         scale = arguments[0];
         rotation = typeof arguments[1] === 'number' ? arguments[1] : this.rotate;
         dontFlip = typeof arguments[2] === 'boolean' ? arguments[2] : false;
       }
 
-      return new _dom_utils.PageViewport({
+      return new _display_utils.PageViewport({
         viewBox: this.view,
         scale: scale,
         rotation: rotation,
@@ -708,7 +764,7 @@ function () {
   }, {
     key: "render",
     value: function render(_ref3) {
-      var _this4 = this;
+      var _this5 = this;
 
       var canvasContext = _ref3.canvasContext,
           viewport = _ref3.viewport,
@@ -730,7 +786,7 @@ function () {
       stats.time('Overall');
       this.pendingCleanup = false;
       var renderingIntent = intent === 'print' ? 'print' : 'display';
-      var canvasFactoryInstance = canvasFactory || new _dom_utils.DOMCanvasFactory();
+      var canvasFactoryInstance = canvasFactory || new _display_utils.DOMCanvasFactory();
       var webGLContext = new _webgl.WebGLContext({
         enable: enableWebGL
       });
@@ -765,11 +821,11 @@ function () {
           intentState.renderTasks.splice(i, 1);
         }
 
-        if (_this4.cleanupAfterRender) {
-          _this4.pendingCleanup = true;
+        if (_this5.cleanupAfterRender || renderingIntent === 'print') {
+          _this5.pendingCleanup = true;
         }
 
-        _this4._tryCleanup();
+        _this5._tryCleanup();
 
         if (error) {
           internalRenderTask.capability.reject(error);
@@ -807,7 +863,7 @@ function () {
       intentState.renderTasks.push(internalRenderTask);
       var renderTask = internalRenderTask.task;
       intentState.displayReadyCapability.promise.then(function (transparency) {
-        if (_this4.pendingCleanup) {
+        if (_this5.pendingCleanup) {
           complete();
           return;
         }
@@ -815,7 +871,7 @@ function () {
         stats.time('Rendering');
         internalRenderTask.initializeGraphics(transparency);
         internalRenderTask.operatorListChanged();
-      }).catch(complete);
+      })["catch"](complete);
       return renderTask;
     }
   }, {
@@ -932,7 +988,7 @@ function () {
 
         var intentState = this.intentStates[intent];
         intentState.renderTasks.forEach(function (renderTask) {
-          var renderCompleted = renderTask.capability.promise.catch(function () {});
+          var renderCompleted = renderTask.capability.promise["catch"](function () {});
           waitOn.push(renderCompleted);
           renderTask.cancel();
         });
@@ -968,8 +1024,8 @@ function () {
       this.objs.clear();
       this.annotationsPromise = null;
 
-      if (resetStats && this._stats instanceof _dom_utils.StatTimer) {
-        this._stats = new _dom_utils.StatTimer();
+      if (resetStats && this._stats instanceof _display_utils.StatTimer) {
+        this._stats = new _display_utils.StatTimer();
       }
 
       this.pendingCleanup = false;
@@ -1033,7 +1089,7 @@ function () {
   }, {
     key: "stats",
     get: function get() {
-      return this._stats instanceof _dom_utils.StatTimer ? this._stats : null;
+      return this._stats instanceof _display_utils.StatTimer ? this._stats : null;
     }
   }]);
 
@@ -1058,7 +1114,7 @@ function () {
   _createClass(LoopbackPort, [{
     key: "postMessage",
     value: function postMessage(obj, transfers) {
-      var _this5 = this;
+      var _this6 = this;
 
       function cloneValue(value) {
         if (_typeof(value) !== 'object' || value === null) {
@@ -1123,9 +1179,9 @@ function () {
       };
 
       this._deferred.then(function () {
-        _this5._listeners.forEach(function (listener) {
+        _this6._listeners.forEach(function (listener) {
           listener.call(this, e);
-        }, _this5);
+        }, _this6);
       });
     }
   }, {
@@ -1143,7 +1199,7 @@ function () {
   }, {
     key: "terminate",
     value: function terminate() {
-      this._listeners = [];
+      this._listeners.length = 0;
     }
   }]);
 
@@ -1193,7 +1249,7 @@ var PDFWorker = function PDFWorkerClosure() {
     }
 
     var loader = fakeWorkerFilesLoader || function () {
-      return (0, _dom_utils.loadScript)(_getWorkerSrc()).then(function () {
+      return (0, _display_utils.loadScript)(_getWorkerSrc()).then(function () {
         return window.pdfjsWorker.WorkerMessageHandler;
       });
     };
@@ -1260,7 +1316,7 @@ var PDFWorker = function PDFWorkerClosure() {
     }, {
       key: "_initialize",
       value: function _initialize() {
-        var _this6 = this;
+        var _this7 = this;
 
         if (typeof Worker !== 'undefined' && !isWorkerDisabled && !getMainThreadWorkerMessageHandler()) {
           var workerSrc = _getWorkerSrc();
@@ -1278,15 +1334,15 @@ var PDFWorker = function PDFWorkerClosure() {
               messageHandler.destroy();
               worker.terminate();
 
-              if (_this6.destroyed) {
-                _this6._readyCapability.reject(new Error('Worker was destroyed'));
+              if (_this7.destroyed) {
+                _this7._readyCapability.reject(new Error('Worker was destroyed'));
               } else {
-                _this6._setupFakeWorker();
+                _this7._setupFakeWorker();
               }
             };
 
             var onWorkerError = function onWorkerError() {
-              if (!_this6._webWorker) {
+              if (!_this7._webWorker) {
                 terminateEarly();
               }
             };
@@ -1295,27 +1351,27 @@ var PDFWorker = function PDFWorkerClosure() {
             messageHandler.on('test', function (data) {
               worker.removeEventListener('error', onWorkerError);
 
-              if (_this6.destroyed) {
+              if (_this7.destroyed) {
                 terminateEarly();
                 return;
               }
 
               if (data && data.supportTypedArray) {
-                _this6._messageHandler = messageHandler;
-                _this6._port = worker;
-                _this6._webWorker = worker;
+                _this7._messageHandler = messageHandler;
+                _this7._port = worker;
+                _this7._webWorker = worker;
 
                 if (!data.supportTransfers) {
-                  _this6.postMessageTransfers = false;
+                  _this7.postMessageTransfers = false;
                 }
 
-                _this6._readyCapability.resolve();
+                _this7._readyCapability.resolve();
 
                 messageHandler.send('configure', {
-                  verbosity: _this6.verbosity
+                  verbosity: _this7.verbosity
                 });
               } else {
-                _this6._setupFakeWorker();
+                _this7._setupFakeWorker();
 
                 messageHandler.destroy();
                 worker.terminate();
@@ -1324,7 +1380,7 @@ var PDFWorker = function PDFWorkerClosure() {
             messageHandler.on('ready', function (data) {
               worker.removeEventListener('error', onWorkerError);
 
-              if (_this6.destroyed) {
+              if (_this7.destroyed) {
                 terminateEarly();
                 return;
               }
@@ -1332,12 +1388,12 @@ var PDFWorker = function PDFWorkerClosure() {
               try {
                 sendTest();
               } catch (e) {
-                _this6._setupFakeWorker();
+                _this7._setupFakeWorker();
               }
             });
 
             var sendTest = function sendTest() {
-              var testObj = new Uint8Array([_this6.postMessageTransfers ? 255 : 0]);
+              var testObj = new Uint8Array([_this7.postMessageTransfers ? 255 : 0]);
 
               try {
                 messageHandler.send('test', testObj, [testObj.buffer]);
@@ -1360,7 +1416,7 @@ var PDFWorker = function PDFWorkerClosure() {
     }, {
       key: "_setupFakeWorker",
       value: function _setupFakeWorker() {
-        var _this7 = this;
+        var _this8 = this;
 
         if (!isWorkerDisabled) {
           (0, _util.warn)('Setting up fake worker.');
@@ -1368,23 +1424,23 @@ var PDFWorker = function PDFWorkerClosure() {
         }
 
         setupFakeWorkerGlobal().then(function (WorkerMessageHandler) {
-          if (_this7.destroyed) {
-            _this7._readyCapability.reject(new Error('Worker was destroyed'));
+          if (_this8.destroyed) {
+            _this8._readyCapability.reject(new Error('Worker was destroyed'));
 
             return;
           }
 
           var port = new LoopbackPort();
-          _this7._port = port;
+          _this8._port = port;
           var id = 'fake' + nextFakeWorkerId++;
           var workerHandler = new _message_handler.MessageHandler(id + '_worker', id, port);
           WorkerMessageHandler.setup(workerHandler, port);
           var messageHandler = new _message_handler.MessageHandler(id, id + '_worker', port);
-          _this7._messageHandler = messageHandler;
+          _this8._messageHandler = messageHandler;
 
-          _this7._readyCapability.resolve();
-        }).catch(function (reason) {
-          _this7._readyCapability.reject(new Error("Setting up fake worker failed: \"".concat(reason.message, "\".")));
+          _this8._readyCapability.resolve();
+        })["catch"](function (reason) {
+          _this8._readyCapability.reject(new Error("Setting up fake worker failed: \"".concat(reason.message, "\".")));
         });
       }
     }, {
@@ -1398,7 +1454,7 @@ var PDFWorker = function PDFWorkerClosure() {
           this._webWorker = null;
         }
 
-        pdfWorkerPorts.delete(this._port);
+        pdfWorkerPorts["delete"](this._port);
         this._port = null;
 
         if (this._messageHandler) {
@@ -1483,7 +1539,7 @@ function () {
   _createClass(WorkerTransport, [{
     key: "destroy",
     value: function destroy() {
-      var _this8 = this;
+      var _this9 = this;
 
       if (this.destroyCapability) {
         return this.destroyCapability.promise;
@@ -1502,24 +1558,24 @@ function () {
           waitOn.push(page._destroy());
         }
       });
-      this.pageCache = [];
-      this.pagePromises = [];
+      this.pageCache.length = 0;
+      this.pagePromises.length = 0;
       var terminated = this.messageHandler.sendWithPromise('Terminate', null);
       waitOn.push(terminated);
       Promise.all(waitOn).then(function () {
-        _this8.fontLoader.clear();
+        _this9.fontLoader.clear();
 
-        if (_this8._networkStream) {
-          _this8._networkStream.cancelAllRequests();
+        if (_this9._networkStream) {
+          _this9._networkStream.cancelAllRequests();
         }
 
-        if (_this8.messageHandler) {
-          _this8.messageHandler.destroy();
+        if (_this9.messageHandler) {
+          _this9.messageHandler.destroy();
 
-          _this8.messageHandler = null;
+          _this9.messageHandler = null;
         }
 
-        _this8.destroyCapability.resolve();
+        _this9.destroyCapability.resolve();
       }, this.destroyCapability.reject);
       return this.destroyCapability.promise;
     }
@@ -1529,20 +1585,20 @@ function () {
       var messageHandler = this.messageHandler,
           loadingTask = this.loadingTask;
       messageHandler.on('GetReader', function (data, sink) {
-        var _this9 = this;
+        var _this10 = this;
 
         (0, _util.assert)(this._networkStream);
         this._fullReader = this._networkStream.getFullReader();
 
         this._fullReader.onProgress = function (evt) {
-          _this9._lastProgress = {
+          _this10._lastProgress = {
             loaded: evt.loaded,
             total: evt.total
           };
         };
 
         sink.onPull = function () {
-          _this9._fullReader.read().then(function (_ref7) {
+          _this10._fullReader.read().then(function (_ref7) {
             var value = _ref7.value,
                 done = _ref7.done;
 
@@ -1553,24 +1609,24 @@ function () {
 
             (0, _util.assert)((0, _util.isArrayBuffer)(value));
             sink.enqueue(new Uint8Array(value), 1, [value]);
-          }).catch(function (reason) {
+          })["catch"](function (reason) {
             sink.error(reason);
           });
         };
 
         sink.onCancel = function (reason) {
-          _this9._fullReader.cancel(reason);
+          _this10._fullReader.cancel(reason);
         };
       }, this);
       messageHandler.on('ReaderHeadersReady', function (data) {
-        var _this10 = this;
+        var _this11 = this;
 
         var headersCapability = (0, _util.createPromiseCapability)();
         var fullReader = this._fullReader;
         fullReader.headersReady.then(function () {
           if (!fullReader.isStreamingSupported || !fullReader.isRangeSupported) {
-            if (_this10._lastProgress && loadingTask.onProgress) {
-              loadingTask.onProgress(_this10._lastProgress);
+            if (_this11._lastProgress && loadingTask.onProgress) {
+              loadingTask.onProgress(_this11._lastProgress);
             }
 
             fullReader.onProgress = function (evt) {
@@ -1596,6 +1652,11 @@ function () {
 
         var rangeReader = this._networkStream.getRangeReader(data.begin, data.end);
 
+        if (!rangeReader) {
+          sink.close();
+          return;
+        }
+
         sink.onPull = function () {
           rangeReader.read().then(function (_ref8) {
             var value = _ref8.value,
@@ -1608,7 +1669,7 @@ function () {
 
             (0, _util.assert)((0, _util.isArrayBuffer)(value));
             sink.enqueue(new Uint8Array(value), 1, [value]);
-          }).catch(function (reason) {
+          })["catch"](function (reason) {
             sink.error(reason);
           });
         };
@@ -1619,19 +1680,18 @@ function () {
       }, this);
       messageHandler.on('GetDoc', function (_ref9) {
         var pdfInfo = _ref9.pdfInfo;
-        this.numPages = pdfInfo.numPages;
-        this.pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask);
+        this._numPages = pdfInfo.numPages;
 
-        loadingTask._capability.resolve(this.pdfDocument);
+        loadingTask._capability.resolve(new PDFDocumentProxy(pdfInfo, this));
       }, this);
       messageHandler.on('PasswordRequest', function (exception) {
-        var _this11 = this;
+        var _this12 = this;
 
         this._passwordCapability = (0, _util.createPromiseCapability)();
 
         if (loadingTask.onPassword) {
           var updatePassword = function updatePassword(password) {
-            _this11._passwordCapability.resolve({
+            _this12._passwordCapability.resolve({
               password: password
             });
           };
@@ -1693,7 +1753,7 @@ function () {
         page._renderPageChunk(data.operatorList, data.intent);
       }, this);
       messageHandler.on('commonobj', function (data) {
-        var _this12 = this;
+        var _this13 = this;
 
         if (this.destroyed) {
           return;
@@ -1721,10 +1781,10 @@ function () {
 
             var fontRegistry = null;
 
-            if (params.pdfBug && _global_scope.default.FontInspector && _global_scope.default.FontInspector.enabled) {
+            if (params.pdfBug && _global_scope["default"].FontInspector && _global_scope["default"].FontInspector.enabled) {
               fontRegistry = {
                 registerFont: function registerFont(font, url) {
-                  _global_scope.default['FontInspector'].fontAdded(font, url);
+                  _global_scope["default"]['FontInspector'].fontAdded(font, url);
                 }
               };
             }
@@ -1737,17 +1797,18 @@ function () {
               fontRegistry: fontRegistry
             });
             this.fontLoader.bind(font).then(function () {
-              _this12.commonObjs.resolve(id, font);
+              _this13.commonObjs.resolve(id, font);
             }, function (reason) {
               messageHandler.sendWithPromise('FontFallback', {
                 id: id
-              }).finally(function () {
-                _this12.commonObjs.resolve(id, font);
+              })["finally"](function () {
+                _this13.commonObjs.resolve(id, font);
               });
             });
             break;
 
           case 'FontPath':
+          case 'FontType3Res':
             this.commonObjs.resolve(id, exportedData);
             break;
 
@@ -1757,7 +1818,7 @@ function () {
       }, this);
       messageHandler.on('obj', function (data) {
         if (this.destroyed) {
-          return;
+          return undefined;
         }
 
         var _data2 = _slicedToArray(data, 4),
@@ -1769,7 +1830,7 @@ function () {
         var pageProxy = this.pageCache[pageIndex];
 
         if (pageProxy.objs.has(id)) {
-          return;
+          return undefined;
         }
 
         switch (type) {
@@ -1783,6 +1844,7 @@ function () {
 
               img.onerror = function () {
                 reject(new Error('Error during JPEG image loading'));
+                (0, _display_utils.releaseImageResources)(img);
               };
 
               img.src = imageData;
@@ -1803,6 +1865,8 @@ function () {
           default:
             throw new Error("Got unknown object type ".concat(type));
         }
+
+        return undefined;
       }, this);
       messageHandler.on('DocProgress', function (data) {
         if (this.destroyed) {
@@ -1821,11 +1885,11 @@ function () {
           return;
         }
 
-        var page = this.pageCache[data.pageNum - 1];
+        var page = this.pageCache[data.pageIndex];
         var intentState = page.intentStates[data.intent];
 
         if (intentState.displayReadyCapability) {
-          intentState.displayReadyCapability.reject(data.error);
+          intentState.displayReadyCapability.reject(new Error(data.error));
         } else {
           throw new Error(data.error);
         }
@@ -1860,8 +1924,8 @@ function () {
           var img = new Image();
 
           img.onload = function () {
-            var width = img.width;
-            var height = img.height;
+            var width = img.width,
+                height = img.height;
             var size = width * height;
             var rgbaLength = size * 4;
             var buf = new Uint8ClampedArray(size * components);
@@ -1889,10 +1953,16 @@ function () {
               width: width,
               height: height
             });
+            (0, _display_utils.releaseImageResources)(img);
+            tmpCanvas.width = 0;
+            tmpCanvas.height = 0;
+            tmpCanvas = null;
+            tmpCtx = null;
           };
 
           img.onerror = function () {
             reject(new Error('JpegDecode failed to load image'));
+            (0, _display_utils.releaseImageResources)(img);
           };
 
           img.src = imageUrl;
@@ -1929,9 +1999,9 @@ function () {
   }, {
     key: "getPage",
     value: function getPage(pageNumber) {
-      var _this13 = this;
+      var _this14 = this;
 
-      if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) {
+      if (!Number.isInteger(pageNumber) || pageNumber <= 0 || pageNumber > this._numPages) {
         return Promise.reject(new Error('Invalid page request'));
       }
 
@@ -1944,12 +2014,12 @@ function () {
       var promise = this.messageHandler.sendWithPromise('GetPage', {
         pageIndex: pageIndex
       }).then(function (pageInfo) {
-        if (_this13.destroyed) {
+        if (_this14.destroyed) {
           throw new Error('Transport destroyed');
         }
 
-        var page = new PDFPageProxy(pageIndex, pageInfo, _this13, _this13._params.pdfBug);
-        _this13.pageCache[pageIndex] = page;
+        var page = new PDFPageProxy(pageIndex, pageInfo, _this14, _this14._params.pdfBug);
+        _this14.pageCache[pageIndex] = page;
         return page;
       });
       this.pagePromises[pageIndex] = promise;
@@ -1960,7 +2030,7 @@ function () {
     value: function getPageIndex(ref) {
       return this.messageHandler.sendWithPromise('GetPageIndex', {
         ref: ref
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         return Promise.reject(new Error(reason));
       });
     }
@@ -1993,15 +2063,25 @@ function () {
     value: function getPageLabels() {
       return this.messageHandler.sendWithPromise('GetPageLabels', null);
     }
+  }, {
+    key: "getPageLayout",
+    value: function getPageLayout() {
+      return this.messageHandler.sendWithPromise('GetPageLayout', null);
+    }
   }, {
     key: "getPageMode",
     value: function getPageMode() {
       return this.messageHandler.sendWithPromise('GetPageMode', null);
     }
+  }, {
+    key: "getViewerPreferences",
+    value: function getViewerPreferences() {
+      return this.messageHandler.sendWithPromise('GetViewerPreferences', null);
+    }
   }, {
     key: "getOpenActionDestination",
     value: function getOpenActionDestination() {
-      return this.messageHandler.sendWithPromise('getOpenActionDestination', null);
+      return this.messageHandler.sendWithPromise('GetOpenActionDestination', null);
     }
   }, {
     key: "getAttachments",
@@ -2026,13 +2106,13 @@ function () {
   }, {
     key: "getMetadata",
     value: function getMetadata() {
-      var _this14 = this;
+      var _this15 = this;
 
       return this.messageHandler.sendWithPromise('GetMetadata', null).then(function (results) {
         return {
           info: results[0],
           metadata: results[1] ? new _metadata.Metadata(results[1]) : null,
-          contentDispositionFilename: _this14._fullReader ? _this14._fullReader.filename : null
+          contentDispositionFilename: _this15._fullReader ? _this15._fullReader.filename : null
         };
       });
     }
@@ -2044,20 +2124,20 @@ function () {
   }, {
     key: "startCleanup",
     value: function startCleanup() {
-      var _this15 = this;
+      var _this16 = this;
 
       this.messageHandler.sendWithPromise('Cleanup', null).then(function () {
-        for (var i = 0, ii = _this15.pageCache.length; i < ii; i++) {
-          var page = _this15.pageCache[i];
+        for (var i = 0, ii = _this16.pageCache.length; i < ii; i++) {
+          var page = _this16.pageCache[i];
 
           if (page) {
             page.cleanup();
           }
         }
 
-        _this15.commonObjs.clear();
+        _this16.commonObjs.clear();
 
-        _this15.fontLoader.clear();
+        _this16.fontLoader.clear();
       });
     }
   }, {
@@ -2135,6 +2215,14 @@ function () {
   }, {
     key: "clear",
     value: function clear() {
+      for (var objId in this._objs) {
+        var data = this._objs[objId].data;
+
+        if (typeof Image !== 'undefined' && data instanceof Image) {
+          (0, _display_utils.releaseImageResources)(data);
+        }
+      }
+
       this._objs = Object.create(null);
     }
   }]);
@@ -2160,7 +2248,7 @@ function () {
   }, {
     key: "then",
     value: function then(onFulfilled, onRejected) {
-      (0, _util.deprecated)('RenderTask.then method, use the `promise` getter instead.');
+      (0, _display_utils.deprecated)('RenderTask.then method, use the `promise` getter instead.');
       return this.promise.then.apply(this.promise, arguments);
     }
   }, {
@@ -2235,8 +2323,8 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
           canvasInRendering.add(this._canvas);
         }
 
-        if (this._pdfBug && _global_scope.default.StepperManager && _global_scope.default.StepperManager.enabled) {
-          this.stepper = _global_scope.default.StepperManager.create(this.pageNumber - 1);
+        if (this._pdfBug && _global_scope["default"].StepperManager && _global_scope["default"].StepperManager.enabled) {
+          this.stepper = _global_scope["default"].StepperManager.create(this.pageNumber - 1);
           this.stepper.init(this.operatorList);
           this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint();
         }
@@ -2273,10 +2361,10 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
         }
 
         if (this._canvas) {
-          canvasInRendering.delete(this._canvas);
+          canvasInRendering["delete"](this._canvas);
         }
 
-        this.callback(error || new _dom_utils.RenderingCancelledException("Rendering cancelled, page ".concat(this.pageNumber), 'canvas'));
+        this.callback(error || new _display_utils.RenderingCancelledException("Rendering cancelled, page ".concat(this.pageNumber), 'canvas'));
       }
     }, {
       key: "operatorListChanged",
@@ -2317,14 +2405,14 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
     }, {
       key: "_scheduleNext",
       value: function _scheduleNext() {
-        var _this16 = this;
+        var _this17 = this;
 
         if (this._useRequestAnimationFrame) {
           window.requestAnimationFrame(function () {
-            _this16._nextBound().catch(_this16.cancel.bind(_this16));
+            _this17._nextBound()["catch"](_this17.cancel.bind(_this17));
           });
         } else {
-          Promise.resolve().then(this._nextBound).catch(this.cancel.bind(this));
+          Promise.resolve().then(this._nextBound)["catch"](this.cancel.bind(this));
         }
       }
     }, {
@@ -2332,8 +2420,8 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
       value: function () {
         var _next2 = _asyncToGenerator(
         /*#__PURE__*/
-        _regenerator.default.mark(function _callee() {
-          return _regenerator.default.wrap(function _callee$(_context) {
+        _regenerator["default"].mark(function _callee() {
+          return _regenerator["default"].wrap(function _callee$(_context) {
             while (1) {
               switch (_context.prev = _context.next) {
                 case 0:
@@ -2354,7 +2442,7 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
                       this.gfx.endDrawing();
 
                       if (this._canvas) {
-                        canvasInRendering.delete(this._canvas);
+                        canvasInRendering["delete"](this._canvas);
                       }
 
                       this.callback();
@@ -2383,7 +2471,7 @@ var InternalRenderTask = function InternalRenderTaskClosure() {
   return InternalRenderTask;
 }();
 
-var version = '2.1.266';
+var version = '2.2.228';
 exports.version = version;
-var build = '81f5835c';
+var build = 'd7afb74a';
 exports.build = build;

+ 1 - 1
lib/display/api_compatibility.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 40 - 19
lib/display/canvas.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -318,7 +318,10 @@ function compileType3Glyph(imgData) {
 
       coords.push(p % width1);
       coords.push(p / width1 | 0);
-      --count;
+
+      if (!points[p]) {
+        --count;
+      }
     } while (p0 !== p);
 
     outlines.push(coords);
@@ -762,16 +765,32 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
         if (fnId !== _util.OPS.dependency) {
           this[fnId].apply(this, argsArray[i]);
         } else {
-          var deps = argsArray[i];
-
-          for (var n = 0, nn = deps.length; n < nn; n++) {
-            var depObjId = deps[n];
-            var common = depObjId[0] === 'g' && depObjId[1] === '_';
-            var objsPool = common ? commonObjs : objs;
-
-            if (!objsPool.has(depObjId)) {
-              objsPool.get(depObjId, continueCallback);
-              return i;
+          var _iteratorNormalCompletion = true;
+          var _didIteratorError = false;
+          var _iteratorError = undefined;
+
+          try {
+            for (var _iterator = argsArray[i][Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+              var depObjId = _step.value;
+              var objsPool = depObjId.startsWith('g_') ? commonObjs : objs;
+
+              if (!objsPool.has(depObjId)) {
+                objsPool.get(depObjId, continueCallback);
+                return i;
+              }
+            }
+          } catch (err) {
+            _didIteratorError = true;
+            _iteratorError = err;
+          } finally {
+            try {
+              if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+                _iterator["return"]();
+              }
+            } finally {
+              if (_didIteratorError) {
+                throw _iteratorError;
+              }
             }
           }
         }
@@ -836,8 +855,8 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
         ctx.lineDashOffset = dashPhase;
       }
     },
-    setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) {},
-    setFlatness: function CanvasGraphics_setFlatness(flatness) {},
+    setRenderingIntent: function setRenderingIntent(intent) {},
+    setFlatness: function setFlatness(flatness) {},
     setGState: function CanvasGraphics_setGState(states) {
       for (var i = 0, ii = states.length; i < ii; i++) {
         var state = states[i];
@@ -1318,7 +1337,9 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
     },
 
     get isFontSubpixelAAEnabled() {
-      var ctx = this.canvasFactory.create(10, 10).context;
+      var _this$cachedCanvases$ = this.cachedCanvases.getCanvas('isFontSubpixelAAEnabled', 10, 10),
+          ctx = _this$cachedCanvases$.context;
+
       ctx.scale(1.5, 1);
       ctx.fillText('I', 0, 10);
       var data = ctx.getImageData(0, 0, 10, 10).data;
@@ -1345,7 +1366,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       var fontSize = current.fontSize;
 
       if (fontSize === 0) {
-        return;
+        return undefined;
       }
 
       var ctx = this.ctx;
@@ -1771,7 +1792,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       this.restore();
     },
     paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) {
-      var domImage = this.objs.get(objId);
+      var domImage = this.processingType3 ? this.commonObjs.get(objId) : this.objs.get(objId);
 
       if (!domImage) {
         (0, _util.warn)('Dependent image isn\'t ready yet');
@@ -1880,7 +1901,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       }
     },
     paintImageXObject: function CanvasGraphics_paintImageXObject(objId) {
-      var imgData = this.objs.get(objId);
+      var imgData = this.processingType3 ? this.commonObjs.get(objId) : this.objs.get(objId);
 
       if (!imgData) {
         (0, _util.warn)('Dependent image isn\'t ready yet');
@@ -1890,7 +1911,7 @@ var CanvasGraphics = function CanvasGraphicsClosure() {
       this.paintInlineImageXObject(imgData);
     },
     paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) {
-      var imgData = this.objs.get(objId);
+      var imgData = this.processingType3 ? this.commonObjs.get(objId) : this.objs.get(objId);
 
       if (!imgData) {
         (0, _util.warn)('Dependent image isn\'t ready yet');

+ 1 - 1
lib/display/content_disposition.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 747 - 0
lib/display/display_utils.js

@@ -0,0 +1,747 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+Object.defineProperty(exports, "__esModule", {
+  value: true
+});
+exports.addLinkAttributes = addLinkAttributes;
+exports.getFilenameFromUrl = getFilenameFromUrl;
+exports.isFetchSupported = isFetchSupported;
+exports.isValidFetchUrl = isValidFetchUrl;
+exports.loadScript = loadScript;
+exports.deprecated = deprecated;
+exports.releaseImageResources = releaseImageResources;
+exports.PDFDateString = exports.DummyStatTimer = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
+
+var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
+
+var _util = require("../shared/util");
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
+exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
+var SVG_NS = 'http://www.w3.org/2000/svg';
+
+var DOMCanvasFactory =
+/*#__PURE__*/
+function () {
+  function DOMCanvasFactory() {
+    _classCallCheck(this, DOMCanvasFactory);
+  }
+
+  _createClass(DOMCanvasFactory, [{
+    key: "create",
+    value: function create(width, height) {
+      if (width <= 0 || height <= 0) {
+        throw new Error('Invalid canvas size');
+      }
+
+      var canvas = document.createElement('canvas');
+      var context = canvas.getContext('2d');
+      canvas.width = width;
+      canvas.height = height;
+      return {
+        canvas: canvas,
+        context: context
+      };
+    }
+  }, {
+    key: "reset",
+    value: function reset(canvasAndContext, width, height) {
+      if (!canvasAndContext.canvas) {
+        throw new Error('Canvas is not specified');
+      }
+
+      if (width <= 0 || height <= 0) {
+        throw new Error('Invalid canvas size');
+      }
+
+      canvasAndContext.canvas.width = width;
+      canvasAndContext.canvas.height = height;
+    }
+  }, {
+    key: "destroy",
+    value: function destroy(canvasAndContext) {
+      if (!canvasAndContext.canvas) {
+        throw new Error('Canvas is not specified');
+      }
+
+      canvasAndContext.canvas.width = 0;
+      canvasAndContext.canvas.height = 0;
+      canvasAndContext.canvas = null;
+      canvasAndContext.context = null;
+    }
+  }]);
+
+  return DOMCanvasFactory;
+}();
+
+exports.DOMCanvasFactory = DOMCanvasFactory;
+
+var DOMCMapReaderFactory =
+/*#__PURE__*/
+function () {
+  function DOMCMapReaderFactory(_ref) {
+    var _ref$baseUrl = _ref.baseUrl,
+        baseUrl = _ref$baseUrl === void 0 ? null : _ref$baseUrl,
+        _ref$isCompressed = _ref.isCompressed,
+        isCompressed = _ref$isCompressed === void 0 ? false : _ref$isCompressed;
+
+    _classCallCheck(this, DOMCMapReaderFactory);
+
+    this.baseUrl = baseUrl;
+    this.isCompressed = isCompressed;
+  }
+
+  _createClass(DOMCMapReaderFactory, [{
+    key: "fetch",
+    value: function (_fetch) {
+      function fetch(_x) {
+        return _fetch.apply(this, arguments);
+      }
+
+      fetch.toString = function () {
+        return _fetch.toString();
+      };
+
+      return fetch;
+    }(
+    /*#__PURE__*/
+    function () {
+      var _ref3 = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee2(_ref2) {
+        var _this = this;
+
+        var name, url, compressionType;
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
+          while (1) {
+            switch (_context2.prev = _context2.next) {
+              case 0:
+                name = _ref2.name;
+
+                if (this.baseUrl) {
+                  _context2.next = 3;
+                  break;
+                }
+
+                throw new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.');
+
+              case 3:
+                if (name) {
+                  _context2.next = 5;
+                  break;
+                }
+
+                throw new Error('CMap name must be specified.');
+
+              case 5:
+                url = this.baseUrl + name + (this.isCompressed ? '.bcmap' : '');
+                compressionType = this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE;
+
+                if (!(isFetchSupported() && isValidFetchUrl(url, document.baseURI))) {
+                  _context2.next = 9;
+                  break;
+                }
+
+                return _context2.abrupt("return", fetch(url).then(
+                /*#__PURE__*/
+                function () {
+                  var _ref4 = _asyncToGenerator(
+                  /*#__PURE__*/
+                  _regenerator["default"].mark(function _callee(response) {
+                    var cMapData;
+                    return _regenerator["default"].wrap(function _callee$(_context) {
+                      while (1) {
+                        switch (_context.prev = _context.next) {
+                          case 0:
+                            if (response.ok) {
+                              _context.next = 2;
+                              break;
+                            }
+
+                            throw new Error(response.statusText);
+
+                          case 2:
+                            if (!_this.isCompressed) {
+                              _context.next = 10;
+                              break;
+                            }
+
+                            _context.t0 = Uint8Array;
+                            _context.next = 6;
+                            return response.arrayBuffer();
+
+                          case 6:
+                            _context.t1 = _context.sent;
+                            cMapData = new _context.t0(_context.t1);
+                            _context.next = 15;
+                            break;
+
+                          case 10:
+                            _context.t2 = _util.stringToBytes;
+                            _context.next = 13;
+                            return response.text();
+
+                          case 13:
+                            _context.t3 = _context.sent;
+                            cMapData = (0, _context.t2)(_context.t3);
+
+                          case 15:
+                            return _context.abrupt("return", {
+                              cMapData: cMapData,
+                              compressionType: compressionType
+                            });
+
+                          case 16:
+                          case "end":
+                            return _context.stop();
+                        }
+                      }
+                    }, _callee);
+                  }));
+
+                  return function (_x3) {
+                    return _ref4.apply(this, arguments);
+                  };
+                }())["catch"](function (reason) {
+                  throw new Error("Unable to load ".concat(_this.isCompressed ? 'binary ' : '') + "CMap at: ".concat(url));
+                }));
+
+              case 9:
+                return _context2.abrupt("return", new Promise(function (resolve, reject) {
+                  var request = new XMLHttpRequest();
+                  request.open('GET', url, true);
+
+                  if (_this.isCompressed) {
+                    request.responseType = 'arraybuffer';
+                  }
+
+                  request.onreadystatechange = function () {
+                    if (request.readyState !== XMLHttpRequest.DONE) {
+                      return;
+                    }
+
+                    if (request.status === 200 || request.status === 0) {
+                      var cMapData;
+
+                      if (_this.isCompressed && request.response) {
+                        cMapData = new Uint8Array(request.response);
+                      } else if (!_this.isCompressed && request.responseText) {
+                        cMapData = (0, _util.stringToBytes)(request.responseText);
+                      }
+
+                      if (cMapData) {
+                        resolve({
+                          cMapData: cMapData,
+                          compressionType: compressionType
+                        });
+                        return;
+                      }
+                    }
+
+                    reject(new Error(request.statusText));
+                  };
+
+                  request.send(null);
+                })["catch"](function (reason) {
+                  throw new Error("Unable to load ".concat(_this.isCompressed ? 'binary ' : '') + "CMap at: ".concat(url));
+                }));
+
+              case 10:
+              case "end":
+                return _context2.stop();
+            }
+          }
+        }, _callee2, this);
+      }));
+
+      return function (_x2) {
+        return _ref3.apply(this, arguments);
+      };
+    }())
+  }]);
+
+  return DOMCMapReaderFactory;
+}();
+
+exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
+
+var DOMSVGFactory =
+/*#__PURE__*/
+function () {
+  function DOMSVGFactory() {
+    _classCallCheck(this, DOMSVGFactory);
+  }
+
+  _createClass(DOMSVGFactory, [{
+    key: "create",
+    value: function create(width, height) {
+      (0, _util.assert)(width > 0 && height > 0, 'Invalid SVG dimensions');
+      var svg = document.createElementNS(SVG_NS, 'svg:svg');
+      svg.setAttribute('version', '1.1');
+      svg.setAttribute('width', width + 'px');
+      svg.setAttribute('height', height + 'px');
+      svg.setAttribute('preserveAspectRatio', 'none');
+      svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
+      return svg;
+    }
+  }, {
+    key: "createElement",
+    value: function createElement(type) {
+      (0, _util.assert)(typeof type === 'string', 'Invalid SVG element type');
+      return document.createElementNS(SVG_NS, type);
+    }
+  }]);
+
+  return DOMSVGFactory;
+}();
+
+exports.DOMSVGFactory = DOMSVGFactory;
+
+var PageViewport =
+/*#__PURE__*/
+function () {
+  function PageViewport(_ref5) {
+    var viewBox = _ref5.viewBox,
+        scale = _ref5.scale,
+        rotation = _ref5.rotation,
+        _ref5$offsetX = _ref5.offsetX,
+        offsetX = _ref5$offsetX === void 0 ? 0 : _ref5$offsetX,
+        _ref5$offsetY = _ref5.offsetY,
+        offsetY = _ref5$offsetY === void 0 ? 0 : _ref5$offsetY,
+        _ref5$dontFlip = _ref5.dontFlip,
+        dontFlip = _ref5$dontFlip === void 0 ? false : _ref5$dontFlip;
+
+    _classCallCheck(this, PageViewport);
+
+    this.viewBox = viewBox;
+    this.scale = scale;
+    this.rotation = rotation;
+    this.offsetX = offsetX;
+    this.offsetY = offsetY;
+    var centerX = (viewBox[2] + viewBox[0]) / 2;
+    var centerY = (viewBox[3] + viewBox[1]) / 2;
+    var rotateA, rotateB, rotateC, rotateD;
+    rotation = rotation % 360;
+    rotation = rotation < 0 ? rotation + 360 : rotation;
+
+    switch (rotation) {
+      case 180:
+        rotateA = -1;
+        rotateB = 0;
+        rotateC = 0;
+        rotateD = 1;
+        break;
+
+      case 90:
+        rotateA = 0;
+        rotateB = 1;
+        rotateC = 1;
+        rotateD = 0;
+        break;
+
+      case 270:
+        rotateA = 0;
+        rotateB = -1;
+        rotateC = -1;
+        rotateD = 0;
+        break;
+
+      default:
+        rotateA = 1;
+        rotateB = 0;
+        rotateC = 0;
+        rotateD = -1;
+        break;
+    }
+
+    if (dontFlip) {
+      rotateC = -rotateC;
+      rotateD = -rotateD;
+    }
+
+    var offsetCanvasX, offsetCanvasY;
+    var width, height;
+
+    if (rotateA === 0) {
+      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
+      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
+      width = Math.abs(viewBox[3] - viewBox[1]) * scale;
+      height = Math.abs(viewBox[2] - viewBox[0]) * scale;
+    } else {
+      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
+      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
+      width = Math.abs(viewBox[2] - viewBox[0]) * scale;
+      height = Math.abs(viewBox[3] - viewBox[1]) * scale;
+    }
+
+    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
+    this.width = width;
+    this.height = height;
+  }
+
+  _createClass(PageViewport, [{
+    key: "clone",
+    value: function clone() {
+      var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
+          _ref6$scale = _ref6.scale,
+          scale = _ref6$scale === void 0 ? this.scale : _ref6$scale,
+          _ref6$rotation = _ref6.rotation,
+          rotation = _ref6$rotation === void 0 ? this.rotation : _ref6$rotation,
+          _ref6$dontFlip = _ref6.dontFlip,
+          dontFlip = _ref6$dontFlip === void 0 ? false : _ref6$dontFlip;
+
+      return new PageViewport({
+        viewBox: this.viewBox.slice(),
+        scale: scale,
+        rotation: rotation,
+        offsetX: this.offsetX,
+        offsetY: this.offsetY,
+        dontFlip: dontFlip
+      });
+    }
+  }, {
+    key: "convertToViewportPoint",
+    value: function convertToViewportPoint(x, y) {
+      return _util.Util.applyTransform([x, y], this.transform);
+    }
+  }, {
+    key: "convertToViewportRectangle",
+    value: function convertToViewportRectangle(rect) {
+      var topLeft = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
+
+      var bottomRight = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
+
+      return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]];
+    }
+  }, {
+    key: "convertToPdfPoint",
+    value: function convertToPdfPoint(x, y) {
+      return _util.Util.applyInverseTransform([x, y], this.transform);
+    }
+  }]);
+
+  return PageViewport;
+}();
+
+exports.PageViewport = PageViewport;
+
+var RenderingCancelledException = function RenderingCancelledException() {
+  function RenderingCancelledException(msg, type) {
+    this.message = msg;
+    this.type = type;
+  }
+
+  RenderingCancelledException.prototype = new Error();
+  RenderingCancelledException.prototype.name = 'RenderingCancelledException';
+  RenderingCancelledException.constructor = RenderingCancelledException;
+  return RenderingCancelledException;
+}();
+
+exports.RenderingCancelledException = RenderingCancelledException;
+var LinkTarget = {
+  NONE: 0,
+  SELF: 1,
+  BLANK: 2,
+  PARENT: 3,
+  TOP: 4
+};
+exports.LinkTarget = LinkTarget;
+var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top'];
+
+function addLinkAttributes(link) {
+  var _ref7 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
+      url = _ref7.url,
+      target = _ref7.target,
+      rel = _ref7.rel;
+
+  link.href = link.title = url ? (0, _util.removeNullCharacters)(url) : '';
+
+  if (url) {
+    var LinkTargetValues = Object.values(LinkTarget);
+    var targetIndex = LinkTargetValues.includes(target) ? target : LinkTarget.NONE;
+    link.target = LinkTargetStringMap[targetIndex];
+    link.rel = typeof rel === 'string' ? rel : DEFAULT_LINK_REL;
+  }
+}
+
+function getFilenameFromUrl(url) {
+  var anchor = url.indexOf('#');
+  var query = url.indexOf('?');
+  var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
+  return url.substring(url.lastIndexOf('/', end) + 1, end);
+}
+
+var StatTimer =
+/*#__PURE__*/
+function () {
+  function StatTimer() {
+    var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
+
+    _classCallCheck(this, StatTimer);
+
+    this.enabled = !!enable;
+    this.started = Object.create(null);
+    this.times = [];
+  }
+
+  _createClass(StatTimer, [{
+    key: "time",
+    value: function time(name) {
+      if (!this.enabled) {
+        return;
+      }
+
+      if (name in this.started) {
+        (0, _util.warn)('Timer is already running for ' + name);
+      }
+
+      this.started[name] = Date.now();
+    }
+  }, {
+    key: "timeEnd",
+    value: function timeEnd(name) {
+      if (!this.enabled) {
+        return;
+      }
+
+      if (!(name in this.started)) {
+        (0, _util.warn)('Timer has not been started for ' + name);
+      }
+
+      this.times.push({
+        'name': name,
+        'start': this.started[name],
+        'end': Date.now()
+      });
+      delete this.started[name];
+    }
+  }, {
+    key: "toString",
+    value: function toString() {
+      var out = '',
+          longest = 0;
+      var _iteratorNormalCompletion = true;
+      var _didIteratorError = false;
+      var _iteratorError = undefined;
+
+      try {
+        for (var _iterator = this.times[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+          var time = _step.value;
+          var name = time.name;
+
+          if (name.length > longest) {
+            longest = name.length;
+          }
+        }
+      } catch (err) {
+        _didIteratorError = true;
+        _iteratorError = err;
+      } finally {
+        try {
+          if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+            _iterator["return"]();
+          }
+        } finally {
+          if (_didIteratorError) {
+            throw _iteratorError;
+          }
+        }
+      }
+
+      var _iteratorNormalCompletion2 = true;
+      var _didIteratorError2 = false;
+      var _iteratorError2 = undefined;
+
+      try {
+        for (var _iterator2 = this.times[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
+          var _time = _step2.value;
+          var duration = _time.end - _time.start;
+          out += "".concat(_time.name.padEnd(longest), " ").concat(duration, "ms\n");
+        }
+      } catch (err) {
+        _didIteratorError2 = true;
+        _iteratorError2 = err;
+      } finally {
+        try {
+          if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
+            _iterator2["return"]();
+          }
+        } finally {
+          if (_didIteratorError2) {
+            throw _iteratorError2;
+          }
+        }
+      }
+
+      return out;
+    }
+  }]);
+
+  return StatTimer;
+}();
+
+exports.StatTimer = StatTimer;
+
+var DummyStatTimer =
+/*#__PURE__*/
+function () {
+  function DummyStatTimer() {
+    _classCallCheck(this, DummyStatTimer);
+
+    (0, _util.unreachable)('Cannot initialize DummyStatTimer.');
+  }
+
+  _createClass(DummyStatTimer, null, [{
+    key: "time",
+    value: function time(name) {}
+  }, {
+    key: "timeEnd",
+    value: function timeEnd(name) {}
+  }, {
+    key: "toString",
+    value: function toString() {
+      return '';
+    }
+  }]);
+
+  return DummyStatTimer;
+}();
+
+exports.DummyStatTimer = DummyStatTimer;
+
+function isFetchSupported() {
+  return typeof fetch !== 'undefined' && typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream !== 'undefined';
+}
+
+function isValidFetchUrl(url, baseUrl) {
+  try {
+    var _ref8 = baseUrl ? new _util.URL(url, baseUrl) : new _util.URL(url),
+        protocol = _ref8.protocol;
+
+    return protocol === 'http:' || protocol === 'https:';
+  } catch (ex) {
+    return false;
+  }
+}
+
+function loadScript(src) {
+  return new Promise(function (resolve, reject) {
+    var script = document.createElement('script');
+    script.src = src;
+    script.onload = resolve;
+
+    script.onerror = function () {
+      reject(new Error("Cannot load script at: ".concat(script.src)));
+    };
+
+    (document.head || document.documentElement).appendChild(script);
+  });
+}
+
+function deprecated(details) {
+  console.log('Deprecated API usage: ' + details);
+}
+
+function releaseImageResources(img) {
+  (0, _util.assert)(img instanceof Image, 'Invalid `img` parameter.');
+  var url = img.src;
+
+  if (typeof url === 'string' && url.startsWith('blob:') && _util.URL.revokeObjectURL) {
+    _util.URL.revokeObjectURL(url);
+  }
+
+  img.removeAttribute('src');
+}
+
+var pdfDateStringRegex;
+
+var PDFDateString =
+/*#__PURE__*/
+function () {
+  function PDFDateString() {
+    _classCallCheck(this, PDFDateString);
+  }
+
+  _createClass(PDFDateString, null, [{
+    key: "toDateObject",
+    value: function toDateObject(input) {
+      if (!input || !(0, _util.isString)(input)) {
+        return null;
+      }
+
+      if (!pdfDateStringRegex) {
+        pdfDateStringRegex = new RegExp('^D:' + '(\\d{4})' + '(\\d{2})?' + '(\\d{2})?' + '(\\d{2})?' + '(\\d{2})?' + '(\\d{2})?' + '([Z|+|-])?' + '(\\d{2})?' + '\'?' + '(\\d{2})?' + '\'?');
+      }
+
+      var matches = pdfDateStringRegex.exec(input);
+
+      if (!matches) {
+        return null;
+      }
+
+      var year = parseInt(matches[1], 10);
+      var month = parseInt(matches[2], 10);
+      month = month >= 1 && month <= 12 ? month - 1 : 0;
+      var day = parseInt(matches[3], 10);
+      day = day >= 1 && day <= 31 ? day : 1;
+      var hour = parseInt(matches[4], 10);
+      hour = hour >= 0 && hour <= 23 ? hour : 0;
+      var minute = parseInt(matches[5], 10);
+      minute = minute >= 0 && minute <= 59 ? minute : 0;
+      var second = parseInt(matches[6], 10);
+      second = second >= 0 && second <= 59 ? second : 0;
+      var universalTimeRelation = matches[7] || 'Z';
+      var offsetHour = parseInt(matches[8], 10);
+      offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0;
+      var offsetMinute = parseInt(matches[9], 10) || 0;
+      offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0;
+
+      if (universalTimeRelation === '-') {
+        hour += offsetHour;
+        minute += offsetMinute;
+      } else if (universalTimeRelation === '+') {
+        hour -= offsetHour;
+        minute -= offsetMinute;
+      }
+
+      return new Date(Date.UTC(year, month, day, hour, minute, second));
+    }
+  }]);
+
+  return PDFDateString;
+}();
+
+exports.PDFDateString = PDFDateString;

+ 0 - 494
lib/display/dom_utils.js

@@ -1,494 +0,0 @@
-/**
- * @licstart The following is the entire license notice for the
- * Javascript code in this page
- *
- * Copyright 2018 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @licend The above is the entire license notice for the
- * Javascript code in this page
- */
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
-  value: true
-});
-exports.addLinkAttributes = addLinkAttributes;
-exports.getFilenameFromUrl = getFilenameFromUrl;
-exports.loadScript = loadScript;
-exports.DummyStatTimer = exports.StatTimer = exports.DOMSVGFactory = exports.DOMCMapReaderFactory = exports.DOMCanvasFactory = exports.DEFAULT_LINK_REL = exports.LinkTarget = exports.RenderingCancelledException = exports.PageViewport = void 0;
-
-var _util = require("../shared/util");
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
-
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
-
-var DEFAULT_LINK_REL = 'noopener noreferrer nofollow';
-exports.DEFAULT_LINK_REL = DEFAULT_LINK_REL;
-var SVG_NS = 'http://www.w3.org/2000/svg';
-
-var DOMCanvasFactory =
-/*#__PURE__*/
-function () {
-  function DOMCanvasFactory() {
-    _classCallCheck(this, DOMCanvasFactory);
-  }
-
-  _createClass(DOMCanvasFactory, [{
-    key: "create",
-    value: function create(width, height) {
-      if (width <= 0 || height <= 0) {
-        throw new Error('invalid canvas size');
-      }
-
-      var canvas = document.createElement('canvas');
-      var context = canvas.getContext('2d');
-      canvas.width = width;
-      canvas.height = height;
-      return {
-        canvas: canvas,
-        context: context
-      };
-    }
-  }, {
-    key: "reset",
-    value: function reset(canvasAndContext, width, height) {
-      if (!canvasAndContext.canvas) {
-        throw new Error('canvas is not specified');
-      }
-
-      if (width <= 0 || height <= 0) {
-        throw new Error('invalid canvas size');
-      }
-
-      canvasAndContext.canvas.width = width;
-      canvasAndContext.canvas.height = height;
-    }
-  }, {
-    key: "destroy",
-    value: function destroy(canvasAndContext) {
-      if (!canvasAndContext.canvas) {
-        throw new Error('canvas is not specified');
-      }
-
-      canvasAndContext.canvas.width = 0;
-      canvasAndContext.canvas.height = 0;
-      canvasAndContext.canvas = null;
-      canvasAndContext.context = null;
-    }
-  }]);
-
-  return DOMCanvasFactory;
-}();
-
-exports.DOMCanvasFactory = DOMCanvasFactory;
-
-var DOMCMapReaderFactory =
-/*#__PURE__*/
-function () {
-  function DOMCMapReaderFactory(_ref) {
-    var _ref$baseUrl = _ref.baseUrl,
-        baseUrl = _ref$baseUrl === void 0 ? null : _ref$baseUrl,
-        _ref$isCompressed = _ref.isCompressed,
-        isCompressed = _ref$isCompressed === void 0 ? false : _ref$isCompressed;
-
-    _classCallCheck(this, DOMCMapReaderFactory);
-
-    this.baseUrl = baseUrl;
-    this.isCompressed = isCompressed;
-  }
-
-  _createClass(DOMCMapReaderFactory, [{
-    key: "fetch",
-    value: function fetch(_ref2) {
-      var _this = this;
-
-      var name = _ref2.name;
-
-      if (!this.baseUrl) {
-        return Promise.reject(new Error('The CMap "baseUrl" parameter must be specified, ensure that ' + 'the "cMapUrl" and "cMapPacked" API parameters are provided.'));
-      }
-
-      if (!name) {
-        return Promise.reject(new Error('CMap name must be specified.'));
-      }
-
-      return new Promise(function (resolve, reject) {
-        var url = _this.baseUrl + name + (_this.isCompressed ? '.bcmap' : '');
-        var request = new XMLHttpRequest();
-        request.open('GET', url, true);
-
-        if (_this.isCompressed) {
-          request.responseType = 'arraybuffer';
-        }
-
-        request.onreadystatechange = function () {
-          if (request.readyState !== XMLHttpRequest.DONE) {
-            return;
-          }
-
-          if (request.status === 200 || request.status === 0) {
-            var data;
-
-            if (_this.isCompressed && request.response) {
-              data = new Uint8Array(request.response);
-            } else if (!_this.isCompressed && request.responseText) {
-              data = (0, _util.stringToBytes)(request.responseText);
-            }
-
-            if (data) {
-              resolve({
-                cMapData: data,
-                compressionType: _this.isCompressed ? _util.CMapCompressionType.BINARY : _util.CMapCompressionType.NONE
-              });
-              return;
-            }
-          }
-
-          reject(new Error('Unable to load ' + (_this.isCompressed ? 'binary ' : '') + 'CMap at: ' + url));
-        };
-
-        request.send(null);
-      });
-    }
-  }]);
-
-  return DOMCMapReaderFactory;
-}();
-
-exports.DOMCMapReaderFactory = DOMCMapReaderFactory;
-
-var DOMSVGFactory =
-/*#__PURE__*/
-function () {
-  function DOMSVGFactory() {
-    _classCallCheck(this, DOMSVGFactory);
-  }
-
-  _createClass(DOMSVGFactory, [{
-    key: "create",
-    value: function create(width, height) {
-      (0, _util.assert)(width > 0 && height > 0, 'Invalid SVG dimensions');
-      var svg = document.createElementNS(SVG_NS, 'svg:svg');
-      svg.setAttribute('version', '1.1');
-      svg.setAttribute('width', width + 'px');
-      svg.setAttribute('height', height + 'px');
-      svg.setAttribute('preserveAspectRatio', 'none');
-      svg.setAttribute('viewBox', '0 0 ' + width + ' ' + height);
-      return svg;
-    }
-  }, {
-    key: "createElement",
-    value: function createElement(type) {
-      (0, _util.assert)(typeof type === 'string', 'Invalid SVG element type');
-      return document.createElementNS(SVG_NS, type);
-    }
-  }]);
-
-  return DOMSVGFactory;
-}();
-
-exports.DOMSVGFactory = DOMSVGFactory;
-
-var PageViewport =
-/*#__PURE__*/
-function () {
-  function PageViewport(_ref3) {
-    var viewBox = _ref3.viewBox,
-        scale = _ref3.scale,
-        rotation = _ref3.rotation,
-        _ref3$offsetX = _ref3.offsetX,
-        offsetX = _ref3$offsetX === void 0 ? 0 : _ref3$offsetX,
-        _ref3$offsetY = _ref3.offsetY,
-        offsetY = _ref3$offsetY === void 0 ? 0 : _ref3$offsetY,
-        _ref3$dontFlip = _ref3.dontFlip,
-        dontFlip = _ref3$dontFlip === void 0 ? false : _ref3$dontFlip;
-
-    _classCallCheck(this, PageViewport);
-
-    this.viewBox = viewBox;
-    this.scale = scale;
-    this.rotation = rotation;
-    this.offsetX = offsetX;
-    this.offsetY = offsetY;
-    var centerX = (viewBox[2] + viewBox[0]) / 2;
-    var centerY = (viewBox[3] + viewBox[1]) / 2;
-    var rotateA, rotateB, rotateC, rotateD;
-    rotation = rotation % 360;
-    rotation = rotation < 0 ? rotation + 360 : rotation;
-
-    switch (rotation) {
-      case 180:
-        rotateA = -1;
-        rotateB = 0;
-        rotateC = 0;
-        rotateD = 1;
-        break;
-
-      case 90:
-        rotateA = 0;
-        rotateB = 1;
-        rotateC = 1;
-        rotateD = 0;
-        break;
-
-      case 270:
-        rotateA = 0;
-        rotateB = -1;
-        rotateC = -1;
-        rotateD = 0;
-        break;
-
-      default:
-        rotateA = 1;
-        rotateB = 0;
-        rotateC = 0;
-        rotateD = -1;
-        break;
-    }
-
-    if (dontFlip) {
-      rotateC = -rotateC;
-      rotateD = -rotateD;
-    }
-
-    var offsetCanvasX, offsetCanvasY;
-    var width, height;
-
-    if (rotateA === 0) {
-      offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX;
-      offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY;
-      width = Math.abs(viewBox[3] - viewBox[1]) * scale;
-      height = Math.abs(viewBox[2] - viewBox[0]) * scale;
-    } else {
-      offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX;
-      offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY;
-      width = Math.abs(viewBox[2] - viewBox[0]) * scale;
-      height = Math.abs(viewBox[3] - viewBox[1]) * scale;
-    }
-
-    this.transform = [rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY];
-    this.width = width;
-    this.height = height;
-  }
-
-  _createClass(PageViewport, [{
-    key: "clone",
-    value: function clone() {
-      var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
-          _ref4$scale = _ref4.scale,
-          scale = _ref4$scale === void 0 ? this.scale : _ref4$scale,
-          _ref4$rotation = _ref4.rotation,
-          rotation = _ref4$rotation === void 0 ? this.rotation : _ref4$rotation,
-          _ref4$dontFlip = _ref4.dontFlip,
-          dontFlip = _ref4$dontFlip === void 0 ? false : _ref4$dontFlip;
-
-      return new PageViewport({
-        viewBox: this.viewBox.slice(),
-        scale: scale,
-        rotation: rotation,
-        offsetX: this.offsetX,
-        offsetY: this.offsetY,
-        dontFlip: dontFlip
-      });
-    }
-  }, {
-    key: "convertToViewportPoint",
-    value: function convertToViewportPoint(x, y) {
-      return _util.Util.applyTransform([x, y], this.transform);
-    }
-  }, {
-    key: "convertToViewportRectangle",
-    value: function convertToViewportRectangle(rect) {
-      var tl = _util.Util.applyTransform([rect[0], rect[1]], this.transform);
-
-      var br = _util.Util.applyTransform([rect[2], rect[3]], this.transform);
-
-      return [tl[0], tl[1], br[0], br[1]];
-    }
-  }, {
-    key: "convertToPdfPoint",
-    value: function convertToPdfPoint(x, y) {
-      return _util.Util.applyInverseTransform([x, y], this.transform);
-    }
-  }]);
-
-  return PageViewport;
-}();
-
-exports.PageViewport = PageViewport;
-
-var RenderingCancelledException = function RenderingCancelledException() {
-  function RenderingCancelledException(msg, type) {
-    this.message = msg;
-    this.type = type;
-  }
-
-  RenderingCancelledException.prototype = new Error();
-  RenderingCancelledException.prototype.name = 'RenderingCancelledException';
-  RenderingCancelledException.constructor = RenderingCancelledException;
-  return RenderingCancelledException;
-}();
-
-exports.RenderingCancelledException = RenderingCancelledException;
-var LinkTarget = {
-  NONE: 0,
-  SELF: 1,
-  BLANK: 2,
-  PARENT: 3,
-  TOP: 4
-};
-exports.LinkTarget = LinkTarget;
-var LinkTargetStringMap = ['', '_self', '_blank', '_parent', '_top'];
-
-function addLinkAttributes(link) {
-  var _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
-      url = _ref5.url,
-      target = _ref5.target,
-      rel = _ref5.rel;
-
-  link.href = link.title = url ? (0, _util.removeNullCharacters)(url) : '';
-
-  if (url) {
-    var LinkTargetValues = Object.values(LinkTarget);
-    var targetIndex = LinkTargetValues.includes(target) ? target : LinkTarget.NONE;
-    link.target = LinkTargetStringMap[targetIndex];
-    link.rel = typeof rel === 'string' ? rel : DEFAULT_LINK_REL;
-  }
-}
-
-function getFilenameFromUrl(url) {
-  var anchor = url.indexOf('#');
-  var query = url.indexOf('?');
-  var end = Math.min(anchor > 0 ? anchor : url.length, query > 0 ? query : url.length);
-  return url.substring(url.lastIndexOf('/', end) + 1, end);
-}
-
-var StatTimer =
-/*#__PURE__*/
-function () {
-  function StatTimer() {
-    var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
-
-    _classCallCheck(this, StatTimer);
-
-    this.enabled = !!enable;
-    this.started = Object.create(null);
-    this.times = [];
-  }
-
-  _createClass(StatTimer, [{
-    key: "time",
-    value: function time(name) {
-      if (!this.enabled) {
-        return;
-      }
-
-      if (name in this.started) {
-        (0, _util.warn)('Timer is already running for ' + name);
-      }
-
-      this.started[name] = Date.now();
-    }
-  }, {
-    key: "timeEnd",
-    value: function timeEnd(name) {
-      if (!this.enabled) {
-        return;
-      }
-
-      if (!(name in this.started)) {
-        (0, _util.warn)('Timer has not been started for ' + name);
-      }
-
-      this.times.push({
-        'name': name,
-        'start': this.started[name],
-        'end': Date.now()
-      });
-      delete this.started[name];
-    }
-  }, {
-    key: "toString",
-    value: function toString() {
-      var times = this.times;
-      var out = '',
-          longest = 0;
-
-      for (var i = 0, ii = times.length; i < ii; ++i) {
-        var name = times[i]['name'];
-
-        if (name.length > longest) {
-          longest = name.length;
-        }
-      }
-
-      for (var _i = 0, _ii = times.length; _i < _ii; ++_i) {
-        var span = times[_i];
-        var duration = span.end - span.start;
-        out += "".concat(span['name'].padEnd(longest), " ").concat(duration, "ms\n");
-      }
-
-      return out;
-    }
-  }]);
-
-  return StatTimer;
-}();
-
-exports.StatTimer = StatTimer;
-
-var DummyStatTimer =
-/*#__PURE__*/
-function () {
-  function DummyStatTimer() {
-    _classCallCheck(this, DummyStatTimer);
-
-    (0, _util.unreachable)('Cannot initialize DummyStatTimer.');
-  }
-
-  _createClass(DummyStatTimer, null, [{
-    key: "time",
-    value: function time(name) {}
-  }, {
-    key: "timeEnd",
-    value: function timeEnd(name) {}
-  }, {
-    key: "toString",
-    value: function toString() {
-      return '';
-    }
-  }]);
-
-  return DummyStatTimer;
-}();
-
-exports.DummyStatTimer = DummyStatTimer;
-
-function loadScript(src) {
-  return new Promise(function (resolve, reject) {
-    var script = document.createElement('script');
-    script.src = src;
-    script.onload = resolve;
-
-    script.onerror = function () {
-      reject(new Error("Cannot load script at: ".concat(script.src)));
-    };
-
-    (document.head || document.documentElement).appendChild(script);
-  });
-}

+ 19 - 12
lib/display/fetch_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -78,6 +78,10 @@ function () {
   }, {
     key: "getRangeReader",
     value: function getRangeReader(begin, end) {
+      if (end <= this._progressiveDataLength) {
+        return null;
+      }
+
       var reader = new PDFFetchStreamRangeReader(this, begin, end);
 
       this._rangeRequestReaders.push(reader);
@@ -97,6 +101,11 @@ function () {
         reader.cancel(reason);
       });
     }
+  }, {
+    key: "_progressiveDataLength",
+    get: function get() {
+      return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
+    }
   }]);
 
   return PDFFetchStream;
@@ -117,7 +126,7 @@ function () {
     this._loaded = 0;
     this._filename = null;
     var source = stream.source;
-    this._withCredentials = source.withCredentials;
+    this._withCredentials = source.withCredentials || false;
     this._contentLength = source.length;
     this._headersCapability = (0, _util.createPromiseCapability)();
     this._disableRange = source.disableRange || false;
@@ -173,9 +182,9 @@ function () {
       _this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
 
       if (!_this._isStreamingSupported && _this._isRangeSupported) {
-        _this.cancel(new _util.AbortException('streaming is disabled'));
+        _this.cancel(new _util.AbortException('Streaming is disabled.'));
       }
-    }).catch(this._headersCapability.reject);
+    })["catch"](this._headersCapability.reject);
     this.onProgress = null;
   }
 
@@ -184,10 +193,10 @@ function () {
     value: function () {
       var _read = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee() {
+      _regenerator["default"].mark(function _callee() {
         var _ref, value, done, buffer;
 
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -296,7 +305,7 @@ function () {
     this._reader = null;
     this._loaded = 0;
     var source = stream.source;
-    this._withCredentials = source.withCredentials;
+    this._withCredentials = source.withCredentials || false;
     this._readCapability = (0, _util.createPromiseCapability)();
     this._isStreamingSupported = !source.disableStream;
 
@@ -316,9 +325,7 @@ function () {
       this._headers.append(property, value);
     }
 
-    var rangeStr = begin + '-' + (end - 1);
-
-    this._headers.append('Range', 'bytes=' + rangeStr);
+    this._headers.append('Range', "bytes=".concat(begin, "-").concat(end - 1));
 
     var url = source.url;
     fetch(url, createFetchOptions(this._headers, this._withCredentials, this._abortController)).then(function (response) {
@@ -338,10 +345,10 @@ function () {
     value: function () {
       var _read2 = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee2() {
+      _regenerator["default"].mark(function _callee2() {
         var _ref2, value, done, buffer;
 
-        return _regenerator.default.wrap(function _callee2$(_context2) {
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
           while (1) {
             switch (_context2.prev = _context2.next) {
               case 0:

+ 11 - 8
lib/display/font_loader.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"))
 
 var _util = require("../shared/util");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
@@ -97,7 +97,7 @@ function () {
     key: "clear",
     value: function clear() {
       this.nativeFontFaces.forEach(function (nativeFontFace) {
-        document.fonts.delete(nativeFontFace);
+        document.fonts["delete"](nativeFontFace);
       });
       this.nativeFontFaces.length = 0;
 
@@ -111,11 +111,11 @@ function () {
     value: function () {
       var _bind = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee(font) {
+      _regenerator["default"].mark(function _callee(font) {
         var _this = this;
 
         var nativeFontFace, rule;
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -124,7 +124,7 @@ function () {
                   break;
                 }
 
-                return _context.abrupt("return");
+                return _context.abrupt("return", undefined);
 
               case 2:
                 font.attached = true;
@@ -163,7 +163,7 @@ function () {
                 throw _context.t0;
 
               case 18:
-                return _context.abrupt("return");
+                return _context.abrupt("return", undefined);
 
               case 19:
                 rule = font.createFontFaceRule();
@@ -180,7 +180,7 @@ function () {
                   break;
                 }
 
-                return _context.abrupt("return");
+                return _context.abrupt("return", undefined);
 
               case 24:
                 return _context.abrupt("return", new Promise(function (resolve) {
@@ -190,6 +190,9 @@ function () {
                 }));
 
               case 25:
+                return _context.abrupt("return", undefined);
+
+              case 26:
               case "end":
                 return _context.stop();
             }

+ 1 - 1
lib/display/metadata.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 563 - 521
lib/display/network.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,8 +24,7 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.PDFNetworkStream = PDFNetworkStream;
-exports.NetworkManager = NetworkManager;
+exports.PDFNetworkStream = void 0;
 
 var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
 
@@ -33,33 +32,21 @@ var _util = require("../shared/util");
 
 var _network_utils = require("./network_utils");
 
-var _global_scope = _interopRequireDefault(require("../shared/global_scope"));
-
 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
 
 function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
 
-;
-var OK_RESPONSE = 200;
-var PARTIAL_CONTENT_RESPONSE = 206;
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
-function NetworkManager(url, args) {
-  this.url = url;
-  args = args || {};
-  this.isHttp = /^https?:/i.test(url);
-  this.httpHeaders = this.isHttp && args.httpHeaders || {};
-  this.withCredentials = args.withCredentials || false;
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
 
-  this.getXhr = args.getXhr || function NetworkManager_getXhr() {
-    return new XMLHttpRequest();
-  };
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
 
-  this.currXhrId = 0;
-  this.pendingRequests = Object.create(null);
-  this.loadedRequests = Object.create(null);
-}
+;
+var OK_RESPONSE = 200;
+var PARTIAL_CONTENT_RESPONSE = 206;
 
 function getArrayBuffer(xhr) {
   var data = xhr.response;
@@ -72,594 +59,649 @@ function getArrayBuffer(xhr) {
   return array.buffer;
 }
 
-var supportsMozChunked = function supportsMozChunkedClosure() {
-  try {
-    var x = new XMLHttpRequest();
-    x.open('GET', _global_scope.default.location.href);
-    x.responseType = 'moz-chunked-arraybuffer';
-    return x.responseType === 'moz-chunked-arraybuffer';
-  } catch (e) {
-    return false;
-  }
-}();
+var NetworkManager =
+/*#__PURE__*/
+function () {
+  function NetworkManager(url, args) {
+    _classCallCheck(this, NetworkManager);
 
-NetworkManager.prototype = {
-  requestRange: function NetworkManager_requestRange(begin, end, listeners) {
-    var args = {
-      begin: begin,
-      end: end
-    };
-
-    for (var prop in listeners) {
-      args[prop] = listeners[prop];
-    }
+    this.url = url;
+    args = args || {};
+    this.isHttp = /^https?:/i.test(url);
+    this.httpHeaders = this.isHttp && args.httpHeaders || {};
+    this.withCredentials = args.withCredentials || false;
 
-    return this.request(args);
-  },
-  requestFull: function NetworkManager_requestFull(listeners) {
-    return this.request(listeners);
-  },
-  request: function NetworkManager_request(args) {
-    var xhr = this.getXhr();
-    var xhrId = this.currXhrId++;
-    var pendingRequest = this.pendingRequests[xhrId] = {
-      xhr: xhr
+    this.getXhr = args.getXhr || function NetworkManager_getXhr() {
+      return new XMLHttpRequest();
     };
-    xhr.open('GET', this.url);
-    xhr.withCredentials = this.withCredentials;
 
-    for (var property in this.httpHeaders) {
-      var value = this.httpHeaders[property];
+    this.currXhrId = 0;
+    this.pendingRequests = Object.create(null);
+  }
+
+  _createClass(NetworkManager, [{
+    key: "requestRange",
+    value: function requestRange(begin, end, listeners) {
+      var args = {
+        begin: begin,
+        end: end
+      };
 
-      if (typeof value === 'undefined') {
-        continue;
+      for (var prop in listeners) {
+        args[prop] = listeners[prop];
       }
 
-      xhr.setRequestHeader(property, value);
+      return this.request(args);
     }
-
-    if (this.isHttp && 'begin' in args && 'end' in args) {
-      var rangeStr = args.begin + '-' + (args.end - 1);
-      xhr.setRequestHeader('Range', 'bytes=' + rangeStr);
-      pendingRequest.expectedStatus = 206;
-    } else {
-      pendingRequest.expectedStatus = 200;
+  }, {
+    key: "requestFull",
+    value: function requestFull(listeners) {
+      return this.request(listeners);
     }
+  }, {
+    key: "request",
+    value: function request(args) {
+      var xhr = this.getXhr();
+      var xhrId = this.currXhrId++;
+      var pendingRequest = this.pendingRequests[xhrId] = {
+        xhr: xhr
+      };
+      xhr.open('GET', this.url);
+      xhr.withCredentials = this.withCredentials;
 
-    var useMozChunkedLoading = supportsMozChunked && !!args.onProgressiveData;
+      for (var property in this.httpHeaders) {
+        var value = this.httpHeaders[property];
 
-    if (useMozChunkedLoading) {
-      xhr.responseType = 'moz-chunked-arraybuffer';
-      pendingRequest.onProgressiveData = args.onProgressiveData;
-      pendingRequest.mozChunked = true;
-    } else {
-      xhr.responseType = 'arraybuffer';
-    }
+        if (typeof value === 'undefined') {
+          continue;
+        }
 
-    if (args.onError) {
-      xhr.onerror = function (evt) {
-        args.onError(xhr.status);
-      };
-    }
+        xhr.setRequestHeader(property, value);
+      }
 
-    xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
-    xhr.onprogress = this.onProgress.bind(this, xhrId);
-    pendingRequest.onHeadersReceived = args.onHeadersReceived;
-    pendingRequest.onDone = args.onDone;
-    pendingRequest.onError = args.onError;
-    pendingRequest.onProgress = args.onProgress;
-    xhr.send(null);
-    return xhrId;
-  },
-  onProgress: function NetworkManager_onProgress(xhrId, evt) {
-    var pendingRequest = this.pendingRequests[xhrId];
-
-    if (!pendingRequest) {
-      return;
-    }
+      if (this.isHttp && 'begin' in args && 'end' in args) {
+        xhr.setRequestHeader('Range', "bytes=".concat(args.begin, "-").concat(args.end - 1));
+        pendingRequest.expectedStatus = PARTIAL_CONTENT_RESPONSE;
+      } else {
+        pendingRequest.expectedStatus = OK_RESPONSE;
+      }
 
-    if (pendingRequest.mozChunked) {
-      var chunk = getArrayBuffer(pendingRequest.xhr);
-      pendingRequest.onProgressiveData(chunk);
-    }
+      xhr.responseType = 'arraybuffer';
 
-    var onProgress = pendingRequest.onProgress;
+      if (args.onError) {
+        xhr.onerror = function (evt) {
+          args.onError(xhr.status);
+        };
+      }
 
-    if (onProgress) {
-      onProgress(evt);
-    }
-  },
-  onStateChange: function NetworkManager_onStateChange(xhrId, evt) {
-    var pendingRequest = this.pendingRequests[xhrId];
+      xhr.onreadystatechange = this.onStateChange.bind(this, xhrId);
+      xhr.onprogress = this.onProgress.bind(this, xhrId);
+      pendingRequest.onHeadersReceived = args.onHeadersReceived;
+      pendingRequest.onDone = args.onDone;
+      pendingRequest.onError = args.onError;
+      pendingRequest.onProgress = args.onProgress;
+      xhr.send(null);
+      return xhrId;
+    }
+  }, {
+    key: "onProgress",
+    value: function onProgress(xhrId, evt) {
+      var pendingRequest = this.pendingRequests[xhrId];
+
+      if (!pendingRequest) {
+        return;
+      }
 
-    if (!pendingRequest) {
-      return;
+      if (pendingRequest.onProgress) {
+        pendingRequest.onProgress(evt);
+      }
     }
+  }, {
+    key: "onStateChange",
+    value: function onStateChange(xhrId, evt) {
+      var pendingRequest = this.pendingRequests[xhrId];
 
-    var xhr = pendingRequest.xhr;
+      if (!pendingRequest) {
+        return;
+      }
 
-    if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
-      pendingRequest.onHeadersReceived();
-      delete pendingRequest.onHeadersReceived;
-    }
+      var xhr = pendingRequest.xhr;
 
-    if (xhr.readyState !== 4) {
-      return;
-    }
+      if (xhr.readyState >= 2 && pendingRequest.onHeadersReceived) {
+        pendingRequest.onHeadersReceived();
+        delete pendingRequest.onHeadersReceived;
+      }
 
-    if (!(xhrId in this.pendingRequests)) {
-      return;
-    }
+      if (xhr.readyState !== 4) {
+        return;
+      }
+
+      if (!(xhrId in this.pendingRequests)) {
+        return;
+      }
 
-    delete this.pendingRequests[xhrId];
+      delete this.pendingRequests[xhrId];
 
-    if (xhr.status === 0 && this.isHttp) {
-      if (pendingRequest.onError) {
-        pendingRequest.onError(xhr.status);
+      if (xhr.status === 0 && this.isHttp) {
+        if (pendingRequest.onError) {
+          pendingRequest.onError(xhr.status);
+        }
+
+        return;
       }
 
-      return;
-    }
+      var xhrStatus = xhr.status || OK_RESPONSE;
+      var ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
 
-    var xhrStatus = xhr.status || OK_RESPONSE;
-    var ok_response_on_range_request = xhrStatus === OK_RESPONSE && pendingRequest.expectedStatus === PARTIAL_CONTENT_RESPONSE;
+      if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
+        if (pendingRequest.onError) {
+          pendingRequest.onError(xhr.status);
+        }
 
-    if (!ok_response_on_range_request && xhrStatus !== pendingRequest.expectedStatus) {
-      if (pendingRequest.onError) {
-        pendingRequest.onError(xhr.status);
+        return;
       }
 
-      return;
+      var chunk = getArrayBuffer(xhr);
+
+      if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
+        var rangeHeader = xhr.getResponseHeader('Content-Range');
+        var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
+        pendingRequest.onDone({
+          begin: parseInt(matches[1], 10),
+          chunk: chunk
+        });
+      } else if (chunk) {
+        pendingRequest.onDone({
+          begin: 0,
+          chunk: chunk
+        });
+      } else if (pendingRequest.onError) {
+        pendingRequest.onError(xhr.status);
+      }
     }
+  }, {
+    key: "hasPendingRequests",
+    value: function hasPendingRequests() {
+      for (var xhrId in this.pendingRequests) {
+        return true;
+      }
 
-    this.loadedRequests[xhrId] = true;
-    var chunk = getArrayBuffer(xhr);
-
-    if (xhrStatus === PARTIAL_CONTENT_RESPONSE) {
-      var rangeHeader = xhr.getResponseHeader('Content-Range');
-      var matches = /bytes (\d+)-(\d+)\/(\d+)/.exec(rangeHeader);
-      var begin = parseInt(matches[1], 10);
-      pendingRequest.onDone({
-        begin: begin,
-        chunk: chunk
-      });
-    } else if (pendingRequest.onProgressiveData) {
-      pendingRequest.onDone(null);
-    } else if (chunk) {
-      pendingRequest.onDone({
-        begin: 0,
-        chunk: chunk
-      });
-    } else if (pendingRequest.onError) {
-      pendingRequest.onError(xhr.status);
+      return false;
     }
-  },
-  hasPendingRequests: function NetworkManager_hasPendingRequests() {
-    for (var xhrId in this.pendingRequests) {
-      return true;
+  }, {
+    key: "getRequestXhr",
+    value: function getRequestXhr(xhrId) {
+      return this.pendingRequests[xhrId].xhr;
     }
-
-    return false;
-  },
-  getRequestXhr: function NetworkManager_getXhr(xhrId) {
-    return this.pendingRequests[xhrId].xhr;
-  },
-  isStreamingRequest: function NetworkManager_isStreamingRequest(xhrId) {
-    return !!this.pendingRequests[xhrId].onProgressiveData;
-  },
-  isPendingRequest: function NetworkManager_isPendingRequest(xhrId) {
-    return xhrId in this.pendingRequests;
-  },
-  isLoadedRequest: function NetworkManager_isLoadedRequest(xhrId) {
-    return xhrId in this.loadedRequests;
-  },
-  abortAllRequests: function NetworkManager_abortAllRequests() {
-    for (var xhrId in this.pendingRequests) {
-      this.abortRequest(xhrId | 0);
+  }, {
+    key: "isPendingRequest",
+    value: function isPendingRequest(xhrId) {
+      return xhrId in this.pendingRequests;
+    }
+  }, {
+    key: "abortAllRequests",
+    value: function abortAllRequests() {
+      for (var xhrId in this.pendingRequests) {
+        this.abortRequest(xhrId | 0);
+      }
     }
-  },
-  abortRequest: function NetworkManager_abortRequest(xhrId) {
-    var xhr = this.pendingRequests[xhrId].xhr;
-    delete this.pendingRequests[xhrId];
-    xhr.abort();
+  }, {
+    key: "abortRequest",
+    value: function abortRequest(xhrId) {
+      var xhr = this.pendingRequests[xhrId].xhr;
+      delete this.pendingRequests[xhrId];
+      xhr.abort();
+    }
+  }]);
+
+  return NetworkManager;
+}();
+
+var PDFNetworkStream =
+/*#__PURE__*/
+function () {
+  function PDFNetworkStream(source) {
+    _classCallCheck(this, PDFNetworkStream);
+
+    this._source = source;
+    this._manager = new NetworkManager(source.url, {
+      httpHeaders: source.httpHeaders,
+      withCredentials: source.withCredentials
+    });
+    this._rangeChunkSize = source.rangeChunkSize;
+    this._fullRequestReader = null;
+    this._rangeRequestReaders = [];
   }
-};
-
-function PDFNetworkStream(source) {
-  this._source = source;
-  this._manager = new NetworkManager(source.url, {
-    httpHeaders: source.httpHeaders,
-    withCredentials: source.withCredentials
-  });
-  this._rangeChunkSize = source.rangeChunkSize;
-  this._fullRequestReader = null;
-  this._rangeRequestReaders = [];
-}
 
-PDFNetworkStream.prototype = {
-  _onRangeRequestReaderClosed: function PDFNetworkStream_onRangeRequestReaderClosed(reader) {
-    var i = this._rangeRequestReaders.indexOf(reader);
+  _createClass(PDFNetworkStream, [{
+    key: "_onRangeRequestReaderClosed",
+    value: function _onRangeRequestReaderClosed(reader) {
+      var i = this._rangeRequestReaders.indexOf(reader);
 
-    if (i >= 0) {
-      this._rangeRequestReaders.splice(i, 1);
+      if (i >= 0) {
+        this._rangeRequestReaders.splice(i, 1);
+      }
     }
-  },
-  getFullReader: function PDFNetworkStream_getFullReader() {
-    (0, _util.assert)(!this._fullRequestReader);
-    this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
-    return this._fullRequestReader;
-  },
-  getRangeReader: function PDFNetworkStream_getRangeReader(begin, end) {
-    var reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
-    reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
-
-    this._rangeRequestReaders.push(reader);
-
-    return reader;
-  },
-  cancelAllRequests: function PDFNetworkStream_cancelAllRequests(reason) {
-    if (this._fullRequestReader) {
-      this._fullRequestReader.cancel(reason);
+  }, {
+    key: "getFullReader",
+    value: function getFullReader() {
+      (0, _util.assert)(!this._fullRequestReader);
+      this._fullRequestReader = new PDFNetworkStreamFullRequestReader(this._manager, this._source);
+      return this._fullRequestReader;
     }
+  }, {
+    key: "getRangeReader",
+    value: function getRangeReader(begin, end) {
+      var reader = new PDFNetworkStreamRangeRequestReader(this._manager, begin, end);
+      reader.onClosed = this._onRangeRequestReaderClosed.bind(this);
 
-    var readers = this._rangeRequestReaders.slice(0);
+      this._rangeRequestReaders.push(reader);
 
-    readers.forEach(function (reader) {
-      reader.cancel(reason);
-    });
-  }
-};
-
-function PDFNetworkStreamFullRequestReader(manager, source) {
-  this._manager = manager;
-  var args = {
-    onHeadersReceived: this._onHeadersReceived.bind(this),
-    onProgressiveData: source.disableStream ? null : this._onProgressiveData.bind(this),
-    onDone: this._onDone.bind(this),
-    onError: this._onError.bind(this),
-    onProgress: this._onProgress.bind(this)
-  };
-  this._url = source.url;
-  this._fullRequestId = manager.requestFull(args);
-  this._headersReceivedCapability = (0, _util.createPromiseCapability)();
-  this._disableRange = source.disableRange || false;
-  this._contentLength = source.length;
-  this._rangeChunkSize = source.rangeChunkSize;
-
-  if (!this._rangeChunkSize && !this._disableRange) {
-    this._disableRange = true;
-  }
+      return reader;
+    }
+  }, {
+    key: "cancelAllRequests",
+    value: function cancelAllRequests(reason) {
+      if (this._fullRequestReader) {
+        this._fullRequestReader.cancel(reason);
+      }
 
-  this._isStreamingSupported = false;
-  this._isRangeSupported = false;
-  this._cachedChunks = [];
-  this._requests = [];
-  this._done = false;
-  this._storedError = undefined;
-  this._filename = null;
-  this.onProgress = null;
-}
+      var readers = this._rangeRequestReaders.slice(0);
 
-PDFNetworkStreamFullRequestReader.prototype = {
-  _onHeadersReceived: function PDFNetworkStreamFullRequestReader_onHeadersReceived() {
-    var fullRequestXhrId = this._fullRequestId;
+      readers.forEach(function (reader) {
+        reader.cancel(reason);
+      });
+    }
+  }]);
+
+  return PDFNetworkStream;
+}();
+
+exports.PDFNetworkStream = PDFNetworkStream;
 
-    var fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
+var PDFNetworkStreamFullRequestReader =
+/*#__PURE__*/
+function () {
+  function PDFNetworkStreamFullRequestReader(manager, source) {
+    _classCallCheck(this, PDFNetworkStreamFullRequestReader);
 
-    var getResponseHeader = function getResponseHeader(name) {
-      return fullRequestXhr.getResponseHeader(name);
+    this._manager = manager;
+    var args = {
+      onHeadersReceived: this._onHeadersReceived.bind(this),
+      onDone: this._onDone.bind(this),
+      onError: this._onError.bind(this),
+      onProgress: this._onProgress.bind(this)
     };
+    this._url = source.url;
+    this._fullRequestId = manager.requestFull(args);
+    this._headersReceivedCapability = (0, _util.createPromiseCapability)();
+    this._disableRange = source.disableRange || false;
+    this._contentLength = source.length;
+    this._rangeChunkSize = source.rangeChunkSize;
 
-    var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
-      getResponseHeader: getResponseHeader,
-      isHttp: this._manager.isHttp,
-      rangeChunkSize: this._rangeChunkSize,
-      disableRange: this._disableRange
-    }),
-        allowRangeRequests = _validateRangeRequest.allowRangeRequests,
-        suggestedLength = _validateRangeRequest.suggestedLength;
-
-    if (allowRangeRequests) {
-      this._isRangeSupported = true;
+    if (!this._rangeChunkSize && !this._disableRange) {
+      this._disableRange = true;
     }
 
-    this._contentLength = suggestedLength || this._contentLength;
-    this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
-    var networkManager = this._manager;
+    this._isStreamingSupported = false;
+    this._isRangeSupported = false;
+    this._cachedChunks = [];
+    this._requests = [];
+    this._done = false;
+    this._storedError = undefined;
+    this._filename = null;
+    this.onProgress = null;
+  }
 
-    if (networkManager.isStreamingRequest(fullRequestXhrId)) {
-      this._isStreamingSupported = true;
-    } else if (this._isRangeSupported) {
-      networkManager.abortRequest(fullRequestXhrId);
-    }
+  _createClass(PDFNetworkStreamFullRequestReader, [{
+    key: "_onHeadersReceived",
+    value: function _onHeadersReceived() {
+      var fullRequestXhrId = this._fullRequestId;
 
-    this._headersReceivedCapability.resolve();
-  },
-  _onProgressiveData: function PDFNetworkStreamFullRequestReader_onProgressiveData(chunk) {
-    if (this._requests.length > 0) {
-      var requestCapability = this._requests.shift();
+      var fullRequestXhr = this._manager.getRequestXhr(fullRequestXhrId);
 
-      requestCapability.resolve({
-        value: chunk,
-        done: false
-      });
-    } else {
-      this._cachedChunks.push(chunk);
-    }
-  },
-  _onDone: function PDFNetworkStreamFullRequestReader_onDone(args) {
-    if (args) {
-      this._onProgressiveData(args.chunk);
-    }
+      var getResponseHeader = function getResponseHeader(name) {
+        return fullRequestXhr.getResponseHeader(name);
+      };
 
-    this._done = true;
+      var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
+        getResponseHeader: getResponseHeader,
+        isHttp: this._manager.isHttp,
+        rangeChunkSize: this._rangeChunkSize,
+        disableRange: this._disableRange
+      }),
+          allowRangeRequests = _validateRangeRequest.allowRangeRequests,
+          suggestedLength = _validateRangeRequest.suggestedLength;
+
+      if (allowRangeRequests) {
+        this._isRangeSupported = true;
+      }
 
-    if (this._cachedChunks.length > 0) {
-      return;
-    }
+      this._contentLength = suggestedLength || this._contentLength;
+      this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
 
-    this._requests.forEach(function (requestCapability) {
-      requestCapability.resolve({
-        value: undefined,
-        done: true
-      });
-    });
+      if (this._isRangeSupported) {
+        this._manager.abortRequest(fullRequestXhrId);
+      }
 
-    this._requests = [];
-  },
-  _onError: function PDFNetworkStreamFullRequestReader_onError(status) {
-    var url = this._url;
-    var exception = (0, _network_utils.createResponseStatusError)(status, url);
-    this._storedError = exception;
+      this._headersReceivedCapability.resolve();
+    }
+  }, {
+    key: "_onDone",
+    value: function _onDone(args) {
+      if (args) {
+        if (this._requests.length > 0) {
+          var requestCapability = this._requests.shift();
+
+          requestCapability.resolve({
+            value: args.chunk,
+            done: false
+          });
+        } else {
+          this._cachedChunks.push(args.chunk);
+        }
+      }
 
-    this._headersReceivedCapability.reject(exception);
+      this._done = true;
 
-    this._requests.forEach(function (requestCapability) {
-      requestCapability.reject(exception);
-    });
+      if (this._cachedChunks.length > 0) {
+        return;
+      }
 
-    this._requests = [];
-    this._cachedChunks = [];
-  },
-  _onProgress: function PDFNetworkStreamFullRequestReader_onProgress(data) {
-    if (this.onProgress) {
-      this.onProgress({
-        loaded: data.loaded,
-        total: data.lengthComputable ? data.total : this._contentLength
+      this._requests.forEach(function (requestCapability) {
+        requestCapability.resolve({
+          value: undefined,
+          done: true
+        });
+      });
+
+      this._requests = [];
+    }
+  }, {
+    key: "_onError",
+    value: function _onError(status) {
+      var url = this._url;
+      var exception = (0, _network_utils.createResponseStatusError)(status, url);
+      this._storedError = exception;
+
+      this._headersReceivedCapability.reject(exception);
+
+      this._requests.forEach(function (requestCapability) {
+        requestCapability.reject(exception);
       });
+
+      this._requests = [];
+      this._cachedChunks = [];
+    }
+  }, {
+    key: "_onProgress",
+    value: function _onProgress(data) {
+      if (this.onProgress) {
+        this.onProgress({
+          loaded: data.loaded,
+          total: data.lengthComputable ? data.total : this._contentLength
+        });
+      }
     }
-  },
-
-  get filename() {
-    return this._filename;
-  },
-
-  get isRangeSupported() {
-    return this._isRangeSupported;
-  },
-
-  get isStreamingSupported() {
-    return this._isStreamingSupported;
-  },
-
-  get contentLength() {
-    return this._contentLength;
-  },
-
-  get headersReady() {
-    return this._headersReceivedCapability.promise;
-  },
-
-  read: function () {
-    var _read = _asyncToGenerator(
-    /*#__PURE__*/
-    _regenerator.default.mark(function _callee() {
-      var chunk, requestCapability;
-      return _regenerator.default.wrap(function _callee$(_context) {
-        while (1) {
-          switch (_context.prev = _context.next) {
-            case 0:
-              if (!this._storedError) {
-                _context.next = 2;
-                break;
-              }
-
-              throw this._storedError;
-
-            case 2:
-              if (!(this._cachedChunks.length > 0)) {
-                _context.next = 5;
-                break;
-              }
-
-              chunk = this._cachedChunks.shift();
-              return _context.abrupt("return", {
-                value: chunk,
-                done: false
-              });
-
-            case 5:
-              if (!this._done) {
-                _context.next = 7;
-                break;
-              }
-
-              return _context.abrupt("return", {
-                value: undefined,
-                done: true
-              });
-
-            case 7:
-              requestCapability = (0, _util.createPromiseCapability)();
-
-              this._requests.push(requestCapability);
-
-              return _context.abrupt("return", requestCapability.promise);
-
-            case 10:
-            case "end":
-              return _context.stop();
+  }, {
+    key: "read",
+    value: function () {
+      var _read = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee() {
+        var chunk, requestCapability;
+        return _regenerator["default"].wrap(function _callee$(_context) {
+          while (1) {
+            switch (_context.prev = _context.next) {
+              case 0:
+                if (!this._storedError) {
+                  _context.next = 2;
+                  break;
+                }
+
+                throw this._storedError;
+
+              case 2:
+                if (!(this._cachedChunks.length > 0)) {
+                  _context.next = 5;
+                  break;
+                }
+
+                chunk = this._cachedChunks.shift();
+                return _context.abrupt("return", {
+                  value: chunk,
+                  done: false
+                });
+
+              case 5:
+                if (!this._done) {
+                  _context.next = 7;
+                  break;
+                }
+
+                return _context.abrupt("return", {
+                  value: undefined,
+                  done: true
+                });
+
+              case 7:
+                requestCapability = (0, _util.createPromiseCapability)();
+
+                this._requests.push(requestCapability);
+
+                return _context.abrupt("return", requestCapability.promise);
+
+              case 10:
+              case "end":
+                return _context.stop();
+            }
           }
-        }
-      }, _callee, this);
-    }));
+        }, _callee, this);
+      }));
 
-    function read() {
-      return _read.apply(this, arguments);
-    }
+      function read() {
+        return _read.apply(this, arguments);
+      }
 
-    return read;
-  }(),
-  cancel: function PDFNetworkStreamFullRequestReader_cancel(reason) {
-    this._done = true;
+      return read;
+    }()
+  }, {
+    key: "cancel",
+    value: function cancel(reason) {
+      this._done = true;
 
-    this._headersReceivedCapability.reject(reason);
+      this._headersReceivedCapability.reject(reason);
 
-    this._requests.forEach(function (requestCapability) {
-      requestCapability.resolve({
-        value: undefined,
-        done: true
+      this._requests.forEach(function (requestCapability) {
+        requestCapability.resolve({
+          value: undefined,
+          done: true
+        });
       });
-    });
 
-    this._requests = [];
+      this._requests = [];
 
-    if (this._manager.isPendingRequest(this._fullRequestId)) {
-      this._manager.abortRequest(this._fullRequestId);
+      if (this._manager.isPendingRequest(this._fullRequestId)) {
+        this._manager.abortRequest(this._fullRequestId);
+      }
+
+      this._fullRequestReader = null;
+    }
+  }, {
+    key: "filename",
+    get: function get() {
+      return this._filename;
+    }
+  }, {
+    key: "isRangeSupported",
+    get: function get() {
+      return this._isRangeSupported;
+    }
+  }, {
+    key: "isStreamingSupported",
+    get: function get() {
+      return this._isStreamingSupported;
+    }
+  }, {
+    key: "contentLength",
+    get: function get() {
+      return this._contentLength;
+    }
+  }, {
+    key: "headersReady",
+    get: function get() {
+      return this._headersReceivedCapability.promise;
     }
+  }]);
 
-    this._fullRequestReader = null;
+  return PDFNetworkStreamFullRequestReader;
+}();
+
+var PDFNetworkStreamRangeRequestReader =
+/*#__PURE__*/
+function () {
+  function PDFNetworkStreamRangeRequestReader(manager, begin, end) {
+    _classCallCheck(this, PDFNetworkStreamRangeRequestReader);
+
+    this._manager = manager;
+    var args = {
+      onDone: this._onDone.bind(this),
+      onProgress: this._onProgress.bind(this)
+    };
+    this._requestId = manager.requestRange(begin, end, args);
+    this._requests = [];
+    this._queuedChunk = null;
+    this._done = false;
+    this.onProgress = null;
+    this.onClosed = null;
   }
-};
-
-function PDFNetworkStreamRangeRequestReader(manager, begin, end) {
-  this._manager = manager;
-  var args = {
-    onDone: this._onDone.bind(this),
-    onProgress: this._onProgress.bind(this)
-  };
-  this._requestId = manager.requestRange(begin, end, args);
-  this._requests = [];
-  this._queuedChunk = null;
-  this._done = false;
-  this.onProgress = null;
-  this.onClosed = null;
-}
 
-PDFNetworkStreamRangeRequestReader.prototype = {
-  _close: function PDFNetworkStreamRangeRequestReader_close() {
-    if (this.onClosed) {
-      this.onClosed(this);
+  _createClass(PDFNetworkStreamRangeRequestReader, [{
+    key: "_close",
+    value: function _close() {
+      if (this.onClosed) {
+        this.onClosed(this);
+      }
     }
-  },
-  _onDone: function PDFNetworkStreamRangeRequestReader_onDone(data) {
-    var chunk = data.chunk;
+  }, {
+    key: "_onDone",
+    value: function _onDone(data) {
+      var chunk = data.chunk;
 
-    if (this._requests.length > 0) {
-      var requestCapability = this._requests.shift();
+      if (this._requests.length > 0) {
+        var requestCapability = this._requests.shift();
 
-      requestCapability.resolve({
-        value: chunk,
-        done: false
-      });
-    } else {
-      this._queuedChunk = chunk;
-    }
+        requestCapability.resolve({
+          value: chunk,
+          done: false
+        });
+      } else {
+        this._queuedChunk = chunk;
+      }
 
-    this._done = true;
+      this._done = true;
 
-    this._requests.forEach(function (requestCapability) {
-      requestCapability.resolve({
-        value: undefined,
-        done: true
+      this._requests.forEach(function (requestCapability) {
+        requestCapability.resolve({
+          value: undefined,
+          done: true
+        });
       });
-    });
 
-    this._requests = [];
+      this._requests = [];
 
-    this._close();
-  },
-  _onProgress: function PDFNetworkStreamRangeRequestReader_onProgress(evt) {
-    if (!this.isStreamingSupported && this.onProgress) {
-      this.onProgress({
-        loaded: evt.loaded
-      });
+      this._close();
     }
-  },
-
-  get isStreamingSupported() {
-    return false;
-  },
-
-  read: function () {
-    var _read2 = _asyncToGenerator(
-    /*#__PURE__*/
-    _regenerator.default.mark(function _callee2() {
-      var chunk, requestCapability;
-      return _regenerator.default.wrap(function _callee2$(_context2) {
-        while (1) {
-          switch (_context2.prev = _context2.next) {
-            case 0:
-              if (!(this._queuedChunk !== null)) {
-                _context2.next = 4;
-                break;
-              }
-
-              chunk = this._queuedChunk;
-              this._queuedChunk = null;
-              return _context2.abrupt("return", {
-                value: chunk,
-                done: false
-              });
-
-            case 4:
-              if (!this._done) {
-                _context2.next = 6;
-                break;
-              }
-
-              return _context2.abrupt("return", {
-                value: undefined,
-                done: true
-              });
-
-            case 6:
-              requestCapability = (0, _util.createPromiseCapability)();
-
-              this._requests.push(requestCapability);
-
-              return _context2.abrupt("return", requestCapability.promise);
-
-            case 9:
-            case "end":
-              return _context2.stop();
-          }
-        }
-      }, _callee2, this);
-    }));
-
-    function read() {
-      return _read2.apply(this, arguments);
+  }, {
+    key: "_onProgress",
+    value: function _onProgress(evt) {
+      if (!this.isStreamingSupported && this.onProgress) {
+        this.onProgress({
+          loaded: evt.loaded
+        });
+      }
     }
+  }, {
+    key: "read",
+    value: function () {
+      var _read2 = _asyncToGenerator(
+      /*#__PURE__*/
+      _regenerator["default"].mark(function _callee2() {
+        var chunk, requestCapability;
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
+          while (1) {
+            switch (_context2.prev = _context2.next) {
+              case 0:
+                if (!(this._queuedChunk !== null)) {
+                  _context2.next = 4;
+                  break;
+                }
+
+                chunk = this._queuedChunk;
+                this._queuedChunk = null;
+                return _context2.abrupt("return", {
+                  value: chunk,
+                  done: false
+                });
+
+              case 4:
+                if (!this._done) {
+                  _context2.next = 6;
+                  break;
+                }
+
+                return _context2.abrupt("return", {
+                  value: undefined,
+                  done: true
+                });
+
+              case 6:
+                requestCapability = (0, _util.createPromiseCapability)();
+
+                this._requests.push(requestCapability);
+
+                return _context2.abrupt("return", requestCapability.promise);
+
+              case 9:
+              case "end":
+                return _context2.stop();
+            }
+          }
+        }, _callee2, this);
+      }));
 
-    return read;
-  }(),
-  cancel: function PDFNetworkStreamRangeRequestReader_cancel(reason) {
-    this._done = true;
+      function read() {
+        return _read2.apply(this, arguments);
+      }
 
-    this._requests.forEach(function (requestCapability) {
-      requestCapability.resolve({
-        value: undefined,
-        done: true
+      return read;
+    }()
+  }, {
+    key: "cancel",
+    value: function cancel(reason) {
+      this._done = true;
+
+      this._requests.forEach(function (requestCapability) {
+        requestCapability.resolve({
+          value: undefined,
+          done: true
+        });
       });
-    });
 
-    this._requests = [];
+      this._requests = [];
 
-    if (this._manager.isPendingRequest(this._requestId)) {
-      this._manager.abortRequest(this._requestId);
+      if (this._manager.isPendingRequest(this._requestId)) {
+        this._manager.abortRequest(this._requestId);
+      }
+
+      this._close();
     }
+  }, {
+    key: "isStreamingSupported",
+    get: function get() {
+      return false;
+    }
+  }]);
 
-    this._close();
-  }
-};
+  return PDFNetworkStreamRangeRequestReader;
+}();

+ 1 - 1
lib/display/network_utils.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 21 - 12
lib/display/node_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,7 +32,7 @@ var _util = require("../shared/util");
 
 var _network_utils = require("./network_utils");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
@@ -95,20 +95,24 @@ function () {
     this.isHttp = this.url.protocol === 'http:' || this.url.protocol === 'https:';
     this.isFsUrl = this.url.protocol === 'file:';
     this.httpHeaders = this.isHttp && source.httpHeaders || {};
-    this._fullRequest = null;
+    this._fullRequestReader = null;
     this._rangeRequestReaders = [];
   }
 
   _createClass(PDFNodeStream, [{
     key: "getFullReader",
     value: function getFullReader() {
-      (0, _util.assert)(!this._fullRequest);
-      this._fullRequest = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
-      return this._fullRequest;
+      (0, _util.assert)(!this._fullRequestReader);
+      this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
+      return this._fullRequestReader;
     }
   }, {
     key: "getRangeReader",
     value: function getRangeReader(start, end) {
+      if (end <= this._progressiveDataLength) {
+        return null;
+      }
+
       var rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
 
       this._rangeRequestReaders.push(rangeReader);
@@ -118,8 +122,8 @@ function () {
   }, {
     key: "cancelAllRequests",
     value: function cancelAllRequests(reason) {
-      if (this._fullRequest) {
-        this._fullRequest.cancel(reason);
+      if (this._fullRequestReader) {
+        this._fullRequestReader.cancel(reason);
       }
 
       var readers = this._rangeRequestReaders.slice(0);
@@ -128,6 +132,11 @@ function () {
         reader.cancel(reason);
       });
     }
+  }, {
+    key: "_progressiveDataLength",
+    get: function get() {
+      return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
+    }
   }]);
 
   return PDFNodeStream;
@@ -168,9 +177,9 @@ function () {
     value: function () {
       var _read = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee() {
+      _regenerator["default"].mark(function _callee() {
         var chunk, buffer;
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -334,9 +343,9 @@ function () {
     value: function () {
       var _read2 = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee2() {
+      _regenerator["default"].mark(function _callee2() {
         var chunk, buffer;
-        return _regenerator.default.wrap(function _callee2$(_context2) {
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
           while (1) {
             switch (_context2.prev = _context2.next) {
               case 0:

+ 24 - 25
lib/display/pattern_helper.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -361,42 +361,42 @@ var TilingPattern = function TilingPatternClosure() {
           y0 = bbox[1],
           x1 = bbox[2],
           y1 = bbox[3];
-      var topLeft = [x0, y0];
-      var botRight = [x0 + xstep, y0 + ystep];
-      var width = botRight[0] - topLeft[0];
-      var height = botRight[1] - topLeft[1];
 
       var matrixScale = _util.Util.singularValueDecompose2dScale(this.matrix);
 
       var curMatrixScale = _util.Util.singularValueDecompose2dScale(this.baseTransform);
 
       var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]];
-      width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE);
-      height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE);
-      var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true);
+      var dimx = this.getSizeAndScale(xstep, this.ctx.canvas.width, combinedScale[0]);
+      var dimy = this.getSizeAndScale(ystep, this.ctx.canvas.height, combinedScale[1]);
+      var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', dimx.size, dimy.size, true);
       var tmpCtx = tmpCanvas.context;
       var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx);
       graphics.groupLevel = owner.groupLevel;
       this.setFillAndStrokeStyleToContext(graphics, paintType, color);
-      this.setScale(width, height, xstep, ystep);
-      this.transformToScale(graphics);
-      var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]];
-      graphics.transform.apply(graphics, tmpTranslate);
+      graphics.transform(dimx.scale, 0, 0, dimy.scale, 0, 0);
+      graphics.transform(1, 0, 0, 1, -x0, -y0);
       this.clipBbox(graphics, bbox, x0, y0, x1, y1);
       graphics.executeOperatorList(operatorList);
+      this.ctx.transform(1, 0, 0, 1, x0, y0);
+      this.ctx.scale(1 / dimx.scale, 1 / dimy.scale);
       return tmpCanvas.canvas;
     },
-    setScale: function TilingPattern_setScale(width, height, xstep, ystep) {
-      this.scale = [width / xstep, height / ystep];
-    },
-    transformToScale: function TilingPattern_transformToScale(graphics) {
-      var scale = this.scale;
-      var tmpScale = [scale[0], 0, 0, scale[1], 0, 0];
-      graphics.transform.apply(graphics, tmpScale);
-    },
-    scaleToContext: function TilingPattern_scaleToContext() {
-      var scale = this.scale;
-      this.ctx.scale(1 / scale[0], 1 / scale[1]);
+    getSizeAndScale: function TilingPattern_getSizeAndScale(step, realOutputSize, scale) {
+      step = Math.abs(step);
+      var maxSize = Math.max(MAX_PATTERN_SIZE, realOutputSize);
+      var size = Math.ceil(step * scale);
+
+      if (size >= maxSize) {
+        size = maxSize;
+      } else {
+        scale = size / step;
+      }
+
+      return {
+        scale: scale,
+        size: size
+      };
     },
     clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) {
       if (Array.isArray(bbox) && bbox.length === 4) {
@@ -434,11 +434,10 @@ var TilingPattern = function TilingPatternClosure() {
       }
     },
     getPattern: function TilingPattern_getPattern(ctx, owner) {
-      var temporaryPatternCanvas = this.createPatternCanvas(owner);
       ctx = this.ctx;
       ctx.setTransform.apply(ctx, this.baseTransform);
       ctx.transform.apply(ctx, this.matrix);
-      this.scaleToContext();
+      var temporaryPatternCanvas = this.createPatternCanvas(owner);
       return ctx.createPattern(temporaryPatternCanvas, 'repeat');
     }
   };

Dosya farkı çok büyük olduğundan ihmal edildi
+ 475 - 338
lib/display/svg.js


+ 24 - 14
lib/display/text_layer.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ var _util = require("../shared/util");
 
 var _global_scope = _interopRequireDefault(require("../shared/global_scope"));
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 var renderTextLayer = function renderTextLayerClosure() {
   var MAX_TEXT_DIVS_TO_RENDER = 100000;
@@ -449,6 +449,8 @@ var renderTextLayer = function renderTextLayerClosure() {
   }
 
   function TextLayerRenderTask(_ref) {
+    var _this = this;
+
     var textContent = _ref.textContent,
         textContentStream = _ref.textContentStream,
         container = _ref.container,
@@ -463,7 +465,7 @@ var renderTextLayer = function renderTextLayerClosure() {
     this._textDivs = textDivs || [];
     this._textContentItemsStr = textContentItemsStr || [];
     this._enhanceTextSelection = !!enhanceTextSelection;
-    this._fontInspectorEnabled = !!(_global_scope.default.FontInspector && _global_scope.default.FontInspector.enabled);
+    this._fontInspectorEnabled = !!(_global_scope["default"].FontInspector && _global_scope["default"].FontInspector.enabled);
     this._reader = null;
     this._layoutTextLastFontSize = null;
     this._layoutTextLastFontFamily = null;
@@ -474,6 +476,14 @@ var renderTextLayer = function renderTextLayerClosure() {
     this._capability = (0, _util.createPromiseCapability)();
     this._renderTimer = null;
     this._bounds = [];
+
+    this._capability.promise["finally"](function () {
+      if (_this._layoutTextCtx) {
+        _this._layoutTextCtx.canvas.width = 0;
+        _this._layoutTextCtx.canvas.height = 0;
+        _this._layoutTextCtx = null;
+      }
+    });
   }
 
   TextLayerRenderTask.prototype = {
@@ -482,20 +492,20 @@ var renderTextLayer = function renderTextLayerClosure() {
     },
 
     cancel: function TextLayer_cancel() {
+      this._canceled = true;
+
       if (this._reader) {
-        this._reader.cancel(new _util.AbortException('text layer task cancelled'));
+        this._reader.cancel(new _util.AbortException('TextLayer task cancelled.'));
 
         this._reader = null;
       }
 
-      this._canceled = true;
-
       if (this._renderTimer !== null) {
         clearTimeout(this._renderTimer);
         this._renderTimer = null;
       }
 
-      this._capability.reject('canceled');
+      this._capability.reject(new Error('TextLayer task cancelled.'));
     },
     _processItems: function _processItems(items, styleCache) {
       for (var i = 0, len = items.length; i < len; i++) {
@@ -545,7 +555,7 @@ var renderTextLayer = function renderTextLayerClosure() {
       textLayerFrag.appendChild(textDiv);
     },
     _render: function TextLayer_render(timeout) {
-      var _this = this;
+      var _this2 = this;
 
       var capability = (0, _util.createPromiseCapability)();
       var styleCache = Object.create(null);
@@ -564,7 +574,7 @@ var renderTextLayer = function renderTextLayerClosure() {
         capability.resolve();
       } else if (this._textContentStream) {
         var pump = function pump() {
-          _this._reader.read().then(function (_ref2) {
+          _this2._reader.read().then(function (_ref2) {
             var value = _ref2.value,
                 done = _ref2.done;
 
@@ -575,7 +585,7 @@ var renderTextLayer = function renderTextLayerClosure() {
 
             Object.assign(styleCache, value.styles);
 
-            _this._processItems(value.items, styleCache);
+            _this2._processItems(value.items, styleCache);
 
             pump();
           }, capability.reject);
@@ -591,11 +601,11 @@ var renderTextLayer = function renderTextLayerClosure() {
         styleCache = null;
 
         if (!timeout) {
-          render(_this);
+          render(_this2);
         } else {
-          _this._renderTimer = setTimeout(function () {
-            render(_this);
-            _this._renderTimer = null;
+          _this2._renderTimer = setTimeout(function () {
+            render(_this2);
+            _this2._renderTimer = null;
           }, timeout);
         }
       }, this._capability.reject);

+ 192 - 70
lib/display/transport_stream.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -36,12 +36,23 @@ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try
 
 function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
 
-var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var PDFDataTransportStream =
+/*#__PURE__*/
+function () {
   function PDFDataTransportStream(params, pdfDataRangeTransport) {
     var _this = this;
 
+    _classCallCheck(this, PDFDataTransportStream);
+
     (0, _util.assert)(pdfDataRangeTransport);
     this._queuedChunks = [];
+    this._progressiveDone = params.progressiveDone || false;
     var initialData = params.initialData;
 
     if (initialData && initialData.length > 0) {
@@ -64,9 +75,10 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
       });
     });
 
-    this._pdfDataRangeTransport.addProgressListener(function (loaded) {
+    this._pdfDataRangeTransport.addProgressListener(function (loaded, total) {
       _this._onProgress({
-        loaded: loaded
+        loaded: loaded,
+        total: total
       });
     });
 
@@ -76,11 +88,16 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
       });
     });
 
+    this._pdfDataRangeTransport.addProgressiveDoneListener(function () {
+      _this._onProgressiveDone();
+    });
+
     this._pdfDataRangeTransport.transportReady();
   }
 
-  PDFDataTransportStream.prototype = {
-    _onReceiveData: function PDFDataTransportStream_onReceiveData(args) {
+  _createClass(PDFDataTransportStream, [{
+    key: "_onReceiveData",
+    value: function _onReceiveData(args) {
       var buffer = new Uint8Array(args.chunk).buffer;
 
       if (args.begin === undefined) {
@@ -102,32 +119,62 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
 
         (0, _util.assert)(found);
       }
-    },
-    _onProgress: function PDFDataTransportStream_onDataProgress(evt) {
-      if (this._rangeReaders.length > 0) {
+    }
+  }, {
+    key: "_onProgress",
+    value: function _onProgress(evt) {
+      if (evt.total === undefined) {
         var firstReader = this._rangeReaders[0];
 
-        if (firstReader.onProgress) {
+        if (firstReader && firstReader.onProgress) {
           firstReader.onProgress({
             loaded: evt.loaded
           });
         }
+      } else {
+        var fullReader = this._fullRequestReader;
+
+        if (fullReader && fullReader.onProgress) {
+          fullReader.onProgress({
+            loaded: evt.loaded,
+            total: evt.total
+          });
+        }
       }
-    },
-    _removeRangeReader: function PDFDataTransportStream_removeRangeReader(reader) {
+    }
+  }, {
+    key: "_onProgressiveDone",
+    value: function _onProgressiveDone() {
+      if (this._fullRequestReader) {
+        this._fullRequestReader.progressiveDone();
+      }
+
+      this._progressiveDone = true;
+    }
+  }, {
+    key: "_removeRangeReader",
+    value: function _removeRangeReader(reader) {
       var i = this._rangeReaders.indexOf(reader);
 
       if (i >= 0) {
         this._rangeReaders.splice(i, 1);
       }
-    },
-    getFullReader: function PDFDataTransportStream_getFullReader() {
+    }
+  }, {
+    key: "getFullReader",
+    value: function getFullReader() {
       (0, _util.assert)(!this._fullRequestReader);
       var queuedChunks = this._queuedChunks;
       this._queuedChunks = null;
-      return new PDFDataTransportStreamReader(this, queuedChunks);
-    },
-    getRangeReader: function PDFDataTransportStream_getRangeReader(begin, end) {
+      return new PDFDataTransportStreamReader(this, queuedChunks, this._progressiveDone);
+    }
+  }, {
+    key: "getRangeReader",
+    value: function getRangeReader(begin, end) {
+      if (end <= this._progressiveDataLength) {
+        return null;
+      }
+
       var reader = new PDFDataTransportStreamRangeReader(this, begin, end);
 
       this._pdfDataRangeTransport.requestDataRange(begin, end);
@@ -135,8 +182,10 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
       this._rangeReaders.push(reader);
 
       return reader;
-    },
-    cancelAllRequests: function PDFDataTransportStream_cancelAllRequests(reason) {
+    }
+  }, {
+    key: "cancelAllRequests",
+    value: function cancelAllRequests(reason) {
       if (this._fullRequestReader) {
         this._fullRequestReader.cancel(reason);
       }
@@ -149,21 +198,64 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
 
       this._pdfDataRangeTransport.abort();
     }
-  };
+  }, {
+    key: "_progressiveDataLength",
+    get: function get() {
+      return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
+    }
+  }]);
+
+  return PDFDataTransportStream;
+}();
+
+exports.PDFDataTransportStream = PDFDataTransportStream;
 
+var PDFDataTransportStreamReader =
+/*#__PURE__*/
+function () {
   function PDFDataTransportStreamReader(stream, queuedChunks) {
+    var progressiveDone = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
+
+    _classCallCheck(this, PDFDataTransportStreamReader);
+
     this._stream = stream;
-    this._done = false;
+    this._done = progressiveDone || false;
     this._filename = null;
     this._queuedChunks = queuedChunks || [];
+    this._loaded = 0;
+    var _iteratorNormalCompletion = true;
+    var _didIteratorError = false;
+    var _iteratorError = undefined;
+
+    try {
+      for (var _iterator = this._queuedChunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
+        var chunk = _step.value;
+        this._loaded += chunk.byteLength;
+      }
+    } catch (err) {
+      _didIteratorError = true;
+      _iteratorError = err;
+    } finally {
+      try {
+        if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+          _iterator["return"]();
+        }
+      } finally {
+        if (_didIteratorError) {
+          throw _iteratorError;
+        }
+      }
+    }
+
     this._requests = [];
     this._headersReady = Promise.resolve();
     stream._fullRequestReader = this;
     this.onProgress = null;
   }
 
-  PDFDataTransportStreamReader.prototype = {
-    _enqueue: function PDFDataTransportStreamReader_enqueue(chunk) {
+  _createClass(PDFDataTransportStreamReader, [{
+    key: "_enqueue",
+    value: function _enqueue(chunk) {
       if (this._done) {
         return;
       }
@@ -175,38 +267,20 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
           value: chunk,
           done: false
         });
-        return;
+      } else {
+        this._queuedChunks.push(chunk);
       }
 
-      this._queuedChunks.push(chunk);
-    },
-
-    get headersReady() {
-      return this._headersReady;
-    },
-
-    get filename() {
-      return this._filename;
-    },
-
-    get isRangeSupported() {
-      return this._stream._isRangeSupported;
-    },
-
-    get isStreamingSupported() {
-      return this._stream._isStreamingSupported;
-    },
-
-    get contentLength() {
-      return this._stream._contentLength;
-    },
-
-    read: function () {
+      this._loaded += chunk.byteLength;
+    }
+  }, {
+    key: "read",
+    value: function () {
       var _read = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee() {
+      _regenerator["default"].mark(function _callee() {
         var chunk, requestCapability;
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -252,8 +326,10 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
       }
 
       return read;
-    }(),
-    cancel: function PDFDataTransportStreamReader_cancel(reason) {
+    }()
+  }, {
+    key: "cancel",
+    value: function cancel(reason) {
       this._done = true;
 
       this._requests.forEach(function (requestCapability) {
@@ -265,9 +341,51 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
 
       this._requests = [];
     }
-  };
+  }, {
+    key: "progressiveDone",
+    value: function progressiveDone() {
+      if (this._done) {
+        return;
+      }
+
+      this._done = true;
+    }
+  }, {
+    key: "headersReady",
+    get: function get() {
+      return this._headersReady;
+    }
+  }, {
+    key: "filename",
+    get: function get() {
+      return this._filename;
+    }
+  }, {
+    key: "isRangeSupported",
+    get: function get() {
+      return this._stream._isRangeSupported;
+    }
+  }, {
+    key: "isStreamingSupported",
+    get: function get() {
+      return this._stream._isStreamingSupported;
+    }
+  }, {
+    key: "contentLength",
+    get: function get() {
+      return this._stream._contentLength;
+    }
+  }]);
+
+  return PDFDataTransportStreamReader;
+}();
 
+var PDFDataTransportStreamRangeReader =
+/*#__PURE__*/
+function () {
   function PDFDataTransportStreamRangeReader(stream, begin, end) {
+    _classCallCheck(this, PDFDataTransportStreamRangeReader);
+
     this._stream = stream;
     this._begin = begin;
     this._end = end;
@@ -277,8 +395,9 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
     this.onProgress = null;
   }
 
-  PDFDataTransportStreamRangeReader.prototype = {
-    _enqueue: function PDFDataTransportStreamRangeReader_enqueue(chunk) {
+  _createClass(PDFDataTransportStreamRangeReader, [{
+    key: "_enqueue",
+    value: function _enqueue(chunk) {
       if (this._done) {
         return;
       }
@@ -306,18 +425,15 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
       this._done = true;
 
       this._stream._removeRangeReader(this);
-    },
-
-    get isStreamingSupported() {
-      return false;
-    },
-
-    read: function () {
+    }
+  }, {
+    key: "read",
+    value: function () {
       var _read2 = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee2() {
+      _regenerator["default"].mark(function _callee2() {
         var chunk, requestCapability;
-        return _regenerator.default.wrap(function _callee2$(_context2) {
+        return _regenerator["default"].wrap(function _callee2$(_context2) {
           while (1) {
             switch (_context2.prev = _context2.next) {
               case 0:
@@ -364,8 +480,10 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
       }
 
       return read;
-    }(),
-    cancel: function PDFDataTransportStreamRangeReader_cancel(reason) {
+    }()
+  }, {
+    key: "cancel",
+    value: function cancel(reason) {
       this._done = true;
 
       this._requests.forEach(function (requestCapability) {
@@ -379,8 +497,12 @@ var PDFDataTransportStream = function PDFDataTransportStreamClosure() {
 
       this._stream._removeRangeReader(this);
     }
-  };
-  return PDFDataTransportStream;
-}();
+  }, {
+    key: "isStreamingSupported",
+    get: function get() {
+      return false;
+    }
+  }]);
 
-exports.PDFDataTransportStream = PDFDataTransportStream;
+  return PDFDataTransportStreamRangeReader;
+}();

+ 1 - 1
lib/display/webgl.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/display/worker_options.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/display/xml_parser.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 4 - 1
lib/examples/node/domstubs.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -129,6 +129,9 @@ DOMElement.prototype = {
       childNodes.push(element);
     }
   },
+  hasChildNodes: function DOMElement_hasChildNodes() {
+    return this.childNodes.length !== 0;
+  },
   cloneNode: function DOMElement_cloneNode() {
     var newNode = new DOMElement(this.nodeName);
     newNode.childNodes = this.childNodes;

+ 20 - 15
lib/pdf.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@
  */
 'use strict';
 
-var pdfjsVersion = '2.1.266';
-var pdfjsBuild = '81f5835c';
+var pdfjsVersion = '2.2.228';
+var pdfjsBuild = 'd7afb74a';
 
 var pdfjsSharedUtil = require('./shared/util.js');
 
@@ -32,7 +32,7 @@ var pdfjsDisplayTextLayer = require('./display/text_layer.js');
 
 var pdfjsDisplayAnnotationLayer = require('./display/annotation_layer.js');
 
-var pdfjsDisplayDOMUtils = require('./display/dom_utils.js');
+var pdfjsDisplayDisplayUtils = require('./display/display_utils.js');
 
 var pdfjsDisplaySVG = require('./display/svg.js');
 
@@ -49,16 +49,20 @@ var pdfjsDisplayAPICompatibility = require('./display/api_compatibility.js');
     pdfjsDisplayAPI.setPDFNetworkStreamFactory(function (params) {
       return new PDFNodeStream(params);
     });
-  } else if (typeof Response !== 'undefined' && 'body' in Response.prototype && typeof ReadableStream !== 'undefined') {
-    var PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;
-
-    pdfjsDisplayAPI.setPDFNetworkStreamFactory(function (params) {
-      return new PDFFetchStream(params);
-    });
   } else {
     var PDFNetworkStream = require('./display/network.js').PDFNetworkStream;
 
+    var PDFFetchStream;
+
+    if (pdfjsDisplayDisplayUtils.isFetchSupported()) {
+      PDFFetchStream = require('./display/fetch_stream.js').PDFFetchStream;
+    }
+
     pdfjsDisplayAPI.setPDFNetworkStreamFactory(function (params) {
+      if (PDFFetchStream && pdfjsDisplayDisplayUtils.isValidFetchUrl(params.url)) {
+        return new PDFFetchStream(params);
+      }
+
       return new PDFNetworkStream(params);
     });
   }
@@ -90,10 +94,11 @@ exports.shadow = pdfjsSharedUtil.shadow;
 exports.Util = pdfjsSharedUtil.Util;
 exports.ReadableStream = pdfjsSharedUtil.ReadableStream;
 exports.URL = pdfjsSharedUtil.URL;
-exports.RenderingCancelledException = pdfjsDisplayDOMUtils.RenderingCancelledException;
-exports.getFilenameFromUrl = pdfjsDisplayDOMUtils.getFilenameFromUrl;
-exports.LinkTarget = pdfjsDisplayDOMUtils.LinkTarget;
-exports.addLinkAttributes = pdfjsDisplayDOMUtils.addLinkAttributes;
-exports.loadScript = pdfjsDisplayDOMUtils.loadScript;
+exports.RenderingCancelledException = pdfjsDisplayDisplayUtils.RenderingCancelledException;
+exports.getFilenameFromUrl = pdfjsDisplayDisplayUtils.getFilenameFromUrl;
+exports.LinkTarget = pdfjsDisplayDisplayUtils.LinkTarget;
+exports.addLinkAttributes = pdfjsDisplayDisplayUtils.addLinkAttributes;
+exports.loadScript = pdfjsDisplayDisplayUtils.loadScript;
+exports.PDFDateString = pdfjsDisplayDisplayUtils.PDFDateString;
 exports.GlobalWorkerOptions = pdfjsDisplayWorkerOptions.GlobalWorkerOptions;
 exports.apiCompatibilityParams = pdfjsDisplayAPICompatibility.apiCompatibilityParams;

+ 3 - 3
lib/pdf.worker.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,8 +21,8 @@
  */
 'use strict';
 
-var pdfjsVersion = '2.1.266';
-var pdfjsBuild = '81f5835c';
+var pdfjsVersion = '2.2.228';
+var pdfjsBuild = 'd7afb74a';
 
 var pdfjsCoreWorker = require('./core/worker.js');
 

+ 6 - 6
lib/shared/compatibility.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -88,8 +88,8 @@ if (!globalScope._pdfjsCompatibilityChecked) {
         tokens[_key] = arguments[_key];
       }
 
-      for (var _i = 0; _i < tokens.length; _i++) {
-        var token = tokens[_i];
+      for (var _i = 0, _tokens = tokens; _i < _tokens.length; _i++) {
+        var token = _tokens[_i];
         OriginalDOMTokenListAdd.call(this, token);
       }
     };
@@ -99,8 +99,8 @@ if (!globalScope._pdfjsCompatibilityChecked) {
         tokens[_key2] = arguments[_key2];
       }
 
-      for (var _i2 = 0; _i2 < tokens.length; _i2++) {
-        var token = tokens[_i2];
+      for (var _i2 = 0, _tokens2 = tokens; _i2 < _tokens2.length; _i2++) {
+        var token = _tokens2[_i2];
         OriginalDOMTokenListRemove.call(this, token);
       }
     };
@@ -196,7 +196,7 @@ if (!globalScope._pdfjsCompatibilityChecked) {
   })();
 
   (function checkPromise() {
-    if (globalScope.Promise && globalScope.Promise.prototype && globalScope.Promise.prototype.finally) {
+    if (globalScope.Promise && globalScope.Promise.prototype && globalScope.Promise.prototype["finally"]) {
       return;
     }
 

+ 1 - 1
lib/shared/global_scope.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 2 - 2
lib/shared/is_node.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,5 +24,5 @@
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
 module.exports = function isNodeJS() {
-  return (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && process + '' === '[object process]' && !process.versions['nw'];
+  return (typeof process === "undefined" ? "undefined" : _typeof(process)) === 'object' && process + '' === '[object process]' && !process.versions['nw'] && !process.versions['electron'];
 };

+ 7 - 7
lib/shared/message_handler.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -30,7 +30,7 @@ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"))
 
 var _util = require("./util");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
 
@@ -45,10 +45,10 @@ function resolveCall(_x, _x2) {
 function _resolveCall() {
   _resolveCall = _asyncToGenerator(
   /*#__PURE__*/
-  _regenerator.default.mark(function _callee(fn, args) {
+  _regenerator["default"].mark(function _callee(fn, args) {
     var thisArg,
         _args = arguments;
-    return _regenerator.default.wrap(function _callee$(_context) {
+    return _regenerator["default"].wrap(function _callee$(_context) {
       while (1) {
         switch (_context.prev = _context.next) {
           case 0:
@@ -59,7 +59,7 @@ function _resolveCall() {
               break;
             }
 
-            return _context.abrupt("return");
+            return _context.abrupt("return", undefined);
 
           case 3:
             return _context.abrupt("return", fn.apply(thisArg, args));
@@ -69,7 +69,7 @@ function _resolveCall() {
             return _context.stop();
         }
       }
-    }, _callee, this);
+    }, _callee);
   }));
   return _resolveCall.apply(this, arguments);
 }
@@ -111,7 +111,7 @@ function resolveOrReject(capability, success, reason) {
 }
 
 function finalize(promise) {
-  return Promise.resolve(promise).catch(function () {});
+  return Promise.resolve(promise)["catch"](function () {});
 }
 
 function MessageHandler(sourceName, targetName, comObj) {

+ 1 - 1
lib/shared/streams_polyfill.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 1 - 1
lib/shared/url_polyfill.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 13 - 125
lib/shared/util.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,18 +24,15 @@
 Object.defineProperty(exports, "__esModule", {
   value: true
 });
-exports.toRomanNumerals = toRomanNumerals;
 exports.arrayByteLength = arrayByteLength;
 exports.arraysToBytes = arraysToBytes;
 exports.assert = assert;
 exports.bytesToString = bytesToString;
 exports.createPromiseCapability = createPromiseCapability;
-exports.deprecated = deprecated;
-exports.getInheritableProperty = getInheritableProperty;
-exports.getLookupTableFactory = getLookupTableFactory;
 exports.getVerbosityLevel = getVerbosityLevel;
 exports.info = info;
 exports.isArrayBuffer = isArrayBuffer;
+exports.isArrayEqual = isArrayEqual;
 exports.isBool = isBool;
 exports.isEmptyObj = isEmptyObj;
 exports.isNum = isNum;
@@ -71,7 +68,7 @@ Object.defineProperty(exports, "URL", {
     return _url_polyfill.URL;
   }
 });
-exports.createObjectURL = exports.FormatError = exports.XRefParseException = exports.XRefEntryException = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.NativeImageDecoding = exports.MissingPDFException = exports.MissingDataException = exports.InvalidPDFException = exports.AbortException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VerbosityLevel = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = void 0;
+exports.createObjectURL = exports.FormatError = exports.Util = exports.UnknownErrorException = exports.UnexpectedResponseException = exports.TextRenderingMode = exports.StreamType = exports.PermissionFlag = exports.PasswordResponses = exports.PasswordException = exports.NativeImageDecoding = exports.MissingPDFException = exports.InvalidPDFException = exports.AbortException = exports.CMapCompressionType = exports.ImageKind = exports.FontType = exports.AnnotationType = exports.AnnotationFlag = exports.AnnotationFieldFlag = exports.AnnotationBorderStyleType = exports.UNSUPPORTED_FEATURES = exports.VerbosityLevel = exports.OPS = exports.IDENTITY_MATRIX = exports.FONT_IDENTITY_MATRIX = void 0;
 
 require("./compatibility");
 
@@ -364,10 +361,6 @@ function warn(msg) {
   }
 }
 
-function deprecated(details) {
-  console.log('Deprecated API usage: ' + details);
-}
-
 function unreachable(msg) {
   throw new Error(msg);
 }
@@ -437,19 +430,6 @@ function shadow(obj, prop, value) {
   return value;
 }
 
-function getLookupTableFactory(initializer) {
-  var lookup;
-  return function () {
-    if (initializer) {
-      lookup = Object.create(null);
-      initializer(lookup);
-      initializer = null;
-    }
-
-    return lookup;
-  };
-}
-
 var PasswordException = function PasswordExceptionClosure() {
   function PasswordException(msg, code) {
     this.name = 'PasswordException';
@@ -518,47 +498,6 @@ var UnexpectedResponseException = function UnexpectedResponseExceptionClosure()
 
 exports.UnexpectedResponseException = UnexpectedResponseException;
 
-var MissingDataException = function MissingDataExceptionClosure() {
-  function MissingDataException(begin, end) {
-    this.begin = begin;
-    this.end = end;
-    this.message = 'Missing data [' + begin + ', ' + end + ')';
-  }
-
-  MissingDataException.prototype = new Error();
-  MissingDataException.prototype.name = 'MissingDataException';
-  MissingDataException.constructor = MissingDataException;
-  return MissingDataException;
-}();
-
-exports.MissingDataException = MissingDataException;
-
-var XRefEntryException = function XRefEntryExceptionClosure() {
-  function XRefEntryException(msg) {
-    this.message = msg;
-  }
-
-  XRefEntryException.prototype = new Error();
-  XRefEntryException.prototype.name = 'XRefEntryException';
-  XRefEntryException.constructor = XRefEntryException;
-  return XRefEntryException;
-}();
-
-exports.XRefEntryException = XRefEntryException;
-
-var XRefParseException = function XRefParseExceptionClosure() {
-  function XRefParseException(msg) {
-    this.message = msg;
-  }
-
-  XRefParseException.prototype = new Error();
-  XRefParseException.prototype.name = 'XRefParseException';
-  XRefParseException.constructor = XRefParseException;
-  return XRefParseException;
-}();
-
-exports.XRefParseException = XRefParseException;
-
 var FormatError = function FormatErrorClosure() {
   function FormatError(msg) {
     this.message = msg;
@@ -714,43 +653,6 @@ function isEvalSupported() {
   }
 }
 
-function getInheritableProperty(_ref) {
-  var dict = _ref.dict,
-      key = _ref.key,
-      _ref$getArray = _ref.getArray,
-      getArray = _ref$getArray === void 0 ? false : _ref$getArray,
-      _ref$stopWhenFound = _ref.stopWhenFound,
-      stopWhenFound = _ref$stopWhenFound === void 0 ? true : _ref$stopWhenFound;
-  var LOOP_LIMIT = 100;
-  var loopCount = 0;
-  var values;
-
-  while (dict) {
-    var value = getArray ? dict.getArray(key) : dict.get(key);
-
-    if (value !== undefined) {
-      if (stopWhenFound) {
-        return value;
-      }
-
-      if (!values) {
-        values = [];
-      }
-
-      values.push(value);
-    }
-
-    if (++loopCount > LOOP_LIMIT) {
-      warn("getInheritableProperty: maximum loop count exceeded for \"".concat(key, "\""));
-      break;
-    }
-
-    dict = dict.get('Parent');
-  }
-
-  return values;
-}
-
 var Util = function UtilClosure() {
   function Util() {}
 
@@ -858,30 +760,6 @@ var Util = function UtilClosure() {
 }();
 
 exports.Util = Util;
-var ROMAN_NUMBER_MAP = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
-
-function toRomanNumerals(number) {
-  var lowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-  assert(Number.isInteger(number) && number > 0, 'The number should be a positive integer.');
-  var pos,
-      romanBuf = [];
-
-  while (number >= 1000) {
-    number -= 1000;
-    romanBuf.push('M');
-  }
-
-  pos = number / 100 | 0;
-  number %= 100;
-  romanBuf.push(ROMAN_NUMBER_MAP[pos]);
-  pos = number / 10 | 0;
-  number %= 10;
-  romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
-  romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
-  var romanStr = romanBuf.join('');
-  return lowerCase ? romanStr.toLowerCase() : romanStr;
-}
-
 var 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];
 
 function stringToPDFString(str) {
@@ -935,6 +813,16 @@ function isArrayBuffer(v) {
   return _typeof(v) === 'object' && v !== null && v.byteLength !== undefined;
 }
 
+function isArrayEqual(arr1, arr2) {
+  if (arr1.length !== arr2.length) {
+    return false;
+  }
+
+  return arr1.every(function (element, index) {
+    return element === arr2[index];
+  });
+}
+
 function isSpace(ch) {
   return ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A;
 }

+ 278 - 93
lib/test/unit/annotation_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -25,14 +25,14 @@ var _annotation = require("../../core/annotation");
 
 var _util = require("../../shared/util");
 
+var _test_utils = require("./test_utils");
+
 var _primitives = require("../../core/primitives");
 
 var _parser = require("../../core/parser");
 
 var _stream = require("../../core/stream");
 
-var _test_utils = require("./test_utils");
-
 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
 function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
@@ -67,34 +67,12 @@ describe('annotation', function () {
     return PDFManagerMock;
   }();
 
-  var IdFactoryMock =
-  /*#__PURE__*/
-  function () {
-    function IdFactoryMock(params) {
-      _classCallCheck(this, IdFactoryMock);
-
-      this.uniquePrefix = params.prefix || 'p0_';
-      this.idCounters = {
-        obj: params.startObjId || 0
-      };
-    }
-
-    _createClass(IdFactoryMock, [{
-      key: "createObjId",
-      value: function createObjId() {
-        return this.uniquePrefix + ++this.idCounters.obj;
-      }
-    }]);
-
-    return IdFactoryMock;
-  }();
-
   var pdfManagerMock, idFactoryMock;
   beforeAll(function (done) {
     pdfManagerMock = new PDFManagerMock({
       docBaseUrl: null
     });
-    idFactoryMock = new IdFactoryMock({});
+    idFactoryMock = (0, _test_utils.createIdFactory)(0);
     done();
   });
   afterAll(function () {
@@ -106,7 +84,9 @@ describe('annotation', function () {
       var annotationDict = new _primitives.Dict();
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
-      var annotationRef = new _primitives.Ref(10, 0);
+
+      var annotationRef = _primitives.Ref.get(10, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -124,10 +104,7 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       var xref = new _test_utils.XRefMock();
-      var idFactory = new IdFactoryMock({
-        prefix: 'p0_',
-        startObjId: 0
-      });
+      var idFactory = (0, _test_utils.createIdFactory)(0);
 
       var annotation1 = _annotation.AnnotationFactory.create(xref, annotationDict, pdfManagerMock, idFactory).then(function (_ref2) {
         var data = _ref2.data;
@@ -146,7 +123,9 @@ describe('annotation', function () {
     it('should handle missing /Subtype', function (done) {
       var annotationDict = new _primitives.Dict();
       annotationDict.set('Type', _primitives.Name.get('Annot'));
-      var annotationRef = new _primitives.Ref(1, 0);
+
+      var annotationRef = _primitives.Ref.get(1, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -163,12 +142,44 @@ describe('annotation', function () {
     var dict, ref;
     beforeAll(function (done) {
       dict = new _primitives.Dict();
-      ref = new _primitives.Ref(1, 0);
+      ref = _primitives.Ref.get(1, 0);
       done();
     });
     afterAll(function () {
       dict = ref = null;
     });
+    it('should set and get valid contents', function () {
+      var annotation = new _annotation.Annotation({
+        dict: dict,
+        ref: ref
+      });
+      annotation.setContents('Foo bar baz');
+      expect(annotation.contents).toEqual('Foo bar baz');
+    });
+    it('should not set and get invalid contents', function () {
+      var annotation = new _annotation.Annotation({
+        dict: dict,
+        ref: ref
+      });
+      annotation.setContents(undefined);
+      expect(annotation.contents).toEqual('');
+    });
+    it('should set and get a valid modification date', function () {
+      var annotation = new _annotation.Annotation({
+        dict: dict,
+        ref: ref
+      });
+      annotation.setModificationDate('D:20190422');
+      expect(annotation.modificationDate).toEqual('D:20190422');
+    });
+    it('should not set and get an invalid modification date', function () {
+      var annotation = new _annotation.Annotation({
+        dict: dict,
+        ref: ref
+      });
+      annotation.setModificationDate(undefined);
+      expect(annotation.modificationDate).toEqual(null);
+    });
     it('should set and get flags', function () {
       var annotation = new _annotation.Annotation({
         dict: dict,
@@ -313,6 +324,33 @@ describe('annotation', function () {
       expect(borderStyle.verticalCornerRadius).toEqual(0);
     });
   });
+  describe('MarkupAnnotation', function () {
+    var dict, ref;
+    beforeAll(function (done) {
+      dict = new _primitives.Dict();
+      ref = _primitives.Ref.get(1, 0);
+      done();
+    });
+    afterAll(function () {
+      dict = ref = null;
+    });
+    it('should set and get a valid creation date', function () {
+      var markupAnnotation = new _annotation.MarkupAnnotation({
+        dict: dict,
+        ref: ref
+      });
+      markupAnnotation.setCreationDate('D:20190422');
+      expect(markupAnnotation.creationDate).toEqual('D:20190422');
+    });
+    it('should not set and get an invalid creation date', function () {
+      var markupAnnotation = new _annotation.MarkupAnnotation({
+        dict: dict,
+        ref: ref
+      });
+      markupAnnotation.setCreationDate(undefined);
+      expect(markupAnnotation.creationDate).toEqual(null);
+    });
+  });
   describe('LinkAnnotation', function () {
     it('should correctly parse a URI action', function (done) {
       var actionDict = new _primitives.Dict();
@@ -323,7 +361,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(820, 0);
+
+      var annotationRef = _primitives.Ref.get(820, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -347,7 +387,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(353, 0);
+
+      var annotationRef = _primitives.Ref.get(353, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -364,14 +406,18 @@ describe('annotation', function () {
     });
     it('should correctly parse a URI action, where the URI entry ' + 'has an incorrect encoding (bug 1122280)', function (done) {
       var actionStream = new _stream.StringStream('<<\n' + '/Type /Action\n' + '/S /URI\n' + '/URI (http://www.example.com/\\303\\274\\303\\266\\303\\244)\n' + '>>\n');
-      var lexer = new _parser.Lexer(actionStream);
-      var parser = new _parser.Parser(lexer);
+      var parser = new _parser.Parser({
+        lexer: new _parser.Lexer(actionStream),
+        xref: null
+      });
       var actionDict = parser.getObj();
       var annotationDict = new _primitives.Dict();
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(8, 0);
+
+      var annotationRef = _primitives.Ref.get(8, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -395,7 +441,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(798, 0);
+
+      var annotationRef = _primitives.Ref.get(798, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -421,7 +469,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(489, 0);
+
+      var annotationRef = _primitives.Ref.get(489, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -447,7 +497,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(489, 0);
+
+      var annotationRef = _primitives.Ref.get(489, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -475,7 +527,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(495, 0);
+
+      var annotationRef = _primitives.Ref.get(495, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -501,7 +555,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(489, 0);
+
+      var annotationRef = _primitives.Ref.get(489, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -531,7 +587,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(88, 0);
+
+      var annotationRef = _primitives.Ref.get(88, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -564,7 +622,9 @@ describe('annotation', function () {
         annotationDict.set('Type', _primitives.Name.get('Annot'));
         annotationDict.set('Subtype', _primitives.Name.get('Link'));
         annotationDict.set('A', actionDict);
-        var annotationRef = new _primitives.Ref(46, 0);
+
+        var annotationRef = _primitives.Ref.get(46, 0);
+
         var xref = new _test_utils.XRefMock([{
           ref: annotationRef,
           data: annotationDict
@@ -608,7 +668,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('A', actionDict);
-      var annotationRef = new _primitives.Ref(12, 0);
+
+      var annotationRef = _primitives.Ref.get(12, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -628,7 +690,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('Dest', _primitives.Name.get('LI0'));
-      var annotationRef = new _primitives.Ref(583, 0);
+
+      var annotationRef = _primitives.Ref.get(583, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -647,8 +711,10 @@ describe('annotation', function () {
       var annotationDict = new _primitives.Dict();
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
-      annotationDict.set('Dest', [new _primitives.Ref(17, 0), _primitives.Name.get('XYZ'), 0, 841.89, null]);
-      var annotationRef = new _primitives.Ref(10, 0);
+      annotationDict.set('Dest', [_primitives.Ref.get(17, 0), _primitives.Name.get('XYZ'), 0, 841.89, null]);
+
+      var annotationRef = _primitives.Ref.get(10, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -677,7 +743,9 @@ describe('annotation', function () {
       annotationDict.set('Type', _primitives.Name.get('Annot'));
       annotationDict.set('Subtype', _primitives.Name.get('Link'));
       annotationDict.set('Dest', destDict);
-      var annotationRef = new _primitives.Ref(798, 0);
+
+      var annotationRef = _primitives.Ref.get(798, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: annotationRef,
         data: annotationDict
@@ -705,7 +773,8 @@ describe('annotation', function () {
       widgetDict = null;
     });
     it('should handle unknown field names', function (done) {
-      var widgetRef = new _primitives.Ref(20, 0);
+      var widgetRef = _primitives.Ref.get(20, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: widgetRef,
         data: widgetDict
@@ -720,7 +789,9 @@ describe('annotation', function () {
     });
     it('should construct the field name when there are no ancestors', function (done) {
       widgetDict.set('T', 'foo');
-      var widgetRef = new _primitives.Ref(21, 0);
+
+      var widgetRef = _primitives.Ref.get(21, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: widgetRef,
         data: widgetDict
@@ -741,7 +812,9 @@ describe('annotation', function () {
       secondParent.set('T', 'bar');
       widgetDict.set('Parent', secondParent);
       widgetDict.set('T', 'baz');
-      var widgetRef = new _primitives.Ref(22, 0);
+
+      var widgetRef = _primitives.Ref.get(22, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: widgetRef,
         data: widgetDict
@@ -760,7 +833,9 @@ describe('annotation', function () {
       parentDict.set('T', 'foo');
       widgetDict.set('Parent', parentDict);
       widgetDict.set('T', 'bar');
-      var widgetRef = new _primitives.Ref(22, 0);
+
+      var widgetRef = _primitives.Ref.get(22, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: widgetRef,
         data: widgetDict
@@ -787,7 +862,8 @@ describe('annotation', function () {
       textWidgetDict = null;
     });
     it('should handle unknown text alignment, maximum length and flags', function (done) {
-      var textWidgetRef = new _primitives.Ref(124, 0);
+      var textWidgetRef = _primitives.Ref.get(124, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: textWidgetRef,
         data: textWidgetDict
@@ -808,7 +884,9 @@ describe('annotation', function () {
       textWidgetDict.set('Q', 'center');
       textWidgetDict.set('MaxLen', 'five');
       textWidgetDict.set('Ff', 'readonly');
-      var textWidgetRef = new _primitives.Ref(43, 0);
+
+      var textWidgetRef = _primitives.Ref.get(43, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: textWidgetRef,
         data: textWidgetDict
@@ -829,7 +907,9 @@ describe('annotation', function () {
       textWidgetDict.set('Q', 1);
       textWidgetDict.set('MaxLen', 20);
       textWidgetDict.set('Ff', _util.AnnotationFieldFlag.READONLY + _util.AnnotationFieldFlag.MULTILINE);
-      var textWidgetRef = new _primitives.Ref(84, 0);
+
+      var textWidgetRef = _primitives.Ref.get(84, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: textWidgetRef,
         data: textWidgetDict
@@ -847,7 +927,9 @@ describe('annotation', function () {
     });
     it('should reject comb fields without a maximum length', function (done) {
       textWidgetDict.set('Ff', _util.AnnotationFieldFlag.COMB);
-      var textWidgetRef = new _primitives.Ref(46, 0);
+
+      var textWidgetRef = _primitives.Ref.get(46, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: textWidgetRef,
         data: textWidgetDict
@@ -863,7 +945,9 @@ describe('annotation', function () {
     it('should accept comb fields with a maximum length', function (done) {
       textWidgetDict.set('MaxLen', 20);
       textWidgetDict.set('Ff', _util.AnnotationFieldFlag.COMB);
-      var textWidgetRef = new _primitives.Ref(46, 0);
+
+      var textWidgetRef = _primitives.Ref.get(46, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: textWidgetRef,
         data: textWidgetDict
@@ -885,7 +969,9 @@ describe('annotation', function () {
         promise = promise.then(function () {
           textWidgetDict.set('MaxLen', 20);
           textWidgetDict.set('Ff', flags);
-          var textWidgetRef = new _primitives.Ref(93, 0);
+
+          var textWidgetRef = _primitives.Ref.get(93, 0);
+
           var xref = new _test_utils.XRefMock([{
             ref: textWidgetRef,
             data: textWidgetDict
@@ -926,7 +1012,9 @@ describe('annotation', function () {
       exportValueOptionsDict.set('Checked', 1);
       appearanceStatesDict.set('D', exportValueOptionsDict);
       buttonWidgetDict.set('AP', appearanceStatesDict);
-      var buttonWidgetRef = new _primitives.Ref(124, 0);
+
+      var buttonWidgetRef = _primitives.Ref.get(124, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: buttonWidgetRef,
         data: buttonWidgetDict
@@ -944,7 +1032,9 @@ describe('annotation', function () {
     });
     it('should handle checkboxes without export value', function (done) {
       buttonWidgetDict.set('V', _primitives.Name.get('1'));
-      var buttonWidgetRef = new _primitives.Ref(124, 0);
+
+      var buttonWidgetRef = _primitives.Ref.get(124, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: buttonWidgetRef,
         data: buttonWidgetDict
@@ -969,7 +1059,9 @@ describe('annotation', function () {
       buttonWidgetDict.set('Ff', _util.AnnotationFieldFlag.RADIO);
       buttonWidgetDict.set('Parent', parentDict);
       buttonWidgetDict.set('AP', appearanceStatesDict);
-      var buttonWidgetRef = new _primitives.Ref(124, 0);
+
+      var buttonWidgetRef = _primitives.Ref.get(124, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: buttonWidgetRef,
         data: buttonWidgetDict
@@ -992,7 +1084,9 @@ describe('annotation', function () {
       appearanceStatesDict.set('N', normalAppearanceStateDict);
       buttonWidgetDict.set('Ff', _util.AnnotationFieldFlag.RADIO);
       buttonWidgetDict.set('AP', appearanceStatesDict);
-      var buttonWidgetRef = new _primitives.Ref(124, 0);
+
+      var buttonWidgetRef = _primitives.Ref.get(124, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: buttonWidgetRef,
         data: buttonWidgetDict
@@ -1022,7 +1116,8 @@ describe('annotation', function () {
       choiceWidgetDict = null;
     });
     it('should handle missing option arrays', function (done) {
-      var choiceWidgetRef = new _primitives.Ref(122, 0);
+      var choiceWidgetRef = _primitives.Ref.get(122, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1036,9 +1131,12 @@ describe('annotation', function () {
       }, done.fail);
     });
     it('should handle option arrays with array elements', function (done) {
-      var optionBarRef = new _primitives.Ref(20, 0);
+      var optionBarRef = _primitives.Ref.get(20, 0);
+
       var optionBarStr = 'Bar';
-      var optionOneRef = new _primitives.Ref(10, 0);
+
+      var optionOneRef = _primitives.Ref.get(10, 0);
+
       var optionOneArr = ['bar_export', optionBarRef];
       var options = [['foo_export', 'Foo'], optionOneRef];
       var expected = [{
@@ -1049,7 +1147,9 @@ describe('annotation', function () {
         displayValue: 'Bar'
       }];
       choiceWidgetDict.set('Opt', options);
-      var choiceWidgetRef = new _primitives.Ref(123, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(123, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1069,7 +1169,8 @@ describe('annotation', function () {
       }, done.fail);
     });
     it('should handle option arrays with string elements', function (done) {
-      var optionBarRef = new _primitives.Ref(10, 0);
+      var optionBarRef = _primitives.Ref.get(10, 0);
+
       var optionBarStr = 'Bar';
       var options = ['Foo', optionBarRef];
       var expected = [{
@@ -1080,7 +1181,9 @@ describe('annotation', function () {
         displayValue: 'Bar'
       }];
       choiceWidgetDict.set('Opt', options);
-      var choiceWidgetRef = new _primitives.Ref(981, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(981, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1108,7 +1211,9 @@ describe('annotation', function () {
       var parentDict = new _primitives.Dict();
       parentDict.set('Opt', options);
       choiceWidgetDict.set('Parent', parentDict);
-      var choiceWidgetRef = new _primitives.Ref(123, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(123, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1128,7 +1233,9 @@ describe('annotation', function () {
         displayValue: 'Foo'
       }];
       choiceWidgetDict.set('Opt', options);
-      var choiceWidgetRef = new _primitives.Ref(984, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(984, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1144,7 +1251,9 @@ describe('annotation', function () {
     it('should handle array field values', function (done) {
       var fieldValue = ['Foo', 'Bar'];
       choiceWidgetDict.set('V', fieldValue);
-      var choiceWidgetRef = new _primitives.Ref(968, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(968, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1160,7 +1269,9 @@ describe('annotation', function () {
     it('should handle string field values', function (done) {
       var fieldValue = 'Foo';
       choiceWidgetDict.set('V', fieldValue);
-      var choiceWidgetRef = new _primitives.Ref(978, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(978, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1174,7 +1285,8 @@ describe('annotation', function () {
       }, done.fail);
     });
     it('should handle unknown flags', function (done) {
-      var choiceWidgetRef = new _primitives.Ref(166, 0);
+      var choiceWidgetRef = _primitives.Ref.get(166, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1191,7 +1303,9 @@ describe('annotation', function () {
     });
     it('should not set invalid flags', function (done) {
       choiceWidgetDict.set('Ff', 'readonly');
-      var choiceWidgetRef = new _primitives.Ref(165, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(165, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1208,7 +1322,9 @@ describe('annotation', function () {
     });
     it('should set valid flags', function (done) {
       choiceWidgetDict.set('Ff', _util.AnnotationFieldFlag.READONLY + _util.AnnotationFieldFlag.COMBO + _util.AnnotationFieldFlag.MULTISELECT);
-      var choiceWidgetRef = new _primitives.Ref(512, 0);
+
+      var choiceWidgetRef = _primitives.Ref.get(512, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: choiceWidgetRef,
         data: choiceWidgetDict
@@ -1230,7 +1346,9 @@ describe('annotation', function () {
       lineDict.set('Type', _primitives.Name.get('Annot'));
       lineDict.set('Subtype', _primitives.Name.get('Line'));
       lineDict.set('L', [1, 2, 3, 4]);
-      var lineRef = new _primitives.Ref(122, 0);
+
+      var lineRef = _primitives.Ref.get(122, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: lineRef,
         data: lineDict
@@ -1247,19 +1365,28 @@ describe('annotation', function () {
   describe('FileAttachmentAnnotation', function () {
     it('should correctly parse a file attachment', function (done) {
       var fileStream = new _stream.StringStream('<<\n' + '/Type /EmbeddedFile\n' + '/Subtype /text#2Fplain\n' + '>>\n' + 'stream\n' + 'Test attachment' + 'endstream\n');
-      var lexer = new _parser.Lexer(fileStream);
-      var parser = new _parser.Parser(lexer, true);
-      var fileStreamRef = new _primitives.Ref(18, 0);
+      var parser = new _parser.Parser({
+        lexer: new _parser.Lexer(fileStream),
+        xref: null,
+        allowStreams: true
+      });
+
+      var fileStreamRef = _primitives.Ref.get(18, 0);
+
       var fileStreamDict = parser.getObj();
       var embeddedFileDict = new _primitives.Dict();
       embeddedFileDict.set('F', fileStreamRef);
-      var fileSpecRef = new _primitives.Ref(19, 0);
+
+      var fileSpecRef = _primitives.Ref.get(19, 0);
+
       var fileSpecDict = new _primitives.Dict();
       fileSpecDict.set('Type', _primitives.Name.get('Filespec'));
       fileSpecDict.set('Desc', '');
       fileSpecDict.set('EF', embeddedFileDict);
       fileSpecDict.set('UF', 'Test.txt');
-      var fileAttachmentRef = new _primitives.Ref(20, 0);
+
+      var fileAttachmentRef = _primitives.Ref.get(20, 0);
+
       var fileAttachmentDict = new _primitives.Dict();
       fileAttachmentDict.set('Type', _primitives.Name.get('Annot'));
       fileAttachmentDict.set('Subtype', _primitives.Name.get('FileAttachment'));
@@ -1290,17 +1417,19 @@ describe('annotation', function () {
     });
   });
   describe('PopupAnnotation', function () {
-    it('should inherit the parent flags when the Popup is not viewable, ' + 'but the parent is (PR 7352)', function (done) {
+    it('should inherit properties from its parent', function (done) {
       var parentDict = new _primitives.Dict();
       parentDict.set('Type', _primitives.Name.get('Annot'));
       parentDict.set('Subtype', _primitives.Name.get('Text'));
-      parentDict.set('F', 28);
+      parentDict.set('M', 'D:20190423');
+      parentDict.set('C', [0, 0, 1]);
       var popupDict = new _primitives.Dict();
       popupDict.set('Type', _primitives.Name.get('Annot'));
       popupDict.set('Subtype', _primitives.Name.get('Popup'));
-      popupDict.set('F', 25);
       popupDict.set('Parent', parentDict);
-      var popupRef = new _primitives.Ref(13, 0);
+
+      var popupRef = _primitives.Ref.get(13, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: popupRef,
         data: popupDict
@@ -1310,6 +1439,58 @@ describe('annotation', function () {
         var data = _ref45.data,
             viewable = _ref45.viewable;
         expect(data.annotationType).toEqual(_util.AnnotationType.POPUP);
+        expect(data.modificationDate).toEqual('D:20190423');
+        expect(data.color).toEqual(new Uint8ClampedArray([0, 0, 255]));
+        done();
+      }, done.fail);
+    });
+    it('should handle missing parent properties', function (done) {
+      var parentDict = new _primitives.Dict();
+      parentDict.set('Type', _primitives.Name.get('Annot'));
+      parentDict.set('Subtype', _primitives.Name.get('Text'));
+      var popupDict = new _primitives.Dict();
+      popupDict.set('Type', _primitives.Name.get('Annot'));
+      popupDict.set('Subtype', _primitives.Name.get('Popup'));
+      popupDict.set('Parent', parentDict);
+
+      var popupRef = _primitives.Ref.get(13, 0);
+
+      var xref = new _test_utils.XRefMock([{
+        ref: popupRef,
+        data: popupDict
+      }]);
+
+      _annotation.AnnotationFactory.create(xref, popupRef, pdfManagerMock, idFactoryMock).then(function (_ref46) {
+        var data = _ref46.data,
+            viewable = _ref46.viewable;
+        expect(data.annotationType).toEqual(_util.AnnotationType.POPUP);
+        expect(data.modificationDate).toEqual(null);
+        expect(data.color).toEqual(null);
+        done();
+      }, done.fail);
+    });
+    it('should inherit the parent flags when the Popup is not viewable, ' + 'but the parent is (PR 7352)', function (done) {
+      var parentDict = new _primitives.Dict();
+      parentDict.set('Type', _primitives.Name.get('Annot'));
+      parentDict.set('Subtype', _primitives.Name.get('Text'));
+      parentDict.set('F', 28);
+      var popupDict = new _primitives.Dict();
+      popupDict.set('Type', _primitives.Name.get('Annot'));
+      popupDict.set('Subtype', _primitives.Name.get('Popup'));
+      popupDict.set('F', 25);
+      popupDict.set('Parent', parentDict);
+
+      var popupRef = _primitives.Ref.get(13, 0);
+
+      var xref = new _test_utils.XRefMock([{
+        ref: popupRef,
+        data: popupDict
+      }]);
+
+      _annotation.AnnotationFactory.create(xref, popupRef, pdfManagerMock, idFactoryMock).then(function (_ref47) {
+        var data = _ref47.data,
+            viewable = _ref47.viewable;
+        expect(data.annotationType).toEqual(_util.AnnotationType.POPUP);
         expect(data.annotationFlags).toEqual(25);
         expect(viewable).toEqual(true);
         done();
@@ -1322,14 +1503,16 @@ describe('annotation', function () {
       inkDict.set('Type', _primitives.Name.get('Annot'));
       inkDict.set('Subtype', _primitives.Name.get('Ink'));
       inkDict.set('InkList', [[1, 1, 1, 2, 2, 2, 3, 3]]);
-      var inkRef = new _primitives.Ref(142, 0);
+
+      var inkRef = _primitives.Ref.get(142, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: inkRef,
         data: inkDict
       }]);
 
-      _annotation.AnnotationFactory.create(xref, inkRef, pdfManagerMock, idFactoryMock).then(function (_ref46) {
-        var data = _ref46.data;
+      _annotation.AnnotationFactory.create(xref, inkRef, pdfManagerMock, idFactoryMock).then(function (_ref48) {
+        var data = _ref48.data;
         expect(data.annotationType).toEqual(_util.AnnotationType.INK);
         expect(data.inkLists.length).toEqual(1);
         expect(data.inkLists[0]).toEqual([{
@@ -1353,14 +1536,16 @@ describe('annotation', function () {
       inkDict.set('Type', _primitives.Name.get('Annot'));
       inkDict.set('Subtype', _primitives.Name.get('Ink'));
       inkDict.set('InkList', [[1, 1, 1, 2], [3, 3, 4, 5]]);
-      var inkRef = new _primitives.Ref(143, 0);
+
+      var inkRef = _primitives.Ref.get(143, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: inkRef,
         data: inkDict
       }]);
 
-      _annotation.AnnotationFactory.create(xref, inkRef, pdfManagerMock, idFactoryMock).then(function (_ref47) {
-        var data = _ref47.data;
+      _annotation.AnnotationFactory.create(xref, inkRef, pdfManagerMock, idFactoryMock).then(function (_ref49) {
+        var data = _ref49.data;
         expect(data.annotationType).toEqual(_util.AnnotationType.INK);
         expect(data.inkLists.length).toEqual(2);
         expect(data.inkLists[0]).toEqual([{

+ 198 - 188
lib/test/unit/api_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -27,7 +27,7 @@ var _test_utils = require("./test_utils");
 
 var _util = require("../../shared/util");
 
-var _dom_utils = require("../../display/dom_utils");
+var _display_utils = require("../../display/display_utils");
 
 var _api = require("../../display/api");
 
@@ -37,7 +37,7 @@ var _is_node = _interopRequireDefault(require("../../shared/is_node"));
 
 var _metadata = require("../../display/metadata");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
 
@@ -59,10 +59,10 @@ describe('api', function () {
   var basicApiGetDocumentParams = (0, _test_utils.buildGetDocumentParams)(basicApiFileName);
   var CanvasFactory;
   beforeAll(function (done) {
-    if ((0, _is_node.default)()) {
+    if ((0, _is_node["default"])()) {
       CanvasFactory = new _test_utils.NodeCanvasFactory();
     } else {
-      CanvasFactory = new _dom_utils.DOMCanvasFactory();
+      CanvasFactory = new _display_utils.DOMCanvasFactory();
     }
 
     done();
@@ -96,14 +96,14 @@ describe('api', function () {
         expect(data[1] instanceof _api.PDFDocumentProxy).toEqual(true);
         expect(loadingTask).toEqual(data[1].loadingTask);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('creates pdf doc from URL and aborts before worker initialized', function (done) {
       var loadingTask = (0, _api.getDocument)(basicApiGetDocumentParams);
       var destroyed = loadingTask.destroy();
       loadingTask.promise.then(function (reason) {
         done.fail('shall fail loading');
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         expect(true).toEqual(true);
         destroyed.then(done);
       });
@@ -118,59 +118,42 @@ describe('api', function () {
       destroyed.then(function (data) {
         expect(true).toEqual(true);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('creates pdf doc from typed array', function (done) {
-      var typedArrayPdf;
+      var typedArrayPdfPromise;
 
-      if ((0, _is_node.default)()) {
-        typedArrayPdf = _test_utils.NodeFileReaderFactory.fetch({
+      if ((0, _is_node["default"])()) {
+        typedArrayPdfPromise = _test_utils.NodeFileReaderFactory.fetch({
           path: _test_utils.TEST_PDFS_PATH.node + basicApiFileName
         });
       } else {
-        var nonBinaryRequest = false;
-        var request = new XMLHttpRequest();
-        request.open('GET', _test_utils.TEST_PDFS_PATH.dom + basicApiFileName, false);
-
-        try {
-          request.responseType = 'arraybuffer';
-          nonBinaryRequest = request.responseType !== 'arraybuffer';
-        } catch (e) {
-          nonBinaryRequest = true;
-        }
-
-        if (nonBinaryRequest && request.overrideMimeType) {
-          request.overrideMimeType('text/plain; charset=x-user-defined');
-        }
-
-        request.send(null);
-
-        if (nonBinaryRequest) {
-          typedArrayPdf = (0, _util.stringToBytes)(request.responseText);
-        } else {
-          typedArrayPdf = new Uint8Array(request.response);
-        }
+        typedArrayPdfPromise = _test_utils.DOMFileReaderFactory.fetch({
+          path: _test_utils.TEST_PDFS_PATH.dom + basicApiFileName
+        });
       }
 
-      expect(typedArrayPdf.length).toEqual(basicApiFileLength);
-      var loadingTask = (0, _api.getDocument)(typedArrayPdf);
-      var progressReportedCapability = (0, _util.createPromiseCapability)();
+      typedArrayPdfPromise.then(function (typedArrayPdf) {
+        expect(typedArrayPdf.length).toEqual(basicApiFileLength);
+        var loadingTask = (0, _api.getDocument)(typedArrayPdf);
+        var progressReportedCapability = (0, _util.createPromiseCapability)();
 
-      loadingTask.onProgress = function (data) {
-        progressReportedCapability.resolve(data);
-      };
+        loadingTask.onProgress = function (data) {
+          progressReportedCapability.resolve(data);
+        };
 
-      Promise.all([loadingTask.promise, progressReportedCapability.promise]).then(function (data) {
-        expect(data[0] instanceof _api.PDFDocumentProxy).toEqual(true);
-        expect(data[1].loaded / data[1].total).toEqual(1);
-        loadingTask.destroy().then(done);
-      }).catch(done.fail);
+        return Promise.all([loadingTask.promise, progressReportedCapability.promise]).then(function (data) {
+          expect(data[0] instanceof _api.PDFDocumentProxy).toEqual(true);
+          expect(data[1].loaded / data[1].total).toEqual(1);
+          loadingTask.destroy().then(done);
+        });
+      })["catch"](done.fail);
     });
     it('creates pdf doc from invalid PDF file', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bug1020226.pdf'));
       loadingTask.promise.then(function () {
         done.fail('shall fail loading');
-      }).catch(function (error) {
+      })["catch"](function (error) {
         expect(error instanceof _util.InvalidPDFException).toEqual(true);
         loadingTask.destroy().then(done);
       });
@@ -179,7 +162,7 @@ describe('api', function () {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('non-existent.pdf'));
       loadingTask.promise.then(function (error) {
         done.fail('shall fail loading');
-      }).catch(function (error) {
+      })["catch"](function (error) {
         expect(error instanceof _util.MissingPDFException).toEqual(true);
         loadingTask.destroy().then(done);
       });
@@ -209,7 +192,7 @@ describe('api', function () {
       Promise.all(promises).then(function (data) {
         expect(data[2] instanceof _api.PDFDocumentProxy).toEqual(true);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('creates pdf doc from PDF file protected with only a user password', function (done) {
       var filename = 'pr6531_2.pdf';
@@ -244,7 +227,7 @@ describe('api', function () {
       });
       Promise.all([result1, result2, result3]).then(function () {
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('creates pdf doc from password protected PDF file and aborts/throws ' + 'in the onPassword callback (issue 7806)', function (done) {
       var filename = 'issue3371.pdf';
@@ -290,12 +273,12 @@ describe('api', function () {
       });
       Promise.all([result1, result2]).then(function () {
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
   });
   describe('PDFWorker', function () {
     it('worker created or destroyed', function (done) {
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         pending('Worker is not supported in Node.js.');
       }
 
@@ -312,10 +295,10 @@ describe('api', function () {
         expect(!!worker.port).toEqual(false);
         expect(worker.destroyed).toEqual(true);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('worker created or destroyed by getDocument', function (done) {
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         pending('Worker is not supported in Node.js.');
       }
 
@@ -333,10 +316,10 @@ describe('api', function () {
         expect(!!destroyedWorker).toEqual(false);
         expect(worker.destroyed).toEqual(true);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('worker created and can be used in getDocument', function (done) {
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         pending('Worker is not supported in Node.js.');
       }
 
@@ -359,10 +342,10 @@ describe('api', function () {
         expect(worker.destroyed).toEqual(false);
         worker.destroy();
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('creates more than one worker', function (done) {
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         pending('Worker is not supported in Node.js.');
       }
 
@@ -382,10 +365,10 @@ describe('api', function () {
         worker2.destroy();
         worker3.destroy();
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets current workerSrc', function () {
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         pending('Worker is not supported in Node.js.');
       }
 
@@ -422,7 +405,7 @@ describe('api', function () {
         expect(data instanceof _api.PDFPageProxy).toEqual(true);
         expect(data.pageIndex).toEqual(0);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-existent page', function (done) {
       var outOfRangePromise = doc.getPage(100);
@@ -445,7 +428,7 @@ describe('api', function () {
       });
       Promise.all([outOfRangePromise, nonIntegerPromise, nonNumberPromise]).then(function () {
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets page index', function (done) {
       var ref = {
@@ -456,7 +439,7 @@ describe('api', function () {
       promise.then(function (pageIndex) {
         expect(pageIndex).toEqual(1);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets invalid page index', function (done) {
       var ref = {
@@ -466,7 +449,7 @@ describe('api', function () {
       var promise = doc.getPageIndex(ref);
       promise.then(function () {
         done.fail('shall fail for invalid page reference.');
-      }).catch(function (reason) {
+      })["catch"](function (reason) {
         expect(reason instanceof Error).toEqual(true);
         done();
       });
@@ -483,7 +466,7 @@ describe('api', function () {
           }, 0, 841.89, null]
         });
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets a destination, from /Dests dictionary', function (done) {
       var promise = doc.getDestination('chapter1');
@@ -495,14 +478,14 @@ describe('api', function () {
           name: 'XYZ'
         }, 0, 841.89, null]);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets a non-existent destination, from /Dests dictionary', function (done) {
       var promise = doc.getDestination('non-existent-named-destination');
       promise.then(function (data) {
         expect(data).toEqual(null);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets destinations, from /Names (NameTree) dictionary', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6204.pdf'));
@@ -525,7 +508,7 @@ describe('api', function () {
           }, 0, 375, null]
         });
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets a destination, from /Names (NameTree) dictionary', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6204.pdf'));
@@ -540,7 +523,7 @@ describe('api', function () {
           name: 'XYZ'
         }, 0, 375, null]);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets a non-existent destination, from /Names (NameTree) dictionary', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6204.pdf'));
@@ -550,7 +533,7 @@ describe('api', function () {
       promise.then(function (destination) {
         expect(destination).toEqual(null);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-string destination', function (done) {
       var numberPromise = doc.getDestination(4.3);
@@ -583,7 +566,7 @@ describe('api', function () {
       promise.then(function (data) {
         expect(data).toEqual(null);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets page labels', function (done) {
       var loadingTask0 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('bug793632.pdf'));
@@ -608,7 +591,22 @@ describe('api', function () {
         expect(pageLabels[2]).toEqual(['1', '2']);
         expect(pageLabels[3]).toEqual(['X3']);
         Promise.all([loadingTask0.destroy(), loadingTask1.destroy(), loadingTask2.destroy(), loadingTask3.destroy()]).then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
+    });
+    it('gets default page layout', function (done) {
+      var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
+      loadingTask.promise.then(function (pdfDocument) {
+        return pdfDocument.getPageLayout();
+      }).then(function (mode) {
+        expect(mode).toEqual('');
+        loadingTask.destroy().then(done);
+      })["catch"](done.fail);
+    });
+    it('gets non-default page layout', function (done) {
+      doc.getPageLayout().then(function (mode) {
+        expect(mode).toEqual('SinglePage');
+        done();
+      })["catch"](done.fail);
     });
     it('gets default page mode', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
@@ -617,13 +615,30 @@ describe('api', function () {
       }).then(function (mode) {
         expect(mode).toEqual('UseNone');
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-default page mode', function (done) {
       doc.getPageMode().then(function (mode) {
         expect(mode).toEqual('UseOutlines');
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
+    });
+    it('gets default viewer preferences', function (done) {
+      var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
+      loadingTask.promise.then(function (pdfDocument) {
+        return pdfDocument.getViewerPreferences();
+      }).then(function (prefs) {
+        expect(_typeof(prefs) === 'object' && prefs !== null && (0, _util.isEmptyObj)(prefs)).toEqual(true);
+        loadingTask.destroy().then(done);
+      })["catch"](done.fail);
+    });
+    it('gets non-default viewer preferences', function (done) {
+      doc.getViewerPreferences().then(function (prefs) {
+        expect(prefs).toEqual({
+          Direction: 'L2R'
+        });
+        done();
+      })["catch"](done.fail);
     });
     it('gets default open action destination', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
@@ -632,7 +647,7 @@ describe('api', function () {
       }).then(function (dest) {
         expect(dest).toEqual(null);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-default open action destination', function (done) {
       doc.getOpenActionDestination().then(function (dest) {
@@ -643,17 +658,17 @@ describe('api', function () {
           name: 'FitH'
         }, null]);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-existent attachments', function (done) {
       var promise = doc.getAttachments();
       promise.then(function (data) {
         expect(data).toEqual(null);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets attachments', function (done) {
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         pending('TODO: Use a non-linked test-case.');
       }
 
@@ -667,14 +682,14 @@ describe('api', function () {
         expect(attachment.content instanceof Uint8Array).toBeTruthy();
         expect(attachment.content.length).toEqual(30098);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets javascript', function (done) {
       var promise = doc.getJavaScript();
       promise.then(function (data) {
         expect(data).toEqual(null);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     var viewerPrintRegExp = /\bprint\s*\(/;
     it('gets javascript with printing instructions (Print action)', function (done) {
@@ -686,7 +701,7 @@ describe('api', function () {
         expect(data).toEqual(['print({});']);
         expect(data[0]).toMatch(viewerPrintRegExp);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets javascript with printing instructions (JS action)', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue6106.pdf'));
@@ -697,7 +712,7 @@ describe('api', function () {
         expect(data).toEqual(['this.print({bUI:true,bSilent:false,bShrinkToFit:true});']);
         expect(data[0]).toMatch(viewerPrintRegExp);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-existent outline', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
@@ -707,7 +722,7 @@ describe('api', function () {
       promise.then(function (outline) {
         expect(outline).toEqual(null);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets outline', function (done) {
       var promise = doc.getOutline();
@@ -726,7 +741,7 @@ describe('api', function () {
         expect(outlineItem.items.length).toEqual(1);
         expect(outlineItem.items[0].title).toEqual('Paragraph 1.1');
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets outline containing a url', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue3214.pdf'));
@@ -746,13 +761,13 @@ describe('api', function () {
           expect(outlineItemOne.color).toEqual(new Uint8ClampedArray([0, 0, 0]));
           loadingTask.destroy().then(done);
         });
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets non-existent permissions', function (done) {
       doc.getPermissions().then(function (permissions) {
         expect(permissions).toEqual(null);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets permissions', function (done) {
       var loadingTask0 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue9972-1.pdf'));
@@ -777,7 +792,7 @@ describe('api', function () {
         expect(permissions[2].length).toEqual(totalPermissionCount - 1);
         expect(permissions[2].includes(_util.PermissionFlag.COPY)).toBeFalsy();
         Promise.all([loadingTask0.destroy(), loadingTask1.destroy(), loadingTask2.destroy()]).then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets metadata', function (done) {
       var promise = doc.getMetadata();
@@ -791,11 +806,12 @@ describe('api', function () {
         expect(info['IsLinearized']).toEqual(false);
         expect(info['IsAcroFormPresent']).toEqual(false);
         expect(info['IsXFAPresent']).toEqual(false);
+        expect(info['IsCollectionPresent']).toEqual(false);
         expect(metadata instanceof _metadata.Metadata).toEqual(true);
         expect(metadata.get('dc:title')).toEqual('Basic API Test');
         expect(contentDispositionFilename).toEqual(null);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets metadata, with custom info dict entries', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('tracemonkey.pdf'));
@@ -815,10 +831,11 @@ describe('api', function () {
         expect(info['IsLinearized']).toEqual(false);
         expect(info['IsAcroFormPresent']).toEqual(false);
         expect(info['IsXFAPresent']).toEqual(false);
+        expect(info['IsCollectionPresent']).toEqual(false);
         expect(metadata).toEqual(null);
         expect(contentDispositionFilename).toEqual(null);
         loadingTask.destroy().then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets data', function (done) {
       var promise = doc.getData();
@@ -826,7 +843,7 @@ describe('api', function () {
         expect(data instanceof Uint8Array).toEqual(true);
         expect(data.length).toEqual(basicApiFileLength);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets download info', function (done) {
       var promise = doc.getDownloadInfo();
@@ -835,7 +852,7 @@ describe('api', function () {
           length: basicApiFileLength
         });
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets document stats', function (done) {
       var promise = doc.getStats();
@@ -845,7 +862,7 @@ describe('api', function () {
           fontTypes: []
         });
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('checks that fingerprints are unique', function (done) {
       var loadingTask1 = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue4436r.pdf'));
@@ -860,13 +877,13 @@ describe('api', function () {
         expect(fingerprint2.length > 0).toEqual(true);
         expect(fingerprint1).not.toEqual(fingerprint2);
         Promise.all([loadingTask1.destroy(), loadingTask2.destroy()]).then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     describe('Cross-origin', function () {
       var loadingTask;
 
       function _checkCanLoad(expectSuccess, filename, options) {
-        if ((0, _is_node.default)()) {
+        if ((0, _is_node["default"])()) {
           pending('Cannot simulate cross-origin requests in Node.js');
         }
 
@@ -905,7 +922,7 @@ describe('api', function () {
       }
 
       afterEach(function (done) {
-        if (loadingTask) {
+        if (loadingTask && !loadingTask.destroyed) {
           loadingTask.destroy().then(done);
         } else {
           done();
@@ -950,7 +967,7 @@ describe('api', function () {
           page = data;
           done();
         });
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     afterAll(function (done) {
       loadingTask.destroy().then(done);
@@ -1020,7 +1037,7 @@ describe('api', function () {
       });
       Promise.all([defaultPromise, displayPromise, printPromise]).then(function () {
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets annotations containing relative URLs (bug 766086)', function (done) {
       var filename = 'bug766086.pdf';
@@ -1057,7 +1074,7 @@ describe('api', function () {
         expect(invalidDocBaseUrlAnnotations[0].url).toBeUndefined();
         expect(invalidDocBaseUrlAnnotations[0].unsafeUrl).toEqual('../../0021/002156/215675E.pdf#15');
         Promise.all([defaultLoadingTask.destroy(), docBaseUrlLoadingTask.destroy(), invalidDocBaseUrlLoadingTask.destroy()]).then(done);
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets text content', function (done) {
       var defaultPromise = page.getTextContent();
@@ -1072,7 +1089,7 @@ describe('api', function () {
         expect(!!data[0].styles).toEqual(true);
         expect(JSON.stringify(data[0])).toEqual(JSON.stringify(data[1]));
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets text content, with correct properties (issue 8276)', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('issue8276_reduced.pdf'));
@@ -1100,7 +1117,7 @@ describe('api', function () {
             loadingTask.destroy().then(done);
           });
         });
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets operator list', function (done) {
       var promise = page.getOperatorList();
@@ -1109,7 +1126,7 @@ describe('api', function () {
         expect(!!oplist.argsArray).toEqual(true);
         expect(oplist.lastChunk).toEqual(true);
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets operatorList with JPEG image (issue 4888)', function (done) {
       var loadingTask = (0, _api.getDocument)((0, _test_utils.buildGetDocumentParams)('cmykjpeg.pdf'));
@@ -1127,7 +1144,7 @@ describe('api', function () {
             loadingTask.destroy().then(done);
           });
         });
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets document stats after parsing page', function (done) {
       var promise = page.getOperatorList().then(function () {
@@ -1144,7 +1161,7 @@ describe('api', function () {
           fontTypes: expectedFontTypes
         });
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
     it('gets page stats after parsing page, without `pdfBug` set', function (done) {
       page.getOperatorList().then(function (opList) {
@@ -1165,7 +1182,7 @@ describe('api', function () {
           });
         });
       }).then(function (stats) {
-        expect(stats instanceof _dom_utils.StatTimer).toEqual(true);
+        expect(stats instanceof _display_utils.StatTimer).toEqual(true);
         expect(stats.times.length).toEqual(1);
 
         var _stats$times = _slicedToArray(stats.times, 1),
@@ -1197,7 +1214,7 @@ describe('api', function () {
           });
         });
       }).then(function (stats) {
-        expect(stats instanceof _dom_utils.StatTimer).toEqual(true);
+        expect(stats instanceof _display_utils.StatTimer).toEqual(true);
         expect(stats.times.length).toEqual(3);
 
         var _stats$times2 = _slicedToArray(stats.times, 3),
@@ -1228,8 +1245,8 @@ describe('api', function () {
       renderTask.cancel();
       renderTask.promise.then(function () {
         done.fail('shall cancel rendering');
-      }).catch(function (error) {
-        expect(error instanceof _dom_utils.RenderingCancelledException).toEqual(true);
+      })["catch"](function (error) {
+        expect(error instanceof _display_utils.RenderingCancelledException).toEqual(true);
         expect(error.type).toEqual('canvas');
         CanvasFactory.destroy(canvasAndCtx);
         done();
@@ -1249,7 +1266,7 @@ describe('api', function () {
       renderTask.promise.then(function () {
         throw new Error('shall cancel rendering');
       }, function (reason) {
-        expect(reason instanceof _dom_utils.RenderingCancelledException).toEqual(true);
+        expect(reason instanceof _display_utils.RenderingCancelledException).toEqual(true);
       }).then(function () {
         var reRenderTask = page.render({
           canvasContext: canvasAndCtx.context,
@@ -1289,7 +1306,6 @@ describe('api', function () {
     var pdf2 = (0, _test_utils.buildGetDocumentParams)('TAMReview.pdf');
     var pdf3 = (0, _test_utils.buildGetDocumentParams)('issue6068.pdf');
     var loadingTasks = [];
-    var pdfDocuments = [];
 
     function renderPDF(_x) {
       return _renderPDF.apply(this, arguments);
@@ -1298,9 +1314,9 @@ describe('api', function () {
     function _renderPDF() {
       _renderPDF = _asyncToGenerator(
       /*#__PURE__*/
-      _regenerator.default.mark(function _callee(filename) {
+      _regenerator["default"].mark(function _callee(filename) {
         var loadingTask, pdf, page, viewport, canvasAndCtx, renderTask, data;
-        return _regenerator.default.wrap(function _callee$(_context) {
+        return _regenerator["default"].wrap(function _callee$(_context) {
           while (1) {
             switch (_context.prev = _context.next) {
               case 0:
@@ -1311,11 +1327,10 @@ describe('api', function () {
 
               case 4:
                 pdf = _context.sent;
-                pdfDocuments.push(pdf);
-                _context.next = 8;
+                _context.next = 7;
                 return pdf.getPage(1);
 
-              case 8:
+              case 7:
                 page = _context.sent;
                 viewport = page.getViewport({
                   scale: 1.2
@@ -1326,34 +1341,29 @@ describe('api', function () {
                   canvasFactory: CanvasFactory,
                   viewport: viewport
                 });
-                _context.next = 14;
+                _context.next = 13;
                 return renderTask.promise;
 
-              case 14:
+              case 13:
                 data = canvasAndCtx.canvas.toDataURL();
                 CanvasFactory.destroy(canvasAndCtx);
                 return _context.abrupt("return", data);
 
-              case 17:
+              case 16:
               case "end":
                 return _context.stop();
             }
           }
-        }, _callee, this);
+        }, _callee);
       }));
       return _renderPDF.apply(this, arguments);
     }
 
     afterEach(function (done) {
-      var destroyPromises = pdfDocuments.map(function (pdfDocument) {
-        return pdfDocument.destroy();
-      });
-      var destroyPromises2 = loadingTasks.map(function (loadingTask) {
+      var destroyPromises = loadingTasks.map(function (loadingTask) {
         return loadingTask.destroy();
       });
-      Promise.all(destroyPromises.concat(destroyPromises2)).then(function () {
-        done();
-      });
+      Promise.all(destroyPromises).then(done);
     });
     it('should correctly render PDFs in parallel', function (done) {
       var baseline1, baseline2, baseline3;
@@ -1374,48 +1384,36 @@ describe('api', function () {
       });
       promiseDone.then(function () {
         done();
-      }).catch(done.fail);
+      })["catch"](done.fail);
     });
   });
   describe('PDFDataRangeTransport', function () {
-    var loadPromise;
-
-    function getDocumentData() {
-      var pdfPath = new URL('../pdfs/tracemonkey.pdf', window.location).href;
+    var dataPromise;
+    beforeAll(function (done) {
+      var fileName = 'tracemonkey.pdf';
 
-      if (loadPromise) {
-        return loadPromise;
+      if ((0, _is_node["default"])()) {
+        dataPromise = _test_utils.NodeFileReaderFactory.fetch({
+          path: _test_utils.TEST_PDFS_PATH.node + fileName
+        });
+      } else {
+        dataPromise = _test_utils.DOMFileReaderFactory.fetch({
+          path: _test_utils.TEST_PDFS_PATH.dom + fileName
+        });
       }
 
-      loadPromise = new Promise(function (resolve, reject) {
-        var xhr = new XMLHttpRequest(pdfPath);
-        xhr.open('GET', pdfPath);
-        xhr.responseType = 'arraybuffer';
-
-        xhr.onload = function () {
-          resolve(new Uint8Array(xhr.response));
-        };
-
-        xhr.onerror = function () {
-          reject(new Error('PDF is not loaded'));
-        };
-
-        xhr.send();
-      });
-      return loadPromise;
-    }
-
+      done();
+    });
+    afterAll(function () {
+      dataPromise = null;
+    });
     it('should fetch document info and page using ranges', function (done) {
-      if ((0, _is_node.default)()) {
-        pending('XMLHttpRequest is not supported in Node.js.');
-      }
-
-      var transport;
       var initialDataLength = 4000;
-      var fetches = 0;
-      var getDocumentPromise = getDocumentData().then(function (data) {
+      var fetches = 0,
+          loadingTask;
+      dataPromise.then(function (data) {
         var initialData = data.subarray(0, initialDataLength);
-        transport = new _api.PDFDataRangeTransport(data.length, initialData);
+        var transport = new _api.PDFDataRangeTransport(data.length, initialData);
 
         transport.requestDataRange = function (begin, end) {
           fetches++;
@@ -1425,33 +1423,24 @@ describe('api', function () {
           });
         };
 
-        var loadingTask = (0, _api.getDocument)(transport);
+        loadingTask = (0, _api.getDocument)(transport);
         return loadingTask.promise;
-      });
-      var pdfDocument;
-      var getPagePromise = getDocumentPromise.then(function (pdfDocument_) {
-        pdfDocument = pdfDocument_;
-        var pagePromise = pdfDocument.getPage(10);
-        return pagePromise;
-      });
-      getPagePromise.then(function (page) {
+      }).then(function (pdfDocument) {
         expect(pdfDocument.numPages).toEqual(14);
-        expect(page.rotate).toEqual(0);
+        return pdfDocument.getPage(10);
+      }).then(function (pdfPage) {
+        expect(pdfPage.rotate).toEqual(0);
         expect(fetches).toBeGreaterThan(2);
-        done();
-      }).catch(done.fail);
+        loadingTask.destroy().then(done);
+      })["catch"](done.fail);
     });
     it('should fetch document info and page using range and streaming', function (done) {
-      if ((0, _is_node.default)()) {
-        pending('XMLHttpRequest is not supported in Node.js.');
-      }
-
-      var transport;
       var initialDataLength = 4000;
-      var fetches = 0;
-      var getDocumentPromise = getDocumentData().then(function (data) {
+      var fetches = 0,
+          loadingTask;
+      dataPromise.then(function (data) {
         var initialData = data.subarray(0, initialDataLength);
-        transport = new _api.PDFDataRangeTransport(data.length, initialData);
+        var transport = new _api.PDFDataRangeTransport(data.length, initialData);
 
         transport.requestDataRange = function (begin, end) {
           fetches++;
@@ -1465,21 +1454,42 @@ describe('api', function () {
           });
         };
 
-        var loadingTask = (0, _api.getDocument)(transport);
+        loadingTask = (0, _api.getDocument)(transport);
         return loadingTask.promise;
-      });
-      var pdfDocument;
-      var getPagePromise = getDocumentPromise.then(function (pdfDocument_) {
-        pdfDocument = pdfDocument_;
-        var pagePromise = pdfDocument.getPage(10);
-        return pagePromise;
-      });
-      getPagePromise.then(function (page) {
+      }).then(function (pdfDocument) {
         expect(pdfDocument.numPages).toEqual(14);
-        expect(page.rotate).toEqual(0);
+        return pdfDocument.getPage(10);
+      }).then(function (pdfPage) {
+        expect(pdfPage.rotate).toEqual(0);
         expect(fetches).toEqual(1);
-        done();
-      }).catch(done.fail);
+        waitSome(function () {
+          loadingTask.destroy().then(done);
+        });
+      })["catch"](done.fail);
+    });
+    it('should fetch document info and page, without range, ' + 'using complete initialData', function (done) {
+      var fetches = 0,
+          loadingTask;
+      dataPromise.then(function (data) {
+        var transport = new _api.PDFDataRangeTransport(data.length, data, true);
+
+        transport.requestDataRange = function (begin, end) {
+          fetches++;
+        };
+
+        loadingTask = (0, _api.getDocument)({
+          disableRange: true,
+          range: transport
+        });
+        return loadingTask.promise;
+      }).then(function (pdfDocument) {
+        expect(pdfDocument.numPages).toEqual(14);
+        return pdfDocument.getPage(10);
+      }).then(function (pdfPage) {
+        expect(pdfPage.rotate).toEqual(0);
+        expect(fetches).toEqual(0);
+        loadingTask.destroy().then(done);
+      })["catch"](done.fail);
     });
   });
 });

+ 1 - 1
lib/test/unit/bidi_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 15 - 1
lib/test/unit/cff_parser_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -304,4 +304,18 @@ describe('CFFCompiler', function () {
     var out = c.compileFDSelect(fdSelect);
     expect(out).toEqual([3, 0, 1, 0, 0, 0, 0, 2]);
   });
+  it('compiles charset of CID font', function () {
+    var charset = new _cff_parser.CFFCharset();
+    var c = new _cff_parser.CFFCompiler();
+    var numGlyphs = 7;
+    var out = c.compileCharset(charset, numGlyphs, new _cff_parser.CFFStrings(), true);
+    expect(out).toEqual([2, 0, 0, 0, numGlyphs - 1]);
+  });
+  it('compiles charset of non CID font', function () {
+    var charset = new _cff_parser.CFFCharset(false, 0, ['space', 'exclam']);
+    var c = new _cff_parser.CFFCompiler();
+    var numGlyphs = 3;
+    var out = c.compileCharset(charset, numGlyphs, new _cff_parser.CFFStrings(), false);
+    expect(out).toEqual([0, 0, 1, 0, 2]);
+  });
 });

+ 3 - 3
lib/test/unit/clitests_helper.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -29,9 +29,9 @@ var _node_stream = require("../../display/node_stream");
 
 var _api = require("../../display/api");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
-if (!(0, _is_node.default)()) {
+if (!(0, _is_node["default"])()) {
   throw new Error('The `gulp unittestcli` command can only be used in ' + 'Node.js environments.');
 }
 

+ 20 - 20
lib/test/unit/cmap_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -23,7 +23,7 @@
 
 var _cmap = require("../../core/cmap");
 
-var _dom_utils = require("../../display/dom_utils");
+var _display_utils = require("../../display/display_utils");
 
 var _is_node = _interopRequireDefault(require("../../shared/is_node"));
 
@@ -33,7 +33,7 @@ var _test_utils = require("./test_utils");
 
 var _stream = require("../../core/stream");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 var cMapUrl = {
   dom: '../../external/bcmaps/',
@@ -45,13 +45,13 @@ describe('cmap', function () {
   beforeAll(function (done) {
     var CMapReaderFactory;
 
-    if ((0, _is_node.default)()) {
+    if ((0, _is_node["default"])()) {
       CMapReaderFactory = new _test_utils.NodeCMapReaderFactory({
         baseUrl: cMapUrl.node,
         isCompressed: cMapPacked
       });
     } else {
-      CMapReaderFactory = new _dom_utils.DOMCMapReaderFactory({
+      CMapReaderFactory = new _display_utils.DOMCMapReaderFactory({
         baseUrl: cMapUrl.dom,
         isCompressed: cMapPacked
       });
@@ -81,7 +81,7 @@ describe('cmap', function () {
       expect(cmap.lookup(0x04)).toEqual(String.fromCharCode(0x01));
       expect(cmap.lookup(0x05)).toBeUndefined();
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -99,7 +99,7 @@ describe('cmap', function () {
       expect(cmap.lookup(0x0B)).toEqual(String.fromCharCode(0x05));
       expect(cmap.lookup(0x0C)).toBeUndefined();
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -117,7 +117,7 @@ describe('cmap', function () {
       expect(cmap.lookup(0x12)).toEqual(0x05);
       expect(cmap.lookup(0x13)).toBeUndefined();
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -133,7 +133,7 @@ describe('cmap', function () {
       expect(cmap.lookup(0x14)).toEqual(0x00);
       expect(cmap.lookup(0x15)).toBeUndefined();
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -151,7 +151,7 @@ describe('cmap', function () {
       expect(cmap.lookup(0x1B)).toEqual(0x05);
       expect(cmap.lookup(0x1C)).toBeUndefined();
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -172,7 +172,7 @@ describe('cmap', function () {
       expect(c.charcode).toEqual(3);
       expect(c.length).toEqual(4);
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -190,7 +190,7 @@ describe('cmap', function () {
       expect(c.charcode).toEqual(0x8EA1A1A1);
       expect(c.length).toEqual(4);
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -211,7 +211,7 @@ describe('cmap', function () {
       expect(cmap.length).toEqual(0x20A7);
       expect(cmap.isIdentityCMap).toEqual(false);
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -226,7 +226,7 @@ describe('cmap', function () {
     cmapPromise.then(function (cmap) {
       expect(cmap.name).toEqual('Identity-H');
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -241,7 +241,7 @@ describe('cmap', function () {
     cmapPromise.then(function (cmap) {
       expect(cmap.vertical).toEqual(true);
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -259,7 +259,7 @@ describe('cmap', function () {
       expect(cmap.length).toEqual(0x20A7);
       expect(cmap.isIdentityCMap).toEqual(false);
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -278,7 +278,7 @@ describe('cmap', function () {
         return cmap.isIdentityCMap;
       }).toThrow(new Error('should not access .isIdentityCMap'));
       done();
-    }).catch(function (reason) {
+    })["catch"](function (reason) {
       done.fail(reason);
     });
   });
@@ -299,7 +299,7 @@ describe('cmap', function () {
   });
   it('attempts to load a built-in CMap without the necessary API parameters', function (done) {
     function tmpFetchBuiltInCMap(name) {
-      var CMapReaderFactory = (0, _is_node.default)() ? new _test_utils.NodeCMapReaderFactory({}) : new _dom_utils.DOMCMapReaderFactory({});
+      var CMapReaderFactory = (0, _is_node["default"])() ? new _test_utils.NodeCMapReaderFactory({}) : new _display_utils.DOMCMapReaderFactory({});
       return CMapReaderFactory.fetch({
         name: name
       });
@@ -323,13 +323,13 @@ describe('cmap', function () {
     function tmpFetchBuiltInCMap(name) {
       var CMapReaderFactory;
 
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         CMapReaderFactory = new _test_utils.NodeCMapReaderFactory({
           baseUrl: cMapUrl.node,
           isCompressed: false
         });
       } else {
-        CMapReaderFactory = new _dom_utils.DOMCMapReaderFactory({
+        CMapReaderFactory = new _display_utils.DOMCMapReaderFactory({
           baseUrl: cMapUrl.dom,
           isCompressed: false
         });

+ 17 - 12
lib/test/unit/colorspace_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ describe('colorspace', function () {
       var cs = _primitives.Name.get('DeviceGray');
 
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -75,7 +75,8 @@ describe('colorspace', function () {
       expect(testDest).toEqual(expectedDest);
     });
     it('should handle the case when cs is an indirect object', function () {
-      var cs = new _primitives.Ref(10, 0);
+      var cs = _primitives.Ref.get(10, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: cs,
         data: _primitives.Name.get('DeviceGray')
@@ -102,7 +103,7 @@ describe('colorspace', function () {
       var cs = _primitives.Name.get('DeviceRGB');
 
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -122,7 +123,8 @@ describe('colorspace', function () {
       expect(testDest).toEqual(expectedDest);
     });
     it('should handle the case when cs is an indirect object', function () {
-      var cs = new _primitives.Ref(10, 0);
+      var cs = _primitives.Ref.get(10, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: cs,
         data: _primitives.Name.get('DeviceRGB')
@@ -149,7 +151,7 @@ describe('colorspace', function () {
       var cs = _primitives.Name.get('DeviceCMYK');
 
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -169,7 +171,8 @@ describe('colorspace', function () {
       expect(testDest).toEqual(expectedDest);
     });
     it('should handle the case when cs is an indirect object', function () {
-      var cs = new _primitives.Ref(10, 0);
+      var cs = _primitives.Ref.get(10, 0);
+
       var xref = new _test_utils.XRefMock([{
         ref: cs,
         data: _primitives.Name.get('DeviceCMYK')
@@ -199,7 +202,7 @@ describe('colorspace', function () {
       params.set('Gamma', 2.0);
       var cs = [_primitives.Name.get('CalGray'), params];
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -228,7 +231,7 @@ describe('colorspace', function () {
       params.set('Matrix', [1, 0, 0, 0, 1, 0, 0, 0, 1]);
       var cs = [_primitives.Name.get('CalRGB'), params];
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -256,7 +259,7 @@ describe('colorspace', function () {
       params.set('Range', [-100, 100, -100, 100]);
       var cs = [_primitives.Name.get('Lab'), params];
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -282,7 +285,7 @@ describe('colorspace', function () {
       var lookup = new Uint8Array([23, 155, 35, 147, 69, 93, 255, 109, 70]);
       var cs = [_primitives.Name.get('Indexed'), _primitives.Name.get('DeviceRGB'), 2, lookup];
       var xref = new _test_utils.XRefMock([{
-        ref: new _primitives.Ref(10, 0),
+        ref: _primitives.Ref.get(10, 0),
         data: new _primitives.Dict()
       }]);
       var res = new _primitives.Dict();
@@ -311,7 +314,9 @@ describe('colorspace', function () {
       fnDict.set('Length', 58);
       var fn = new _stream.StringStream('{ dup 0.84 mul ' + 'exch 0.00 exch ' + 'dup 0.44 mul ' + 'exch 0.21 mul }');
       fn = new _stream.Stream(fn.bytes, 0, 58, fnDict);
-      var fnRef = new _primitives.Ref(10, 0);
+
+      var fnRef = _primitives.Ref.get(10, 0);
+
       var cs = [_primitives.Name.get('Separation'), _primitives.Name.get('LogoGreen'), _primitives.Name.get('DeviceCMYK'), fnRef];
       var xref = new _test_utils.XRefMock([{
         ref: fnRef,

+ 191 - 0
lib/test/unit/core_utils_spec.js

@@ -0,0 +1,191 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+var _primitives = require("../../core/primitives");
+
+var _core_utils = require("../../core/core_utils");
+
+var _test_utils = require("./test_utils");
+
+describe('core_utils', function () {
+  describe('getInheritableProperty', function () {
+    it('handles non-dictionary arguments', function () {
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: null,
+        key: 'foo'
+      })).toEqual(undefined);
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: undefined,
+        key: 'foo'
+      })).toEqual(undefined);
+    });
+    it('handles dictionaries that do not contain the property', function () {
+      var emptyDict = new _primitives.Dict();
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: emptyDict,
+        key: 'foo'
+      })).toEqual(undefined);
+      var filledDict = new _primitives.Dict();
+      filledDict.set('bar', 'baz');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: filledDict,
+        key: 'foo'
+      })).toEqual(undefined);
+    });
+    it('fetches the property if it is not inherited', function () {
+      var ref = _primitives.Ref.get(10, 0);
+
+      var xref = new _test_utils.XRefMock([{
+        ref: ref,
+        data: 'quux'
+      }]);
+      var dict = new _primitives.Dict(xref);
+      dict.set('foo', 'bar');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: dict,
+        key: 'foo'
+      })).toEqual('bar');
+      dict.set('baz', ['qux', ref]);
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: dict,
+        key: 'baz',
+        getArray: true
+      })).toEqual(['qux', 'quux']);
+    });
+    it('fetches the property if it is inherited and present on one level', function () {
+      var ref = _primitives.Ref.get(10, 0);
+
+      var xref = new _test_utils.XRefMock([{
+        ref: ref,
+        data: 'quux'
+      }]);
+      var firstDict = new _primitives.Dict(xref);
+      var secondDict = new _primitives.Dict(xref);
+      firstDict.set('Parent', secondDict);
+      secondDict.set('foo', 'bar');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: firstDict,
+        key: 'foo'
+      })).toEqual('bar');
+      secondDict.set('baz', ['qux', ref]);
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: firstDict,
+        key: 'baz',
+        getArray: true
+      })).toEqual(['qux', 'quux']);
+    });
+    it('fetches the property if it is inherited and present on multiple levels', function () {
+      var ref = _primitives.Ref.get(10, 0);
+
+      var xref = new _test_utils.XRefMock([{
+        ref: ref,
+        data: 'quux'
+      }]);
+      var firstDict = new _primitives.Dict(xref);
+      var secondDict = new _primitives.Dict(xref);
+      firstDict.set('Parent', secondDict);
+      firstDict.set('foo', 'bar1');
+      secondDict.set('foo', 'bar2');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: firstDict,
+        key: 'foo'
+      })).toEqual('bar1');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: firstDict,
+        key: 'foo',
+        getArray: false,
+        stopWhenFound: false
+      })).toEqual(['bar1', 'bar2']);
+      firstDict.set('baz', ['qux1', ref]);
+      secondDict.set('baz', ['qux2', ref]);
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: firstDict,
+        key: 'baz',
+        getArray: true,
+        stopWhenFound: false
+      })).toEqual([['qux1', 'quux'], ['qux2', 'quux']]);
+    });
+    it('stops searching when the loop limit is reached', function () {
+      var dict = new _primitives.Dict();
+      var currentDict = dict;
+      var parentDict = null;
+
+      for (var i = 0; i < 150; i++) {
+        parentDict = new _primitives.Dict();
+        currentDict.set('Parent', parentDict);
+        currentDict = parentDict;
+      }
+
+      parentDict.set('foo', 'bar');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: dict,
+        key: 'foo'
+      })).toEqual(undefined);
+      dict.set('foo', 'baz');
+      expect((0, _core_utils.getInheritableProperty)({
+        dict: dict,
+        key: 'foo',
+        getArray: false,
+        stopWhenFound: false
+      })).toEqual(['baz']);
+    });
+  });
+  describe('toRomanNumerals', function () {
+    it('handles invalid arguments', function () {
+      var _loop = function _loop() {
+        var input = _arr[_i];
+        expect(function () {
+          (0, _core_utils.toRomanNumerals)(input);
+        }).toThrow(new Error('The number should be a positive integer.'));
+      };
+
+      for (var _i = 0, _arr = ['foo', -1, 0]; _i < _arr.length; _i++) {
+        _loop();
+      }
+    });
+    it('converts numbers to uppercase Roman numerals', function () {
+      expect((0, _core_utils.toRomanNumerals)(1)).toEqual('I');
+      expect((0, _core_utils.toRomanNumerals)(6)).toEqual('VI');
+      expect((0, _core_utils.toRomanNumerals)(7)).toEqual('VII');
+      expect((0, _core_utils.toRomanNumerals)(8)).toEqual('VIII');
+      expect((0, _core_utils.toRomanNumerals)(10)).toEqual('X');
+      expect((0, _core_utils.toRomanNumerals)(40)).toEqual('XL');
+      expect((0, _core_utils.toRomanNumerals)(100)).toEqual('C');
+      expect((0, _core_utils.toRomanNumerals)(500)).toEqual('D');
+      expect((0, _core_utils.toRomanNumerals)(1000)).toEqual('M');
+      expect((0, _core_utils.toRomanNumerals)(2019)).toEqual('MMXIX');
+    });
+    it('converts numbers to lowercase Roman numerals', function () {
+      expect((0, _core_utils.toRomanNumerals)(1, true)).toEqual('i');
+      expect((0, _core_utils.toRomanNumerals)(6, true)).toEqual('vi');
+      expect((0, _core_utils.toRomanNumerals)(7, true)).toEqual('vii');
+      expect((0, _core_utils.toRomanNumerals)(8, true)).toEqual('viii');
+      expect((0, _core_utils.toRomanNumerals)(10, true)).toEqual('x');
+      expect((0, _core_utils.toRomanNumerals)(40, true)).toEqual('xl');
+      expect((0, _core_utils.toRomanNumerals)(100, true)).toEqual('c');
+      expect((0, _core_utils.toRomanNumerals)(500, true)).toEqual('d');
+      expect((0, _core_utils.toRomanNumerals)(1000, true)).toEqual('m');
+      expect((0, _core_utils.toRomanNumerals)(2019, true)).toEqual('mmxix');
+    });
+  });
+});

+ 1 - 1
lib/test/unit/crypto_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.

+ 8 - 8
lib/test/unit/custom_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -23,13 +23,13 @@
 
 var _test_utils = require("./test_utils");
 
-var _dom_utils = require("../../display/dom_utils");
+var _display_utils = require("../../display/display_utils");
 
 var _api = require("../../display/api");
 
 var _is_node = _interopRequireDefault(require("../../shared/is_node"));
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 function getTopLeftPixel(canvasContext) {
   var imgData = canvasContext.getImageData(0, 0, 1, 1);
@@ -47,10 +47,10 @@ describe('custom canvas rendering', function () {
   var loadingTask;
   var page;
   beforeAll(function (done) {
-    if ((0, _is_node.default)()) {
+    if ((0, _is_node["default"])()) {
       CanvasFactory = new _test_utils.NodeCanvasFactory();
     } else {
-      CanvasFactory = new _dom_utils.DOMCanvasFactory();
+      CanvasFactory = new _display_utils.DOMCanvasFactory();
     }
 
     loadingTask = (0, _api.getDocument)(transparentGetDocumentParams);
@@ -59,7 +59,7 @@ describe('custom canvas rendering', function () {
     }).then(function (data) {
       page = data;
       done();
-    }).catch(done.fail);
+    })["catch"](done.fail);
   });
   afterAll(function (done) {
     CanvasFactory = null;
@@ -84,7 +84,7 @@ describe('custom canvas rendering', function () {
       });
       CanvasFactory.destroy(canvasAndCtx);
       done();
-    }).catch(done.fail);
+    })["catch"](done.fail);
   });
   it('renders to canvas with a custom background', function (done) {
     var viewport = page.getViewport({
@@ -105,6 +105,6 @@ describe('custom canvas rendering', function () {
       });
       CanvasFactory.destroy(canvasAndCtx);
       done();
-    }).catch(done.fail);
+    })["catch"](done.fail);
   });
 });

+ 8 - 8
lib/test/unit/display_svg_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -33,20 +33,20 @@ var _util = require("../../shared/util");
 
 var _svg = require("../../display/svg");
 
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
 
 var XLINK_NS = 'http://www.w3.org/1999/xlink';
 
 function withZlib(isZlibRequired, callback) {
   if (isZlibRequired) {
-    if (!(0, _is_node.default)()) {
+    if (!(0, _is_node["default"])()) {
       throw new Error('zlib test can only be run in Node.js');
     }
 
     return callback();
   }
 
-  if (!(0, _is_node.default)()) {
+  if (!(0, _is_node["default"])()) {
     return callback();
   }
 
@@ -103,7 +103,7 @@ describe('SVGGraphics', function () {
         };
         var xobjectObjId = 'img_p0_1';
 
-        if ((0, _is_node.default)()) {
+        if ((0, _is_node["default"])()) {
           (0, _domstubs.setStubs)(global);
         }
 
@@ -111,7 +111,7 @@ describe('SVGGraphics', function () {
           var imgData = svgGfx.objs.get(xobjectObjId);
           svgGfx.paintInlineImageXObject(imgData, elementContainer);
         } finally {
-          if ((0, _is_node.default)()) {
+          if ((0, _is_node["default"])()) {
             (0, _domstubs.unsetStubs)(global);
           }
         }
@@ -127,14 +127,14 @@ describe('SVGGraphics', function () {
 
       expect(testFunc.toString()).toMatch(/\srequire\(["']zlib["']\)/);
 
-      if ((0, _is_node.default)()) {
+      if ((0, _is_node["default"])()) {
         expect(testFunc).not.toThrow();
       } else {
         expect(testFunc).toThrow();
       }
     });
     it('should produce a reasonably small svg:image', function (done) {
-      if (!(0, _is_node.default)()) {
+      if (!(0, _is_node["default"])()) {
         pending('zlib.deflateSync is not supported in non-Node environments.');
       }
 

+ 273 - 0
lib/test/unit/display_utils_spec.js

@@ -0,0 +1,273 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+var _display_utils = require("../../display/display_utils");
+
+var _is_node = _interopRequireDefault(require("../../shared/is_node"));
+
+function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
+
+function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
+
+function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
+
+function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
+
+function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
+
+describe('display_utils', function () {
+  describe('DOMCanvasFactory', function () {
+    var canvasFactory;
+    beforeAll(function (done) {
+      canvasFactory = new _display_utils.DOMCanvasFactory();
+      done();
+    });
+    afterAll(function () {
+      canvasFactory = null;
+    });
+    it('`create` should throw an error if the dimensions are invalid', function () {
+      expect(function () {
+        return canvasFactory.create(-1, 1);
+      }).toThrow(new Error('Invalid canvas size'));
+      expect(function () {
+        return canvasFactory.create(1, -1);
+      }).toThrow(new Error('Invalid canvas size'));
+    });
+    it('`create` should return a canvas if the dimensions are valid', function () {
+      if ((0, _is_node["default"])()) {
+        pending('Document is not supported in Node.js.');
+      }
+
+      var _canvasFactory$create = canvasFactory.create(20, 40),
+          canvas = _canvasFactory$create.canvas,
+          context = _canvasFactory$create.context;
+
+      expect(canvas instanceof HTMLCanvasElement).toBe(true);
+      expect(context instanceof CanvasRenderingContext2D).toBe(true);
+      expect(canvas.width).toBe(20);
+      expect(canvas.height).toBe(40);
+    });
+    it('`reset` should throw an error if no canvas is provided', function () {
+      var canvasAndContext = {
+        canvas: null,
+        context: null
+      };
+      expect(function () {
+        return canvasFactory.reset(canvasAndContext, 20, 40);
+      }).toThrow(new Error('Canvas is not specified'));
+    });
+    it('`reset` should throw an error if the dimensions are invalid', function () {
+      var canvasAndContext = {
+        canvas: 'foo',
+        context: 'bar'
+      };
+      expect(function () {
+        return canvasFactory.reset(canvasAndContext, -1, 1);
+      }).toThrow(new Error('Invalid canvas size'));
+      expect(function () {
+        return canvasFactory.reset(canvasAndContext, 1, -1);
+      }).toThrow(new Error('Invalid canvas size'));
+    });
+    it('`reset` should alter the canvas/context if the dimensions are valid', function () {
+      if ((0, _is_node["default"])()) {
+        pending('Document is not supported in Node.js.');
+      }
+
+      var canvasAndContext = canvasFactory.create(20, 40);
+      canvasFactory.reset(canvasAndContext, 60, 80);
+      var canvas = canvasAndContext.canvas,
+          context = canvasAndContext.context;
+      expect(canvas instanceof HTMLCanvasElement).toBe(true);
+      expect(context instanceof CanvasRenderingContext2D).toBe(true);
+      expect(canvas.width).toBe(60);
+      expect(canvas.height).toBe(80);
+    });
+    it('`destroy` should throw an error if no canvas is provided', function () {
+      expect(function () {
+        return canvasFactory.destroy({});
+      }).toThrow(new Error('Canvas is not specified'));
+    });
+    it('`destroy` should clear the canvas/context', function () {
+      if ((0, _is_node["default"])()) {
+        pending('Document is not supported in Node.js.');
+      }
+
+      var canvasAndContext = canvasFactory.create(20, 40);
+      canvasFactory.destroy(canvasAndContext);
+      var canvas = canvasAndContext.canvas,
+          context = canvasAndContext.context;
+      expect(canvas).toBe(null);
+      expect(context).toBe(null);
+    });
+  });
+  describe('DOMSVGFactory', function () {
+    var svgFactory;
+    beforeAll(function (done) {
+      svgFactory = new _display_utils.DOMSVGFactory();
+      done();
+    });
+    afterAll(function () {
+      svgFactory = null;
+    });
+    it('`create` should throw an error if the dimensions are invalid', function () {
+      expect(function () {
+        return svgFactory.create(-1, 0);
+      }).toThrow(new Error('Invalid SVG dimensions'));
+      expect(function () {
+        return svgFactory.create(0, -1);
+      }).toThrow(new Error('Invalid SVG dimensions'));
+    });
+    it('`create` should return an SVG element if the dimensions are valid', function () {
+      if ((0, _is_node["default"])()) {
+        pending('Document is not supported in Node.js.');
+      }
+
+      var svg = svgFactory.create(20, 40);
+      expect(svg instanceof SVGSVGElement).toBe(true);
+      expect(svg.getAttribute('version')).toBe('1.1');
+      expect(svg.getAttribute('width')).toBe('20px');
+      expect(svg.getAttribute('height')).toBe('40px');
+      expect(svg.getAttribute('preserveAspectRatio')).toBe('none');
+      expect(svg.getAttribute('viewBox')).toBe('0 0 20 40');
+    });
+    it('`createElement` should throw an error if the type is not a string', function () {
+      expect(function () {
+        return svgFactory.createElement(true);
+      }).toThrow(new Error('Invalid SVG element type'));
+    });
+    it('`createElement` should return an SVG element if the type is valid', function () {
+      if ((0, _is_node["default"])()) {
+        pending('Document is not supported in Node.js.');
+      }
+
+      var svg = svgFactory.createElement('svg:rect');
+      expect(svg instanceof SVGRectElement).toBe(true);
+    });
+  });
+  describe('getFilenameFromUrl', function () {
+    it('should get the filename from an absolute URL', function () {
+      var url = 'https://server.org/filename.pdf';
+      expect((0, _display_utils.getFilenameFromUrl)(url)).toEqual('filename.pdf');
+    });
+    it('should get the filename from a relative URL', function () {
+      var url = '../../filename.pdf';
+      expect((0, _display_utils.getFilenameFromUrl)(url)).toEqual('filename.pdf');
+    });
+    it('should get the filename from a URL with an anchor', function () {
+      var url = 'https://server.org/filename.pdf#foo';
+      expect((0, _display_utils.getFilenameFromUrl)(url)).toEqual('filename.pdf');
+    });
+    it('should get the filename from a URL with query parameters', function () {
+      var url = 'https://server.org/filename.pdf?foo=bar';
+      expect((0, _display_utils.getFilenameFromUrl)(url)).toEqual('filename.pdf');
+    });
+  });
+  describe('isValidFetchUrl', function () {
+    it('handles invalid Fetch URLs', function () {
+      expect((0, _display_utils.isValidFetchUrl)(null)).toEqual(false);
+      expect((0, _display_utils.isValidFetchUrl)(100)).toEqual(false);
+      expect((0, _display_utils.isValidFetchUrl)('foo')).toEqual(false);
+      expect((0, _display_utils.isValidFetchUrl)('/foo', 100)).toEqual(false);
+    });
+    it('handles relative Fetch URLs', function () {
+      expect((0, _display_utils.isValidFetchUrl)('/foo', 'file://www.example.com')).toEqual(false);
+      expect((0, _display_utils.isValidFetchUrl)('/foo', 'http://www.example.com')).toEqual(true);
+    });
+    it('handles unsupported Fetch protocols', function () {
+      expect((0, _display_utils.isValidFetchUrl)('file://www.example.com')).toEqual(false);
+      expect((0, _display_utils.isValidFetchUrl)('ftp://www.example.com')).toEqual(false);
+    });
+    it('handles supported Fetch protocols', function () {
+      expect((0, _display_utils.isValidFetchUrl)('http://www.example.com')).toEqual(true);
+      expect((0, _display_utils.isValidFetchUrl)('https://www.example.com')).toEqual(true);
+    });
+  });
+  describe('PDFDateString', function () {
+    describe('toDateObject', function () {
+      it('converts PDF date strings to JavaScript `Date` objects', function () {
+        var expectations = {
+          undefined: null,
+          "null": null,
+          42: null,
+          '2019': null,
+          'D2019': null,
+          'D:': null,
+          'D:201': null,
+          'D:2019': new Date(Date.UTC(2019, 0, 1, 0, 0, 0)),
+          'D:20190': new Date(Date.UTC(2019, 0, 1, 0, 0, 0)),
+          'D:201900': new Date(Date.UTC(2019, 0, 1, 0, 0, 0)),
+          'D:201913': new Date(Date.UTC(2019, 0, 1, 0, 0, 0)),
+          'D:201902': new Date(Date.UTC(2019, 1, 1, 0, 0, 0)),
+          'D:2019020': new Date(Date.UTC(2019, 1, 1, 0, 0, 0)),
+          'D:20190200': new Date(Date.UTC(2019, 1, 1, 0, 0, 0)),
+          'D:20190232': new Date(Date.UTC(2019, 1, 1, 0, 0, 0)),
+          'D:20190203': new Date(Date.UTC(2019, 1, 3, 0, 0, 0)),
+          'D:20190431': new Date(Date.UTC(2019, 4, 1, 0, 0, 0)),
+          'D:201902030': new Date(Date.UTC(2019, 1, 3, 0, 0, 0)),
+          'D:2019020300': new Date(Date.UTC(2019, 1, 3, 0, 0, 0)),
+          'D:2019020324': new Date(Date.UTC(2019, 1, 3, 0, 0, 0)),
+          'D:2019020304': new Date(Date.UTC(2019, 1, 3, 4, 0, 0)),
+          'D:20190203040': new Date(Date.UTC(2019, 1, 3, 4, 0, 0)),
+          'D:201902030400': new Date(Date.UTC(2019, 1, 3, 4, 0, 0)),
+          'D:201902030460': new Date(Date.UTC(2019, 1, 3, 4, 0, 0)),
+          'D:201902030405': new Date(Date.UTC(2019, 1, 3, 4, 5, 0)),
+          'D:2019020304050': new Date(Date.UTC(2019, 1, 3, 4, 5, 0)),
+          'D:20190203040500': new Date(Date.UTC(2019, 1, 3, 4, 5, 0)),
+          'D:20190203040560': new Date(Date.UTC(2019, 1, 3, 4, 5, 0)),
+          'D:20190203040506': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506F': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506Z': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506-': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506+': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506+\'': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506+0': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506+01': new Date(Date.UTC(2019, 1, 3, 3, 5, 6)),
+          'D:20190203040506+00\'': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506+24\'': new Date(Date.UTC(2019, 1, 3, 4, 5, 6)),
+          'D:20190203040506+01\'': new Date(Date.UTC(2019, 1, 3, 3, 5, 6)),
+          'D:20190203040506+01\'0': new Date(Date.UTC(2019, 1, 3, 3, 5, 6)),
+          'D:20190203040506+01\'00': new Date(Date.UTC(2019, 1, 3, 3, 5, 6)),
+          'D:20190203040506+01\'60': new Date(Date.UTC(2019, 1, 3, 3, 5, 6)),
+          'D:20190203040506+0102': new Date(Date.UTC(2019, 1, 3, 3, 3, 6)),
+          'D:20190203040506+01\'02': new Date(Date.UTC(2019, 1, 3, 3, 3, 6)),
+          'D:20190203040506+01\'02\'': new Date(Date.UTC(2019, 1, 3, 3, 3, 6)),
+          'D:20190203040506+05\'07': new Date(Date.UTC(2019, 1, 2, 22, 58, 6))
+        };
+
+        for (var _i = 0, _Object$entries = Object.entries(expectations); _i < _Object$entries.length; _i++) {
+          var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
+              input = _Object$entries$_i[0],
+              expectation = _Object$entries$_i[1];
+
+          var result = _display_utils.PDFDateString.toDateObject(input);
+
+          if (result) {
+            expect(result.getTime()).toEqual(expectation.getTime());
+          } else {
+            expect(result).toEqual(expectation);
+          }
+        }
+      });
+    });
+  });
+});

+ 7 - 12
lib/test/unit/document_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,27 +21,22 @@
  */
 "use strict";
 
-var _document = require("../../core/document");
+var _test_utils = require("./test_utils");
 
 describe('document', function () {
   describe('Page', function () {
     it('should create correct objId using the idFactory', function () {
-      var page1 = new _document.Page({
-        pdfManager: {},
-        pageIndex: 0
-      });
-      var page2 = new _document.Page({
-        pdfManager: {},
-        pageIndex: 1
-      });
-      var idFactory1 = page1.idFactory,
-          idFactory2 = page2.idFactory;
+      var idFactory1 = (0, _test_utils.createIdFactory)(0);
+      var idFactory2 = (0, _test_utils.createIdFactory)(1);
       expect(idFactory1.createObjId()).toEqual('p0_1');
       expect(idFactory1.createObjId()).toEqual('p0_2');
+      expect(idFactory1.getDocId()).toEqual('g_d0');
       expect(idFactory2.createObjId()).toEqual('p1_1');
       expect(idFactory2.createObjId()).toEqual('p1_2');
+      expect(idFactory2.getDocId()).toEqual('g_d0');
       expect(idFactory1.createObjId()).toEqual('p0_3');
       expect(idFactory1.createObjId()).toEqual('p0_4');
+      expect(idFactory1.getDocId()).toEqual('g_d0');
     });
   });
 });

+ 0 - 89
lib/test/unit/dom_utils_spec.js

@@ -1,89 +0,0 @@
-/**
- * @licstart The following is the entire license notice for the
- * Javascript code in this page
- *
- * Copyright 2018 Mozilla Foundation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * @licend The above is the entire license notice for the
- * Javascript code in this page
- */
-"use strict";
-
-var _dom_utils = require("../../display/dom_utils");
-
-var _is_node = _interopRequireDefault(require("../../shared/is_node"));
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-describe('dom_utils', function () {
-  describe('DOMSVGFactory', function () {
-    var svgFactory;
-    beforeAll(function (done) {
-      svgFactory = new _dom_utils.DOMSVGFactory();
-      done();
-    });
-    afterAll(function () {
-      svgFactory = null;
-    });
-    it('`create` should throw an error if the dimensions are invalid', function () {
-      expect(function () {
-        return svgFactory.create(-1, 0);
-      }).toThrow(new Error('Invalid SVG dimensions'));
-      expect(function () {
-        return svgFactory.create(0, -1);
-      }).toThrow(new Error('Invalid SVG dimensions'));
-    });
-    it('`create` should return an SVG element if the dimensions are valid', function () {
-      if ((0, _is_node.default)()) {
-        pending('Document is not supported in Node.js.');
-      }
-
-      var svg = svgFactory.create(20, 40);
-      expect(svg instanceof SVGSVGElement).toBe(true);
-      expect(svg.getAttribute('version')).toBe('1.1');
-      expect(svg.getAttribute('width')).toBe('20px');
-      expect(svg.getAttribute('height')).toBe('40px');
-      expect(svg.getAttribute('preserveAspectRatio')).toBe('none');
-      expect(svg.getAttribute('viewBox')).toBe('0 0 20 40');
-    });
-    it('`createElement` should throw an error if the type is not a string', function () {
-      expect(function () {
-        return svgFactory.createElement(true);
-      }).toThrow(new Error('Invalid SVG element type'));
-    });
-    it('`createElement` should return an SVG element if the type is valid', function () {
-      if ((0, _is_node.default)()) {
-        pending('Document is not supported in Node.js.');
-      }
-
-      var svg = svgFactory.createElement('svg:rect');
-      expect(svg instanceof SVGRectElement).toBe(true);
-    });
-  });
-  describe('getFilenameFromUrl', function () {
-    it('should get the filename from an absolute URL', function () {
-      var url = 'http://server.org/filename.pdf';
-      var result = (0, _dom_utils.getFilenameFromUrl)(url);
-      var expected = 'filename.pdf';
-      expect(result).toEqual(expected);
-    });
-    it('should get the filename from a relative URL', function () {
-      var url = '../../filename.pdf';
-      var result = (0, _dom_utils.getFilenameFromUrl)(url);
-      var expected = 'filename.pdf';
-      expect(result).toEqual(expected);
-    });
-  });
-});

+ 5 - 5
lib/test/unit/encodings_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -30,8 +30,8 @@ describe('encodings', function () {
     it('fetches a valid array for known encoding names', function () {
       var knownEncodingNames = ['ExpertEncoding', 'MacExpertEncoding', 'MacRomanEncoding', 'StandardEncoding', 'SymbolSetEncoding', 'WinAnsiEncoding', 'ZapfDingbatsEncoding'];
 
-      for (var _i = 0; _i < knownEncodingNames.length; _i++) {
-        var knownEncodingName = knownEncodingNames[_i];
+      for (var _i = 0, _knownEncodingNames = knownEncodingNames; _i < _knownEncodingNames.length; _i++) {
+        var knownEncodingName = _knownEncodingNames[_i];
         var encoding = (0, _encodings.getEncoding)(knownEncodingName);
         expect(Array.isArray(encoding)).toEqual(true);
         expect(encoding.length).toEqual(256);
@@ -49,8 +49,8 @@ describe('encodings', function () {
           _iteratorError = err;
         } finally {
           try {
-            if (!_iteratorNormalCompletion && _iterator.return != null) {
-              _iterator.return();
+            if (!_iteratorNormalCompletion && _iterator["return"] != null) {
+              _iterator["return"]();
             }
           } finally {
             if (_didIteratorError) {

+ 8 - 10
lib/test/unit/evaluator_spec.js

@@ -2,7 +2,7 @@
  * @licstart The following is the entire license notice for the
  * Javascript code in this page
  *
- * Copyright 2018 Mozilla Foundation
+ * Copyright 2019 Mozilla Foundation
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,6 +21,8 @@
  */
 "use strict";
 
+var _test_utils = require("./test_utils");
+
 var _primitives = require("../../core/primitives");
 
 var _util = require("../../shared/util");
@@ -33,8 +35,6 @@ var _evaluator = require("../../core/evaluator");
 
 var _worker = require("../../core/worker");
 
-var _test_utils = require("./test_utils");
-
 describe('evaluator', function () {
   function HandlerMock() {
     this.inputs = [];
@@ -57,8 +57,6 @@ describe('evaluator', function () {
     }
   };
 
-  function PdfManagerMock() {}
-
   function runOperatorListCheck(evaluator, stream, resources, callback) {
     var result = new _operator_list.OperatorList();
     var task = new _worker.WorkerTask('OperatorListCheck');
@@ -77,10 +75,10 @@ describe('evaluator', function () {
   var partialEvaluator;
   beforeAll(function (done) {
     partialEvaluator = new _evaluator.PartialEvaluator({
-      pdfManager: new PdfManagerMock(),
       xref: new _test_utils.XRefMock(),
       handler: new HandlerMock(),
-      pageIndex: 0
+      pageIndex: 0,
+      idFactory: (0, _test_utils.createIdFactory)(0)
     });
     done();
   });
@@ -245,7 +243,7 @@ describe('evaluator', function () {
         done();
       });
     });
-    it('should skip paintXObject if name is missing', function (done) {
+    it('should error on paintXObject if name is missing', function (done) {
       var stream = new _stream.StringStream('/ Do');
       runOperatorListCheck(partialEvaluator, stream, new ResourcesMock(), function (result) {
         expect(result instanceof _util.FormatError).toEqual(true);
@@ -281,7 +279,7 @@ describe('evaluator', function () {
         task: task,
         resources: resources,
         operatorList: result
-      }).catch(function () {
+      })["catch"](function () {
         expect(!!result.fnArray && !!result.argsArray).toEqual(true);
         expect(result.fnArray.length).toEqual(0);
         done();
@@ -296,7 +294,7 @@ describe('evaluator', function () {
         stream: stream,
         task: task,
         resources: resources
-      }).catch(function () {
+      })["catch"](function () {
         expect(true).toEqual(true);
         done();
       });

+ 109 - 0
lib/test/unit/fetch_stream_spec.js

@@ -0,0 +1,109 @@
+/**
+ * @licstart The following is the entire license notice for the
+ * Javascript code in this page
+ *
+ * Copyright 2019 Mozilla Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * @licend The above is the entire license notice for the
+ * Javascript code in this page
+ */
+"use strict";
+
+var _fetch_stream = require("../../display/fetch_stream");
+
+describe('fetch_stream', function () {
+  var pdfUrl = new URL('../pdfs/tracemonkey.pdf', window.location).href;
+  var pdfLength = 1016315;
+  it('read with streaming', function (done) {
+    var stream = new _fetch_stream.PDFFetchStream({
+      url: pdfUrl,
+      disableStream: false,
+      disableRange: true
+    });
+    var fullReader = stream.getFullReader();
+    var isStreamingSupported, isRangeSupported;
+    var promise = fullReader.headersReady.then(function () {
+      isStreamingSupported = fullReader.isStreamingSupported;
+      isRangeSupported = fullReader.isRangeSupported;
+    });
+    var len = 0;
+
+    var read = function read() {
+      return fullReader.read().then(function (result) {
+        if (result.done) {
+          return undefined;
+        }
+
+        len += result.value.byteLength;
+        return read();
+      });
+    };
+
+    var readPromise = Promise.all([read(), promise]);
+    readPromise.then(function () {
+      expect(len).toEqual(pdfLength);
+      expect(isStreamingSupported).toEqual(true);
+      expect(isRangeSupported).toEqual(false);
+      done();
+    })["catch"](done.fail);
+  });
+  it('read ranges with streaming', function (done) {
+    var rangeSize = 32768;
+    var stream = new _fetch_stream.PDFFetchStream({
+      url: pdfUrl,
+      rangeChunkSize: rangeSize,
+      disableStream: false,
+      disableRange: false
+    });
+    var fullReader = stream.getFullReader();
+    var isStreamingSupported, isRangeSupported, fullReaderCancelled;
+    var promise = fullReader.headersReady.then(function () {
+      isStreamingSupported = fullReader.isStreamingSupported;
+      isRangeSupported = fullReader.isRangeSupported;
+      fullReader.cancel(new Error('Don\'t need full reader'));
+      fullReaderCancelled = true;
+    });
+    var tailSize = pdfLength % rangeSize || rangeSize;
+    var rangeReader1 = stream.getRangeReader(pdfLength - tailSize - rangeSize, pdfLength - tailSize);
+    var rangeReader2 = stream.getRangeReader(pdfLength - tailSize, pdfLength);
+    var result1 = {
+      value: 0
+    },
+        result2 = {
+      value: 0
+    };
+
+    var read = function read(reader, lenResult) {
+      return reader.read().then(function (result) {
+        if (result.done) {
+          return undefined;
+        }
+
+        lenResult.value += result.value.byteLength;
+        return read(reader, lenResult);
+      });
+    };
+
+    var readPromise = Promise.all([read(rangeReader1, result1), read(rangeReader2, result2), promise]);
+    readPromise.then(function () {
+      expect(isStreamingSupported).toEqual(true);
+      expect(isRangeSupported).toEqual(true);
+      expect(fullReaderCancelled).toEqual(true);
+      expect(result1.value).toEqual(rangeSize);
+      expect(result2.value).toEqual(tailSize);
+      done();
+    })["catch"](done.fail);
+  });
+});

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor