pdfjs-dist 2.0.489 → 2.2.228

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pdfjs-dist might be problematic. Click here for more details.

Files changed (169) hide show
  1. package/CODE_OF_CONDUCT.md +15 -0
  2. package/bower.json +1 -1
  3. package/build/pdf.js +18515 -11402
  4. package/build/pdf.js.map +1 -1
  5. package/build/pdf.min.js +1 -1
  6. package/build/pdf.worker.js +48266 -37137
  7. package/build/pdf.worker.js.map +1 -1
  8. package/build/pdf.worker.min.js +1 -1
  9. package/external/url/url-lib.js +627 -0
  10. package/image_decoders/pdf.image_decoders.js +11350 -0
  11. package/image_decoders/pdf.image_decoders.js.map +1 -0
  12. package/image_decoders/pdf.image_decoders.min.js +1 -0
  13. package/lib/core/annotation.js +587 -242
  14. package/lib/core/arithmetic_decoder.js +275 -245
  15. package/lib/core/bidi.js +65 -6
  16. package/lib/core/ccitt.js +173 -18
  17. package/lib/core/ccitt_stream.js +15 -6
  18. package/lib/core/cff_parser.js +433 -61
  19. package/lib/core/charsets.js +5 -4
  20. package/lib/core/chunked_stream.js +400 -152
  21. package/lib/core/cmap.js +326 -87
  22. package/lib/core/colorspace.js +874 -594
  23. package/lib/core/core_utils.js +147 -0
  24. package/lib/core/crypto.js +290 -45
  25. package/lib/core/document.js +560 -268
  26. package/lib/core/encodings.js +19 -10
  27. package/lib/core/evaluator.js +1005 -360
  28. package/lib/core/font_renderer.js +331 -97
  29. package/lib/core/fonts.js +812 -195
  30. package/lib/core/function.js +284 -71
  31. package/lib/core/glyphlist.js +4 -3
  32. package/lib/core/image.js +169 -62
  33. package/lib/core/image_utils.js +111 -0
  34. package/lib/core/jbig2.js +479 -66
  35. package/lib/core/jbig2_stream.js +19 -8
  36. package/lib/core/jpeg_stream.js +38 -13
  37. package/lib/core/jpg.js +253 -29
  38. package/lib/core/jpx.js +396 -6
  39. package/lib/core/jpx_stream.js +18 -6
  40. package/lib/core/metrics.js +15 -15
  41. package/lib/core/murmurhash3.js +56 -34
  42. package/lib/core/obj.js +1354 -488
  43. package/lib/core/operator_list.js +144 -31
  44. package/lib/core/parser.js +539 -191
  45. package/lib/core/pattern.js +148 -14
  46. package/lib/core/pdf_manager.js +323 -133
  47. package/lib/core/primitives.js +111 -24
  48. package/lib/core/ps_parser.js +134 -45
  49. package/lib/core/standard_fonts.js +17 -17
  50. package/lib/core/stream.js +313 -34
  51. package/lib/core/type1_parser.js +143 -13
  52. package/lib/core/unicode.js +32 -5
  53. package/lib/core/worker.js +217 -190
  54. package/lib/core/worker_stream.js +277 -0
  55. package/lib/display/annotation_layer.js +450 -133
  56. package/lib/display/api.js +1597 -784
  57. package/lib/display/api_compatibility.js +11 -13
  58. package/lib/display/canvas.js +360 -44
  59. package/lib/display/content_disposition.js +83 -32
  60. package/lib/display/display_utils.js +747 -0
  61. package/lib/display/fetch_stream.js +221 -90
  62. package/lib/display/font_loader.js +468 -236
  63. package/lib/display/metadata.js +38 -16
  64. package/lib/display/network.js +635 -428
  65. package/lib/display/network_utils.js +32 -19
  66. package/lib/display/node_stream.js +367 -175
  67. package/lib/display/pattern_helper.js +81 -31
  68. package/lib/display/svg.js +1235 -519
  69. package/lib/display/text_layer.js +153 -29
  70. package/lib/display/transport_stream.js +345 -94
  71. package/lib/display/webgl.js +64 -18
  72. package/lib/display/worker_options.js +5 -4
  73. package/lib/display/xml_parser.js +166 -53
  74. package/lib/examples/node/domstubs.js +60 -4
  75. package/lib/pdf.js +36 -14
  76. package/lib/pdf.worker.js +5 -3
  77. package/lib/shared/compatibility.js +158 -564
  78. package/lib/shared/global_scope.js +2 -2
  79. package/lib/shared/is_node.js +4 -4
  80. package/lib/shared/message_handler.js +521 -0
  81. package/lib/shared/streams_polyfill.js +21 -17
  82. package/lib/shared/url_polyfill.js +56 -0
  83. package/lib/shared/util.js +243 -710
  84. package/lib/test/unit/annotation_spec.js +870 -401
  85. package/lib/test/unit/api_spec.js +657 -345
  86. package/lib/test/unit/bidi_spec.js +7 -7
  87. package/lib/test/unit/cff_parser_spec.js +54 -11
  88. package/lib/test/unit/clitests_helper.js +10 -8
  89. package/lib/test/unit/cmap_spec.js +95 -41
  90. package/lib/test/unit/colorspace_spec.js +115 -63
  91. package/lib/test/unit/core_utils_spec.js +191 -0
  92. package/lib/test/unit/crypto_spec.js +17 -5
  93. package/lib/test/unit/custom_spec.js +43 -55
  94. package/lib/test/unit/display_svg_spec.js +34 -18
  95. package/lib/test/unit/display_utils_spec.js +273 -0
  96. package/lib/test/unit/document_spec.js +8 -13
  97. package/lib/test/unit/encodings_spec.js +25 -45
  98. package/lib/test/unit/evaluator_spec.js +38 -15
  99. package/lib/test/unit/fetch_stream_spec.js +109 -0
  100. package/lib/test/unit/function_spec.js +17 -5
  101. package/lib/test/unit/jasmine-boot.js +33 -20
  102. package/lib/test/unit/{util_stream_spec.js → message_handler_spec.js} +41 -69
  103. package/lib/test/unit/metadata_spec.js +71 -11
  104. package/lib/test/unit/murmurhash3_spec.js +3 -3
  105. package/lib/test/unit/network_spec.js +19 -54
  106. package/lib/test/unit/network_utils_spec.js +91 -14
  107. package/lib/test/unit/node_stream_spec.js +56 -32
  108. package/lib/test/unit/parser_spec.js +162 -71
  109. package/lib/test/unit/pdf_find_controller_spec.js +230 -0
  110. package/lib/test/unit/pdf_find_utils_spec.js +63 -0
  111. package/lib/test/unit/pdf_history_spec.js +21 -9
  112. package/lib/test/unit/primitives_spec.js +53 -20
  113. package/lib/test/unit/stream_spec.js +12 -4
  114. package/lib/test/unit/test_utils.js +273 -56
  115. package/lib/test/unit/testreporter.js +21 -3
  116. package/lib/test/unit/type1_parser_spec.js +8 -6
  117. package/lib/test/unit/ui_utils_spec.js +454 -16
  118. package/lib/test/unit/unicode_spec.js +18 -15
  119. package/lib/test/unit/util_spec.js +87 -128
  120. package/lib/web/annotation_layer_builder.js +39 -22
  121. package/lib/web/app.js +1290 -588
  122. package/lib/web/app_options.js +100 -62
  123. package/lib/web/base_viewer.js +511 -182
  124. package/lib/web/chromecom.js +261 -117
  125. package/lib/web/debugger.js +166 -22
  126. package/lib/web/download_manager.js +32 -13
  127. package/lib/web/firefox_print_service.js +20 -10
  128. package/lib/web/firefoxcom.js +315 -80
  129. package/lib/web/genericcom.js +89 -30
  130. package/lib/web/genericl10n.js +142 -30
  131. package/lib/web/grab_to_pan.js +28 -4
  132. package/lib/web/interfaces.js +170 -47
  133. package/lib/web/overlay_manager.js +235 -85
  134. package/lib/web/password_prompt.js +22 -14
  135. package/lib/web/pdf_attachment_viewer.js +38 -18
  136. package/lib/web/pdf_cursor_tools.js +39 -16
  137. package/lib/web/pdf_document_properties.js +255 -136
  138. package/lib/web/pdf_find_bar.js +84 -40
  139. package/lib/web/pdf_find_controller.js +495 -184
  140. package/lib/web/pdf_find_utils.js +111 -0
  141. package/lib/web/pdf_history.js +190 -53
  142. package/lib/web/pdf_link_service.js +138 -77
  143. package/lib/web/pdf_outline_viewer.js +122 -46
  144. package/lib/web/pdf_page_view.js +191 -67
  145. package/lib/web/pdf_presentation_mode.js +99 -34
  146. package/lib/web/pdf_print_service.js +61 -13
  147. package/lib/web/pdf_rendering_queue.js +28 -9
  148. package/lib/web/pdf_sidebar.js +141 -81
  149. package/lib/web/pdf_sidebar_resizer.js +42 -16
  150. package/lib/web/pdf_single_page_viewer.js +74 -66
  151. package/lib/web/pdf_thumbnail_view.js +104 -33
  152. package/lib/web/pdf_thumbnail_viewer.js +66 -26
  153. package/lib/web/pdf_viewer.component.js +112 -32
  154. package/lib/web/pdf_viewer.js +91 -52
  155. package/lib/web/preferences.js +284 -89
  156. package/lib/web/secondary_toolbar.js +165 -40
  157. package/lib/web/text_layer_builder.js +134 -59
  158. package/lib/web/toolbar.js +78 -43
  159. package/lib/web/ui_utils.js +462 -136
  160. package/lib/web/view_history.js +215 -67
  161. package/lib/web/viewer_compatibility.js +4 -13
  162. package/package.json +5 -4
  163. package/web/pdf_viewer.css +79 -11
  164. package/web/pdf_viewer.js +6107 -3748
  165. package/web/pdf_viewer.js.map +1 -1
  166. package/lib/display/dom_utils.js +0 -309
  167. package/lib/test/unit/dom_utils_spec.js +0 -89
  168. package/lib/test/unit/fonts_spec.js +0 -81
  169. package/lib/web/dom_events.js +0 -137
package/lib/core/obj.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * @licstart The following is the entire license notice for the
3
3
  * Javascript code in this page
4
4
  *
5
- * Copyright 2017 Mozilla Foundation
5
+ * Copyright 2019 Mozilla Foundation
6
6
  *
7
7
  * Licensed under the Apache License, Version 2.0 (the "License");
8
8
  * you may not use this file except in compliance with the License.
@@ -19,97 +19,102 @@
19
19
  * @licend The above is the entire license notice for the
20
20
  * Javascript code in this page
21
21
  */
22
- 'use strict';
22
+ "use strict";
23
23
 
24
24
  Object.defineProperty(exports, "__esModule", {
25
25
  value: true
26
26
  });
27
- exports.FileSpec = exports.XRef = exports.ObjectLoader = exports.Catalog = undefined;
27
+ exports.FileSpec = exports.XRef = exports.ObjectLoader = exports.Catalog = void 0;
28
28
 
29
- var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
29
+ var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
30
30
 
