pdfjs-dist 2.0.487 → 2.1.266

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