31
- var _slicedToArray = function () { function sliceIterator(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"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
31
+ var _util = require("../shared/util");
32
32
 
33
- var _util = require('../shared/util');
33
+ var _primitives = require("./primitives");
34
34
 
35
- var _primitives = require('./primitives');
35
+ var _parser = require("./parser");
36
36
 
37
- var _parser = require('./parser');
37
+ var _core_utils = require("./core_utils");
38
38
 
39
- var _chunked_stream = require('./chunked_stream');
39
+ var _chunked_stream = require("./chunked_stream");
40
40
 
41
- var _crypto = require('./crypto');
41
+ var _crypto = require("./crypto");
42
42
 
43
- var _colorspace = require('./colorspace');
43
+ var _colorspace = require("./colorspace");
44
+
45
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
46
+
47
+ function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
48
+
49
+ function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
50
+
51
+ function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
52
+
53
+ 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); }
54
+
55
+ function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
56
+
57
+ 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); } }
58
+
59
+ 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); }); }; }
60
+
61
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
62
+
63
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
64
+
65
+ 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; }
66
+
67
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
68
+
69
+ 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); }
70
+
71
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
72
+
73
+ 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); } }
74
+
75
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
76
+
77
+ function fetchDestination(dest) {
78
+ return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
79
+ }
80
+
81
+ var Catalog =
82
+ /*#__PURE__*/
83
+ function () {
84
+ function Catalog(pdfManager, xref) {
85
+ _classCallCheck(this, Catalog);
44
86
 
45
- var Catalog = function CatalogClosure() {
46
- function Catalog(pdfManager, xref, pageFactory) {
47
87
  this.pdfManager = pdfManager;
48
88
  this.xref = xref;
49
89
  this.catDict = xref.getCatalogObj();
90
+
50
91
  if (!(0, _primitives.isDict)(this.catDict)) {
51
- throw new _util.FormatError('catalog object is not a dictionary');
92
+ throw new _util.FormatError('Catalog object is not a dictionary.');
52
93
  }
94
+
53
95
  this.fontCache = new _primitives.RefSetCache();
54
- this.builtInCMapCache = Object.create(null);
96
+ this.builtInCMapCache = new Map();
55
97
  this.pageKidsCountCache = new _primitives.RefSetCache();
56
- this.pageFactory = pageFactory;
57
- this.pagePromises = [];
58
98
  }
59
- Catalog.prototype = {
60
- get metadata() {
61
- var streamRef = this.catDict.getRaw('Metadata');
62
- if (!(0, _primitives.isRef)(streamRef)) {
63
- return (0, _util.shadow)(this, 'metadata', null);
64
- }
65
- var encryptMetadata = !this.xref.encrypt ? false : this.xref.encrypt.encryptMetadata;
66
- var stream = this.xref.fetch(streamRef, !encryptMetadata);
67
- var metadata;
68
- if (stream && (0, _primitives.isDict)(stream.dict)) {
69
- var type = stream.dict.get('Type');
70
- var subtype = stream.dict.get('Subtype');
71
- if ((0, _primitives.isName)(type, 'Metadata') && (0, _primitives.isName)(subtype, 'XML')) {
72
- try {
73
- metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
74
- } catch (e) {
75
- if (e instanceof _util.MissingDataException) {
76
- throw e;
77
- }
78
- (0, _util.info)('Skipping invalid metadata.');
79
- }
80
- }
81
- }
82
- return (0, _util.shadow)(this, 'metadata', metadata);
83
- },
84
- get toplevelPagesDict() {
85
- var pagesObj = this.catDict.get('Pages');
86
- if (!(0, _primitives.isDict)(pagesObj)) {
87
- throw new _util.FormatError('invalid top-level pages dictionary');
88
- }
89
- return (0, _util.shadow)(this, 'toplevelPagesDict', pagesObj);
90
- },
91
- get documentOutline() {
92
- var obj = null;
93
- try {
94
- obj = this.readDocumentOutline();
95
- } catch (ex) {
96
- if (ex instanceof _util.MissingDataException) {
97
- throw ex;
98
- }
99
- (0, _util.warn)('Unable to read document outline');
100
- }
101
- return (0, _util.shadow)(this, 'documentOutline', obj);
102
- },
103
- readDocumentOutline: function Catalog_readDocumentOutline() {
99
+
100
+ _createClass(Catalog, [{
101
+ key: "_readDocumentOutline",
102
+ value: function _readDocumentOutline() {
104
103
  var obj = this.catDict.get('Outlines');
104
+
105
105
  if (!(0, _primitives.isDict)(obj)) {
106
106
  return null;
107
107
  }
108
+
108
109
  obj = obj.getRaw('First');
110
+
109
111
  if (!(0, _primitives.isRef)(obj)) {
110
112
  return null;
111
113
  }
112
- var root = { items: [] };
114
+
115
+ var root = {
116
+ items: []
117
+ };
113
118
  var queue = [{
114
119
  obj: obj,
115
120
  parent: root
@@ -117,16 +122,20 @@ var Catalog = function CatalogClosure() {
117
122
  var processed = new _primitives.RefSet();
118
123
  processed.put(obj);
119
124
  var xref = this.xref,
120
- blackColor = new Uint8Array(3);
125
+ blackColor = new Uint8ClampedArray(3);
126
+
121
127
  while (queue.length > 0) {
122
128
  var i = queue.shift();
123
129
  var outlineDict = xref.fetchIfRef(i.obj);
130
+
124
131
  if (outlineDict === null) {
125
132
  continue;
126
133
  }
134
+
127
135
  if (!outlineDict.has('Title')) {
128
- throw new _util.FormatError('Invalid outline item');
136
+ throw new _util.FormatError('Invalid outline item encountered.');
129
137
  }
138
+
130
139
  var data = {
131
140
  url: null,
132
141
  dest: null
@@ -138,11 +147,14 @@ var Catalog = function CatalogClosure() {
138
147
  });
139
148
  var title = outlineDict.get('Title');
140
149
  var flags = outlineDict.get('F') || 0;
141
- var color = outlineDict.getArray('C'),
142
- rgbColor = blackColor;
150
+ var color = outlineDict.getArray('C');
151
+ var count = outlineDict.get('Count');
152
+ var rgbColor = blackColor;
153
+
143
154
  if (Array.isArray(color) && color.length === 3 && (color[0] !== 0 || color[1] !== 0 || color[2] !== 0)) {
144
155
  rgbColor = _colorspace.ColorSpace.singletons.rgb.getRgb(color, 0);
145
156
  }
157
+
146
158
  var outlineItem = {
147
159
  dest: data.dest,
148
160
  url: data.url,
@@ -150,13 +162,14 @@ var Catalog = function CatalogClosure() {
150
162
  newWindow: data.newWindow,
151
163
  title: (0, _util.stringToPDFString)(title),
152
164
  color: rgbColor,
153
- count: outlineDict.get('Count'),
165
+ count: Number.isInteger(count) ? count : undefined,
154
166
  bold: !!(flags & 2),
155
167
  italic: !!(flags & 1),
156
168
  items: []
157
169
  };
158
170
  i.parent.items.push(outlineItem);
159
171
  obj = outlineDict.getRaw('First');
172
+
160
173
  if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
161
174
  queue.push({
162
175
  obj: obj,
@@ -164,7 +177,9 @@ var Catalog = function CatalogClosure() {
164
177
  });
165
178
  processed.put(obj);
166
179
  }
180
+
167
181
  obj = outlineDict.getRaw('Next');
182
+
168
183
  if ((0, _primitives.isRef)(obj) && !processed.has(obj)) {
169
184
  queue.push({
170
185
  obj: obj,
@@ -173,142 +188,137 @@ var Catalog = function CatalogClosure() {
173
188
  processed.put(obj);
174
189
  }
175
190
  }
191
+
176
192
  return root.items.length > 0 ? root.items : null;
177
- },
178
- get numPages() {
179
- var obj = this.toplevelPagesDict.get('Count');
180
- if (!Number.isInteger(obj)) {
181
- throw new _util.FormatError('page count in top level pages object is not an integer');
182
- }
183
- return (0, _util.shadow)(this, 'numPages', obj);
184
- },
185
- get destinations() {
186
- function fetchDestination(dest) {
187
- return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
188
- }
189
- var xref = this.xref;
190
- var dests = {},
191
- nameTreeRef,
192
- nameDictionaryRef;
193
- var obj = this.catDict.get('Names');
194
- if (obj && obj.has('Dests')) {
195
- nameTreeRef = obj.getRaw('Dests');
196
- } else if (this.catDict.has('Dests')) {
197
- nameDictionaryRef = this.catDict.get('Dests');
193
+ }
194
+ }, {
195
+ key: "_readPermissions",
196
+ value: function _readPermissions() {
197
+ var encrypt = this.xref.trailer.get('Encrypt');
198
+
199
+ if (!(0, _primitives.isDict)(encrypt)) {
200
+ return null;
198
201
  }
199
- if (nameDictionaryRef) {
200
- obj = nameDictionaryRef;
201
- obj.forEach(function catalogForEach(key, value) {
202
- if (!value) {
203
- return;
204
- }
205
- dests[key] = fetchDestination(value);
206
- });
202
+
203
+ var flags = encrypt.get('P');
204
+
205
+ if (!(0, _util.isNum)(flags)) {
206
+ return null;
207
207
  }
208
- if (nameTreeRef) {
209
- var nameTree = new NameTree(nameTreeRef, xref);
210
- var names = nameTree.getAll();
211
- for (var name in names) {
212
- dests[name] = fetchDestination(names[name]);
208
+
209
+ flags += Math.pow(2, 32);
210
+ var permissions = [];
211
+
212
+ for (var key in _util.PermissionFlag) {
213
+ var value = _util.PermissionFlag[key];
214
+
215
+ if (flags & value) {
216
+ permissions.push(value);
213
217
  }
214
218
  }
215
- return (0, _util.shadow)(this, 'destinations', dests);
216
- },
217
- getDestination: function Catalog_getDestination(destinationId) {
218
- function fetchDestination(dest) {
219
- return (0, _primitives.isDict)(dest) ? dest.get('D') : dest;
219
+
220
+ return permissions;
221
+ }
222
+ }, {
223
+ key: "getDestination",
224
+ value: function getDestination(destinationId) {
225
+ var obj = this._readDests();
226
+
227
+ if (obj instanceof NameTree || obj instanceof _primitives.Dict) {
228
+ return fetchDestination(obj.get(destinationId) || null);
220
229
  }
221
- var xref = this.xref;
222
- var dest = null,
223
- nameTreeRef,
224
- nameDictionaryRef;
230
+
231
+ return null;
232
+ }
233
+ }, {
234
+ key: "_readDests",
235
+ value: function _readDests() {
225
236
  var obj = this.catDict.get('Names');
237
+
226
238
  if (obj && obj.has('Dests')) {
227
- nameTreeRef = obj.getRaw('Dests');
239
+ return new NameTree(obj.getRaw('Dests'), this.xref);
228
240
  } else if (this.catDict.has('Dests')) {
229
- nameDictionaryRef = this.catDict.get('Dests');
230
- }
231
- if (nameDictionaryRef) {
232
- var value = nameDictionaryRef.get(destinationId);
233
- if (value) {
234
- dest = fetchDestination(value);
235
- }
236
- }
237
- if (nameTreeRef) {
238
- var nameTree = new NameTree(nameTreeRef, xref);
239
- dest = fetchDestination(nameTree.get(destinationId));
240
- }
241
- return dest;
242
- },
243
- get pageLabels() {
244
- var obj = null;
245
- try {
246
- obj = this.readPageLabels();
247
- } catch (ex) {
248
- if (ex instanceof _util.MissingDataException) {
249
- throw ex;
250
- }
251
- (0, _util.warn)('Unable to read page labels.');
241
+ return this.catDict.get('Dests');
252
242
  }
253
- return (0, _util.shadow)(this, 'pageLabels', obj);
254
- },
255
- readPageLabels: function Catalog_readPageLabels() {
243
+
244
+ return undefined;
245
+ }
246
+ }, {
247
+ key: "_readPageLabels",
248
+ value: function _readPageLabels() {
256
249
  var obj = this.catDict.getRaw('PageLabels');
250
+
257
251
  if (!obj) {
258
252
  return null;
259
253
  }
254
+
260
255
  var pageLabels = new Array(this.numPages);
261
- var style = null;
262
- var prefix = '';
256
+ var style = null,
257
+ prefix = '';
263
258
  var numberTree = new NumberTree(obj, this.xref);
264
259
  var nums = numberTree.getAll();
265
260
  var currentLabel = '',
266
261
  currentIndex = 1;
262
+
267
263
  for (var i = 0, ii = this.numPages; i < ii; i++) {
268
264
  if (i in nums) {
269
265
  var labelDict = nums[i];
266
+
270
267
  if (!(0, _primitives.isDict)(labelDict)) {
271
- throw new _util.FormatError('The PageLabel is not a dictionary.');
268
+ throw new _util.FormatError('PageLabel is not a dictionary.');
272
269
  }
270
+
273
271
  if (labelDict.has('Type') && !(0, _primitives.isName)(labelDict.get('Type'), 'PageLabel')) {
274
272
  throw new _util.FormatError('Invalid type in PageLabel dictionary.');
275
273
  }
274
+
276
275
  if (labelDict.has('S')) {
277
276
  var s = labelDict.get('S');
277
+
278
278
  if (!(0, _primitives.isName)(s)) {
279
279
  throw new _util.FormatError('Invalid style in PageLabel dictionary.');
280
280
  }
281
+
281
282
  style = s.name;
282
283
  } else {
283
284
  style = null;
284
285
  }
286
+
285
287
  if (labelDict.has('P')) {
286
288
  var p = labelDict.get('P');
289
+
287
290
  if (!(0, _util.isString)(p)) {
288
291
  throw new _util.FormatError('Invalid prefix in PageLabel dictionary.');
289
292
  }
293
+
290
294
  prefix = (0, _util.stringToPDFString)(p);
291
295
  } else {
292
296
  prefix = '';
293
297
  }
298
+
294
299
  if (labelDict.has('St')) {
295
300
  var st = labelDict.get('St');
301
+
296
302
  if (!(Number.isInteger(st) && st >= 1)) {
297
303
  throw new _util.FormatError('Invalid start in PageLabel dictionary.');
298
304
  }
305
+
299
306
  currentIndex = st;
300
307
  } else {
301
308
  currentIndex = 1;
302
309
  }
303
310
  }
311
+
304
312
  switch (style) {
305
313
  case 'D':
306
314
  currentLabel = currentIndex;
307
315
  break;
316
+
308
317
  case 'R':
309
318
  case 'r':
310
- currentLabel = _util.Util.toRoman(currentIndex, style === 'r');
319
+ currentLabel = (0, _core_utils.toRomanNumerals)(currentIndex, style === 'r');
311
320
  break;
321
+
312
322
  case 'A':
313
323
  case 'a':
314
324
  var LIMIT = 26;
@@ -318,109 +328,71 @@ var Catalog = function CatalogClosure() {
318
328
  var letterIndex = currentIndex - 1;
319
329
  var character = String.fromCharCode(baseCharCode + letterIndex % LIMIT);
320
330
  var charBuf = [];
331
+
321
332
  for (var j = 0, jj = letterIndex / LIMIT | 0; j <= jj; j++) {
322
333
  charBuf.push(character);
323
334
  }
335
+
324
336
  currentLabel = charBuf.join('');
325
337
  break;
338
+
326
339
  default:
327
340
  if (style) {
328
- throw new _util.FormatError('Invalid style "' + style + '" in PageLabel dictionary.');
341
+ throw new _util.FormatError("Invalid style \"".concat(style, "\" in PageLabel dictionary."));
329
342
  }
343
+
330
344
  currentLabel = '';
331
345
  }
346
+
332
347
  pageLabels[i] = prefix + currentLabel;
333
348
  currentIndex++;
334
349
  }
350
+
335
351
  return pageLabels;
336
- },
337
- get pageMode() {
338
- var obj = this.catDict.get('PageMode');
339
- var pageMode = 'UseNone';
340
- if ((0, _primitives.isName)(obj)) {
341
- switch (obj.name) {
342
- case 'UseNone':
343
- case 'UseOutlines':
344
- case 'UseThumbs':
345
- case 'FullScreen':
346
- case 'UseOC':
347
- case 'UseAttachments':
348
- pageMode = obj.name;
349
- }
350
- }
351
- return (0, _util.shadow)(this, 'pageMode', pageMode);
352
- },
353
- get attachments() {
354
- var xref = this.xref;
355
- var attachments = null,
356
- nameTreeRef;
357
- var obj = this.catDict.get('Names');
358
- if (obj) {
359
- nameTreeRef = obj.getRaw('EmbeddedFiles');
360
- }
361
- if (nameTreeRef) {
362
- var nameTree = new NameTree(nameTreeRef, xref);
363
- var names = nameTree.getAll();
364
- for (var name in names) {
365
- var fs = new FileSpec(names[name], xref);
366
- if (!attachments) {
367
- attachments = Object.create(null);
368
- }
369
- attachments[(0, _util.stringToPDFString)(name)] = fs.serializable;
370
- }
371
- }
372
- return (0, _util.shadow)(this, 'attachments', attachments);
373
- },
374
- get javaScript() {
375
- var xref = this.xref;
376
- var obj = this.catDict.get('Names');
377
- var javaScript = null;
378
- function appendIfJavaScriptDict(jsDict) {
379
- var type = jsDict.get('S');
380
- if (!(0, _primitives.isName)(type, 'JavaScript')) {
381
- return;
382
- }
383
- var js = jsDict.get('JS');
384
- if ((0, _primitives.isStream)(js)) {
385
- js = (0, _util.bytesToString)(js.getBytes());
386
- } else if (!(0, _util.isString)(js)) {
387
- return;
388
- }
389
- if (!javaScript) {
390
- javaScript = [];
391
- }
392
- javaScript.push((0, _util.stringToPDFString)(js));
393
- }
394
- if (obj && obj.has('JavaScript')) {
395
- var nameTree = new NameTree(obj.getRaw('JavaScript'), xref);
396
- var names = nameTree.getAll();
397
- for (var name in names) {
398
- var jsDict = names[name];
399
- if ((0, _primitives.isDict)(jsDict)) {
400
- appendIfJavaScriptDict(jsDict);
352
+ }
353
+ }, {
354
+ key: "fontFallback",
355
+ value: function fontFallback(id, handler) {
356
+ var promises = [];
357
+ this.fontCache.forEach(function (promise) {
358
+ promises.push(promise);
359
+ });
360
+ return Promise.all(promises).then(function (translatedFonts) {
361
+ var _iteratorNormalCompletion = true;
362
+ var _didIteratorError = false;
363
+ var _iteratorError = undefined;
364
+
365
+ try {
366
+ for (var _iterator = translatedFonts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
367
+ var translatedFont = _step.value;
368
+
369
+ if (translatedFont.loadedName === id) {
370
+ translatedFont.fallback(handler);
371
+ return;
372
+ }
401
373
  }
402
- }
403
- }
404
- var openactionDict = this.catDict.get('OpenAction');
405
- if ((0, _primitives.isDict)(openactionDict, 'Action')) {
406
- var actionType = openactionDict.get('S');
407
- if ((0, _primitives.isName)(actionType, 'Named')) {
408
- var action = openactionDict.get('N');
409
- if ((0, _primitives.isName)(action, 'Print')) {
410
- if (!javaScript) {
411
- javaScript = [];
374
+ } catch (err) {
375
+ _didIteratorError = true;
376
+ _iteratorError = err;
377
+ } finally {
378
+ try {
379
+ if (!_iteratorNormalCompletion && _iterator["return"] != null) {
380
+ _iterator["return"]();
381
+ }
382
+ } finally {
383
+ if (_didIteratorError) {
384
+ throw _iteratorError;
412
385
  }
413
- javaScript.push('print({});');
414
386
  }
415
- } else {
416
- appendIfJavaScriptDict(openactionDict);
417
387
  }
418
- }
419
- return (0, _util.shadow)(this, 'javaScript', javaScript);
420
- },
421
- cleanup: function Catalog_cleanup() {
388
+ });
389
+ }
390
+ }, {
391
+ key: "cleanup",
392
+ value: function cleanup() {
422
393
  var _this = this;
423
394
 
395
+ (0, _primitives.clearPrimitiveCaches)();
424
396
  this.pageKidsCountCache.clear();
425
397
  var promises = [];
426
398
  this.fontCache.forEach(function (promise) {
@@ -431,299 +403,826 @@ var Catalog = function CatalogClosure() {
431
403
  var font = translatedFonts[i].dict;
432
404
  delete font.translated;
433
405
  }
434
- _this.fontCache.clear();
435
- _this.builtInCMapCache = Object.create(null);
436
- });
437
- },
438
- getPage: function Catalog_getPage(pageIndex) {
439
- var _this2 = this;
440
406
 
441
- if (!(pageIndex in this.pagePromises)) {
442
- this.pagePromises[pageIndex] = this.getPageDict(pageIndex).then(function (_ref) {
443
- var _ref2 = _slicedToArray(_ref, 2),
444
- dict = _ref2[0],
445
- ref = _ref2[1];
407
+ _this.fontCache.clear();
446
408
 
447
- return _this2.pageFactory.createPage(pageIndex, dict, ref, _this2.fontCache, _this2.builtInCMapCache);
448
- });
449
- }
450
- return this.pagePromises[pageIndex];
451
- },
452
- getPageDict: function Catalog_getPageDict(pageIndex) {
409
+ _this.builtInCMapCache.clear();
410
+ });
411
+ }
412
+ }, {
413
+ key: "getPageDict",
414
+ value: function getPageDict(pageIndex) {
453
415
  var capability = (0, _util.createPromiseCapability)();
454
416
  var nodesToVisit = [this.catDict.getRaw('Pages')];
455
- var count,
456
- currentPageIndex = 0;
457
417
  var xref = this.xref,
458
418
  pageKidsCountCache = this.pageKidsCountCache;
419
+ var count,
420
+ currentPageIndex = 0;
421
+
459
422
  function next() {
460
- while (nodesToVisit.length) {
423
+ var _loop = function _loop() {
461
424
  var currentNode = nodesToVisit.pop();
425
+
462
426
  if ((0, _primitives.isRef)(currentNode)) {
463
427
  count = pageKidsCountCache.get(currentNode);
428
+
464
429
  if (count > 0 && currentPageIndex + count < pageIndex) {
465
430
  currentPageIndex += count;
466
- continue;
431
+ return "continue";
467
432
  }
433
+
468
434
  xref.fetchAsync(currentNode).then(function (obj) {
469
435
  if ((0, _primitives.isDict)(obj, 'Page') || (0, _primitives.isDict)(obj) && !obj.has('Kids')) {
470
436
  if (pageIndex === currentPageIndex) {
471
437
  if (currentNode && !pageKidsCountCache.has(currentNode)) {
472
438
  pageKidsCountCache.put(currentNode, 1);
473
439
  }
440
+
474
441
  capability.resolve([obj, currentNode]);
475
442
  } else {
476
443
  currentPageIndex++;
477
444
  next();
478
445
  }
446
+
479
447
  return;
480
448
  }
449
+
481
450
  nodesToVisit.push(obj);
482
451
  next();
483
452
  }, capability.reject);
484
- return;
453
+ return {
454
+ v: void 0
455
+ };
485
456
  }
457
+
486
458
  if (!(0, _primitives.isDict)(currentNode)) {
487
- capability.reject(new _util.FormatError('page dictionary kid reference points to wrong type of object'));
488
- return;
459
+ capability.reject(new _util.FormatError('Page dictionary kid reference points to wrong type of object.'));
460
+ return {
461
+ v: void 0
462
+ };
489
463
  }
464
+
490
465
  count = currentNode.get('Count');
466
+
491
467
  if (Number.isInteger(count) && count >= 0) {
492
468
  var objId = currentNode.objId;
469
+
493
470
  if (objId && !pageKidsCountCache.has(objId)) {
494
471
  pageKidsCountCache.put(objId, count);
495
472
  }
473
+
496
474
  if (currentPageIndex + count <= pageIndex) {
497
475
  currentPageIndex += count;
498
- continue;
476
+ return "continue";
499
477
  }
500
478
  }
479
+
501
480
  var kids = currentNode.get('Kids');
481
+
502
482
  if (!Array.isArray(kids)) {
503
483
  if ((0, _primitives.isName)(currentNode.get('Type'), 'Page') || !currentNode.has('Type') && currentNode.has('Contents')) {
504
484
  if (currentPageIndex === pageIndex) {
505
485
  capability.resolve([currentNode, null]);
506
- return;
486
+ return {
487
+ v: void 0
488
+ };
507
489
  }
490
+
508
491
  currentPageIndex++;
509
- continue;
492
+ return "continue";
510
493
  }
511
- capability.reject(new _util.FormatError('page dictionary kids object is not an array'));
512
- return;
494
+
495
+ capability.reject(new _util.FormatError('Page dictionary kids object is not an array.'));
496
+ return {
497
+ v: void 0
498
+ };
513
499
  }
500
+
514
501
  for (var last = kids.length - 1; last >= 0; last--) {
515
502
  nodesToVisit.push(kids[last]);
516
503
  }
504
+ };
505
+
506
+ while (nodesToVisit.length) {
507
+ var _ret = _loop();
508
+
509
+ switch (_ret) {
510
+ case "continue":
511
+ continue;
512
+
513
+ default:
514
+ if (_typeof(_ret) === "object") return _ret.v;
515
+ }
517
516
  }
518
- capability.reject(new Error('Page index ' + pageIndex + ' not found.'));
517
+
518
+ capability.reject(new Error("Page index ".concat(pageIndex, " not found.")));
519
519
  }
520
+
520
521
  next();
521
522
  return capability.promise;
522
- },
523
- getPageIndex: function Catalog_getPageIndex(pageRef) {
523
+ }
524
+ }, {
525
+ key: "getPageIndex",
526
+ value: function getPageIndex(pageRef) {
524
527
  var xref = this.xref;
528
+
525
529
  function pagesBeforeRef(kidRef) {
526
- var total = 0;
527
- var parentRef;
530
+ var total = 0,
531
+ parentRef;
528
532
  return xref.fetchAsync(kidRef).then(function (node) {
529
533
  if ((0, _primitives.isRefsEqual)(kidRef, pageRef) && !(0, _primitives.isDict)(node, 'Page') && !((0, _primitives.isDict)(node) && !node.has('Type') && node.has('Contents'))) {
530
- throw new _util.FormatError('The reference does not point to a /Page Dict.');
534
+ throw new _util.FormatError('The reference does not point to a /Page dictionary.');
531
535
  }
536
+
532
537
  if (!node) {
533
538
  return null;
534
539
  }
540
+
535
541
  if (!(0, _primitives.isDict)(node)) {
536
- throw new _util.FormatError('node must be a Dict.');
542
+ throw new _util.FormatError('Node must be a dictionary.');
537
543
  }
544
+
538
545
  parentRef = node.getRaw('Parent');
539
546
  return node.getAsync('Parent');
540
547
  }).then(function (parent) {
541
548
  if (!parent) {
542
549
  return null;
543
550
  }
551
+
544
552
  if (!(0, _primitives.isDict)(parent)) {
545
- throw new _util.FormatError('parent must be a Dict.');
553
+ throw new _util.FormatError('Parent must be a dictionary.');
546
554
  }
555
+
547
556
  return parent.getAsync('Kids');
548
557
  }).then(function (kids) {
549
558
  if (!kids) {
550
559
  return null;
551
560
  }
561
+
552
562
  var kidPromises = [];
553
563
  var found = false;
554
- for (var i = 0; i < kids.length; i++) {
564
+
565
+ for (var i = 0, ii = kids.length; i < ii; i++) {
555
566
  var kid = kids[i];
567
+
556
568
  if (!(0, _primitives.isRef)(kid)) {
557
- throw new _util.FormatError('kid must be a Ref.');
569
+ throw new _util.FormatError('Kid must be a reference.');
558
570
  }
571
+
559
572
  if ((0, _primitives.isRefsEqual)(kid, kidRef)) {
560
573
  found = true;
561
574
  break;
562
575
  }
576
+
563
577
  kidPromises.push(xref.fetchAsync(kid).then(function (kid) {
564
578
  if (!(0, _primitives.isDict)(kid)) {
565
- throw new _util.FormatError('kid node must be a Dict.');
579
+ throw new _util.FormatError('Kid node must be a dictionary.');
566
580
  }
581
+
567
582
  if (kid.has('Count')) {
568
- var count = kid.get('Count');
569
- total += count;
583
+ total += kid.get('Count');
570
584
  } else {
571
585
  total++;
572
586
  }
573
587
  }));
574
588
  }
589
+
575
590
  if (!found) {
576
- throw new _util.FormatError('kid ref not found in parents kids');
591
+ throw new _util.FormatError('Kid reference not found in parent\'s kids.');
577
592
  }
593
+
578
594
  return Promise.all(kidPromises).then(function () {
579
595
  return [total, parentRef];
580
596
  });
581
597
  });
582
598
  }
599
+
583
600
  var total = 0;
601
+
584
602
  function next(ref) {
585
603
  return pagesBeforeRef(ref).then(function (args) {
586
604
  if (!args) {
587
605
  return total;
588
606
  }
589
- var count = args[0];
590
- var parentRef = args[1];
607
+
608
+ var _args = _slicedToArray(args, 2),
609
+ count = _args[0],
610
+ parentRef = _args[1];
611
+
591
612
  total += count;
592
613
  return next(parentRef);
593
614
  });
594
615
  }
616
+
595
617
  return next(pageRef);
596
618
  }
597
- };
598
- Catalog.parseDestDictionary = function Catalog_parseDestDictionary(params) {
599
- function addDefaultProtocolToUrl(url) {
600
- if (url.indexOf('www.') === 0) {
601
- return 'http://' + url;
619
+ }, {
620
+ key: "metadata",
621
+ get: function get() {
622
+ var streamRef = this.catDict.getRaw('Metadata');
623
+
624
+ if (!(0, _primitives.isRef)(streamRef)) {
625
+ return (0, _util.shadow)(this, 'metadata', null);
626
+ }
627
+
628
+ var suppressEncryption = !(this.xref.encrypt && this.xref.encrypt.encryptMetadata);
629
+ var stream = this.xref.fetch(streamRef, suppressEncryption);
630
+ var metadata;
631
+
632
+ if (stream && (0, _primitives.isDict)(stream.dict)) {
633
+ var type = stream.dict.get('Type');
634
+ var subtype = stream.dict.get('Subtype');
635
+
636
+ if ((0, _primitives.isName)(type, 'Metadata') && (0, _primitives.isName)(subtype, 'XML')) {
637
+ try {
638
+ metadata = (0, _util.stringToUTF8String)((0, _util.bytesToString)(stream.getBytes()));
639
+ } catch (e) {
640
+ if (e instanceof _core_utils.MissingDataException) {
641
+ throw e;
642
+ }
643
+
644
+ (0, _util.info)('Skipping invalid metadata.');
645
+ }
646
+ }
647
+ }
648
+
649
+ return (0, _util.shadow)(this, 'metadata', metadata);
650
+ }
651
+ }, {
652
+ key: "toplevelPagesDict",
653
+ get: function get() {
654
+ var pagesObj = this.catDict.get('Pages');
655
+
656
+ if (!(0, _primitives.isDict)(pagesObj)) {
657
+ throw new _util.FormatError('Invalid top-level pages dictionary.');
602
658
  }
603
- return url;
659
+
660
+ return (0, _util.shadow)(this, 'toplevelPagesDict', pagesObj);
604
661
  }
605
- function tryConvertUrlEncoding(url) {
662
+ }, {
663
+ key: "documentOutline",
664
+ get: function get() {
665
+ var obj = null;
666
+
606
667
  try {
607
- return (0, _util.stringToUTF8String)(url);
608
- } catch (e) {
609
- return url;
668
+ obj = this._readDocumentOutline();
669
+ } catch (ex) {
670
+ if (ex instanceof _core_utils.MissingDataException) {
671
+ throw ex;
672
+ }
673
+
674
+ (0, _util.warn)('Unable to read document outline.');
610
675
  }
676
+
677
+ return (0, _util.shadow)(this, 'documentOutline', obj);
611
678
  }
612
- var destDict = params.destDict;
613
- if (!(0, _primitives.isDict)(destDict)) {
614
- (0, _util.warn)('parseDestDictionary: "destDict" must be a dictionary.');
615
- return;
679
+ }, {
680
+ key: "permissions",
681
+ get: function get() {
682
+ var permissions = null;
683
+
684
+ try {
685
+ permissions = this._readPermissions();
686
+ } catch (ex) {
687
+ if (ex instanceof _core_utils.MissingDataException) {
688
+ throw ex;
689
+ }
690
+
691
+ (0, _util.warn)('Unable to read permissions.');
692
+ }
693
+
694
+ return (0, _util.shadow)(this, 'permissions', permissions);
616
695
  }
617
- var resultObj = params.resultObj;
618
- if ((typeof resultObj === 'undefined' ? 'undefined' : _typeof(resultObj)) !== 'object') {
619
- (0, _util.warn)('parseDestDictionary: "resultObj" must be an object.');
620
- return;
696
+ }, {
697
+ key: "numPages",
698
+ get: function get() {
699
+ var obj = this.toplevelPagesDict.get('Count');
700
+
701
+ if (!Number.isInteger(obj)) {
702
+ throw new _util.FormatError('Page count in top-level pages dictionary is not an integer.');
703
+ }
704
+
705
+ return (0, _util.shadow)(this, 'numPages', obj);
706
+ }
707
+ }, {
708
+ key: "destinations",
709
+ get: function get() {
710
+ var obj = this._readDests(),
711
+ dests = Object.create(null);
712
+
713
+ if (obj instanceof NameTree) {
714
+ var names = obj.getAll();
715
+
716
+ for (var name in names) {
717
+ dests[name] = fetchDestination(names[name]);
718
+ }
719
+ } else if (obj instanceof _primitives.Dict) {
720
+ obj.forEach(function (key, value) {
721
+ if (value) {
722
+ dests[key] = fetchDestination(value);
723
+ }
724
+ });
725
+ }
726
+
727
+ return (0, _util.shadow)(this, 'destinations', dests);
621
728
  }
622
- var docBaseUrl = params.docBaseUrl || null;
623
- var action = destDict.get('A'),
624
- url,
625
- dest;
626
- if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
627
- action = destDict.get('Dest');
729
+ }, {
730
+ key: "pageLabels",
731
+ get: function get() {
732
+ var obj = null;
733
+
734
+ try {
735
+ obj = this._readPageLabels();
736
+ } catch (ex) {
737
+ if (ex instanceof _core_utils.MissingDataException) {
738
+ throw ex;
739
+ }
740
+
741
+ (0, _util.warn)('Unable to read page labels.');
742
+ }
743
+
744
+ return (0, _util.shadow)(this, 'pageLabels', obj);
628
745
  }
629
- if ((0, _primitives.isDict)(action)) {
630
- var actionType = action.get('S');
631
- if (!(0, _primitives.isName)(actionType)) {
632
- (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
633
- return;
746
+ }, {
747
+ key: "pageLayout",
748
+ get: function get() {
749
+ var obj = this.catDict.get('PageLayout');
750
+ var pageLayout = '';
751
+
752
+ if ((0, _primitives.isName)(obj)) {
753
+ switch (obj.name) {
754
+ case 'SinglePage':
755
+ case 'OneColumn':
756
+ case 'TwoColumnLeft':
757
+ case 'TwoColumnRight':
758
+ case 'TwoPageLeft':
759
+ case 'TwoPageRight':
760
+ pageLayout = obj.name;
761
+ }
634
762
  }
635
- var actionName = actionType.name;
636
- switch (actionName) {
637
- case 'URI':
638
- url = action.get('URI');
639
- if ((0, _primitives.isName)(url)) {
640
- url = '/' + url.name;
641
- } else if ((0, _util.isString)(url)) {
642
- url = addDefaultProtocolToUrl(url);
643
- }
644
- break;
645
- case 'GoTo':
646
- dest = action.get('D');
647
- break;
648
- case 'Launch':
649
- case 'GoToR':
650
- var urlDict = action.get('F');
651
- if ((0, _primitives.isDict)(urlDict)) {
652
- url = urlDict.get('F') || null;
653
- } else if ((0, _util.isString)(urlDict)) {
654
- url = urlDict;
655
- }
656
- var remoteDest = action.get('D');
657
- if (remoteDest) {
658
- if ((0, _primitives.isName)(remoteDest)) {
659
- remoteDest = remoteDest.name;
660
- }
661
- if ((0, _util.isString)(url)) {
662
- var baseUrl = url.split('#')[0];
663
- if ((0, _util.isString)(remoteDest)) {
664
- url = baseUrl + '#' + remoteDest;
665
- } else if (Array.isArray(remoteDest)) {
666
- url = baseUrl + '#' + JSON.stringify(remoteDest);
667
- }
668
- }
763
+
764
+ return (0, _util.shadow)(this, 'pageLayout', pageLayout);
765
+ }
766
+ }, {
767
+ key: "pageMode",
768
+ get: function get() {
769
+ var obj = this.catDict.get('PageMode');
770
+ var pageMode = 'UseNone';
771
+
772
+ if ((0, _primitives.isName)(obj)) {
773
+ switch (obj.name) {
774
+ case 'UseNone':
775
+ case 'UseOutlines':
776
+ case 'UseThumbs':
777
+ case 'FullScreen':
778
+ case 'UseOC':
779
+ case 'UseAttachments':
780
+ pageMode = obj.name;
781
+ }
782
+ }
783
+
784
+ return (0, _util.shadow)(this, 'pageMode', pageMode);
785
+ }
786
+ }, {
787
+ key: "viewerPreferences",
788
+ get: function get() {
789
+ var _this2 = this;
790
+
791
+ var ViewerPreferencesValidators = {
792
+ HideToolbar: _util.isBool,
793
+ HideMenubar: _util.isBool,
794
+ HideWindowUI: _util.isBool,
795
+ FitWindow: _util.isBool,
796
+ CenterWindow: _util.isBool,
797
+ DisplayDocTitle: _util.isBool,
798
+ NonFullScreenPageMode: _primitives.isName,
799
+ Direction: _primitives.isName,
800
+ ViewArea: _primitives.isName,
801
+ ViewClip: _primitives.isName,
802
+ PrintArea: _primitives.isName,
803
+ PrintClip: _primitives.isName,
804
+ PrintScaling: _primitives.isName,
805
+ Duplex: _primitives.isName,
806
+ PickTrayByPDFSize: _util.isBool,
807
+ PrintPageRange: Array.isArray,
808
+ NumCopies: Number.isInteger
809
+ };
810
+ var obj = this.catDict.get('ViewerPreferences');
811
+ var prefs = Object.create(null);
812
+
813
+ if ((0, _primitives.isDict)(obj)) {
814
+ for (var key in ViewerPreferencesValidators) {
815
+ if (!obj.has(key)) {
816
+ continue;
817
+ }
818
+
819
+ var value = obj.get(key);
820
+
821
+ if (!ViewerPreferencesValidators[key](value)) {
822
+ (0, _util.info)("Bad value in ViewerPreferences for \"".concat(key, "\"."));
823
+ continue;
669
824
  }
670
- var newWindow = action.get('NewWindow');
671
- if ((0, _util.isBool)(newWindow)) {
672
- resultObj.newWindow = newWindow;
673
- }
674
- break;
675
- case 'Named':
676
- var namedAction = action.get('N');
677
- if ((0, _primitives.isName)(namedAction)) {
678
- resultObj.action = namedAction.name;
679
- }
680
- break;
681
- case 'JavaScript':
682
- var jsAction = action.get('JS'),
683
- js;
684
- if ((0, _primitives.isStream)(jsAction)) {
685
- js = (0, _util.bytesToString)(jsAction.getBytes());
686
- } else if ((0, _util.isString)(jsAction)) {
687
- js = jsAction;
688
- }
689
- if (js) {
690
- var URL_OPEN_METHODS = ['app.launchURL', 'window.open'];
691
- var regex = new RegExp('^\\s*(' + URL_OPEN_METHODS.join('|').split('.').join('\\.') + ')\\((?:\'|\")([^\'\"]*)(?:\'|\")(?:,\\s*(\\w+)\\)|\\))', 'i');
692
- var jsUrl = regex.exec((0, _util.stringToPDFString)(js));
693
- if (jsUrl && jsUrl[2]) {
694
- url = jsUrl[2];
695
- if (jsUrl[3] === 'true' && jsUrl[1] === 'app.launchURL') {
696
- resultObj.newWindow = true;
825
+
826
+ var prefValue = void 0;
827
+
828
+ switch (key) {
829
+ case 'NonFullScreenPageMode':
830
+ switch (value.name) {
831
+ case 'UseNone':
832
+ case 'UseOutlines':
833
+ case 'UseThumbs':
834
+ case 'UseOC':
835
+ prefValue = value.name;
836
+ break;
837
+
838
+ default:
839
+ prefValue = 'UseNone';
697
840
  }
841
+
698
842
  break;
699
- }
843
+
844
+ case 'Direction':
845
+ switch (value.name) {
846
+ case 'L2R':
847
+ case 'R2L':
848
+ prefValue = value.name;
849
+ break;
850
+
851
+ default:
852
+ prefValue = 'L2R';
853
+ }
854
+
855
+ break;
856
+
857
+ case 'ViewArea':
858
+ case 'ViewClip':
859
+ case 'PrintArea':
860
+ case 'PrintClip':
861
+ switch (value.name) {
862
+ case 'MediaBox':
863
+ case 'CropBox':
864
+ case 'BleedBox':
865
+ case 'TrimBox':
866
+ case 'ArtBox':
867
+ prefValue = value.name;
868
+ break;
869
+
870
+ default:
871
+ prefValue = 'CropBox';
872
+ }
873
+
874
+ break;
875
+
876
+ case 'PrintScaling':
877
+ switch (value.name) {
878
+ case 'None':
879
+ case 'AppDefault':
880
+ prefValue = value.name;
881
+ break;
882
+
883
+ default:
884
+ prefValue = 'AppDefault';
885
+ }
886
+
887
+ break;
888
+
889
+ case 'Duplex':
890
+ switch (value.name) {
891
+ case 'Simplex':
892
+ case 'DuplexFlipShortEdge':
893
+ case 'DuplexFlipLongEdge':
894
+ prefValue = value.name;
895
+ break;
896
+
897
+ default:
898
+ prefValue = 'None';
899
+ }
900
+
901
+ break;
902
+
903
+ case 'PrintPageRange':
904
+ var length = value.length;
905
+
906
+ if (length % 2 !== 0) {
907
+ break;
908
+ }
909
+
910
+ var isValid = value.every(function (page, i, arr) {
911
+ return Number.isInteger(page) && page > 0 && (i === 0 || page >= arr[i - 1]) && page <= _this2.numPages;
912
+ });
913
+
914
+ if (isValid) {
915
+ prefValue = value;
916
+ }
917
+
918
+ break;
919
+
920
+ case 'NumCopies':
921
+ if (value > 0) {
922
+ prefValue = value;
923
+ }
924
+
925
+ break;
926
+
927
+ default:
928
+ (0, _util.assert)(typeof value === 'boolean');
929
+ prefValue = value;
930
+ }
931
+
932
+ if (prefValue !== undefined) {
933
+ prefs[key] = prefValue;
934
+ } else {
935
+ (0, _util.info)("Bad value in ViewerPreferences for \"".concat(key, "\"."));
936
+ }
937
+ }
938
+ }
939
+
940
+ return (0, _util.shadow)(this, 'viewerPreferences', prefs);
941
+ }
942
+ }, {
943
+ key: "openActionDestination",
944
+ get: function get() {
945
+ var obj = this.catDict.get('OpenAction');
946
+ var openActionDest = null;
947
+
948
+ if ((0, _primitives.isDict)(obj)) {
949
+ var destDict = new _primitives.Dict(this.xref);
950
+ destDict.set('A', obj);
951
+ var resultObj = {
952
+ url: null,
953
+ dest: null
954
+ };
955
+ Catalog.parseDestDictionary({
956
+ destDict: destDict,
957
+ resultObj: resultObj
958
+ });
959
+
960
+ if (Array.isArray(resultObj.dest)) {
961
+ openActionDest = resultObj.dest;
962
+ }
963
+ } else if (Array.isArray(obj)) {
964
+ openActionDest = obj;
965
+ }
966
+
967
+ return (0, _util.shadow)(this, 'openActionDestination', openActionDest);
968
+ }
969
+ }, {
970
+ key: "attachments",
971
+ get: function get() {
972
+ var obj = this.catDict.get('Names');
973
+ var attachments = null;
974
+
975
+ if (obj && obj.has('EmbeddedFiles')) {
976
+ var nameTree = new NameTree(obj.getRaw('EmbeddedFiles'), this.xref);
977
+ var names = nameTree.getAll();
978
+
979
+ for (var name in names) {
980
+ var fs = new FileSpec(names[name], this.xref);
981
+
982
+ if (!attachments) {
983
+ attachments = Object.create(null);
700
984
  }
701
- default:
702
- (0, _util.warn)('parseDestDictionary: Unsupported Action type "' + actionName + '".');
703
- break;
985
+
986
+ attachments[(0, _util.stringToPDFString)(name)] = fs.serializable;
987
+ }
704
988
  }
705
- } else if (destDict.has('Dest')) {
706
- dest = destDict.get('Dest');
989
+
990
+ return (0, _util.shadow)(this, 'attachments', attachments);
707
991
  }
708
- if ((0, _util.isString)(url)) {
709
- url = tryConvertUrlEncoding(url);
710
- var absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
711
- if (absoluteUrl) {
712
- resultObj.url = absoluteUrl.href;
992
+ }, {
993
+ key: "javaScript",
994
+ get: function get() {
995
+ var obj = this.catDict.get('Names');
996
+ var javaScript = null;
997
+
998
+ function appendIfJavaScriptDict(jsDict) {
999
+ var type = jsDict.get('S');
1000
+
1001
+ if (!(0, _primitives.isName)(type, 'JavaScript')) {
1002
+ return;
1003
+ }
1004
+
1005
+ var js = jsDict.get('JS');
1006
+
1007
+ if ((0, _primitives.isStream)(js)) {
1008
+ js = (0, _util.bytesToString)(js.getBytes());
1009
+ } else if (!(0, _util.isString)(js)) {
1010
+ return;
1011
+ }
1012
+
1013
+ if (!javaScript) {
1014
+ javaScript = [];
1015
+ }
1016
+
1017
+ javaScript.push((0, _util.stringToPDFString)(js));
1018
+ }
1019
+
1020
+ if (obj && obj.has('JavaScript')) {
1021
+ var nameTree = new NameTree(obj.getRaw('JavaScript'), this.xref);
1022
+ var names = nameTree.getAll();
1023
+
1024
+ for (var name in names) {
1025
+ var jsDict = names[name];
1026
+
1027
+ if ((0, _primitives.isDict)(jsDict)) {
1028
+ appendIfJavaScriptDict(jsDict);
1029
+ }
1030
+ }
1031
+ }
1032
+
1033
+ var openActionDict = this.catDict.get('OpenAction');
1034
+
1035
+ if ((0, _primitives.isDict)(openActionDict, 'Action')) {
1036
+ var actionType = openActionDict.get('S');
1037
+
1038
+ if ((0, _primitives.isName)(actionType, 'Named')) {
1039
+ var action = openActionDict.get('N');
1040
+
1041
+ if ((0, _primitives.isName)(action, 'Print')) {
1042
+ if (!javaScript) {
1043
+ javaScript = [];
1044
+ }
1045
+
1046
+ javaScript.push('print({});');
1047
+ }
1048
+ } else {
1049
+ appendIfJavaScriptDict(openActionDict);
1050
+ }
713
1051
  }
714
- resultObj.unsafeUrl = url;
1052
+
1053
+ return (0, _util.shadow)(this, 'javaScript', javaScript);
715
1054
  }
716
- if (dest) {
717
- if ((0, _primitives.isName)(dest)) {
718
- dest = dest.name;
1055
+ }], [{
1056
+ key: "parseDestDictionary",
1057
+ value: function parseDestDictionary(params) {
1058
+ function addDefaultProtocolToUrl(url) {
1059
+ return url.startsWith('www.') ? "http://".concat(url) : url;
1060
+ }
1061
+
1062
+ function tryConvertUrlEncoding(url) {
1063
+ try {
1064
+ return (0, _util.stringToUTF8String)(url);
1065
+ } catch (e) {
1066
+ return url;
1067
+ }
1068
+ }
1069
+
1070
+ var destDict = params.destDict;
1071
+
1072
+ if (!(0, _primitives.isDict)(destDict)) {
1073
+ (0, _util.warn)('parseDestDictionary: `destDict` must be a dictionary.');
1074
+ return;
1075
+ }
1076
+
1077
+ var resultObj = params.resultObj;
1078
+
1079
+ if (_typeof(resultObj) !== 'object') {
1080
+ (0, _util.warn)('parseDestDictionary: `resultObj` must be an object.');
1081
+ return;
1082
+ }
1083
+
1084
+ var docBaseUrl = params.docBaseUrl || null;
1085
+ var action = destDict.get('A'),
1086
+ url,
1087
+ dest;
1088
+
1089
+ if (!(0, _primitives.isDict)(action) && destDict.has('Dest')) {
1090
+ action = destDict.get('Dest');
1091
+ }
1092
+
1093
+ if ((0, _primitives.isDict)(action)) {
1094
+ var actionType = action.get('S');
1095
+
1096
+ if (!(0, _primitives.isName)(actionType)) {
1097
+ (0, _util.warn)('parseDestDictionary: Invalid type in Action dictionary.');
1098
+ return;
1099
+ }
1100
+
1101
+ var actionName = actionType.name;
1102
+
1103
+ switch (actionName) {
1104
+ case 'URI':
1105
+ url = action.get('URI');
1106
+
1107
+ if ((0, _primitives.isName)(url)) {
1108
+ url = '/' + url.name;
1109
+ } else if ((0, _util.isString)(url)) {
1110
+ url = addDefaultProtocolToUrl(url);
1111
+ }
1112
+
1113
+ break;
1114
+
1115
+ case 'GoTo':
1116
+ dest = action.get('D');
1117
+ break;
1118
+
1119
+ case 'Launch':
1120
+ case 'GoToR':
1121
+ var urlDict = action.get('F');
1122
+
1123
+ if ((0, _primitives.isDict)(urlDict)) {
1124
+ url = urlDict.get('F') || null;
1125
+ } else if ((0, _util.isString)(urlDict)) {
1126
+ url = urlDict;
1127
+ }
1128
+
1129
+ var remoteDest = action.get('D');
1130
+
1131
+ if (remoteDest) {
1132
+ if ((0, _primitives.isName)(remoteDest)) {
1133
+ remoteDest = remoteDest.name;
1134
+ }
1135
+
1136
+ if ((0, _util.isString)(url)) {
1137
+ var baseUrl = url.split('#')[0];
1138
+
1139
+ if ((0, _util.isString)(remoteDest)) {
1140
+ url = baseUrl + '#' + remoteDest;
1141
+ } else if (Array.isArray(remoteDest)) {
1142
+ url = baseUrl + '#' + JSON.stringify(remoteDest);
1143
+ }
1144
+ }
1145
+ }
1146
+
1147
+ var newWindow = action.get('NewWindow');
1148
+
1149
+ if ((0, _util.isBool)(newWindow)) {
1150
+ resultObj.newWindow = newWindow;
1151
+ }
1152
+
1153
+ break;
1154
+
1155
+ case 'Named':
1156
+ var namedAction = action.get('N');
1157
+
1158
+ if ((0, _primitives.isName)(namedAction)) {
1159
+ resultObj.action = namedAction.name;
1160
+ }
1161
+
1162
+ break;
1163
+
1164
+ case 'JavaScript':
1165
+ var jsAction = action.get('JS');
1166
+ var js;
1167
+
1168
+ if ((0, _primitives.isStream)(jsAction)) {
1169
+ js = (0, _util.bytesToString)(jsAction.getBytes());
1170
+ } else if ((0, _util.isString)(jsAction)) {
1171
+ js = jsAction;
1172
+ }
1173
+
1174
+ if (js) {
1175
+ var URL_OPEN_METHODS = ['app.launchURL', 'window.open'];
1176
+ var regex = new RegExp('^\\s*(' + URL_OPEN_METHODS.join('|').split('.').join('\\.') + ')\\((?:\'|\")([^\'\"]*)(?:\'|\")(?:,\\s*(\\w+)\\)|\\))', 'i');
1177
+ var jsUrl = regex.exec((0, _util.stringToPDFString)(js));
1178
+
1179
+ if (jsUrl && jsUrl[2]) {
1180
+ url = jsUrl[2];
1181
+
1182
+ if (jsUrl[3] === 'true' && jsUrl[1] === 'app.launchURL') {
1183
+ resultObj.newWindow = true;
1184
+ }
1185
+
1186
+ break;
1187
+ }
1188
+ }
1189
+
1190
+ default:
1191
+ (0, _util.warn)("parseDestDictionary: unsupported action type \"".concat(actionName, "\"."));
1192
+ break;
1193
+ }
1194
+ } else if (destDict.has('Dest')) {
1195
+ dest = destDict.get('Dest');
719
1196
  }
720
- if ((0, _util.isString)(dest) || Array.isArray(dest)) {
721
- resultObj.dest = dest;
1197
+
1198
+ if ((0, _util.isString)(url)) {
1199
+ url = tryConvertUrlEncoding(url);
1200
+ var absoluteUrl = (0, _util.createValidAbsoluteUrl)(url, docBaseUrl);
1201
+
1202
+ if (absoluteUrl) {
1203
+ resultObj.url = absoluteUrl.href;
1204
+ }
1205
+
1206
+ resultObj.unsafeUrl = url;
1207
+ }
1208
+
1209
+ if (dest) {
1210
+ if ((0, _primitives.isName)(dest)) {
1211
+ dest = dest.name;
1212
+ }
1213
+
1214
+ if ((0, _util.isString)(dest) || Array.isArray(dest)) {
1215
+ resultObj.dest = dest;
1216
+ }
722
1217
  }
723
1218
  }
724
- };
1219
+ }]);
1220
+
725
1221
  return Catalog;
726
1222
  }();
1223
+
1224
+ exports.Catalog = Catalog;
1225
+
727
1226
  var XRef = function XRefClosure() {
728
1227
  function XRef(stream, pdfManager) {
729
1228
  this.stream = stream;
@@ -736,28 +1235,61 @@ var XRef = function XRefClosure() {
736
1235
  fontTypes: []
737
1236
  };
738
1237
  }
1238
+
739
1239
  XRef.prototype = {
740
1240
  setStartXRef: function XRef_setStartXRef(startXRef) {
741
1241
  this.startXRefQueue = [startXRef];
742
1242
  },
743
1243
  parse: function XRef_parse(recoveryMode) {
744
1244
  var trailerDict;
1245
+
745
1246
  if (!recoveryMode) {
746
1247
  trailerDict = this.readXRef();
747
1248
  } else {
748
1249
  (0, _util.warn)('Indexing all PDF objects');
749
1250
  trailerDict = this.indexObjects();
750
1251
  }
1252
+
751
1253
  trailerDict.assignXref(this);
752
1254
  this.trailer = trailerDict;
753
- var encrypt = trailerDict.get('Encrypt');
1255
+ var encrypt;
1256
+
1257
+ try {
1258
+ encrypt = trailerDict.get('Encrypt');
1259
+ } catch (ex) {
1260
+ if (ex instanceof _core_utils.MissingDataException) {
1261
+ throw ex;
1262
+ }
1263
+
1264
+ (0, _util.warn)("XRef.parse - Invalid \"Encrypt\" reference: \"".concat(ex, "\"."));
1265
+ }
1266
+
754
1267
  if ((0, _primitives.isDict)(encrypt)) {
755
1268
  var ids = trailerDict.get('ID');
756
1269
  var fileId = ids && ids.length ? ids[0] : '';
757
1270
  encrypt.suppressEncryption = true;
758
1271
  this.encrypt = new _crypto.CipherTransformFactory(encrypt, fileId, this.pdfManager.password);
759
1272
  }
760
- if (!(this.root = trailerDict.get('Root'))) {
1273
+
1274
+ var root;
1275
+
1276
+ try {
1277
+ root = trailerDict.get('Root');
1278
+ } catch (ex) {
1279
+ if (ex instanceof _core_utils.MissingDataException) {
1280
+ throw ex;
1281
+ }
1282
+
1283
+ (0, _util.warn)("XRef.parse - Invalid \"Root\" reference: \"".concat(ex, "\"."));
1284
+ }
1285
+
1286
+ if ((0, _primitives.isDict)(root) && root.has('Pages')) {
1287
+ this.root = root;
1288
+ } else {
1289
+ if (!recoveryMode) {
1290
+ throw new _core_utils.XRefParseException();
1291
+ }
1292
+
761
1293
  throw new _util.FormatError('Invalid root reference');
762
1294
  }
763
1295
  },
@@ -770,17 +1302,23 @@ var XRef = function XRefClosure() {
770
1302
  parserBuf2: parser.buf2
771
1303
  };
772
1304
  }
1305
+
773
1306
  var obj = this.readXRefTable(parser);
1307
+
774
1308
  if (!(0, _primitives.isCmd)(obj, 'trailer')) {
775
1309
  throw new _util.FormatError('Invalid XRef table: could not find trailer dictionary');
776
1310
  }
1311
+
777
1312
  var dict = parser.getObj();
1313
+
778
1314
  if (!(0, _primitives.isDict)(dict) && dict.dict) {
779
1315
  dict = dict.dict;
780
1316
  }
1317
+
781
1318
  if (!(0, _primitives.isDict)(dict)) {
782
1319
  throw new _util.FormatError('Invalid XRef table: could not parse trailer dictionary');
783
1320
  }
1321
+
784
1322
  delete this.tableState;
785
1323
  return dict;
786
1324
  },
@@ -791,19 +1329,24 @@ var XRef = function XRefClosure() {
791
1329
  parser.buf1 = tableState.parserBuf1;
792
1330
  parser.buf2 = tableState.parserBuf2;
793
1331
  var obj;
1332
+
794
1333
  while (true) {
795
1334
  if (!('firstEntryNum' in tableState) || !('entryCount' in tableState)) {
796
1335
  if ((0, _primitives.isCmd)(obj = parser.getObj(), 'trailer')) {
797
1336
  break;
798
1337
  }
1338
+
799
1339
  tableState.firstEntryNum = obj;
800
1340
  tableState.entryCount = parser.getObj();
801
1341
  }
1342
+
802
1343
  var first = tableState.firstEntryNum;
803
1344
  var count = tableState.entryCount;
1345
+
804
1346
  if (!Number.isInteger(first) || !Number.isInteger(count)) {
805
1347
  throw new _util.FormatError('Invalid XRef table: wrong types in subsection header');
806
1348
  }
1349
+
807
1350
  for (var i = tableState.entryNum; i < count; i++) {
808
1351
  tableState.streamPos = stream.pos;
809
1352
  tableState.entryNum = i;
@@ -813,21 +1356,32 @@ var XRef = function XRefClosure() {
813
1356
  entry.offset = parser.getObj();
814
1357
  entry.gen = parser.getObj();
815
1358
  var type = parser.getObj();
816
- if ((0, _primitives.isCmd)(type, 'f')) {
817
- entry.free = true;
818
- } else if ((0, _primitives.isCmd)(type, 'n')) {
819
- entry.uncompressed = true;
1359
+
1360
+ if (type instanceof _primitives.Cmd) {
1361
+ switch (type.cmd) {
1362
+ case 'f':
1363
+ entry.free = true;
1364
+ break;
1365
+
1366
+ case 'n':
1367
+ entry.uncompressed = true;
1368
+ break;
1369
+ }
820
1370
  }
1371
+
821
1372
  if (!Number.isInteger(entry.offset) || !Number.isInteger(entry.gen) || !(entry.free || entry.uncompressed)) {
822
- throw new _util.FormatError('Invalid entry in XRef subsection: ' + first + ', ' + count);
1373
+ throw new _util.FormatError("Invalid entry in XRef subsection: ".concat(first, ", ").concat(count));
823
1374
  }
1375
+
824
1376
  if (i === 0 && entry.free && first === 1) {
825
1377
  first = 0;
826
1378
  }
1379
+
827
1380
  if (!this.entries[i + first]) {
828
1381
  this.entries[i + first] = entry;
829
1382
  }
830
1383
  }
1384
+
831
1385
  tableState.entryNum = 0;
832
1386
  tableState.streamPos = stream.pos;
833
1387
  tableState.parserBuf1 = parser.buf1;
@@ -835,9 +1389,11 @@ var XRef = function XRefClosure() {
835
1389
  delete tableState.firstEntryNum;
836
1390
  delete tableState.entryCount;
837
1391
  }
1392
+
838
1393
  if (this.entries[0] && !this.entries[0].free) {
839
1394
  throw new _util.FormatError('Invalid XRef table: unexpected first object');
840
1395
  }
1396
+
841
1397
  return obj;
842
1398
  },
843
1399
  processXRefStream: function XRef_processXRefStream(stream) {
@@ -845,9 +1401,11 @@ var XRef = function XRefClosure() {
845
1401
  var streamParameters = stream.dict;
846
1402
  var byteWidths = streamParameters.get('W');
847
1403
  var range = streamParameters.get('Index');
1404
+
848
1405
  if (!range) {
849
1406
  range = [0, streamParameters.get('Size')];
850
1407
  }
1408
+
851
1409
  this.streamState = {
852
1410
  entryRanges: range,
853
1411
  byteWidths: byteWidths,
@@ -855,6 +1413,7 @@ var XRef = function XRefClosure() {
855
1413
  streamPos: stream.pos
856
1414
  };
857
1415
  }
1416
+
858
1417
  this.readXRefStream(stream);
859
1418
  delete this.streamState;
860
1419
  return stream.dict;
@@ -868,52 +1427,67 @@ var XRef = function XRefClosure() {
868
1427
  var offsetFieldWidth = byteWidths[1];
869
1428
  var generationFieldWidth = byteWidths[2];
870
1429
  var entryRanges = streamState.entryRanges;
1430
+
871
1431
  while (entryRanges.length > 0) {
872
1432
  var first = entryRanges[0];
873
1433
  var n = entryRanges[1];
1434
+
874
1435
  if (!Number.isInteger(first) || !Number.isInteger(n)) {
875
- throw new _util.FormatError('Invalid XRef range fields: ' + first + ', ' + n);
1436
+ throw new _util.FormatError("Invalid XRef range fields: ".concat(first, ", ").concat(n));
876
1437
  }
1438
+
877
1439
  if (!Number.isInteger(typeFieldWidth) || !Number.isInteger(offsetFieldWidth) || !Number.isInteger(generationFieldWidth)) {
878
- throw new _util.FormatError('Invalid XRef entry fields length: ' + first + ', ' + n);
1440
+ throw new _util.FormatError("Invalid XRef entry fields length: ".concat(first, ", ").concat(n));
879
1441
  }
1442
+
880
1443
  for (i = streamState.entryNum; i < n; ++i) {
881
1444
  streamState.entryNum = i;
882
1445
  streamState.streamPos = stream.pos;
883
1446
  var type = 0,
884
1447
  offset = 0,
885
1448
  generation = 0;
1449
+
886
1450
  for (j = 0; j < typeFieldWidth; ++j) {
887
1451
  type = type << 8 | stream.getByte();
888
1452
  }
1453
+
889
1454
  if (typeFieldWidth === 0) {
890
1455
  type = 1;
891
1456
  }
1457
+
892
1458
  for (j = 0; j < offsetFieldWidth; ++j) {
893
1459
  offset = offset << 8 | stream.getByte();
894
1460
  }
1461
+
895
1462
  for (j = 0; j < generationFieldWidth; ++j) {
896
1463
  generation = generation << 8 | stream.getByte();
897
1464
  }
1465
+
898
1466
  var entry = {};
899
1467
  entry.offset = offset;
900
1468
  entry.gen = generation;
1469
+
901
1470
  switch (type) {
902
1471
  case 0:
903
1472
  entry.free = true;
904
1473
  break;
1474
+
905
1475
  case 1:
906
1476
  entry.uncompressed = true;
907
1477
  break;
1478
+
908
1479
  case 2:
909
1480
  break;
1481
+
910
1482
  default:
911
- throw new _util.FormatError('Invalid XRef entry type: ' + type);
1483
+ throw new _util.FormatError("Invalid XRef entry type: ".concat(type));
912
1484
  }
1485
+
913
1486
  if (!this.entries[first + i]) {
914
1487
  this.entries[first + i] = entry;
915
1488
  }
916
1489
  }
1490
+
917
1491
  streamState.entryNum = 0;
918
1492
  streamState.streamPos = stream.pos;
919
1493
  entryRanges.splice(0, 2);
@@ -926,38 +1500,49 @@ var XRef = function XRefClosure() {
926
1500
  SPACE = 0x20;
927
1501
  var PERCENT = 0x25,
928
1502
  LT = 0x3C;
1503
+
929
1504
  function readToken(data, offset) {
930
1505
  var token = '',
931
1506
  ch = data[offset];
1507
+
932
1508
  while (ch !== LF && ch !== CR && ch !== LT) {
933
1509
  if (++offset >= data.length) {
934
1510
  break;
935
1511
  }
1512
+
936
1513
  token += String.fromCharCode(ch);
937
1514
  ch = data[offset];
938
1515
  }
1516
+
939
1517
  return token;
940
1518
  }
1519
+
941
1520
  function skipUntil(data, offset, what) {
942
1521
  var length = what.length,
943
1522
  dataLength = data.length;
944
1523
  var skipped = 0;
1524
+
945
1525
  while (offset < dataLength) {
946
1526
  var i = 0;
1527
+
947
1528
  while (i < length && data[offset + i] === what[i]) {
948
1529
  ++i;
949
1530
  }
1531
+
950
1532
  if (i >= length) {
951
1533
  break;
952
1534
  }
1535
+
953
1536
  offset++;
954
1537
  skipped++;
955
1538
  }
1539
+
956
1540
  return skipped;
957
1541
  }
1542
+
958
1543
  var objRegExp = /^(\d+)\s+(\d+)\s+obj\b/;
959
1544
  var endobjRegExp = /\bendobj[\b\s]$/;
960
- var nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s])$/;
1545
+ var nestedObjRegExp = /\s+(\d+\s+\d+\s+obj[\b\s<])$/;
961
1546
  var CHECK_CONTENT_LENGTH = 25;
962
1547
  var trailerBytes = new Uint8Array([116, 114, 97, 105, 108, 101, 114]);
963
1548
  var startxrefBytes = new Uint8Array([115, 116, 97, 114, 116, 120, 114, 101, 102]);
@@ -971,119 +1556,183 @@ var XRef = function XRefClosure() {
971
1556
  length = buffer.length;
972
1557
  var trailers = [],
973
1558
  xrefStms = [];
1559
+
974
1560
  while (position < length) {
975
1561
  var ch = buffer[position];
1562
+
976
1563
  if (ch === TAB || ch === LF || ch === CR || ch === SPACE) {
977
1564
  ++position;
978
1565
  continue;
979
1566
  }
1567
+
980
1568
  if (ch === PERCENT) {
981
1569
  do {
982
1570
  ++position;
1571
+
983
1572
  if (position >= length) {
984
1573
  break;
985
1574
  }
1575
+
986
1576
  ch = buffer[position];
987
1577
  } while (ch !== LF && ch !== CR);
1578
+
988
1579
  continue;
989
1580
  }
1581
+
990
1582
  var token = readToken(buffer, position);
991
1583
  var m;
992
- if (token.indexOf('xref') === 0 && (token.length === 4 || /\s/.test(token[4]))) {
1584
+
1585
+ if (token.startsWith('xref') && (token.length === 4 || /\s/.test(token[4]))) {
993
1586
  position += skipUntil(buffer, position, trailerBytes);
994
1587
  trailers.push(position);
995
1588
  position += skipUntil(buffer, position, startxrefBytes);
996
1589
  } else if (m = objRegExp.exec(token)) {
997
- if (typeof this.entries[m[1]] === 'undefined') {
998
- this.entries[m[1]] = {
1590
+ var num = m[1] | 0,
1591
+ gen = m[2] | 0;
1592
+
1593
+ if (typeof this.entries[num] === 'undefined') {
1594
+ this.entries[num] = {
999
1595
  offset: position - stream.start,
1000
- gen: m[2] | 0,
1596
+ gen: gen,
1001
1597
  uncompressed: true
1002
1598
  };
1003
1599
  }
1600
+
1004
1601
  var contentLength = void 0,
1005
1602
  startPos = position + token.length;
1603
+
1006
1604
  while (startPos < buffer.length) {
1007
1605
  var endPos = startPos + skipUntil(buffer, startPos, objBytes) + 4;
1008
1606
  contentLength = endPos - position;
1009
1607
  var checkPos = Math.max(endPos - CHECK_CONTENT_LENGTH, startPos);
1010
1608
  var tokenStr = (0, _util.bytesToString)(buffer.subarray(checkPos, endPos));
1609
+
1011
1610
  if (endobjRegExp.test(tokenStr)) {
1012
1611
  break;
1013
1612
  } else {
1014
1613
  var objToken = nestedObjRegExp.exec(tokenStr);
1614
+
1015
1615
  if (objToken && objToken[1]) {
1016
1616
  (0, _util.warn)('indexObjects: Found new "obj" inside of another "obj", ' + 'caused by missing "endobj" -- trying to recover.');
1017
1617
  contentLength -= objToken[1].length;
1018
1618
  break;
1019
1619
  }
1020
1620
  }
1021
- startPos += contentLength;
1621
+
1622
+ startPos = endPos;
1022
1623
  }
1624
+
1023
1625
  var content = buffer.subarray(position, position + contentLength);
1024
1626
  var xrefTagOffset = skipUntil(content, 0, xrefBytes);
1627
+
1025
1628
  if (xrefTagOffset < contentLength && content[xrefTagOffset + 5] < 64) {
1026
1629
  xrefStms.push(position - stream.start);
1027
1630
  this.xrefstms[position - stream.start] = 1;
1028
1631
  }
1632
+
1029
1633
  position += contentLength;
1030
- } else if (token.indexOf('trailer') === 0 && (token.length === 7 || /\s/.test(token[7]))) {
1634
+ } else if (token.startsWith('trailer') && (token.length === 7 || /\s/.test(token[7]))) {
1031
1635
  trailers.push(position);
1032
1636
  position += skipUntil(buffer, position, startxrefBytes);
1033
1637
  } else {
1034
1638
  position += token.length + 1;
1035
1639
  }
1036
1640
  }
1641
+
1037
1642
  var i, ii;
1643
+
1038
1644
  for (i = 0, ii = xrefStms.length; i < ii; ++i) {
1039
1645
  this.startXRefQueue.push(xrefStms[i]);
1040
1646
  this.readXRef(true);
1041
1647
  }
1042
- var dict;
1648
+
1649
+ var trailerDict;
1650
+
1043
1651
  for (i = 0, ii = trailers.length; i < ii; ++i) {
1044
1652
  stream.pos = trailers[i];
1045
- var parser = new _parser.Parser(new _parser.Lexer(stream), true, this, true);
1653
+ var parser = new _parser.Parser({
1654
+ lexer: new _parser.Lexer(stream),
1655
+ xref: this,
1656
+ allowStreams: true,
1657
+ recoveryMode: true
1658
+ });
1046
1659
  var obj = parser.getObj();
1660
+
1047
1661
  if (!(0, _primitives.isCmd)(obj, 'trailer')) {
1048
1662
  continue;
1049
1663
  }
1050
- dict = parser.getObj();
1664
+
1665
+ var dict = parser.getObj();
1666
+
1051
1667
  if (!(0, _primitives.isDict)(dict)) {
1052
1668
  continue;
1053
1669
  }
1670
+
1671
+ var rootDict = void 0;
1672
+
1673
+ try {
1674
+ rootDict = dict.get('Root');
1675
+ } catch (ex) {
1676
+ if (ex instanceof _core_utils.MissingDataException) {
1677
+ throw ex;
1678
+ }
1679
+
1680
+ continue;
1681
+ }
1682
+
1683
+ if (!(0, _primitives.isDict)(rootDict) || !rootDict.has('Pages')) {
1684
+ continue;
1685
+ }
1686
+
1054
1687
  if (dict.has('ID')) {
1055
1688
  return dict;
1056
1689
  }
1690
+
1691
+ trailerDict = dict;
1057
1692
  }
1058
- if (dict) {
1059
- return dict;
1693
+
1694
+ if (trailerDict) {
1695
+ return trailerDict;
1060
1696
  }
1697
+
1061
1698
  throw new _util.InvalidPDFException('Invalid PDF structure');
1062
1699
  },
1063
1700
  readXRef: function XRef_readXRef(recoveryMode) {
1064
1701
  var stream = this.stream;
1065
1702
  var startXRefParsedCache = Object.create(null);
1703
+
1066
1704
  try {
1067
1705
  while (this.startXRefQueue.length) {
1068
1706
  var startXRef = this.startXRefQueue[0];
1707
+
1069
1708
  if (startXRefParsedCache[startXRef]) {
1070
1709
  (0, _util.warn)('readXRef - skipping XRef table since it was already parsed.');
1071
1710
  this.startXRefQueue.shift();
1072
1711
  continue;
1073
1712
  }
1713
+
1074
1714
  startXRefParsedCache[startXRef] = true;
1075
1715
  stream.pos = startXRef + stream.start;
1076
- var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
1716
+ var parser = new _parser.Parser({
1717
+ lexer: new _parser.Lexer(stream),
1718
+ xref: this,
1719
+ allowStreams: true
1720
+ });
1077
1721
  var obj = parser.getObj();
1078
1722
  var dict;
1723
+
1079
1724
  if ((0, _primitives.isCmd)(obj, 'xref')) {
1080
1725
  dict = this.processXRefTable(parser);
1726
+
1081
1727
  if (!this.topDict) {
1082
1728
  this.topDict = dict;
1083
1729
  }
1730
+
1084
1731
  obj = dict.get('XRefStm');
1732
+
1085
1733
  if (Number.isInteger(obj)) {
1086
1734
  var pos = obj;
1735
+
1087
1736
  if (!(pos in this.xrefstms)) {
1088
1737
  this.xrefstms[pos] = 1;
1089
1738
  this.startXRefQueue.push(pos);
@@ -1093,255 +1742,398 @@ var XRef = function XRefClosure() {
1093
1742
  if (!Number.isInteger(parser.getObj()) || !(0, _primitives.isCmd)(parser.getObj(), 'obj') || !(0, _primitives.isStream)(obj = parser.getObj())) {
1094
1743
  throw new _util.FormatError('Invalid XRef stream');
1095
1744
  }
1745
+
1096
1746
  dict = this.processXRefStream(obj);
1747
+
1097
1748
  if (!this.topDict) {
1098
1749
  this.topDict = dict;
1099
1750
  }
1751
+
1100
1752
  if (!dict) {
1101
1753
  throw new _util.FormatError('Failed to read XRef stream');
1102
1754
  }
1103
1755
  } else {
1104
1756
  throw new _util.FormatError('Invalid XRef stream header');
1105
1757
  }
1758
+
1106
1759
  obj = dict.get('Prev');
1760
+
1107
1761
  if (Number.isInteger(obj)) {
1108
1762
  this.startXRefQueue.push(obj);
1109
1763
  } else if ((0, _primitives.isRef)(obj)) {
1110
1764
  this.startXRefQueue.push(obj.num);
1111
1765
  }
1766
+
1112
1767
  this.startXRefQueue.shift();
1113
1768
  }
1769
+
1114
1770
  return this.topDict;
1115
1771
  } catch (e) {
1116
- if (e instanceof _util.MissingDataException) {
1772
+ if (e instanceof _core_utils.MissingDataException) {
1117
1773
  throw e;
1118
1774
  }
1775
+
1119
1776
  (0, _util.info)('(while reading XRef): ' + e);
1120
1777
  }
1778
+
1121
1779
  if (recoveryMode) {
1122
- return;
1780
+ return undefined;
1123
1781
  }
1124
- throw new _util.XRefParseException();
1782
+
1783
+ throw new _core_utils.XRefParseException();
1125
1784
  },
1126
1785
  getEntry: function XRef_getEntry(i) {
1127
1786
  var xrefEntry = this.entries[i];
1787
+
1128
1788
  if (xrefEntry && !xrefEntry.free && xrefEntry.offset) {
1129
1789
  return xrefEntry;
1130
1790
  }
1791
+
1131
1792
  return null;
1132
1793
  },
1133
1794
  fetchIfRef: function XRef_fetchIfRef(obj, suppressEncryption) {
1134
1795
  if (!(0, _primitives.isRef)(obj)) {
1135
1796
  return obj;
1136
1797
  }
1798
+
1137
1799
  return this.fetch(obj, suppressEncryption);
1138
1800
  },
1139
1801
  fetch: function XRef_fetch(ref, suppressEncryption) {
1140
1802
  if (!(0, _primitives.isRef)(ref)) {
1141
1803
  throw new Error('ref object is not a reference');
1142
1804
  }
1805
+
1143
1806
  var num = ref.num;
1807
+
1144
1808
  if (num in this.cache) {
1145
1809
  var cacheEntry = this.cache[num];
1810
+
1146
1811
  if (cacheEntry instanceof _primitives.Dict && !cacheEntry.objId) {
1147
1812
  cacheEntry.objId = ref.toString();
1148
1813
  }
1814
+
1149
1815
  return cacheEntry;
1150
1816
  }
1817
+
1151
1818
  var xrefEntry = this.getEntry(num);
1819
+
1152
1820
  if (xrefEntry === null) {
1153
1821
  return this.cache[num] = null;
1154
1822
  }
1823
+
1155
1824
  if (xrefEntry.uncompressed) {
1156
1825
  xrefEntry = this.fetchUncompressed(ref, xrefEntry, suppressEncryption);
1157
1826
  } else {
1158
- xrefEntry = this.fetchCompressed(xrefEntry, suppressEncryption);
1827
+ xrefEntry = this.fetchCompressed(ref, xrefEntry, suppressEncryption);
1159
1828
  }
1829
+
1160
1830
  if ((0, _primitives.isDict)(xrefEntry)) {
1161
1831
  xrefEntry.objId = ref.toString();
1162
1832
  } else if ((0, _primitives.isStream)(xrefEntry)) {
1163
1833
  xrefEntry.dict.objId = ref.toString();
1164
1834
  }
1835
+
1165
1836
  return xrefEntry;
1166
1837
  },
1167
- fetchUncompressed: function XRef_fetchUncompressed(ref, xrefEntry, suppressEncryption) {
1838
+ fetchUncompressed: function fetchUncompressed(ref, xrefEntry) {
1839
+ var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1168
1840
  var gen = ref.gen;
1169
1841
  var num = ref.num;
1842
+
1170
1843
  if (xrefEntry.gen !== gen) {
1171
- throw new _util.FormatError('inconsistent generation in XRef');
1844
+ throw new _core_utils.XRefEntryException("Inconsistent generation in XRef: ".concat(ref));
1172
1845
  }
1846
+
1173
1847
  var stream = this.stream.makeSubStream(xrefEntry.offset + this.stream.start);
1174
- var parser = new _parser.Parser(new _parser.Lexer(stream), true, this);
1848
+ var parser = new _parser.Parser({
1849
+ lexer: new _parser.Lexer(stream),
1850
+ xref: this,
1851
+ allowStreams: true
1852
+ });
1175
1853
  var obj1 = parser.getObj();
1176
1854
  var obj2 = parser.getObj();
1177
1855
  var obj3 = parser.getObj();
1856
+
1178
1857
  if (!Number.isInteger(obj1)) {
1179
1858
  obj1 = parseInt(obj1, 10);
1180
1859
  }
1860
+
1181
1861
  if (!Number.isInteger(obj2)) {
1182
1862
  obj2 = parseInt(obj2, 10);
1183
1863
  }
1184
- if (obj1 !== num || obj2 !== gen || !(0, _primitives.isCmd)(obj3)) {
1185
- throw new _util.FormatError('bad XRef entry');
1864
+
1865
+ if (obj1 !== num || obj2 !== gen || !(obj3 instanceof _primitives.Cmd)) {
1866
+ throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
1186
1867
  }
1868
+
1187
1869
  if (obj3.cmd !== 'obj') {
1188
- if (obj3.cmd.indexOf('obj') === 0) {
1870
+ if (obj3.cmd.startsWith('obj')) {
1189
1871
  num = parseInt(obj3.cmd.substring(3), 10);
1872
+
1190
1873
  if (!Number.isNaN(num)) {
1191
1874
  return num;
1192
1875
  }
1193
1876
  }
1194
- throw new _util.FormatError('bad XRef entry');
1877
+
1878
+ throw new _core_utils.XRefEntryException("Bad (uncompressed) XRef entry: ".concat(ref));
1195
1879
  }
1880
+
1196
1881
  if (this.encrypt && !suppressEncryption) {
1197
1882
  xrefEntry = parser.getObj(this.encrypt.createCipherTransform(num, gen));
1198
1883
  } else {
1199
1884
  xrefEntry = parser.getObj();
1200
1885
  }
1886
+
1201
1887
  if (!(0, _primitives.isStream)(xrefEntry)) {
1202
1888
  this.cache[num] = xrefEntry;
1203
1889
  }
1890
+
1204
1891
  return xrefEntry;
1205
1892
  },
1206
- fetchCompressed: function XRef_fetchCompressed(xrefEntry, suppressEncryption) {
1893
+ fetchCompressed: function fetchCompressed(ref, xrefEntry) {
1894
+ var suppressEncryption = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1207
1895
  var tableOffset = xrefEntry.offset;
1208
- var stream = this.fetch(new _primitives.Ref(tableOffset, 0));
1896
+ var stream = this.fetch(_primitives.Ref.get(tableOffset, 0));
1897
+
1209
1898
  if (!(0, _primitives.isStream)(stream)) {
1210
1899
  throw new _util.FormatError('bad ObjStm stream');
1211
1900
  }
1901
+
1212
1902
  var first = stream.dict.get('First');
1213
1903
  var n = stream.dict.get('N');
1904
+
1214
1905
  if (!Number.isInteger(first) || !Number.isInteger(n)) {
1215
1906
  throw new _util.FormatError('invalid first and n parameters for ObjStm stream');
1216
1907
  }
1217
- var parser = new _parser.Parser(new _parser.Lexer(stream), false, this);
1218
- parser.allowStreams = true;
1908
+
1909
+ var parser = new _parser.Parser({
1910
+ lexer: new _parser.Lexer(stream),
1911
+ xref: this,
1912
+ allowStreams: true
1913
+ });
1219
1914
  var i,
1220
1915
  entries = [],
1221
1916
  num,
1222
1917
  nums = [];
1918
+
1223
1919
  for (i = 0; i < n; ++i) {
1224
1920
  num = parser.getObj();
1921
+
1225
1922
  if (!Number.isInteger(num)) {
1226
- throw new _util.FormatError('invalid object number in the ObjStm stream: ' + num);
1923
+ throw new _util.FormatError("invalid object number in the ObjStm stream: ".concat(num));
1227
1924
  }
1925
+
1228
1926
  nums.push(num);
1229
1927
  var offset = parser.getObj();
1928
+
1230
1929
  if (!Number.isInteger(offset)) {
1231
- throw new _util.FormatError('invalid object offset in the ObjStm stream: ' + offset);
1930
+ throw new _util.FormatError("invalid object offset in the ObjStm stream: ".concat(offset));
1232
1931
  }
1233
1932
  }
1933
+
1234
1934
  for (i = 0; i < n; ++i) {
1235
1935
  entries.push(parser.getObj());
1936
+
1236
1937
  if ((0, _primitives.isCmd)(parser.buf1, 'endobj')) {
1237
1938
  parser.shift();
1238
1939
  }
1940
+
1239
1941
  num = nums[i];
1240
1942
  var entry = this.entries[num];
1943
+
1241
1944
  if (entry && entry.offset === tableOffset && entry.gen === i) {
1242
1945
  this.cache[num] = entries[i];
1243
1946
  }
1244
1947
  }
1948
+
1245
1949
  xrefEntry = entries[xrefEntry.gen];
1950
+
1246
1951
  if (xrefEntry === undefined) {
1247
- throw new _util.FormatError('bad XRef entry for compressed object');
1952
+ throw new _core_utils.XRefEntryException("Bad (compressed) XRef entry: ".concat(ref));
1248
1953
  }
1954
+
1249
1955
  return xrefEntry;
1250
1956
  },
1251
- fetchIfRefAsync: function XRef_fetchIfRefAsync(obj, suppressEncryption) {
1252
- if (!(0, _primitives.isRef)(obj)) {
1253
- return Promise.resolve(obj);
1957
+ fetchIfRefAsync: function () {
1958
+ var _fetchIfRefAsync = _asyncToGenerator(
1959
+ /*#__PURE__*/
1960
+ _regenerator["default"].mark(function _callee(obj, suppressEncryption) {
1961
+ return _regenerator["default"].wrap(function _callee$(_context) {
1962
+ while (1) {
1963
+ switch (_context.prev = _context.next) {
1964
+ case 0:
1965
+ if ((0, _primitives.isRef)(obj)) {
1966
+ _context.next = 2;
1967
+ break;
1968
+ }
1969
+
1970
+ return _context.abrupt("return", obj);
1971
+
1972
+ case 2:
1973
+ return _context.abrupt("return", this.fetchAsync(obj, suppressEncryption));
1974
+
1975
+ case 3:
1976
+ case "end":
1977
+ return _context.stop();
1978
+ }
1979
+ }
1980
+ }, _callee, this);
1981
+ }));
1982
+
1983
+ function fetchIfRefAsync(_x, _x2) {
1984
+ return _fetchIfRefAsync.apply(this, arguments);
1254
1985
  }
1255
- return this.fetchAsync(obj, suppressEncryption);
1256
- },
1257
- fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
1258
- var streamManager = this.stream.manager;
1259
- var xref = this;
1260
- return new Promise(function tryFetch(resolve, reject) {
1261
- try {
1262
- resolve(xref.fetch(ref, suppressEncryption));
1263
- } catch (e) {
1264
- if (e instanceof _util.MissingDataException) {
1265
- streamManager.requestRange(e.begin, e.end).then(function () {
1266
- tryFetch(resolve, reject);
1267
- }, reject);
1268
- return;
1986
+
1987
+ return fetchIfRefAsync;
1988
+ }(),
1989
+ fetchAsync: function () {
1990
+ var _fetchAsync = _asyncToGenerator(
1991
+ /*#__PURE__*/
1992
+ _regenerator["default"].mark(function _callee2(ref, suppressEncryption) {
1993
+ return _regenerator["default"].wrap(function _callee2$(_context2) {
1994
+ while (1) {
1995
+ switch (_context2.prev = _context2.next) {
1996
+ case 0:
1997
+ _context2.prev = 0;
1998
+ return _context2.abrupt("return", this.fetch(ref, suppressEncryption));
1999
+
2000
+ case 4:
2001
+ _context2.prev = 4;
2002
+ _context2.t0 = _context2["catch"](0);
2003
+
2004
+ if (_context2.t0 instanceof _core_utils.MissingDataException) {
2005
+ _context2.next = 8;
2006
+ break;
2007
+ }
2008
+
2009
+ throw _context2.t0;
2010
+
2011
+ case 8:
2012
+ _context2.next = 10;
2013
+ return this.pdfManager.requestRange(_context2.t0.begin, _context2.t0.end);
2014
+
2015
+ case 10:
2016
+ return _context2.abrupt("return", this.fetchAsync(ref, suppressEncryption));
2017
+
2018
+ case 11:
2019
+ case "end":
2020
+ return _context2.stop();
2021
+ }
1269
2022
  }
1270
- reject(e);
1271
- }
1272
- });
1273
- },
2023
+ }, _callee2, this, [[0, 4]]);
2024
+ }));
2025
+
2026
+ function fetchAsync(_x3, _x4) {
2027
+ return _fetchAsync.apply(this, arguments);
2028
+ }
2029
+
2030
+ return fetchAsync;
2031
+ }(),
1274
2032
  getCatalogObj: function XRef_getCatalogObj() {
1275
2033
  return this.root;
1276
2034
  }
1277
2035
  };
1278
2036
  return XRef;
1279
2037
  }();
1280
- var NameOrNumberTree = function NameOrNumberTreeClosure() {
1281
- function NameOrNumberTree(root, xref) {
1282
- (0, _util.unreachable)('Cannot initialize NameOrNumberTree.');
2038
+
2039
+ exports.XRef = XRef;
2040
+
2041
+ var NameOrNumberTree =
2042
+ /*#__PURE__*/
2043
+ function () {
2044
+ function NameOrNumberTree(root, xref, type) {
2045
+ _classCallCheck(this, NameOrNumberTree);
2046
+
2047
+ if (this.constructor === NameOrNumberTree) {
2048
+ (0, _util.unreachable)('Cannot initialize NameOrNumberTree.');
2049
+ }
2050
+
2051
+ this.root = root;
2052
+ this.xref = xref;
2053
+ this._type = type;
1283
2054
  }
1284
- NameOrNumberTree.prototype = {
1285
- getAll: function NameOrNumberTree_getAll() {
2055
+
2056
+ _createClass(NameOrNumberTree, [{
2057
+ key: "getAll",
2058
+ value: function getAll() {
1286
2059
  var dict = Object.create(null);
2060
+
1287
2061
  if (!this.root) {
1288
2062
  return dict;
1289
2063
  }
2064
+
1290
2065
  var xref = this.xref;
1291
2066
  var processed = new _primitives.RefSet();
1292
2067
  processed.put(this.root);
1293
2068
  var queue = [this.root];
2069
+
1294
2070
  while (queue.length > 0) {
1295
- var i, n;
1296
2071
  var obj = xref.fetchIfRef(queue.shift());
2072
+
1297
2073
  if (!(0, _primitives.isDict)(obj)) {
1298
2074
  continue;
1299
2075
  }
2076
+
1300
2077
  if (obj.has('Kids')) {
1301
2078
  var kids = obj.get('Kids');
1302
- for (i = 0, n = kids.length; i < n; i++) {
2079
+
2080
+ for (var i = 0, ii = kids.length; i < ii; i++) {
1303
2081
  var kid = kids[i];
2082
+
1304
2083
  if (processed.has(kid)) {
1305
- throw new _util.FormatError('Duplicate entry in "' + this._type + '" tree.');
2084
+ throw new _util.FormatError("Duplicate entry in \"".concat(this._type, "\" tree."));
1306
2085
  }
2086
+
1307
2087
  queue.push(kid);
1308
2088
  processed.put(kid);
1309
2089
  }
2090
+
1310
2091
  continue;
1311
2092
  }
2093
+
1312
2094
  var entries = obj.get(this._type);
2095
+
1313
2096
  if (Array.isArray(entries)) {
1314
- for (i = 0, n = entries.length; i < n; i += 2) {
1315
- dict[xref.fetchIfRef(entries[i])] = xref.fetchIfRef(entries[i + 1]);
2097
+ for (var _i2 = 0, _ii = entries.length; _i2 < _ii; _i2 += 2) {
2098
+ dict[xref.fetchIfRef(entries[_i2])] = xref.fetchIfRef(entries[_i2 + 1]);
1316
2099
  }
1317
2100
  }
1318
2101
  }
2102
+
1319
2103
  return dict;
1320
- },
1321
- get: function NameOrNumberTree_get(key) {
2104
+ }
2105
+ }, {
2106
+ key: "get",
2107
+ value: function get(key) {
1322
2108
  if (!this.root) {
1323
2109
  return null;
1324
2110
  }
2111
+
1325
2112
  var xref = this.xref;
1326
2113
  var kidsOrEntries = xref.fetchIfRef(this.root);
1327
2114
  var loopCount = 0;
1328
2115
  var MAX_LEVELS = 10;
1329
- var l, r, m;
2116
+
1330
2117
  while (kidsOrEntries.has('Kids')) {
1331
2118
  if (++loopCount > MAX_LEVELS) {
1332
- (0, _util.warn)('Search depth limit reached for "' + this._type + '" tree.');
2119
+ (0, _util.warn)("Search depth limit reached for \"".concat(this._type, "\" tree."));
1333
2120
  return null;
1334
2121
  }
2122
+
1335
2123
  var kids = kidsOrEntries.get('Kids');
2124
+
1336
2125
  if (!Array.isArray(kids)) {
1337
2126
  return null;
1338
2127
  }
1339
- l = 0;
1340
- r = kids.length - 1;
2128
+
2129
+ var l = 0,
2130
+ r = kids.length - 1;
2131
+
1341
2132
  while (l <= r) {
1342
- m = l + r >> 1;
2133
+ var m = l + r >> 1;
1343
2134
  var kid = xref.fetchIfRef(kids[m]);
1344
2135
  var limits = kid.get('Limits');
2136
+
1345
2137
  if (key < xref.fetchIfRef(limits[0])) {
1346
2138
  r = m - 1;
1347
2139
  } else if (key > xref.fetchIfRef(limits[1])) {
@@ -1351,69 +2143,107 @@ var NameOrNumberTree = function NameOrNumberTreeClosure() {
1351
2143
  break;
1352
2144
  }
1353
2145
  }
2146
+
1354
2147
  if (l > r) {
1355
2148
  return null;
1356
2149
  }
1357
2150
  }
2151
+
1358
2152
  var entries = kidsOrEntries.get(this._type);
2153
+
1359
2154
  if (Array.isArray(entries)) {
1360
- l = 0;
1361
- r = entries.length - 2;
1362
- while (l <= r) {
1363
- m = l + r & ~1;
1364
- var currentKey = xref.fetchIfRef(entries[m]);
2155
+ var _l = 0,
2156
+ _r = entries.length - 2;
2157
+
2158
+ while (_l <= _r) {
2159
+ var tmp = _l + _r >> 1,
2160
+ _m = tmp + (tmp & 1);
2161
+
2162
+ var currentKey = xref.fetchIfRef(entries[_m]);
2163
+
1365
2164
  if (key < currentKey) {
1366
- r = m - 2;
2165
+ _r = _m - 2;
1367
2166
  } else if (key > currentKey) {
1368
- l = m + 2;
2167
+ _l = _m + 2;
1369
2168
  } else {
1370
- return xref.fetchIfRef(entries[m + 1]);
2169
+ return xref.fetchIfRef(entries[_m + 1]);
2170
+ }
2171
+ }
2172
+
2173
+ (0, _util.info)("Falling back to an exhaustive search, for key \"".concat(key, "\", ") + "in \"".concat(this._type, "\" tree."));
2174
+
2175
+ for (var _m2 = 0, mm = entries.length; _m2 < mm; _m2 += 2) {
2176
+ var _currentKey = xref.fetchIfRef(entries[_m2]);
2177
+
2178
+ if (_currentKey === key) {
2179
+ (0, _util.warn)("The \"".concat(key, "\" key was found at an incorrect, ") + "i.e. out-of-order, position in \"".concat(this._type, "\" tree."));
2180
+ return xref.fetchIfRef(entries[_m2 + 1]);
1371
2181
  }
1372
2182
  }
1373
2183
  }
2184
+
1374
2185
  return null;
1375
2186
  }
1376
- };
2187
+ }]);
2188
+
1377
2189
  return NameOrNumberTree;
1378
2190
  }();
1379
- var NameTree = function NameTreeClosure() {
2191
+
2192
+ var NameTree =
2193
+ /*#__PURE__*/
2194
+ function (_NameOrNumberTree) {
2195
+ _inherits(NameTree, _NameOrNumberTree);
2196
+
1380
2197
  function NameTree(root, xref) {
1381
- this.root = root;
1382
- this.xref = xref;
1383
- this._type = 'Names';
2198
+ _classCallCheck(this, NameTree);
2199
+
2200
+ return _possibleConstructorReturn(this, _getPrototypeOf(NameTree).call(this, root, xref, 'Names'));
1384
2201
  }
1385
- _util.Util.inherit(NameTree, NameOrNumberTree, {});
2202
+
1386
2203
  return NameTree;
1387
- }();
1388
- var NumberTree = function NumberTreeClosure() {
2204
+ }(NameOrNumberTree);
2205
+
2206
+ var NumberTree =
2207
+ /*#__PURE__*/
2208
+ function (_NameOrNumberTree2) {
2209
+ _inherits(NumberTree, _NameOrNumberTree2);
2210
+
1389
2211
  function NumberTree(root, xref) {
1390
- this.root = root;
1391
- this.xref = xref;
1392
- this._type = 'Nums';
2212
+ _classCallCheck(this, NumberTree);
2213
+
2214
+ return _possibleConstructorReturn(this, _getPrototypeOf(NumberTree).call(this, root, xref, 'Nums'));
1393
2215
  }
1394
- _util.Util.inherit(NumberTree, NameOrNumberTree, {});
2216
+
1395
2217
  return NumberTree;
1396
- }();
2218
+ }(NameOrNumberTree);
2219
+
1397
2220
  var FileSpec = function FileSpecClosure() {
1398
2221
  function FileSpec(root, xref) {
1399
2222
  if (!root || !(0, _primitives.isDict)(root)) {
1400
2223
  return;
1401
2224
  }
2225
+
1402
2226
  this.xref = xref;
1403
2227
  this.root = root;
2228
+
1404
2229
  if (root.has('FS')) {
1405
2230
  this.fs = root.get('FS');
1406
2231
  }
2232
+
1407
2233
  this.description = root.has('Desc') ? (0, _util.stringToPDFString)(root.get('Desc')) : '';
2234
+
1408
2235
  if (root.has('RF')) {
1409
2236
  (0, _util.warn)('Related file specifications are not supported');
1410
2237
  }
2238
+
1411
2239
  this.contentAvailable = true;
2240
+
1412
2241
  if (!root.has('EF')) {
1413
2242
  this.contentAvailable = false;
1414
2243
  (0, _util.warn)('Non-embedded file specifications are not supported');
1415
2244
  }
1416
2245
  }
2246
+
1417
2247
  function pickPlatformItem(dict) {
1418
2248
  if (dict.has('UF')) {
1419
2249
  return dict.get('UF');
@@ -1426,27 +2256,35 @@ var FileSpec = function FileSpecClosure() {
1426
2256
  } else if (dict.has('DOS')) {
1427
2257
  return dict.get('DOS');
1428
2258
  }
2259
+
1429
2260
  return null;
1430
2261
  }
2262
+
1431
2263
  FileSpec.prototype = {
1432
2264
  get filename() {
1433
2265
  if (!this._filename && this.root) {
1434
2266
  var filename = pickPlatformItem(this.root) || 'unnamed';
1435
2267
  this._filename = (0, _util.stringToPDFString)(filename).replace(/\\\\/g, '\\').replace(/\\\//g, '/').replace(/\\/g, '/');
1436
2268
  }
2269
+
1437
2270
  return this._filename;
1438
2271
  },
2272
+
1439
2273
  get content() {
1440
2274
  if (!this.contentAvailable) {
1441
2275
  return null;
1442
2276
  }
2277
+
1443
2278
  if (!this.contentRef && this.root) {
1444
2279
  this.contentRef = pickPlatformItem(this.root.get('EF'));
1445
2280
  }
2281
+
1446
2282
  var content = null;
2283
+
1447
2284
  if (this.contentRef) {
1448
2285
  var xref = this.xref;
1449
2286
  var fileObj = xref.fetchIfRef(this.contentRef);
2287
+
1450
2288
  if (fileObj && (0, _primitives.isStream)(fileObj)) {
1451
2289
  content = fileObj.getBytes();
1452
2290
  } else {
@@ -1455,40 +2293,51 @@ var FileSpec = function FileSpecClosure() {
1455
2293
  } else {
1456
2294
  (0, _util.warn)('Embedded file specification does not have a content');
1457
2295
  }
2296
+
1458
2297
  return content;
1459
2298
  },
2299
+
1460
2300
  get serializable() {
1461
2301
  return {
1462
2302
  filename: this.filename,
1463
2303
  content: this.content
1464
2304
  };
1465
2305
  }
2306
+
1466
2307
  };
1467
2308
  return FileSpec;
1468
2309
  }();
2310
+
2311
+ exports.FileSpec = FileSpec;
2312
+
1469
2313
  var ObjectLoader = function () {
1470
2314
  function mayHaveChildren(value) {
1471
2315
  return (0, _primitives.isRef)(value) || (0, _primitives.isDict)(value) || Array.isArray(value) || (0, _primitives.isStream)(value);
1472
2316
  }
2317
+
1473
2318
  function addChildren(node, nodesToVisit) {
1474
2319
  if ((0, _primitives.isDict)(node) || (0, _primitives.isStream)(node)) {
1475
2320
  var dict = (0, _primitives.isDict)(node) ? node : node.dict;
1476
2321
  var dictKeys = dict.getKeys();
2322
+
1477
2323
  for (var i = 0, ii = dictKeys.length; i < ii; i++) {
1478
2324
  var rawValue = dict.getRaw(dictKeys[i]);
2325
+
1479
2326
  if (mayHaveChildren(rawValue)) {
1480
2327
  nodesToVisit.push(rawValue);
1481
2328
  }
1482
2329
  }
1483
2330
  } else if (Array.isArray(node)) {
1484
- for (var _i = 0, _ii = node.length; _i < _ii; _i++) {
1485
- var value = node[_i];
2331
+ for (var _i3 = 0, _ii2 = node.length; _i3 < _ii2; _i3++) {
2332
+ var value = node[_i3];
2333
+
1486
2334
  if (mayHaveChildren(value)) {
1487
2335
  nodesToVisit.push(value);
1488
2336
  }
1489
2337
  }
1490
2338
  }
1491
2339
  }
2340
+
1492
2341
  function ObjectLoader(dict, keys, xref) {
1493
2342
  this.dict = dict;
1494
2343
  this.keys = keys;
@@ -1496,25 +2345,31 @@ var ObjectLoader = function () {
1496
2345
  this.refSet = null;
1497
2346
  this.capability = null;
1498
2347
  }
2348
+
1499
2349
  ObjectLoader.prototype = {
1500
2350
  load: function load() {
1501
2351
  this.capability = (0, _util.createPromiseCapability)();
2352
+
1502
2353
  if (!(this.xref.stream instanceof _chunked_stream.ChunkedStream) || this.xref.stream.getMissingChunks().length === 0) {
1503
2354
  this.capability.resolve();
1504
2355
  return this.capability.promise;
1505
2356
  }
2357
+
1506
2358
  var keys = this.keys,
1507
2359
  dict = this.dict;
1508
-
1509
2360
  this.refSet = new _primitives.RefSet();
1510
2361
  var nodesToVisit = [];
2362
+
1511
2363
  for (var i = 0, ii = keys.length; i < ii; i++) {
1512
2364
  var rawValue = dict.getRaw(keys[i]);
2365
+
1513
2366
  if (rawValue !== undefined) {
1514
2367
  nodesToVisit.push(rawValue);
1515
2368
  }
1516
2369
  }
2370
+
1517
2371
  this._walk(nodesToVisit);
2372
+
1518
2373
  return this.capability.promise;
1519
2374
  },
1520
2375
  _walk: function _walk(nodesToVisit) {
@@ -1522,19 +2377,23 @@ var ObjectLoader = function () {
1522
2377
 
1523
2378
  var nodesToRevisit = [];
1524
2379
  var pendingRequests = [];
2380
+
1525
2381
  while (nodesToVisit.length) {
1526
2382
  var currentNode = nodesToVisit.pop();
2383
+
1527
2384
  if ((0, _primitives.isRef)(currentNode)) {
1528
2385
  if (this.refSet.has(currentNode)) {
1529
2386
  continue;
1530
2387
  }
2388
+
1531
2389
  try {
1532
2390
  this.refSet.put(currentNode);
1533
2391
  currentNode = this.xref.fetch(currentNode);
1534
2392
  } catch (ex) {
1535
- if (!(ex instanceof _util.MissingDataException)) {
2393
+ if (!(ex instanceof _core_utils.MissingDataException)) {
1536
2394
  throw ex;
1537
2395
  }
2396
+
1538
2397
  nodesToRevisit.push(currentNode);
1539
2398
  pendingRequests.push({
1540
2399
  begin: ex.begin,
@@ -1542,11 +2401,14 @@ var ObjectLoader = function () {
1542
2401
  });
1543
2402
  }
1544
2403
  }
2404
+
1545
2405
  if (currentNode && currentNode.getBaseStreams) {
1546
2406
  var baseStreams = currentNode.getBaseStreams();
1547
2407
  var foundMissingData = false;
2408
+
1548
2409
  for (var i = 0, ii = baseStreams.length; i < ii; i++) {
1549
2410
  var stream = baseStreams[i];
2411
+
1550
2412
  if (stream.getMissingChunks && stream.getMissingChunks().length) {
1551
2413
  foundMissingData = true;
1552
2414
  pendingRequests.push({
@@ -1555,31 +2417,35 @@ var ObjectLoader = function () {
1555
2417
  });
1556
2418
  }
1557
2419
  }
2420
+
1558
2421
  if (foundMissingData) {
1559
2422
  nodesToRevisit.push(currentNode);
1560
2423
  }
1561
2424
  }
2425
+
1562
2426
  addChildren(currentNode, nodesToVisit);
1563
2427
  }
2428
+
1564
2429
  if (pendingRequests.length) {
1565
2430
  this.xref.stream.manager.requestRanges(pendingRequests).then(function () {
1566
- for (var _i2 = 0, _ii2 = nodesToRevisit.length; _i2 < _ii2; _i2++) {
1567
- var node = nodesToRevisit[_i2];
2431
+ for (var _i4 = 0, _ii3 = nodesToRevisit.length; _i4 < _ii3; _i4++) {
2432
+ var node = nodesToRevisit[_i4];
2433
+
1568
2434
  if ((0, _primitives.isRef)(node)) {
1569
2435
  _this3.refSet.remove(node);
1570
2436
  }
1571
2437
  }
2438
+
1572
2439
  _this3._walk(nodesToRevisit);
1573
2440
  }, this.capability.reject);
1574
2441
  return;
1575
2442
  }
2443
+
1576
2444
  this.refSet = null;
1577
2445
  this.capability.resolve();
1578
2446
  }
1579
2447
  };
1580
2448
  return ObjectLoader;
1581
2449
  }();
1582
- exports.Catalog = Catalog;
1583
- exports.ObjectLoader = ObjectLoader;
1584
- exports.XRef = XRef;
1585
- exports.FileSpec = FileSpec;
2450
+
2451
+ exports.ObjectLoader = ObjectLoader;